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