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