2 This file is part of GNUnet.
3 (C) 2006 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file src/util/os_installation.c
23 * @brief get paths used by the program
30 #include <unistr.h> /* for u16_to_u8 */
33 #include "gnunet_util_lib.h"
35 #include <mach-o/ldsyms.h>
36 #include <mach-o/dyld.h>
42 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
49 * Try to determine path by reading /proc/PID/exe
51 * @return NULL on error
54 get_path_from_proc_maps ()
62 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
63 if (NULL == (f = FOPEN (fn, "r")))
65 while (NULL != fgets (line, sizeof (line), f))
68 SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2u:%*2u %*u%*[ ]%1023s", dir)) &&
69 (NULL != (lgu = strstr (dir, "libgnunetutil"))))
73 return GNUNET_strdup (dir);
82 * Try to determine path by reading /proc/PID/exe
84 * @return NULL on error
87 get_path_from_proc_exe ()
93 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ());
94 size = readlink (fn, lnk, sizeof (lnk) - 1);
97 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
100 GNUNET_assert (size < sizeof (lnk));
102 while ((lnk[size] != '/') && (size > 0))
104 /* test for being in lib/gnunet/libexec/ */
105 if ( (size > strlen ("/gnunet/libexec/")) &&
106 (0 == strcmp ("/gnunet/libexec/",
107 &lnk[size - strlen ("/gnunet/libexec/")])) )
108 size -= strlen ("gnunet/libexec/");
109 if ((size < 4) || (lnk[size - 4] != '/'))
111 /* not installed in "/bin/" -- binary path probably useless */
115 return GNUNET_strdup (lnk);
121 static HINSTANCE dll_instance;
125 * GNUNET_util_cl_init() in common_logging.c is preferred.
126 * This function is only for thread-local storage (not used in GNUnet)
127 * and hInstance saving.
130 DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
134 case DLL_PROCESS_ATTACH:
135 dll_instance = hinstDLL;
137 case DLL_THREAD_ATTACH:
139 case DLL_THREAD_DETACH:
141 case DLL_PROCESS_DETACH:
149 * Try to determine path with win32-specific function
151 * @return NULL on error
154 get_path_from_module_filename ()
156 size_t pathlen = 512;
159 wchar_t *modulepath = NULL;
162 size_t u8_string_length;
164 /* This braindead function won't tell us how much space it needs, so
165 * we start at 1024 and double the space up if it doesn't fit, until
166 * it fits, or we exceed the threshold.
170 pathlen = pathlen * 2;
171 modulepath = GNUNET_realloc (modulepath, pathlen * sizeof (wchar_t));
173 real_pathlen = GetModuleFileNameW (dll_instance, modulepath, pathlen * sizeof (wchar_t));
174 } while (real_pathlen >= pathlen && pathlen < 16*1024);
175 if (real_pathlen >= pathlen)
178 modulepath[real_pathlen] = '\0';
180 idx = modulepath + real_pathlen;
181 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
185 /* Now modulepath holds full path to the directory where libgnunetutil is.
186 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
188 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
190 /* At least one directory component (i.e. we're not in a root directory) */
191 wchar_t *dirname = idx;
192 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
195 if (dirname > modulepath)
198 /* Now modulepath holds full path to the parent directory of the directory
199 * where libgnunetutil is.
200 * dirname holds the name of the directory where libgnunetutil is.
202 if (wcsicmp (dirname, L"bin") == 0)
208 /* Roll back our changes to modulepath */
215 /* modulepath is GNUNET_PREFIX */
216 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
217 if (NULL == u8_string)
220 upath = GNUNET_malloc (u8_string_length + 1);
221 memcpy (upath, u8_string, u8_string_length);
222 upath[u8_string_length] = '\0';
225 GNUNET_free (modulepath);
234 * Signature of the '_NSGetExecutablePath" function.
236 * @param buf where to write the path
237 * @param number of bytes available in 'buf'
238 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
240 typedef int (*MyNSGetExecutablePathProto) (char *buf, size_t * bufsize);
244 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
246 * @return NULL on error
249 get_path_from_NSGetExecutablePath ()
251 static char zero = '\0';
254 MyNSGetExecutablePathProto func;
258 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
262 /* get the path len, including the trailing \0 */
263 (void) func (path, &len);
266 path = GNUNET_malloc (len);
267 if (0 != func (path, &len))
273 while ((path[len] != '/') && (len > 0))
281 * Try to obtain the path of our executable using '_dyld_image' API.
283 * @return NULL on error
286 get_path_from_dyld_image ()
294 c = _dyld_image_count ();
295 for (i = 0; i < c; i++)
297 if (((const void *) _dyld_get_image_header (i)) != (const void *)&_mh_dylib_header)
299 path = _dyld_get_image_name (i);
300 if ( (NULL == path) || (0 == strlen (path)) )
302 p = GNUNET_strdup (path);
304 while ((s > p) && ('/' != *s))
316 * Return the actual path to a file found in the current
317 * PATH environment variable.
319 * @param binary the name of the file to find
320 * @return path to binary, NULL if not found
323 get_path_from_PATH (const char *binary)
331 if (NULL == (p = getenv ("PATH")))
334 /* On W32 look in CWD first. */
335 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
337 path = GNUNET_strdup (p); /* because we write on it */
339 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
341 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
344 sprintf (buf, "%s/%s", pos, binary);
345 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
347 pos = GNUNET_strdup (pos);
354 sprintf (buf, "%s/%s", pos, binary);
355 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
357 pos = GNUNET_strdup (pos);
369 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
372 * @return NULL on error (environment variable not set)
375 get_path_from_GNUNET_PREFIX ()
379 if (NULL != (p = getenv ("GNUNET_PREFIX")))
380 return GNUNET_strdup (p);
386 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
389 * @return a pointer to the executable path, or NULL on error
392 os_get_gnunet_path ()
396 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
399 if (NULL != (ret = get_path_from_proc_maps ()))
401 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
402 if (NULL != (ret = get_path_from_PATH ("gnunet-arm")))
404 if (NULL != (ret = get_path_from_proc_exe ()))
408 if (NULL != (ret = get_path_from_module_filename ()))
412 if (NULL != (ret = get_path_from_dyld_image ()))
414 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
417 if (NULL != (ret = get_path_from_PATH ("gnunet-arm")))
419 /* other attempts here */
420 LOG (GNUNET_ERROR_TYPE_ERROR,
421 _("Could not determine installation path for %s. Set `%s' environment variable.\n"),
422 "GNUnet", "GNUNET_PREFIX");
428 * @brief get the path to current app's bin/
431 * @return a pointer to the executable path, or NULL on error
439 if (NULL != (ret = get_path_from_proc_exe ()))
443 if (NULL != (ret = get_path_from_module_filename ()))
447 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
450 /* other attempts here */
456 * @brief get the path to a specific GNUnet installation directory or,
457 * with #GNUNET_IPK_SELF_PREFIX, the current running apps installation directory
459 * @return a pointer to the dir path (to be freed by the caller)
462 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
466 char *execpath = NULL;
470 /* if wanted, try to get the current app's bin/ */
471 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
472 execpath = os_get_exec_path ();
474 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
475 * guess for the current app */
476 if (NULL == execpath)
477 execpath = os_get_gnunet_path ();
479 if (NULL == execpath)
482 n = strlen (execpath);
485 /* should never happen, but better safe than sorry */
486 GNUNET_free (execpath);
489 /* remove filename itself */
490 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
491 execpath[--n] = '\0';
495 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
496 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
498 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
499 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
501 /* strip '/lib32' or '/lib64' */
502 execpath[n - 6] = '\0';
509 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
510 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
512 /* strip '/bin' or '/lib' */
513 execpath[n - 4] = '\0';
516 /* in case this was a directory named foo-bin, remove "foo-" */
517 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
518 execpath[--n] = '\0';
521 case GNUNET_OS_IPK_PREFIX:
522 case GNUNET_OS_IPK_SELF_PREFIX:
523 dirname = DIR_SEPARATOR_STR;
525 case GNUNET_OS_IPK_BINDIR:
526 dirname = DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR;
528 case GNUNET_OS_IPK_LIBDIR:
532 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
533 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
534 sprintf (tmp, "%s%s", execpath, dirname);
536 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
537 (4 == sizeof (void *)) )
541 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
542 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
543 sprintf (tmp, "%s%s", execpath, dirname);
546 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
547 (8 == sizeof (void *)) )
550 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
555 dirname = DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
557 case GNUNET_OS_IPK_DATADIR:
559 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
561 case GNUNET_OS_IPK_LOCALEDIR:
563 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR;
565 case GNUNET_OS_IPK_ICONDIR:
567 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR;
569 case GNUNET_OS_IPK_DOCDIR:
571 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR \
572 "gnunet" DIR_SEPARATOR_STR;
574 case GNUNET_OS_IPK_LIBEXECDIR:
578 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
579 "libexec" DIR_SEPARATOR_STR;
580 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
581 sprintf (tmp, "%s%s", execpath, dirname);
583 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
584 (4 == sizeof (void *)) )
588 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
589 "libexec" DIR_SEPARATOR_STR;
590 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
591 sprintf (tmp, "%s%s", execpath, dirname);
594 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
595 (8 == sizeof (void *)) )
598 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
599 "libexec" DIR_SEPARATOR_STR;
605 DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
606 "libexec" DIR_SEPARATOR_STR;
609 GNUNET_free (execpath);
612 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
613 sprintf (tmp, "%s%s", execpath, dirname);
614 GNUNET_free (execpath);
620 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
621 * binary, try to prefix it with the libexec/-directory to get the
624 * @param progname name of the binary
625 * @return full path to the binary, if possible, otherwise copy of 'progname'
628 GNUNET_OS_get_libexec_binary_path (const char *progname)
633 if (DIR_SEPARATOR == progname[0])
634 return GNUNET_strdup (progname);
635 if (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (progname, GNUNET_NO, NULL, NULL))
636 return GNUNET_strdup (progname);
637 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
638 if (NULL == libexecdir)
639 return GNUNET_strdup (progname);
640 GNUNET_asprintf (&binary,
644 GNUNET_free (libexecdir);
650 * Check whether an executable exists and possibly
651 * if the suid bit is set on the file.
652 * Attempts to find the file using the current
653 * PATH environment variable as a search path.
655 * @param binary the name of the file to check.
656 * W32: must not have an .exe suffix.
657 * @param check_suid input true if the binary should be checked for SUID (*nix)
658 * W32: checks if the program has sufficient privileges by executing this
659 * binary with the -d flag. -d omits a programs main loop and only
660 * executes all privileged operations in an binary.
661 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
662 * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
663 * #GNUNET_NO if not SUID (but binary exists),
664 * #GNUNET_SYSERR on error (no such binary or not executable)
667 GNUNET_OS_check_helper_binary (const char *binary, int check_suid, const char *params)
675 GNUNET_asprintf (&binaryexe, "%s.exe", binary);
676 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO,
678 (0 == strncmp (binary, "./", 2)) )
679 p = GNUNET_strdup (binaryexe);
682 p = get_path_from_PATH (binaryexe);
685 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
690 GNUNET_free (binaryexe);
692 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO,
694 (0 == strncmp (binary, "./", 2)) )
695 p = GNUNET_strdup (binary);
698 p = get_path_from_PATH (binary);
701 GNUNET_asprintf (&pf, "%s/%s", p, binary);
709 LOG (GNUNET_ERROR_TYPE_INFO,
710 _("Could not find binary `%s' in PATH!\n"),
712 return GNUNET_SYSERR;
714 if (0 != ACCESS (p, X_OK))
716 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
718 return GNUNET_SYSERR;
723 /* as we run as root, we don't insist on SUID */
728 if (0 != STAT (p, &statbuf))
730 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
732 return GNUNET_SYSERR;
736 if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
741 /* binary exists, but not SUID */
744 char parameters[512];
745 PROCESS_INFORMATION proc;
748 GNUNET_snprintf (parameters,
751 memset (&start, 0, sizeof (start));
752 start.cb = sizeof (start);
753 memset (&proc, 0, sizeof (proc));
756 // Start the child process.
757 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
758 parameters, // execute dryrun/priviliege checking mode
759 NULL, // Process handle not inheritable
760 NULL, // Thread handle not inheritable
761 FALSE, // Set handle inheritance to FALSE
762 CREATE_DEFAULT_ERROR_MODE, // No creation flags
763 NULL, // Use parent's environment block
764 NULL, // Use parent's starting directory
765 &start, // Pointer to STARTUPINFO structure
766 &proc ) // Pointer to PROCESS_INFORMATION structure
769 LOG (GNUNET_ERROR_TYPE_ERROR,
770 _("CreateProcess failed for binary %s (%d).\n"),
772 return GNUNET_SYSERR;
775 // Wait until child process exits.
776 WaitForSingleObject( proc.hProcess, INFINITE );
778 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
779 LOG (GNUNET_ERROR_TYPE_ERROR,
780 _("GetExitCodeProcess failed for binary %s (%d).\n"),
782 return GNUNET_SYSERR;
784 // Close process and thread handles.
785 CloseHandle( proc.hProcess );
786 CloseHandle( proc.hThread );
797 /* end of os_installation.c */