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