-dead
[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   unsigned int i;
198   int c;
199
200   c = _dyld_image_count ();
201   for (i = 0; i < c; i++)
202   {
203     if (_dyld_get_image_header (i) != &_mh_dylib_header)
204       continue;
205     path = _dyld_get_image_name (i);
206     if ( (NULL == path) || (0 == strlen (path)) )
207       continue;
208     p = GNUNET_strdup (path);
209     s = p + strlen (p);
210     while ((s > p) && ('/' != *s))
211       s--;
212     s++;
213     *s = '\0';
214     return p;
215   }
216   return NULL;
217 }
218 #endif
219
220
221 /**
222  * Return the actual path to a file found in the current
223  * PATH environment variable.
224  *
225  * @param binary the name of the file to find
226  * @return path to binary, NULL if not found
227  */
228 static char *
229 get_path_from_PATH (const char *binary)
230 {
231   char *path;
232   char *pos;
233   char *end;
234   char *buf;
235   const char *p;
236
237   if (NULL == (p = getenv ("PATH")))
238     return NULL;
239 #if WINDOWS
240   /* On W32 look in CWD first. */
241   GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p);
242 #else
243   path = GNUNET_strdup (p);     /* because we write on it */
244 #endif
245   buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1);
246   pos = path;
247   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
248   {
249     *end = '\0';
250     sprintf (buf, "%s/%s", pos, binary);
251     if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
252     {
253       pos = GNUNET_strdup (pos);
254       GNUNET_free (buf);
255       GNUNET_free (path);
256       return pos;
257     }
258     pos = end + 1;
259   }
260   sprintf (buf, "%s/%s", pos, binary);
261   if (GNUNET_YES == GNUNET_DISK_file_test (buf))
262   {
263     pos = GNUNET_strdup (pos);
264     GNUNET_free (buf);
265     GNUNET_free (path);
266     return pos;
267   }
268   GNUNET_free (buf);
269   GNUNET_free (path);
270   return NULL;
271 }
272
273
274 /**
275  * Try to obtain the installation path using the "GNUNET_PREFIX" environment
276  * variable.
277  *
278  * @return NULL on error (environment variable not set)
279  */
280 static char *
281 get_path_from_GNUNET_PREFIX ()
282 {
283   const char *p;
284
285   if (NULL != (p = getenv ("GNUNET_PREFIX")))
286     return GNUNET_strdup (p);
287   return NULL;
288 }
289
290
291 /**
292  * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
293  * @author Milan
294  *
295  * @return a pointer to the executable path, or NULL on error
296  */
297 static char *
298 os_get_gnunet_path ()
299 {
300   char *ret;
301
302   if (NULL != (ret = get_path_from_GNUNET_PREFIX ()))
303     return ret;
304 #if LINUX
305   if (NULL != (ret = get_path_from_proc_maps ()))
306     return ret;
307   if (NULL != (ret = get_path_from_proc_exe ()))
308     return ret;
309 #endif
310 #if WINDOWS
311   if (NULL != (ret = get_path_from_module_filename ()))
312     return ret;
313 #endif
314 #if DARWIN
315   if (NULL != (ret = get_path_from_dyld_image ()))
316     return ret;
317   if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
318     return ret;
319 #endif
320   if (NULL != (ret = get_path_from_PATH ("gnunet-arm")))
321     return ret;
322   /* other attempts here */
323   LOG (GNUNET_ERROR_TYPE_ERROR,
324        _
325        ("Could not determine installation path for %s.  Set `%s' environment variable.\n"),
326        "GNUnet", "GNUNET_PREFIX");
327   return NULL;
328 }
329
330
331 /**
332  * @brief get the path to current app's bin/
333  * @author Milan
334  *
335  * @return a pointer to the executable path, or NULL on error
336  */
337 static char *
338 os_get_exec_path ()
339 {
340   char *ret;
341
342 #if LINUX
343   if (NULL != (ret = get_path_from_proc_exe ()))
344     return ret;
345 #endif
346 #if WINDOWS
347   if (NULL != (ret = get_path_from_module_filename ()))
348     return ret;
349 #endif
350 #if DARWIN
351   if (NULL != (ret = get_path_from_NSGetExecutablePath ()))
352     return ret;
353 #endif
354   /* other attempts here */
355   return NULL;
356 }
357
358
359 /**
360  * @brief get the path to a specific GNUnet installation directory or,
361  * with GNUNET_IPK_SELF_PREFIX, the current running apps installation directory
362  * @author Milan
363  * @return a pointer to the dir path (to be freed by the caller)
364  */
365 char *
366 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
367 {
368   size_t n;
369   const char *dirname;
370   char *execpath = NULL;
371   char *tmp;
372   int isbasedir;
373
374   /* if wanted, try to get the current app's bin/ */
375   if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
376     execpath = os_get_exec_path ();
377
378   /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
379    * guess for the current app */
380   if (NULL == execpath)
381     execpath = os_get_gnunet_path ();
382
383   if (NULL == execpath)
384     return NULL;
385
386   n = strlen (execpath);
387   if (0 == n)
388   {
389     /* should never happen, but better safe than sorry */
390     GNUNET_free (execpath);
391     return NULL;
392   }
393   /* remove filename itself */
394   while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
395     execpath[--n] = '\0';
396
397   isbasedir = 1;
398   if ((n > 5) &&
399       ((0 == strcasecmp (&execpath[n - 5], "lib32")) ||
400        (0 == strcasecmp (&execpath[n - 5], "lib64"))))
401   {
402     if (GNUNET_OS_IPK_LIBDIR != dirkind)
403     {
404       /* strip '/lib32' or '/lib64' */
405       execpath[n - 5] = '\0';
406       n -= 5;
407     }
408     else
409       isbasedir = 0;
410   }
411   else if ((n > 3) &&
412            ((0 == strcasecmp (&execpath[n - 3], "bin")) ||
413             (0 == strcasecmp (&execpath[n - 3], "lib"))))
414   {
415     /* strip '/bin' or '/lib' */
416     execpath[n - 3] = '\0';
417     n -= 3;
418   }
419   /* in case this was a directory named foo-bin, remove "foo-" */
420   while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
421     execpath[--n] = '\0';
422   switch (dirkind)
423   {
424   case GNUNET_OS_IPK_PREFIX:
425   case GNUNET_OS_IPK_SELF_PREFIX:
426     dirname = DIR_SEPARATOR_STR;
427     break;
428   case GNUNET_OS_IPK_BINDIR:
429     dirname = DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR;
430     break;
431   case GNUNET_OS_IPK_LIBDIR:
432     if (isbasedir)
433       dirname =
434           DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
435     else
436       dirname = DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
437     break;
438   case GNUNET_OS_IPK_DATADIR:
439     dirname =
440         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
441     break;
442   case GNUNET_OS_IPK_LOCALEDIR:
443     dirname =
444         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR;
445     break;
446   case GNUNET_OS_IPK_ICONDIR:
447     dirname =
448         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR;
449     break;
450   case GNUNET_OS_IPK_DOCDIR:
451     dirname =
452         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR \
453         "gnunet" DIR_SEPARATOR_STR;
454     break;
455   default:
456     GNUNET_free (execpath);
457     return NULL;
458   }
459   tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
460   sprintf (tmp, "%s%s", execpath, dirname);
461   GNUNET_free (execpath);
462   return tmp;
463 }
464
465
466 /**
467  * Check whether an executable exists and possibly
468  * if the suid bit is set on the file.
469  * Attempts to find the file using the current
470  * PATH environment variable as a search path.
471  *
472  * @param binary the name of the file to check.
473  *        W32: must not have an .exe suffix.
474  * @return GNUNET_YES if the file is SUID,
475  *         GNUNET_NO if not SUID (but binary exists)
476  *         GNUNET_SYSERR on error (no such binary or not executable)
477  */
478 int
479 GNUNET_OS_check_helper_binary (const char *binary)
480 {
481   struct stat statbuf;
482   char *p;
483   char *pf;
484 #ifdef MINGW
485   SOCKET rawsock;
486   char *binaryexe;
487
488   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
489   if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO,
490                                                        NULL, NULL)) ||
491        (0 == strncmp (binary, "./", 2)) )
492     p = GNUNET_strdup (binaryexe);
493   else
494   {
495     p = get_path_from_PATH (binaryexe);
496     if (NULL != p)
497     {
498       GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
499       GNUNET_free (p);
500       p = pf;
501     }
502   }
503   GNUNET_free (binaryexe);
504 #else
505   if ( (GNUNET_YES == GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO,
506                                                        NULL, NULL)) ||
507        (0 == strncmp (binary, "./", 2)) )
508     p = GNUNET_strdup (binary);
509   else
510   {
511     p = get_path_from_PATH (binary);
512     if (NULL != p)
513     {
514       GNUNET_asprintf (&pf, "%s/%s", p, binary);
515       GNUNET_free (p);
516       p = pf;
517     }
518   }
519 #endif
520   if (NULL == p)
521   {
522     LOG (GNUNET_ERROR_TYPE_INFO, _("Could not find binary `%s' in PATH!\n"),
523          binary);
524     return GNUNET_SYSERR;
525   }
526   if (0 != ACCESS (p, X_OK))
527   {
528     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
529     GNUNET_free (p);
530     return GNUNET_SYSERR;
531   }
532 #ifndef MINGW
533   if (0 == getuid ())
534   {
535     /* as we run as root, we don't insist on SUID */
536     GNUNET_free (p);
537     return GNUNET_OK;
538   }
539 #endif
540   if (0 != STAT (p, &statbuf))
541   {
542     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
543     GNUNET_free (p);
544     return GNUNET_SYSERR;
545   }
546 #ifndef MINGW
547   if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
548   {
549     GNUNET_free (p);
550     return GNUNET_YES;
551   }
552   /* binary exists, but not SUID */
553   GNUNET_free (p);
554   return GNUNET_NO;
555 #else
556   GNUNET_free (p);
557   {
558     static int once; /* remember result from previous runs... */
559
560     if (0 == once)
561     {
562       rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
563       if (INVALID_SOCKET == rawsock)
564         {
565           DWORD err = GetLastError ();
566           
567           LOG (GNUNET_ERROR_TYPE_DEBUG,
568                "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n", err);
569           once = -1;
570           return GNUNET_NO;           /* not running as administrator */
571         }
572       once = 1;
573       closesocket (rawsock);
574     }
575     if (-1 == once)
576       return GNUNET_NO;
577     return GNUNET_YES;
578   }
579 #endif
580 }
581
582
583 /* end of os_installation.c */