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