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