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