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