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