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_common.h"
34 #include "gnunet_configuration_lib.h"
35 #include "gnunet_disk_lib.h"
36 #include "gnunet_os_lib.h"
37 #include "gnunet_strings_lib.h"
39 #include <mach-o/ldsyms.h>
40 #include <mach-o/dyld.h>
46 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
48 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
52 * Try to determine path by reading /proc/PID/exe
54 * @return NULL on error
57 get_path_from_proc_maps ()
65 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
66 if (NULL == (f = FOPEN (fn, "r")))
68 while (NULL != fgets (line, sizeof (line), f))
71 SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2u:%*2u %*u%*[ ]%1023s", dir)) &&
72 (NULL != (lgu = strstr (dir, "libgnunetutil"))))
76 return GNUNET_strdup (dir);
85 * Try to determine path by reading /proc/PID/exe
87 * @return NULL on error
90 get_path_from_proc_exe ()
96 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ());
97 size = readlink (fn, lnk, sizeof (lnk) - 1);
100 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
103 GNUNET_assert (size < sizeof (lnk));
105 while ((lnk[size] != '/') && (size > 0))
107 /* test for being in lib/gnunet/libexec/ */
108 if ( (size > strlen ("/gnunet/libexec/")) &&
109 (0 == strcmp ("/gnunet/libexec/",
110 &lnk[size - strlen ("/gnunet/libexec/")])) )
111 size -= strlen ("gnunet/libexec/");
112 if ((size < 4) || (lnk[size - 4] != '/'))
114 /* not installed in "/bin/" -- binary path probably useless */
118 return GNUNET_strdup (lnk);
124 static HINSTANCE dll_instance;
127 /* GNUNET_util_cl_init() in common_logging.c is preferred.
128 * This function is only for thread-local storage (not used in GNUnet)
129 * and hInstance saving.
132 DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
136 case DLL_PROCESS_ATTACH:
137 dll_instance = hinstDLL;
139 case DLL_THREAD_ATTACH:
141 case DLL_THREAD_DETACH:
143 case DLL_PROCESS_DETACH:
151 * Try to determine path with win32-specific function
153 * @return NULL on error
156 get_path_from_module_filename ()
158 size_t pathlen = 512;
161 wchar_t *modulepath = NULL;
164 size_t u8_string_length;
166 /* This braindead function won't tell us how much space it needs, so
167 * we start at 1024 and double the space up if it doesn't fit, until
168 * it fits, or we exceed the threshold.
172 pathlen = pathlen * 2;
173 modulepath = GNUNET_realloc (modulepath, pathlen * sizeof (wchar_t));
175 real_pathlen = GetModuleFileNameW (dll_instance, modulepath, pathlen * sizeof (wchar_t));
176 } while (real_pathlen >= pathlen && pathlen < 16*1024);
177 if (real_pathlen >= pathlen)
180 modulepath[real_pathlen] = '\0';
182 idx = modulepath + real_pathlen;
183 while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
187 /* Now modulepath holds full path to the directory where libgnunetutil is.
188 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
190 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
192 /* At least one directory component (i.e. we're not in a root directory) */
193 wchar_t *dirname = idx;
194 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
197 if (dirname > modulepath)
200 /* Now modulepath holds full path to the parent directory of the directory
201 * where libgnunetutil is.
202 * dirname holds the name of the directory where libgnunetutil is.
204 if (wcsicmp (dirname, L"bin") == 0)
210 /* Roll back our changes to modulepath */
217 /* modulepath is GNUNET_PREFIX */
218 u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
219 if (NULL == u8_string)
222 upath = GNUNET_malloc (u8_string_length + 1);
223 memcpy (upath, u8_string, u8_string_length);
224 upath[u8_string_length] = '\0';
227 GNUNET_free (modulepath);
235 * Signature of the '_NSGetExecutablePath" function.
237 * @param buf where to write the path
238 * @param number of bytes available in 'buf'
239 * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
241 typedef int (*MyNSGetExecutablePathProto) (char *buf, size_t * bufsize);
245 * Try to obtain the path of our executable using '_NSGetExecutablePath'.
247 * @return NULL on error
250 get_path_from_NSGetExecutablePath ()
252 static char zero = '\0';
255 MyNSGetExecutablePathProto func;
259 (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
263 /* get the path len, including the trailing \0 */
264 (void) func (path, &len);
267 path = GNUNET_malloc (len);
268 if (0 != func (path, &len))
274 while ((path[len] != '/') && (len > 0))
282 * Try to obtain the path of our executable using '_dyld_image' API.
284 * @return NULL on error
287 get_path_from_dyld_image ()
295 c = _dyld_image_count ();
296 for (i = 0; i < c; i++)
298 if (_dyld_get_image_header (i) != &_mh_dylib_header)
300 path = _dyld_get_image_name (i);
301 if ( (NULL == path) || (0 == strlen (path)) )
303 p = GNUNET_strdup (path);
305 while ((s > p) && ('/' != *s))
317 * Return the actual path to a file found in the current
318 * PATH environment variable.
320 * @param binary the name of the file to find
321 * @return path to binary, NULL if not found
324 get_path_from_PATH (const char *binary)
332 if (NULL == (p = getenv ("PATH")))
335 /* On W32 look in CWD first. */
336 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
338 path = GNUNET_strdup (p); /* because we write on it */
340 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
342 while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
345 sprintf (buf, "%s/%s", pos, binary);
346 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
348 pos = GNUNET_strdup (pos);
355 sprintf (buf, "%s/%s", pos, binary);
356 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
358 pos = GNUNET_strdup (pos);
370 * Try to obtain the installation path using the "GNUNET_PREFIX" environment
373 * @return NULL on error (environment variable not set)
376 get_path_from_GNUNET_PREFIX ()
380 if (NULL != (p = getenv ("GNUNET_PREFIX")))
381 return GNUNET_strdup (p);
387 * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
390 * @return a pointer to the executable path, or NULL on error
393 os_get_gnunet_path ()
397 if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
400 if (NULL != (ret = get_path_from_proc_maps ()))
402 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
403 if (NULL != (ret = get_path_from_PATH ("gnunet-arm")))
405 if (NULL != (ret = get_path_from_proc_exe ()))
409 if (NULL != (ret = get_path_from_module_filename ()))
413 if (NULL != (ret = get_path_from_dyld_image ()))
415 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
418 if (NULL != (ret = get_path_from_PATH ("gnunet-arm")))
420 /* other attempts here */
421 LOG (GNUNET_ERROR_TYPE_ERROR,
423 ("Could not determine installation path for %s. Set `%s' environment variable.\n"),
424 "GNUnet", "GNUNET_PREFIX");
430 * @brief get the path to current app's bin/
433 * @return a pointer to the executable path, or NULL on error
441 if (NULL != (ret = get_path_from_proc_exe ()))
445 if (NULL != (ret = get_path_from_module_filename ()))
449 if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
452 /* other attempts here */
458 * @brief get the path to a specific GNUnet installation directory or,
459 * with GNUNET_IPK_SELF_PREFIX, the current running apps installation directory
461 * @return a pointer to the dir path (to be freed by the caller)
464 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
468 char *execpath = NULL;
472 /* if wanted, try to get the current app's bin/ */
473 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
474 execpath = os_get_exec_path ();
476 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
477 * guess for the current app */
478 if (NULL == execpath)
479 execpath = os_get_gnunet_path ();
481 if (NULL == execpath)
484 n = strlen (execpath);
487 /* should never happen, but better safe than sorry */
488 GNUNET_free (execpath);
491 /* remove filename itself */
492 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
493 execpath[--n] = '\0';
497 ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
498 (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
500 if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
501 (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
503 /* strip '/lib32' or '/lib64' */
504 execpath[n - 6] = '\0';
511 ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
512 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
514 /* strip '/bin' or '/lib' */
515 execpath[n - 4] = '\0';
518 /* in case this was a directory named foo-bin, remove "foo-" */
519 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
520 execpath[--n] = '\0';
523 case GNUNET_OS_IPK_PREFIX:
524 case GNUNET_OS_IPK_SELF_PREFIX:
525 dirname = DIR_SEPARATOR_STR;
527 case GNUNET_OS_IPK_BINDIR:
528 dirname = DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR;
530 case GNUNET_OS_IPK_LIBDIR:
534 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
535 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
536 sprintf (tmp, "%s%s", execpath, dirname);
538 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
539 (4 == sizeof (void *)) )
543 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
544 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
545 sprintf (tmp, "%s%s", execpath, dirname);
548 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
549 (8 == sizeof (void *)) )
552 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
557 dirname = DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
559 case GNUNET_OS_IPK_DATADIR:
561 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
563 case GNUNET_OS_IPK_LOCALEDIR:
565 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR;
567 case GNUNET_OS_IPK_ICONDIR:
569 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR;
571 case GNUNET_OS_IPK_DOCDIR:
573 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR \
574 "gnunet" DIR_SEPARATOR_STR;
576 case GNUNET_OS_IPK_LIBEXECDIR:
580 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
581 "libexec" DIR_SEPARATOR_STR;
582 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
583 sprintf (tmp, "%s%s", execpath, dirname);
585 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
586 (4 == sizeof (void *)) )
590 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
591 "libexec" DIR_SEPARATOR_STR;
592 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
593 sprintf (tmp, "%s%s", execpath, dirname);
596 GNUNET_DISK_directory_test (tmp, GNUNET_YES)) &&
597 (8 == sizeof (void *)) )
600 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
601 "libexec" DIR_SEPARATOR_STR;
607 DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR \
608 "libexec" DIR_SEPARATOR_STR;
611 GNUNET_free (execpath);
614 tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
615 sprintf (tmp, "%s%s", execpath, dirname);
616 GNUNET_free (execpath);
622 * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
623 * binary, try to prefix it with the libexec/-directory to get the
626 * @param progname name of the binary
627 * @return full path to the binary, if possible, otherwise copy of 'progname'
630 GNUNET_OS_get_libexec_binary_path (const char *progname)
635 if (DIR_SEPARATOR == progname[0])
636 return GNUNET_strdup (progname);
637 if (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (progname, GNUNET_NO, NULL, NULL))
638 return GNUNET_strdup (progname);
639 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
640 if (NULL == libexecdir)
641 return GNUNET_strdup (progname);
642 GNUNET_asprintf (&binary,
646 GNUNET_free (libexecdir);
652 * Check whether an executable exists and possibly
653 * if the suid bit is set on the file.
654 * Attempts to find the file using the current
655 * PATH environment variable as a search path.
657 * @param binary the name of the file to check.
658 * W32: must not have an .exe suffix.
659 * @param check_suid input true if the binary should be checked for SUID (*nix)
660 * W32: checks if the program has sufficient privileges by executing this
661 * binary with the -d flag. -d omits a programs main loop and only
662 * executes all privileged operations in an binary.
663 * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
664 * @return GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
665 * GNUNET_NO if not SUID (but binary exists),
666 * GNUNET_SYSERR on error (no such binary or not executable)
669 GNUNET_OS_check_helper_binary (const char *binary, int check_suid, const char *params)
677 GNUNET_asprintf (&binaryexe, "%s.exe", binary);
678 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO,
680 (0 == strncmp (binary, "./", 2)) )
681 p = GNUNET_strdup (binaryexe);
684 p = get_path_from_PATH (binaryexe);
687 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
692 GNUNET_free (binaryexe);
694 if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO,
696 (0 == strncmp (binary, "./", 2)) )
697 p = GNUNET_strdup (binary);
700 p = get_path_from_PATH (binary);
703 GNUNET_asprintf (&pf, "%s/%s", p, binary);
711 LOG (GNUNET_ERROR_TYPE_INFO, _("Could not find binary `%s' in PATH!\n"),
713 return GNUNET_SYSERR;
715 if (0 != ACCESS (p, X_OK))
717 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
719 return GNUNET_SYSERR;
724 /* as we run as root, we don't insist on SUID */
729 if (0 != STAT (p, &statbuf))
731 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
733 return GNUNET_SYSERR;
737 if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
742 /* binary exists, but not SUID */
745 char parameters[512];
746 PROCESS_INFORMATION proc;
749 GNUNET_snprintf (parameters,
752 memset (&start, 0, sizeof (start));
753 start.cb = sizeof (start);
754 memset (&proc, 0, sizeof (proc));
757 // Start the child process.
758 if ( ! (CreateProcess( p, // current windows (2k3 and up can handle / instead of \ in paths))
759 parameters, // execute dryrun/priviliege checking mode
760 NULL, // Process handle not inheritable
761 NULL, // Thread handle not inheritable
762 FALSE, // Set handle inheritance to FALSE
763 CREATE_DEFAULT_ERROR_MODE, // No creation flags
764 NULL, // Use parent's environment block
765 NULL, // Use parent's starting directory
766 &start, // Pointer to STARTUPINFO structure
767 &proc ) // Pointer to PROCESS_INFORMATION structure
770 LOG (GNUNET_ERROR_TYPE_ERROR,
771 _("CreateProcess failed for binary %s (%d).\n"),
773 return GNUNET_SYSERR;
776 // Wait until child process exits.
777 WaitForSingleObject( proc.hProcess, INFINITE );
779 if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
780 LOG (GNUNET_ERROR_TYPE_ERROR,
781 _("GetExitCodeProcess failed for binary %s (%d).\n"),
783 return GNUNET_SYSERR;
785 // Close process and thread handles.
786 CloseHandle( proc.hProcess );
787 CloseHandle( proc.hThread );
798 /* end of os_installation.c */