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",
64 * Which project data do we currently use for installation
65 * path detection? Never NULL.
67 static const struct GNUNET_OS_ProjectData *current_pd = &default_pd;
70 * Return default project data used by 'libgnunetutil' for GNUnet.
72 const struct GNUNET_OS_ProjectData *
73 GNUNET_OS_project_data_default (void)
80 * Setup OS subsystem with project data.
82 * @param pd project data used to determine paths
85 GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd)
87 GNUNET_assert (NULL != pd);
95 * Try to determine path by reading /proc/PID/exe
97 * @return NULL on error
100 get_path_from_proc_maps ()
108 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
109 if (NULL == (f = FOPEN (fn, "r")))
111 while (NULL != fgets (line, sizeof (line), f))
114 SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s", dir)) &&
115 (NULL != (lgu = strstr (dir,
116 current_pd->libname))))
120 return GNUNET_strdup (dir);
129 * Try to determine path by reading /proc/PID/exe
131 * @return NULL on error
134 get_path_from_proc_exe ()
141 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ());
142 size = readlink (fn, lnk, sizeof (lnk) - 1);
145 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
148 GNUNET_assert (size < sizeof (lnk));
150 while ((lnk[size] != '/') && (size > 0))
152 GNUNET_asprintf (&lep,
154 current_pd->project_dirname);
155 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
156 if ( (size > strlen (lep)) &&
158 &lnk[size - strlen (lep)])) )
159 size -= strlen (lep) - 1;
161 if ((size < 4) || (lnk[size - 4] != '/'))
163 /* not installed in "/bin/" -- binary path probably useless */
167 return GNUNET_strdup (lnk);
173 static HINSTANCE dll_instance;
177 * GNUNET_util_cl_init() in common_logging.c is preferred.
178 * This function is only for thread-local storage (not used in GNUnet)
179 * and hInstance saving.
182 DllMain (HINSTANCE hinstDLL,
188 case DLL_PROCESS_ATTACH:
189 dll_instance = hinstDLL;
191 case DLL_THREAD_ATTACH:
193 case DLL_THREAD_DETACH:
195 case DLL_PROCESS_DETACH:
203 * Try to determine path with win32-specific function
205 * @return NULL on error
208 get_path_from_module_filename ()
210 size_t pathlen = 512;
213 wchar_t *modulepath = NULL;
216 size_t u8_string_length;
218 /* This braindead function won't tell us how much space it needs, so
219 * we start at 1024 and double the space up if it doesn't fit, until
220 * it fits, or we exceed the threshold.
224 pathlen = pathlen * 2;
225 modulepath = GNUNET_realloc (modulepath,
226 pathlen * sizeof (wchar_t));
228 real_pathlen = GetModuleFileNameW (dll_instance,
230 pathlen * sizeof (wchar_t));
231 } while (real_pathlen >= pathlen && pathlen < 16*1024);
232 if (real_pathlen >= pathlen)
235 modulepath[real_pathlen] = '\0';
237 idx = modulepath + real_pathlen;
238 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
242 /* Now modulepath holds full path to the directory where libgnunetutil is.
243 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
245 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
247 /* At least one directory component (i.e. we're not in a root directory) */
248 wchar_t *dirname = idx;
249 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
252 if (dirname > modulepath)
255 /* Now modulepath holds full path to the parent directory of the directory
256 * where libgnunetutil is.
257 * dirname holds the name of the directory where libgnunetutil is.
259 if (wcsicmp (dirname, L"bin") == 0)
265 /* Roll back our changes to modulepath */
272 /* modulepath is GNUNET_PREFIX */
273 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
274 if (NULL == u8_string)
277 upath = GNUNET_malloc (u8_string_length + 1);
278 memcpy (upath, u8_string, u8_string_length);
279 upath[u8_string_length] = '\0';
282 GNUNET_free (modulepath);
291 * Signature of the '_NSGetExecutablePath" function.
293 * @param buf where to write the path
294 * @param number of bytes available in @a buf
295 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
298 (*MyNSGetExecutablePathProto) (char *buf,
303 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
305 * @return NULL on error
308 get_path_from_NSGetExecutablePath ()
310 static char zero = '\0';
313 MyNSGetExecutablePathProto func;
317 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
321 /* get the path len, including the trailing \0 */
322 (void) func (path, &len);
325 path = GNUNET_malloc (len);
326 if (0 != func (path, &len))
332 while ((path[len] != '/') && (len > 0))
340 * Try to obtain the path of our executable using '_dyld_image' API.
342 * @return NULL on error
345 get_path_from_dyld_image ()
353 c = _dyld_image_count ();
354 for (i = 0; i < c; i++)
356 if (((const void *) _dyld_get_image_header (i)) !=
357 ((const void *) &_mh_dylib_header) )
359 path = _dyld_get_image_name (i);
360 if ( (NULL == path) || (0 == strlen (path)) )
362 p = GNUNET_strdup (path);
364 while ((s > p) && ('/' != *s))
376 * Return the actual path to a file found in the current
377 * PATH environment variable.
379 * @param binary the name of the file to find
380 * @return path to binary, NULL if not found
383 get_path_from_PATH (const char *binary)
391 if (NULL == (p = getenv ("PATH")))
394 /* On W32 look in CWD first. */
395 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
397 path = GNUNET_strdup (p); /* because we write on it */
399 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
401 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
404 sprintf (buf, "%s/%s", pos, binary);
405 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
407 pos = GNUNET_strdup (pos);
414 sprintf (buf, "%s/%s", pos, binary);
415 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
417 pos = GNUNET_strdup (pos);
429 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
432 * @return NULL on error (environment variable not set)
435 get_path_from_GNUNET_PREFIX ()
439 if ( (NULL != current_pd->env_varname) &&
440 (NULL != (p = getenv (current_pd->env_varname))) )
441 return GNUNET_strdup (p);
442 if ( (NULL != current_pd->env_varname_alt) &&
443 (NULL != (p = getenv (current_pd->env_varname_alt))) )
444 return GNUNET_strdup (p);
450 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
453 * @return a pointer to the executable path, or NULL on error
456 os_get_gnunet_path ()
460 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
463 if (NULL != (ret = get_path_from_proc_maps ()))
465 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
466 if ( (NULL != current_pd->binary_name) &&
467 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
469 if (NULL != (ret = get_path_from_proc_exe ()))
473 if (NULL != (ret = get_path_from_module_filename ()))
477 if (NULL != (ret = get_path_from_dyld_image ()))
479 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
482 if ( (NULL != current_pd->binary_name) &&
483 (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
485 /* other attempts here */
486 LOG (GNUNET_ERROR_TYPE_ERROR,
487 _("Could not determine installation path for %s. Set `%s' environment variable.\n"),
488 current_pd->project_dirname,
489 current_pd->env_varname);
495 * @brief get the path to current app's bin/
496 * @return a pointer to the executable path, or NULL on error
504 if (NULL != (ret = get_path_from_proc_exe ()))
508 if (NULL != (ret = get_path_from_module_filename ()))
512 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
515 /* other attempts here */
521 * @brief get the path to a specific GNUnet installation directory or,
522 * with #GNUNET_OS_IPK_SELF_PREFIX, the current running apps installation directory
523 * @return a pointer to the dir path (to be freed by the caller)
526 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
530 char *execpath = NULL;
536 /* if wanted, try to get the current app's bin/ */
537 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
538 execpath = os_get_exec_path ();
540 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
541 * guess for the current app */
542 if (NULL == execpath)
543 execpath = os_get_gnunet_path ();
545 if (NULL == execpath)
548 n = strlen (execpath);
551 /* should never happen, but better safe than sorry */
552 GNUNET_free (execpath);
555 /* remove filename itself */
556 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
557 execpath[--n] = '\0';
561 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
562 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
564 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
565 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
567 /* strip '/lib32' or '/lib64' */
568 execpath[n - 6] = '\0';
575 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
576 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
578 /* strip '/bin' or '/lib' */
579 execpath[n - 4] = '\0';
583 if (NULL != (libdir = strstr (execpath, "/lib/")))
585 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
586 here we need to re-add 'multiarch' to lib and libexec paths later! */
587 multiarch = &libdir[5];
588 if (NULL == strchr (multiarch, '/'))
589 libdir[0] = '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
591 multiarch = NULL; /* maybe not, multiarch still has a '/', which is not OK */
593 /* in case this was a directory named foo-bin, remove "foo-" */
594 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
595 execpath[--n] = '\0';
598 case GNUNET_OS_IPK_PREFIX:
599 case GNUNET_OS_IPK_SELF_PREFIX:
600 dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
602 case GNUNET_OS_IPK_BINDIR:
603 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
605 case GNUNET_OS_IPK_LIBDIR:
608 GNUNET_asprintf (&tmp,
611 DIR_SEPARATOR_STR "lib",
612 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
613 (NULL != multiarch) ? multiarch : "",
615 current_pd->project_dirname,
618 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
620 GNUNET_free (execpath);
626 if (4 == sizeof (void *))
628 GNUNET_asprintf (&dirname,
629 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
630 current_pd->project_dirname);
631 GNUNET_asprintf (&tmp,
636 if (8 == sizeof (void *))
638 GNUNET_asprintf (&dirname,
639 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
640 current_pd->project_dirname);
641 GNUNET_asprintf (&tmp,
647 if ( (NULL != tmp) &&
649 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
651 GNUNET_free (execpath);
652 GNUNET_free_non_null (dirname);
656 GNUNET_free_non_null (dirname);
658 GNUNET_asprintf (&dirname,
659 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
660 current_pd->project_dirname);
662 case GNUNET_OS_IPK_DATADIR:
663 GNUNET_asprintf (&dirname,
664 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
665 current_pd->project_dirname);
667 case GNUNET_OS_IPK_LOCALEDIR:
668 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR);
670 case GNUNET_OS_IPK_ICONDIR:
671 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR);
673 case GNUNET_OS_IPK_DOCDIR:
674 GNUNET_asprintf (&dirname,
675 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
676 current_pd->project_dirname);
678 case GNUNET_OS_IPK_LIBEXECDIR:
681 GNUNET_asprintf (&dirname,
682 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
683 current_pd->project_dirname);
684 GNUNET_asprintf (&tmp,
687 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
688 (NULL != multiarch) ? multiarch : "",
691 GNUNET_DISK_directory_test (tmp, GNUNET_YES))
693 GNUNET_free (execpath);
694 GNUNET_free (dirname);
700 if (4 == sizeof (void *))
702 GNUNET_asprintf (&dirname,
703 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
704 current_pd->project_dirname);
705 GNUNET_asprintf (&tmp,
710 if (8 == sizeof (void *))
712 GNUNET_asprintf (&dirname,
713 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
714 current_pd->project_dirname);
715 GNUNET_asprintf (&tmp,
720 if ( (NULL != tmp) &&
722 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
724 GNUNET_free (execpath);
725 GNUNET_free_non_null (dirname);
729 GNUNET_free_non_null (dirname);
731 GNUNET_asprintf (&dirname,
732 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
733 current_pd->project_dirname);
736 GNUNET_free (execpath);
739 GNUNET_asprintf (&tmp,
743 GNUNET_free (execpath);
749 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
750 * binary, try to prefix it with the libexec/-directory to get the
753 * @param progname name of the binary
754 * @return full path to the binary, if possible, otherwise copy of 'progname'
757 GNUNET_OS_get_libexec_binary_path (const char *progname)
763 if ( (DIR_SEPARATOR == progname[0]) ||
765 GNUNET_STRINGS_path_is_absolute (progname,
768 return GNUNET_strdup (progname);
772 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
773 if (NULL == libexecdir)
774 return GNUNET_strdup (progname);
775 GNUNET_asprintf (&binary,
785 * Check whether an executable exists and possibly if the suid bit is
786 * set on the file. Attempts to find the file using the current PATH
787 * environment variable as a search path.
789 * @param binary the name of the file to check.
790 * W32: must not have an .exe suffix.
791 * @param check_suid input true if the binary should be checked for SUID (*nix)
792 * W32: checks if the program has sufficient privileges by executing this
793 * binary with the -d flag. -d omits a programs main loop and only
794 * executes all privileged operations in an binary.
795 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
796 * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
797 * #GNUNET_NO if not SUID (but binary exists),
798 * #GNUNET_SYSERR on error (no such binary or not executable)
801 GNUNET_OS_check_helper_binary (const char *binary,
811 GNUNET_asprintf (&binaryexe, "%s.exe", binary);
812 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO,
814 (0 == strncmp (binary, "./", 2)) )
815 p = GNUNET_strdup (binaryexe);
818 p = get_path_from_PATH (binaryexe);
821 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
826 GNUNET_free (binaryexe);
828 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO,
830 (0 == strncmp (binary, "./", 2)) )
831 p = GNUNET_strdup (binary);
834 p = get_path_from_PATH (binary);
837 GNUNET_asprintf (&pf, "%s/%s", p, binary);
845 LOG (GNUNET_ERROR_TYPE_INFO,
846 _("Could not find binary `%s' in PATH!\n"),
848 return GNUNET_SYSERR;
850 if (0 != ACCESS (p, X_OK))
852 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
854 return GNUNET_SYSERR;
859 /* as we run as root, we don't insist on SUID */
864 if (0 != STAT (p, &statbuf))
866 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
868 return GNUNET_SYSERR;
872 if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
877 /* binary exists, but not SUID */
880 char parameters[512];
881 PROCESS_INFORMATION proc;
884 GNUNET_snprintf (parameters,
887 memset (&start, 0, sizeof (start));
888 start.cb = sizeof (start);
889 memset (&proc, 0, sizeof (proc));
892 // Start the child process.
893 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
894 parameters, // execute dryrun/priviliege checking mode
895 NULL, // Process handle not inheritable
896 NULL, // Thread handle not inheritable
897 FALSE, // Set handle inheritance to FALSE
898 CREATE_DEFAULT_ERROR_MODE, // No creation flags
899 NULL, // Use parent's environment block
900 NULL, // Use parent's starting directory
901 &start, // Pointer to STARTUPINFO structure
902 &proc ) // Pointer to PROCESS_INFORMATION structure
905 LOG (GNUNET_ERROR_TYPE_ERROR,
906 _("CreateProcess failed for binary %s (%d).\n"),
908 return GNUNET_SYSERR;
911 // Wait until child process exits.
912 WaitForSingleObject( proc.hProcess, INFINITE );
914 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
915 LOG (GNUNET_ERROR_TYPE_ERROR,
916 _("GetExitCodeProcess failed for binary %s (%d).\n"),
918 return GNUNET_SYSERR;
920 // Close process and thread handles.
921 CloseHandle( proc.hProcess );
922 CloseHandle( proc.hThread );
933 /* end of os_installation.c */