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