-always check that WE can execute
[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   f = FOPEN (fn, "r");
60   if (f == NULL)
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  * 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 static char *
135 get_path_from_NSGetExecutablePath ()
136 {
137   static char zero = '\0';
138   char *path;
139   size_t len;
140   MyNSGetExecutablePathProto func;
141   int ret;
142
143   path = NULL;
144   func =
145       (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath");
146   if (!func)
147     return NULL;
148   path = &zero;
149   len = 0;
150   /* get the path len, including the trailing \0 */
151   func (path, &len);
152   if (len == 0)
153     return NULL;
154   path = GNUNET_malloc (len);
155   ret = func (path, &len);
156   if (ret != 0)
157   {
158     GNUNET_free (path);
159     return NULL;
160   }
161   len = strlen (path);
162   while ((path[len] != '/') && (len > 0))
163     len--;
164   path[len] = '\0';
165   return path;
166 }
167
168 static char *
169 get_path_from_dyld_image ()
170 {
171   const char *path;
172   char *p, *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 (path != NULL && 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  * Return the actual path to a file found in the current
201  * PATH environment variable.
202  *
203  * @param binary the name of the file to find
204  * @return path to binary, NULL if not found
205  */
206 static char *
207 get_path_from_PATH (const char *binary)
208 {
209   char *path;
210   char *pos;
211   char *end;
212   char *buf;
213   const char *p;
214
215   p = getenv ("PATH");
216   if (p == NULL)
217     return NULL;
218   path = GNUNET_strdup (p);     /* because we write on it */
219   buf = GNUNET_malloc (strlen (path) + 20);
220   pos = path;
221   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
222   {
223     *end = '\0';
224     sprintf (buf, "%s/%s", pos, binary);
225     if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
226     {
227       pos = GNUNET_strdup (pos);
228       GNUNET_free (buf);
229       GNUNET_free (path);
230       return pos;
231     }
232     pos = end + 1;
233   }
234   sprintf (buf, "%s/%s", pos, binary);
235   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
236   {
237     pos = GNUNET_strdup (pos);
238     GNUNET_free (buf);
239     GNUNET_free (path);
240     return pos;
241   }
242   GNUNET_free (buf);
243   GNUNET_free (path);
244   return NULL;
245 }
246
247 static char *
248 get_path_from_GNUNET_PREFIX ()
249 {
250   const char *p;
251
252   p = getenv ("GNUNET_PREFIX");
253   if (p != NULL)
254     return GNUNET_strdup (p);
255   return NULL;
256 }
257
258 /**
259  * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
260  * @author Milan
261  *
262  * @return a pointer to the executable path, or NULL on error
263  */
264 static char *
265 os_get_gnunet_path ()
266 {
267   char *ret;
268
269   ret = get_path_from_GNUNET_PREFIX ();
270   if (ret != NULL)
271     return ret;
272 #if LINUX
273   ret = get_path_from_proc_maps ();
274   if (ret != NULL)
275     return ret;
276   ret = get_path_from_proc_exe ();
277   if (ret != NULL)
278     return ret;
279 #endif
280 #if WINDOWS
281   ret = get_path_from_module_filename ();
282   if (ret != NULL)
283     return ret;
284 #endif
285 #if DARWIN
286   ret = get_path_from_dyld_image ();
287   if (ret != NULL)
288     return ret;
289   ret = get_path_from_NSGetExecutablePath ();
290   if (ret != NULL)
291     return ret;
292 #endif
293   ret = get_path_from_PATH ("gnunet-arm");
294   if (ret != NULL)
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   ret = NULL;
316 #if LINUX
317   ret = get_path_from_proc_exe ();
318   if (ret != NULL)
319     return ret;
320 #endif
321 #if WINDOWS
322   ret = get_path_from_module_filename ();
323   if (ret != NULL)
324     return ret;
325 #endif
326 #if DARWIN
327   ret = get_path_from_NSGetExecutablePath ();
328   if (ret != NULL)
329     return ret;
330 #endif
331   /* other attempts here */
332   return ret;
333 }
334
335
336
337 /**
338  * @brief get the path to a specific GNUnet installation directory or,
339  * with GNUNET_IPK_SELF_PREFIX, the current running apps installation directory
340  * @author Milan
341  * @return a pointer to the dir path (to be freed by the caller)
342  */
343 char *
344 GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
345 {
346   size_t n;
347   const char *dirname;
348   char *execpath = NULL;
349   char *tmp;
350   int isbasedir;
351
352   /* if wanted, try to get the current app's bin/ */
353   if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
354     execpath = os_get_exec_path ();
355
356   /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
357    * guess for the current app */
358   if (execpath == NULL)
359     execpath = os_get_gnunet_path ();
360
361   if (execpath == NULL)
362     return NULL;
363
364   n = strlen (execpath);
365   if (n == 0)
366   {
367     /* should never happen, but better safe than sorry */
368     GNUNET_free (execpath);
369     return NULL;
370   }
371   /* remove filename itself */
372   while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
373     execpath[--n] = '\0';
374
375   isbasedir = 1;
376   if ((n > 5) &&
377       ((0 == strcasecmp (&execpath[n - 5], "lib32")) ||
378        (0 == strcasecmp (&execpath[n - 5], "lib64"))))
379   {
380     if (dirkind != GNUNET_OS_IPK_LIBDIR)
381     {
382       /* strip '/lib32' or '/lib64' */
383       execpath[n - 5] = '\0';
384       n -= 5;
385     }
386     else
387       isbasedir = 0;
388   }
389   else if ((n > 3) &&
390            ((0 == strcasecmp (&execpath[n - 3], "bin")) ||
391             (0 == strcasecmp (&execpath[n - 3], "lib"))))
392   {
393     /* strip '/bin' or '/lib' */
394     execpath[n - 3] = '\0';
395     n -= 3;
396   }
397   /* in case this was a directory named foo-bin, remove "foo-" */
398   while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
399     execpath[--n] = '\0';
400   switch (dirkind)
401   {
402   case GNUNET_OS_IPK_PREFIX:
403   case GNUNET_OS_IPK_SELF_PREFIX:
404     dirname = DIR_SEPARATOR_STR;
405     break;
406   case GNUNET_OS_IPK_BINDIR:
407     dirname = DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR;
408     break;
409   case GNUNET_OS_IPK_LIBDIR:
410     if (isbasedir)
411       dirname =
412           DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
413     else
414       dirname = DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
415     break;
416   case GNUNET_OS_IPK_DATADIR:
417     dirname =
418         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR;
419     break;
420   case GNUNET_OS_IPK_LOCALEDIR:
421     dirname =
422         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale" DIR_SEPARATOR_STR;
423     break;
424   case GNUNET_OS_IPK_ICONDIR:
425     dirname =
426         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR;
427     break;
428   case GNUNET_OS_IPK_DOCDIR:
429     dirname =
430         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "doc" DIR_SEPARATOR_STR \
431         "gnunet" DIR_SEPARATOR_STR;
432     break;
433   default:
434     GNUNET_free (execpath);
435     return NULL;
436   }
437   tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
438   sprintf (tmp, "%s%s", execpath, dirname);
439   GNUNET_free (execpath);
440   return tmp;
441 }
442
443
444 /**
445  * Check whether an executable exists and possibly
446  * if the suid bit is set on the file.
447  * Attempts to find the file using the current
448  * PATH environment variable as a search path.
449  *
450  * @param binary the name of the file to check
451  * @return GNUNET_YES if the file is SUID,
452  *         GNUNET_NO if not SUID (but binary exists)
453  *         GNUNET_SYSERR on error (no such binary or not executable)
454  */
455 int
456 GNUNET_OS_check_helper_binary (const char *binary)
457 {
458   struct stat statbuf;
459   char *p;
460   char *pf;
461
462 #ifdef MINGW
463   SOCKET rawsock;
464   char *binaryexe;
465
466   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
467   p = get_path_from_PATH (binaryexe);
468   if (p != NULL)
469   {
470     GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
471     GNUNET_free (p);
472     p = pf;
473   }
474   free (binaryexe);
475 #else
476   p = get_path_from_PATH (binary);
477   if (p != NULL)
478   {
479     GNUNET_asprintf (&pf, "%s/%s", p, binary);
480     GNUNET_free (p);
481     p = pf;
482   }
483 #endif
484   if (p == NULL)
485   {
486     LOG (GNUNET_ERROR_TYPE_INFO, _("Could not find binary `%s' in PATH!\n"),
487          binary);
488     return GNUNET_SYSERR;
489   }
490   if (0 != ACCESS (p, X_OK))
491   {
492     LOG (GNUNET_ERROR_TYPE_WARNING, _("access (%s, X_OK) failed: %s\n"), p,
493          STRERROR (errno));
494     GNUNET_free (p);
495     return GNUNET_SYSERR;
496   }
497   if (0 != STAT (p, &statbuf))
498   {
499     LOG (GNUNET_ERROR_TYPE_WARNING, _("stat (%s) failed: %s\n"), p,
500          STRERROR (errno));
501     GNUNET_free (p);
502     return GNUNET_SYSERR;
503   }
504 #ifndef MINGW
505   if ((0 != (statbuf.st_mode & S_ISUID)) && (statbuf.st_uid == 0))
506   {
507     GNUNET_free (p);
508     return GNUNET_YES;
509   }
510   GNUNET_free (p);
511   return GNUNET_SYSERR;
512 #else
513   GNUNET_free (p);
514   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
515   if (INVALID_SOCKET == rawsock)
516   {
517     DWORD err = GetLastError ();
518
519     LOG (GNUNET_ERROR_TYPE_INFO,
520          "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n", err);
521     return GNUNET_NO;           /* not running as administrator */
522   }
523   closesocket (rawsock);
524   return GNUNET_YES;
525 #endif
526 }
527
528
529 /* end of os_installation.c */