get rid of duplicate statistics handle in each plugin
[oweals/gnunet.git] / src / transport / plugin_transport_udp_nat.c
1 /*
2      This file is part of GNUnet
3      (C) 2010 Christian Grothoff (and other contributing authors)
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 transport/plugin_transport_udp.c
23  * @brief Implementation of the UDP NAT punching
24  *        transport service
25  * @author Christian Grothoff
26  * @author Nathan Evans
27  *
28  * The idea with this transport is to connect gnunet peers to each other
29  * when one or both is behind a NAT.  This is based on pwnat
30  * (http://samy.pl/pwnat) created by Samy Kamkar.  This transport will
31  * take external IP addresses for a NAT'd peer, start a server daemon
32  * which sends ICMP messages out to a predefined address.  Then it forks
33  * a client process which sends ICMP death messages to the given external
34  * IP address for the other peer (which has already also started the
35  * server).  If everything works according to plan, the transport will
36  * be given a port which has worked to punch into the other external
37  * addresses NAT to communicate with the other gnunet peer.  Then keep
38  * alive messages will be sent every (???)ms or so to keep the tunnel
39  * safe.
40  */
41
42 #include "platform.h"
43 #include "gnunet_hello_lib.h"
44 #include "gnunet_connection_lib.h"
45 #include "gnunet_os_lib.h"
46 #include "gnunet_peerinfo_service.h"
47 #include "gnunet_protocols.h"
48 #include "gnunet_resolver_service.h"
49 #include "gnunet_server_lib.h"
50 #include "gnunet_service_lib.h"
51 #include "gnunet_signatures.h"
52 #include "gnunet_statistics_service.h"
53 #include "gnunet_transport_service.h"
54 #include "plugin_transport.h"
55 #include "transport.h"
56
57 #define DEBUG_UDP_NAT GNUNET_NO
58
59 /*
60  * Transport cost to peer, always 1 for UDP (direct connection)
61  */
62 #define UDP_DIRECT_DISTANCE 1
63
64 /**
65  * Handle for request of hostname resolution, non-NULL if pending.
66  */
67 static struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
68
69 /**
70  * How long until we give up on transmitting the welcome message?
71  */
72 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
73
74 /**
75  * How many ports do we want to listen on (and send on) in order to get replies?
76  *
77  * FIXME: make this value dynamic, specified by configuration
78  */
79 #define UDP_NAT_LISTEN_PORTS 257
80
81 /**
82  * Starting port for listening and sending, eventually a config value
83  */
84 #define UDP_NAT_STARTING_PORT 22086
85
86 /**
87  * UDP Message-Packet header.
88  */
89 struct UDPMessage
90 {
91   /**
92    * Message header.
93    */
94   struct GNUNET_MessageHeader header;
95
96   /**
97    * What is the identity of the sender (GNUNET_hash of public key)
98    */
99   struct GNUNET_PeerIdentity sender;
100
101 };
102
103
104 /**
105  * UDP NAT Probe message definition
106  */
107 struct UDP_NAT_ProbeMessage
108 {
109   /**
110    * Message header
111    */
112   struct GNUNET_MessageHeader header;
113
114 };
115
116 /**
117  * UDP NAT Probe message reply definition
118  */
119 struct UDP_NAT_ProbeMessageReply
120 {
121   /**
122    * Message header
123    */
124   struct GNUNET_MessageHeader header;
125
126 };
127
128
129 /**
130  * UDP NAT Probe message confirm definition
131  */
132 struct UDP_NAT_ProbeMessageConfirmation
133 {
134   /**
135    * Message header
136    */
137   struct GNUNET_MessageHeader header;
138
139 };
140
141
142
143 /* Forward definition */
144 struct Plugin;
145
146 struct PrettyPrinterContext
147 {
148   GNUNET_TRANSPORT_AddressStringCallback asc;
149   void *asc_cls;
150   uint16_t port;
151 };
152
153 struct MessageQueue
154 {
155   /**
156    * Linked List
157    */
158   struct MessageQueue *next;
159
160   /**
161    * Session this message belongs to
162    */
163   struct PeerSession *session;
164
165   /**
166    * Actual message to be sent
167    */
168   char *msgbuf;
169
170   /**
171    * Size of message buffer to be sent
172    */
173   size_t msgbuf_size;
174
175   /**
176    * When to discard this message
177    */
178   struct GNUNET_TIME_Absolute timeout;
179
180   /**
181    * Continuation to call when this message goes out
182    */
183   GNUNET_TRANSPORT_TransmitContinuation cont;
184
185   /**
186    * closure for continuation
187    */
188   void *cont_cls;
189
190 };
191
192 /**
193  * UDP NAT "Session"
194  */
195 struct PeerSession
196 {
197
198   /**
199    * Stored in a linked list.
200    */
201   struct PeerSession *next;
202
203   /**
204    * Pointer to the global plugin struct.
205    */
206   struct Plugin *plugin;
207
208   /**
209    * To whom are we talking to (set to our identity
210    * if we are still waiting for the welcome message)
211    */
212   struct GNUNET_PeerIdentity target;
213
214   /**
215    * Address of the other peer (either based on our 'connect'
216    * call or on our 'accept' call).
217    */
218   void *connect_addr;
219
220   /**
221    * Length of connect_addr.
222    */
223   size_t connect_alen;
224
225   /**
226    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
227    */
228   int expecting_welcome;
229
230   /**
231    * From which socket do we need to send to this peer?
232    */
233   struct GNUNET_NETWORK_Handle *sock;
234
235   /*
236    * Queue of messages for this peer, in the case that
237    * we have to await a connection...
238    */
239   struct MessageQueue *messages;
240
241 };
242
243
244 struct UDP_NAT_Probes
245 {
246
247   /**
248    * Linked list
249    */
250   struct UDP_NAT_Probes *next;
251
252   /**
253    * Address string that the server process returned to us
254    */
255   char *address_string;
256
257   /**
258    * Timeout for this set of probes
259    */
260   struct GNUNET_TIME_Absolute timeout;
261
262   /**
263    * Current index (which port to send on next basically)
264    */
265   int index;
266
267   /**
268    * The plugin this probe belongs to
269    */
270   struct Plugin *plugin;
271
272   /**
273    * The task used to send these probes
274    */
275   GNUNET_SCHEDULER_TaskIdentifier task;
276
277   /**
278    * Network address (always ipv4)
279    */
280   struct sockaddr_in sock_addr;
281
282   /**
283    * The port to send this probe to, 0 to choose randomly
284    */
285   int port;
286
287 };
288
289
290 /**
291  * Encapsulation of all of the state of the plugin.
292  */
293 struct Plugin
294 {
295   /**
296    * Our environment.
297    */
298   struct GNUNET_TRANSPORT_PluginEnvironment *env;
299
300   /**
301    * Handle to the network service.
302    */
303   struct GNUNET_SERVICE_Context *service;
304
305   /*
306    * Session of peers with whom we are currently connected
307    */
308   struct PeerSession *sessions;
309
310   /**
311    * Handle for request of hostname resolution, non-NULL if pending.
312    */
313   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
314
315   /**
316    * ID of task used to update our addresses when one expires.
317    */
318   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
319
320   /**
321    * ID of select task
322    */
323   GNUNET_SCHEDULER_TaskIdentifier select_task;
324
325   /**
326    * Starting port, will listen on num_ports (if available) starting
327    * at this number (or will listen only on this port if non-nat'd)
328    */
329   uint16_t starting_port;
330
331   /**
332    * Starting port for sending out crazy messages
333    */
334   uint32_t random_starting_port;
335
336   /**
337    * How many ports should we be using?
338    */
339   uint16_t num_ports;
340
341   /**
342    * The external address given to us by the user.  Must be actual
343    * outside visible address for NAT punching to work.
344    */
345   char *external_address;
346
347   /**
348    * The internal address given to us by the user (or discovered).
349    */
350   char *internal_address;
351
352   /*
353    * FD Read set
354    */
355   struct GNUNET_NETWORK_FDSet *rs;
356
357   /*
358    * stdout pipe handle for the gnunet-nat-server process
359    */
360   struct GNUNET_DISK_PipeHandle *server_stdout;
361
362   /*
363    * stdout file handle (for reading) for the gnunet-nat-server process
364    */
365   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
366
367   /**
368    * ID of select gnunet-nat-server stdout read task
369    */
370   GNUNET_SCHEDULER_TaskIdentifier server_read_task;
371
372   /**
373    * Is this transport configured to be behind a NAT?
374    */
375   int behind_nat;
376
377   /**
378    * The process id of the server process (if behind NAT)
379    */
380   pid_t server_pid;
381
382   /**
383    * Probes in flight
384    */
385   struct UDP_NAT_Probes *probes;
386
387 };
388
389
390 struct UDP_Sock_Info
391 {
392   /* The network handle */
393   struct GNUNET_NETWORK_Handle *desc;
394
395   /* The port we bound to */
396   int port;
397 };
398
399 /* *********** globals ************* */
400
401 /**
402  * the socket that we transmit all data with
403  */
404 static struct UDP_Sock_Info *udp_nat_socks[UDP_NAT_LISTEN_PORTS];
405
406
407 /**
408  * Forward declaration.
409  */
410 void
411 udp_probe_continuation (void *cls, const struct GNUNET_PeerIdentity *target, int result);
412
413
414 /**
415  * Disconnect from a remote node.  Clean up session if we have one for this peer
416  *
417  * @param cls closure for this call (should be handle to Plugin)
418  * @param target the peeridentity of the peer to disconnect
419  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
420  */
421 void
422 udp_nat_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
423 {
424   /** TODO: Implement! */
425   return;
426 }
427
428 /**
429  * Shutdown the server process (stop receiving inbound traffic). Maybe
430  * restarted later!
431  *
432  * @param cls Handle to the plugin for this transport
433  *
434  * @return returns the number of sockets successfully closed,
435  *         should equal the number of sockets successfully opened
436  */
437 static int
438 udp_nat_transport_server_stop (void *cls)
439 {
440   struct Plugin *plugin = cls;
441   int ret;
442   int ok;
443   int i;
444
445   ret = 0;
446   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
447     {
448       GNUNET_SCHEDULER_cancel (plugin->env->sched, plugin->select_task);
449       plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
450     }
451
452   for (i = 0; i < plugin->num_ports; i++)
453     {
454       ok = GNUNET_NETWORK_socket_close (udp_nat_socks[i]->desc);
455       if (ok == GNUNET_OK)
456         udp_nat_socks[i]->desc = NULL;
457       ret += ok;
458     }
459
460   if (plugin->behind_nat == GNUNET_YES)
461     {
462       if (0 != PLIBC_KILL (plugin->server_pid, SIGTERM))
463         {
464           GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
465         }
466       GNUNET_OS_process_wait (plugin->server_pid);
467     }
468
469   if (ret != GNUNET_OK)
470     return GNUNET_SYSERR;
471   return ret;
472 }
473
474
475 struct PeerSession *
476 find_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *peer)
477 {
478   struct PeerSession *pos;
479
480   pos = plugin->sessions;
481   while (pos != NULL)
482     {
483       if (memcmp(&pos->target, peer, sizeof(struct GNUNET_PeerIdentity)) == 0)
484         return pos;
485       pos = pos->next;
486     }
487
488   return pos;
489 }
490
491
492 /**
493  * Actually send out the message, assume we've got the address and
494  * send_handle squared away!
495  *
496  * @param cls closure
497  * @param send_handle which handle to send message on
498  * @param target who should receive this message (ignored by UDP)
499  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
500  * @param msgbuf_size the size of the msgbuf to send
501  * @param priority how important is the message (ignored by UDP)
502  * @param timeout when should we time out (give up) if we can not transmit?
503  * @param addr the addr to send the message to, needs to be a sockaddr for us
504  * @param addrlen the len of addr
505  * @param cont continuation to call once the message has
506  *        been transmitted (or if the transport is ready
507  *        for the next transmission call; or if the
508  *        peer disconnected...)
509  * @param cont_cls closure for cont
510  * @return the number of bytes written
511  */
512 static ssize_t
513 udp_nat_real_send (void *cls,
514                    struct GNUNET_NETWORK_Handle *send_handle,
515                    const struct GNUNET_PeerIdentity *target,
516                    const char *msgbuf,
517                    size_t msgbuf_size,
518                    unsigned int priority,
519                    struct GNUNET_TIME_Relative timeout,
520                    const void *addr,
521                    size_t addrlen,
522                    GNUNET_TRANSPORT_TransmitContinuation cont,
523                    void *cont_cls)
524 {
525   struct Plugin *plugin = cls;
526   struct UDPMessage *message;
527   int ssize;
528   ssize_t sent;
529
530   if ((addr == NULL) || (addrlen == 0))
531     {
532 #if DEBUG_UDP_NAT
533   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
534                    ("udp_nat_plugin_send called without address, returning!\n"));
535 #endif
536       cont (cont_cls, target, GNUNET_SYSERR);
537       return 0; /* Can never send if we don't have an address!! */
538     }
539
540   /* Build the message to be sent */
541   message = GNUNET_malloc (sizeof (struct UDPMessage) + msgbuf_size);
542   ssize = sizeof (struct UDPMessage) + msgbuf_size;
543
544   message->header.size = htons (ssize);
545   message->header.type = htons (0);
546   memcpy (&message->sender, plugin->env->my_identity,
547           sizeof (struct GNUNET_PeerIdentity));
548   memcpy (&message[1], msgbuf, msgbuf_size);
549
550   /* Actually send the message */
551   sent =
552     GNUNET_NETWORK_socket_sendto (send_handle, message, ssize,
553                                   addr,
554                                   addrlen);
555
556   if (cont != NULL)
557     {
558       if (sent == GNUNET_SYSERR)
559         cont (cont_cls, target, GNUNET_SYSERR);
560       else
561         {
562           cont (cont_cls, target, GNUNET_OK);
563         }
564     }
565   GNUNET_free (message);
566   return sent;
567 }
568
569 /**
570  * We learned about a peer (possibly behind NAT) so run the
571  * gnunet-nat-client to send a dummy ICMP response
572  *
573  * @param plugin the plugin for this transport
574  * @param addr the address of the peer
575  * @param addrlen the length of the address
576  */
577 void
578 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
579 {
580   char inet4[INET_ADDRSTRLEN];
581   char *address_as_string;
582   char *port_as_string;
583   pid_t pid;
584   const struct sockaddr *sa = (const struct sockaddr *)addr;
585
586   if (addrlen < sizeof (struct sockaddr))
587     return;
588   switch (sa->sa_family)
589     {
590     case AF_INET:
591       if (addrlen != sizeof (struct sockaddr_in))
592         return;
593       inet_ntop (AF_INET,
594                  &((struct sockaddr_in *) sa)->sin_addr,
595                  inet4, INET_ADDRSTRLEN);
596       address_as_string = GNUNET_strdup (inet4);
597       break;
598     case AF_INET6:
599     default:
600       return;
601     }
602
603   GNUNET_asprintf(&port_as_string, "%d", plugin->starting_port);
604 #if DEBUG_UDP_NAT
605   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
606                   _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->starting_port);
607 #endif
608   /* Start the server process */
609   pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
610   GNUNET_free(address_as_string);
611   GNUNET_free(port_as_string);
612   GNUNET_OS_process_wait (pid);
613 }
614
615 /**
616  * Function that can be used by the transport service to transmit
617  * a message using the plugin.
618  *
619  * @param cls closure
620  * @param target who should receive this message (ignored by UDP)
621  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
622  * @param msgbuf_size the size of the msgbuf to send
623  * @param priority how important is the message (ignored by UDP)
624  * @param timeout when should we time out (give up) if we can not transmit?
625  * @param session identifier used for this session (can be NULL)
626  * @param addr the addr to send the message to, needs to be a sockaddr for us
627  * @param addrlen the len of addr
628  * @param force_address not used, we had better have an address to send to
629  *        because we are stateless!!
630  * @param cont continuation to call once the message has
631  *        been transmitted (or if the transport is ready
632  *        for the next transmission call; or if the
633  *        peer disconnected...)
634  * @param cont_cls closure for cont
635  *
636  * @return the number of bytes written (may return 0 and the message can
637  *         still be transmitted later!)
638  */
639 static ssize_t
640 udp_nat_plugin_send (void *cls,
641                      const struct GNUNET_PeerIdentity *target,
642                      const char *msgbuf,
643                      size_t msgbuf_size,
644                      unsigned int priority,
645                      struct GNUNET_TIME_Relative timeout,
646                      struct Session *session,
647                      const void *addr,
648                      size_t addrlen,
649                      int force_address,
650                      GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
651 {
652   struct Plugin *plugin = cls;
653   ssize_t sent;
654   struct MessageQueue *temp_message;
655   struct PeerSession *peer_session;
656   struct sockaddr_in *sockaddr = (struct sockaddr_in *)addr;
657   int other_peer_natd;
658
659   GNUNET_assert (NULL == session);
660   other_peer_natd = GNUNET_NO;
661   if ((sockaddr->sin_family == AF_INET) && (ntohs(sockaddr->sin_port) == 0))
662     {
663       other_peer_natd = GNUNET_YES;
664     }
665
666   sent = 0;
667
668   if (other_peer_natd == GNUNET_YES)
669     {
670       peer_session = find_session(plugin, target);
671       if (peer_session == NULL) /* We have a new peer to add */
672         {
673           /*
674            * The first time, we can assume we have no knowledge of a
675            * working port for this peer, call the ICMP message sender
676            * and wait...
677            */
678           peer_session = GNUNET_malloc(sizeof(struct PeerSession));
679           peer_session->connect_addr = GNUNET_malloc(addrlen);
680           memcpy(peer_session->connect_addr, addr, addrlen);
681           peer_session->connect_alen = addrlen;
682           peer_session->plugin = plugin;
683           peer_session->sock = NULL;
684           memcpy(&peer_session->target, target, sizeof(struct GNUNET_PeerIdentity));
685           peer_session->expecting_welcome = GNUNET_YES;
686
687           peer_session->next = plugin->sessions;
688           plugin->sessions = peer_session;
689
690           peer_session->messages = GNUNET_malloc(sizeof(struct MessageQueue));
691           peer_session->messages->msgbuf = GNUNET_malloc(msgbuf_size);
692           memcpy(peer_session->messages->msgbuf, msgbuf, msgbuf_size);
693           peer_session->messages->msgbuf_size = msgbuf_size;
694           peer_session->messages->next = NULL;
695           peer_session->messages->timeout = GNUNET_TIME_relative_to_absolute(timeout);
696           peer_session->messages->cont = cont;
697           peer_session->messages->cont_cls = cont_cls;
698 #if DEBUG_UDP_NAT
699           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
700                           _("Other peer is NAT'd, set up peer session for peer %s\n"), GNUNET_i2s(target));
701 #endif
702           run_gnunet_nat_client(plugin, addr, addrlen);
703
704         }
705       else
706         {
707           if (peer_session->expecting_welcome == GNUNET_NO) /* We are "connected" */
708             {
709               sent = udp_nat_real_send(cls, peer_session->sock, target, msgbuf, msgbuf_size, priority, timeout, peer_session->connect_addr, peer_session->connect_alen, cont, cont_cls);
710             }
711           else /* Haven't gotten a response from this peer, queue message */
712             {
713               temp_message = GNUNET_malloc(sizeof(struct MessageQueue));
714               temp_message->msgbuf = GNUNET_malloc(msgbuf_size);
715               memcpy(temp_message->msgbuf, msgbuf, msgbuf_size);
716               temp_message->msgbuf_size = msgbuf_size;
717               temp_message->timeout = GNUNET_TIME_relative_to_absolute(timeout);
718               temp_message->cont = cont;
719               temp_message->cont_cls = cont_cls;
720               temp_message->next = peer_session->messages;
721               peer_session->messages = temp_message;
722             }
723         }
724     }
725   else /* Other peer not behind a NAT, so we can just send the message as is */
726     {
727       sent = udp_nat_real_send(cls, udp_nat_socks[0]->desc, target, msgbuf, msgbuf_size, priority, timeout, addr, addrlen, cont, cont_cls);
728     }
729
730   return sent;
731 }
732
733
734 /**
735  * Add the IP of our network interface to the list of
736  * our external IP addresses.
737  */
738 static int
739 process_interfaces (void *cls,
740                     const char *name,
741                     int isDefault,
742                     const struct sockaddr *addr, socklen_t addrlen)
743 {
744   struct Plugin *plugin = cls;
745   int af;
746   struct sockaddr_in *v4;
747   struct sockaddr_in6 *v6;
748
749   /*
750    * FIXME: Do we want to advertise _all_ of our UDP NAT addresses?
751    * Probably not.  Can we assume that we'll only send these out of band?
752    * Ostensibly we won't accept just any connection on these ports anyways
753    * right?
754    */
755
756   af = addr->sa_family;
757   if (af == AF_INET)
758     {
759       v4 = (struct sockaddr_in *) addr;
760       if (plugin->behind_nat == GNUNET_YES)
761         {
762           GNUNET_assert(inet_pton(AF_INET, plugin->external_address, &v4->sin_addr) == GNUNET_OK);
763           v4->sin_port = htons (0); /* Indicates to receiver we are behind NAT */
764         }
765       else
766         v4->sin_port = htons (plugin->starting_port);
767     }
768   else
769     {
770       GNUNET_assert (af == AF_INET6);
771       v6 = (struct sockaddr_in6 *) addr;
772       if (plugin->behind_nat == GNUNET_YES)
773         v6->sin6_port = htons (0);
774       else
775         v6->sin6_port = htons (plugin->starting_port);
776     }
777
778 #if !IPV6
779   if (af == AF_INET)
780     {
781 #endif
782       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
783                         GNUNET_ERROR_TYPE_BULK,
784                         "udp-nat", _("Found address `%s' (%s)\n"),
785                         GNUNET_a2s (addr, addrlen), name);
786       plugin->env->notify_address (plugin->env->cls,
787                                   "udp_nat",
788                                   addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
789 #if !IPV6
790     }
791 #endif
792
793   return GNUNET_OK;
794 }
795
796
797 /**
798  * Function called by the resolver for each address obtained from DNS
799  * for our own hostname.  Add the addresses to the list of our
800  * external IP addresses.
801  *
802  * @param cls closure
803  * @param addr one of the addresses of the host, NULL for the last address
804  * @param addrlen length of the address
805  */
806 static void
807 process_hostname_ips (void *cls,
808                       const struct sockaddr *addr, socklen_t addrlen)
809 {
810   struct Plugin *plugin = cls;
811
812   if (addr == NULL)
813     {
814       plugin->hostname_dns = NULL;
815       return;
816     }
817   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
818 }
819
820
821 /**
822  * Send UDP probe messages or UDP keepalive messages, depending on the
823  * state of the connection.
824  *
825  * @param cls closure for this call (should be the main Plugin)
826  * @param tc task context for running this
827  */
828 static void
829 send_udp_probe_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
830 {
831   struct UDP_NAT_Probes *probe = cls;
832   struct UDP_NAT_ProbeMessage *message;
833   struct Plugin *plugin = probe->plugin;
834
835   message = GNUNET_malloc(sizeof(struct UDP_NAT_ProbeMessage));
836   message->header.size = htons(sizeof(struct UDP_NAT_ProbeMessage));
837   message->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_NAT_PROBE);
838   /* Try the agreed upon port first, then go in order starting with our randomly chosen port */
839   if (probe->index == 0)
840     {
841       if (probe->port != 0)
842         probe->sock_addr.sin_port = htons(probe->port);
843       else
844         probe->sock_addr.sin_port = htons(plugin->starting_port);
845     }
846   else
847     probe->sock_addr.sin_port = htons (GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000); /* Find a non-root port */
848 #if DEBUG_UDP_NAT
849       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
850                       _("Sending a probe to port %d\n"), ntohs(probe->sock_addr.sin_port));
851 #endif
852   if (probe->index + 1 < plugin->num_ports)
853     probe->index += 1;
854   else
855     probe->index = 0;
856
857   udp_nat_real_send(plugin, udp_nat_socks[probe->index]->desc, NULL, 
858                     (char *)message, ntohs(message->header.size), 0, 
859                     GNUNET_TIME_relative_get_unit(), 
860                     &probe->sock_addr, sizeof(probe->sock_addr),
861                     &udp_probe_continuation, probe);
862
863   GNUNET_free(message);
864 }
865
866
867 /**
868  * Continuation for probe sends.  If the last probe was sent
869  * "successfully", schedule sending of another one.  If not,
870  *
871  */
872 void
873 udp_probe_continuation (void *cls, const struct GNUNET_PeerIdentity *target, int result)
874 {
875   struct UDP_NAT_Probes *probe = cls;
876   struct Plugin *plugin = probe->plugin;
877
878   if (result == GNUNET_OK)
879     {
880       if (probe->index == 0)
881         {
882 #if DEBUG_UDP_NAT
883           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
884                           _("Scheduling next probe for 10000 milliseconds\n"));
885 #endif
886           probe->task = GNUNET_SCHEDULER_add_delayed(plugin->env->sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 10000), &send_udp_probe_message, probe);
887         }
888
889       else
890         {
891           probe->task = GNUNET_SCHEDULER_add_delayed(plugin->env->sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 50), &send_udp_probe_message, probe);
892         }
893     }
894   else /* Destroy the probe context? */
895     {
896 #if DEBUG_UDP_NAT
897       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
898                       _("Sending probe didn't go well...\n"));
899 #endif
900
901     }
902 }
903
904 /**
905  * Find probe message by address
906  *
907  * @param plugin the plugin for this transport
908  * @param address_string the ip address as a string
909  */
910 struct UDP_NAT_Probes *
911 find_probe(struct Plugin *plugin, char * address_string)
912 {
913   struct UDP_NAT_Probes *pos;
914
915   pos = plugin->probes;
916   while (pos != NULL)
917     if (strcmp(pos->address_string, address_string) == 0)
918       return pos;
919
920   return pos;
921 }
922
923
924 /*
925  * @param cls the plugin handle
926  * @param tc the scheduling context (for rescheduling this function again)
927  *
928  * We have been notified that gnunet-nat-server has written something to stdout.
929  * Handle the output, then reschedule this function to be called again once
930  * more is available.
931  *
932  */
933 static void
934 udp_nat_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
935 {
936   struct Plugin *plugin = cls;
937   char mybuf[40];
938   ssize_t bytes;
939   memset(&mybuf, 0, sizeof(mybuf));
940   int i;
941   struct UDP_NAT_Probes *temp_probe;
942   int port;
943   char *port_start;
944   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
945
946   if (bytes < 1)
947     {
948 #if DEBUG_UDP_NAT
949       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
950                       _("Finished reading from server stdout with code: %d\n"), bytes);
951 #endif
952       return;
953     }
954
955   port = 0;
956   port_start = NULL;
957   for (i = 0; i < sizeof(mybuf); i++)
958     {
959       if (mybuf[i] == '\n')
960         mybuf[i] = '\0';
961
962       if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
963         {
964           mybuf[i] = '\0';
965           port_start = &mybuf[i + 1];
966         }
967     }
968
969   if (port_start != NULL)
970     port = atoi(port_start);
971
972 #if DEBUG_UDP_NAT
973   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
974                   _("nat-server-read read: %s port %d\n"), &mybuf, port);
975 #endif
976
977   /* Schedule sending of messages to peer on random ports */
978   temp_probe = find_probe(plugin, &mybuf[0]);
979
980   if (temp_probe == NULL)
981     {
982       temp_probe = GNUNET_malloc(sizeof(struct UDP_NAT_Probes));
983       temp_probe->address_string = strdup(&mybuf[0]);
984       temp_probe->sock_addr.sin_family = AF_INET;
985       GNUNET_assert(inet_pton(AF_INET, &mybuf[0], &temp_probe->sock_addr.sin_addr) == 1);
986       temp_probe->index = 0;
987       temp_probe->port = port;
988       temp_probe->next = plugin->probes;
989       temp_probe->plugin = plugin;
990       temp_probe->task = GNUNET_SCHEDULER_add_delayed(plugin->env->sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500), &send_udp_probe_message, temp_probe);
991       plugin->probes = temp_probe;
992     }
993
994   plugin->server_read_task =
995        GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
996                                        GNUNET_TIME_UNIT_FOREVER_REL,
997                                        plugin->server_stdout_handle, &udp_nat_plugin_server_read, plugin);
998
999 }
1000
1001
1002 /**
1003  * Demultiplexer for UDP NAT messages
1004  *
1005  * @param plugin the main plugin for this transport
1006  * @param sender from which peer the message was received
1007  * @param currhdr pointer to the header of the message
1008  * @param sender_addr the address from which the message was received
1009  * @param fromlen the length of the address
1010  * @param sockinfo which socket did we receive the message on
1011  */
1012 static void
1013 udp_nat_demultiplexer(struct Plugin *plugin, struct GNUNET_PeerIdentity *sender, const struct GNUNET_MessageHeader *currhdr, struct sockaddr_storage *sender_addr, socklen_t fromlen, struct UDP_Sock_Info *sockinfo)
1014 {
1015   struct UDP_NAT_ProbeMessageReply *outgoing_probe_reply;
1016   struct UDP_NAT_ProbeMessageConfirmation *outgoing_probe_confirmation;
1017
1018   char addr_buf[INET_ADDRSTRLEN];
1019   struct UDP_NAT_Probes *outgoing_probe;
1020   struct PeerSession *peer_session;
1021   struct MessageQueue *pending_message;
1022   struct MessageQueue *pending_message_temp;
1023
1024   if (memcmp(sender, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity)) == 0)
1025     {
1026 #if DEBUG_UDP_NAT
1027       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
1028                       _("Received a message from myself, dropping!!!\n"));
1029 #endif
1030       return;
1031     }
1032
1033   switch (ntohs(currhdr->type))
1034   {
1035     case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_NAT_PROBE:
1036       /* Send probe reply */
1037       outgoing_probe_reply = GNUNET_malloc(sizeof(struct UDP_NAT_ProbeMessageReply));
1038       outgoing_probe_reply->header.size = htons(sizeof(struct UDP_NAT_ProbeMessageReply));
1039       outgoing_probe_reply->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_NAT_PROBE_REPLY);
1040
1041 #if DEBUG_UDP_NAT
1042       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
1043                       _("Received a probe on listen port %d, sent_from port %d\n"), sockinfo->port, ntohs(((struct sockaddr_in *)sender_addr)->sin_port));
1044 #endif
1045
1046       udp_nat_real_send(plugin, sockinfo->desc, NULL, 
1047                         (char *)outgoing_probe_reply,
1048                         ntohs(outgoing_probe_reply->header.size), 0, 
1049                         GNUNET_TIME_relative_get_unit(), 
1050                         sender_addr, fromlen, 
1051                         NULL, NULL);
1052
1053 #if DEBUG_UDP_NAT
1054       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
1055                       _("Sent PROBE REPLY to port %d on outgoing port %d\n"), ntohs(((struct sockaddr_in *)sender_addr)->sin_port), sockinfo->port);
1056 #endif
1057       GNUNET_free(outgoing_probe_reply);
1058       break;
1059     case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_NAT_PROBE_REPLY:
1060       /* Check for existing probe, check ports returned, send confirmation if all is well */
1061 #if DEBUG_UDP_NAT
1062       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
1063                       _("Received PROBE REPLY from port %d on incoming port %d\n"), ntohs(((struct sockaddr_in *)sender_addr)->sin_port), sockinfo->port);
1064 #endif
1065       /* FIXME: use nonce, then IPv6 replies could work I think... */
1066       if (sender_addr->ss_family == AF_INET)
1067         {
1068           memset(&addr_buf, 0, sizeof(addr_buf));
1069           inet_ntop(AF_INET, &((struct sockaddr_in *) sender_addr)->sin_addr, addr_buf, INET_ADDRSTRLEN);
1070           outgoing_probe = find_probe(plugin, &addr_buf[0]);
1071           if (outgoing_probe != NULL)
1072             {
1073 #if DEBUG_UDP_NAT
1074               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
1075                               _("Sending confirmation that we were reached!\n"));
1076 #endif
1077               outgoing_probe_confirmation = GNUNET_malloc(sizeof(struct UDP_NAT_ProbeMessageConfirmation));
1078               outgoing_probe_confirmation->header.size = htons(sizeof(struct UDP_NAT_ProbeMessageConfirmation));
1079               outgoing_probe_confirmation->header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_NAT_PROBE_CONFIRM);
1080
1081               udp_nat_real_send(plugin, sockinfo->desc, NULL, (char *)outgoing_probe_confirmation, ntohs(outgoing_probe_confirmation->header.size), 0, GNUNET_TIME_relative_get_unit(), sender_addr, fromlen, NULL, NULL);
1082
1083               if (outgoing_probe->task != GNUNET_SCHEDULER_NO_TASK)
1084                 {
1085                   GNUNET_SCHEDULER_cancel(plugin->env->sched, outgoing_probe->task);
1086                   outgoing_probe->task = GNUNET_SCHEDULER_NO_TASK;
1087                   /* Schedule task to timeout and remove probe if confirmation not received */
1088                 }
1089               GNUNET_free(outgoing_probe_confirmation);
1090             }
1091           else
1092             {
1093 #if DEBUG_UDP_NAT
1094               GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp-nat",
1095                               _("Received a probe reply, but have no record of a sent probe!\n"));
1096 #endif
1097             }
1098         }
1099       break;
1100     case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_NAT_PROBE_CONFIRM:
1101       peer_session = find_session(plugin, sender);
1102 #if DEBUG_UDP_NAT
1103           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
1104                           _("Looking up peer session for peer %s\n"), GNUNET_i2s(sender));
1105 #endif
1106       if (peer_session == NULL) /* Shouldn't this NOT happen? */
1107         {
1108 #if DEBUG_UDP_NAT
1109           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat",
1110                           _("Peer not in list, adding (THIS MAY BE A MISTAKE) %s\n"), GNUNET_i2s(sender));
1111 #endif
1112           peer_session = GNUNET_malloc(sizeof(struct PeerSession));
1113           peer_session->connect_addr = GNUNET_malloc(fromlen);
1114           memcpy(peer_session->connect_addr, sender_addr, fromlen);
1115           peer_session->connect_alen = fromlen;
1116           peer_session->plugin = plugin;
1117           peer_session->sock = sockinfo->desc;
1118           memcpy(&peer_session->target, sender, sizeof(struct GNUNET_PeerIdentity));
1119           peer_session->expecting_welcome = GNUNET_NO;
1120
1121           peer_session->next = plugin->sessions;
1122           plugin->sessions = peer_session;
1123
1124           peer_session->messages = NULL;
1125         }
1126       else if (peer_session->expecting_welcome == GNUNET_YES)
1127         {
1128           peer_session->expecting_welcome = GNUNET_NO;
1129           /* FIXME: There is no way to find this based on receiving port at the moment! */
1130           peer_session->sock = sockinfo->desc; /* This may matter, not sure right now... */
1131           ((struct sockaddr_in *)peer_session->connect_addr)->sin_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1132 #if DEBUG_UDP_NAT
1133               GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp-nat",
1134                               _("Received a probe confirmation, will send to peer on port %d\n"), ntohs(((struct sockaddr_in *)peer_session->connect_addr)->sin_port));
1135 #endif
1136           if (peer_session->messages != NULL)
1137             {
1138 #if DEBUG_UDP_NAT
1139               GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp-nat",
1140                               _("Received a probe confirmation, sending queued messages.\n"));
1141 #endif
1142               pending_message = peer_session->messages;
1143               int count = 0;
1144               while (pending_message != NULL)
1145                 {
1146 #if DEBUG_UDP_NAT
1147                   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp-nat",
1148                                   _("sending queued message %d\n"), count);
1149 #endif
1150                   udp_nat_real_send(plugin, peer_session->sock, &peer_session->target, pending_message->msgbuf, pending_message->msgbuf_size, 0, GNUNET_TIME_relative_get_unit(), peer_session->connect_addr, peer_session->connect_alen, pending_message->cont, pending_message->cont_cls);
1151                   pending_message_temp = pending_message;
1152                   pending_message = pending_message->next;
1153                   GNUNET_free(pending_message_temp->msgbuf);
1154                   GNUNET_free(pending_message_temp);
1155 #if DEBUG_UDP_NAT
1156                   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp-nat",
1157                                   _("finished sending queued message %d\n"), count);
1158 #endif
1159                   count++;
1160                 }
1161             }
1162
1163         }
1164       else
1165         {
1166 #if DEBUG_UDP_NAT
1167           GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp-nat",
1168                           _("Received probe confirmation for already confirmed peer!\n"));
1169 #endif
1170         }
1171       /* Received confirmation, add peer with address/port specified */
1172       break;
1173     case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_NAT_PROBE_KEEPALIVE:
1174       /* Once we've sent NAT_PROBE_CONFIRM change to sending keepalives */
1175       /* If we receive these just ignore! */
1176       break;
1177     default:
1178       plugin->env->receive (plugin->env->cls, sender, currhdr, UDP_DIRECT_DISTANCE, 
1179                             NULL, (char *)sender_addr, fromlen);
1180   }
1181
1182 }
1183
1184
1185 /*
1186  * @param cls the plugin handle
1187  * @param tc the scheduling context (for rescheduling this function again)
1188  *
1189  * We have been notified that our writeset has something to read.  We don't
1190  * know which socket needs to be read, so we have to check each one
1191  * Then reschedule this function to be called again once more is available.
1192  *
1193  */
1194 static void
1195 udp_nat_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1196 {
1197   struct Plugin *plugin = cls;
1198   char *buf;
1199   struct UDPMessage *msg;
1200   struct GNUNET_PeerIdentity *sender;
1201   unsigned int buflen;
1202   socklen_t fromlen;
1203   struct sockaddr_storage addr;
1204   ssize_t ret;
1205   int offset;
1206   int count;
1207   int tsize;
1208   int i;
1209   char *msgbuf;
1210   const struct GNUNET_MessageHeader *currhdr;
1211
1212   buf = NULL;
1213   sender = NULL;
1214
1215   for (i = 0; i < plugin->num_ports; i++)
1216     {
1217       buflen = GNUNET_NETWORK_socket_recvfrom_amount (udp_nat_socks[i]->desc);
1218
1219       if (buflen == GNUNET_NO)
1220         continue;
1221
1222       buf = GNUNET_malloc (buflen);
1223       fromlen = sizeof (addr);
1224       memset (&addr, 0, fromlen);
1225       ret =
1226         GNUNET_NETWORK_socket_recvfrom (udp_nat_socks[i]->desc, buf, buflen,
1227                                         (struct sockaddr *) &addr, &fromlen);
1228
1229 #if DEBUG_UDP_NAT
1230       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp-nat", _
1231                        ("socket_recv returned %u, src_addr_len is %u\n"), ret,
1232                        fromlen);
1233 #endif
1234
1235       if (ret <= 0)
1236         {
1237           GNUNET_free (buf);
1238           continue;
1239         }
1240       msg = (struct UDPMessage *) buf;
1241
1242 #if DEBUG_UDP_NAT
1243       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
1244                       ("header reports message size of %d, type %d\n"),
1245                       ntohs (msg->header.size), ntohs (msg->header.type));
1246 #endif
1247       if (ntohs (msg->header.size) < sizeof (struct UDPMessage))
1248         {
1249           GNUNET_free (buf);
1250           continue;
1251         }
1252
1253       msgbuf = (char *)&msg[1];
1254       sender = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
1255       memcpy (sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
1256
1257       offset = 0;
1258       count = 0;
1259       tsize = ntohs (msg->header.size) - sizeof(struct UDPMessage);
1260
1261       while (offset < tsize)
1262         {
1263           currhdr = (struct GNUNET_MessageHeader *)&msgbuf[offset];
1264 #if DEBUG_UDP_NAT
1265           GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
1266                            ("processing msg %d: type %d, size %d at offset %d\n"),
1267                            count, ntohs(currhdr->type), ntohs(currhdr->size), offset);
1268 #endif
1269           udp_nat_demultiplexer(plugin, sender, currhdr, &addr, fromlen, udp_nat_socks[i]);
1270 #if DEBUG_UDP_NAT
1271           GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "udp", _
1272                            ("processing done msg %d: type %d, size %d at offset %d\n"),
1273                            count, ntohs(currhdr->type), ntohs(currhdr->size), offset);
1274 #endif
1275           offset += ntohs(currhdr->size);
1276           count++;
1277         }
1278       GNUNET_free_non_null (buf);
1279       GNUNET_free_non_null (sender);
1280     }
1281
1282   plugin->select_task =
1283     GNUNET_SCHEDULER_add_select (plugin->env->sched,
1284                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1285                                  GNUNET_SCHEDULER_NO_TASK,
1286                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1287                                  NULL, &udp_nat_plugin_select, plugin);
1288
1289 }
1290
1291 /**
1292  * Create a slew of UDP sockets.  If possible, use IPv6, otherwise
1293  * try IPv4.
1294  *
1295  * @param cls closure for server start, should be a struct Plugin *
1296  *
1297  * @return number of sockets created or GNUNET_SYSERR on error
1298  */
1299 static int
1300 udp_nat_transport_server_start (void *cls)
1301 {
1302   struct Plugin *plugin = cls;
1303   struct sockaddr_in serverAddrv4;
1304 #if IPV6
1305   struct sockaddr_in6 serverAddrv6;
1306 #endif
1307   struct sockaddr *serverAddr;
1308   socklen_t addrlen;
1309   int i;
1310   int sockets_created;
1311
1312   /* Pipe to read from started processes stdout (on read end) */
1313   plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
1314
1315   sockets_created = 0;
1316   if (plugin->server_stdout == NULL)
1317     return sockets_created;
1318
1319   if (plugin->behind_nat == GNUNET_YES)
1320     {
1321 #if DEBUG_UDP_NAT
1322   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1323                    "udp_nat",
1324                    "Starting gnunet-nat-server process\n");
1325 #endif
1326       /* Start the server process */
1327       plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
1328       if (plugin->server_pid == GNUNET_SYSERR)
1329         return GNUNET_SYSERR;
1330       /* Close the write end of the read pipe */
1331       GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
1332
1333       plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
1334       plugin->server_read_task =
1335           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1336                                           GNUNET_TIME_UNIT_FOREVER_REL,
1337                                           plugin->server_stdout_handle, &udp_nat_plugin_server_read, plugin);
1338     }
1339
1340   /* Open all our sockets for reading/writing */
1341   for (i = 0; i < plugin->num_ports; i++)
1342     {
1343       udp_nat_socks[i] = GNUNET_malloc(sizeof(struct UDP_Sock_Info));
1344       udp_nat_socks[i]->desc = NULL;
1345 #if IPV6
1346       if (GNUNET_YES !=
1347           GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "GNUNETD",
1348                                                 "DISABLE-IPV6"))
1349         {
1350           udp_nat_socks[i] = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 17);
1351           if (udp_nat_socks[i] != NULL)
1352             {
1353               memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1354     #if HAVE_SOCKADDR_IN_SIN_LEN
1355               serverAddrv6.sin6_len = sizeof (serverAddrv6);
1356     #endif
1357               serverAddrv6.sin6_family = AF_INET6;
1358               serverAddrv6.sin6_addr = in6addr_any;
1359               serverAddrv6.sin6_port = htons (i + plugin->starting_port);
1360               addrlen = sizeof (serverAddrv6);
1361               serverAddr = (struct sockaddr *) &serverAddrv6;
1362             }
1363         }
1364 #endif
1365       if (NULL == udp_nat_socks[i]->desc)
1366         {
1367           udp_nat_socks[i]->desc = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 17);
1368           if (NULL == udp_nat_socks[i]->desc)
1369             {
1370               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp-nat", "socket");
1371               return sockets_created;
1372             }
1373           else
1374             {
1375               memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1376     #if HAVE_SOCKADDR_IN_SIN_LEN
1377               serverAddrv4.sin_len = sizeof (serverAddrv4);
1378     #endif
1379               serverAddrv4.sin_family = AF_INET;
1380               serverAddrv4.sin_addr.s_addr = INADDR_ANY;
1381               if (i == 0)
1382                 serverAddrv4.sin_port = htons (plugin->starting_port);
1383               else
1384                 serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000); /* Find a non-root port */
1385               addrlen = sizeof (serverAddrv4);
1386               serverAddr = (struct sockaddr *) &serverAddrv4;
1387 #if DEBUG_UDP_NAT
1388               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1389                                "udp_nat",
1390                                "Binding to port %d\n", ntohs(serverAddrv4.sin_port));
1391 #endif
1392               while (GNUNET_NETWORK_socket_bind (udp_nat_socks[i]->desc, serverAddr, addrlen) !=
1393                              GNUNET_OK)
1394                 {
1395                   serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000); /* Find a good, non-root port */
1396 #if DEBUG_UDP_NAT
1397               GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1398                               "udp_nat",
1399                               "Binding failed, trying new port %d\n", ntohs(serverAddrv4.sin_port));
1400 #endif
1401                 }
1402               udp_nat_socks[i]->port = ntohs(serverAddrv4.sin_port);
1403               sockets_created++;
1404             }
1405         }
1406
1407     }
1408
1409   plugin->rs = GNUNET_NETWORK_fdset_create ();
1410
1411   GNUNET_NETWORK_fdset_zero (plugin->rs);
1412
1413   for (i = 0; i < plugin->num_ports; i++)
1414     {
1415       GNUNET_NETWORK_fdset_set (plugin->rs, udp_nat_socks[i]->desc);
1416     }
1417
1418   plugin->select_task =
1419     GNUNET_SCHEDULER_add_select (plugin->env->sched,
1420                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1421                                  GNUNET_SCHEDULER_NO_TASK,
1422                                  GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1423                                  NULL, &udp_nat_plugin_select, plugin);
1424
1425   return sockets_created;
1426 }
1427
1428
1429 /**
1430  * Check if the given port is plausible (must be either
1431  * our listen port or our advertised port).  If it is
1432  * neither, we return one of these two ports at random.
1433  *
1434  * @return either in_port or a more plausible port
1435  */
1436 static uint16_t
1437 check_port (struct Plugin *plugin, uint16_t in_port)
1438 {
1439
1440   /* FIXME: remember what ports we are using to better respond to this */
1441   return in_port;
1442   /*
1443   for (i = plugin->starting_port; i < plugin->num_ports + plugin->starting_port; i++)
1444     {
1445       if (in_port == i)
1446         return in_port;
1447     }
1448
1449   return GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1450                                     plugin->num_ports) + plugin->starting_port;
1451   */
1452 }
1453
1454
1455 /**
1456  * Another peer has suggested an address for this peer and transport
1457  * plugin.  Check that this could be a valid address.  This function
1458  * is not expected to 'validate' the address in the sense of trying to
1459  * connect to it but simply to see if the binary format is technically
1460  * legal for establishing a connection.
1461  *
1462  * @param cls closure, should be our handle to the Plugin
1463  * @param addr pointer to the address, may be modified (slightly)
1464  * @param addrlen length of addr
1465  * @return GNUNET_OK if this is a plausible address for this peer
1466  *         and transport, GNUNET_SYSERR if not
1467  *
1468  */
1469 static int
1470 udp_nat_check_address (void *cls, void *addr, size_t addrlen)
1471 {
1472   struct Plugin *plugin = cls;
1473   char buf[sizeof (struct sockaddr_in6)];
1474
1475   struct sockaddr_in *v4;
1476 #if IPV6
1477   struct sockaddr_in6 *v6;
1478 #endif
1479 #if IPV6
1480   if ((addrlen != sizeof (struct sockaddr_in)) &&
1481       (addrlen != sizeof (struct sockaddr_in6)))
1482 #else
1483     if (addrlen != sizeof (struct sockaddr_in))
1484 #endif
1485     {
1486       GNUNET_break_op (0);
1487       return GNUNET_SYSERR;
1488     }
1489   memcpy (buf, addr, sizeof (struct sockaddr_in6));
1490   if (addrlen == sizeof (struct sockaddr_in))
1491     {
1492       v4 = (struct sockaddr_in *) buf;
1493       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1494     }
1495 #if IPV6
1496   else
1497     {
1498       v6 = (struct sockaddr_in6 *) buf;
1499       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1500     }
1501 #endif
1502 #if DEBUG_UDP_NAT
1503   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1504                    "udp_nat",
1505                    "Informing transport service about my address `%s'.\n",
1506                    GNUNET_a2s (addr, addrlen));
1507 #endif
1508   return GNUNET_OK;
1509 }
1510
1511
1512 /**
1513  * Append our port and forward the result.
1514  */
1515 static void
1516 append_port (void *cls, const char *hostname)
1517 {
1518   struct PrettyPrinterContext *ppc = cls;
1519   char *ret;
1520
1521   if (hostname == NULL)
1522     {
1523       ppc->asc (ppc->asc_cls, NULL);
1524       GNUNET_free (ppc);
1525       return;
1526     }
1527   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1528   ppc->asc (ppc->asc_cls, ret);
1529   GNUNET_free (ret);
1530 }
1531
1532
1533 /**
1534  * Convert the transports address to a nice, human-readable
1535  * format.
1536  *
1537  * @param cls closure
1538  * @param type name of the transport that generated the address
1539  * @param addr one of the addresses of the host, NULL for the last address
1540  *        the specific address format depends on the transport
1541  * @param addrlen length of the address
1542  * @param numeric should (IP) addresses be displayed in numeric form?
1543  * @param timeout after how long should we give up?
1544  * @param asc function to call on each string
1545  * @param asc_cls closure for asc
1546  */
1547 static void
1548 udp_nat_plugin_address_pretty_printer (void *cls,
1549                                    const char *type,
1550                                    const void *addr,
1551                                    size_t addrlen,
1552                                    int numeric,
1553                                    struct GNUNET_TIME_Relative timeout,
1554                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1555                                    void *asc_cls)
1556 {
1557   struct Plugin *plugin = cls;
1558   const struct sockaddr_in *v4;
1559   const struct sockaddr_in6 *v6;
1560   struct PrettyPrinterContext *ppc;
1561
1562   if ((addrlen != sizeof (struct sockaddr_in)) &&
1563       (addrlen != sizeof (struct sockaddr_in6)))
1564     {
1565       /* invalid address */
1566       GNUNET_break_op (0);
1567       asc (asc_cls, NULL);
1568       return;
1569     }
1570   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1571   ppc->asc = asc;
1572   ppc->asc_cls = asc_cls;
1573   if (addrlen == sizeof (struct sockaddr_in))
1574     {
1575       v4 = (const struct sockaddr_in *) addr;
1576       ppc->port = ntohs (v4->sin_port);
1577     }
1578   else
1579     {
1580       v6 = (const struct sockaddr_in6 *) addr;
1581       ppc->port = ntohs (v6->sin6_port);
1582
1583     }
1584   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1585                                 plugin->env->cfg,
1586                                 addr,
1587                                 addrlen,
1588                                 !numeric, timeout, &append_port, ppc);
1589 }
1590
1591
1592 /**
1593  * The exported method. Makes the core api available via a global and
1594  * returns the udp transport API.
1595  */
1596 void *
1597 libgnunet_plugin_transport_udp_nat_init (void *cls)
1598 {
1599   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1600   unsigned long long mtu;
1601   unsigned long long starting_port;
1602   struct GNUNET_TRANSPORT_PluginFunctions *api;
1603   struct Plugin *plugin;
1604   struct GNUNET_SERVICE_Context *service;
1605   int sockets_created;
1606   int behind_nat;
1607   char *internal_address;
1608   char *external_address;
1609
1610   service = GNUNET_SERVICE_start ("transport-udp-nat", env->sched, env->cfg);
1611   if (service == NULL)
1612     {
1613       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "udp_nat", _
1614                        ("Failed to start service for `%s' transport plugin.\n"),
1615                        "udp-nat");
1616       return NULL;
1617     }
1618
1619   if (GNUNET_OK !=
1620          GNUNET_CONFIGURATION_get_value_string (env->cfg,
1621                                                 "transport-udp-nat",
1622                                                 "EXTERNAL_ADDRESS",
1623                                                 &external_address))
1624     {
1625       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1626                        "udp_nat",
1627                        _
1628                        ("Require EXTERNAL_ADDRESS for service `%s' in configuration!\n"),
1629                        "transport-udp");
1630       GNUNET_SERVICE_stop (service);
1631       return NULL;
1632     }
1633
1634   if (GNUNET_OK !=
1635          GNUNET_CONFIGURATION_get_value_string (env->cfg,
1636                                                 "transport-udp-nat",
1637                                                 "INTERNAL_ADDRESS",
1638                                                 &internal_address))
1639     {
1640       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1641                        "udp_nat",
1642                        _
1643                        ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
1644                        "transport-udp");
1645       GNUNET_SERVICE_stop (service);
1646       GNUNET_free_non_null(external_address);
1647       return NULL;
1648     }
1649
1650   if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
1651                                                          "transport-udp-nat",
1652                                                          "BEHIND_NAT"))
1653     behind_nat = GNUNET_NO; /* We are not behind nat, or so says the user! */
1654   else
1655     behind_nat = GNUNET_YES; /* Assume we are behind nat (default) */
1656
1657   if (GNUNET_OK !=
1658       GNUNET_CONFIGURATION_get_value_number (env->cfg,
1659                                              "transport-udp-nat",
1660                                              "PORT",
1661                                              &starting_port))
1662     starting_port = UDP_NAT_STARTING_PORT;
1663   else if (starting_port > 65535)
1664     {
1665       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1666                        "udp_nat",
1667                        _("Given `%s' option is out of range: %llu > %u\n"),
1668                        "PORT",
1669                        starting_port,
1670                        65535);
1671       GNUNET_SERVICE_stop (service);
1672       GNUNET_free_non_null(external_address);
1673       GNUNET_free_non_null(internal_address);
1674       return NULL;      
1675     }
1676
1677   mtu = 1240;
1678   if (mtu < 1200)
1679     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1680                      "udp_nat",
1681                      _("MTU %llu for `%s' is probably too low!\n"), mtu,
1682                      "UDP");
1683
1684   plugin = GNUNET_malloc (sizeof (struct Plugin));
1685   plugin->external_address = external_address;
1686   plugin->internal_address = internal_address;
1687   plugin->starting_port = (uint16_t) UDP_NAT_STARTING_PORT;
1688   plugin->behind_nat = behind_nat;
1689   if (plugin->behind_nat == GNUNET_NO)
1690     plugin->num_ports = 1; /* Only use one port/socket */
1691   else
1692     plugin->num_ports = UDP_NAT_LISTEN_PORTS;
1693
1694   plugin->env = env;
1695   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1696   api->cls = plugin;
1697
1698   api->send = &udp_nat_plugin_send;
1699   api->disconnect = &udp_nat_disconnect;
1700   api->address_pretty_printer = &udp_nat_plugin_address_pretty_printer;
1701   api->check_address = &udp_nat_check_address;
1702
1703   plugin->service = service;
1704
1705   plugin->random_starting_port = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000;
1706
1707   /* FIXME: do the two calls below periodically again and
1708      not just once (since the info we get might change...) */
1709   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1710   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1711                                                            env->cfg,
1712                                                            AF_UNSPEC,
1713                                                            HOSTNAME_RESOLVE_TIMEOUT,
1714                                                            &process_hostname_ips,
1715                                                            plugin);
1716
1717   sockets_created = udp_nat_transport_server_start (plugin);
1718
1719   GNUNET_assert (sockets_created == plugin->num_ports);
1720
1721   return api;
1722 }
1723
1724
1725 void *
1726 libgnunet_plugin_transport_udp_nat_done (void *cls)
1727 {
1728   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1729   struct Plugin *plugin = api->cls;
1730
1731   udp_nat_transport_server_stop (plugin);
1732   if (NULL != hostname_dns)
1733     {
1734       GNUNET_RESOLVER_request_cancel (hostname_dns);
1735       hostname_dns = NULL;
1736     }
1737   GNUNET_SERVICE_stop (plugin->service);
1738
1739   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1740   GNUNET_free (plugin);
1741   GNUNET_free (api);
1742   return NULL;
1743 }
1744
1745 /* end of plugin_transport_udp.c */