check vspnrintf return value, stack-allocate log buffer
[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",
66                    dir)) && (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   char path[4097];
116   char *idx;
117
118   GetModuleFileName (NULL, path, sizeof (path) - 1);
119   idx = path + strlen (path);
120   while ((idx > path) && (*idx != '\\') && (*idx != '/'))
121     idx--;
122   *idx = '\0';
123   return GNUNET_strdup (path);
124 }
125 #endif
126
127 #if DARWIN
128 typedef int (*MyNSGetExecutablePathProto) (char *buf, size_t * bufsize);
129
130 static char *
131 get_path_from_NSGetExecutablePath ()
132 {
133   static char zero = '\0';
134   char *path;
135   size_t len;
136   MyNSGetExecutablePathProto func;
137   int ret;
138
139   path = NULL;
140   func =
141     (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, "_NSGetExecutablePath");
142   if (!func)
143     return NULL;
144   path = &zero;
145   len = 0;
146   /* get the path len, including the trailing \0 */
147   func (path, &len);
148   if (len == 0)
149     return NULL;
150   path = GNUNET_malloc (len);
151   ret = func (path, &len);
152   if (ret != 0)
153     {
154       GNUNET_free (path);
155       return NULL;
156     }
157   len = strlen (path);
158   while ((path[len] != '/') && (len > 0))
159     len--;
160   path[len] = '\0';
161   return path;
162 }
163
164 static char *
165 get_path_from_dyld_image ()
166 {
167   const char *path;
168   char *p, *s;
169   int i;
170   int c;
171
172   p = NULL;
173   c = _dyld_image_count ();
174   for (i = 0; i < c; i++)
175     {
176       if (_dyld_get_image_header (i) == &_mh_dylib_header)
177         {
178           path = _dyld_get_image_name (i);
179           if (path != NULL && strlen (path) > 0)
180             {
181               p = strdup (path);
182               s = p + strlen (p);
183               while ((s > p) && (*s != '/'))
184                 s--;
185               s++;
186               *s = '\0';
187             }
188           break;
189         }
190     }
191   return p;
192 }
193 #endif
194
195 /**
196  * Return the actual path to a file found in the current
197  * PATH environment variable.
198  *
199  * @param binary the name of the file to find
200  * @return path to binary, NULL if not found
201  */
202 static char *
203 get_path_from_PATH (const char *binary)
204 {
205   char *path;
206   char *pos;
207   char *end;
208   char *buf;
209   const char *p;
210
211   p = getenv ("PATH");
212   if (p == NULL)
213     return NULL;
214   path = GNUNET_strdup (p);     /* because we write on it */
215   buf = GNUNET_malloc (strlen (path) + 20);
216   pos = path;
217   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
218     {
219       *end = '\0';
220       sprintf (buf, "%s/%s", pos, binary);
221       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
222         {
223           pos = GNUNET_strdup (pos);
224           GNUNET_free (buf);
225           GNUNET_free (path);
226           return pos;
227         }
228       pos = end + 1;
229     }
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   GNUNET_free (buf);
239   GNUNET_free (path);
240   return NULL;
241 }
242
243 static char *
244 get_path_from_GNUNET_PREFIX ()
245 {
246   const char *p;
247
248   p = getenv ("GNUNET_PREFIX");
249   if (p != NULL)
250     return GNUNET_strdup (p);
251   return NULL;
252 }
253
254 /*
255  * @brief get the path to GNUnet bin/ or lib/, prefering the lib/ path
256  * @author Milan
257  *
258  * @return a pointer to the executable path, or NULL on error
259  */
260 static char *
261 os_get_gnunet_path ()
262 {
263   char *ret;
264
265   ret = get_path_from_GNUNET_PREFIX ();
266   if (ret != NULL)
267     return ret;
268 #if LINUX
269   ret = get_path_from_proc_maps ();
270   if (ret != NULL)
271     return ret;
272   ret = get_path_from_proc_exe ();
273   if (ret != NULL)
274     return ret;
275 #endif
276 #if WINDOWS
277   ret = get_path_from_module_filename ();
278   if (ret != NULL)
279     return ret;
280 #endif
281 #if DARWIN
282   ret = get_path_from_dyld_image ();
283   if (ret != NULL)
284     return ret;
285   ret = get_path_from_NSGetExecutablePath ();
286   if (ret != NULL)
287     return ret;
288 #endif
289   ret = get_path_from_PATH ("gnunet-arm");
290   if (ret != NULL)
291     return ret;
292   /* other attempts here */
293   LOG (GNUNET_ERROR_TYPE_ERROR,
294        _
295        ("Could not determine installation path for %s.  Set `%s' environment variable.\n"),
296        "GNUnet", "GNUNET_PREFIX");
297   return NULL;
298 }
299
300 /*
301  * @brief get the path to current app's bin/
302  * @author Milan
303  *
304  * @return a pointer to the executable path, or NULL on error
305  */
306 static char *
307 os_get_exec_path ()
308 {
309   char *ret;
310
311   ret = NULL;
312 #if LINUX
313   ret = get_path_from_proc_exe ();
314   if (ret != NULL)
315     return ret;
316 #endif
317 #if WINDOWS
318   ret = get_path_from_module_filename ();
319   if (ret != NULL)
320     return ret;
321 #endif
322 #if DARWIN
323   ret = get_path_from_NSGetExecutablePath ();
324   if (ret != NULL)
325     return ret;
326 #endif
327   /* other attempts here */
328   return ret;
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 (execpath == NULL)
355     execpath = os_get_gnunet_path ();
356
357   if (execpath == NULL)
358     return NULL;
359
360   n = strlen (execpath);
361   if (n == 0)
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) && (execpath[n - 1] == DIR_SEPARATOR))
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 (dirkind != GNUNET_OS_IPK_LIBDIR)
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"
409           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"
416         DIR_SEPARATOR_STR;
417       break;
418     case GNUNET_OS_IPK_LOCALEDIR:
419       dirname =
420         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "locale"
421         DIR_SEPARATOR_STR;
422       break;
423     case GNUNET_OS_IPK_ICONDIR:
424       dirname =
425         DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "icons" DIR_SEPARATOR_STR;
426       break;
427     default:
428       GNUNET_free (execpath);
429       return NULL;
430     }
431   tmp = GNUNET_malloc (strlen (execpath) + strlen (dirname) + 1);
432   sprintf (tmp, "%s%s", execpath, dirname);
433   GNUNET_free (execpath);
434   return tmp;
435 }
436
437
438 /**
439  * Check whether an executable exists and possibly
440  * if the suid bit is set on the file.
441  * Attempts to find the file using the current
442  * PATH environment variable as a search path.
443  *
444  * @param binary the name of the file to check
445  * @return GNUNET_YES if the file is SUID,
446  *         GNUNET_NO if not SUID (but binary exists)
447  *         GNUNET_SYSERR on error (no such binary or not executable)
448  */
449 int
450 GNUNET_OS_check_helper_binary (const char *binary)
451 {
452   struct stat statbuf;
453   char *p;
454   char *pf;
455
456 #ifdef MINGW
457   SOCKET rawsock;
458   char *binaryexe;
459
460   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
461   p = get_path_from_PATH (binaryexe);
462   if (p != NULL)
463     {
464       GNUNET_asprintf (&pf, "%s/%s", p, binaryexe);
465       GNUNET_free (p);
466       p = pf;
467     }
468   free (binaryexe);
469 #else
470   p = get_path_from_PATH (binary);
471   if (p != NULL)
472     {
473       GNUNET_asprintf (&pf, "%s/%s", p, binary);
474       GNUNET_free (p);
475       p = pf;
476     }
477 #endif
478   if (p == NULL)
479     {
480       LOG (GNUNET_ERROR_TYPE_INFO,
481            _("Could not find binary `%s' in PATH!\n"), binary);
482       return GNUNET_SYSERR;
483     }
484   if (0 != STAT (p, &statbuf))
485     {
486       LOG (GNUNET_ERROR_TYPE_WARNING, _("stat (%s) failed: %s\n"), p,
487            STRERROR (errno));
488       GNUNET_free (p);
489       return GNUNET_SYSERR;
490     }
491 #ifndef MINGW
492   if ((0 != (statbuf.st_mode & S_ISUID)) && (statbuf.st_uid == 0))
493     {
494       GNUNET_free (p);
495       return GNUNET_YES;
496     }
497   if (0 == ACCESS (p, X_OK))
498     {
499       GNUNET_free (p);
500       return GNUNET_NO;
501     }
502   GNUNET_free (p);
503   return GNUNET_SYSERR;
504 #else
505   GNUNET_free (p);
506   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
507   if (INVALID_SOCKET == rawsock)
508     {
509       DWORD err = GetLastError ();
510
511       LOG (GNUNET_ERROR_TYPE_INFO,
512            "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n",
513            err);
514       return GNUNET_NO;         /* not running as administrator */
515     }
516   closesocket (rawsock);
517   return GNUNET_YES;
518 #endif
519 }
520
521
522 /* end of os_installation.c */