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