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