changing time measurement from milliseconds to microseconds
[oweals/gnunet.git] / src / pt / test_gns_vpn.c
1 /*
2      This file is part of GNUnet
3      (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 2, 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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file test_gns_vpn.c
23  * @brief testcase for accessing VPN services via GNS
24  * @author Martin Schanzenbach
25  */
26 #include "platform.h"
27 #include <curl/curl.h>
28 #include <microhttpd.h>
29 #include "gnunet_namestore_service.h"
30 #include "gnunet_gns_service.h"
31 #include "gnunet_testing_lib.h"
32
33 #define PORT 8080
34 #define TEST_DOMAIN "www.gads"
35
36 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300)
37
38 /**
39  * Return value for 'main'.
40  */
41 static int global_ret;
42
43 static struct GNUNET_NAMESTORE_Handle *namestore;
44
45 static struct MHD_Daemon *mhd;
46
47 static GNUNET_SCHEDULER_TaskIdentifier mhd_task_id;
48
49 static GNUNET_SCHEDULER_TaskIdentifier curl_task_id;
50
51 static CURL *curl;
52
53 static CURLM *multi;
54
55 static char *url;
56
57 /**
58  * IP address of the ultimate destination.
59  */
60 static const char *dest_ip;
61
62 /**
63  * Address family of the dest_ip.
64  */
65 static int dest_af;
66
67 /**
68  * Address family to use by the curl client.
69  */
70 static int src_af;
71
72 static int use_v6;
73
74
75 struct CBC
76 {
77   char buf[1024];
78   size_t pos;
79 };
80
81 static struct CBC cbc;
82
83
84 static size_t
85 copy_buffer (void *ptr, size_t size, size_t nmemb, void *ctx)
86 {
87   struct CBC *cbc = ctx;
88
89   if (cbc->pos + size * nmemb > sizeof(cbc->buf))
90     return 0;                   /* overflow */
91   memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
92   cbc->pos += size * nmemb;
93   return size * nmemb;
94 }
95
96
97 static int
98 mhd_ahc (void *cls,
99           struct MHD_Connection *connection,
100           const char *url,
101           const char *method,
102           const char *version,
103           const char *upload_data, size_t *upload_data_size,
104           void **unused)
105 {
106   static int ptr;
107   struct MHD_Response *response;
108   int ret;
109
110   if (0 != strcmp ("GET", method))
111     return MHD_NO;              /* unexpected method */
112   if (&ptr != *unused)
113   {
114     *unused = &ptr;
115     return MHD_YES;
116   }
117   *unused = NULL;
118   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MHD sends respose for request to URL `%s'\n", url);
119   response = MHD_create_response_from_buffer (strlen (url),
120                                               (void *) url,
121                                               MHD_RESPMEM_MUST_COPY);
122   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
123   MHD_destroy_response (response);
124   if (ret == MHD_NO)
125     abort ();
126   return ret;
127 }
128
129
130 static void
131 do_shutdown ()
132 {
133   if (mhd_task_id != GNUNET_SCHEDULER_NO_TASK)
134   {
135     GNUNET_SCHEDULER_cancel (mhd_task_id);
136     mhd_task_id = GNUNET_SCHEDULER_NO_TASK;
137   }
138   if (curl_task_id != GNUNET_SCHEDULER_NO_TASK)
139   {
140     GNUNET_SCHEDULER_cancel (curl_task_id);
141     curl_task_id = GNUNET_SCHEDULER_NO_TASK;
142   }
143   if (NULL != mhd)
144   {
145     MHD_stop_daemon (mhd);
146     mhd = NULL;
147   }
148   GNUNET_free_non_null (url);
149   url = NULL;
150 }
151
152
153 /**
154  * Function to run the HTTP client.
155  */
156 static void
157 curl_main (void);
158
159
160 static void
161 curl_task (void *cls,
162           const struct GNUNET_SCHEDULER_TaskContext *tc)
163 {
164   curl_task_id = GNUNET_SCHEDULER_NO_TASK;
165   curl_main ();
166 }
167
168
169 static void
170 curl_main ()
171 {
172   fd_set rs;
173   fd_set ws;
174   fd_set es;
175   int max;
176   struct GNUNET_NETWORK_FDSet nrs;
177   struct GNUNET_NETWORK_FDSet nws;
178   struct GNUNET_TIME_Relative delay;
179   long timeout;
180   int running;
181   struct CURLMsg *msg;
182
183   max = 0;
184   FD_ZERO (&rs);
185   FD_ZERO (&ws);
186   FD_ZERO (&es);
187   curl_multi_perform (multi, &running);
188   if (running == 0)
189   {
190     GNUNET_assert (NULL != (msg = curl_multi_info_read (multi, &running)));
191     if (msg->msg == CURLMSG_DONE)
192     {
193       if (msg->data.result != CURLE_OK)
194       {
195         fprintf (stderr,
196                  "%s failed at %s:%d: `%s'\n",
197                  "curl_multi_perform",
198                 __FILE__,
199                 __LINE__, curl_easy_strerror (msg->data.result));
200         global_ret = 1;
201       }
202     }
203     curl_multi_remove_handle (multi, curl);
204     curl_multi_cleanup (multi);
205     curl_easy_cleanup (curl);
206     curl = NULL;
207     multi = NULL;
208     if (cbc.pos != strlen ("/hello_world"))
209     {
210       GNUNET_break (0);
211       global_ret = 2;
212     }
213     if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
214     {
215       GNUNET_break (0);
216       global_ret = 3;
217     }
218     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download complete, shutting down!\n");
219     do_shutdown ();
220     return;    
221   }
222   GNUNET_assert (CURLM_OK == curl_multi_fdset (multi, &rs, &ws, &es, &max)); 
223   if ( (CURLM_OK != curl_multi_timeout (multi, &timeout)) ||
224        (-1 == timeout) )
225     delay = GNUNET_TIME_UNIT_SECONDS;
226   else
227     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, (unsigned int) timeout);
228   GNUNET_NETWORK_fdset_copy_native (&nrs,
229                                     &rs,
230                                     max + 1);
231   GNUNET_NETWORK_fdset_copy_native (&nws,
232                                     &ws,
233                                     max + 1);
234   curl_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
235                                               delay,
236                                               &nrs,
237                                               &nws,
238                                               &curl_task,
239                                               NULL);  
240 }
241
242
243 static void
244 start_curl (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
245 {
246   GNUNET_asprintf (&url, 
247                    "http://%s/hello_world",     
248                    TEST_DOMAIN);
249   curl = curl_easy_init ();
250   curl_easy_setopt (curl, CURLOPT_URL, url);
251   curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, &copy_buffer);
252   curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbc);
253   curl_easy_setopt (curl, CURLOPT_FAILONERROR, 1);
254   curl_easy_setopt (curl, CURLOPT_TIMEOUT, 150L);
255   curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, 15L);
256   curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1);
257
258   multi = curl_multi_init ();
259   GNUNET_assert (multi != NULL);
260   GNUNET_assert (CURLM_OK == curl_multi_add_handle (multi, curl));
261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Beginning HTTP download from `%s'\n", url);
262   curl_main ();
263 }
264
265
266 static void
267 disco_ns (void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
268 {
269   GNUNET_NAMESTORE_disconnect (namestore);
270   namestore = NULL;
271 }
272
273
274 /**
275  * Callback invoked from the namestore service once record is
276  * created.
277  *
278  * @param cls closure
279  * @param af address family, AF_INET or AF_INET6; AF_UNSPEC on error;
280  *                will match 'result_af' from the request
281  * @param address IP address (struct in_addr or struct in_addr6, depending on 'af')
282  *                that the VPN allocated for the redirection;
283  *                traffic to this IP will now be redirected to the 
284  *                specified target peer; NULL on error
285  */
286 static void
287 commence_testing (void *cls, int32_t success, const char *emsg)
288 {
289   GNUNET_SCHEDULER_add_now (&disco_ns, NULL);
290
291   if ((emsg != NULL) && (GNUNET_YES != success))
292   {
293     fprintf (stderr, 
294              "NS failed to create record %s\n", emsg);
295     GNUNET_SCHEDULER_shutdown ();
296     return;
297   }  
298   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10), &start_curl, NULL);
299 }
300
301
302 /**
303  * Function to keep the HTTP server running.
304  */
305 static void 
306 mhd_main (void);
307
308
309 static void
310 mhd_task (void *cls,
311           const struct GNUNET_SCHEDULER_TaskContext *tc)
312 {
313   mhd_task_id = GNUNET_SCHEDULER_NO_TASK;
314   MHD_run (mhd);
315   mhd_main ();
316 }
317
318
319 static void 
320 mhd_main ()
321 {
322   struct GNUNET_NETWORK_FDSet nrs;
323   struct GNUNET_NETWORK_FDSet nws;
324   fd_set rs;
325   fd_set ws;
326   fd_set es;
327   int max_fd;
328   unsigned MHD_LONG_LONG timeout;
329   struct GNUNET_TIME_Relative delay;
330
331   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == mhd_task_id);
332   FD_ZERO (&rs);
333   FD_ZERO (&ws);
334   FD_ZERO (&es);
335   max_fd = -1;
336   GNUNET_assert (MHD_YES ==
337                  MHD_get_fdset (mhd, &rs, &ws, &es, &max_fd));
338   if (MHD_YES == MHD_get_timeout (mhd, &timeout))
339     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
340                                            (unsigned int) timeout);
341   else
342     delay = GNUNET_TIME_UNIT_FOREVER_REL;
343   GNUNET_NETWORK_fdset_copy_native (&nrs,
344                                     &rs,
345                                     max_fd + 1);
346   GNUNET_NETWORK_fdset_copy_native (&nws,
347                                     &ws,
348                                     max_fd + 1);
349   mhd_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
350                                              delay,
351                                              &nrs,
352                                              &nws,
353                                              &mhd_task,
354                                              NULL);  
355 }
356
357
358 static void
359 run (void *cls,
360      const struct GNUNET_CONFIGURATION_Handle *cfg,
361      struct GNUNET_TESTING_Peer *peer)
362 {
363   enum MHD_FLAG flags;
364   struct GNUNET_PeerIdentity id;
365   struct GNUNET_CRYPTO_HashAsciiEncoded peername;
366   struct GNUNET_CRYPTO_EccPrivateKey *host_key;
367   struct GNUNET_NAMESTORE_RecordData rd;
368   char *rd_string;
369   char *zone_keyfile;
370   
371   GNUNET_TESTING_peer_get_identity (peer, &id);
372   GNUNET_CRYPTO_hash_to_enc ((struct GNUNET_HashCode*)&id, &peername);
373
374   namestore = GNUNET_NAMESTORE_connect (cfg);
375   GNUNET_assert (NULL != namestore);
376   flags = MHD_USE_DEBUG;
377   //if (GNUNET_YES == use_v6)
378   //  flags |= MHD_USE_IPv6;
379   mhd = MHD_start_daemon (flags,
380                           PORT,
381                           NULL, NULL,
382                           &mhd_ahc, NULL,
383                           MHD_OPTION_END);
384   GNUNET_assert (NULL != mhd);
385   mhd_main ();
386   
387   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
388                                                             "ZONEKEY",
389                                                             &zone_keyfile))
390   {
391     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to get key from cfg\n");
392     return;
393   }
394
395   host_key = GNUNET_CRYPTO_ecc_key_create_from_file (zone_keyfile);
396   rd.expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
397   GNUNET_asprintf (&rd_string, "6 %s %s", (char*)&peername, "www.gads.");
398   GNUNET_assert (GNUNET_OK == GNUNET_NAMESTORE_string_to_value (GNUNET_GNS_RECORD_VPN,
399                                                                rd_string,
400                                                                (void**)&rd.data,
401                                                                &rd.data_size));
402   rd.record_type = GNUNET_GNS_RECORD_VPN;
403
404   GNUNET_NAMESTORE_record_put_by_authority (namestore,
405                                             host_key,
406                                             "www",
407                                             1, &rd,
408                                             &commence_testing,
409                                             NULL);
410   GNUNET_free ((void**)rd.data);
411   GNUNET_free (rd_string);
412   GNUNET_free (zone_keyfile);
413   GNUNET_CRYPTO_ecc_key_free (host_key);
414 }
415
416
417 /**
418  * Open '/dev/null' and make the result the given
419  * file descriptor.
420  *
421  * @param target_fd desired FD to point to /dev/null
422  * @param flags open flags (O_RDONLY, O_WRONLY)
423  */
424 static void
425 open_dev_null (int target_fd,
426                int flags)
427 {
428   int fd;
429
430   fd = open ("/dev/null", flags);
431   if (-1 == fd)
432     abort ();
433   if (fd == target_fd)
434     return;
435   if (-1 == dup2 (fd, target_fd))
436   {    
437     (void) close (fd);
438     abort ();
439   }
440   (void) close (fd);
441 }
442
443
444 /**
445  * Run the given command and wait for it to complete.
446  * 
447  * @param file name of the binary to run
448  * @param cmd command line arguments (as given to 'execv')
449  * @return 0 on success, 1 on any error
450  */
451 static int
452 fork_and_exec (const char *file, 
453                char *const cmd[])
454 {
455   int status;
456   pid_t pid;
457   pid_t ret;
458
459   pid = fork ();
460   if (-1 == pid)
461   {
462     fprintf (stderr, 
463              "fork failed: %s\n", 
464              strerror (errno));
465     return 1;
466   }
467   if (0 == pid)
468   {
469     /* we are the child process */
470     /* close stdin/stdout to not cause interference
471        with the helper's main protocol! */
472     (void) close (0); 
473     open_dev_null (0, O_RDONLY);
474     (void) close (1); 
475     open_dev_null (1, O_WRONLY);
476     (void) execv (file, cmd);
477     /* can only get here on error */
478     fprintf (stderr, 
479              "exec `%s' failed: %s\n", 
480              file,
481              strerror (errno));
482     _exit (1);
483   }
484   /* keep running waitpid as long as the only error we get is 'EINTR' */
485   while ( (-1 == (ret = waitpid (pid, &status, 0))) &&
486           (errno == EINTR) ); 
487   if (-1 == ret)
488   {
489     fprintf (stderr, 
490              "waitpid failed: %s\n", 
491              strerror (errno));
492     return 1;
493   }
494   if (! (WIFEXITED (status) && (0 == WEXITSTATUS (status))))
495     return 1;
496   /* child process completed and returned success, we're happy */
497   return 0;
498 }
499
500 int
501 main (int argc, char *const *argv)
502 {
503   char *sbin_iptables;
504   char *bin_vpn;
505   char *bin_exit;
506   char *bin_dns;
507   char *const iptables_args[] =
508   {
509     "iptables", "-t", "mangle", "-L", "-v", NULL
510   };
511   
512   if (0 == access ("/sbin/iptables", X_OK))
513     sbin_iptables = "/sbin/iptables";
514   else if (0 == access ("/usr/sbin/iptables", X_OK))
515     sbin_iptables = "/usr/sbin/iptables";
516   else
517   {
518     fprintf (stderr, 
519              "Executable iptables not found in approved directories: %s, skipping\n",
520              strerror (errno));
521     return 0;
522   }
523   
524   if (0 != fork_and_exec (sbin_iptables, iptables_args))
525   {
526     fprintf (stderr,
527              "Failed to run `iptables -t mangle -L -v'. Skipping test.\n");
528     return 0;
529   }
530
531   if (0 != ACCESS ("/dev/net/tun", R_OK))
532   {
533     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
534                               "access",
535                               "/dev/net/tun");
536     fprintf (stderr,
537              "WARNING: System unable to run test, skipping.\n");
538     return 0;
539   }
540
541   bin_vpn = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-vpn");
542   bin_exit = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-exit");
543   bin_dns = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-dns");
544   if ( (0 != geteuid ()) &&
545        ( (GNUNET_YES !=
546           GNUNET_OS_check_helper_binary (bin_vpn, GNUNET_YES, "-d gnunet-vpn - - 169.1.3.3.7 255.255.255.0")) || //ipv4 only please!
547          (GNUNET_YES !=
548           GNUNET_OS_check_helper_binary (bin_exit, GNUNET_YES, "-d gnunet-vpn - - - 169.1.3.3.7 255.255.255.0")) || //no nat, ipv4 only
549          (GNUNET_YES !=
550           GNUNET_OS_check_helper_binary (bin_dns, GNUNET_YES, NULL))) ) // TODO: once we have a windows-testcase, add test parameters here
551   {    
552     fprintf (stderr,
553              "WARNING: gnunet-helper-{exit,vpn,dns} binaries in $PATH are not SUID, refusing to run test (as it would have to fail).\n");
554     fprintf (stderr,
555              "Change $PATH ('.' in $PATH before $GNUNET_PREFIX/bin is problematic) or permissions (run 'make install' as root) to fix this!\n");
556     GNUNET_free (bin_vpn);    
557     GNUNET_free (bin_exit);
558     GNUNET_free (bin_dns);
559     return 0;
560   }
561   GNUNET_free (bin_vpn);    
562   GNUNET_free (bin_exit);
563   GNUNET_free (bin_dns);
564   
565   dest_ip = "169.254.86.1";
566   dest_af = AF_INET;
567   src_af = AF_INET;
568
569   if (GNUNET_OK == GNUNET_NETWORK_test_pf (PF_INET6))
570     use_v6 = GNUNET_YES;
571   else
572     use_v6 = GNUNET_NO;
573   
574   if ( (GNUNET_OK != GNUNET_NETWORK_test_pf (src_af)) ||
575        (GNUNET_OK != GNUNET_NETWORK_test_pf (dest_af)) )
576   {
577     fprintf (stderr, 
578              "Required address families not supported by this system, skipping test.\n");
579     return 0;
580   }
581   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
582   {
583     fprintf (stderr, "failed to initialize curl\n");
584     return 2;
585   }
586   if (0 != GNUNET_TESTING_peer_run ("test-gnunet-vpn",
587                                     "test_gns_vpn.conf",
588                                     &run, NULL))
589     return 1;
590   GNUNET_DISK_directory_remove ("/tmp/gnunet-test-vpn");
591   return global_ret;
592 }
593
594 /* end of test_gns_vpn.c */
595