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-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 ()
155 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ());
156 size = readlink (fn, lnk, sizeof (lnk) - 1);
159 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
162 GNUNET_assert (size < sizeof (lnk));
164 while ((lnk[size] != '/') && (size > 0))
166 GNUNET_asprintf (&lep,
168 current_pd->project_dirname);
169 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
170 if ( (size > strlen (lep)) &&
172 &lnk[size - strlen (lep)])) )
173 size -= strlen (lep) - 1;
175 if ((size < 4) || (lnk[size - 4] != '/'))
177 /* not installed in "/bin/" -- binary path probably useless */
181 return GNUNET_strdup (lnk);
187 static HINSTANCE dll_instance;
191 * GNUNET_util_cl_init() in common_logging.c is preferred.
192 * This function is only for thread-local storage (not used in GNUnet)
193 * and hInstance saving.
196 DllMain (HINSTANCE hinstDLL,
202 case DLL_PROCESS_ATTACH:
203 dll_instance = hinstDLL;
205 case DLL_THREAD_ATTACH:
207 case DLL_THREAD_DETACH:
209 case DLL_PROCESS_DETACH:
217 * Try to determine path with win32-specific function
219 * @return NULL on error
222 get_path_from_module_filename ()
224 size_t pathlen = 512;
227 wchar_t *modulepath = NULL;
230 size_t u8_string_length;
232 /* This braindead function won't tell us how much space it needs, so
233 * we start at 1024 and double the space up if it doesn't fit, until
234 * it fits, or we exceed the threshold.
238 pathlen = pathlen * 2;
239 modulepath = GNUNET_realloc (modulepath,
240 pathlen * sizeof (wchar_t));
242 real_pathlen = GetModuleFileNameW (dll_instance,
244 pathlen * sizeof (wchar_t));
245 } while (real_pathlen >= pathlen && pathlen < 16*1024);
246 if (real_pathlen >= pathlen)
249 modulepath[real_pathlen] = '\0';
251 idx = modulepath + real_pathlen;
252 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
256 /* Now modulepath holds full path to the directory where libgnunetutil is.
257 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
259 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
261 /* At least one directory component (i.e. we're not in a root directory) */
262 wchar_t *dirname = idx;
263 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
266 if (dirname > modulepath)
269 /* Now modulepath holds full path to the parent directory of the directory
270 * where libgnunetutil is.
271 * dirname holds the name of the directory where libgnunetutil is.
273 if (wcsicmp (dirname, L"bin") == 0)
279 /* Roll back our changes to modulepath */
286 /* modulepath is GNUNET_PREFIX */
287 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
288 if (NULL == u8_string)
291 upath = GNUNET_malloc (u8_string_length + 1);
292 GNUNET_memcpy (upath, u8_string, u8_string_length);
293 upath[u8_string_length] = '\0';
296 GNUNET_free (modulepath);
305 * Signature of the '_NSGetExecutablePath" function.
307 * @param buf where to write the path
308 * @param number of bytes available in @a buf
309 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
312 (*MyNSGetExecutablePathProto) (char *buf,
317 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
319 * @return NULL on error
322 get_path_from_NSGetExecutablePath ()
324 static char zero = '\0';
327 MyNSGetExecutablePathProto func;
331 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
335 /* get the path len, including the trailing \0 */
336 (void) func (path, &len);
339 path = GNUNET_malloc (len);
340 if (0 != func (path, &len))
346 while ((path[len] != '/') && (len > 0))
354 * Try to obtain the path of our executable using '_dyld_image' API.
356 * @return NULL on error
359 get_path_from_dyld_image ()
367 c = _dyld_image_count ();
368 for (i = 0; i < c; i++)
370 if (((const void *) _dyld_get_image_header (i)) !=
371 ((const void *) &_mh_dylib_header) )
373 path = _dyld_get_image_name (i);
374 if ( (NULL == path) || (0 == strlen (path)) )
376 p = GNUNET_strdup (path);
378 while ((s > p) && ('/' != *s))
390 * Return the actual path to a file found in the current
391 * PATH environment variable.
393 * @param binary the name of the file to find
394 * @return path to binary, NULL if not found
397 get_path_from_PATH (const char *binary)
405 if (NULL == (p = getenv ("PATH")))
408 /* On W32 look in CWD first. */
409 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
411 path = GNUNET_strdup (p); /* because we write on it */
413 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
415 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
418 sprintf (buf, "%s/%s", pos, binary);
419 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
421 pos = GNUNET_strdup (pos);
428 sprintf (buf, "%s/%s", pos, binary);
429 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
431 pos = GNUNET_strdup (pos);
443 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
446 * @return NULL on error (environment variable not set)
449 get_path_from_GNUNET_PREFIX ()
453 if ( (NULL != current_pd->env_varname) &&
454 (NULL != (p = getenv (current_pd->env_varname))) )
455 return GNUNET_strdup (p);
456 if ( (NULL != current_pd->env_varname_alt) &&
457 (NULL != (p = getenv (current_pd->env_varname_alt))) )
458 return GNUNET_strdup (p);
464 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
467 * @return a pointer to the executable path, or NULL on error
470 os_get_gnunet_path ()
474 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
477 if (NULL != (ret = get_path_from_proc_maps ()))
479 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
480 if ( (NULL != current_pd->binary_name) &&
481 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
483 if (NULL != (ret = get_path_from_proc_exe ()))
487 if (NULL != (ret = get_path_from_module_filename ()))
491 if (NULL != (ret = get_path_from_dyld_image ()))
493 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
496 if ( (NULL != current_pd->binary_name) &&
497 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
499 /* other attempts here */
500 LOG (GNUNET_ERROR_TYPE_ERROR,
501 _("Could not determine installation path for %s. Set `%s' environment variable.\n"),
502 current_pd->project_dirname,
503 current_pd->env_varname);
509 * @brief get the path to current app's bin/
510 * @return a pointer to the executable path, or NULL on error
518 if (NULL != (ret = get_path_from_proc_exe ()))
522 if (NULL != (ret = get_path_from_module_filename ()))
526 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
529 /* other attempts here */
535 * @brief get the path to a specific GNUnet installation directory or,
536 * with #GNUNET_OS_IPK_SELF_PREFIX, the current running apps installation directory
537 * @return a pointer to the dir path (to be freed by the caller)
540 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
544 char *execpath = NULL;
550 /* if wanted, try to get the current app's bin/ */
551 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
552 execpath = os_get_exec_path ();
554 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
555 * guess for the current app */
556 if (NULL == execpath)
557 execpath = os_get_gnunet_path ();
559 if (NULL == execpath)
562 n = strlen (execpath);
565 /* should never happen, but better safe than sorry */
566 GNUNET_free (execpath);
569 /* remove filename itself */
570 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
571 execpath[--n] = '\0';
575 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
576 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
578 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
579 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
581 /* strip '/lib32' or '/lib64' */
582 execpath[n - 6] = '\0';
589 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
590 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
592 /* strip '/bin' or '/lib' */
593 execpath[n - 4] = '\0';
597 if (NULL != (libdir = strstr (execpath, "/lib/")))
599 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
600 here we need to re-add 'multiarch' to lib and libexec paths later! */
601 multiarch = &libdir[5];
602 if (NULL == strchr (multiarch, '/'))
603 libdir[0] = '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
605 multiarch = NULL; /* maybe not, multiarch still has a '/', which is not OK */
607 /* in case this was a directory named foo-bin, remove "foo-" */
608 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
609 execpath[--n] = '\0';
612 case GNUNET_OS_IPK_PREFIX:
613 case GNUNET_OS_IPK_SELF_PREFIX:
614 dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
616 case GNUNET_OS_IPK_BINDIR:
617 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
619 case GNUNET_OS_IPK_LIBDIR:
622 GNUNET_asprintf (&tmp,
625 DIR_SEPARATOR_STR "lib",
626 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
627 (NULL != multiarch) ? multiarch : "",
629 current_pd->project_dirname,
632 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
634 GNUNET_free (execpath);
640 if (4 == sizeof (void *))
642 GNUNET_asprintf (&dirname,
643 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
644 current_pd->project_dirname);
645 GNUNET_asprintf (&tmp,
650 if (8 == sizeof (void *))
652 GNUNET_asprintf (&dirname,
653 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
654 current_pd->project_dirname);
655 GNUNET_asprintf (&tmp,
661 if ( (NULL != tmp) &&
663 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
665 GNUNET_free (execpath);
666 GNUNET_free_non_null (dirname);
670 GNUNET_free_non_null (dirname);
672 GNUNET_asprintf (&dirname,
673 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
674 current_pd->project_dirname);
676 case GNUNET_OS_IPK_DATADIR:
677 GNUNET_asprintf (&dirname,
678 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
679 current_pd->project_dirname);
681 case GNUNET_OS_IPK_LOCALEDIR:
682 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR);
684 case GNUNET_OS_IPK_ICONDIR:
685 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR);
687 case GNUNET_OS_IPK_DOCDIR:
688 GNUNET_asprintf (&dirname,
689 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
690 current_pd->project_dirname);
692 case GNUNET_OS_IPK_LIBEXECDIR:
695 GNUNET_asprintf (&dirname,
696 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
697 current_pd->project_dirname);
698 GNUNET_asprintf (&tmp,
701 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
702 (NULL != multiarch) ? multiarch : "",
705 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
707 GNUNET_free (execpath);
708 GNUNET_free (dirname);
714 if (4 == sizeof (void *))
716 GNUNET_asprintf (&dirname,
717 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
718 current_pd->project_dirname);
719 GNUNET_asprintf (&tmp,
724 if (8 == sizeof (void *))
726 GNUNET_asprintf (&dirname,
727 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
728 current_pd->project_dirname);
729 GNUNET_asprintf (&tmp,
734 if ( (NULL != tmp) &&
736 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
738 GNUNET_free (execpath);
739 GNUNET_free_non_null (dirname);
743 GNUNET_free_non_null (dirname);
745 GNUNET_asprintf (&dirname,
746 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
747 current_pd->project_dirname);
750 GNUNET_free (execpath);
753 GNUNET_asprintf (&tmp,
757 GNUNET_free (dirname);
758 GNUNET_free (execpath);
764 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
765 * binary, try to prefix it with the libexec/-directory to get the
768 * @param progname name of the binary
769 * @return full path to the binary, if possible, otherwise copy of 'progname'
772 GNUNET_OS_get_libexec_binary_path (const char *progname)
778 if ( (DIR_SEPARATOR == progname[0]) ||
780 GNUNET_STRINGS_path_is_absolute (progname,
783 return GNUNET_strdup (progname);
787 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
788 if (NULL == libexecdir)
789 return GNUNET_strdup (progname);
790 GNUNET_asprintf (&binary,
800 * Check whether an executable exists and possibly if the suid bit is
801 * set on the file. Attempts to find the file using the current PATH
802 * environment variable as a search path.
804 * @param binary the name of the file to check.
805 * W32: must not have an .exe suffix.
806 * @param check_suid input true if the binary should be checked for SUID (*nix)
807 * W32: checks if the program has sufficient privileges by executing this
808 * binary with the -d flag. -d omits a programs main loop and only
809 * executes all privileged operations in an binary.
810 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
811 * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
812 * #GNUNET_NO if not SUID (but binary exists),
813 * #GNUNET_SYSERR on error (no such binary or not executable)
816 GNUNET_OS_check_helper_binary (const char *binary,
826 GNUNET_asprintf (&binaryexe,
830 GNUNET_STRINGS_path_is_absolute (binaryexe,
833 (0 == strncmp (binary, "./", 2)) )
834 p = GNUNET_strdup (binaryexe);
837 p = get_path_from_PATH (binaryexe);
840 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
845 GNUNET_free (binaryexe);
848 GNUNET_STRINGS_path_is_absolute (binary,
852 (0 == strncmp (binary, "./", 2)) )
854 p = GNUNET_strdup (binary);
858 p = get_path_from_PATH (binary);
861 GNUNET_asprintf (&pf,
872 LOG (GNUNET_ERROR_TYPE_INFO,
873 _("Could not find binary `%s' in PATH!\n"),
875 return GNUNET_SYSERR;
880 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
884 return GNUNET_SYSERR;
889 /* as we run as root, we don't insist on SUID */
897 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
901 return GNUNET_SYSERR;
906 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
907 (0 == statbuf.st_uid) )
912 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
913 _("Binary `%s' exists, but is not SUID\n"),
915 /* binary exists, but not SUID */
918 char parameters[512];
919 PROCESS_INFORMATION proc;
922 GNUNET_snprintf (parameters,
925 memset (&start, 0, sizeof (start));
926 start.cb = sizeof (start);
927 memset (&proc, 0, sizeof (proc));
930 // Start the child process.
931 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
932 parameters, // execute dryrun/priviliege checking mode
933 NULL, // Process handle not inheritable
934 NULL, // Thread handle not inheritable
935 FALSE, // Set handle inheritance to FALSE
936 CREATE_DEFAULT_ERROR_MODE, // No creation flags
937 NULL, // Use parent's environment block
938 NULL, // Use parent's starting directory
939 &start, // Pointer to STARTUPINFO structure
940 &proc ) // Pointer to PROCESS_INFORMATION structure
943 LOG (GNUNET_ERROR_TYPE_ERROR,
944 _("CreateProcess failed for binary %s (%d).\n"),
946 return GNUNET_SYSERR;
949 // Wait until child process exits.
950 WaitForSingleObject( proc.hProcess, INFINITE );
952 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
953 LOG (GNUNET_ERROR_TYPE_ERROR,
954 _("GetExitCodeProcess failed for binary %s (%d).\n"),
956 return GNUNET_SYSERR;
958 // Close process and thread handles.
959 CloseHandle( proc.hProcess );
960 CloseHandle( proc.hThread );
971 /* end of os_installation.c */