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