a313ce87e61eedf385c3998b8b3a4c3e3361633a
[oweals/gnunet.git] / src / util / program.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 GNUnet e.V.
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 3, 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 PURPROSE.  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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/program.c
23  * @brief standard code for GNUnet startup and shutdown
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_resolver_service.h"
30 #include "gnunet_constants.h"
31 #include "speedup.h"
32 #include <gcrypt.h>
33
34 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
35
36 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
37
38 /**
39  * Context for the command.
40  */
41 struct CommandContext
42 {
43   /**
44    * Argv argument.
45    */
46   char *const *args;
47
48   /**
49    * Name of the configuration file used, can be NULL!
50    */
51   char *cfgfile;
52
53   /**
54    * Main function to run.
55    */
56   GNUNET_PROGRAM_Main task;
57
58   /**
59    * Closure for @e task.
60    */
61   void *task_cls;
62
63   /**
64    * Configuration to use.
65    */
66   const struct GNUNET_CONFIGURATION_Handle *cfg;
67
68 };
69
70
71 /**
72  * Initial task called by the scheduler for each
73  * program.  Runs the program-specific main task.
74  */
75 static void
76 program_main (void *cls)
77 {
78   struct CommandContext *cc = cls;
79   const struct GNUNET_SCHEDULER_TaskContext *tc;
80
81   tc = GNUNET_SCHEDULER_get_task_context ();
82   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
83     return;
84   GNUNET_SPEEDUP_start_(cc->cfg);
85   GNUNET_RESOLVER_connect (cc->cfg);
86   cc->task (cc->task_cls, cc->args, cc->cfgfile, cc->cfg);
87 }
88
89
90 /**
91  * Compare function for 'qsort' to sort command-line arguments by the
92  * short option.
93  *
94  * @param a1 first command line option
95  * @param a2 second command line option
96  */
97 static int
98 cmd_sorter (const void *a1, const void *a2)
99 {
100   const struct GNUNET_GETOPT_CommandLineOption *c1 = a1;
101   const struct GNUNET_GETOPT_CommandLineOption *c2 = a2;
102
103   if (toupper ((unsigned char) c1->shortName) >
104       toupper ((unsigned char) c2->shortName))
105     return 1;
106   if (toupper ((unsigned char) c1->shortName) <
107       toupper ((unsigned char) c2->shortName))
108     return -1;
109   if (c1->shortName > c2->shortName)
110     return 1;
111   if (c1->shortName < c2->shortName)
112     return -1;
113   return 0;
114 }
115
116
117 /**
118  * Run a standard GNUnet command startup sequence (initialize loggers
119  * and configuration, parse options).
120  *
121  * @param argc number of command line arguments in @a argv
122  * @param argv command line arguments
123  * @param binaryName our expected name
124  * @param binaryHelp help text for the program
125  * @param options command line options
126  * @param task main function to run
127  * @param task_cls closure for @a task
128  * @param run_without_scheduler #GNUNET_NO start the scheduler, #GNUNET_YES do not
129  *        start the scheduler just run the main task
130  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
131  */
132 int
133 GNUNET_PROGRAM_run2 (int argc, char *const *argv, const char *binaryName,
134                      const char *binaryHelp,
135                      const struct GNUNET_GETOPT_CommandLineOption *options,
136                      GNUNET_PROGRAM_Main task, void *task_cls,
137                      int run_without_scheduler)
138 {
139   struct CommandContext cc;
140 #if ENABLE_NLS
141   char *path;
142 #endif
143   char *loglev;
144   char *logfile;
145   char *cfg_fn;
146   const char *xdg;
147   int ret;
148   unsigned int cnt;
149   unsigned long long skew_offset;
150   unsigned long long skew_variance;
151   long long clock_offset;
152   struct GNUNET_CONFIGURATION_Handle *cfg;
153
154   struct GNUNET_GETOPT_CommandLineOption defoptions[] = {
155     GNUNET_GETOPT_OPTION_CFG_FILE (&cc.cfgfile),
156     GNUNET_GETOPT_OPTION_HELP (binaryHelp),
157     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
158     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
159     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION " " VCS_VERSION)
160   };
161   struct GNUNET_GETOPT_CommandLineOption *allopts;
162   const char *gargs;
163   char *lpfx;
164   char *spc;
165
166   logfile = NULL;
167   gargs = getenv ("GNUNET_ARGS");
168   if (NULL != gargs)
169   {
170     char **gargv;
171     unsigned int gargc;
172     int i;
173     char *tok;
174     char *cargs;
175
176     gargv = NULL;
177     gargc = 0;
178     for (i = 0; i < argc; i++)
179       GNUNET_array_append (gargv, gargc, GNUNET_strdup (argv[i]));
180     cargs = GNUNET_strdup (gargs);
181     for (tok = strtok (cargs, " "); NULL != tok; tok = strtok (NULL, " "))
182       GNUNET_array_append (gargv, gargc, GNUNET_strdup (tok));
183     GNUNET_free (cargs);
184     GNUNET_array_append (gargv, gargc, NULL);
185     argv = (char *const *) gargv;
186     argc = gargc - 1;
187   }
188   memset (&cc, 0, sizeof (cc));
189   loglev = NULL;
190   cc.task = task;
191   cc.task_cls = task_cls;
192   cc.cfg = cfg = GNUNET_CONFIGURATION_create ();
193   /* prepare */
194 #if ENABLE_NLS
195   setlocale (LC_ALL, "");
196   path = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LOCALEDIR);
197   if (NULL != path)
198   {
199     BINDTEXTDOMAIN ("GNUnet", path);
200     GNUNET_free (path);
201   }
202   textdomain ("GNUnet");
203 #endif
204   cnt = 0;
205   while (NULL != options[cnt].name)
206     cnt++;
207   allopts =
208       GNUNET_malloc ((cnt +
209                       1) * sizeof (struct GNUNET_GETOPT_CommandLineOption) +
210                      sizeof (defoptions));
211   memcpy (allopts, defoptions, sizeof (defoptions));
212   memcpy (&allopts
213           [sizeof (defoptions) /
214            sizeof (struct GNUNET_GETOPT_CommandLineOption)], options,
215           (cnt + 1) * sizeof (struct GNUNET_GETOPT_CommandLineOption));
216   cnt += sizeof (defoptions) / sizeof (struct GNUNET_GETOPT_CommandLineOption);
217   qsort (allopts, cnt, sizeof (struct GNUNET_GETOPT_CommandLineOption),
218          &cmd_sorter);
219   loglev = NULL;
220   xdg = getenv ("XDG_CONFIG_HOME");
221   if (NULL != xdg)
222     GNUNET_asprintf (&cfg_fn,
223                      "%s%s%s",
224                      xdg,
225                      DIR_SEPARATOR_STR,
226                      GNUNET_OS_project_data_get ()->config_file);
227   else
228     cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
229   lpfx = GNUNET_strdup (binaryName);
230   if (NULL != (spc = strstr (lpfx, " ")))
231     *spc = '\0';
232   ret = GNUNET_GETOPT_run (binaryName, allopts, (unsigned int) argc, argv);
233   if ((GNUNET_OK > ret) ||
234       (GNUNET_OK != GNUNET_log_setup (lpfx, loglev, logfile)))
235   {
236     GNUNET_free (allopts);
237     GNUNET_free (lpfx);
238     goto cleanup;
239   }
240   if (NULL == cc.cfgfile)
241     cc.cfgfile = GNUNET_strdup (cfg_fn);
242   if (GNUNET_YES ==
243       GNUNET_DISK_file_test (cc.cfgfile))
244   {
245     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, cc.cfgfile))
246     {
247       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
248                   _("Malformed configuration file `%s', exit ...\n"),
249                   cc.cfgfile);
250       ret = GNUNET_SYSERR;
251       GNUNET_free (allopts);
252       GNUNET_free (lpfx);
253       goto cleanup;
254     }
255   }
256   else
257   {
258     if (0 != strcmp (cc.cfgfile, cfg_fn))
259       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
260                   _("Could not access configuration file `%s'\n"),
261                   cc.cfgfile);
262     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL))
263     {
264       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
265                   _("Malformed configuration, exit ...\n"));
266       ret = GNUNET_SYSERR;
267       GNUNET_free (allopts);
268       GNUNET_free (lpfx);
269       goto cleanup;
270     }
271   }
272   GNUNET_free (allopts);
273   GNUNET_free (lpfx);
274   if (GNUNET_OK ==
275       GNUNET_CONFIGURATION_get_value_number (cc.cfg, "testing", "skew_offset",
276                                              &skew_offset) &&
277       (GNUNET_OK ==
278        GNUNET_CONFIGURATION_get_value_number (cc.cfg, "testing",
279                                               "skew_variance", &skew_variance)))
280   {
281     clock_offset = skew_offset - skew_variance;
282     GNUNET_TIME_set_offset (clock_offset);
283   }
284   /* ARM needs to know which configuration file to use when starting
285      services.  If we got a command-line option *and* if nothing is
286      specified in the configuration, remember the command-line option
287      in "cfg".  This is typically really only having an effect if we
288      are running code in src/arm/, as obviously the rest of the code
289      has little business with ARM-specific options. */
290   if (GNUNET_YES !=
291       GNUNET_CONFIGURATION_have_value (cfg,
292                                        "arm",
293                                        "CONFIG"))
294   {
295     GNUNET_CONFIGURATION_set_value_string (cfg,
296                                            "arm", "CONFIG",
297                                            cc.cfgfile);
298   }
299
300   /* run */
301   cc.args = &argv[ret];
302   if (GNUNET_NO == run_without_scheduler)
303   {
304     GNUNET_SCHEDULER_run (&program_main, &cc);
305   }
306   else
307   {
308     GNUNET_RESOLVER_connect (cc.cfg);
309     cc.task (cc.task_cls, cc.args, cc.cfgfile, cc.cfg);
310   }
311   ret = GNUNET_OK;
312  cleanup:
313   GNUNET_SPEEDUP_stop_ ();
314   GNUNET_CONFIGURATION_destroy (cfg);
315   GNUNET_free_non_null (cc.cfgfile);
316   GNUNET_free (cfg_fn);
317   GNUNET_free_non_null (loglev);
318   GNUNET_free_non_null (logfile);
319   return ret;
320 }
321
322 /**
323  * Run a standard GNUnet command startup sequence (initialize loggers
324  * and configuration, parse options).
325  *
326  * @param argc number of command line arguments
327  * @param argv command line arguments
328  * @param binaryName our expected name
329  * @param binaryHelp help text for the program
330  * @param options command line options
331  * @param task main function to run
332  * @param task_cls closure for @a task
333  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
334  */
335 int
336 GNUNET_PROGRAM_run (int argc, char *const *argv,
337                     const char *binaryName,
338                     const char *binaryHelp,
339                     const struct GNUNET_GETOPT_CommandLineOption *options,
340                     GNUNET_PROGRAM_Main task,
341                     void *task_cls)
342 {
343   return GNUNET_PROGRAM_run2 (argc, argv,
344                               binaryName, binaryHelp,
345                               options,
346                               task, task_cls,
347                               GNUNET_NO);
348 }
349
350
351 /* end of program.c */