implementing new scheduler shutdown semantics
[oweals/gnunet.git] / src / gns / test_gns_proxy.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2007, 2009, 2011, 2012 Christian Grothoff
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 test_gns_proxy.c
23  * @brief testcase for accessing SOCKS5 GNS proxy
24  * @author Martin Schanzenbach
25  */
26 #include "platform.h"
27 #if HAVE_CURL_CURL_H
28 #include <curl/curl.h>
29 #elif HAVE_GNURL_CURL_H
30 #include <gnurl/curl.h>
31 #endif
32 #include <microhttpd.h>
33 #include "gnunet_namestore_service.h"
34 #include "gnunet_gns_service.h"
35 #include "gnunet_testing_lib.h"
36 #include "gnunet_os_lib.h"
37
38 #define PORT 8080
39 #define TEST_DOMAIN "www.gnu"
40
41 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300)
42
43 /**
44  * Return value for 'main'.
45  */
46 static int global_ret;
47
48 static struct GNUNET_NAMESTORE_Handle *namestore;
49
50 static struct MHD_Daemon *mhd;
51
52 static struct GNUNET_SCHEDULER_Task * mhd_task_id;
53
54 static struct GNUNET_SCHEDULER_Task * curl_task_id;
55
56 static CURL *curl;
57
58 static CURLM *multi;
59
60 static char *url;
61
62 static struct GNUNET_OS_Process *proxy_proc;
63
64 static char* tmp_cfgfile;
65
66 struct CBC
67 {
68   char buf[1024];
69   size_t pos;
70 };
71
72 static struct CBC cbc;
73
74
75 static size_t
76 copy_buffer (void *ptr, size_t size, size_t nmemb, void *ctx)
77 {
78   struct CBC *cbc = ctx;
79
80   if (cbc->pos + size * nmemb > sizeof(cbc->buf))
81     return 0;                   /* overflow */
82   memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
83   cbc->pos += size * nmemb;
84   return size * nmemb;
85 }
86
87
88 static int
89 mhd_ahc (void *cls,
90           struct MHD_Connection *connection,
91           const char *url,
92           const char *method,
93           const char *version,
94           const char *upload_data, size_t *upload_data_size,
95           void **unused)
96 {
97   static int ptr;
98   struct MHD_Response *response;
99   int ret;
100
101   if (0 != strcmp ("GET", method))
102     return MHD_NO;              /* unexpected method */
103   if (&ptr != *unused)
104   {
105     *unused = &ptr;
106     return MHD_YES;
107   }
108   *unused = NULL;
109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MHD sends respose for request to URL `%s'\n", url);
110   response = MHD_create_response_from_buffer (strlen (url),
111                                               (void *) url,
112                                               MHD_RESPMEM_MUST_COPY);
113   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
114   MHD_destroy_response (response);
115   if (ret == MHD_NO)
116     abort ();
117   return ret;
118 }
119
120
121 static void
122 do_shutdown ()
123 {
124   if (mhd_task_id != NULL)
125   {
126     GNUNET_SCHEDULER_cancel (mhd_task_id);
127     mhd_task_id = NULL;
128   }
129   if (curl_task_id != NULL)
130   {
131     GNUNET_SCHEDULER_cancel (curl_task_id);
132     curl_task_id = NULL;
133   }
134   if (NULL != mhd)
135   {
136     MHD_stop_daemon (mhd);
137     mhd = NULL;
138   }
139   GNUNET_free_non_null (url);
140
141   if (NULL != tmp_cfgfile)
142     {
143       if (0 != remove (tmp_cfgfile))
144         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "remove", tmp_cfgfile);
145       GNUNET_free (tmp_cfgfile);
146       tmp_cfgfile = NULL;
147     }
148   if (NULL != proxy_proc)
149     {
150       (void) GNUNET_OS_process_kill (proxy_proc, SIGKILL);
151       GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (proxy_proc));
152       GNUNET_OS_process_destroy (proxy_proc);
153       proxy_proc = NULL;
154     }
155   url = NULL;
156   GNUNET_SCHEDULER_shutdown ();
157 }
158
159
160 /**
161  * Function to run the HTTP client.
162  */
163 static void
164 curl_main (void);
165
166
167 static void
168 curl_task (void *cls)
169 {
170   curl_task_id = NULL;
171   curl_main ();
172 }
173
174
175 static void
176 curl_main ()
177 {
178   fd_set rs;
179   fd_set ws;
180   fd_set es;
181   int max;
182   struct GNUNET_NETWORK_FDSet nrs;
183   struct GNUNET_NETWORK_FDSet nws;
184   struct GNUNET_TIME_Relative delay;
185   long timeout;
186   int running;
187   struct CURLMsg *msg;
188
189   max = 0;
190   FD_ZERO (&rs);
191   FD_ZERO (&ws);
192   FD_ZERO (&es);
193   curl_multi_perform (multi, &running);
194   if (running == 0)
195   {
196     GNUNET_assert (NULL != (msg = curl_multi_info_read (multi, &running)));
197     if (msg->msg == CURLMSG_DONE)
198     {
199       if (msg->data.result != CURLE_OK)
200       {
201         fprintf (stderr,
202                  "%s failed at %s:%d: `%s'\n",
203                  "curl_multi_perform",
204                 __FILE__,
205                 __LINE__, curl_easy_strerror (msg->data.result));
206         global_ret = 1;
207       }
208     }
209     curl_multi_remove_handle (multi, curl);
210     curl_multi_cleanup (multi);
211     curl_easy_cleanup (curl);
212     curl = NULL;
213     multi = NULL;
214     if (cbc.pos != strlen ("/hello_world"))
215     {
216       GNUNET_break (0);
217       global_ret = 2;
218     }
219     if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
220     {
221       GNUNET_break (0);
222       global_ret = 3;
223     }
224     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download complete, shutting down!\n");
225     do_shutdown ();
226     return;
227   }
228   GNUNET_assert (CURLM_OK == curl_multi_fdset (multi, &rs, &ws, &es, &max));
229   if ( (CURLM_OK != curl_multi_timeout (multi, &timeout)) ||
230        (-1 == timeout) )
231     delay = GNUNET_TIME_UNIT_SECONDS;
232   else
233     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, (unsigned int) timeout);
234   GNUNET_NETWORK_fdset_copy_native (&nrs,
235                                     &rs,
236                                     max + 1);
237   GNUNET_NETWORK_fdset_copy_native (&nws,
238                                     &ws,
239                                     max + 1);
240   curl_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
241                                               delay,
242                                               &nrs,
243                                               &nws,
244                                               &curl_task,
245                                               NULL);
246 }
247
248
249 static void
250 start_curl (void *cls)
251 {
252   GNUNET_asprintf (&url,
253                    "http://%s:%d/hello_world",
254                    TEST_DOMAIN, PORT);
255   curl = curl_easy_init ();
256   curl_easy_setopt (curl, CURLOPT_URL, url);
257   curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, &copy_buffer);
258   curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbc);
259   curl_easy_setopt (curl, CURLOPT_FAILONERROR, 1);
260   curl_easy_setopt (curl, CURLOPT_TIMEOUT, 150L);
261   curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, 15L);
262   curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1);
263   curl_easy_setopt (curl, CURLOPT_PROXY, "socks5h://127.0.0.1:7777");
264
265   multi = curl_multi_init ();
266   GNUNET_assert (multi != NULL);
267   GNUNET_assert (CURLM_OK == curl_multi_add_handle (multi, curl));
268   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Beginning HTTP download from `%s'\n", url);
269   curl_main ();
270 }
271
272
273 static void
274 disco_ns (void* cls)
275 {
276   GNUNET_NAMESTORE_disconnect (namestore);
277 }
278
279
280 /**
281  * Callback invoked from the namestore service once record is
282  * created.
283  *
284  * @param cls closure
285  * @param af address family, AF_INET or AF_INET6; AF_UNSPEC on error;
286  *                will match 'result_af' from the request
287  * @param address IP address (struct in_addr or struct in_addr6, depending on 'af')
288  *                that the VPN allocated for the redirection;
289  *                traffic to this IP will now be redirected to the
290  *                specified target peer; NULL on error
291  */
292 static void
293 commence_testing (void *cls,
294                   int32_t success,
295                   const char *emsg)
296 {
297   GNUNET_SCHEDULER_add_now (&disco_ns, NULL);
298
299   if ( (emsg != NULL) && (GNUNET_YES != success) )
300   {
301     fprintf (stderr,
302              "NS failed to create record %s\n",
303              emsg);
304     GNUNET_SCHEDULER_shutdown ();
305     return;
306   }
307
308   curl_task_id =
309     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, 
310                                   &start_curl, NULL);
311 }
312
313
314 /**
315  * Function to keep the HTTP server running.
316  */
317 static void
318 mhd_main (void);
319
320
321 static void
322 mhd_task (void *cls)
323 {
324   mhd_task_id = NULL;
325   MHD_run (mhd);
326   mhd_main ();
327 }
328
329
330 static void
331 mhd_main ()
332 {
333   struct GNUNET_NETWORK_FDSet nrs;
334   struct GNUNET_NETWORK_FDSet nws;
335   fd_set rs;
336   fd_set ws;
337   fd_set es;
338   int max_fd;
339   unsigned MHD_LONG_LONG timeout;
340   struct GNUNET_TIME_Relative delay;
341
342   GNUNET_assert (NULL == mhd_task_id);
343   FD_ZERO (&rs);
344   FD_ZERO (&ws);
345   FD_ZERO (&es);
346   max_fd = -1;
347   GNUNET_assert (MHD_YES ==
348                  MHD_get_fdset (mhd, &rs, &ws, &es, &max_fd));
349   if (MHD_YES == MHD_get_timeout (mhd, &timeout))
350     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
351                                            (unsigned int) timeout);
352   else
353     delay = GNUNET_TIME_UNIT_FOREVER_REL;
354   GNUNET_NETWORK_fdset_copy_native (&nrs,
355                                     &rs,
356                                     max_fd + 1);
357   GNUNET_NETWORK_fdset_copy_native (&nws,
358                                     &ws,
359                                     max_fd + 1);
360   mhd_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
361                                              delay,
362                                              &nrs,
363                                              &nws,
364                                              &mhd_task,
365                                              NULL);
366 }
367
368 static void
369 run (void *cls,
370      const struct GNUNET_CONFIGURATION_Handle *cfg,
371      struct GNUNET_TESTING_Peer *peer)
372 {
373   enum MHD_FLAG flags;
374   struct GNUNET_CRYPTO_EcdsaPrivateKey *host_key;
375   struct GNUNET_GNSRECORD_Data rd;
376   char *zone_keyfile;
377
378   namestore = GNUNET_NAMESTORE_connect (cfg);
379   GNUNET_assert (NULL != namestore);
380   flags = MHD_USE_DEBUG;
381   mhd = MHD_start_daemon (flags,
382                           PORT,
383                           NULL, NULL,
384                           &mhd_ahc, NULL,
385                           MHD_OPTION_END);
386   GNUNET_assert (NULL != mhd);
387   mhd_main ();
388
389   tmp_cfgfile = GNUNET_DISK_mktemp ("test_gns_proxy_tmp.conf");
390   if (NULL == tmp_cfgfile)
391   {
392     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
393                 "Failed to create tmp cfg!\n");
394     do_shutdown ();
395     return;
396   }
397
398   if (GNUNET_OK != GNUNET_CONFIGURATION_write ((struct GNUNET_CONFIGURATION_Handle *)cfg,
399                               tmp_cfgfile))
400   {
401     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
402                 "Failed to write tmp cfg\n");
403     do_shutdown ();
404     return;
405   }
406
407   proxy_proc = GNUNET_OS_start_process (GNUNET_NO,
408                                         GNUNET_OS_INHERIT_STD_ALL,
409                                         NULL,
410                                         NULL,
411                                         NULL,
412                                         "gnunet-gns-proxy",
413                                         "gnunet-gns-proxy",
414                                         "-c", tmp_cfgfile, NULL);
415
416   if (NULL == proxy_proc)
417   {
418     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
419                 "Unable to start proxy\n");
420     do_shutdown ();
421     return;
422   }
423
424   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
425                                                             "ZONEKEY",
426                                                             &zone_keyfile))
427   {
428     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to get key from cfg\n");
429     return;
430   }
431
432   host_key = GNUNET_CRYPTO_ecdsa_key_create_from_file (zone_keyfile);
433   rd.expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
434   GNUNET_assert (GNUNET_OK == GNUNET_GNSRECORD_string_to_value (GNUNET_DNSPARSER_TYPE_A,
435                                                                "127.0.0.1",
436                                                                (void**)&rd.data,
437                                                                &rd.data_size));
438   rd.record_type = GNUNET_DNSPARSER_TYPE_A;
439
440   GNUNET_NAMESTORE_record_create (namestore,
441                                   host_key,
442                                   "www",
443                                   &rd,
444                                   &commence_testing,
445                                   NULL);
446
447   GNUNET_free ((void**)rd.data);
448   GNUNET_free (zone_keyfile);
449   GNUNET_free (host_key);
450 }
451
452 int
453 main (int argc, char *const *argv)
454 {
455   char *binary;
456
457   if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary ("gnunet-gns-proxy", GNUNET_NO, NULL))
458   {
459     fprintf (stderr, "Proxy binary not in PATH... skipping!\n");
460     return 0;
461   }
462   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-dns");
463   if (GNUNET_YES != GNUNET_OS_check_helper_binary (binary, GNUNET_YES, NULL)) // TODO: once we have a windows-testcase, add test parameters here
464   {
465     fprintf (stderr, "DNS helper binary has wrong permissions... skipping!\n");
466     GNUNET_free (binary);
467     return 0;
468   }
469     GNUNET_free (binary);
470
471   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
472   {
473     fprintf (stderr, "failed to initialize curl\n");
474     return 2;
475   }
476   if (0 != GNUNET_TESTING_peer_run ("test-gnunet-gns-proxy",
477                                     "test_gns_proxy.conf",
478                                     &run, NULL))
479     return 1;
480   GNUNET_DISK_directory_remove ("/tmp/gnunet-test-gns-proxy");
481   return global_ret;
482 }
483
484 /* end of test_gns_vpn.c */