small API change: do no longer pass rarely needed GNUNET_SCHEDULER_TaskContext to...
[oweals/gnunet.git] / src / gns / gnunet-bcd.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 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 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file gns/gnunet-bcd.c
23  * @author Christian Grothoff
24  * @brief HTTP server to create GNS business cards
25  */
26
27 #include "platform.h"
28 #include <microhttpd.h>
29 #include "gnunet_util_lib.h"
30
31 /**
32  * Error page to display if submitted GNS key is invalid.
33  */
34 #define INVALID_GNSKEY "<html><head><title>Error</title><body>Invalid GNS public key given.</body></html>"
35
36 /**
37  * Error page to display on 404.
38  */
39 #define NOT_FOUND "<html><head><title>Error</title><body>404 not found</body></html>"
40
41 /**
42  * Handle to the HTTP server as provided by libmicrohttpd
43  */
44 static struct MHD_Daemon *daemon_handle;
45
46 /**
47  * Our configuration.
48  */
49 static const struct GNUNET_CONFIGURATION_Handle *cfg;
50
51 /**
52  * Our primary task for the HTTPD.
53  */
54 static struct GNUNET_SCHEDULER_Task * http_task;
55
56 /**
57  * Our main website.
58  */
59 static struct MHD_Response *main_response;
60
61 /**
62  * Error: invalid gns key.
63  */
64 static struct MHD_Response *invalid_gnskey_response;
65
66 /**
67  * Error: 404
68  */
69 static struct MHD_Response *not_found_response;
70
71 /**
72  * Absolute name of the 'gns-bcd.tex' file.
73  */
74 static char *resfile;
75
76 /**
77  * Port number.
78  */
79 static unsigned int port = 8888;
80
81
82 struct Entry
83 {
84   const char *formname;
85   const char *texname;
86 };
87
88
89 /**
90  * Main request handler.
91  */
92 static int
93 access_handler_callback (void *cls, struct MHD_Connection *connection,
94                          const char *url, const char *method,
95                          const char *version, const char *upload_data,
96                          size_t * upload_data_size, void **con_cls)
97 {
98   static int dummy;
99   static const struct Entry map[] = {
100     { "prefix", "prefix" },
101     { "name", "name" },
102     { "suffix", "suffix" },
103     { "street", "street" },
104     { "city", "city" },
105     { "phone", "phone" },
106     { "fax", "fax" },
107     { "email", "email"},
108     { "homepage", "homepage" },
109     { "orga", "orga"},
110     { "departmenti18n", "departmentde"},
111     { "departmenten", "departmenten"},
112     { "subdepartmenti18n", "subdepartmentde"},
113     { "subdepartmenten", "subdepartmenten"},
114     { "jobtitlei18n", "jobtitlegerman"},
115     { "jobtitleen", "jobtitleenglish"},
116     { "subdepartmenten", "subdepartmenten"},
117     { NULL, NULL }
118   };
119
120   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
121   {
122     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
123                 _("Refusing `%s' request to HTTP server\n"),
124                 method);
125     return MHD_NO;
126   }
127   if (NULL == *con_cls)
128   {
129     (*con_cls) = &dummy;
130     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
131                 "Sending 100 CONTINUE reply\n");
132     return MHD_YES;             /* send 100 continue */
133   }
134   if (0 == strcasecmp (url, "/"))
135     return MHD_queue_response (connection,
136                                MHD_HTTP_OK,
137                                main_response);
138   if (0 == strcasecmp (url, "/submit.pdf"))
139   {
140     unsigned int i;
141     char *p;
142     char *tmp;
143     char *deffile;
144     struct GNUNET_CRYPTO_EcdsaPublicKey pub;
145     size_t slen;
146     FILE *f;
147     struct stat st;
148     struct MHD_Response *response;
149     int fd;
150     int ret;
151
152     const char *gpg_fp = MHD_lookup_connection_value (connection,
153                                                       MHD_GET_ARGUMENT_KIND,
154                                                       "gpgfingerprint");
155     const char *gns_nick = MHD_lookup_connection_value (connection,
156                                                         MHD_GET_ARGUMENT_KIND,
157                                                         "gnsnick");
158     const char *gnskey = MHD_lookup_connection_value (connection,
159                                                       MHD_GET_ARGUMENT_KIND,
160                                                       "gnskey");
161     if ( (NULL == gnskey) ||
162          (GNUNET_OK !=
163           GNUNET_CRYPTO_ecdsa_public_key_from_string (gnskey,
164                                                       strlen (gnskey),
165                                                       &pub)))
166     {
167       return MHD_queue_response (connection,
168                                  MHD_HTTP_OK,
169                                  invalid_gnskey_response);
170     }
171     tmp = GNUNET_DISK_mkdtemp (gnskey);
172     if (NULL == tmp)
173     {
174       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mktemp", gnskey);
175       return MHD_NO;
176     }
177     GNUNET_asprintf (&deffile,
178                      "%s%s%s",
179                      tmp, DIR_SEPARATOR_STR, "def.tex");
180     f = FOPEN (deffile, "w");
181     if (NULL == f)
182     {
183       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", deffile);
184       GNUNET_free (deffile);
185       GNUNET_DISK_directory_remove (tmp);
186       GNUNET_free (tmp);
187       return MHD_NO;
188     }
189     for (i=0; NULL != map[i].formname; i++)
190     {
191       const char *val =  MHD_lookup_connection_value (connection,
192                                                       MHD_GET_ARGUMENT_KIND,
193                                                       map[i].formname);
194       if (NULL != val)
195         FPRINTF (f,
196                  "\\def\\%s{%s}\n",
197                  map[i].texname, val);
198       else
199         FPRINTF (f,
200                  "\\def\\%s{}\n",
201                  map[i].texname);
202     }
203     if (NULL != gpg_fp)
204     {
205       char *gpg1;
206       char *gpg2;
207
208       slen = strlen (gpg_fp);
209       gpg1 = GNUNET_strndup (gpg_fp, slen / 2);
210       gpg2 = GNUNET_strdup (&gpg_fp[slen / 2]);
211       FPRINTF (f,
212                "\\def\\gpglineone{%s}\n\\def\\gpglinetwo{%s}\n",
213                gpg1, gpg2);
214       GNUNET_free (gpg2);
215       GNUNET_free (gpg1);
216     }
217     FPRINTF (f,
218              "\\def\\gns{%s/%s}\n",
219              gnskey,
220              (NULL == gns_nick) ? "" : gns_nick);
221     FCLOSE (f);
222     GNUNET_asprintf (&p,
223                      "cd %s; cp %s gns-bcd.tex | pdflatex --enable-write18 gns-bcd.tex > /dev/null 2> /dev/null",
224                      tmp,
225                      resfile);
226     GNUNET_free (deffile);
227     ret = system (p);
228     if (WIFSIGNALED (ret) || (0 != WEXITSTATUS(ret)))
229       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
230                                 "system",
231                                 p);
232     GNUNET_asprintf (&deffile,
233                      "%s%s%s",
234                      tmp, DIR_SEPARATOR_STR, "gns-bcd.pdf");
235     fd = OPEN (deffile, O_RDONLY);
236     if (-1 == fd)
237     {
238       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
239                                 "open",
240                                 deffile);
241       GNUNET_free (deffile);
242       GNUNET_free (p);
243       GNUNET_DISK_directory_remove (tmp);
244       GNUNET_free (tmp);
245       return MHD_NO;
246     }
247     GNUNET_break (0 == STAT (deffile, &st));
248     if (NULL == (response = MHD_create_response_from_fd ((size_t) st.st_size, fd)))
249     {
250       GNUNET_break (0);
251       GNUNET_break (0 == CLOSE (fd));
252       GNUNET_free (deffile);
253       GNUNET_free (p);
254       GNUNET_DISK_directory_remove (tmp);
255       GNUNET_free (tmp);
256       return MHD_NO;
257     }
258     (void) MHD_add_response_header (response,
259                                     MHD_HTTP_HEADER_CONTENT_TYPE,
260                                     "application/pdf");
261     ret = MHD_queue_response (connection,
262                               MHD_HTTP_OK,
263                               response);
264     MHD_destroy_response (response);
265     GNUNET_free (deffile);
266     GNUNET_free (p);
267     GNUNET_DISK_directory_remove (tmp);
268     GNUNET_free (tmp);
269     return ret;
270   }
271   return MHD_queue_response (connection,
272                              MHD_HTTP_NOT_FOUND,
273                              not_found_response);
274 }
275
276
277 /**
278  * Function that queries MHD's select sets and
279  * starts the task waiting for them.
280  */
281 static struct GNUNET_SCHEDULER_Task *
282 prepare_daemon (struct MHD_Daemon *daemon_handle);
283
284
285 /**
286  * Call MHD to process pending requests and then go back
287  * and schedule the next run.
288  */
289 static void
290 run_daemon (void *cls)
291 {
292   struct MHD_Daemon *daemon_handle = cls;
293   const struct GNUNET_SCHEDULER_TaskContext *tc;
294
295   http_task = NULL;
296   tc = GNUNET_SCHEDULER_get_task_context ();
297   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
298     return;
299   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
300   http_task = prepare_daemon (daemon_handle);
301 }
302
303
304 /**
305  * Function that queries MHD's select sets and
306  * starts the task waiting for them.
307  */
308 static struct GNUNET_SCHEDULER_Task *
309 prepare_daemon (struct MHD_Daemon *daemon_handle)
310 {
311   struct GNUNET_SCHEDULER_Task * ret;
312   fd_set rs;
313   fd_set ws;
314   fd_set es;
315   struct GNUNET_NETWORK_FDSet *wrs;
316   struct GNUNET_NETWORK_FDSet *wws;
317   int max;
318   MHD_UNSIGNED_LONG_LONG timeout;
319   int haveto;
320   struct GNUNET_TIME_Relative tv;
321
322   FD_ZERO (&rs);
323   FD_ZERO (&ws);
324   FD_ZERO (&es);
325   wrs = GNUNET_NETWORK_fdset_create ();
326   wws = GNUNET_NETWORK_fdset_create ();
327   max = -1;
328   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
329   haveto = MHD_get_timeout (daemon_handle, &timeout);
330   if (haveto == MHD_YES)
331     tv.rel_value_us = (uint64_t) timeout * 1000LL;
332   else
333     tv = GNUNET_TIME_UNIT_FOREVER_REL;
334   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
335   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
336   ret =
337       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
338                                    tv, wrs, wws,
339                                    &run_daemon, daemon_handle);
340   GNUNET_NETWORK_fdset_destroy (wrs);
341   GNUNET_NETWORK_fdset_destroy (wws);
342   return ret;
343 }
344
345
346 /**
347  * Start server offering our hostlist.
348  *
349  * @return #GNUNET_OK on success
350  */
351 static int
352 server_start ()
353 {
354   if ((0 == port) || (port > UINT16_MAX))
355   {
356     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
357                 _("Invalid port number %llu.  Exiting.\n"),
358                 port);
359     return GNUNET_SYSERR;
360   }
361   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
362               _("Businesscard HTTP server starts on %llu\n"),
363               port);
364   daemon_handle = MHD_start_daemon (MHD_USE_DUAL_STACK | MHD_USE_DEBUG,
365                                     (uint16_t) port,
366                                     NULL /* accept_policy_callback */, NULL,
367                                     &access_handler_callback, NULL,
368                                     MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 512,
369                                     MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 2,
370                                     MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 60,
371                                     MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
372                                     MHD_OPTION_END);
373   if (NULL == daemon_handle)
374   {
375     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
376                 _("Could not start businesscard HTTP server on port %u\n"),
377                 (unsigned short) port);
378     return GNUNET_SYSERR;
379   }
380   http_task = prepare_daemon (daemon_handle);
381   return GNUNET_OK;
382 }
383
384
385 /**
386  * Stop HTTP server.
387  */
388 static void
389 server_stop (void *cls)
390 {
391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
392               "HTTP server shutdown\n");
393   if (NULL != http_task)
394   {
395     GNUNET_SCHEDULER_cancel (http_task);
396     http_task = NULL;
397   }
398   if (NULL != daemon_handle)
399   {
400     MHD_stop_daemon (daemon_handle);
401     daemon_handle = NULL;
402   }
403   if (NULL != main_response)
404   {
405     MHD_destroy_response (main_response);
406     main_response = NULL;
407   }
408   if (NULL != invalid_gnskey_response)
409   {
410     MHD_destroy_response (invalid_gnskey_response);
411     invalid_gnskey_response = NULL;
412   }
413   if (NULL != not_found_response)
414   {
415     MHD_destroy_response (not_found_response);
416     not_found_response = NULL;
417   }
418   if (NULL != resfile)
419   {
420     GNUNET_free (resfile);
421     resfile = NULL;
422   }
423 }
424
425
426 /**
427  * Main function that will be run.
428  *
429  * @param cls closure
430  * @param args remaining command-line arguments
431  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
432  * @param c configuration
433  */
434 static void
435 run (void *cls,
436      char *const *args,
437      const char *cfgfile,
438      const struct GNUNET_CONFIGURATION_Handle *c)
439 {
440   struct stat st;
441   char *dir;
442   char *fn;
443   int fd;
444
445   cfg = c;
446   dir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
447   GNUNET_assert (NULL != dir);
448   GNUNET_asprintf (&fn,
449                    "%s%s%s",
450                    dir,
451                    DIR_SEPARATOR_STR,
452                    "gns-bcd.html");
453   GNUNET_asprintf (&resfile,
454                    "%s%s%s",
455                    dir,
456                    DIR_SEPARATOR_STR,
457                    "gns-bcd.tex");
458   GNUNET_free (dir);
459   fd = OPEN (fn, O_RDONLY);
460   if (-1 == fd)
461   {
462     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
463                               "open",
464                               fn);
465     GNUNET_free (fn);
466     return;
467   }
468   if (0 != STAT (fn, &st))
469   {
470     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
471                               "open",
472                               fn);
473     GNUNET_free (fn);
474     CLOSE (fd);
475     return;
476   }
477   GNUNET_free (fn);
478   if (NULL == (main_response = MHD_create_response_from_fd ((size_t) st.st_size, fd)))
479   {
480     GNUNET_break (0);
481     GNUNET_break (0 == CLOSE (fd));
482     return;
483   }
484   (void) MHD_add_response_header (main_response,
485                                   MHD_HTTP_HEADER_CONTENT_TYPE,
486                                   "text/html");
487   invalid_gnskey_response = MHD_create_response_from_buffer (strlen (INVALID_GNSKEY),
488                                                              INVALID_GNSKEY,
489                                                              MHD_RESPMEM_PERSISTENT);
490   (void) MHD_add_response_header (invalid_gnskey_response,
491                                   MHD_HTTP_HEADER_CONTENT_TYPE,
492                                   "text/html");
493   not_found_response = MHD_create_response_from_buffer (strlen (NOT_FOUND),
494                                                         NOT_FOUND,
495                                                         MHD_RESPMEM_PERSISTENT);
496   (void) MHD_add_response_header (not_found_response,
497                                   MHD_HTTP_HEADER_CONTENT_TYPE,
498                                   "text/html");
499   if (GNUNET_OK !=
500       server_start ())
501     return;
502   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
503                                 &server_stop,
504                                 NULL);
505 }
506
507
508 /**
509  * The main function for gnunet-gns.
510  *
511  * @param argc number of arguments from the command line
512  * @param argv command line arguments
513  * @return 0 ok, 1 on error
514  */
515 int
516 main (int argc, char *const *argv)
517 {
518   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
519     {'p', "port", "PORT",
520       gettext_noop ("Run HTTP serve on port PORT (default is 8888)"), 1,
521       &GNUNET_GETOPT_set_uint, &port},
522     GNUNET_GETOPT_OPTION_END
523   };
524   int ret;
525
526   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
527     return 2;
528   GNUNET_log_setup ("gnunet-bcd", "WARNING", NULL);
529   ret =
530       (GNUNET_OK ==
531        GNUNET_PROGRAM_run (argc, argv, "gnunet-bcd",
532                            _("GNUnet HTTP server to create business cards"),
533                            options,
534                            &run, NULL)) ? 0 : 1;
535   GNUNET_free ((void*) argv);
536   return ret;
537 }
538
539
540 /* end of gnunet-bcd.c */