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