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