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