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