remove 'nac' option from VPN, always return IP immediately, always build mesh tunnel...
[oweals/gnunet.git] / src / pt / gnunet-daemon-pt.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010, 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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file pt/gnunet-daemon-pt.c
23  * @brief tool to manipulate DNS and VPN services to perform protocol translation (IPvX over GNUnet)
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_dns_service.h"
29 #include "gnunet_dnsparser_lib.h"
30 #include "gnunet_mesh_service.h"
31 #include "gnunet_tun_lib.h"
32 #include "gnunet_dht_service.h"
33 #include "gnunet_vpn_service.h"
34 #include "gnunet_statistics_service.h"
35 #include "gnunet_applications.h"
36 #include "block_dns.h"
37
38 #define PORT_PT 4242 // FIXME
39
40
41 /**
42  * After how long do we time out if we could not get an IP from VPN or MESH?
43  */
44 #define TIMEOUT GNUNET_TIME_UNIT_MINUTES
45
46
47 /**
48  * How many bytes of payload do we allow at most for a DNS reply?
49  * Given that this is pretty much limited to loopback, we can be
50  * pretty high (Linux loopback defaults to 16k, most local UDP packets
51  * should survive up to 9k (NFS), so 8k should be pretty safe in
52  * general).
53  */
54 #define MAX_DNS_SIZE (8 * 1024)
55
56
57 /**
58  * Which group of DNS records are we currently processing?
59  */
60 enum RequestGroup
61 {
62   /**
63    * DNS answers
64    */
65   ANSWERS = 0, 
66
67   /**
68    * DNS authority records
69    */
70   AUTHORITY_RECORDS = 1,
71
72   /**
73    * DNS additional records
74    */
75   ADDITIONAL_RECORDS = 2,
76
77   /**
78    * We're done processing.
79    */
80   END = 3
81 };
82
83
84 /**
85  * Information tracked per DNS reply that we are processing.
86  */
87 struct ReplyContext
88 {
89   /**
90    * Handle to submit the final result.
91    */
92   struct GNUNET_DNS_RequestHandle *rh;
93   
94   /**
95    * DNS packet that is being modified.
96    */
97   struct GNUNET_DNSPARSER_Packet *dns;
98
99   /**
100    * Active redirection request with the VPN.
101    */
102   struct GNUNET_VPN_RedirectionRequest *rr;
103
104   /**
105    * Record for which we have an active redirection request.
106    */
107   struct GNUNET_DNSPARSER_Record *rec;
108
109   /**
110    * Offset in the current record group that is being modified.
111    */
112   unsigned int offset;
113
114   /**
115    * Group that is being modified
116    */
117   enum RequestGroup group;
118   
119 };
120
121
122 /**
123  * State we keep for a request that is going out via MESH.
124  */
125 struct RequestContext
126 {
127   /**
128    * We keep these in a DLL.
129    */
130   struct RequestContext *next;
131
132   /**
133    * We keep these in a DLL.
134    */
135   struct RequestContext *prev;
136
137   /**
138    * Handle for interaction with DNS service.
139    */
140   struct GNUNET_DNS_RequestHandle *rh;
141   
142   /**
143    * Message we're sending out via MESH, allocated at the
144    * end of this struct.
145    */
146   const struct GNUNET_MessageHeader *mesh_message;
147
148   /**
149    * Task used to abort this operation with timeout.
150    */
151   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
152
153   /**
154    * ID of the original DNS request (used to match the reply).
155    */
156   uint16_t dns_id;
157
158   /**
159    * #GNUNET_NO if this request is still in the transmit_queue,
160    * #GNUNET_YES if we are in the receive_queue.
161    */ 
162   int16_t was_transmitted;
163
164 };
165
166
167 /**
168  * The handle to the configuration used throughout the process
169  */
170 static const struct GNUNET_CONFIGURATION_Handle *cfg;
171
172 /**
173  * The handle to the VPN
174  */
175 static struct GNUNET_VPN_Handle *vpn_handle;
176
177 /**
178  * The handle to the MESH service
179  */
180 static struct GNUNET_MESH_Handle *mesh_handle;
181
182 /**
183  * Tunnel we use for DNS requests over MESH.
184  * FIXME: we might want to keep multiple tunnels open
185  * at all times...
186  */
187 static struct GNUNET_MESH_Tunnel *mesh_tunnel;
188
189 /**
190  * Active transmission request with MESH (or NULL).
191  */
192 static struct GNUNET_MESH_TransmitHandle *mesh_th;
193
194 /**
195  * Head of DLL of requests to be transmitted to mesh_tunnel.
196  */
197 static struct RequestContext *transmit_queue_head;
198
199 /**
200  * Tail of DLL of requests to be transmitted to mesh_tunnel.
201  */
202 static struct RequestContext *transmit_queue_tail;
203
204 /**
205  * Head of DLL of requests waiting for a response.
206  */
207 static struct RequestContext *receive_queue_head;
208
209 /**
210  * Tail of DLL of requests waiting for a response.
211  */
212 static struct RequestContext *receive_queue_tail;
213
214 /**
215  * Statistics.
216  */
217 static struct GNUNET_STATISTICS_Handle *stats;
218
219 /**
220  * The handle to DNS post-resolution modifications.
221  */
222 static struct GNUNET_DNS_Handle *dns_post_handle;
223
224 /**
225  * The handle to DNS pre-resolution modifications.
226  */
227 static struct GNUNET_DNS_Handle *dns_pre_handle;
228
229 /**
230  * Handle to access the DHT.
231  */
232 static struct GNUNET_DHT_Handle *dht;
233
234 /**
235  * Our DHT GET operation to find DNS exits.
236  */
237 static struct GNUNET_DHT_GetHandle *dht_get;
238
239 /**
240  * Are we doing IPv4-pt?
241  */
242 static int ipv4_pt;
243
244 /**
245  * Are we doing IPv6-pt?
246  */
247 static int ipv6_pt;
248
249 /**
250  * Are we tunneling DNS queries?
251  */
252 static int dns_tunnel;
253
254 /**
255  * Number of DNS exit peers we currently have in the mesh tunnel.
256  * Used to see if using the mesh tunnel makes any sense right now.
257  */
258 static unsigned int dns_exit_available;
259
260
261 /**
262  * We're done modifying all records in the response.  Submit the reply
263  * and free the resources of the rc.
264  *
265  * @param rc context to process
266  */
267 static void
268 finish_request (struct ReplyContext *rc)
269 {
270   char *buf;
271   size_t buf_len;
272
273   if (GNUNET_SYSERR ==
274       GNUNET_DNSPARSER_pack (rc->dns,
275                              MAX_DNS_SIZE,
276                              &buf,
277                              &buf_len))
278   {
279     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
280                 _("Failed to pack DNS request.  Dropping.\n"));
281     GNUNET_DNS_request_drop (rc->rh);
282   }
283   else
284   {
285     GNUNET_STATISTICS_update (stats,
286                               gettext_noop ("# DNS requests mapped to VPN"),
287                               1, GNUNET_NO);
288     GNUNET_DNS_request_answer (rc->rh,
289                                buf_len, buf);
290     GNUNET_free (buf);
291   }
292   GNUNET_DNSPARSER_free_packet (rc->dns);
293   GNUNET_free (rc);
294 }
295
296
297 /**
298  * Process the next record of the given request context.
299  * When done, submit the reply and free the resources of
300  * the rc.
301  *
302  * @param rc context to process
303  */
304 static void
305 submit_request (struct ReplyContext *rc);
306
307
308 /**
309  * Callback invoked from the VPN service once a redirection is
310  * available.  Provides the IP address that can now be used to
311  * reach the requested destination.  We substitute the active
312  * record and then continue with 'submit_request' to look at
313  * the other records.
314  *
315  * @param cls our 'struct ReplyContext'
316  * @param af address family, AF_INET or AF_INET6; AF_UNSPEC on error;
317  *                will match 'result_af' from the request
318  * @param address IP address (struct in_addr or struct in_addr6, depending on 'af')
319  *                that the VPN allocated for the redirection;
320  *                traffic to this IP will now be redirected to the 
321  *                specified target peer; NULL on error
322  */
323 static void
324 vpn_allocation_callback (void *cls,
325                          int af,
326                          const void *address)
327 {
328   struct ReplyContext *rc = cls;
329
330   rc->rr = NULL;
331   if (af == AF_UNSPEC)
332   {
333     GNUNET_DNS_request_drop (rc->rh);
334     GNUNET_DNSPARSER_free_packet (rc->dns);
335     GNUNET_free (rc);
336     return;
337   }
338   GNUNET_STATISTICS_update (stats,
339                             gettext_noop ("# DNS records modified"),
340                             1, GNUNET_NO);
341   switch (rc->rec->type)
342   {
343   case GNUNET_DNSPARSER_TYPE_A:
344     GNUNET_assert (AF_INET == af);
345     memcpy (rc->rec->data.raw.data, address, sizeof (struct in_addr));
346     break;
347   case GNUNET_DNSPARSER_TYPE_AAAA:
348     GNUNET_assert (AF_INET6 == af);
349     memcpy (rc->rec->data.raw.data, address, sizeof (struct in6_addr));
350     break;
351   default:
352     GNUNET_assert (0);
353     return;
354   }
355   rc->rec = NULL;
356   submit_request (rc);
357 }
358
359
360 /**
361  * Modify the given DNS record by asking VPN to create a tunnel
362  * to the given address.  When done, continue with submitting
363  * other records from the request context ('submit_request' is
364  * our continuation).
365  *
366  * @param rc context to process
367  * @param rec record to modify
368  */
369 static void
370 modify_address (struct ReplyContext *rc,
371                 struct GNUNET_DNSPARSER_Record *rec)
372 {
373   int af;
374
375   switch (rec->type)
376   {
377   case GNUNET_DNSPARSER_TYPE_A:
378     af = AF_INET;
379     GNUNET_assert (rec->data.raw.data_len == sizeof (struct in_addr));
380     break;
381   case GNUNET_DNSPARSER_TYPE_AAAA:
382     af = AF_INET6;
383     GNUNET_assert (rec->data.raw.data_len == sizeof (struct in6_addr));
384     break;
385   default:
386     GNUNET_assert (0);
387     return;
388   }
389   rc->rec = rec;
390   rc->rr = GNUNET_VPN_redirect_to_ip (vpn_handle,
391                                       af, af,
392                                       rec->data.raw.data,
393                                       GNUNET_TIME_relative_to_absolute (TIMEOUT),
394                                       &vpn_allocation_callback,
395                                       rc);
396 }
397
398
399 /**
400  * Process the next record of the given request context.
401  * When done, submit the reply and free the resources of
402  * the rc.
403  *
404  * @param rc context to process
405  */
406 static void
407 submit_request (struct ReplyContext *rc)
408 {
409   struct GNUNET_DNSPARSER_Record *ra;
410   unsigned int ra_len;
411   unsigned int i;
412
413   while (1)
414   {
415     switch (rc->group)
416     {
417     case ANSWERS:
418       ra = rc->dns->answers;
419       ra_len = rc->dns->num_answers;
420       break;
421     case AUTHORITY_RECORDS:
422       ra = rc->dns->authority_records;
423       ra_len = rc->dns->num_authority_records;
424       break;
425     case ADDITIONAL_RECORDS:
426       ra = rc->dns->additional_records;
427       ra_len = rc->dns->num_additional_records;
428       break;
429     case END:
430       finish_request (rc);
431       return;
432     default:
433       GNUNET_assert (0);      
434     }
435     for (i=rc->offset;i<ra_len;i++)
436     {
437       switch (ra[i].type)
438       {
439       case GNUNET_DNSPARSER_TYPE_A:
440         if (ipv4_pt)
441         {
442           rc->offset = i + 1;
443           modify_address (rc, &ra[i]);
444           return;
445         }
446         break;
447       case GNUNET_DNSPARSER_TYPE_AAAA:
448         if (ipv6_pt)
449         {
450           rc->offset = i + 1;
451           modify_address (rc, &ra[i]);
452           return;
453         }
454         break;
455       }
456     }
457     rc->group++;
458   }
459 }
460
461
462 /**
463  * Test if any of the given records need protocol-translation work.
464  *
465  * @param ra array of records
466  * @param ra_len number of entries in ra
467  * @return GNUNET_YES if any of the given records require protocol-translation
468  */
469 static int
470 work_test (const struct GNUNET_DNSPARSER_Record *ra,
471            unsigned int ra_len)
472 {
473   unsigned int i;
474
475   for (i=0;i<ra_len;i++)
476   {
477     switch (ra[i].type)
478     {
479     case GNUNET_DNSPARSER_TYPE_A:
480       if (ipv4_pt)
481         return GNUNET_YES;
482       break;
483     case GNUNET_DNSPARSER_TYPE_AAAA:
484       if (ipv6_pt)
485         return GNUNET_YES;
486       break;
487     }
488   }
489   return GNUNET_NO;
490 }
491
492
493 /**
494  * This function is called AFTER we got an IP address for a 
495  * DNS request.  Now, the PT daemon has the chance to substitute
496  * the IP address with one from the VPN range to tunnel requests
497  * destined for this IP address via VPN and MESH.
498  *
499  * @param cls closure
500  * @param rh request handle to user for reply
501  * @param request_length number of bytes in request
502  * @param request udp payload of the DNS request
503  */
504 static void 
505 dns_post_request_handler (void *cls,
506                           struct GNUNET_DNS_RequestHandle *rh,
507                           size_t request_length,
508                           const char *request)
509 {
510   struct GNUNET_DNSPARSER_Packet *dns;
511   struct ReplyContext *rc;
512   int work;
513
514   GNUNET_STATISTICS_update (stats,
515                             gettext_noop ("# DNS replies intercepted"),
516                             1, GNUNET_NO);
517   dns = GNUNET_DNSPARSER_parse (request, request_length);
518   if (NULL == dns)
519   {
520     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
521                 _("Failed to parse DNS request.  Dropping.\n"));
522     GNUNET_DNS_request_drop (rh);
523     return;
524   }
525   work = GNUNET_NO;
526   work |= work_test (dns->answers, dns->num_answers);
527   work |= work_test (dns->authority_records, dns->num_authority_records);
528   work |= work_test (dns->additional_records, dns->num_additional_records);
529   if (! work)
530   {
531     GNUNET_DNS_request_forward (rh);
532     GNUNET_DNSPARSER_free_packet (dns);
533     return;
534   }
535   rc = GNUNET_new (struct ReplyContext);
536   rc->rh = rh;
537   rc->dns = dns;
538   rc->offset = 0;
539   rc->group = ANSWERS;
540   submit_request (rc);
541 }
542
543
544 /**
545  * Transmit a DNS request via MESH and move the request
546  * handle to the receive queue.
547  *
548  * @param cls NULL
549  * @param size number of bytes available in buf
550  * @param buf where to copy the message
551  * @return number of bytes written to buf
552  */
553 static size_t
554 transmit_dns_request_to_mesh (void *cls,
555                               size_t size,
556                               void *buf)
557 {
558   struct RequestContext *rc;
559   size_t mlen;
560
561   mesh_th = NULL;
562   if (NULL == (rc = transmit_queue_head))
563     return 0;
564   mlen = ntohs (rc->mesh_message->size);
565   if (mlen > size)
566   {
567     mesh_th = GNUNET_MESH_notify_transmit_ready (mesh_tunnel,
568                                                  GNUNET_NO,
569                                                  TIMEOUT,
570                                                  mlen,
571                                                  &transmit_dns_request_to_mesh,
572                                                  NULL);
573     return 0;
574   }
575   GNUNET_assert (GNUNET_NO == rc->was_transmitted);
576   memcpy (buf, rc->mesh_message, mlen);
577   GNUNET_CONTAINER_DLL_remove (transmit_queue_head,
578                                transmit_queue_tail,
579                                rc);
580   rc->was_transmitted = GNUNET_YES;
581   GNUNET_CONTAINER_DLL_insert (receive_queue_head,
582                                receive_queue_tail,
583                                rc);
584   rc = transmit_queue_head;
585   if (NULL != rc)
586     mesh_th = GNUNET_MESH_notify_transmit_ready (mesh_tunnel,
587                                                  GNUNET_NO,
588                                                  TIMEOUT,
589                                                  ntohs (rc->mesh_message->size),
590                                                  &transmit_dns_request_to_mesh,
591                                                  NULL);
592   return mlen;
593 }
594
595
596 /**
597  * Task run if the time to answer a DNS request via MESH is over.
598  *
599  * @param cls the 'struct RequestContext' to abort
600  * @param tc scheduler context
601  */
602 static void
603 timeout_request (void *cls,
604                  const struct GNUNET_SCHEDULER_TaskContext *tc)
605 {
606   struct RequestContext *rc = cls;
607   
608   if (rc->was_transmitted)
609     GNUNET_CONTAINER_DLL_remove (receive_queue_head,
610                                  receive_queue_tail,
611                                  rc);
612   else
613     GNUNET_CONTAINER_DLL_remove (transmit_queue_head,
614                                  transmit_queue_tail,
615                                  rc);
616   GNUNET_STATISTICS_update (stats,
617                             gettext_noop ("# DNS requests dropped (timeout)"),
618                             1, GNUNET_NO);
619   GNUNET_DNS_request_drop (rc->rh);
620   GNUNET_free (rc);
621 }
622
623
624 /**
625  * This function is called *before* the DNS request has been 
626  * given to a "local" DNS resolver.  Tunneling for DNS requests
627  * was enabled, so we now need to send the request via some MESH
628  * tunnel to a DNS EXIT for resolution.
629  *
630  * @param cls closure
631  * @param rh request handle to user for reply
632  * @param request_length number of bytes in request
633  * @param request udp payload of the DNS request
634  */
635 static void 
636 dns_pre_request_handler (void *cls,
637                          struct GNUNET_DNS_RequestHandle *rh,
638                          size_t request_length,
639                          const char *request)
640 {
641   struct RequestContext *rc;
642   size_t mlen;
643   struct GNUNET_MessageHeader hdr;
644   struct GNUNET_TUN_DnsHeader dns;
645
646   GNUNET_STATISTICS_update (stats,
647                             gettext_noop ("# DNS requests intercepted"),
648                             1, GNUNET_NO);
649   if (0 == dns_exit_available)
650   {
651     GNUNET_STATISTICS_update (stats,
652                               gettext_noop ("# DNS requests dropped (DNS mesh tunnel down)"),
653                               1, GNUNET_NO);
654     GNUNET_DNS_request_drop (rh);
655     return;
656   }
657   if (request_length < sizeof (dns))
658   {
659     GNUNET_STATISTICS_update (stats,
660                               gettext_noop ("# DNS requests dropped (malformed)"),
661                               1, GNUNET_NO);
662     GNUNET_DNS_request_drop (rh);
663     return;
664   }
665   memcpy (&dns, request, sizeof (dns));
666   GNUNET_assert (NULL != mesh_tunnel);
667   mlen = sizeof (struct GNUNET_MessageHeader) + request_length;
668   rc = GNUNET_malloc (sizeof (struct RequestContext) + mlen);
669   rc->rh = rh;
670   rc->mesh_message = (const struct GNUNET_MessageHeader*) &rc[1];
671   rc->timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
672                                                    &timeout_request,
673                                                    rc);
674   rc->dns_id = dns.id;
675   hdr.type = htons (GNUNET_MESSAGE_TYPE_VPN_DNS_TO_INTERNET);
676   hdr.size = htons (mlen);
677   memcpy (&rc[1], &hdr, sizeof (struct GNUNET_MessageHeader));
678   memcpy (&(((char*)&rc[1])[sizeof (struct GNUNET_MessageHeader)]),
679           request,
680           request_length);
681   GNUNET_CONTAINER_DLL_insert_tail (transmit_queue_head,
682                                     transmit_queue_tail,
683                                     rc);
684   if (NULL == mesh_th)
685     mesh_th = GNUNET_MESH_notify_transmit_ready (mesh_tunnel,
686                                                  GNUNET_NO,
687                                                  TIMEOUT,
688                                                  mlen,
689                                                  &transmit_dns_request_to_mesh,
690                                                  NULL);
691 }
692
693
694 /**
695  * Process a request via mesh to perform a DNS query.
696  *
697  * @param cls closure, NULL
698  * @param tunnel connection to the other end
699  * @param tunnel_ctx pointer to our 'struct TunnelState *'
700  * @param message the actual message
701  * 
702  * @return GNUNET_OK to keep the connection open,
703  *         GNUNET_SYSERR to close it (signal serious error)
704  */
705 static int
706 receive_dns_response (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
707                       void **tunnel_ctx,
708                       const struct GNUNET_MessageHeader *message)
709 {
710   struct GNUNET_TUN_DnsHeader dns;
711   size_t mlen;
712   struct RequestContext *rc;
713
714   mlen = ntohs (message->size);
715   mlen -= sizeof (struct GNUNET_MessageHeader);
716   if (mlen < sizeof (struct GNUNET_TUN_DnsHeader))
717   {
718     GNUNET_break_op (0);
719     return GNUNET_SYSERR;
720   }
721   memcpy (&dns, &message[1], sizeof (dns));
722   for (rc = receive_queue_head; NULL != rc; rc = rc->next)
723   {
724     GNUNET_assert (GNUNET_YES == rc->was_transmitted);
725     if (dns.id == rc->dns_id)
726     {
727       GNUNET_STATISTICS_update (stats,
728                                 gettext_noop ("# DNS replies received"),
729                                 1, GNUNET_NO);
730       GNUNET_DNS_request_answer (rc->rh,
731                                  mlen,
732                                  (const void*) &message[1]);
733       GNUNET_CONTAINER_DLL_remove (receive_queue_head,
734                                    receive_queue_tail,
735                                    rc);
736       GNUNET_SCHEDULER_cancel (rc->timeout_task);
737       GNUNET_free (rc);
738       return GNUNET_OK;      
739     }
740   }
741   GNUNET_STATISTICS_update (stats,
742                             gettext_noop ("# DNS replies dropped (too late?)"),
743                             1, GNUNET_NO);
744   return GNUNET_OK;
745 }
746
747
748 /**
749  * The MESH DNS tunnel went down.  Abort all pending DNS
750  * requests (we're unlikely to get an answer in time).
751  */ 
752 static void
753 abort_all_requests ()
754 {
755   struct RequestContext *rc;
756
757   while (NULL != (rc = receive_queue_head))
758   {
759     GNUNET_STATISTICS_update (stats,
760                               gettext_noop ("# DNS requests aborted (tunnel down)"),
761                               1, GNUNET_NO);
762     GNUNET_CONTAINER_DLL_remove (receive_queue_head,
763                                  receive_queue_tail,
764                                  rc);
765     GNUNET_DNS_request_drop (rc->rh);
766     GNUNET_SCHEDULER_cancel (rc->timeout_task);
767     GNUNET_free (rc);    
768   }
769   while (NULL != (rc = transmit_queue_head))
770   {
771     GNUNET_STATISTICS_update (stats,
772                               gettext_noop ("# DNS requests aborted (tunnel down)"),
773                               1, GNUNET_NO);
774     GNUNET_CONTAINER_DLL_remove (transmit_queue_head,
775                                  transmit_queue_tail,
776                                  rc);
777     GNUNET_DNS_request_drop (rc->rh);
778     GNUNET_SCHEDULER_cancel (rc->timeout_task);
779     GNUNET_free (rc);    
780   }
781 }
782
783
784 /**
785  * Function scheduled as very last function, cleans up after us
786  *
787  * @param cls closure, NULL
788  * @param tskctx scheduler context, unused
789  */
790 static void
791 cleanup (void *cls,
792          const struct GNUNET_SCHEDULER_TaskContext *tskctx)
793 {
794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
795               "Protocol translation daemon is shutting down now\n");
796   if (NULL != vpn_handle)
797   {
798     GNUNET_VPN_disconnect (vpn_handle);
799     vpn_handle = NULL;
800   }
801   if (NULL != mesh_th)
802   {
803     GNUNET_MESH_notify_transmit_ready_cancel (mesh_th);
804     mesh_th = NULL;
805   }
806   if (NULL != mesh_tunnel)
807   {
808     GNUNET_MESH_tunnel_destroy (mesh_tunnel);
809     mesh_tunnel = NULL;
810   }
811   if (NULL != mesh_handle)
812   {
813     GNUNET_MESH_disconnect (mesh_handle);
814     mesh_handle = NULL;
815   }
816   abort_all_requests ();
817   if (NULL != dns_post_handle)
818   {
819     GNUNET_DNS_disconnect (dns_post_handle);
820     dns_post_handle = NULL;
821   }
822   if (NULL != dns_pre_handle)
823   {
824     GNUNET_DNS_disconnect (dns_pre_handle);
825     dns_pre_handle = NULL;
826   }
827   if (NULL != stats)
828   {
829     GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
830     stats = NULL;
831   }
832   if (NULL != dht_get)
833   {
834     GNUNET_DHT_get_stop (dht_get);
835     dht_get = NULL;
836   }
837   if (NULL != dht)
838   {
839     GNUNET_DHT_disconnect (dht);
840     dht = NULL;
841   }
842 }
843
844
845
846 /**
847  * Function called whenever a tunnel is destroyed.  Should clean up
848  * the associated state and attempt to build a new one.
849  * 
850  * It must NOT call #GNUNET_MESH_tunnel_destroy on the tunnel.
851  *
852  * @param cls closure (set from #GNUNET_MESH_connect)
853  * @param tunnel connection to the other end (henceforth invalid)
854  * @param tunnel_ctx place where local state associated
855  *                   with the tunnel is stored
856  */
857 static void
858 mesh_tunnel_end_cb (void *cls,
859                     const struct GNUNET_MESH_Tunnel *tunnel, 
860                     void *tunnel_ctx)
861 {
862   // FIXME: do cleanup here!
863 }
864
865
866 /**
867  * Function called whenever we find an advertisement for a 
868  * DNS exit in the DHT.  If we don't have a mesh tunnel,
869  * we should build one; otherwise, we should save the
870  * advertisement for later use.
871  *
872  * @param cls closure
873  * @param exp when will this value expire
874  * @param key key of the result
875  * @param get_path peers on reply path (or NULL if not recorded)
876  *                 [0] = datastore's first neighbor, [length - 1] = local peer
877  * @param get_path_length number of entries in @a get_path
878  * @param put_path peers on the PUT path (or NULL if not recorded)
879  *                 [0] = origin, [length - 1] = datastore
880  * @param put_path_length number of entries in @a put_path
881  * @param type type of the result
882  * @param size number of bytes in @a data
883  * @param data pointer to the result data
884  */
885 static void
886 handle_dht_result (void *cls,
887                    struct GNUNET_TIME_Absolute exp,
888                    const struct GNUNET_HashCode *key,
889                    const struct GNUNET_PeerIdentity *get_path, 
890                    unsigned int get_path_length,
891                    const struct GNUNET_PeerIdentity *put_path,
892                    unsigned int put_path_length,
893                    enum GNUNET_BLOCK_Type type,
894                    size_t size, const void *data)
895 {
896   const struct GNUNET_DNS_Advertisement *ad;
897   struct GNUNET_PeerIdentity pid;
898
899   if (sizeof (struct GNUNET_DNS_Advertisement) != size)
900   {
901     GNUNET_break (0);
902     return;
903   }
904   ad = data;
905   GNUNET_CRYPTO_hash (&ad->peer,
906                       sizeof (struct GNUNET_CRYPTO_EccPublicSignKey),
907                       &pid.hashPubKey);
908   /* FIXME: decide between creating more mesh tunnels and
909      just remembering the peer ID */
910   mesh_tunnel = GNUNET_MESH_tunnel_create (mesh_handle,
911                                            NULL /* FIXME: tunnel ctx */,
912                                            &pid,
913                                            PORT_PT, /* FIXME: DNS port, right? */
914                                            GNUNET_YES /* no buffer */,
915                                            GNUNET_NO /* reliable */);
916
917 }
918
919
920 /**
921  * @brief Main function that will be run by the scheduler.
922  *
923  * @param cls closure
924  * @param args remaining command-line arguments
925  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
926  * @param cfg_ configuration
927  */
928 static void
929 run (void *cls, char *const *args GNUNET_UNUSED,
930      const char *cfgfile GNUNET_UNUSED,
931      const struct GNUNET_CONFIGURATION_Handle *cfg_)
932 {
933   struct GNUNET_HashCode dns_key;
934
935   cfg = cfg_;
936   stats = GNUNET_STATISTICS_create ("pt", cfg);
937   ipv4_pt = GNUNET_CONFIGURATION_get_value_yesno (cfg, "pt", "TUNNEL_IPV4");
938   ipv6_pt = GNUNET_CONFIGURATION_get_value_yesno (cfg, "pt", "TUNNEL_IPV6"); 
939   dns_tunnel = GNUNET_CONFIGURATION_get_value_yesno (cfg, "pt", "TUNNEL_DNS"); 
940   if (! (ipv4_pt || ipv6_pt || dns_tunnel))
941   {
942     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
943                 _("No useful service enabled.  Exiting.\n"));
944     GNUNET_SCHEDULER_shutdown ();
945     return;    
946   }
947   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
948   if (ipv4_pt || ipv6_pt)
949   {
950     dns_post_handle 
951       = GNUNET_DNS_connect (cfg, 
952                             GNUNET_DNS_FLAG_POST_RESOLUTION,
953                             &dns_post_request_handler, NULL);
954     if (NULL == dns_post_handle)       
955     {
956       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
957                   _("Failed to connect to %s service.  Exiting.\n"),
958                   "DNS");
959       GNUNET_SCHEDULER_shutdown ();
960       return;
961     }
962     vpn_handle = GNUNET_VPN_connect (cfg);
963     if (NULL == vpn_handle)
964     {
965       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
966                   _("Failed to connect to %s service.  Exiting.\n"),
967                   "VPN");
968       GNUNET_SCHEDULER_shutdown ();
969       return;
970     }
971   }
972   if (dns_tunnel)
973   {
974     static struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
975       {&receive_dns_response, GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET, 0},
976       {NULL, 0, 0}
977     };
978
979     dns_pre_handle 
980       = GNUNET_DNS_connect (cfg, 
981                             GNUNET_DNS_FLAG_PRE_RESOLUTION,
982                             &dns_pre_request_handler, NULL);
983     if (NULL == dns_pre_handle)       
984     {
985       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
986                   _("Failed to connect to %s service.  Exiting.\n"),
987                   "DNS");
988       GNUNET_SCHEDULER_shutdown ();
989       return;
990     }
991     mesh_handle = GNUNET_MESH_connect (cfg, NULL, NULL,
992                                        &mesh_tunnel_end_cb,
993                                        mesh_handlers, NULL);
994     if (NULL == mesh_handle)
995     {
996       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
997                   _("Failed to connect to %s service.  Exiting.\n"),
998                   "MESH");
999       GNUNET_SCHEDULER_shutdown ();
1000       return;
1001     }
1002     dht = GNUNET_DHT_connect (cfg, 1);
1003     if (NULL == dht)
1004     {
1005       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1006                   _("Failed to connect to %s service.  Exiting.\n"),
1007                   "DHT");
1008       GNUNET_SCHEDULER_shutdown ();
1009       return;
1010     }
1011     GNUNET_CRYPTO_hash ("dns", strlen ("dns"), &dns_key);
1012     dht_get = GNUNET_DHT_get_start (dht,
1013                                     GNUNET_BLOCK_TYPE_DNS,
1014                                     &dns_key,
1015                                     1,
1016                                     GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1017                                     NULL, 0,
1018                                     &handle_dht_result, NULL);
1019   }
1020 }
1021
1022
1023 /**
1024  * The main function
1025  *
1026  * @param argc number of arguments from the command line
1027  * @param argv command line arguments
1028  * @return 0 ok, 1 on error
1029  */
1030 int
1031 main (int argc, char *const *argv)
1032 {
1033   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1034     GNUNET_GETOPT_OPTION_END
1035   };
1036   int ret;
1037
1038   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1039     return 2;
1040   ret = (GNUNET_OK ==
1041          GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-pt",
1042                              gettext_noop
1043                              ("Daemon to run to perform IP protocol translation to GNUnet"),
1044                              options, &run, NULL)) ? 0 : 1;
1045   GNUNET_free ((void*) argv);
1046   return ret;
1047 }
1048
1049
1050 /* end of gnunet-daemon-pt.c */