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