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