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