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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
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-os-installation", __VA_ARGS__)
49 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-os-installation", 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 .base_config_varname = "GNUNET_BASE_CONFIG",
62 .bug_email = "gnunet-developers@gnu.org",
63 .homepage = "http://www.gnu.org/s/gnunet/",
64 .config_file = "gnunet.conf",
65 .user_config_file = "~/.config/gnunet.conf",
69 * Which project data do we currently use for installation
70 * path detection? Never NULL.
72 static const struct GNUNET_OS_ProjectData *current_pd = &default_pd;
75 * Return default project data used by 'libgnunetutil' for GNUnet.
77 const struct GNUNET_OS_ProjectData *
78 GNUNET_OS_project_data_default (void)
85 * @return current project data.
87 const struct GNUNET_OS_ProjectData *
88 GNUNET_OS_project_data_get ()
95 * Setup OS subsystem with project data.
97 * @param pd project data used to determine paths
100 GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd)
102 GNUNET_assert (NULL != pd);
109 * Try to determine path by reading /proc/PID/exe
111 * @return NULL on error
114 get_path_from_proc_maps ()
122 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
123 if (NULL == (f = FOPEN (fn, "r")))
125 while (NULL != fgets (line, sizeof (line), f))
128 SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s", dir)) &&
129 (NULL != (lgu = strstr (dir,
130 current_pd->libname))))
134 return GNUNET_strdup (dir);
143 * Try to determine path by reading /proc/PID/exe
145 * @return NULL on error
148 get_path_from_proc_exe ()
164 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
169 GNUNET_assert ( ((size_t) size) < sizeof (lnk));
171 while ((lnk[size] != '/') && (size > 0))
173 GNUNET_asprintf (&lep,
175 current_pd->project_dirname);
176 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
177 if ( (((size_t) size) > strlen (lep)) &&
179 &lnk[size - strlen (lep)])) )
180 size -= strlen (lep) - 1;
183 (lnk[size - 4] != '/') )
185 /* not installed in "/bin/" -- binary path probably useless */
189 return GNUNET_strdup (lnk);
195 static HINSTANCE dll_instance;
199 * GNUNET_util_cl_init() in common_logging.c is preferred.
200 * This function is only for thread-local storage (not used in GNUnet)
201 * and hInstance saving.
204 DllMain (HINSTANCE hinstDLL,
210 case DLL_PROCESS_ATTACH:
211 dll_instance = hinstDLL;
213 case DLL_THREAD_ATTACH:
215 case DLL_THREAD_DETACH:
217 case DLL_PROCESS_DETACH:
225 * Try to determine path with win32-specific function
227 * @return NULL on error
230 get_path_from_module_filename ()
232 size_t pathlen = 512;
235 wchar_t *modulepath = NULL;
238 size_t u8_string_length;
240 /* This braindead function won't tell us how much space it needs, so
241 * we start at 1024 and double the space up if it doesn't fit, until
242 * it fits, or we exceed the threshold.
246 pathlen = pathlen * 2;
247 modulepath = GNUNET_realloc (modulepath,
248 pathlen * sizeof (wchar_t));
250 real_pathlen = GetModuleFileNameW (dll_instance,
252 pathlen * sizeof (wchar_t));
253 } while (real_pathlen >= pathlen && pathlen < 16*1024);
254 if (real_pathlen >= pathlen)
257 modulepath[real_pathlen] = '\0';
259 idx = modulepath + real_pathlen;
260 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
264 /* Now modulepath holds full path to the directory where libgnunetutil is.
265 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
267 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
269 /* At least one directory component (i.e. we're not in a root directory) */
270 wchar_t *dirname = idx;
271 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
274 if (dirname > modulepath)
277 /* Now modulepath holds full path to the parent directory of the directory
278 * where libgnunetutil is.
279 * dirname holds the name of the directory where libgnunetutil is.
281 if (wcsicmp (dirname, L"bin") == 0)
287 /* Roll back our changes to modulepath */
294 /* modulepath is GNUNET_PREFIX */
295 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
296 if (NULL == u8_string)
299 upath = GNUNET_malloc (u8_string_length + 1);
300 GNUNET_memcpy (upath, u8_string, u8_string_length);
301 upath[u8_string_length] = '\0';
304 GNUNET_free (modulepath);
313 * Signature of the '_NSGetExecutablePath" function.
315 * @param buf where to write the path
316 * @param number of bytes available in @a buf
317 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
320 (*MyNSGetExecutablePathProto) (char *buf,
325 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
327 * @return NULL on error
330 get_path_from_NSGetExecutablePath ()
332 static char zero = '\0';
335 MyNSGetExecutablePathProto func;
339 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
343 /* get the path len, including the trailing \0 */
344 (void) func (path, &len);
347 path = GNUNET_malloc (len);
348 if (0 != func (path, &len))
354 while ((path[len] != '/') && (len > 0))
362 * Try to obtain the path of our executable using '_dyld_image' API.
364 * @return NULL on error
367 get_path_from_dyld_image ()
375 c = _dyld_image_count ();
376 for (i = 0; i < c; i++)
378 if (((const void *) _dyld_get_image_header (i)) !=
379 ((const void *) &_mh_dylib_header) )
381 path = _dyld_get_image_name (i);
382 if ( (NULL == path) || (0 == strlen (path)) )
384 p = GNUNET_strdup (path);
386 while ((s > p) && ('/' != *s))
398 * Return the actual path to a file found in the current
399 * PATH environment variable.
401 * @param binary the name of the file to find
402 * @return path to binary, NULL if not found
405 get_path_from_PATH (const char *binary)
413 if (NULL == (p = getenv ("PATH")))
416 /* On W32 look in CWD first. */
417 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
419 path = GNUNET_strdup (p); /* because we write on it */
421 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
423 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
426 sprintf (buf, "%s/%s", pos, binary);
427 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
429 pos = GNUNET_strdup (pos);
436 sprintf (buf, "%s/%s", pos, binary);
437 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
439 pos = GNUNET_strdup (pos);
451 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
454 * @return NULL on error (environment variable not set)
457 get_path_from_GNUNET_PREFIX ()
461 if ( (NULL != current_pd->env_varname) &&
462 (NULL != (p = getenv (current_pd->env_varname))) )
463 return GNUNET_strdup (p);
464 if ( (NULL != current_pd->env_varname_alt) &&
465 (NULL != (p = getenv (current_pd->env_varname_alt))) )
466 return GNUNET_strdup (p);
472 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
475 * @return a pointer to the executable path, or NULL on error
478 os_get_gnunet_path ()
482 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
485 if (NULL != (ret = get_path_from_proc_maps ()))
487 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
488 if ( (NULL != current_pd->binary_name) &&
489 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
491 if (NULL != (ret = get_path_from_proc_exe ()))
495 if (NULL != (ret = get_path_from_module_filename ()))
499 if (NULL != (ret = get_path_from_dyld_image ()))
501 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
504 if ( (NULL != current_pd->binary_name) &&
505 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
507 /* other attempts here */
508 LOG (GNUNET_ERROR_TYPE_ERROR,
509 _("Could not determine installation path for %s. Set `%s' environment variable.\n"),
510 current_pd->project_dirname,
511 current_pd->env_varname);
517 * @brief get the path to current app's bin/
518 * @return a pointer to the executable path, or NULL on error
526 if (NULL != (ret = get_path_from_proc_exe ()))
530 if (NULL != (ret = get_path_from_module_filename ()))
534 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
537 /* other attempts here */
543 * @brief get the path to a specific GNUnet installation directory or,
544 * with #GNUNET_OS_IPK_SELF_PREFIX, the current running apps installation directory
545 * @return a pointer to the dir path (to be freed by the caller)
548 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
552 char *execpath = NULL;
558 /* if wanted, try to get the current app's bin/ */
559 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
560 execpath = os_get_exec_path ();
562 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
563 * guess for the current app */
564 if (NULL == execpath)
565 execpath = os_get_gnunet_path ();
567 if (NULL == execpath)
570 n = strlen (execpath);
573 /* should never happen, but better safe than sorry */
574 GNUNET_free (execpath);
577 /* remove filename itself */
578 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
579 execpath[--n] = '\0';
583 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
584 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
586 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
587 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
589 /* strip '/lib32' or '/lib64' */
590 execpath[n - 6] = '\0';
597 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
598 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
600 /* strip '/bin' or '/lib' */
601 execpath[n - 4] = '\0';
605 if (NULL != (libdir = strstr (execpath, "/lib/")))
607 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
608 here we need to re-add 'multiarch' to lib and libexec paths later! */
609 multiarch = &libdir[5];
610 if (NULL == strchr (multiarch, '/'))
611 libdir[0] = '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
613 multiarch = NULL; /* maybe not, multiarch still has a '/', which is not OK */
615 /* in case this was a directory named foo-bin, remove "foo-" */
616 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
617 execpath[--n] = '\0';
620 case GNUNET_OS_IPK_PREFIX:
621 case GNUNET_OS_IPK_SELF_PREFIX:
622 dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
624 case GNUNET_OS_IPK_BINDIR:
625 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
627 case GNUNET_OS_IPK_LIBDIR:
630 GNUNET_asprintf (&tmp,
633 DIR_SEPARATOR_STR "lib",
634 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
635 (NULL != multiarch) ? multiarch : "",
637 current_pd->project_dirname,
640 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
642 GNUNET_free (execpath);
648 if (4 == sizeof (void *))
650 GNUNET_asprintf (&dirname,
651 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
652 current_pd->project_dirname);
653 GNUNET_asprintf (&tmp,
658 if (8 == sizeof (void *))
660 GNUNET_asprintf (&dirname,
661 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
662 current_pd->project_dirname);
663 GNUNET_asprintf (&tmp,
669 if ( (NULL != tmp) &&
671 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
673 GNUNET_free (execpath);
674 GNUNET_free_non_null (dirname);
678 GNUNET_free_non_null (dirname);
680 GNUNET_asprintf (&dirname,
681 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
682 current_pd->project_dirname);
684 case GNUNET_OS_IPK_DATADIR:
685 GNUNET_asprintf (&dirname,
686 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
687 current_pd->project_dirname);
689 case GNUNET_OS_IPK_LOCALEDIR:
690 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR);
692 case GNUNET_OS_IPK_ICONDIR:
693 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR);
695 case GNUNET_OS_IPK_DOCDIR:
696 GNUNET_asprintf (&dirname,
697 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
698 current_pd->project_dirname);
700 case GNUNET_OS_IPK_LIBEXECDIR:
703 GNUNET_asprintf (&dirname,
704 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
705 current_pd->project_dirname);
706 GNUNET_asprintf (&tmp,
709 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
710 (NULL != multiarch) ? multiarch : "",
713 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
715 GNUNET_free (execpath);
716 GNUNET_free (dirname);
722 if (4 == sizeof (void *))
724 GNUNET_asprintf (&dirname,
725 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
726 current_pd->project_dirname);
727 GNUNET_asprintf (&tmp,
732 if (8 == sizeof (void *))
734 GNUNET_asprintf (&dirname,
735 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
736 current_pd->project_dirname);
737 GNUNET_asprintf (&tmp,
742 if ( (NULL != tmp) &&
744 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
746 GNUNET_free (execpath);
747 GNUNET_free_non_null (dirname);
751 GNUNET_free_non_null (dirname);
753 GNUNET_asprintf (&dirname,
754 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
755 current_pd->project_dirname);
758 GNUNET_free (execpath);
761 GNUNET_asprintf (&tmp,
765 GNUNET_free (dirname);
766 GNUNET_free (execpath);
772 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
773 * binary, try to prefix it with the libexec/-directory to get the
776 * @param progname name of the binary
777 * @return full path to the binary, if possible, otherwise copy of 'progname'
780 GNUNET_OS_get_libexec_binary_path (const char *progname)
786 if ( (DIR_SEPARATOR == progname[0]) ||
788 GNUNET_STRINGS_path_is_absolute (progname,
791 return GNUNET_strdup (progname);
795 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
796 if (NULL == libexecdir)
797 return GNUNET_strdup (progname);
798 GNUNET_asprintf (&binary,
808 * Check whether an executable exists and possibly if the suid bit is
809 * set on the file. Attempts to find the file using the current PATH
810 * environment variable as a search path.
812 * @param binary the name of the file to check.
813 * W32: must not have an .exe suffix.
814 * @param check_suid input true if the binary should be checked for SUID (*nix)
815 * W32: checks if the program has sufficient privileges by executing this
816 * binary with the -d flag. -d omits a programs main loop and only
817 * executes all privileged operations in an binary.
818 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
819 * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
820 * #GNUNET_NO if not SUID (but binary exists),
821 * #GNUNET_SYSERR on error (no such binary or not executable)
824 GNUNET_OS_check_helper_binary (const char *binary,
834 GNUNET_asprintf (&binaryexe,
838 GNUNET_STRINGS_path_is_absolute (binaryexe,
841 (0 == strncmp (binary, "./", 2)) )
842 p = GNUNET_strdup (binaryexe);
845 p = get_path_from_PATH (binaryexe);
848 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
853 GNUNET_free (binaryexe);
856 GNUNET_STRINGS_path_is_absolute (binary,
860 (0 == strncmp (binary, "./", 2)) )
862 p = GNUNET_strdup (binary);
866 p = get_path_from_PATH (binary);
869 GNUNET_asprintf (&pf,
880 LOG (GNUNET_ERROR_TYPE_INFO,
881 _("Could not find binary `%s' in PATH!\n"),
883 return GNUNET_SYSERR;
888 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
892 return GNUNET_SYSERR;
897 /* as we run as root, we don't insist on SUID */
905 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
909 return GNUNET_SYSERR;
915 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
916 (0 == statbuf.st_uid) )
921 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
922 _("Binary `%s' exists, but is not SUID\n"),
924 /* binary exists, but not SUID */
927 char parameters[512];
928 PROCESS_INFORMATION proc;
931 GNUNET_snprintf (parameters,
934 memset (&start, 0, sizeof (start));
935 start.cb = sizeof (start);
936 memset (&proc, 0, sizeof (proc));
939 // Start the child process.
940 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
941 parameters, // execute dryrun/priviliege checking mode
942 NULL, // Process handle not inheritable
943 NULL, // Thread handle not inheritable
944 FALSE, // Set handle inheritance to FALSE
945 CREATE_DEFAULT_ERROR_MODE, // No creation flags
946 NULL, // Use parent's environment block
947 NULL, // Use parent's starting directory
948 &start, // Pointer to STARTUPINFO structure
949 &proc ) // Pointer to PROCESS_INFORMATION structure
952 LOG (GNUNET_ERROR_TYPE_ERROR,
953 _("CreateProcess failed for binary %s (%d).\n"),
955 return GNUNET_SYSERR;
958 // Wait until child process exits.
959 WaitForSingleObject( proc.hProcess, INFINITE );
961 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
962 LOG (GNUNET_ERROR_TYPE_ERROR,
963 _("GetExitCodeProcess failed for binary %s (%d).\n"),
965 return GNUNET_SYSERR;
967 // Close process and thread handles.
968 CloseHandle( proc.hProcess );
969 CloseHandle( proc.hThread );
980 /* end of os_installation.c */