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