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/",
63 .config_file = "gnunet.conf",
64 .user_config_file = "~/.config/gnunet.conf"
68 * Which project data do we currently use for installation
69 * path detection? Never NULL.
71 static const struct GNUNET_OS_ProjectData *current_pd = &default_pd;
74 * Return default project data used by 'libgnunetutil' for GNUnet.
76 const struct GNUNET_OS_ProjectData *
77 GNUNET_OS_project_data_default (void)
84 * @return current project data.
86 const struct GNUNET_OS_ProjectData *
87 GNUNET_OS_project_data_get ()
94 * Setup OS subsystem with project data.
96 * @param pd project data used to determine paths
99 GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd)
101 GNUNET_assert (NULL != pd);
108 * Try to determine path by reading /proc/PID/exe
110 * @return NULL on error
113 get_path_from_proc_maps ()
121 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
122 if (NULL == (f = FOPEN (fn, "r")))
124 while (NULL != fgets (line, sizeof (line), f))
127 SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s", dir)) &&
128 (NULL != (lgu = strstr (dir,
129 current_pd->libname))))
133 return GNUNET_strdup (dir);
142 * Try to determine path by reading /proc/PID/exe
144 * @return NULL on error
147 get_path_from_proc_exe ()
154 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ());
155 size = readlink (fn, lnk, sizeof (lnk) - 1);
158 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
161 GNUNET_assert (size < sizeof (lnk));
163 while ((lnk[size] != '/') && (size > 0))
165 GNUNET_asprintf (&lep,
167 current_pd->project_dirname);
168 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
169 if ( (size > strlen (lep)) &&
171 &lnk[size - strlen (lep)])) )
172 size -= strlen (lep) - 1;
174 if ((size < 4) || (lnk[size - 4] != '/'))
176 /* not installed in "/bin/" -- binary path probably useless */
180 return GNUNET_strdup (lnk);
186 static HINSTANCE dll_instance;
190 * GNUNET_util_cl_init() in common_logging.c is preferred.
191 * This function is only for thread-local storage (not used in GNUnet)
192 * and hInstance saving.
195 DllMain (HINSTANCE hinstDLL,
201 case DLL_PROCESS_ATTACH:
202 dll_instance = hinstDLL;
204 case DLL_THREAD_ATTACH:
206 case DLL_THREAD_DETACH:
208 case DLL_PROCESS_DETACH:
216 * Try to determine path with win32-specific function
218 * @return NULL on error
221 get_path_from_module_filename ()
223 size_t pathlen = 512;
226 wchar_t *modulepath = NULL;
229 size_t u8_string_length;
231 /* This braindead function won't tell us how much space it needs, so
232 * we start at 1024 and double the space up if it doesn't fit, until
233 * it fits, or we exceed the threshold.
237 pathlen = pathlen * 2;
238 modulepath = GNUNET_realloc (modulepath,
239 pathlen * sizeof (wchar_t));
241 real_pathlen = GetModuleFileNameW (dll_instance,
243 pathlen * sizeof (wchar_t));
244 } while (real_pathlen >= pathlen && pathlen < 16*1024);
245 if (real_pathlen >= pathlen)
248 modulepath[real_pathlen] = '\0';
250 idx = modulepath + real_pathlen;
251 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
255 /* Now modulepath holds full path to the directory where libgnunetutil is.
256 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
258 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
260 /* At least one directory component (i.e. we're not in a root directory) */
261 wchar_t *dirname = idx;
262 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
265 if (dirname > modulepath)
268 /* Now modulepath holds full path to the parent directory of the directory
269 * where libgnunetutil is.
270 * dirname holds the name of the directory where libgnunetutil is.
272 if (wcsicmp (dirname, L"bin") == 0)
278 /* Roll back our changes to modulepath */
285 /* modulepath is GNUNET_PREFIX */
286 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
287 if (NULL == u8_string)
290 upath = GNUNET_malloc (u8_string_length + 1);
291 memcpy (upath, u8_string, u8_string_length);
292 upath[u8_string_length] = '\0';
295 GNUNET_free (modulepath);
304 * Signature of the '_NSGetExecutablePath" function.
306 * @param buf where to write the path
307 * @param number of bytes available in @a buf
308 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
311 (*MyNSGetExecutablePathProto) (char *buf,
316 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
318 * @return NULL on error
321 get_path_from_NSGetExecutablePath ()
323 static char zero = '\0';
326 MyNSGetExecutablePathProto func;
330 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
334 /* get the path len, including the trailing \0 */
335 (void) func (path, &len);
338 path = GNUNET_malloc (len);
339 if (0 != func (path, &len))
345 while ((path[len] != '/') && (len > 0))
353 * Try to obtain the path of our executable using '_dyld_image' API.
355 * @return NULL on error
358 get_path_from_dyld_image ()
366 c = _dyld_image_count ();
367 for (i = 0; i < c; i++)
369 if (((const void *) _dyld_get_image_header (i)) !=
370 ((const void *) &_mh_dylib_header) )
372 path = _dyld_get_image_name (i);
373 if ( (NULL == path) || (0 == strlen (path)) )
375 p = GNUNET_strdup (path);
377 while ((s > p) && ('/' != *s))
389 * Return the actual path to a file found in the current
390 * PATH environment variable.
392 * @param binary the name of the file to find
393 * @return path to binary, NULL if not found
396 get_path_from_PATH (const char *binary)
404 if (NULL == (p = getenv ("PATH")))
407 /* On W32 look in CWD first. */
408 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
410 path = GNUNET_strdup (p); /* because we write on it */
412 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
414 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
417 sprintf (buf, "%s/%s", pos, binary);
418 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
420 pos = GNUNET_strdup (pos);
427 sprintf (buf, "%s/%s", pos, binary);
428 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
430 pos = GNUNET_strdup (pos);
442 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
445 * @return NULL on error (environment variable not set)
448 get_path_from_GNUNET_PREFIX ()
452 if ( (NULL != current_pd->env_varname) &&
453 (NULL != (p = getenv (current_pd->env_varname))) )
454 return GNUNET_strdup (p);
455 if ( (NULL != current_pd->env_varname_alt) &&
456 (NULL != (p = getenv (current_pd->env_varname_alt))) )
457 return GNUNET_strdup (p);
463 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
466 * @return a pointer to the executable path, or NULL on error
469 os_get_gnunet_path ()
473 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
476 if (NULL != (ret = get_path_from_proc_maps ()))
478 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
479 if ( (NULL != current_pd->binary_name) &&
480 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
482 if (NULL != (ret = get_path_from_proc_exe ()))
486 if (NULL != (ret = get_path_from_module_filename ()))
490 if (NULL != (ret = get_path_from_dyld_image ()))
492 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
495 if ( (NULL != current_pd->binary_name) &&
496 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
498 /* other attempts here */
499 LOG (GNUNET_ERROR_TYPE_ERROR,
500 _("Could not determine installation path for %s. Set `%s' environment variable.\n"),
501 current_pd->project_dirname,
502 current_pd->env_varname);
508 * @brief get the path to current app's bin/
509 * @return a pointer to the executable path, or NULL on error
517 if (NULL != (ret = get_path_from_proc_exe ()))
521 if (NULL != (ret = get_path_from_module_filename ()))
525 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
528 /* other attempts here */
534 * @brief get the path to a specific GNUnet installation directory or,
535 * with #GNUNET_OS_IPK_SELF_PREFIX, the current running apps installation directory
536 * @return a pointer to the dir path (to be freed by the caller)
539 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
543 char *execpath = NULL;
549 /* if wanted, try to get the current app's bin/ */
550 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
551 execpath = os_get_exec_path ();
553 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
554 * guess for the current app */
555 if (NULL == execpath)
556 execpath = os_get_gnunet_path ();
558 if (NULL == execpath)
561 n = strlen (execpath);
564 /* should never happen, but better safe than sorry */
565 GNUNET_free (execpath);
568 /* remove filename itself */
569 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
570 execpath[--n] = '\0';
574 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
575 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
577 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
578 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
580 /* strip '/lib32' or '/lib64' */
581 execpath[n - 6] = '\0';
588 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
589 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
591 /* strip '/bin' or '/lib' */
592 execpath[n - 4] = '\0';
596 if (NULL != (libdir = strstr (execpath, "/lib/")))
598 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
599 here we need to re-add 'multiarch' to lib and libexec paths later! */
600 multiarch = &libdir[5];
601 if (NULL == strchr (multiarch, '/'))
602 libdir[0] = '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
604 multiarch = NULL; /* maybe not, multiarch still has a '/', which is not OK */
606 /* in case this was a directory named foo-bin, remove "foo-" */
607 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
608 execpath[--n] = '\0';
611 case GNUNET_OS_IPK_PREFIX:
612 case GNUNET_OS_IPK_SELF_PREFIX:
613 dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
615 case GNUNET_OS_IPK_BINDIR:
616 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
618 case GNUNET_OS_IPK_LIBDIR:
621 GNUNET_asprintf (&tmp,
624 DIR_SEPARATOR_STR "lib",
625 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
626 (NULL != multiarch) ? multiarch : "",
628 current_pd->project_dirname,
631 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
633 GNUNET_free (execpath);
639 if (4 == sizeof (void *))
641 GNUNET_asprintf (&dirname,
642 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
643 current_pd->project_dirname);
644 GNUNET_asprintf (&tmp,
649 if (8 == sizeof (void *))
651 GNUNET_asprintf (&dirname,
652 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
653 current_pd->project_dirname);
654 GNUNET_asprintf (&tmp,
660 if ( (NULL != tmp) &&
662 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
664 GNUNET_free (execpath);
665 GNUNET_free_non_null (dirname);
669 GNUNET_free_non_null (dirname);
671 GNUNET_asprintf (&dirname,
672 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
673 current_pd->project_dirname);
675 case GNUNET_OS_IPK_DATADIR:
676 GNUNET_asprintf (&dirname,
677 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
678 current_pd->project_dirname);
680 case GNUNET_OS_IPK_LOCALEDIR:
681 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR);
683 case GNUNET_OS_IPK_ICONDIR:
684 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR);
686 case GNUNET_OS_IPK_DOCDIR:
687 GNUNET_asprintf (&dirname,
688 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
689 current_pd->project_dirname);
691 case GNUNET_OS_IPK_LIBEXECDIR:
694 GNUNET_asprintf (&dirname,
695 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
696 current_pd->project_dirname);
697 GNUNET_asprintf (&tmp,
700 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
701 (NULL != multiarch) ? multiarch : "",
704 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
706 GNUNET_free (execpath);
707 GNUNET_free (dirname);
713 if (4 == sizeof (void *))
715 GNUNET_asprintf (&dirname,
716 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
717 current_pd->project_dirname);
718 GNUNET_asprintf (&tmp,
723 if (8 == sizeof (void *))
725 GNUNET_asprintf (&dirname,
726 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
727 current_pd->project_dirname);
728 GNUNET_asprintf (&tmp,
733 if ( (NULL != tmp) &&
735 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
737 GNUNET_free (execpath);
738 GNUNET_free_non_null (dirname);
742 GNUNET_free_non_null (dirname);
744 GNUNET_asprintf (&dirname,
745 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
746 current_pd->project_dirname);
749 GNUNET_free (execpath);
752 GNUNET_asprintf (&tmp,
756 GNUNET_free (dirname);
757 GNUNET_free (execpath);
763 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
764 * binary, try to prefix it with the libexec/-directory to get the
767 * @param progname name of the binary
768 * @return full path to the binary, if possible, otherwise copy of 'progname'
771 GNUNET_OS_get_libexec_binary_path (const char *progname)
777 if ( (DIR_SEPARATOR == progname[0]) ||
779 GNUNET_STRINGS_path_is_absolute (progname,
782 return GNUNET_strdup (progname);
786 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
787 if (NULL == libexecdir)
788 return GNUNET_strdup (progname);
789 GNUNET_asprintf (&binary,
799 * Check whether an executable exists and possibly if the suid bit is
800 * set on the file. Attempts to find the file using the current PATH
801 * environment variable as a search path.
803 * @param binary the name of the file to check.
804 * W32: must not have an .exe suffix.
805 * @param check_suid input true if the binary should be checked for SUID (*nix)
806 * W32: checks if the program has sufficient privileges by executing this
807 * binary with the -d flag. -d omits a programs main loop and only
808 * executes all privileged operations in an binary.
809 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
810 * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
811 * #GNUNET_NO if not SUID (but binary exists),
812 * #GNUNET_SYSERR on error (no such binary or not executable)
815 GNUNET_OS_check_helper_binary (const char *binary,
825 GNUNET_asprintf (&binaryexe, "%s.exe", binary);
826 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO,
828 (0 == strncmp (binary, "./", 2)) )
829 p = GNUNET_strdup (binaryexe);
832 p = get_path_from_PATH (binaryexe);
835 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
840 GNUNET_free (binaryexe);
842 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO,
844 (0 == strncmp (binary, "./", 2)) )
845 p = GNUNET_strdup (binary);
848 p = get_path_from_PATH (binary);
851 GNUNET_asprintf (&pf, "%s/%s", p, binary);
859 LOG (GNUNET_ERROR_TYPE_INFO,
860 _("Could not find binary `%s' in PATH!\n"),
862 return GNUNET_SYSERR;
864 if (0 != ACCESS (p, X_OK))
866 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
868 return GNUNET_SYSERR;
873 /* as we run as root, we don't insist on SUID */
878 if (0 != STAT (p, &statbuf))
880 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
882 return GNUNET_SYSERR;
886 if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
891 /* binary exists, but not SUID */
894 char parameters[512];
895 PROCESS_INFORMATION proc;
898 GNUNET_snprintf (parameters,
901 memset (&start, 0, sizeof (start));
902 start.cb = sizeof (start);
903 memset (&proc, 0, sizeof (proc));
906 // Start the child process.
907 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
908 parameters, // execute dryrun/priviliege checking mode
909 NULL, // Process handle not inheritable
910 NULL, // Thread handle not inheritable
911 FALSE, // Set handle inheritance to FALSE
912 CREATE_DEFAULT_ERROR_MODE, // No creation flags
913 NULL, // Use parent's environment block
914 NULL, // Use parent's starting directory
915 &start, // Pointer to STARTUPINFO structure
916 &proc ) // Pointer to PROCESS_INFORMATION structure
919 LOG (GNUNET_ERROR_TYPE_ERROR,
920 _("CreateProcess failed for binary %s (%d).\n"),
922 return GNUNET_SYSERR;
925 // Wait until child process exits.
926 WaitForSingleObject( proc.hProcess, INFINITE );
928 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
929 LOG (GNUNET_ERROR_TYPE_ERROR,
930 _("GetExitCodeProcess failed for binary %s (%d).\n"),
932 return GNUNET_SYSERR;
934 // Close process and thread handles.
935 CloseHandle( proc.hProcess );
936 CloseHandle( proc.hThread );
947 /* end of os_installation.c */