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