2 This file is part of GNUnet.
3 Copyright (C) 2006-2016 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 * @file src/util/os_installation.c
23 * @brief get paths used by the program
25 * @author Christian Fuchs
26 * @author Christian Grothoff
27 * @author Matthias Wachs
28 * @author Heikki Lindholm
35 #include <unistr.h> /* for u16_to_u8 */
38 #include "gnunet_util_lib.h"
40 #include <mach-o/ldsyms.h>
41 #include <mach-o/dyld.h>
47 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
49 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
53 * Default project data used for installation path detection
56 static const struct GNUNET_OS_ProjectData default_pd = {
57 .libname = "libgnunetutil",
58 .project_dirname = "gnunet",
59 .binary_name = "gnunet-arm",
60 .env_varname = "GNUNET_PREFIX",
61 .bug_email = "gnunet-developers@gnu.org",
62 .homepage = "http://www.gnu.org/s/gnunet/",
66 * Which project data do we currently use for installation
67 * path detection? Never NULL.
69 static const struct GNUNET_OS_ProjectData *current_pd = &default_pd;
72 * Return default project data used by 'libgnunetutil' for GNUnet.
74 const struct GNUNET_OS_ProjectData *
75 GNUNET_OS_project_data_default (void)
82 * @return current project data.
84 const struct GNUNET_OS_ProjectData *
85 GNUNET_OS_project_data_get ()
92 * Setup OS subsystem with project data.
94 * @param pd project data used to determine paths
97 GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd)
99 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 ()
153 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ());
154 size = readlink (fn, lnk, sizeof (lnk) - 1);
157 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
160 GNUNET_assert (size < sizeof (lnk));
162 while ((lnk[size] != '/') && (size > 0))
164 GNUNET_asprintf (&lep,
166 current_pd->project_dirname);
167 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
168 if ( (size > strlen (lep)) &&
170 &lnk[size - strlen (lep)])) )
171 size -= strlen (lep) - 1;
173 if ((size < 4) || (lnk[size - 4] != '/'))
175 /* not installed in "/bin/" -- binary path probably useless */
179 return GNUNET_strdup (lnk);
185 static HINSTANCE dll_instance;
189 * GNUNET_util_cl_init() in common_logging.c is preferred.
190 * This function is only for thread-local storage (not used in GNUnet)
191 * and hInstance saving.
194 DllMain (HINSTANCE hinstDLL,
200 case DLL_PROCESS_ATTACH:
201 dll_instance = hinstDLL;
203 case DLL_THREAD_ATTACH:
205 case DLL_THREAD_DETACH:
207 case DLL_PROCESS_DETACH:
215 * Try to determine path with win32-specific function
217 * @return NULL on error
220 get_path_from_module_filename ()
222 size_t pathlen = 512;
225 wchar_t *modulepath = NULL;
228 size_t u8_string_length;
230 /* This braindead function won't tell us how much space it needs, so
231 * we start at 1024 and double the space up if it doesn't fit, until
232 * it fits, or we exceed the threshold.
236 pathlen = pathlen * 2;
237 modulepath = GNUNET_realloc (modulepath,
238 pathlen * sizeof (wchar_t));
240 real_pathlen = GetModuleFileNameW (dll_instance,
242 pathlen * sizeof (wchar_t));
243 } while (real_pathlen >= pathlen && pathlen < 16*1024);
244 if (real_pathlen >= pathlen)
247 modulepath[real_pathlen] = '\0';
249 idx = modulepath + real_pathlen;
250 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
254 /* Now modulepath holds full path to the directory where libgnunetutil is.
255 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
257 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
259 /* At least one directory component (i.e. we're not in a root directory) */
260 wchar_t *dirname = idx;
261 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
264 if (dirname > modulepath)
267 /* Now modulepath holds full path to the parent directory of the directory
268 * where libgnunetutil is.
269 * dirname holds the name of the directory where libgnunetutil is.
271 if (wcsicmp (dirname, L"bin") == 0)
277 /* Roll back our changes to modulepath */
284 /* modulepath is GNUNET_PREFIX */
285 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
286 if (NULL == u8_string)
289 upath = GNUNET_malloc (u8_string_length + 1);
290 memcpy (upath, u8_string, u8_string_length);
291 upath[u8_string_length] = '\0';
294 GNUNET_free (modulepath);
303 * Signature of the '_NSGetExecutablePath" function.
305 * @param buf where to write the path
306 * @param number of bytes available in @a buf
307 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
310 (*MyNSGetExecutablePathProto) (char *buf,
315 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
317 * @return NULL on error
320 get_path_from_NSGetExecutablePath ()
322 static char zero = '\0';
325 MyNSGetExecutablePathProto func;
329 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
333 /* get the path len, including the trailing \0 */
334 (void) func (path, &len);
337 path = GNUNET_malloc (len);
338 if (0 != func (path, &len))
344 while ((path[len] != '/') && (len > 0))
352 * Try to obtain the path of our executable using '_dyld_image' API.
354 * @return NULL on error
357 get_path_from_dyld_image ()
365 c = _dyld_image_count ();
366 for (i = 0; i < c; i++)
368 if (((const void *) _dyld_get_image_header (i)) !=
369 ((const void *) &_mh_dylib_header) )
371 path = _dyld_get_image_name (i);
372 if ( (NULL == path) || (0 == strlen (path)) )
374 p = GNUNET_strdup (path);
376 while ((s > p) && ('/' != *s))
388 * Return the actual path to a file found in the current
389 * PATH environment variable.
391 * @param binary the name of the file to find
392 * @return path to binary, NULL if not found
395 get_path_from_PATH (const char *binary)
403 if (NULL == (p = getenv ("PATH")))
406 /* On W32 look in CWD first. */
407 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
409 path = GNUNET_strdup (p); /* because we write on it */
411 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
413 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
416 sprintf (buf, "%s/%s", pos, binary);
417 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
419 pos = GNUNET_strdup (pos);
426 sprintf (buf, "%s/%s", pos, binary);
427 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
429 pos = GNUNET_strdup (pos);
441 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
444 * @return NULL on error (environment variable not set)
447 get_path_from_GNUNET_PREFIX ()
451 if ( (NULL != current_pd->env_varname) &&
452 (NULL != (p = getenv (current_pd->env_varname))) )
453 return GNUNET_strdup (p);
454 if ( (NULL != current_pd->env_varname_alt) &&
455 (NULL != (p = getenv (current_pd->env_varname_alt))) )
456 return GNUNET_strdup (p);
462 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
465 * @return a pointer to the executable path, or NULL on error
468 os_get_gnunet_path ()
472 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
475 if (NULL != (ret = get_path_from_proc_maps ()))
477 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
478 if ( (NULL != current_pd->binary_name) &&
479 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
481 if (NULL != (ret = get_path_from_proc_exe ()))
485 if (NULL != (ret = get_path_from_module_filename ()))
489 if (NULL != (ret = get_path_from_dyld_image ()))
491 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
494 if ( (NULL != current_pd->binary_name) &&
495 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
497 /* other attempts here */
498 LOG (GNUNET_ERROR_TYPE_ERROR,
499 _("Could not determine installation path for %s. Set `%s' environment variable.\n"),
500 current_pd->project_dirname,
501 current_pd->env_varname);
507 * @brief get the path to current app's bin/
508 * @return a pointer to the executable path, or NULL on error
516 if (NULL != (ret = get_path_from_proc_exe ()))
520 if (NULL != (ret = get_path_from_module_filename ()))
524 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
527 /* other attempts here */
533 * @brief get the path to a specific GNUnet installation directory or,
534 * with #GNUNET_OS_IPK_SELF_PREFIX, the current running apps installation directory
535 * @return a pointer to the dir path (to be freed by the caller)
538 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
542 char *execpath = NULL;
548 /* if wanted, try to get the current app's bin/ */
549 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
550 execpath = os_get_exec_path ();
552 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
553 * guess for the current app */
554 if (NULL == execpath)
555 execpath = os_get_gnunet_path ();
557 if (NULL == execpath)
560 n = strlen (execpath);
563 /* should never happen, but better safe than sorry */
564 GNUNET_free (execpath);
567 /* remove filename itself */
568 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
569 execpath[--n] = '\0';
573 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
574 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
576 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
577 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
579 /* strip '/lib32' or '/lib64' */
580 execpath[n - 6] = '\0';
587 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
588 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
590 /* strip '/bin' or '/lib' */
591 execpath[n - 4] = '\0';
595 if (NULL != (libdir = strstr (execpath, "/lib/")))
597 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
598 here we need to re-add 'multiarch' to lib and libexec paths later! */
599 multiarch = &libdir[5];
600 if (NULL == strchr (multiarch, '/'))
601 libdir[0] = '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
603 multiarch = NULL; /* maybe not, multiarch still has a '/', which is not OK */
605 /* in case this was a directory named foo-bin, remove "foo-" */
606 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
607 execpath[--n] = '\0';
610 case GNUNET_OS_IPK_PREFIX:
611 case GNUNET_OS_IPK_SELF_PREFIX:
612 dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
614 case GNUNET_OS_IPK_BINDIR:
615 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
617 case GNUNET_OS_IPK_LIBDIR:
620 GNUNET_asprintf (&tmp,
623 DIR_SEPARATOR_STR "lib",
624 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
625 (NULL != multiarch) ? multiarch : "",
627 current_pd->project_dirname,
630 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
632 GNUNET_free (execpath);
638 if (4 == sizeof (void *))
640 GNUNET_asprintf (&dirname,
641 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
642 current_pd->project_dirname);
643 GNUNET_asprintf (&tmp,
648 if (8 == sizeof (void *))
650 GNUNET_asprintf (&dirname,
651 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
652 current_pd->project_dirname);
653 GNUNET_asprintf (&tmp,
659 if ( (NULL != tmp) &&
661 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
663 GNUNET_free (execpath);
664 GNUNET_free_non_null (dirname);
668 GNUNET_free_non_null (dirname);
670 GNUNET_asprintf (&dirname,
671 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
672 current_pd->project_dirname);
674 case GNUNET_OS_IPK_DATADIR:
675 GNUNET_asprintf (&dirname,
676 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
677 current_pd->project_dirname);
679 case GNUNET_OS_IPK_LOCALEDIR:
680 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR);
682 case GNUNET_OS_IPK_ICONDIR:
683 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR);
685 case GNUNET_OS_IPK_DOCDIR:
686 GNUNET_asprintf (&dirname,
687 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
688 current_pd->project_dirname);
690 case GNUNET_OS_IPK_LIBEXECDIR:
693 GNUNET_asprintf (&dirname,
694 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
695 current_pd->project_dirname);
696 GNUNET_asprintf (&tmp,
699 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
700 (NULL != multiarch) ? multiarch : "",
703 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
705 GNUNET_free (execpath);
706 GNUNET_free (dirname);
712 if (4 == sizeof (void *))
714 GNUNET_asprintf (&dirname,
715 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
716 current_pd->project_dirname);
717 GNUNET_asprintf (&tmp,
722 if (8 == sizeof (void *))
724 GNUNET_asprintf (&dirname,
725 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
726 current_pd->project_dirname);
727 GNUNET_asprintf (&tmp,
732 if ( (NULL != tmp) &&
734 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
736 GNUNET_free (execpath);
737 GNUNET_free_non_null (dirname);
741 GNUNET_free_non_null (dirname);
743 GNUNET_asprintf (&dirname,
744 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
745 current_pd->project_dirname);
748 GNUNET_free (execpath);
751 GNUNET_asprintf (&tmp,
755 GNUNET_free (dirname);
756 GNUNET_free (execpath);
762 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
763 * binary, try to prefix it with the libexec/-directory to get the
766 * @param progname name of the binary
767 * @return full path to the binary, if possible, otherwise copy of 'progname'
770 GNUNET_OS_get_libexec_binary_path (const char *progname)
776 if ( (DIR_SEPARATOR == progname[0]) ||
778 GNUNET_STRINGS_path_is_absolute (progname,
781 return GNUNET_strdup (progname);
785 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
786 if (NULL == libexecdir)
787 return GNUNET_strdup (progname);
788 GNUNET_asprintf (&binary,
798 * Check whether an executable exists and possibly if the suid bit is
799 * set on the file. Attempts to find the file using the current PATH
800 * environment variable as a search path.
802 * @param binary the name of the file to check.
803 * W32: must not have an .exe suffix.
804 * @param check_suid input true if the binary should be checked for SUID (*nix)
805 * W32: checks if the program has sufficient privileges by executing this
806 * binary with the -d flag. -d omits a programs main loop and only
807 * executes all privileged operations in an binary.
808 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
809 * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
810 * #GNUNET_NO if not SUID (but binary exists),
811 * #GNUNET_SYSERR on error (no such binary or not executable)
814 GNUNET_OS_check_helper_binary (const char *binary,
824 GNUNET_asprintf (&binaryexe, "%s.exe", binary);
825 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO,
827 (0 == strncmp (binary, "./", 2)) )
828 p = GNUNET_strdup (binaryexe);
831 p = get_path_from_PATH (binaryexe);
834 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
839 GNUNET_free (binaryexe);
841 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO,
843 (0 == strncmp (binary, "./", 2)) )
844 p = GNUNET_strdup (binary);
847 p = get_path_from_PATH (binary);
850 GNUNET_asprintf (&pf, "%s/%s", p, binary);
858 LOG (GNUNET_ERROR_TYPE_INFO,
859 _("Could not find binary `%s' in PATH!\n"),
861 return GNUNET_SYSERR;
863 if (0 != ACCESS (p, X_OK))
865 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
867 return GNUNET_SYSERR;
872 /* as we run as root, we don't insist on SUID */
877 if (0 != STAT (p, &statbuf))
879 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
881 return GNUNET_SYSERR;
885 if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
890 /* binary exists, but not SUID */
893 char parameters[512];
894 PROCESS_INFORMATION proc;
897 GNUNET_snprintf (parameters,
900 memset (&start, 0, sizeof (start));
901 start.cb = sizeof (start);
902 memset (&proc, 0, sizeof (proc));
905 // Start the child process.
906 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
907 parameters, // execute dryrun/priviliege checking mode
908 NULL, // Process handle not inheritable
909 NULL, // Thread handle not inheritable
910 FALSE, // Set handle inheritance to FALSE
911 CREATE_DEFAULT_ERROR_MODE, // No creation flags
912 NULL, // Use parent's environment block
913 NULL, // Use parent's starting directory
914 &start, // Pointer to STARTUPINFO structure
915 &proc ) // Pointer to PROCESS_INFORMATION structure
918 LOG (GNUNET_ERROR_TYPE_ERROR,
919 _("CreateProcess failed for binary %s (%d).\n"),
921 return GNUNET_SYSERR;
924 // Wait until child process exits.
925 WaitForSingleObject( proc.hProcess, INFINITE );
927 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
928 LOG (GNUNET_ERROR_TYPE_ERROR,
929 _("GetExitCodeProcess failed for binary %s (%d).\n"),
931 return GNUNET_SYSERR;
933 // Close process and thread handles.
934 CloseHandle( proc.hProcess );
935 CloseHandle( proc.hThread );
946 /* end of os_installation.c */