c6ba8ef839ada34e78ec0d3ae09f27f501b1ac2f
[oweals/gnunet.git] / src / transport / plugin_transport_udp.c
1 /*
2      This file is part of GNUnet
3      (C) 2010, 2011 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 #include "platform.h"
29 #include "gnunet_hello_lib.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_fragmentation_lib.h"
32 #include "gnunet_nat_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_resolver_service.h"
35 #include "gnunet_signatures.h"
36 #include "gnunet_constants.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
41
42 #define LOG(kind,...) GNUNET_log_from (kind, "transport-udp", __VA_ARGS__)
43
44
45 #define DEBUG_UDP GNUNET_EXTRA_LOGGING
46
47 /**
48  * MTU for fragmentation subsystem.  Should be conservative since
49  * all communicating peers MUST work with this MTU.
50  */
51 #define UDP_MTU 1400
52
53 /**
54  * Number of messages we can defragment in parallel.  We only really
55  * defragment 1 message at a time, but if messages get re-ordered, we
56  * may want to keep knowledge about the previous message to avoid
57  * discarding the current message in favor of a single fragment of a
58  * previous message.  3 should be good since we don't expect massive
59  * message reorderings with UDP.
60  */
61 #define UDP_MAX_MESSAGES_IN_DEFRAG 3
62
63 /**
64  * We keep a defragmentation queue per sender address.  How many
65  * sender addresses do we support at the same time? Memory consumption
66  * is roughly a factor of 32k * UDP_MAX_MESSAGES_IN_DEFRAG times this
67  * value. (So 128 corresponds to 12 MB and should suffice for
68  * connecting to roughly 128 peers via UDP).
69  */
70 #define UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG 128
71
72
73 /**
74  * UDP Message-Packet header (after defragmentation).
75  */
76 struct UDPMessage
77 {
78   /**
79    * Message header.
80    */
81   struct GNUNET_MessageHeader header;
82
83   /**
84    * Always zero for now.
85    */
86   uint32_t reserved;
87
88   /**
89    * What is the identity of the sender
90    */
91   struct GNUNET_PeerIdentity sender;
92
93 };
94
95
96 /**
97  * Network format for IPv4 addresses.
98  */
99 struct IPv4UdpAddress
100 {
101   /**
102    * IPv4 address, in network byte order.
103    */
104   uint32_t ipv4_addr GNUNET_PACKED;
105
106   /**
107    * Port number, in network byte order.
108    */
109   uint16_t u4_port GNUNET_PACKED;
110 };
111
112
113 /**
114  * Network format for IPv6 addresses.
115  */
116 struct IPv6UdpAddress
117 {
118
119   /**
120    * IPv6 address.
121    */
122   struct in6_addr ipv6_addr GNUNET_PACKED;
123
124   /**
125    * Port number, in network byte order.
126    */
127   uint16_t u6_port GNUNET_PACKED;
128 };
129
130
131 /* Forward definition */
132 struct Plugin;
133
134
135 /**
136  * Session with another peer.  FIXME: why not make this into
137  * a regular 'struct Session' and pass it around!?
138  */
139 struct PeerSession
140 {
141
142   /**
143    * Which peer is this session for?
144    */
145   struct GNUNET_PeerIdentity target;
146
147   /**
148    * Pointer to the global plugin struct.
149    */
150   struct Plugin *plugin;
151
152   /**
153    * Address of the other peer
154    */
155   const struct sockaddr *sock_addr;
156
157   size_t addrlen;
158
159   /**
160    * Function to call upon completion of the transmission.
161    */
162   GNUNET_TRANSPORT_TransmitContinuation cont;
163
164   /**
165    * Closure for 'cont'.
166    */
167   void *cont_cls;
168
169   /**
170    * Current outgoing message to this peer.
171    */
172   struct GNUNET_FRAGMENT_Context *frag;
173
174   struct GNUNET_TIME_Absolute valid_until;
175
176 };
177
178
179 /**
180  * Data structure to track defragmentation contexts based
181  * on the source of the UDP traffic.
182  */
183 struct ReceiveContext
184 {
185
186   /**
187    * Defragmentation context.
188    */
189   struct GNUNET_DEFRAGMENT_Context *defrag;
190
191   /**
192    * Source address this receive context is for (allocated at the
193    * end of the struct).
194    */
195   const struct sockaddr *src_addr;
196
197   /**
198    * Reference to master plugin struct.
199    */
200   struct Plugin *plugin;
201
202   /**
203    * Node in the defrag heap.
204    */
205   struct GNUNET_CONTAINER_HeapNode *hnode;
206
207   /**
208    * Length of 'src_addr'
209    */
210   size_t addr_len;
211
212 };
213
214
215 /**
216  * Encapsulation of all of the state of the plugin.
217  */
218 struct Plugin
219 {
220
221   /**
222    * Our environment.
223    */
224   struct GNUNET_TRANSPORT_PluginEnvironment *env;
225
226   /**
227    * Session of peers with whom we are currently connected,
228    * map of peer identity to 'struct PeerSession'.
229    */
230   struct GNUNET_CONTAINER_MultiHashMap *sessions;
231
232   /**
233    * Session of peers with whom we are currently connected,
234    * map of peer identity to 'struct PeerSession'.
235    */
236   struct GNUNET_CONTAINER_MultiHashMap *inbound_sessions;
237
238   /**
239    * Heap with all of our defragmentation activities.
240    */
241   struct GNUNET_CONTAINER_Heap *defrags;
242
243   /**
244    * ID of select task
245    */
246   GNUNET_SCHEDULER_TaskIdentifier select_task;
247
248   /**
249    * Tokenizer for inbound messages.
250    */
251   struct GNUNET_SERVER_MessageStreamTokenizer *mst;
252
253   /**
254    * Bandwidth tracker to limit global UDP traffic.
255    */
256   struct GNUNET_BANDWIDTH_Tracker tracker;
257
258   /**
259    * Address we were told to bind to exclusively (IPv4).
260    */
261   char *bind4_address;
262
263   /**
264    * Address we were told to bind to exclusively (IPv6).
265    */
266   char *bind6_address;
267
268   /**
269    * Handle to NAT traversal support.
270    */
271   struct GNUNET_NAT_Handle *nat;
272
273   /**
274    * FD Read set
275    */
276   struct GNUNET_NETWORK_FDSet *rs;
277
278   /**
279    * The read socket for IPv4
280    */
281   struct GNUNET_NETWORK_Handle *sockv4;
282
283   /**
284    * The read socket for IPv6
285    */
286   struct GNUNET_NETWORK_Handle *sockv6;
287
288   /**
289    * expected delay for ACKs
290    */
291   struct GNUNET_TIME_Relative last_expected_delay;
292
293   /**
294    * Port we listen on.
295    */
296   uint16_t port;
297
298   /**
299    * Port we advertise on.
300    */
301   uint16_t aport;
302
303 };
304
305 struct PeerSessionIteratorContext
306 {
307   struct PeerSession * result;
308   const void * addr;
309   size_t addrlen;
310 };
311
312
313 /**
314  * Lookup the session for the given peer.
315  *
316  * @param plugin the plugin
317  * @param peer peer's identity
318  * @return NULL if we have no session
319  */
320 struct PeerSession *
321 find_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *peer)
322 {
323   return GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
324                                             &peer->hashPubKey);
325 }
326
327 int inbound_session_iterator (void *cls,
328                              const GNUNET_HashCode * key,
329                              void *value)
330 {
331   struct PeerSessionIteratorContext *psc = cls;
332   struct PeerSession *s = value;
333   if (s->addrlen == psc->addrlen)
334   {
335     if (0 == memcmp (&s[1], psc->addr, s->addrlen))
336       psc->result = s;
337   }
338   if (psc->result != NULL)
339     return GNUNET_NO;
340   else
341     return GNUNET_YES;
342 };
343
344 /**
345  * Lookup the session for the given peer.
346  *
347  * @param plugin the plugin
348  * @param peer peer's identity
349  * @return NULL if we have no session
350  */
351 struct PeerSession *
352 find_inbound_session (struct Plugin *plugin,
353                       const struct GNUNET_PeerIdentity *peer,
354                       const void * addr, size_t addrlen)
355 {
356   struct PeerSessionIteratorContext psc;
357   psc.result = NULL;
358   psc.addrlen = addrlen;
359   psc.addr = addr;
360
361   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->inbound_sessions, &peer->hashPubKey, &inbound_session_iterator, &psc);
362   return psc.result;
363 }
364
365
366 /**
367  * Disconnect from a remote node.  Clean up session if we have one for this peer
368  *
369  * @param cls closure for this call (should be handle to Plugin)
370  * @param target the peeridentity of the peer to disconnect
371  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
372  */
373 static void
374 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
375 {
376   struct Plugin *plugin = cls;
377   struct PeerSession *session;
378
379   session = find_session (plugin, target);
380   if (NULL == session)
381     return;
382   GNUNET_assert (GNUNET_OK ==
383                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
384                                                        &target->hashPubKey,
385                                                        session));
386   plugin->last_expected_delay = GNUNET_FRAGMENT_context_destroy (session->frag);
387   if (session->cont != NULL)
388     session->cont (session->cont_cls, target, GNUNET_SYSERR);
389   GNUNET_free (session);
390 }
391
392
393 /**
394  * Actually send out the message.
395  *
396  * @param plugin the plugin
397  * @param sa the address to send the message to
398  * @param msg message to transmit
399  * @return the number of bytes written
400  */
401 static ssize_t
402 udp_send (struct Plugin *plugin, const struct sockaddr *sa,
403           const struct GNUNET_MessageHeader *msg)
404 {
405   ssize_t sent;
406   size_t slen;
407
408   switch (sa->sa_family)
409   {
410   case AF_INET:
411     if (NULL == plugin->sockv4)
412       return 0;
413     sent =
414         GNUNET_NETWORK_socket_sendto (plugin->sockv4, msg, ntohs (msg->size),
415                                       sa, slen = sizeof (struct sockaddr_in));
416     break;
417   case AF_INET6:
418     if (NULL == plugin->sockv6)
419       return 0;
420     sent =
421         GNUNET_NETWORK_socket_sendto (plugin->sockv6, msg, ntohs (msg->size),
422                                       sa, slen = sizeof (struct sockaddr_in6));
423     break;
424   default:
425     GNUNET_break (0);
426     return 0;
427   }
428   if (GNUNET_SYSERR == sent)
429     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
430   LOG (GNUNET_ERROR_TYPE_DEBUG,
431               "UDP transmited %u-byte message to %s (%d: %s)\n",
432               (unsigned int) ntohs (msg->size), GNUNET_a2s (sa, slen),
433               (int) sent, (sent < 0) ? STRERROR (errno) : "ok");
434   return sent;
435 }
436
437
438 /**
439  * Function that is called with messages created by the fragmentation
440  * module.  In the case of the 'proc' callback of the
441  * GNUNET_FRAGMENT_context_create function, this function must
442  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
443  *
444  * @param cls closure, the 'struct PeerSession'
445  * @param msg the message that was created
446  */
447 static void
448 send_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
449 {
450   struct PeerSession *session = cls;
451
452   udp_send (session->plugin, session->sock_addr, msg);
453   GNUNET_FRAGMENT_context_transmission_done (session->frag);
454 }
455
456 static struct PeerSession *
457 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
458     const void *addr, size_t addrlen,
459     GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
460 {
461   struct PeerSession * peer_session;
462   const struct IPv4UdpAddress *t4;
463   const struct IPv6UdpAddress *t6;
464   struct sockaddr_in *v4;
465   struct sockaddr_in6 *v6;
466   size_t len;
467
468   switch (addrlen)
469   {
470   case sizeof (struct IPv4UdpAddress):
471     if (NULL == plugin->sockv4)
472     {
473       return NULL;
474     }
475     t4 = addr;
476     peer_session =
477         GNUNET_malloc (sizeof (struct PeerSession) +
478                        sizeof (struct sockaddr_in));
479     len = sizeof (struct sockaddr_in);
480     v4 = (struct sockaddr_in *) &peer_session[1];
481     v4->sin_family = AF_INET;
482 #if HAVE_SOCKADDR_IN_SIN_LEN
483     v4->sin_len = sizeof (struct sockaddr_in);
484 #endif
485     v4->sin_port = t4->u4_port;
486     v4->sin_addr.s_addr = t4->ipv4_addr;
487     break;
488   case sizeof (struct IPv6UdpAddress):
489     if (NULL == plugin->sockv6)
490     {
491       return NULL;
492     }
493     t6 = addr;
494     peer_session =
495         GNUNET_malloc (sizeof (struct PeerSession) +
496                        sizeof (struct sockaddr_in6));
497     len = sizeof (struct sockaddr_in6);
498     v6 = (struct sockaddr_in6 *) &peer_session[1];
499     v6->sin6_family = AF_INET6;
500 #if HAVE_SOCKADDR_IN_SIN_LEN
501     v6->sin6_len = sizeof (struct sockaddr_in6);
502 #endif
503     v6->sin6_port = t6->u6_port;
504     v6->sin6_addr = t6->ipv6_addr;
505     break;
506   default:
507     /* Must have a valid address to send to */
508     GNUNET_break_op (0);
509     return NULL;
510   }
511
512   peer_session->addrlen = len;
513   peer_session->target = *target;
514   peer_session->plugin = plugin;
515   peer_session->sock_addr = (const struct sockaddr *) &peer_session[1];
516   peer_session->cont = cont;
517   peer_session->cont_cls = cont_cls;
518
519   return peer_session;
520 }
521
522 static const char *
523 udp_address_to_string (void *cls, const void *addr, size_t addrlen);
524
525 /**
526  * Function that can be used by the transport service to transmit
527  * a message using the plugin.
528  *
529  * @param cls closure
530  * @param target who should receive this message (ignored by UDP)
531  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
532  * @param msgbuf_size the size of the msgbuf to send
533  * @param priority how important is the message (ignored by UDP)
534  * @param timeout when should we time out (give up) if we can not transmit?
535  * @param session identifier used for this session (NULL for UDP)
536  * @param addr the addr to send the message to
537  * @param addrlen the len of addr
538  * @param force_address not used, we had better have an address to send to
539  *        because we are stateless!!
540  * @param cont continuation to call once the message has
541  *        been transmitted (or if the transport is ready
542  *        for the next transmission call; or if the
543  *        peer disconnected...)
544  * @param cont_cls closure for cont
545  *
546  * @return the number of bytes written (may return 0 and the message can
547  *         still be transmitted later!)
548  */
549 static ssize_t
550 udp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
551                  const char *msgbuf, size_t msgbuf_size, unsigned int priority,
552                  struct GNUNET_TIME_Relative timeout, struct Session *session,
553                  const void *addr, size_t addrlen, int force_address,
554                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
555 {
556   struct Plugin *plugin = cls;
557   struct PeerSession *peer_session;
558   struct PeerSession *inbound_session;
559   const struct IPv4UdpAddress *t4;
560   const struct IPv6UdpAddress *t6;
561   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
562   char mbuf[mlen];
563   struct UDPMessage *udp;
564
565   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
566   {
567     GNUNET_break (0);
568     return GNUNET_SYSERR;
569   }
570
571   LOG (GNUNET_ERROR_TYPE_DEBUG,
572               "UDP transmits %u-byte message to `%s' using address `%s' session 0x%X mode %i\n",
573               msgbuf_size, GNUNET_i2s (target), udp_address_to_string (NULL, addr, addrlen), session, force_address);
574
575   if ((force_address == GNUNET_SYSERR) && (session == NULL))
576     return GNUNET_SYSERR;
577
578   /* safety check: comparing address to address stored in session */
579   if ((session != NULL) && (addr != NULL) && (addrlen != 0))
580   {
581     inbound_session = (struct PeerSession *) session;
582     /* session timed out */
583     if (GNUNET_TIME_absolute_get().abs_value > inbound_session->valid_until.abs_value)
584     {
585         /* TODO: remove session */
586       if (force_address == GNUNET_SYSERR)
587         return GNUNET_SYSERR;
588     }
589     if  (0 != memcmp (&inbound_session->target, target, sizeof (struct GNUNET_PeerIdentity)))
590       return GNUNET_SYSERR;
591     switch (addrlen)
592     {
593     case sizeof (struct IPv4UdpAddress):
594       if (NULL == plugin->sockv4)
595       {
596         if (cont != NULL)
597           cont (cont_cls, target, GNUNET_SYSERR);
598         return GNUNET_SYSERR;
599       }
600       t4 = addr;
601       if (inbound_session->addrlen != (sizeof (struct sockaddr_in)))
602         return GNUNET_SYSERR;
603       struct sockaddr_in *a4 = (struct sockaddr_in *) inbound_session->sock_addr;
604       GNUNET_assert (a4->sin_port == t4->u4_port);
605       GNUNET_assert (0 == memcmp(&a4->sin_addr, &t4->ipv4_addr, sizeof (struct in_addr)));
606       LOG (GNUNET_ERROR_TYPE_DEBUG,
607                   "Session 0x%X successfully checked!\n", session);
608       break;
609     case sizeof (struct IPv6UdpAddress):
610       if (NULL == plugin->sockv6)
611       {
612         if (cont != NULL)
613           cont (cont_cls, target, GNUNET_SYSERR);
614         return GNUNET_SYSERR;
615       }
616       t6 = addr;
617       GNUNET_assert (inbound_session->addrlen == sizeof (struct sockaddr_in6));
618       struct sockaddr_in6 *a6 = (struct sockaddr_in6 *) inbound_session->sock_addr;
619       GNUNET_assert (a6->sin6_port == t6->u6_port);
620       GNUNET_assert (0 == memcmp(&a6->sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr)));
621       LOG (GNUNET_ERROR_TYPE_DEBUG,
622                   "Session 0x%X successfully checked!\n", session);
623       break;
624     default:
625       /* Must have a valid address to send to */
626       GNUNET_break_op (0);
627     }
628   }
629
630   peer_session = create_session (plugin, target, addr, addrlen, cont, cont_cls);
631   if (peer_session == NULL)
632   {
633     if (cont != NULL)
634       cont (cont_cls, target, GNUNET_SYSERR);
635   }
636
637   /* Message */
638   udp = (struct UDPMessage *) mbuf;
639   udp->header.size = htons (mlen);
640   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
641   udp->reserved = htonl (0);
642   udp->sender = *plugin->env->my_identity;
643   memcpy (&udp[1], msgbuf, msgbuf_size);
644
645   if (mlen <= UDP_MTU)
646   {
647     mlen = udp_send (plugin, peer_session->sock_addr, &udp->header);
648     if (cont != NULL)
649       cont (cont_cls, target, (mlen > 0) ? GNUNET_OK : GNUNET_SYSERR);
650     GNUNET_free_non_null (peer_session);
651   }
652   else
653   {
654     GNUNET_assert (GNUNET_OK ==
655                    GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
656                                                       &target->hashPubKey,
657                                                       peer_session,
658                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
659     peer_session->frag =
660         GNUNET_FRAGMENT_context_create (plugin->env->stats, UDP_MTU,
661                                         &plugin->tracker,
662                                         plugin->last_expected_delay,
663                                         &udp->header, &send_fragment,
664                                         peer_session);
665   }
666   return mlen;
667 }
668
669
670 /**
671  * Closure for 'process_inbound_tokenized_messages'
672  */
673 struct SourceInformation
674 {
675   /**
676    * Sender identity.
677    */
678   struct GNUNET_PeerIdentity sender;
679
680   /**
681    * Source address.
682    */
683   const void *arg;
684
685   /**
686    * Number of bytes in source address.
687    */
688   size_t args;
689
690   struct PeerSession * session;
691 };
692
693
694 /**
695  * Message tokenizer has broken up an incomming message. Pass it on
696  * to the service.
697  *
698  * @param cls the 'struct Plugin'
699  * @param client the 'struct SourceInformation'
700  * @param hdr the actual message
701  */
702 static void
703 process_inbound_tokenized_messages (void *cls, void *client,
704                                     const struct GNUNET_MessageHeader *hdr)
705 {
706   struct Plugin *plugin = cls;
707   struct SourceInformation *si = client;
708   struct GNUNET_TRANSPORT_ATS_Information distance[2];
709
710   /* setup ATS */
711   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
712   distance[0].value = htonl (1);
713   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
714   distance[1].value = htonl (0);
715
716   LOG (GNUNET_ERROR_TYPE_DEBUG,
717                    "Giving Session %X %s  to transport\n", (struct Session *) si->session, GNUNET_i2s(&si->session->target));
718   plugin->env->receive (plugin->env->cls, &si->sender, hdr, distance, 2, (struct Session *) si->session,
719                         si->arg, si->args);
720 }
721
722
723 /**
724  * We've received a UDP Message.  Process it (pass contents to main service).
725  *
726  * @param plugin plugin context
727  * @param msg the message
728  * @param sender_addr sender address
729  * @param sender_addr_len number of bytes in sender_addr
730  */
731 static void
732 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
733                      const struct sockaddr *sender_addr,
734                      socklen_t sender_addr_len)
735 {
736   struct SourceInformation si;
737   struct IPv4UdpAddress u4;
738   struct IPv6UdpAddress u6;
739   const void *arg;
740   size_t args;
741
742   if (0 != ntohl (msg->reserved))
743   {
744     GNUNET_break_op (0);
745     return;
746   }
747   if (ntohs (msg->header.size) <
748       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
749   {
750     GNUNET_break_op (0);
751     return;
752   }
753
754   /* convert address */
755   switch (sender_addr->sa_family)
756   {
757   case AF_INET:
758     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
759     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
760     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
761     arg = &u4;
762     args = sizeof (u4);
763     break;
764   case AF_INET6:
765     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
766     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
767     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
768     arg = &u6;
769     args = sizeof (u6);
770     break;
771   default:
772     GNUNET_break (0);
773     return;
774   }
775 #if DEBUG_UDP
776   LOG (GNUNET_ERROR_TYPE_DEBUG,
777                    "Received message with %u bytes from peer `%s' at `%s'\n",
778                    (unsigned int) ntohs (msg->header.size),
779                    GNUNET_i2s (&msg->sender), GNUNET_a2s (sender_addr,
780                                                           sender_addr_len));
781 #endif
782
783   /* create a session for inbound connections */
784   const struct UDPMessage * udp_msg = (const struct UDPMessage *) msg;
785   LOG (GNUNET_ERROR_TYPE_DEBUG,
786               "Lookup inbound UDP sessions for peer `%s' address `%s'\n",
787               GNUNET_i2s (&udp_msg->sender),
788               udp_address_to_string(NULL, arg, args));
789
790   struct PeerSession * s = NULL;
791   s = find_inbound_session (plugin, &udp_msg->sender, sender_addr, sender_addr_len);
792
793   if (s != NULL)
794   {
795     LOG (GNUNET_ERROR_TYPE_DEBUG,
796                 "Found existing inbound UDP sessions 0x%X for peer `%s' address `%s'\n",
797                 s,
798                 GNUNET_i2s (&s->target),
799                 udp_address_to_string(NULL, arg, args));
800   }
801   else
802   {
803     s = create_session (plugin, &udp_msg->sender, arg, args, NULL, NULL);
804     LOG (GNUNET_ERROR_TYPE_DEBUG,
805                 "Creating inbound UDP sessions 0x%X for peer `%s' address `%s'\n",
806                 s,
807                 GNUNET_i2s (&s->target),
808                 udp_address_to_string(NULL, arg, args));
809
810     GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (plugin->inbound_sessions,
811                                                       &s->target.hashPubKey,
812                                                       s,
813                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
814   }
815   s->valid_until = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
816
817   /* iterate over all embedded messages */
818   si.sender = msg->sender;
819   si.arg = arg;
820   si.args = args;
821   si.session = s;
822   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
823                              ntohs (msg->header.size) -
824                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
825 }
826
827
828 /**
829  * Process a defragmented message.
830  *
831  * @param cls the 'struct ReceiveContext'
832  * @param msg the message
833  */
834 static void
835 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
836 {
837   struct ReceiveContext *rc = cls;
838
839   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
840   {
841     GNUNET_break (0);
842     return;
843   }
844   if (ntohs (msg->size) < sizeof (struct UDPMessage))
845   {
846     GNUNET_break (0);
847     return;
848   }
849   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
850                        rc->src_addr, rc->addr_len);
851 }
852
853
854 /**
855  * Transmit an acknowledgement.
856  *
857  * @param cls the 'struct ReceiveContext'
858  * @param id message ID (unused)
859  * @param msg ack to transmit
860  */
861 static void
862 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
863 {
864   struct ReceiveContext *rc = cls;
865   size_t msize = sizeof (struct UDPMessage) + ntohs (msg->size);
866   char buf[msize];
867   struct UDPMessage *udp;
868
869 #if DEBUG_UDP
870   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending ACK to `%s'\n",
871                    GNUNET_a2s (rc->src_addr,
872                                (rc->src_addr->sa_family ==
873                                 AF_INET) ? sizeof (struct sockaddr_in) :
874                                sizeof (struct sockaddr_in6)));
875 #endif
876   udp = (struct UDPMessage *) buf;
877   udp->header.size = htons ((uint16_t) msize);
878   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
879   udp->reserved = htonl (0);
880   udp->sender = *rc->plugin->env->my_identity;
881   memcpy (&udp[1], msg, ntohs (msg->size));
882   (void) udp_send (rc->plugin, rc->src_addr, &udp->header);
883 }
884
885
886 /**
887  * Closure for 'find_receive_context'.
888  */
889 struct FindReceiveContext
890 {
891   /**
892    * Where to store the result.
893    */
894   struct ReceiveContext *rc;
895
896   /**
897    * Address to find.
898    */
899   const struct sockaddr *addr;
900
901   /**
902    * Number of bytes in 'addr'.
903    */
904   socklen_t addr_len;
905 };
906
907
908 /**
909  * Scan the heap for a receive context with the given address.
910  *
911  * @param cls the 'struct FindReceiveContext'
912  * @param node internal node of the heap
913  * @param element value stored at the node (a 'struct ReceiveContext')
914  * @param cost cost associated with the node
915  * @return GNUNET_YES if we should continue to iterate,
916  *         GNUNET_NO if not.
917  */
918 static int
919 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
920                       void *element, GNUNET_CONTAINER_HeapCostType cost)
921 {
922   struct FindReceiveContext *frc = cls;
923   struct ReceiveContext *e = element;
924
925   if ((frc->addr_len == e->addr_len) &&
926       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
927   {
928     frc->rc = e;
929     return GNUNET_NO;
930   }
931   return GNUNET_YES;
932 }
933
934
935 /**
936  * Read and process a message from the given socket.
937  *
938  * @param plugin the overall plugin
939  * @param rsock socket to read from
940  */
941 static void
942 udp_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
943 {
944   socklen_t fromlen;
945   char addr[32];
946   char buf[65536];
947   ssize_t ret;
948   const struct GNUNET_MessageHeader *msg;
949   const struct GNUNET_MessageHeader *ack;
950   struct PeerSession *peer_session;
951   const struct UDPMessage *udp;
952   struct ReceiveContext *rc;
953   struct GNUNET_TIME_Absolute now;
954   struct FindReceiveContext frc;
955
956   fromlen = sizeof (addr);
957   memset (&addr, 0, sizeof (addr));
958   ret =
959       GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
960                                       (struct sockaddr *) &addr, &fromlen);
961   if (ret < sizeof (struct GNUNET_MessageHeader))
962   {
963     GNUNET_break_op (0);
964     return;
965   }
966 #if DEBUG_UDP
967   LOG (GNUNET_ERROR_TYPE_DEBUG,
968               "UDP received %u-byte message from `%s'\n", (unsigned int) ret,
969               GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
970 #endif
971   msg = (const struct GNUNET_MessageHeader *) buf;
972   if (ret != ntohs (msg->size))
973   {
974     GNUNET_break_op (0);
975     return;
976   }
977   switch (ntohs (msg->type))
978   {
979   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
980     if (ntohs (msg->size) < sizeof (struct UDPMessage))
981     {
982       GNUNET_break_op (0);
983       return;
984     }
985     process_udp_message (plugin, (const struct UDPMessage *) msg,
986                          (const struct sockaddr *) addr, fromlen);
987     return;
988   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
989     if (ntohs (msg->size) <
990         sizeof (struct UDPMessage) + sizeof (struct GNUNET_MessageHeader))
991     {
992       GNUNET_break_op (0);
993       return;
994     }
995     udp = (const struct UDPMessage *) msg;
996     if (ntohl (udp->reserved) != 0)
997     {
998       GNUNET_break_op (0);
999       return;
1000     }
1001     ack = (const struct GNUNET_MessageHeader *) &udp[1];
1002     if (ntohs (ack->size) != ntohs (msg->size) - sizeof (struct UDPMessage))
1003     {
1004       GNUNET_break_op (0);
1005       return;
1006     }
1007 #if DEBUG_UDP
1008     LOG (GNUNET_ERROR_TYPE_DEBUG,
1009                 "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1010                 (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp->sender),
1011                 GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1012 #endif
1013
1014     peer_session = find_session (plugin, &udp->sender);
1015     if (NULL == peer_session)
1016     {
1017 #if DEBUG_UDP
1018       LOG (GNUNET_ERROR_TYPE_DEBUG,
1019                   "Session for ACK not found, dropping ACK!\n");
1020 #endif
1021       return;
1022     }
1023     if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (peer_session->frag, ack))
1024       return;
1025     GNUNET_assert (GNUNET_OK ==
1026                    GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
1027                                                          &udp->
1028                                                          sender.hashPubKey,
1029                                                          peer_session));
1030     plugin->last_expected_delay =
1031         GNUNET_FRAGMENT_context_destroy (peer_session->frag);
1032     if (peer_session->cont != NULL)
1033       peer_session->cont (peer_session->cont_cls, &udp->sender, GNUNET_OK);
1034     GNUNET_free (peer_session);
1035     return;
1036   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1037     frc.rc = NULL;
1038     frc.addr = (const struct sockaddr *) addr;
1039     frc.addr_len = fromlen;
1040     GNUNET_CONTAINER_heap_iterate (plugin->defrags, &find_receive_context,
1041                                    &frc);
1042     now = GNUNET_TIME_absolute_get ();
1043     rc = frc.rc;
1044     if (rc == NULL)
1045     {
1046       /* need to create a new RC */
1047       rc = GNUNET_malloc (sizeof (struct ReceiveContext) + fromlen);
1048       memcpy (&rc[1], addr, fromlen);
1049       rc->src_addr = (const struct sockaddr *) &rc[1];
1050       rc->addr_len = fromlen;
1051       rc->plugin = plugin;
1052       rc->defrag =
1053           GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1054                                             UDP_MAX_MESSAGES_IN_DEFRAG, rc,
1055                                             &fragment_msg_proc, &ack_proc);
1056       rc->hnode =
1057           GNUNET_CONTAINER_heap_insert (plugin->defrags, rc,
1058                                         (GNUNET_CONTAINER_HeapCostType)
1059                                         now.abs_value);
1060     }
1061 #if DEBUG_UDP
1062     LOG (GNUNET_ERROR_TYPE_DEBUG,
1063                 "UDP processes %u-byte fragment from `%s'\n",
1064                 (unsigned int) ntohs (msg->size),
1065                 GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1066 #endif
1067
1068     if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (rc->defrag, msg))
1069     {
1070       /* keep this 'rc' from expiring */
1071       GNUNET_CONTAINER_heap_update_cost (plugin->defrags, rc->hnode,
1072                                          (GNUNET_CONTAINER_HeapCostType)
1073                                          now.abs_value);
1074     }
1075     if (GNUNET_CONTAINER_heap_get_size (plugin->defrags) >
1076         UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1077     {
1078       /* remove 'rc' that was inactive the longest */
1079       rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags);
1080       GNUNET_assert (NULL != rc);
1081       GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
1082       GNUNET_free (rc);
1083     }
1084     return;
1085   default:
1086     GNUNET_break_op (0);
1087     return;
1088   }
1089 }
1090
1091
1092 /**
1093  * We have been notified that our writeset has something to read.  We don't
1094  * know which socket needs to be read, so we have to check each one
1095  * Then reschedule this function to be called again once more is available.
1096  *
1097  * @param cls the plugin handle
1098  * @param tc the scheduling context (for rescheduling this function again)
1099  */
1100 static void
1101 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1102 {
1103   struct Plugin *plugin = cls;
1104
1105   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1106   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1107     return;
1108   if ((NULL != plugin->sockv4) &&
1109       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
1110     udp_read (plugin, plugin->sockv4);
1111   if ((NULL != plugin->sockv6) &&
1112       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
1113     udp_read (plugin, plugin->sockv6);
1114   plugin->select_task =
1115       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1116                                    GNUNET_SCHEDULER_NO_TASK,
1117                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1118                                    NULL, &udp_plugin_select, plugin);
1119
1120 }
1121
1122
1123 /**
1124  * Check if the given port is plausible (must be either our listen
1125  * port or our advertised port).  If it is neither, we return
1126  * GNUNET_SYSERR.
1127  *
1128  * @param plugin global variables
1129  * @param in_port port number to check
1130  * @return GNUNET_OK if port is either open_port or adv_port
1131  */
1132 static int
1133 check_port (struct Plugin *plugin, uint16_t in_port)
1134 {
1135   if ((in_port == plugin->port) || (in_port == plugin->aport))
1136     return GNUNET_OK;
1137   return GNUNET_SYSERR;
1138 }
1139
1140
1141 /**
1142  * Function that will be called to check if a binary address for this
1143  * plugin is well-formed and corresponds to an address for THIS peer
1144  * (as per our configuration).  Naturally, if absolutely necessary,
1145  * plugins can be a bit conservative in their answer, but in general
1146  * plugins should make sure that the address does not redirect
1147  * traffic to a 3rd party that might try to man-in-the-middle our
1148  * traffic.
1149  *
1150  * @param cls closure, should be our handle to the Plugin
1151  * @param addr pointer to the address
1152  * @param addrlen length of addr
1153  * @return GNUNET_OK if this is a plausible address for this peer
1154  *         and transport, GNUNET_SYSERR if not
1155  *
1156  */
1157 static int
1158 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1159 {
1160   struct Plugin *plugin = cls;
1161   struct IPv4UdpAddress *v4;
1162   struct IPv6UdpAddress *v6;
1163
1164   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
1165       (addrlen != sizeof (struct IPv6UdpAddress)))
1166   {
1167     GNUNET_break_op (0);
1168     return GNUNET_SYSERR;
1169   }
1170   if (addrlen == sizeof (struct IPv4UdpAddress))
1171   {
1172     v4 = (struct IPv4UdpAddress *) addr;
1173     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
1174       return GNUNET_SYSERR;
1175     if (GNUNET_OK !=
1176         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1177                                  sizeof (struct in_addr)))
1178       return GNUNET_SYSERR;
1179   }
1180   else
1181   {
1182     v6 = (struct IPv6UdpAddress *) addr;
1183     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1184     {
1185       GNUNET_break_op (0);
1186       return GNUNET_SYSERR;
1187     }
1188     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
1189       return GNUNET_SYSERR;
1190     if (GNUNET_OK !=
1191         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1192                                  sizeof (struct in6_addr)))
1193       return GNUNET_SYSERR;
1194   }
1195   return GNUNET_OK;
1196 }
1197
1198
1199 /**
1200  * Function called for a quick conversion of the binary address to
1201  * a numeric address.  Note that the caller must not free the
1202  * address and that the next call to this function is allowed
1203  * to override the address again.
1204  *
1205  * @param cls closure
1206  * @param addr binary address
1207  * @param addrlen length of the address
1208  * @return string representing the same address
1209  */
1210 static const char *
1211 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
1212 {
1213   static char rbuf[INET6_ADDRSTRLEN + 10];
1214   char buf[INET6_ADDRSTRLEN];
1215   const void *sb;
1216   struct in_addr a4;
1217   struct in6_addr a6;
1218   const struct IPv4UdpAddress *t4;
1219   const struct IPv6UdpAddress *t6;
1220   int af;
1221   uint16_t port;
1222
1223   if (addrlen == sizeof (struct IPv6UdpAddress))
1224   {
1225     t6 = addr;
1226     af = AF_INET6;
1227     port = ntohs (t6->u6_port);
1228     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
1229     sb = &a6;
1230   }
1231   else if (addrlen == sizeof (struct IPv4UdpAddress))
1232   {
1233     t4 = addr;
1234     af = AF_INET;
1235     port = ntohs (t4->u4_port);
1236     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
1237     sb = &a4;
1238   }
1239   else
1240   {
1241     GNUNET_break_op (0);
1242     return NULL;
1243   }
1244   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
1245   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
1246                    buf, port);
1247   return rbuf;
1248 }
1249
1250
1251 /**
1252  * Closure for 'append_port'.
1253  */
1254 struct PrettyPrinterContext
1255 {
1256   /**
1257    * Function to call with the result.
1258    */
1259   GNUNET_TRANSPORT_AddressStringCallback asc;
1260
1261   /**
1262    * Clsoure for 'asc'.
1263    */
1264   void *asc_cls;
1265
1266   /**
1267    * Port to add after the IP address.
1268    */
1269   uint16_t port;
1270 };
1271
1272
1273 /**
1274  * Append our port and forward the result.
1275  *
1276  * @param cls a 'struct PrettyPrinterContext'
1277  * @param hostname result from DNS resolver
1278  */
1279 static void
1280 append_port (void *cls, const char *hostname)
1281 {
1282   struct PrettyPrinterContext *ppc = cls;
1283   char *ret;
1284
1285   if (hostname == NULL)
1286   {
1287     ppc->asc (ppc->asc_cls, NULL);
1288     GNUNET_free (ppc);
1289     return;
1290   }
1291   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1292   ppc->asc (ppc->asc_cls, ret);
1293   GNUNET_free (ret);
1294 }
1295
1296
1297 /**
1298  * Convert the transports address to a nice, human-readable
1299  * format.
1300  *
1301  * @param cls closure
1302  * @param type name of the transport that generated the address
1303  * @param addr one of the addresses of the host, NULL for the last address
1304  *        the specific address format depends on the transport
1305  * @param addrlen length of the address
1306  * @param numeric should (IP) addresses be displayed in numeric form?
1307  * @param timeout after how long should we give up?
1308  * @param asc function to call on each string
1309  * @param asc_cls closure for asc
1310  */
1311 static void
1312 udp_plugin_address_pretty_printer (void *cls, const char *type,
1313                                    const void *addr, size_t addrlen,
1314                                    int numeric,
1315                                    struct GNUNET_TIME_Relative timeout,
1316                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1317                                    void *asc_cls)
1318 {
1319   struct PrettyPrinterContext *ppc;
1320   const void *sb;
1321   size_t sbs;
1322   struct sockaddr_in a4;
1323   struct sockaddr_in6 a6;
1324   const struct IPv4UdpAddress *u4;
1325   const struct IPv6UdpAddress *u6;
1326   uint16_t port;
1327
1328   if (addrlen == sizeof (struct IPv6UdpAddress))
1329   {
1330     u6 = addr;
1331     memset (&a6, 0, sizeof (a6));
1332     a6.sin6_family = AF_INET6;
1333 #if HAVE_SOCKADDR_IN_SIN_LEN
1334     a6.sin6_len = sizeof (a6);
1335 #endif
1336     a6.sin6_port = u6->u6_port;
1337     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
1338     port = ntohs (u6->u6_port);
1339     sb = &a6;
1340     sbs = sizeof (a6);
1341   }
1342   else if (addrlen == sizeof (struct IPv4UdpAddress))
1343   {
1344     u4 = addr;
1345     memset (&a4, 0, sizeof (a4));
1346     a4.sin_family = AF_INET;
1347 #if HAVE_SOCKADDR_IN_SIN_LEN
1348     a4.sin_len = sizeof (a4);
1349 #endif
1350     a4.sin_port = u4->u4_port;
1351     a4.sin_addr.s_addr = u4->ipv4_addr;
1352     port = ntohs (u4->u4_port);
1353     sb = &a4;
1354     sbs = sizeof (a4);
1355   }
1356   else
1357   {
1358     /* invalid address */
1359     GNUNET_break_op (0);
1360     asc (asc_cls, NULL);
1361     return;
1362   }
1363   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1364   ppc->asc = asc;
1365   ppc->asc_cls = asc_cls;
1366   ppc->port = port;
1367   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1368 }
1369
1370
1371 /**
1372  * Our external IP address/port mapping has changed.
1373  *
1374  * @param cls closure, the 'struct LocalAddrList'
1375  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1376  *     the previous (now invalid) one
1377  * @param addr either the previous or the new public IP address
1378  * @param addrlen actual lenght of the address
1379  */
1380 static void
1381 udp_nat_port_map_callback (void *cls, int add_remove,
1382                            const struct sockaddr *addr, socklen_t addrlen)
1383 {
1384   struct Plugin *plugin = cls;
1385   struct IPv4UdpAddress u4;
1386   struct IPv6UdpAddress u6;
1387   void *arg;
1388   size_t args;
1389
1390   /* convert 'addr' to our internal format */
1391   switch (addr->sa_family)
1392   {
1393   case AF_INET:
1394     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1395     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1396     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1397     arg = &u4;
1398     args = sizeof (u4);
1399     break;
1400   case AF_INET6:
1401     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1402     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1403             sizeof (struct in6_addr));
1404     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1405     arg = &u6;
1406     args = sizeof (u6);
1407     break;
1408   default:
1409     GNUNET_break (0);
1410     return;
1411   }
1412   /* modify our published address list */
1413   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
1414 }
1415
1416
1417 /**
1418  * The exported method. Makes the core api available via a global and
1419  * returns the udp transport API.
1420  *
1421  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1422  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1423  */
1424 void *
1425 libgnunet_plugin_transport_udp_init (void *cls)
1426 {
1427   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1428   unsigned long long port;
1429   unsigned long long aport;
1430   struct GNUNET_TRANSPORT_PluginFunctions *api;
1431   struct Plugin *plugin;
1432   int sockets_created;
1433   struct sockaddr_in serverAddrv4;
1434   struct sockaddr_in6 serverAddrv6;
1435   struct sockaddr *serverAddr;
1436   struct sockaddr *addrs[2];
1437   socklen_t addrlens[2];
1438   socklen_t addrlen;
1439   unsigned int tries;
1440   unsigned long long udp_max_bps;
1441
1442   if (GNUNET_OK !=
1443       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
1444                                              &port))
1445     port = 2086;
1446   if (GNUNET_OK !=
1447       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1448                                              "MAX_BPS", &udp_max_bps))
1449     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1450   if (GNUNET_OK !=
1451       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1452                                              "ADVERTISED_PORT", &aport))
1453     aport = port;
1454   if (port > 65535)
1455   {
1456     LOG (GNUNET_ERROR_TYPE_WARNING,
1457                 _("Given `%s' option is out of range: %llu > %u\n"), "PORT",
1458                 port, 65535);
1459     return NULL;
1460   }
1461   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1462   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1463
1464   plugin = GNUNET_malloc (sizeof (struct Plugin));
1465   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1466                                  GNUNET_BANDWIDTH_value_init ((uint32_t)
1467                                                               udp_max_bps), 30);
1468   plugin->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
1469   plugin->port = port;
1470   plugin->aport = aport;
1471   plugin->env = env;
1472   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1473   api->cls = plugin;
1474
1475   api->send = &udp_plugin_send;
1476   api->disconnect = &udp_disconnect;
1477   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1478   api->address_to_string = &udp_address_to_string;
1479   api->check_address = &udp_plugin_check_address;
1480
1481   if (GNUNET_YES ==
1482       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1483                                              "BINDTO", &plugin->bind4_address))
1484   {
1485     LOG (GNUNET_ERROR_TYPE_DEBUG,
1486                 "Binding udp plugin to specific address: `%s'\n",
1487                 plugin->bind4_address);
1488     if (1 != inet_pton (AF_INET, plugin->bind4_address, &serverAddrv4.sin_addr))
1489     {
1490       GNUNET_free (plugin->bind4_address);
1491       GNUNET_free (plugin);
1492       GNUNET_free (api);
1493       return NULL;
1494     }
1495   }
1496
1497   if (GNUNET_YES ==
1498       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1499                                              "BINDTO6", &plugin->bind6_address))
1500   {
1501     LOG (GNUNET_ERROR_TYPE_DEBUG,
1502                 "Binding udp plugin to specific address: `%s'\n",
1503                 plugin->bind6_address);
1504     if (1 !=
1505         inet_pton (AF_INET6, plugin->bind6_address, &serverAddrv6.sin6_addr))
1506     {
1507       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1508                   plugin->bind6_address);
1509       GNUNET_free_non_null (plugin->bind4_address);
1510       GNUNET_free (plugin->bind6_address);
1511       GNUNET_free (plugin);
1512       GNUNET_free (api);
1513       return NULL;
1514     }
1515   }
1516
1517   plugin->defrags =
1518       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1519   plugin->sessions =
1520       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
1521                                             * 2);
1522   plugin->inbound_sessions =
1523       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
1524                                             * 2);
1525   sockets_created = 0;
1526   if ((GNUNET_YES !=
1527        GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "nat",
1528                                              "DISABLEV6")))
1529   {
1530     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1531     if (NULL == plugin->sockv6)
1532     {
1533       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1534     }
1535     else
1536     {
1537 #if HAVE_SOCKADDR_IN_SIN_LEN
1538       serverAddrv6.sin6_len = sizeof (serverAddrv6);
1539 #endif
1540       serverAddrv6.sin6_family = AF_INET6;
1541       serverAddrv6.sin6_addr = in6addr_any;
1542       serverAddrv6.sin6_port = htons (plugin->port);
1543       addrlen = sizeof (serverAddrv6);
1544       serverAddr = (struct sockaddr *) &serverAddrv6;
1545 #if DEBUG_UDP
1546       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1547                   ntohs (serverAddrv6.sin6_port));
1548 #endif
1549       tries = 0;
1550       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1551              GNUNET_OK)
1552       {
1553         serverAddrv6.sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1554 #if DEBUG_UDP
1555         LOG (GNUNET_ERROR_TYPE_DEBUG,
1556                     "IPv6 Binding failed, trying new port %d\n",
1557                     ntohs (serverAddrv6.sin6_port));
1558 #endif
1559         tries++;
1560         if (tries > 10)
1561         {
1562           GNUNET_NETWORK_socket_close (plugin->sockv6);
1563           plugin->sockv6 = NULL;
1564           break;
1565         }
1566       }
1567       if (plugin->sockv6 != NULL)
1568       {
1569         addrs[sockets_created] = (struct sockaddr *) &serverAddrv6;
1570         addrlens[sockets_created] = sizeof (serverAddrv6);
1571         sockets_created++;
1572       }
1573     }
1574   }
1575
1576   plugin->mst =
1577       GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
1578   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1579   if (NULL == plugin->sockv4)
1580   {
1581     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1582   }
1583   else
1584   {
1585 #if HAVE_SOCKADDR_IN_SIN_LEN
1586     serverAddrv4.sin_len = sizeof (serverAddrv4);
1587 #endif
1588     serverAddrv4.sin_family = AF_INET;
1589     serverAddrv4.sin_addr.s_addr = INADDR_ANY;
1590     serverAddrv4.sin_port = htons (plugin->port);
1591     addrlen = sizeof (serverAddrv4);
1592     serverAddr = (struct sockaddr *) &serverAddrv4;
1593 #if DEBUG_UDP
1594     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1595                 ntohs (serverAddrv4.sin_port));
1596 #endif
1597     tries = 0;
1598     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1599            GNUNET_OK)
1600     {
1601       serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1602 #if DEBUG_UDP
1603       LOG (GNUNET_ERROR_TYPE_DEBUG,
1604                   "IPv4 Binding failed, trying new port %d\n",
1605                   ntohs (serverAddrv4.sin_port));
1606 #endif
1607       tries++;
1608       if (tries > 10)
1609       {
1610         GNUNET_NETWORK_socket_close (plugin->sockv4);
1611         plugin->sockv4 = NULL;
1612         break;
1613       }
1614     }
1615     if (plugin->sockv4 != NULL)
1616     {
1617       addrs[sockets_created] = (struct sockaddr *) &serverAddrv4;
1618       addrlens[sockets_created] = sizeof (serverAddrv4);
1619       sockets_created++;
1620     }
1621   }
1622
1623   plugin->rs = GNUNET_NETWORK_fdset_create ();
1624   GNUNET_NETWORK_fdset_zero (plugin->rs);
1625   if (NULL != plugin->sockv4)
1626     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
1627   if (NULL != plugin->sockv6)
1628     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
1629
1630   plugin->select_task =
1631       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1632                                    GNUNET_SCHEDULER_NO_TASK,
1633                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1634                                    NULL, &udp_plugin_select, plugin);
1635   if (sockets_created == 0)
1636     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
1637   plugin->nat =
1638       GNUNET_NAT_register (env->cfg, GNUNET_NO, port, sockets_created,
1639                            (const struct sockaddr **) addrs, addrlens,
1640                            &udp_nat_port_map_callback, NULL, plugin);
1641   return api;
1642 }
1643
1644
1645 /**
1646  * Destroy a session, plugin is being unloaded.
1647  *
1648  * @param cls unused
1649  * @param key hash of public key of target peer
1650  * @param value a 'struct PeerSession*' to clean up
1651  * @return GNUNET_OK (continue to iterate)
1652  */
1653 static int
1654 destroy_session (void *cls, const GNUNET_HashCode * key, void *value)
1655 {
1656   struct PeerSession *peer_session = value;
1657
1658   GNUNET_FRAGMENT_context_destroy (peer_session->frag);
1659   GNUNET_free (peer_session);
1660   return GNUNET_OK;
1661 }
1662
1663
1664 /**
1665  * Shutdown the plugin.
1666  *
1667  * @param cls our 'struct GNUNET_TRANSPORT_PluginFunctions'
1668  * @return NULL
1669  */
1670 void *
1671 libgnunet_plugin_transport_udp_done (void *cls)
1672 {
1673   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1674   struct Plugin *plugin = api->cls;
1675   struct ReceiveContext *rc;
1676
1677   /* FIXME: clean up heap and hashmap */
1678   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &destroy_session,
1679                                          NULL);
1680   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1681   plugin->sessions = NULL;
1682   GNUNET_CONTAINER_multihashmap_iterate (plugin->inbound_sessions, &destroy_session,
1683                                          NULL);
1684   GNUNET_CONTAINER_multihashmap_destroy (plugin->inbound_sessions);
1685   plugin->inbound_sessions = NULL;
1686   while (NULL != (rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags)))
1687   {
1688     GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
1689     GNUNET_free (rc);
1690   }
1691   GNUNET_CONTAINER_heap_destroy (plugin->defrags);
1692
1693   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1694   {
1695     GNUNET_SCHEDULER_cancel (plugin->select_task);
1696     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1697   }
1698   if (plugin->sockv4 != NULL)
1699   {
1700     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
1701     plugin->sockv4 = NULL;
1702   }
1703   if (plugin->sockv6 != NULL)
1704   {
1705     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
1706     plugin->sockv6 = NULL;
1707   }
1708   GNUNET_SERVER_mst_destroy (plugin->mst);
1709   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1710   GNUNET_NAT_unregister (plugin->nat);
1711   plugin->nat = NULL;
1712   GNUNET_free (plugin);
1713   GNUNET_free (api);
1714   return NULL;
1715 }
1716
1717 /* end of plugin_transport_udp.c */