merge branch 'refactoring-scheduler'
[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-program", __VA_ARGS__)
35
36 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-program", 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  * task run when the scheduler shuts down
73  */
74 static void
75 shutdown_task (void *cls)
76 {
77   GNUNET_SPEEDUP_stop_ ();
78 }
79
80
81 /**
82  * Initial task called by the scheduler for each
83  * program.  Runs the program-specific main task.
84  */
85 static void
86 program_main (void *cls)
87 {
88   struct CommandContext *cc = cls;
89
90   GNUNET_SPEEDUP_start_(cc->cfg);
91   GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
92   GNUNET_RESOLVER_connect (cc->cfg);
93   cc->task (cc->task_cls, cc->args, cc->cfgfile, cc->cfg);
94 }
95
96
97 /**
98  * Compare function for 'qsort' to sort command-line arguments by the
99  * short option.
100  *
101  * @param a1 first command line option
102  * @param a2 second command line option
103  */
104 static int
105 cmd_sorter (const void *a1, const void *a2)
106 {
107   const struct GNUNET_GETOPT_CommandLineOption *c1 = a1;
108   const struct GNUNET_GETOPT_CommandLineOption *c2 = a2;
109
110   if (toupper ((unsigned char) c1->shortName) >
111       toupper ((unsigned char) c2->shortName))
112     return 1;
113   if (toupper ((unsigned char) c1->shortName) <
114       toupper ((unsigned char) c2->shortName))
115     return -1;
116   if (c1->shortName > c2->shortName)
117     return 1;
118   if (c1->shortName < c2->shortName)
119     return -1;
120   return 0;
121 }
122
123
124 /**
125  * Run a standard GNUnet command startup sequence (initialize loggers
126  * and configuration, parse options).
127  *
128  * @param argc number of command line arguments in @a argv
129  * @param argv command line arguments
130  * @param binaryName our expected name
131  * @param binaryHelp help text for the program
132  * @param options command line options
133  * @param task main function to run
134  * @param task_cls closure for @a task
135  * @param run_without_scheduler #GNUNET_NO start the scheduler, #GNUNET_YES do not
136  *        start the scheduler just run the main task
137  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
138  */
139 int
140 GNUNET_PROGRAM_run2 (int argc, char *const *argv, const char *binaryName,
141                      const char *binaryHelp,
142                      const struct GNUNET_GETOPT_CommandLineOption *options,
143                      GNUNET_PROGRAM_Main task, void *task_cls,
144                      int run_without_scheduler)
145 {
146   struct CommandContext cc;
147 #if ENABLE_NLS
148   char *path;
149 #endif
150   char *loglev;
151   char *logfile;
152   char *cfg_fn;
153   const char *xdg;
154   int ret;
155   unsigned int cnt;
156   unsigned long long skew_offset;
157   unsigned long long skew_variance;
158   long long clock_offset;
159   struct GNUNET_CONFIGURATION_Handle *cfg;
160
161   struct GNUNET_GETOPT_CommandLineOption defoptions[] = {
162     GNUNET_GETOPT_option_cfgfile (&cc.cfgfile),
163     GNUNET_GETOPT_option_help (binaryHelp),
164     GNUNET_GETOPT_option_loglevel (&loglev),
165     GNUNET_GETOPT_option_logfile (&logfile),
166     GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION)
167   };
168   struct GNUNET_GETOPT_CommandLineOption *allopts;
169   const char *gargs;
170   char *lpfx;
171   char *spc;
172
173   logfile = NULL;
174   gargs = getenv ("GNUNET_ARGS");
175   if (NULL != gargs)
176   {
177     char **gargv;
178     unsigned int gargc;
179     int i;
180     char *tok;
181     char *cargs;
182
183     gargv = NULL;
184     gargc = 0;
185     for (i = 0; i < argc; i++)
186       GNUNET_array_append (gargv, gargc, GNUNET_strdup (argv[i]));
187     cargs = GNUNET_strdup (gargs);
188     for (tok = strtok (cargs, " "); NULL != tok; tok = strtok (NULL, " "))
189       GNUNET_array_append (gargv, gargc, GNUNET_strdup (tok));
190     GNUNET_free (cargs);
191     GNUNET_array_append (gargv, gargc, NULL);
192     argv = (char *const *) gargv;
193     argc = gargc - 1;
194   }
195   memset (&cc, 0, sizeof (cc));
196   loglev = NULL;
197   cc.task = task;
198   cc.task_cls = task_cls;
199   cc.cfg = cfg = GNUNET_CONFIGURATION_create ();
200   /* prepare */
201 #if ENABLE_NLS
202   setlocale (LC_ALL, "");
203   path = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LOCALEDIR);
204   if (NULL != path)
205   {
206     BINDTEXTDOMAIN ("GNUnet", path);
207     GNUNET_free (path);
208   }
209   textdomain ("GNUnet");
210 #endif
211   cnt = 0;
212   while (NULL != options[cnt].name)
213     cnt++;
214   allopts =
215       GNUNET_malloc ((cnt +
216                       1) * sizeof (struct GNUNET_GETOPT_CommandLineOption) +
217                      sizeof (defoptions));
218   GNUNET_memcpy (allopts, defoptions, sizeof (defoptions));
219   GNUNET_memcpy (&allopts
220           [sizeof (defoptions) /
221            sizeof (struct GNUNET_GETOPT_CommandLineOption)], options,
222           (cnt + 1) * sizeof (struct GNUNET_GETOPT_CommandLineOption));
223   cnt += sizeof (defoptions) / sizeof (struct GNUNET_GETOPT_CommandLineOption);
224   qsort (allopts, cnt, sizeof (struct GNUNET_GETOPT_CommandLineOption),
225          &cmd_sorter);
226   loglev = NULL;
227   xdg = getenv ("XDG_CONFIG_HOME");
228   if (NULL != xdg)
229     GNUNET_asprintf (&cfg_fn,
230                      "%s%s%s",
231                      xdg,
232                      DIR_SEPARATOR_STR,
233                      GNUNET_OS_project_data_get ()->config_file);
234   else
235     cfg_fn = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
236   lpfx = GNUNET_strdup (binaryName);
237   if (NULL != (spc = strstr (lpfx, " ")))
238     *spc = '\0';
239   ret = GNUNET_GETOPT_run (binaryName, allopts, (unsigned int) argc, argv);
240   if ((GNUNET_OK > ret) ||
241       (GNUNET_OK != GNUNET_log_setup (lpfx, loglev, logfile)))
242   {
243     GNUNET_free (allopts);
244     GNUNET_free (lpfx);
245     goto cleanup;
246   }
247   if (NULL == cc.cfgfile)
248     cc.cfgfile = GNUNET_strdup (cfg_fn);
249   if (GNUNET_YES ==
250       GNUNET_DISK_file_test (cc.cfgfile))
251   {
252     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, cc.cfgfile))
253     {
254       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
255                   _("Malformed configuration file `%s', exit ...\n"),
256                   cc.cfgfile);
257       ret = GNUNET_SYSERR;
258       GNUNET_free (allopts);
259       GNUNET_free (lpfx);
260       goto cleanup;
261     }
262   }
263   else
264   {
265     if (0 != strcmp (cc.cfgfile, cfg_fn))
266       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
267                   _("Could not access configuration file `%s'\n"),
268                   cc.cfgfile);
269     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL))
270     {
271       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
272                   _("Malformed configuration, exit ...\n"));
273       ret = GNUNET_SYSERR;
274       GNUNET_free (allopts);
275       GNUNET_free (lpfx);
276       goto cleanup;
277     }
278   }
279   GNUNET_free (allopts);
280   GNUNET_free (lpfx);
281   if (GNUNET_OK ==
282       GNUNET_CONFIGURATION_get_value_number (cc.cfg, "testing", "skew_offset",
283                                              &skew_offset) &&
284       (GNUNET_OK ==
285        GNUNET_CONFIGURATION_get_value_number (cc.cfg, "testing",
286                                               "skew_variance", &skew_variance)))
287   {
288     clock_offset = skew_offset - skew_variance;
289     GNUNET_TIME_set_offset (clock_offset);
290   }
291   /* ARM needs to know which configuration file to use when starting
292      services.  If we got a command-line option *and* if nothing is
293      specified in the configuration, remember the command-line option
294      in "cfg".  This is typically really only having an effect if we
295      are running code in src/arm/, as obviously the rest of the code
296      has little business with ARM-specific options. */
297   if (GNUNET_YES !=
298       GNUNET_CONFIGURATION_have_value (cfg,
299                                        "arm",
300                                        "CONFIG"))
301   {
302     GNUNET_CONFIGURATION_set_value_string (cfg,
303                                            "arm", "CONFIG",
304                                            cc.cfgfile);
305   }
306
307   /* run */
308   cc.args = &argv[ret];
309   if (GNUNET_NO == run_without_scheduler)
310   {
311     GNUNET_SCHEDULER_run (&program_main, &cc);
312   }
313   else
314   {
315     GNUNET_RESOLVER_connect (cc.cfg);
316     cc.task (cc.task_cls, cc.args, cc.cfgfile, cc.cfg);
317   }
318   ret = GNUNET_OK;
319  cleanup:
320   GNUNET_CONFIGURATION_destroy (cfg);
321   GNUNET_free_non_null (cc.cfgfile);
322   GNUNET_free (cfg_fn);
323   GNUNET_free_non_null (loglev);
324   GNUNET_free_non_null (logfile);
325   return ret;
326 }
327
328 /**
329  * Run a standard GNUnet command startup sequence (initialize loggers
330  * and configuration, parse options).
331  *
332  * @param argc number of command line arguments
333  * @param argv command line arguments
334  * @param binaryName our expected name
335  * @param binaryHelp help text for the program
336  * @param options command line options
337  * @param task main function to run
338  * @param task_cls closure for @a task
339  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
340  */
341 int
342 GNUNET_PROGRAM_run (int argc, char *const *argv,
343                     const char *binaryName,
344                     const char *binaryHelp,
345                     const struct GNUNET_GETOPT_CommandLineOption *options,
346                     GNUNET_PROGRAM_Main task,
347                     void *task_cls)
348 {
349   return GNUNET_PROGRAM_run2 (argc, argv,
350                               binaryName, binaryHelp,
351                               options,
352                               task, task_cls,
353                               GNUNET_NO);
354 }
355
356
357 /* end of program.c */