c52628dcdd6d4e8b203a69510927964cf278ffa5
[oweals/gnunet.git] / src / util / os_installation.c
1 /*
2      This file is part of GNUnet.
3      (C) 2006 Christian Grothoff (and other contributing authors)
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 2, 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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file src/util/os_installation.c
23  * @brief get paths used by the program
24  * @author Milan
25  */
26 #include <sys/stat.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #include "platform.h"
32 #include "gnunet_common.h"
33 #include "gnunet_configuration_lib.h"
34 #include "gnunet_disk_lib.h"
35 #include "gnunet_os_lib.h"
36 #include "gnunet_strings_lib.h"
37 #if DARWIN
38 #include <mach-o/ldsyms.h>
39 #include <mach-o/dyld.h>
40 #endif
41
42 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
43
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
45
46 #if LINUX
47 /**
48  * Try to determine path by reading /proc/PID/exe
49  *
50  * @return NULL on error
51  */
52 static char *
53 get_path_from_proc_maps ()
54 {
55   char fn[64];
56   char line[1024];
57   char dir[1024];
58   FILE *f;
59   char *lgu;
60
61   GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ());
62   if (NULL == (f = FOPEN (fn, "r")))
63     return NULL;
64   while (NULL != fgets (line, sizeof (line), f))
65   {
66     if ((1 ==
67          SSCANF (line, "%*x-%*x %*c%*c%*c%*c %*x %*2u:%*2u %*u%*[ ]%s", dir)) &&
68         (NULL != (lgu = strstr (dir, "libgnunetutil"))))
69     {
70       lgu[0] = '\0';
71       FCLOSE (f);
72       return GNUNET_strdup (dir);
73     }
74   }
75   FCLOSE (f);
76   return NULL;
77 }
78
79
80 /**
81  * Try to determine path by reading /proc/PID/exe
82  *
83  * @return NULL on error
84  */
85 static char *
86 get_path_from_proc_exe ()
87 {
88   char fn[64];
89   char lnk[1024];
90   ssize_t size;
91
92   GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ());
93   size = readlink (fn, lnk, sizeof (lnk) - 1);
94   if (size <= 0)
95   {
96     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
97     return NULL;
98   }
99   GNUNET_assert (size < sizeof (lnk));
100   lnk[size] = '\0';
101   while ((lnk[size] != '/') && (size > 0))
102     size--;
103   if ((size < 4) || (lnk[size - 4] != '/'))
104   {
105     /* not installed in "/bin/" -- binary path probably useless */
106     return NULL;
107   }
108   lnk[size] = '\0';
109   return GNUNET_strdup (lnk);
110 }
111 #endif
112
113 #if WINDOWS
114 /**
115  * Try to determine path with win32-specific function
116  *
117  * @return NULL on error
118  */
119 static char *
120 get_path_from_module_filename ()
121 {
122   wchar_t path[4097];
123   char upath[4097];
124   wchar_t *idx;
125
126   GetModuleFileNameW (NULL, path, sizeof (path) - 1);
127   idx = path + wcslen (path);
128   while ((idx > path) && (*idx != L'\\') && (*idx != L'/'))
129     idx--;
130   *idx = L'\0';
131   upath[0] = '\0';
132   WideCharToMultiByte (CP_UTF8, 0, path, -1, upath, 4097, NULL, NULL);
133
134   return GNUNET_strdup (upath);
135 }
136 #endif
137
138 #if DARWIN
139 /**
140  * Signature of the '_NSGetExecutablePath" function.
141  *
142  * @param buf where to write the path
143  * @param number of bytes available in 'buf'
144  * @return 0 on success, otherwise desired number of bytes is stored in 'bufsize'
145  */
146 typedef int (*MyNSGetExecutablePathProto) (char *buf, size_t * bufsize);
147
148
149 /**
150  * Try to obtain the path of our executable using '_NSGetExecutablePath'.
151  *
152  * @return NULL on error
153  */
154 static char *
155 get_path_from_NSGetExecutablePath ()
156 {
157   static char zero = '\0';
158   char *path;
159   size_t len;
160   MyNSGetExecutablePathProto func;
161
162   path = NULL;
163   if (NULL == (func =
164                (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath")))
165     return NULL;
166   path = &zero;
167   len = 0;
168   /* get the path len, including the trailing \0 */
169   (void) func (path, &len);
170   if (0 == len)
171     return NULL;
172   path = GNUNET_malloc (len);
173   if (0 != func (path, &len))
174   {
175     GNUNET_free (path);
176     return NULL;
177   }
178   len = strlen (path);
179   while ((path[len] != '/') && (len > 0))
180     len--;
181   path[len] = '\0';
182   return path;
183 }
184
185
186 /**
187  * Try to obtain the path of our executable using '_dyld_image' API.
188  *
189  * @return NULL on error
190  */
191 static char *
192 get_path_from_dyld_image ()
193 {
194   const char *path;
195   char *p;
196   char *s;
197   int i;
198   int c;
199
200   p = NULL;
201   c = _dyld_image_count ();
202   for (i = 0; i < c; i++)
203   {
204     if (_dyld_get_image_header (i) == &_mh_dylib_header)
205     {
206       path = _dyld_get_image_name (i);
207       if ( (NULL != path) && (strlen (path) > 0) )
208       {
209         p = GNUNET_strdup (path);
210         s = p + strlen (p);
211         while ((s > p) && ('/' != *s))
212           s--;
213         s++;
214         *s = '\0';
215       }
216       break;
217     }
218   }
219   return p;
220 }
221 #endif
222
223
224 /**
225  * Return the actual path to a file found in the current
226  * PATH environment variable.
227  *
228  * @param binary the name of the file to find
229  * @return path to binary, NULL if not found
230  */
231 static char *
232 get_path_from_PATH (const char *binary)
233 {
234   char *path;
235   char *pos;
236   char *end;
237   char *buf;
238   const char *p;
239
240   p = getenv ("PATH");
241   if (NULL == p)
242     return NULL;
243 #if WINDOWS
244   /* On W32 look in CWD first. */
245   GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
246 #else
247   path = GNUNET_strdup (p);     /* because we write on it */
248 #endif
249   buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
250   pos = path;
251   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
252   {
253     *end = '\0';
254     sprintf (buf, "%s/%s", pos, binary);
255     if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
256     {
257       pos = GNUNET_strdup (pos);
258       GNUNET_free (buf);
259       GNUNET_free (path);
260       return pos;
261     }
262     pos = end + 1;
263   }
264   sprintf (buf, "%s/%s", pos, binary);
265   if (GNUNET_YES == GNUNET_DISK_file_test (buf))
266   {
267     pos = GNUNET_strdup (pos);
268     GNUNET_free (buf);
269     GNUNET_free (path);
270     return pos;
271   }
272   GNUNET_free (buf);
273   GNUNET_free (path);
274   return NULL;
275 }
276
277
278 /**
279  * Try to obtain the installation path using the "GNUNET_PREFIX" environment
280  * variable.
281  *
282  * @return NULL on error (environment variable not set)
283  */
284 static char *
285 get_path_from_GNUNET_PREFIX ()
286 {
287   const char *p;
288
289   if (NULL != (p = getenv ("GNUNET_PREFIX")))
290     return GNUNET_strdup (p);
291   return NULL;
292 }
293
294
295 /**
296  * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
297  * @author Milan
298  *
299  * @return a pointer to the executable path, or NULL on error
300  */
301 static char *
302 os_get_gnunet_path ()
303 {
304   char *ret;
305
306   if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
307     return ret;
308 #if LINUX
309   if (NULL != (ret = get_path_from_proc_maps ()))
310     return ret;
311   if (NULL != (ret = get_path_from_proc_exe ()))
312     return ret;
313 #endif
314 #if WINDOWS
315   if (NULL != (ret = get_path_from_module_filename ()))
316     return ret;
317 #endif
318 #if DARWIN
319   if (NULL != (ret = get_path_from_dyld_image ()))
320     return ret;
321   if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
322     return ret;
323 #endif
324   if (NULL != (ret = get_path_from_PATH ("gnunet-arm")))
325     return ret;
326   /* other attempts here */
327   LOG (GNUNET_ERROR_TYPE_ERROR,
328        _
329        ("Could not determine installation path for %s.  Set `%s' environment variable.\n"),
330        "GNUnet", "GNUNET_PREFIX");
331   return NULL;
332 }
333
334
335 /**
336  * @brief get the path to current app's bin/
337  * @author Milan
338  *
339  * @return a pointer to the executable path, or NULL on error
340  */
341 static char *
342 os_get_exec_path ()
343 {
344   char *ret;
345
346 #if LINUX
347   if (NULL != (ret = get_path_from_proc_exe ()))
348     return ret;
349 #endif
350 #if WINDOWS
351   if (NULL != (ret = get_path_from_module_filename ()))
352     return ret;
353 #endif
354 #if DARWIN
355   if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
356     return ret;
357 #endif
358   /* other attempts here */
359   return NULL;
360 }
361
362
363 /**
364  * @brief get the path to a specific GNUnet installation directory or,
365  * with GNUNET_IPK_SELF_PREFIX, the current running apps installation directory
366  * @author Milan
367  * @return a pointer to the dir path (to be freed by the caller)
368  */
369 char *
370 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
371 {
372   size_t n;
373   const char *dirname;
374   char *execpath = NULL;
375   char *tmp;
376   int isbasedir;
377
378   /* if wanted, try to get the current app's bin/ */
379   if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
380     execpath = os_get_exec_path ();
381
382   /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
383    * guess for the current app */
384   if (NULL == execpath)
385     execpath = os_get_gnunet_path ();
386
387   if (NULL == execpath)
388     return NULL;
389
390   n = strlen (execpath);
391   if (0 == n)
392   {
393     /* should never happen, but better safe than sorry */
394     GNUNET_free (execpath);
395     return NULL;
396   }
397   /* remove filename itself */
398   while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
399     execpath[--n] = '\0';
400
401   isbasedir = 1;
402   if ((n > 5) &&
403       ((0 == strcasecmp (&execpath[n - 5], "lib32")) ||
404        (0 == strcasecmp (&execpath[n - 5], "lib64"))))
405   {
406     if (GNUNET_OS_IPK_LIBDIR != dirkind)
407     {
408       /* strip '/lib32' or '/lib64' */
409       execpath[n - 5] = '\0';
410       n -= 5;
411     }
412     else
413       isbasedir = 0;
414   }
415   else if ((n > 3) &&
416            ((0 == strcasecmp (&execpath[n - 3], "bin")) ||
417             (0 == strcasecmp (&execpath[n - 3], "lib"))))
418   {
419     /* strip '/bin' or '/lib' */
420     execpath[n - 3] = '\0';
421     n -= 3;
422   }
423   /* in case this was a directory named foo-bin, remove "foo-" */
424   while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
425     execpath[--n] = '\0';
426   switch (dirkind)
427   {
428   case GNUNET_OS_IPK_PREFIX:
429   case GNUNET_OS_IPK_SELF_PREFIX:
430     dirname = DIR_SEPARATOR_STR;
431     break;
432   case GNUNET_OS_IPK_BINDIR:
433     dirname = DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR;
434     break;
435   case GNUNET_OS_IPK_LIBDIR:
436     if (isbasedir)
437       dirname =
438           DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
439     else
440       dirname = DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
441     break;
442   case GNUNET_OS_IPK_DATADIR:
443     dirname =
444         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
445     break;
446   case GNUNET_OS_IPK_LOCALEDIR:
447     dirname =
448         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR;
449     break;
450   case GNUNET_OS_IPK_ICONDIR:
451     dirname =
452         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR;
453     break;
454   case GNUNET_OS_IPK_DOCDIR:
455     dirname =
456         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR \
457         "gnunet" DIR_SEPARATOR_STR;
458     break;
459   default:
460     GNUNET_free (execpath);
461     return NULL;
462   }
463   tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
464   sprintf (tmp, "%s%s", execpath, dirname);
465   GNUNET_free (execpath);
466   return tmp;
467 }
468
469
470 /**
471  * Check whether an executable exists and possibly
472  * if the suid bit is set on the file.
473  * Attempts to find the file using the current
474  * PATH environment variable as a search path.
475  *
476  * @param binary the name of the file to check.
477  *        W32: must not have an .exe suffix.
478  * @return GNUNET_YES if the file is SUID,
479  *         GNUNET_NO if not SUID (but binary exists)
480  *         GNUNET_SYSERR on error (no such binary or not executable)
481  */
482 int
483 GNUNET_OS_check_helper_binary (const char *binary)
484 {
485   struct stat statbuf;
486   char *p;
487   char *pf;
488 #ifdef MINGW
489   SOCKET rawsock;
490   char *binaryexe;
491
492   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
493   if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO,
494                                                        NULL, NULL)) ||
495        (0 == strncmp (binary, "./", 2)) )
496     p = GNUNET_strdup (binaryexe);
497   else
498   {
499     p = get_path_from_PATH (binaryexe);
500     if (NULL != p)
501     {
502       GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
503       GNUNET_free (p);
504       p = pf;
505     }
506   }
507   GNUNET_free (binaryexe);
508 #else
509   if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO,
510                                                        NULL, NULL)) ||
511        (0 == strncmp (binary, "./", 2)) )
512     p = GNUNET_strdup (binary);
513   else
514   {
515     p = get_path_from_PATH (binary);
516     if (NULL != p)
517     {
518       GNUNET_asprintf (&pf, "%s/%s", p, binary);
519       GNUNET_free (p);
520       p = pf;
521     }
522   }
523 #endif
524   if (NULL == p)
525   {
526     LOG (GNUNET_ERROR_TYPE_INFO, _("Could not find binary `%s' in PATH!\n"),
527          binary);
528     return GNUNET_SYSERR;
529   }
530   if (0 != ACCESS (p, X_OK))
531   {
532     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
533     GNUNET_free (p);
534     return GNUNET_SYSERR;
535   }
536 #ifndef MINGW
537   if (0 == getuid ())
538   {
539     /* as we run as root, we don't insist on SUID */
540     GNUNET_free (p);
541     return GNUNET_OK;
542   }
543 #endif
544   if (0 != STAT (p, &statbuf))
545   {
546     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
547     GNUNET_free (p);
548     return GNUNET_SYSERR;
549   }
550 #ifndef MINGW
551   if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
552   {
553     GNUNET_free (p);
554     return GNUNET_YES;
555   }
556   /* binary exists, but not SUID */
557   GNUNET_free (p);
558   return GNUNET_NO;
559 #else
560   GNUNET_free (p);
561   {
562     static int once; /* remember result from previous runs... */
563
564     if (0 == once)
565     {
566       rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
567       if (INVALID_SOCKET == rawsock)
568         {
569           DWORD err = GetLastError ();
570           
571           LOG (GNUNET_ERROR_TYPE_DEBUG,
572                "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n", err);
573           once = -1;
574           return GNUNET_NO;           /* not running as administrator */
575         }
576       once = 1;
577       closesocket (rawsock);
578     }
579     if (-1 == once)
580       return GNUNET_NO;
581     return GNUNET_YES;
582   }
583 #endif
584 }
585
586
587 /* end of os_installation.c */