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