2 This file is part of GNUnet.
3 Copyright (C) 2006-2018 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * @file src/util/os_installation.c
21 * @brief get paths used by the program
23 * @author Christian Fuchs
24 * @author Christian Grothoff
25 * @author Matthias Wachs
26 * @author Heikki Lindholm
33 #include <unistr.h> /* for u16_to_u8 */
36 #include "gnunet_util_lib.h"
38 #include <mach-o/ldsyms.h>
39 #include <mach-o/dyld.h>
45 #define LOG(kind,...) GNUNET_log_from (kind, "util-os-installation", __VA_ARGS__)
47 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-os-installation", syscall, filename)
51 * Default project data used for installation path detection
54 static const struct GNUNET_OS_ProjectData default_pd = {
55 .libname = "libgnunetutil",
56 .project_dirname = "gnunet",
57 .binary_name = "gnunet-arm",
58 .env_varname = "GNUNET_PREFIX",
59 .base_config_varname = "GNUNET_BASE_CONFIG",
60 .bug_email = "gnunet-developers@gnu.org",
61 .homepage = "http://www.gnu.org/s/gnunet/",
62 .config_file = "gnunet.conf",
63 .user_config_file = "~/.config/gnunet.conf",
67 * Which project data do we currently use for installation
68 * path detection? Never NULL.
70 static const struct GNUNET_OS_ProjectData *current_pd = &default_pd;
73 * Return default project data used by 'libgnunetutil' for GNUnet.
75 const struct GNUNET_OS_ProjectData *
76 GNUNET_OS_project_data_default (void)
83 * @return current project data.
85 const struct GNUNET_OS_ProjectData *
86 GNUNET_OS_project_data_get ()
93 * Setup OS subsystem with project data.
95 * @param pd project data used to determine paths
98 GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd)
100 GNUNET_assert (NULL != pd);
107 * Try to determine path by reading /proc/PID/exe
109 * @return NULL on error
112 get_path_from_proc_maps ()
120 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
121 if (NULL == (f = FOPEN (fn, "r")))
123 while (NULL != fgets (line, sizeof (line), f))
126 SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s", dir)) &&
127 (NULL != (lgu = strstr (dir,
128 current_pd->libname))))
132 return GNUNET_strdup (dir);
141 * Try to determine path by reading /proc/PID/exe
143 * @return NULL on error
146 get_path_from_proc_exe ()
162 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
167 GNUNET_assert ( ((size_t) size) < sizeof (lnk));
169 while ((lnk[size] != '/') && (size > 0))
171 GNUNET_asprintf (&lep,
173 current_pd->project_dirname);
174 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
175 if ( (((size_t) size) > strlen (lep)) &&
177 &lnk[size - strlen (lep)])) )
178 size -= strlen (lep) - 1;
181 (lnk[size - 4] != '/') )
183 /* not installed in "/bin/" -- binary path probably useless */
187 return GNUNET_strdup (lnk);
193 static HINSTANCE dll_instance;
197 * GNUNET_util_cl_init() in common_logging.c is preferred.
198 * This function is only for thread-local storage (not used in GNUnet)
199 * and hInstance saving.
202 DllMain (HINSTANCE hinstDLL,
208 case DLL_PROCESS_ATTACH:
209 dll_instance = hinstDLL;
211 case DLL_THREAD_ATTACH:
213 case DLL_THREAD_DETACH:
215 case DLL_PROCESS_DETACH:
223 * Try to determine path with win32-specific function
225 * @return NULL on error
228 get_path_from_module_filename ()
230 size_t pathlen = 512;
233 wchar_t *modulepath = NULL;
236 size_t u8_string_length;
238 /* This braindead function won't tell us how much space it needs, so
239 * we start at 1024 and double the space up if it doesn't fit, until
240 * it fits, or we exceed the threshold.
244 pathlen = pathlen * 2;
245 modulepath = GNUNET_realloc (modulepath,
246 pathlen * sizeof (wchar_t));
248 real_pathlen = GetModuleFileNameW (dll_instance,
250 pathlen * sizeof (wchar_t));
251 } while (real_pathlen >= pathlen && pathlen < 16*1024);
252 if (real_pathlen >= pathlen)
255 modulepath[real_pathlen] = '\0';
257 idx = modulepath + real_pathlen;
258 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
262 /* Now modulepath holds full path to the directory where libgnunetutil is.
263 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
265 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
267 /* At least one directory component (i.e. we're not in a root directory) */
268 wchar_t *dirname = idx;
269 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
272 if (dirname > modulepath)
275 /* Now modulepath holds full path to the parent directory of the directory
276 * where libgnunetutil is.
277 * dirname holds the name of the directory where libgnunetutil is.
279 if (wcsicmp (dirname, L"bin") == 0)
285 /* Roll back our changes to modulepath */
292 /* modulepath is GNUNET_PREFIX */
293 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
294 if (NULL == u8_string)
297 upath = GNUNET_malloc (u8_string_length + 1);
298 GNUNET_memcpy (upath, u8_string, u8_string_length);
299 upath[u8_string_length] = '\0';
302 GNUNET_free (modulepath);
311 * Signature of the '_NSGetExecutablePath" function.
313 * @param buf where to write the path
314 * @param number of bytes available in @a buf
315 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
318 (*MyNSGetExecutablePathProto) (char *buf,
323 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
325 * @return NULL on error
328 get_path_from_NSGetExecutablePath ()
330 static char zero = '\0';
333 MyNSGetExecutablePathProto func;
337 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
341 /* get the path len, including the trailing \0 */
342 (void) func (path, &len);
345 path = GNUNET_malloc (len);
346 if (0 != func (path, &len))
352 while ((path[len] != '/') && (len > 0))
360 * Try to obtain the path of our executable using '_dyld_image' API.
362 * @return NULL on error
365 get_path_from_dyld_image ()
373 c = _dyld_image_count ();
374 for (i = 0; i < c; i++)
376 if (((const void *) _dyld_get_image_header (i)) !=
377 ((const void *) &_mh_dylib_header) )
379 path = _dyld_get_image_name (i);
380 if ( (NULL == path) || (0 == strlen (path)) )
382 p = GNUNET_strdup (path);
384 while ((s > p) && ('/' != *s))
396 * Return the actual path to a file found in the current
397 * PATH environment variable.
399 * @param binary the name of the file to find
400 * @return path to binary, NULL if not found
403 get_path_from_PATH (const char *binary)
411 if (NULL == (p = getenv ("PATH")))
414 /* On W32 look in CWD first. */
415 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
417 path = GNUNET_strdup (p); /* because we write on it */
419 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
421 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
424 sprintf (buf, "%s/%s", pos, binary);
425 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
427 pos = GNUNET_strdup (pos);
434 sprintf (buf, "%s/%s", pos, binary);
435 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
437 pos = GNUNET_strdup (pos);
449 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
452 * @return NULL on error (environment variable not set)
455 get_path_from_GNUNET_PREFIX ()
459 if ( (NULL != current_pd->env_varname) &&
460 (NULL != (p = getenv (current_pd->env_varname))) )
461 return GNUNET_strdup (p);
462 if ( (NULL != current_pd->env_varname_alt) &&
463 (NULL != (p = getenv (current_pd->env_varname_alt))) )
464 return GNUNET_strdup (p);
470 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
473 * @return a pointer to the executable path, or NULL on error
476 os_get_gnunet_path ()
480 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
483 if (NULL != (ret = get_path_from_proc_maps ()))
485 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
486 if ( (NULL != current_pd->binary_name) &&
487 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
489 if (NULL != (ret = get_path_from_proc_exe ()))
493 if (NULL != (ret = get_path_from_module_filename ()))
497 if (NULL != (ret = get_path_from_dyld_image ()))
499 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
502 if ( (NULL != current_pd->binary_name) &&
503 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
505 /* other attempts here */
506 LOG (GNUNET_ERROR_TYPE_ERROR,
507 _("Could not determine installation path for %s. Set `%s' environment variable.\n"),
508 current_pd->project_dirname,
509 current_pd->env_varname);
515 * @brief get the path to current app's bin/
516 * @return a pointer to the executable path, or NULL on error
524 if (NULL != (ret = get_path_from_proc_exe ()))
528 if (NULL != (ret = get_path_from_module_filename ()))
532 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
535 /* other attempts here */
541 * @brief get the path to a specific GNUnet installation directory or,
542 * with #GNUNET_OS_IPK_SELF_PREFIX, the current running apps installation directory
543 * @return a pointer to the dir path (to be freed by the caller)
546 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
550 char *execpath = NULL;
556 /* if wanted, try to get the current app's bin/ */
557 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
558 execpath = os_get_exec_path ();
560 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
561 * guess for the current app */
562 if (NULL == execpath)
563 execpath = os_get_gnunet_path ();
565 if (NULL == execpath)
568 n = strlen (execpath);
571 /* should never happen, but better safe than sorry */
572 GNUNET_free (execpath);
575 /* remove filename itself */
576 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
577 execpath[--n] = '\0';
581 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
582 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
584 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
585 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
587 /* strip '/lib32' or '/lib64' */
588 execpath[n - 6] = '\0';
595 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
596 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
598 /* strip '/bin' or '/lib' */
599 execpath[n - 4] = '\0';
603 if (NULL != (libdir = strstr (execpath, "/lib/")))
605 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
606 here we need to re-add 'multiarch' to lib and libexec paths later! */
607 multiarch = &libdir[5];
608 if (NULL == strchr (multiarch, '/'))
609 libdir[0] = '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
611 multiarch = NULL; /* maybe not, multiarch still has a '/', which is not OK */
613 /* in case this was a directory named foo-bin, remove "foo-" */
614 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
615 execpath[--n] = '\0';
618 case GNUNET_OS_IPK_PREFIX:
619 case GNUNET_OS_IPK_SELF_PREFIX:
620 dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
622 case GNUNET_OS_IPK_BINDIR:
623 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
625 case GNUNET_OS_IPK_LIBDIR:
628 GNUNET_asprintf (&tmp,
631 DIR_SEPARATOR_STR "lib",
632 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
633 (NULL != multiarch) ? multiarch : "",
635 current_pd->project_dirname,
638 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
640 GNUNET_free (execpath);
646 if (4 == sizeof (void *))
648 GNUNET_asprintf (&dirname,
649 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
650 current_pd->project_dirname);
651 GNUNET_asprintf (&tmp,
656 if (8 == sizeof (void *))
658 GNUNET_asprintf (&dirname,
659 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
660 current_pd->project_dirname);
661 GNUNET_asprintf (&tmp,
667 if ( (NULL != tmp) &&
669 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
671 GNUNET_free (execpath);
672 GNUNET_free_non_null (dirname);
676 GNUNET_free_non_null (dirname);
678 GNUNET_asprintf (&dirname,
679 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
680 current_pd->project_dirname);
682 case GNUNET_OS_IPK_DATADIR:
683 GNUNET_asprintf (&dirname,
684 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
685 current_pd->project_dirname);
687 case GNUNET_OS_IPK_LOCALEDIR:
688 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR);
690 case GNUNET_OS_IPK_ICONDIR:
691 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR);
693 case GNUNET_OS_IPK_DOCDIR:
694 GNUNET_asprintf (&dirname,
695 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
696 current_pd->project_dirname);
698 case GNUNET_OS_IPK_LIBEXECDIR:
701 GNUNET_asprintf (&dirname,
702 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
703 current_pd->project_dirname);
704 GNUNET_asprintf (&tmp,
707 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
708 (NULL != multiarch) ? multiarch : "",
711 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
713 GNUNET_free (execpath);
714 GNUNET_free (dirname);
720 if (4 == sizeof (void *))
722 GNUNET_asprintf (&dirname,
723 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
724 current_pd->project_dirname);
725 GNUNET_asprintf (&tmp,
730 if (8 == sizeof (void *))
732 GNUNET_asprintf (&dirname,
733 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
734 current_pd->project_dirname);
735 GNUNET_asprintf (&tmp,
740 if ( (NULL != tmp) &&
742 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
744 GNUNET_free (execpath);
745 GNUNET_free_non_null (dirname);
749 GNUNET_free_non_null (dirname);
751 GNUNET_asprintf (&dirname,
752 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
753 current_pd->project_dirname);
756 GNUNET_free (execpath);
759 GNUNET_asprintf (&tmp,
763 GNUNET_free (dirname);
764 GNUNET_free (execpath);
770 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
771 * binary, try to prefix it with the libexec/-directory to get the
774 * @param progname name of the binary
775 * @return full path to the binary, if possible, otherwise copy of 'progname'
778 GNUNET_OS_get_libexec_binary_path (const char *progname)
784 if ( (DIR_SEPARATOR == progname[0]) ||
786 GNUNET_STRINGS_path_is_absolute (progname,
789 return GNUNET_strdup (progname);
793 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
794 if (NULL == libexecdir)
795 return GNUNET_strdup (progname);
796 GNUNET_asprintf (&binary,
806 * Check whether an executable exists and possibly if the suid bit is
807 * set on the file. Attempts to find the file using the current PATH
808 * environment variable as a search path.
810 * @param binary the name of the file to check.
811 * W32: must not have an .exe suffix.
812 * @param check_suid input true if the binary should be checked for SUID (*nix)
813 * W32: checks if the program has sufficient privileges by executing this
814 * binary with the -d flag. -d omits a programs main loop and only
815 * executes all privileged operations in an binary.
816 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
817 * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
818 * #GNUNET_NO if not SUID (but binary exists),
819 * #GNUNET_SYSERR on error (no such binary or not executable)
822 GNUNET_OS_check_helper_binary (const char *binary,
832 GNUNET_asprintf (&binaryexe,
836 GNUNET_STRINGS_path_is_absolute (binaryexe,
839 (0 == strncmp (binary, "./", 2)) )
840 p = GNUNET_strdup (binaryexe);
843 p = get_path_from_PATH (binaryexe);
846 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
851 GNUNET_free (binaryexe);
854 GNUNET_STRINGS_path_is_absolute (binary,
858 (0 == strncmp (binary, "./", 2)) )
860 p = GNUNET_strdup (binary);
864 p = get_path_from_PATH (binary);
867 GNUNET_asprintf (&pf,
878 LOG (GNUNET_ERROR_TYPE_INFO,
879 _("Could not find binary `%s' in PATH!\n"),
881 return GNUNET_SYSERR;
886 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
890 return GNUNET_SYSERR;
895 /* as we run as root, we don't insist on SUID */
903 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
907 return GNUNET_SYSERR;
913 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
914 (0 == statbuf.st_uid) )
919 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
920 _("Binary `%s' exists, but is not SUID\n"),
922 /* binary exists, but not SUID */
925 char parameters[512];
926 PROCESS_INFORMATION proc;
929 GNUNET_snprintf (parameters,
932 memset (&start, 0, sizeof (start));
933 start.cb = sizeof (start);
934 memset (&proc, 0, sizeof (proc));
937 // Start the child process.
938 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
939 parameters, // execute dryrun/priviliege checking mode
940 NULL, // Process handle not inheritable
941 NULL, // Thread handle not inheritable
942 FALSE, // Set handle inheritance to FALSE
943 CREATE_DEFAULT_ERROR_MODE, // No creation flags
944 NULL, // Use parent's environment block
945 NULL, // Use parent's starting directory
946 &start, // Pointer to STARTUPINFO structure
947 &proc ) // Pointer to PROCESS_INFORMATION structure
950 LOG (GNUNET_ERROR_TYPE_ERROR,
951 _("CreateProcess failed for binary %s (%d).\n"),
953 return GNUNET_SYSERR;
956 // Wait until child process exits.
957 WaitForSingleObject( proc.hProcess, INFINITE );
959 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
960 LOG (GNUNET_ERROR_TYPE_ERROR,
961 _("GetExitCodeProcess failed for binary %s (%d).\n"),
963 return GNUNET_SYSERR;
965 // Close process and thread handles.
966 CloseHandle( proc.hProcess );
967 CloseHandle( proc.hThread );
978 /* end of os_installation.c */