paragraph for gnunet devs that don't know how to use the web
[oweals/gnunet.git] / src / util / os_installation.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2006-2018 GNUnet e.V.
4
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.
9
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.
14     
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/>.
17 */
18
19 /**
20  * @file src/util/os_installation.c
21  * @brief get paths used by the program
22  * @author Milan
23  * @author Christian Fuchs
24  * @author Christian Grothoff
25  * @author Matthias Wachs
26  * @author Heikki Lindholm
27  * @author LRN
28  */
29 #include <sys/stat.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <unistr.h> /* for u16_to_u8 */
34
35 #include "platform.h"
36 #include "gnunet_util_lib.h"
37 #if DARWIN
38 #include <mach-o/ldsyms.h>
39 #include <mach-o/dyld.h>
40 #elif WINDOWS
41 #include <windows.h>
42 #endif
43
44
45 #define LOG(kind,...) GNUNET_log_from (kind, "util-os-installation", __VA_ARGS__)
46
47 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-os-installation", syscall, filename)
48
49
50 /**
51  * Default project data used for installation path detection
52  * for GNUnet (core).
53  */
54 static const struct GNUNET_OS_ProjectData default_pd = {
55   .libname = "libgnunetutil",
56   .project_dirname = "gnunet",
57   .binary_name = "gnunet-arm",
58   .env_varname = "GNUNET_PREFIX",
59   .base_config_varname = "GNUNET_BASE_CONFIG",
60   .bug_email = "gnunet-developers@gnu.org",
61   .homepage = "http://www.gnu.org/s/gnunet/",
62   .config_file = "gnunet.conf",
63   .user_config_file = "~/.config/gnunet.conf",
64 };
65
66 /**
67  * Which project data do we currently use for installation
68  * path detection? Never NULL.
69  */
70 static const struct GNUNET_OS_ProjectData *current_pd = &default_pd;
71
72 /**
73  * Return default project data used by 'libgnunetutil' for GNUnet.
74  */
75 const struct GNUNET_OS_ProjectData *
76 GNUNET_OS_project_data_default (void)
77 {
78   return &default_pd;
79 }
80
81
82 /**
83  * @return current project data.
84  */
85 const struct GNUNET_OS_ProjectData *
86 GNUNET_OS_project_data_get ()
87 {
88   return current_pd;
89 }
90
91
92 /**
93  * Setup OS subsystem with project data.
94  *
95  * @param pd project data used to determine paths
96  */
97 void
98 GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd)
99 {
100   GNUNET_assert (NULL != pd);
101   current_pd = pd;
102 }
103
104
105 #if LINUX
106 /**
107  * Try to determine path by reading /proc/PID/exe
108  *
109  * @return NULL on error
110  */
111 static char *
112 get_path_from_proc_maps ()
113 {
114   char fn[64];
115   char line[1024];
116   char dir[1024];
117   FILE *f;
118   char *lgu;
119
120   GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
121   if (NULL == (f = FOPEN (fn, "r")))
122     return NULL;
123   while (NULL != fgets (line, sizeof (line), f))
124   {
125     if ((1 ==
126          SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s", dir)) &&
127         (NULL != (lgu = strstr (dir,
128                                 current_pd->libname))))
129     {
130       lgu[0] = '\0';
131       FCLOSE (f);
132       return GNUNET_strdup (dir);
133     }
134   }
135   FCLOSE (f);
136   return NULL;
137 }
138
139
140 /**
141  * Try to determine path by reading /proc/PID/exe
142  *
143  * @return NULL on error
144  */
145 static char *
146 get_path_from_proc_exe ()
147 {
148   char fn[64];
149   char lnk[1024];
150   ssize_t size;
151   char *lep;
152
153   GNUNET_snprintf (fn,
154                    sizeof (fn),
155                    "/proc/%u/exe",
156                    getpid ());
157   size = readlink (fn,
158                    lnk,
159                    sizeof (lnk) - 1);
160   if (size <= 0)
161   {
162     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR,
163                        "readlink",
164                        fn);
165     return NULL;
166   }
167   GNUNET_assert ( ((size_t) size) < sizeof (lnk));
168   lnk[size] = '\0';
169   while ((lnk[size] != '/') && (size > 0))
170     size--;
171   GNUNET_asprintf (&lep,
172                    "/%s/libexec/",
173                    current_pd->project_dirname);
174   /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
175   if ( (((size_t) size) > strlen (lep)) &&
176        (0 == strcmp (lep,
177                      &lnk[size - strlen (lep)])) )
178     size -= strlen (lep) - 1;
179   GNUNET_free (lep);
180   if ( (size < 4) ||
181        (lnk[size - 4] != '/') )
182   {
183     /* not installed in "/bin/" -- binary path probably useless */
184     return NULL;
185   }
186   lnk[size] = '\0';
187   return GNUNET_strdup (lnk);
188 }
189 #endif
190
191
192 #if WINDOWS
193 static HINSTANCE dll_instance;
194
195
196 /**
197  * GNUNET_util_cl_init() in common_logging.c is preferred.
198  * This function is only for thread-local storage (not used in GNUnet)
199  * and hInstance saving.
200  */
201 BOOL WINAPI
202 DllMain (HINSTANCE hinstDLL,
203          DWORD fdwReason,
204          LPVOID lpvReserved)
205 {
206   switch (fdwReason)
207   {
208     case DLL_PROCESS_ATTACH:
209       dll_instance = hinstDLL;
210       break;
211     case DLL_THREAD_ATTACH:
212       break;
213     case DLL_THREAD_DETACH:
214       break;
215     case DLL_PROCESS_DETACH:
216       break;
217   }
218   return TRUE;
219 }
220
221
222 /**
223  * Try to determine path with win32-specific function
224  *
225  * @return NULL on error
226  */
227 static char *
228 get_path_from_module_filename ()
229 {
230   size_t pathlen = 512;
231   DWORD real_pathlen;
232   wchar_t *idx;
233   wchar_t *modulepath = NULL;
234   char *upath;
235   uint8_t *u8_string;
236   size_t u8_string_length;
237
238   /* This braindead function won't tell us how much space it needs, so
239    * we start at 1024 and double the space up if it doesn't fit, until
240    * it fits, or we exceed the threshold.
241    */
242   do
243   {
244     pathlen = pathlen * 2;
245     modulepath = GNUNET_realloc (modulepath,
246                                  pathlen * sizeof (wchar_t));
247     SetLastError (0);
248     real_pathlen = GetModuleFileNameW (dll_instance,
249                                        modulepath,
250                                        pathlen * sizeof (wchar_t));
251   } while (real_pathlen >= pathlen && pathlen < 16*1024);
252   if (real_pathlen >= pathlen)
253     GNUNET_assert (0);
254   /* To be safe */
255   modulepath[real_pathlen] = '\0';
256
257   idx = modulepath + real_pathlen;
258   while ((idx > modulepath) && (*idx != L'\\') && (*idx != L'/'))
259     idx--;
260   *idx = L'\0';
261
262   /* Now modulepath holds full path to the directory where libgnunetutil is.
263    * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
264    */
265   if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\'))
266   {
267     /* At least one directory component (i.e. we're not in a root directory) */
268     wchar_t *dirname = idx;
269     while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
270       dirname--;
271     *dirname = L'\0';
272     if (dirname > modulepath)
273     {
274       dirname++;
275       /* Now modulepath holds full path to the parent directory of the directory
276        * where libgnunetutil is.
277        * dirname holds the name of the directory where libgnunetutil is.
278        */
279       if (wcsicmp (dirname, L"bin") == 0)
280       {
281         /* pass */
282       }
283       else
284       {
285         /* Roll back our changes to modulepath */
286         dirname--;
287         *dirname = L'/';
288       }
289     }
290   }
291
292   /* modulepath is GNUNET_PREFIX */
293   u8_string = u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length);
294   if (NULL == u8_string)
295     GNUNET_assert (0);
296
297   upath = GNUNET_malloc (u8_string_length + 1);
298   GNUNET_memcpy (upath, u8_string, u8_string_length);
299   upath[u8_string_length] = '\0';
300
301   free (u8_string);
302   GNUNET_free (modulepath);
303
304   return upath;
305 }
306 #endif
307
308
309 #if DARWIN
310 /**
311  * Signature of the '_NSGetExecutablePath" function.
312  *
313  * @param buf where to write the path
314  * @param number of bytes available in @a buf
315  * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
316  */
317 typedef int
318 (*MyNSGetExecutablePathProto) (char *buf,
319                                size_t *bufsize);
320
321
322 /**
323  * Try to obtain the path of our executable using '_NSGetExecutablePath'.
324  *
325  * @return NULL on error
326  */
327 static char *
328 get_path_from_NSGetExecutablePath ()
329 {
330   static char zero = '\0';
331   char *path;
332   size_t len;
333   MyNSGetExecutablePathProto func;
334
335   path = NULL;
336   if (NULL == (func =
337                (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
338     return NULL;
339   path = &zero;
340   len = 0;
341   /* get the path len, including the trailing \0 */
342   (void) func (path, &len);
343   if (0 == len)
344     return NULL;
345   path = GNUNET_malloc (len);
346   if (0 != func (path, &len))
347   {
348     GNUNET_free (path);
349     return NULL;
350   }
351   len = strlen (path);
352   while ((path[len] != '/') && (len > 0))
353     len--;
354   path[len] = '\0';
355   return path;
356 }
357
358
359 /**
360  * Try to obtain the path of our executable using '_dyld_image' API.
361  *
362  * @return NULL on error
363  */
364 static char *
365 get_path_from_dyld_image ()
366 {
367   const char *path;
368   char *p;
369   char *s;
370   unsigned int i;
371   int c;
372
373   c = _dyld_image_count ();
374   for (i = 0; i < c; i++)
375   {
376     if (((const void *) _dyld_get_image_header (i)) !=
377         ((const void *) &_mh_dylib_header) )
378       continue;
379     path = _dyld_get_image_name (i);
380     if ( (NULL == path) || (0 == strlen (path)) )
381       continue;
382     p = GNUNET_strdup (path);
383     s = p + strlen (p);
384     while ((s > p) && ('/' != *s))
385       s--;
386     s++;
387     *s = '\0';
388     return p;
389   }
390   return NULL;
391 }
392 #endif
393
394
395 /**
396  * Return the actual path to a file found in the current
397  * PATH environment variable.
398  *
399  * @param binary the name of the file to find
400  * @return path to binary, NULL if not found
401  */
402 static char *
403 get_path_from_PATH (const char *binary)
404 {
405   char *path;
406   char *pos;
407   char *end;
408   char *buf;
409   const char *p;
410
411   if (NULL == (p = getenv ("PATH")))
412     return NULL;
413 #if WINDOWS
414   /* On W32 look in CWD first. */
415   GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
416 #else
417   path = GNUNET_strdup (p);     /* because we write on it */
418 #endif
419   buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
420   pos = path;
421   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
422   {
423     *end = '\0';
424     sprintf (buf, "%s/%s", pos, binary);
425     if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
426     {
427       pos = GNUNET_strdup (pos);
428       GNUNET_free (buf);
429       GNUNET_free (path);
430       return pos;
431     }
432     pos = end + 1;
433   }
434   sprintf (buf, "%s/%s", pos, binary);
435   if (GNUNET_YES == GNUNET_DISK_file_test (buf))
436   {
437     pos = GNUNET_strdup (pos);
438     GNUNET_free (buf);
439     GNUNET_free (path);
440     return pos;
441   }
442   GNUNET_free (buf);
443   GNUNET_free (path);
444   return NULL;
445 }
446
447
448 /**
449  * Try to obtain the installation path using the "GNUNET_PREFIX" environment
450  * variable.
451  *
452  * @return NULL on error (environment variable not set)
453  */
454 static char *
455 get_path_from_GNUNET_PREFIX ()
456 {
457   const char *p;
458
459   if ( (NULL != current_pd->env_varname) &&
460        (NULL != (p = getenv (current_pd->env_varname))) )
461     return GNUNET_strdup (p);
462   if ( (NULL != current_pd->env_varname_alt) &&
463        (NULL != (p = getenv (current_pd->env_varname_alt))) )
464     return GNUNET_strdup (p);
465   return NULL;
466 }
467
468
469 /**
470  * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
471  * @author Milan
472  *
473  * @return a pointer to the executable path, or NULL on error
474  */
475 static char *
476 os_get_gnunet_path ()
477 {
478   char *ret;
479
480   if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
481     return ret;
482 #if LINUX
483   if (NULL != (ret = get_path_from_proc_maps ()))
484     return ret;
485   /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
486   if ( (NULL != current_pd->binary_name) &&
487        (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
488     return ret;
489   if (NULL != (ret = get_path_from_proc_exe ()))
490     return ret;
491 #endif
492 #if WINDOWS
493   if (NULL != (ret = get_path_from_module_filename ()))
494     return ret;
495 #endif
496 #if DARWIN
497   if (NULL != (ret = get_path_from_dyld_image ()))
498     return ret;
499   if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
500     return ret;
501 #endif
502   if ( (NULL != current_pd->binary_name) &&
503        (NULL != (ret = get_path_from_PATH (current_pd->binary_name))) )
504     return ret;
505   /* other attempts here */
506   LOG (GNUNET_ERROR_TYPE_ERROR,
507        _("Could not determine installation path for %s.  Set `%s' environment variable.\n"),
508        current_pd->project_dirname,
509        current_pd->env_varname);
510   return NULL;
511 }
512
513
514 /**
515  * @brief get the path to current app's bin/
516  * @return a pointer to the executable path, or NULL on error
517  */
518 static char *
519 os_get_exec_path ()
520 {
521   char *ret = NULL;
522
523 #if LINUX
524   if (NULL != (ret = get_path_from_proc_exe ()))
525     return ret;
526 #endif
527 #if WINDOWS
528   if (NULL != (ret = get_path_from_module_filename ()))
529     return ret;
530 #endif
531 #if DARWIN
532   if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
533     return ret;
534 #endif
535   /* other attempts here */
536   return ret;
537 }
538
539
540 /**
541  * @brief get the path to a specific GNUnet installation directory or,
542  * with #GNUNET_OS_IPK_SELF_PREFIX, the current running apps installation directory
543  * @return a pointer to the dir path (to be freed by the caller)
544  */
545 char *
546 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
547 {
548   size_t n;
549   char *dirname;
550   char *execpath = NULL;
551   char *tmp;
552   char *multiarch;
553   char *libdir;
554   int isbasedir;
555
556   /* if wanted, try to get the current app's bin/ */
557   if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
558     execpath = os_get_exec_path ();
559
560   /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
561    * guess for the current app */
562   if (NULL == execpath)
563     execpath = os_get_gnunet_path ();
564
565   if (NULL == execpath)
566     return NULL;
567
568   n = strlen (execpath);
569   if (0 == n)
570   {
571     /* should never happen, but better safe than sorry */
572     GNUNET_free (execpath);
573     return NULL;
574   }
575   /* remove filename itself */
576   while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
577     execpath[--n] = '\0';
578
579   isbasedir = 1;
580   if ((n > 6) &&
581       ((0 == strcasecmp (&execpath[n - 6], "/lib32")) ||
582        (0 == strcasecmp (&execpath[n - 6], "/lib64"))))
583   {
584     if ( (GNUNET_OS_IPK_LIBDIR != dirkind) &&
585          (GNUNET_OS_IPK_LIBEXECDIR != dirkind) )
586     {
587       /* strip '/lib32' or '/lib64' */
588       execpath[n - 6] = '\0';
589       n -= 6;
590     }
591     else
592       isbasedir = 0;
593   }
594   else if ((n > 4) &&
595            ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
596             (0 == strcasecmp (&execpath[n - 4], "/lib"))))
597   {
598     /* strip '/bin' or '/lib' */
599     execpath[n - 4] = '\0';
600     n -= 4;
601   }
602   multiarch = NULL;
603   if (NULL != (libdir = strstr (execpath, "/lib/")))
604   {
605     /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
606        here we need to re-add 'multiarch' to lib and libexec paths later! */
607     multiarch = &libdir[5];
608     if (NULL == strchr (multiarch, '/'))
609       libdir[0] = '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
610     else
611       multiarch = NULL; /* maybe not, multiarch still has a '/', which is not OK */
612   }
613   /* in case this was a directory named foo-bin, remove "foo-" */
614   while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
615     execpath[--n] = '\0';
616   switch (dirkind)
617   {
618   case GNUNET_OS_IPK_PREFIX:
619   case GNUNET_OS_IPK_SELF_PREFIX:
620     dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
621     break;
622   case GNUNET_OS_IPK_BINDIR:
623     dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
624     break;
625   case GNUNET_OS_IPK_LIBDIR:
626     if (isbasedir)
627     {
628       GNUNET_asprintf (&tmp,
629                        "%s%s%s%s%s%s%s",
630                        execpath,
631                        DIR_SEPARATOR_STR "lib",
632                        (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
633                        (NULL != multiarch) ? multiarch : "",
634                        DIR_SEPARATOR_STR,
635                        current_pd->project_dirname,
636                        DIR_SEPARATOR_STR);
637       if (GNUNET_YES ==
638           GNUNET_DISK_directory_test (tmp, GNUNET_YES))
639       {
640         GNUNET_free (execpath);
641         return tmp;
642       }
643       GNUNET_free (tmp);
644       tmp = NULL;
645       dirname = NULL;
646       if (4 == sizeof (void *))
647       {
648         GNUNET_asprintf (&dirname,
649                          DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
650                          current_pd->project_dirname);
651         GNUNET_asprintf (&tmp,
652                          "%s%s",
653                          execpath,
654                          dirname);
655       }
656       if (8 == sizeof (void *))
657       {
658         GNUNET_asprintf (&dirname,
659                          DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
660                          current_pd->project_dirname);
661         GNUNET_asprintf (&tmp,
662                          "%s%s",
663                          execpath,
664                          dirname);
665       }
666
667       if ( (NULL != tmp) &&
668            (GNUNET_YES ==
669             GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
670       {
671         GNUNET_free (execpath);
672         GNUNET_free_non_null (dirname);
673         return tmp;
674       }
675       GNUNET_free (tmp);
676       GNUNET_free_non_null (dirname);
677     }
678     GNUNET_asprintf (&dirname,
679                      DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
680                      current_pd->project_dirname);
681     break;
682   case GNUNET_OS_IPK_DATADIR:
683     GNUNET_asprintf (&dirname,
684                      DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
685                      current_pd->project_dirname);
686     break;
687   case GNUNET_OS_IPK_LOCALEDIR:
688     dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR);
689     break;
690   case GNUNET_OS_IPK_ICONDIR:
691     dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR);
692     break;
693   case GNUNET_OS_IPK_DOCDIR:
694     GNUNET_asprintf (&dirname,
695                      DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
696                      current_pd->project_dirname);
697     break;
698   case GNUNET_OS_IPK_LIBEXECDIR:
699     if (isbasedir)
700     {
701       GNUNET_asprintf (&dirname,
702                        DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
703                        current_pd->project_dirname);
704       GNUNET_asprintf (&tmp,
705                        "%s%s%s%s",
706                        execpath,
707                        DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
708                        (NULL != multiarch) ? multiarch : "",
709                        dirname);
710       if (GNUNET_YES ==
711           GNUNET_DISK_directory_test (tmp, GNUNET_YES))
712       {
713         GNUNET_free (execpath);
714         GNUNET_free (dirname);
715         return tmp;
716       }
717       GNUNET_free (tmp);
718       tmp = NULL;
719       dirname = NULL;
720       if (4 == sizeof (void *))
721       {
722         GNUNET_asprintf (&dirname,
723                          DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
724                          current_pd->project_dirname);
725         GNUNET_asprintf (&tmp,
726                          "%s%s",
727                          execpath,
728                          dirname);
729       }
730       if (8 == sizeof (void *))
731       {
732         GNUNET_asprintf (&dirname,
733                          DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
734                          current_pd->project_dirname);
735         GNUNET_asprintf (&tmp,
736                          "%s%s",
737                          execpath,
738                          dirname);
739       }
740       if ( (NULL != tmp) &&
741            (GNUNET_YES ==
742             GNUNET_DISK_directory_test (tmp, GNUNET_YES)) )
743       {
744         GNUNET_free (execpath);
745         GNUNET_free_non_null (dirname);
746         return tmp;
747       }
748       GNUNET_free (tmp);
749       GNUNET_free_non_null (dirname);
750     }
751     GNUNET_asprintf (&dirname,
752                      DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR "libexec" DIR_SEPARATOR_STR,
753                      current_pd->project_dirname);
754     break;
755   default:
756     GNUNET_free (execpath);
757     return NULL;
758   }
759   GNUNET_asprintf (&tmp,
760                    "%s%s",
761                    execpath,
762                    dirname);
763   GNUNET_free (dirname);
764   GNUNET_free (execpath);
765   return tmp;
766 }
767
768
769 /**
770  * Given the name of a gnunet-helper, gnunet-service or gnunet-daemon
771  * binary, try to prefix it with the libexec/-directory to get the
772  * full path.
773  *
774  * @param progname name of the binary
775  * @return full path to the binary, if possible, otherwise copy of 'progname'
776  */
777 char *
778 GNUNET_OS_get_libexec_binary_path (const char *progname)
779 {
780   static char *cache;
781   char *libexecdir;
782   char *binary;
783
784   if ( (DIR_SEPARATOR == progname[0]) ||
785        (GNUNET_YES ==
786         GNUNET_STRINGS_path_is_absolute (progname,
787                                          GNUNET_NO,
788                                          NULL, NULL)) )
789     return GNUNET_strdup (progname);
790   if (NULL != cache)
791     libexecdir = cache;
792   else
793     libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
794   if (NULL == libexecdir)
795     return GNUNET_strdup (progname);
796   GNUNET_asprintf (&binary,
797                    "%s%s",
798                    libexecdir,
799                    progname);
800   cache = libexecdir;
801   return binary;
802 }
803
804
805 /**
806  * Check whether an executable exists and possibly if the suid bit is
807  * set on the file.  Attempts to find the file using the current PATH
808  * environment variable as a search path.
809  *
810  * @param binary the name of the file to check.
811  *        W32: must not have an .exe suffix.
812  * @param check_suid input true if the binary should be checked for SUID (*nix)
813  *        W32: checks if the program has sufficient privileges by executing this
814  *             binary with the -d flag. -d omits a programs main loop and only
815  *             executes all privileged operations in an binary.
816  * @param params parameters used for w32 privilege checking (can be NULL for != w32 )
817  * @return #GNUNET_YES if the file is SUID (*nix) or can be executed with current privileges (W32),
818  *         #GNUNET_NO if not SUID (but binary exists),
819  *         #GNUNET_SYSERR on error (no such binary or not executable)
820  */
821 int
822 GNUNET_OS_check_helper_binary (const char *binary,
823                                int check_suid,
824                                const char *params)
825 {
826   struct stat statbuf;
827   char *p;
828   char *pf;
829 #ifdef MINGW
830   char *binaryexe;
831
832   GNUNET_asprintf (&binaryexe,
833                    "%s.exe",
834                    binary);
835   if ( (GNUNET_YES ==
836         GNUNET_STRINGS_path_is_absolute (binaryexe,
837                                          GNUNET_NO,
838                                          NULL, NULL)) ||
839        (0 == strncmp (binary, "./", 2)) )
840     p = GNUNET_strdup (binaryexe);
841   else
842   {
843     p = get_path_from_PATH (binaryexe);
844     if (NULL != p)
845     {
846       GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
847       GNUNET_free (p);
848       p = pf;
849     }
850   }
851   GNUNET_free (binaryexe);
852 #else
853   if ( (GNUNET_YES ==
854         GNUNET_STRINGS_path_is_absolute (binary,
855                                          GNUNET_NO,
856                                          NULL,
857                                          NULL)) ||
858        (0 == strncmp (binary, "./", 2)) )
859   {
860     p = GNUNET_strdup (binary);
861   }
862   else
863   {
864     p = get_path_from_PATH (binary);
865     if (NULL != p)
866     {
867       GNUNET_asprintf (&pf,
868                        "%s/%s",
869                        p,
870                        binary);
871       GNUNET_free (p);
872       p = pf;
873     }
874   }
875 #endif
876   if (NULL == p)
877   {
878     LOG (GNUNET_ERROR_TYPE_INFO,
879          _("Could not find binary `%s' in PATH!\n"),
880          binary);
881     return GNUNET_SYSERR;
882   }
883   if (0 != ACCESS (p,
884                    X_OK))
885   {
886     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
887                        "access",
888                        p);
889     GNUNET_free (p);
890     return GNUNET_SYSERR;
891   }
892 #ifndef MINGW
893   if (0 == getuid ())
894   {
895     /* as we run as root, we don't insist on SUID */
896     GNUNET_free (p);
897     return GNUNET_YES;
898   }
899 #endif
900   if (0 != STAT (p,
901                  &statbuf))
902   {
903     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
904                        "stat",
905                        p);
906     GNUNET_free (p);
907     return GNUNET_SYSERR;
908   }
909   if (check_suid)
910   {
911 #ifndef MINGW
912     (void) params;
913     if ( (0 != (statbuf.st_mode & S_ISUID)) &&
914          (0 == statbuf.st_uid) )
915     {
916       GNUNET_free (p);
917       return GNUNET_YES;
918     }
919     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
920                 _("Binary `%s' exists, but is not SUID\n"),
921                 p);
922     /* binary exists, but not SUID */
923 #else
924     STARTUPINFO start;
925     char parameters[512];
926     PROCESS_INFORMATION proc;
927     DWORD exit_value;
928
929     GNUNET_snprintf (parameters,
930                      sizeof (parameters),
931                      "-d %s", params);
932     memset (&start, 0, sizeof (start));
933     start.cb = sizeof (start);
934     memset (&proc, 0, sizeof (proc));
935
936
937     // Start the child process.
938     if ( ! (CreateProcess( p,   // current windows (2k3 and up can handle / instead of \ in paths))
939         parameters,           // execute dryrun/priviliege checking mode
940         NULL,           // Process handle not inheritable
941         NULL,           // Thread handle not inheritable
942         FALSE,          // Set handle inheritance to FALSE
943         CREATE_DEFAULT_ERROR_MODE, // No creation flags
944         NULL,           // Use parent's environment block
945         NULL,           // Use parent's starting directory
946         &start,            // Pointer to STARTUPINFO structure
947         &proc )           // Pointer to PROCESS_INFORMATION structure
948                                ))
949       {
950         LOG (GNUNET_ERROR_TYPE_ERROR,
951              _("CreateProcess failed for binary %s (%d).\n"),
952              p, GetLastError());
953         return GNUNET_SYSERR;
954     }
955
956     // Wait until child process exits.
957     WaitForSingleObject( proc.hProcess, INFINITE );
958
959     if ( ! GetExitCodeProcess (proc.hProcess, &exit_value)){
960         LOG (GNUNET_ERROR_TYPE_ERROR,
961              _("GetExitCodeProcess failed for binary %s (%d).\n"),
962              p, GetLastError() );
963         return GNUNET_SYSERR;
964       }
965     // Close process and thread handles.
966     CloseHandle( proc.hProcess );
967     CloseHandle( proc.hThread );
968
969     if (!exit_value)
970       return GNUNET_YES;
971 #endif
972     }
973   GNUNET_free (p);
974   return GNUNET_NO;
975 }
976
977
978 /* end of os_installation.c */