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