fix for mantis bug 0002154:
[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 transport protocol
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  * @author Matthias Wachs
27  */
28 #include "platform.h"
29 #include "plugin_transport_udp.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_fragmentation_lib.h"
33 #include "gnunet_nat_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_resolver_service.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_constants.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_transport_service.h"
40 #include "gnunet_transport_plugin.h"
41 #include "transport.h"
42
43 #define LOG(kind,...) GNUNET_log_from (kind, "transport-udp", __VA_ARGS__)
44
45
46 /**
47  * Number of messages we can defragment in parallel.  We only really
48  * defragment 1 message at a time, but if messages get re-ordered, we
49  * may want to keep knowledge about the previous message to avoid
50  * discarding the current message in favor of a single fragment of a
51  * previous message.  3 should be good since we don't expect massive
52  * message reorderings with UDP.
53  */
54 #define UDP_MAX_MESSAGES_IN_DEFRAG 3
55
56 /**
57  * We keep a defragmentation queue per sender address.  How many
58  * sender addresses do we support at the same time? Memory consumption
59  * is roughly a factor of 32k * UDP_MAX_MESSAGES_IN_DEFRAG times this
60  * value. (So 128 corresponds to 12 MB and should suffice for
61  * connecting to roughly 128 peers via UDP).
62  */
63 #define UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG 128
64
65
66
67 /**
68  * Closure for 'append_port'.
69  */
70 struct PrettyPrinterContext
71 {
72   /**
73    * Function to call with the result.
74    */
75   GNUNET_TRANSPORT_AddressStringCallback asc;
76
77   /**
78    * Clsoure for 'asc'.
79    */
80   void *asc_cls;
81
82   /**
83    * Port to add after the IP address.
84    */
85   uint16_t port;
86 };
87
88 struct Session
89 {
90   /**
91    * Which peer is this session for?
92    */
93   struct GNUNET_PeerIdentity target;
94
95   /**
96    * Address of the other peer
97    */
98   const struct sockaddr *sock_addr;
99
100   size_t addrlen;
101
102   /**
103    * Desired delay for next sending we send to other peer
104    */
105   struct GNUNET_TIME_Relative flow_delay_for_other_peer;
106
107   /**
108    * Desired delay for next sending we received from other peer
109    */
110   struct GNUNET_TIME_Absolute flow_delay_from_other_peer;
111
112   /**
113    * expected delay for ACKs
114    */
115   struct GNUNET_TIME_Relative last_expected_delay;
116
117
118   struct GNUNET_ATS_Information ats;
119
120   struct FragmentationContext * frag_ctx;
121 };
122
123
124 struct SessionCompareContext
125 {
126   struct Session *res;
127   const struct GNUNET_HELLO_Address *addr;
128 };
129
130
131 /**
132  * Closure for 'process_inbound_tokenized_messages'
133  */
134 struct SourceInformation
135 {
136   /**
137    * Sender identity.
138    */
139   struct GNUNET_PeerIdentity sender;
140
141   /**
142    * Source address.
143    */
144   const void *arg;
145
146   /**
147    * Number of bytes in source address.
148    */
149   size_t args;
150
151   struct Session *session;
152 };
153
154
155 /**
156  * Closure for 'find_receive_context'.
157  */
158 struct FindReceiveContext
159 {
160   /**
161    * Where to store the result.
162    */
163   struct DefragContext *rc;
164
165   /**
166    * Address to find.
167    */
168   const struct sockaddr *addr;
169
170   /**
171    * Number of bytes in 'addr'.
172    */
173   socklen_t addr_len;
174
175   struct Session *session;
176 };
177
178
179
180 /**
181  * Data structure to track defragmentation contexts based
182  * on the source of the UDP traffic.
183  */
184 struct DefragContext
185 {
186
187   /**
188    * Defragmentation context.
189    */
190   struct GNUNET_DEFRAGMENT_Context *defrag;
191
192   /**
193    * Source address this receive context is for (allocated at the
194    * end of the struct).
195    */
196   const struct sockaddr *src_addr;
197
198   /**
199    * Reference to master plugin struct.
200    */
201   struct Plugin *plugin;
202
203   /**
204    * Node in the defrag heap.
205    */
206   struct GNUNET_CONTAINER_HeapNode *hnode;
207
208   /**
209    * Length of 'src_addr'
210    */
211   size_t addr_len;
212 };
213
214
215
216 /**
217  * Closure for 'process_inbound_tokenized_messages'
218  */
219 struct FragmentationContext
220 {
221   struct FragmentationContext * next;
222   struct FragmentationContext * prev;
223
224   struct Plugin * plugin;
225   struct GNUNET_FRAGMENT_Context * frag;
226   struct Session * session;
227
228   struct GNUNET_TIME_Absolute timeout;
229
230
231   /**
232    * Function to call upon completion of the transmission.
233    */
234   GNUNET_TRANSPORT_TransmitContinuation cont;
235
236   /**
237    * Closure for 'cont'.
238    */
239   void *cont_cls;
240
241   size_t bytes_to_send;
242 };
243
244
245 struct UDPMessageWrapper
246 {
247   struct Session *session;
248   struct UDPMessageWrapper *prev;
249   struct UDPMessageWrapper *next;
250   char *udp;
251   size_t msg_size;
252
253   struct GNUNET_TIME_Absolute timeout;
254
255   /**
256    * Function to call upon completion of the transmission.
257    */
258   GNUNET_TRANSPORT_TransmitContinuation cont;
259
260   /**
261    * Closure for 'cont'.
262    */
263   void *cont_cls;
264
265   struct FragmentationContext *frag_ctx;
266
267 };
268
269
270 /**
271  * UDP ACK Message-Packet header (after defragmentation).
272  */
273 struct UDP_ACK_Message
274 {
275   /**
276    * Message header.
277    */
278   struct GNUNET_MessageHeader header;
279
280   /**
281    * Desired delay for flow control
282    */
283   uint32_t delay;
284
285   /**
286    * What is the identity of the sender
287    */
288   struct GNUNET_PeerIdentity sender;
289
290 };
291
292
293
294 /**
295  * Function called for a quick conversion of the binary address to
296  * a numeric address.  Note that the caller must not free the
297  * address and that the next call to this function is allowed
298  * to override the address again.
299  *
300  * @param cls closure
301  * @param addr binary address
302  * @param addrlen length of the address
303  * @return string representing the same address
304  */
305 const char *
306 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
307 {
308   static char rbuf[INET6_ADDRSTRLEN + 10];
309   char buf[INET6_ADDRSTRLEN];
310   const void *sb;
311   struct in_addr a4;
312   struct in6_addr a6;
313   const struct IPv4UdpAddress *t4;
314   const struct IPv6UdpAddress *t6;
315   int af;
316   uint16_t port;
317
318   if (addrlen == sizeof (struct IPv6UdpAddress))
319   {
320     t6 = addr;
321     af = AF_INET6;
322     port = ntohs (t6->u6_port);
323     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
324     sb = &a6;
325   }
326   else if (addrlen == sizeof (struct IPv4UdpAddress))
327   {
328     t4 = addr;
329     af = AF_INET;
330     port = ntohs (t4->u4_port);
331     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
332     sb = &a4;
333   }
334   else
335   {
336     GNUNET_break_op (0);
337     return NULL;
338   }
339   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
340   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
341                    buf, port);
342   return rbuf;
343 }
344
345
346 /**
347  * Append our port and forward the result.
348  *
349  * @param cls a 'struct PrettyPrinterContext'
350  * @param hostname result from DNS resolver
351  */
352 static void
353 append_port (void *cls, const char *hostname)
354 {
355   struct PrettyPrinterContext *ppc = cls;
356   char *ret;
357
358   if (hostname == NULL)
359   {
360     ppc->asc (ppc->asc_cls, NULL);
361     GNUNET_free (ppc);
362     return;
363   }
364   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
365   ppc->asc (ppc->asc_cls, ret);
366   GNUNET_free (ret);
367 }
368
369
370 /**
371  * Convert the transports address to a nice, human-readable
372  * format.
373  *
374  * @param cls closure
375  * @param type name of the transport that generated the address
376  * @param addr one of the addresses of the host, NULL for the last address
377  *        the specific address format depends on the transport
378  * @param addrlen length of the address
379  * @param numeric should (IP) addresses be displayed in numeric form?
380  * @param timeout after how long should we give up?
381  * @param asc function to call on each string
382  * @param asc_cls closure for asc
383  */
384 static void
385 udp_plugin_address_pretty_printer (void *cls, const char *type,
386                                    const void *addr, size_t addrlen,
387                                    int numeric,
388                                    struct GNUNET_TIME_Relative timeout,
389                                    GNUNET_TRANSPORT_AddressStringCallback asc,
390                                    void *asc_cls)
391 {
392   struct PrettyPrinterContext *ppc;
393   const void *sb;
394   size_t sbs;
395   struct sockaddr_in a4;
396   struct sockaddr_in6 a6;
397   const struct IPv4UdpAddress *u4;
398   const struct IPv6UdpAddress *u6;
399   uint16_t port;
400
401   if (addrlen == sizeof (struct IPv6UdpAddress))
402   {
403     u6 = addr;
404     memset (&a6, 0, sizeof (a6));
405     a6.sin6_family = AF_INET6;
406 #if HAVE_SOCKADDR_IN_SIN_LEN
407     a6.sin6_len = sizeof (a6);
408 #endif
409     a6.sin6_port = u6->u6_port;
410     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
411     port = ntohs (u6->u6_port);
412     sb = &a6;
413     sbs = sizeof (a6);
414   }
415   else if (addrlen == sizeof (struct IPv4UdpAddress))
416   {
417     u4 = addr;
418     memset (&a4, 0, sizeof (a4));
419     a4.sin_family = AF_INET;
420 #if HAVE_SOCKADDR_IN_SIN_LEN
421     a4.sin_len = sizeof (a4);
422 #endif
423     a4.sin_port = u4->u4_port;
424     a4.sin_addr.s_addr = u4->ipv4_addr;
425     port = ntohs (u4->u4_port);
426     sb = &a4;
427     sbs = sizeof (a4);
428   }
429   else
430   {
431     /* invalid address */
432     GNUNET_break_op (0);
433     asc (asc_cls, NULL);
434     return;
435   }
436   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
437   ppc->asc = asc;
438   ppc->asc_cls = asc_cls;
439   ppc->port = port;
440   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
441 }
442
443
444 /**
445  * Check if the given port is plausible (must be either our listen
446  * port or our advertised port).  If it is neither, we return
447  * GNUNET_SYSERR.
448  *
449  * @param plugin global variables
450  * @param in_port port number to check
451  * @return GNUNET_OK if port is either open_port or adv_port
452  */
453 static int
454 check_port (struct Plugin *plugin, uint16_t in_port)
455 {
456   if ((in_port == plugin->port) || (in_port == plugin->aport))
457     return GNUNET_OK;
458   return GNUNET_SYSERR;
459 }
460
461
462
463 /**
464  * Function that will be called to check if a binary address for this
465  * plugin is well-formed and corresponds to an address for THIS peer
466  * (as per our configuration).  Naturally, if absolutely necessary,
467  * plugins can be a bit conservative in their answer, but in general
468  * plugins should make sure that the address does not redirect
469  * traffic to a 3rd party that might try to man-in-the-middle our
470  * traffic.
471  *
472  * @param cls closure, should be our handle to the Plugin
473  * @param addr pointer to the address
474  * @param addrlen length of addr
475  * @return GNUNET_OK if this is a plausible address for this peer
476  *         and transport, GNUNET_SYSERR if not
477  *
478  */
479 static int
480 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
481 {
482   struct Plugin *plugin = cls;
483   struct IPv4UdpAddress *v4;
484   struct IPv6UdpAddress *v6;
485
486   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
487       (addrlen != sizeof (struct IPv6UdpAddress)))
488   {
489     GNUNET_break_op (0);
490     return GNUNET_SYSERR;
491   }
492   if (addrlen == sizeof (struct IPv4UdpAddress))
493   {
494     v4 = (struct IPv4UdpAddress *) addr;
495     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
496       return GNUNET_SYSERR;
497     if (GNUNET_OK !=
498         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
499                                  sizeof (struct in_addr)))
500       return GNUNET_SYSERR;
501   }
502   else
503   {
504     v6 = (struct IPv6UdpAddress *) addr;
505     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
506     {
507       GNUNET_break_op (0);
508       return GNUNET_SYSERR;
509     }
510     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
511       return GNUNET_SYSERR;
512     if (GNUNET_OK !=
513         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
514                                  sizeof (struct in6_addr)))
515       return GNUNET_SYSERR;
516   }
517   return GNUNET_OK;
518 }
519
520
521 /**
522  * Destroy a session, plugin is being unloaded.
523  *
524  * @param cls unused
525  * @param key hash of public key of target peer
526  * @param value a 'struct PeerSession*' to clean up
527  * @return GNUNET_OK (continue to iterate)
528  */
529 static int
530 disconnect_and_free_it (void *cls, const GNUNET_HashCode * key, void *value)
531 {
532   struct Plugin *plugin = cls;
533   struct Session *s = value;
534   struct UDPMessageWrapper *udpw;
535   struct UDPMessageWrapper *next;
536
537 #if DEBUG_UDP
538   LOG (GNUNET_ERROR_TYPE_DEBUG,
539        "Session %p to peer `%s' address ended \n",
540          s,
541          GNUNET_i2s (&s->target),
542          GNUNET_a2s (s->sock_addr, s->addrlen));
543 #endif
544
545   if (s->frag_ctx != NULL)
546   {
547     GNUNET_FRAGMENT_context_destroy(s->frag_ctx->frag);
548     GNUNET_free (s->frag_ctx);
549     s->frag_ctx = NULL;
550   }
551
552   udpw = plugin->ipv4_queue_head;
553   while (udpw != NULL)
554   {
555     next = udpw->next;
556     if (udpw->session == s)
557     {
558       GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
559
560       if (udpw->cont != NULL)
561         udpw->cont (udpw->cont_cls, &s->target, GNUNET_SYSERR);
562       GNUNET_free (udpw);
563     }
564     udpw = next;
565   }
566
567   udpw = plugin->ipv6_queue_head;
568   while (udpw != NULL)
569   {
570     next = udpw->next;
571     if (udpw->session == s)
572     {
573       GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
574
575       if (udpw->cont != NULL)
576         udpw->cont (udpw->cont_cls, &s->target, GNUNET_SYSERR);
577       GNUNET_free (udpw);
578     }
579     udpw = next;
580   }
581
582   plugin->env->session_end (plugin->env->cls, &s->target, s);
583
584   GNUNET_assert (GNUNET_YES ==
585                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
586                                                        &s->target.hashPubKey,
587                                                        s));
588
589
590   GNUNET_free (s);
591   return GNUNET_OK;
592 }
593
594
595 /**
596  * Disconnect from a remote node.  Clean up session if we have one for this peer
597  *
598  * @param cls closure for this call (should be handle to Plugin)
599  * @param target the peeridentity of the peer to disconnect
600  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
601  */
602 static void
603 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
604 {
605   struct Plugin *plugin = cls;
606   GNUNET_assert (plugin != NULL);
607
608   GNUNET_assert (target != NULL);
609 #if DEBUG_UDP
610   LOG (GNUNET_ERROR_TYPE_DEBUG,
611        "Disconnecting from peer `%s'\n", GNUNET_i2s (target));
612 #endif
613   /* Clean up sessions */
614   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessions, &target->hashPubKey, &disconnect_and_free_it, plugin);
615 }
616
617 static struct Session *
618 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
619                 const void *addr, size_t addrlen,
620                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
621 {
622   struct Session *s;
623   const struct IPv4UdpAddress *t4;
624   const struct IPv6UdpAddress *t6;
625   struct sockaddr_in *v4;
626   struct sockaddr_in6 *v6;
627   size_t len;
628
629   switch (addrlen)
630   {
631   case sizeof (struct IPv4UdpAddress):
632     if (NULL == plugin->sockv4)
633     {
634       return NULL;
635     }
636     t4 = addr;
637     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
638     len = sizeof (struct sockaddr_in);
639     v4 = (struct sockaddr_in *) &s[1];
640     v4->sin_family = AF_INET;
641 #if HAVE_SOCKADDR_IN_SIN_LEN
642     v4->sin_len = sizeof (struct sockaddr_in);
643 #endif
644     v4->sin_port = t4->u4_port;
645     v4->sin_addr.s_addr = t4->ipv4_addr;
646     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
647     break;
648   case sizeof (struct IPv6UdpAddress):
649     if (NULL == plugin->sockv6)
650     {
651       return NULL;
652     }
653     t6 = addr;
654     s =
655         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
656     len = sizeof (struct sockaddr_in6);
657     v6 = (struct sockaddr_in6 *) &s[1];
658     v6->sin6_family = AF_INET6;
659 #if HAVE_SOCKADDR_IN_SIN_LEN
660     v6->sin6_len = sizeof (struct sockaddr_in6);
661 #endif
662     v6->sin6_port = t6->u6_port;
663     v6->sin6_addr = t6->ipv6_addr;
664     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
665     break;
666   default:
667     /* Must have a valid address to send to */
668     GNUNET_break_op (0);
669     return NULL;
670   }
671
672   s->addrlen = len;
673   s->target = *target;
674   s->sock_addr = (const struct sockaddr *) &s[1];
675   s->flow_delay_for_other_peer = GNUNET_TIME_relative_get_zero();
676   s->flow_delay_from_other_peer = GNUNET_TIME_absolute_get_zero();
677   s->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
678
679   return s;
680 }
681
682 static int session_cmp_it (void *cls,
683                            const GNUNET_HashCode * key,
684                            void *value)
685 {
686   struct SessionCompareContext * cctx = cls;
687   const struct GNUNET_HELLO_Address *address = cctx->addr;
688   struct Session *s = value;
689
690   socklen_t s_addrlen = s->addrlen;
691
692 #if VERBOSE_UDP
693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Comparing  address %s <-> %s\n",
694       udp_address_to_string (NULL, (void *) address->address, address->address_length),
695       GNUNET_a2s (s->sock_addr, s->addrlen));
696 #endif
697
698   if ((address->address_length == sizeof (struct IPv4UdpAddress)) &&
699       (s_addrlen == sizeof (struct sockaddr_in)))
700   {
701     struct IPv4UdpAddress * u4 = NULL;
702     u4 = (struct IPv4UdpAddress *) address->address;
703     const struct sockaddr_in *s4 = (const struct sockaddr_in *) s->sock_addr;
704     if ((0 == memcmp ((const void *) &u4->ipv4_addr,(const void *) &s4->sin_addr, sizeof (struct in_addr))) &&
705         (u4->u4_port == s4->sin_port))
706     {
707       cctx->res = s;
708       return GNUNET_NO;
709     }
710
711   }
712   if ((address->address_length == sizeof (struct IPv6UdpAddress)) &&
713       (s_addrlen == sizeof (struct sockaddr_in6)))
714   {
715     struct IPv6UdpAddress * u6 = NULL;
716     u6 = (struct IPv6UdpAddress *) address->address;
717     const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) s->sock_addr;
718     if ((0 == memcmp (&u6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr))) &&
719         (u6->u6_port == s6->sin6_port))
720     {
721       cctx->res = s;
722       return GNUNET_NO;
723     }
724   }
725
726
727   return GNUNET_YES;
728 }
729
730
731 /**
732  * Creates a new outbound session the transport service will use to send data to the
733  * peer
734  *
735  * @param cls the plugin
736  * @param address the address
737  * @return the session or NULL of max connections exceeded
738  */
739 static struct Session *
740 udp_plugin_get_session (void *cls,
741                   const struct GNUNET_HELLO_Address *address)
742 {
743   struct Session * s = NULL;
744   struct Plugin * plugin = cls;
745
746   GNUNET_assert (plugin != NULL);
747   GNUNET_assert (address != NULL);
748
749   if ((address->address == NULL) ||
750       ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
751       (address->address_length != sizeof (struct IPv6UdpAddress))))
752   {
753     GNUNET_break (0);
754     return NULL;
755   }
756
757   /* check if session already exists */
758   struct SessionCompareContext cctx;
759   cctx.addr = address;
760   cctx.res = NULL;
761 #if VERBOSE_UDP
762   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking for existing session for peer `%s' `%s' \n", GNUNET_i2s (&address->peer), udp_address_to_string(NULL, address->address, address->address_length));
763 #endif
764   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessions, &address->peer.hashPubKey, session_cmp_it, &cctx);
765   if (cctx.res != NULL)
766   {
767 #if VERBOSE_UDP
768     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p\n", cctx.res);
769 #endif
770     return cctx.res;
771   }
772
773   /* otherwise create new */
774   s = create_session (plugin,
775       &address->peer,
776       address->address,
777       address->address_length,
778       NULL, NULL);
779 #if VERBOSE
780     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
781               "Creating new session %p for peer `%s' address `%s'\n",
782               s,
783               GNUNET_i2s(&address->peer),
784               udp_address_to_string(NULL,address->address,address->address_length));
785 #endif
786   GNUNET_assert (GNUNET_OK ==
787                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
788                                                     &s->target.hashPubKey,
789                                                     s,
790                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
791
792   return s;
793 }
794
795 static void enqueue (struct Plugin *plugin, struct UDPMessageWrapper * udpw)
796 {
797
798   if (udpw->session->addrlen == sizeof (struct sockaddr_in))
799     GNUNET_CONTAINER_DLL_insert(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
800   if (udpw->session->addrlen == sizeof (struct sockaddr_in6))
801     GNUNET_CONTAINER_DLL_insert(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
802 }
803
804 /**
805  * Function that is called with messages created by the fragmentation
806  * module.  In the case of the 'proc' callback of the
807  * GNUNET_FRAGMENT_context_create function, this function must
808  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
809  *
810  * @param cls closure, the 'struct FragmentationContext'
811  * @param msg the message that was created
812  */
813 static void
814 enqueue_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
815 {
816   struct FragmentationContext *frag_ctx = cls;
817   struct Plugin *plugin = frag_ctx->plugin;
818   struct UDPMessageWrapper * udpw;
819
820   size_t msg_len = ntohs (msg->size);
821
822 #if VERBOSE_UDP
823   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Enqueuing fragment with %u bytes %u\n", msg_len , sizeof (struct UDPMessageWrapper));
824 #endif
825
826   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msg_len);
827   udpw->session = frag_ctx->session;
828   udpw->udp = (char *) &udpw[1];
829
830   udpw->msg_size = msg_len;
831   udpw->cont = frag_ctx->cont;
832   udpw->cont_cls = frag_ctx->cont_cls;
833   udpw->timeout = frag_ctx->timeout;
834   udpw->frag_ctx = frag_ctx;
835   memcpy (udpw->udp, msg, msg_len);
836
837   enqueue (plugin, udpw);
838
839 }
840
841
842 /**
843  * Function that can be used by the transport service to transmit
844  * a message using the plugin.   Note that in the case of a
845  * peer disconnecting, the continuation MUST be called
846  * prior to the disconnect notification itself.  This function
847  * will be called with this peer's HELLO message to initiate
848  * a fresh connection to another peer.
849  *
850  * @param cls closure
851  * @param s which session must be used
852  * @param msgbuf the message to transmit
853  * @param msgbuf_size number of bytes in 'msgbuf'
854  * @param priority how important is the message (most plugins will
855  *                 ignore message priority and just FIFO)
856  * @param to how long to wait at most for the transmission (does not
857  *                require plugins to discard the message after the timeout,
858  *                just advisory for the desired delay; most plugins will ignore
859  *                this as well)
860  * @param cont continuation to call once the message has
861  *        been transmitted (or if the transport is ready
862  *        for the next transmission call; or if the
863  *        peer disconnected...); can be NULL
864  * @param cont_cls closure for cont
865  * @return number of bytes used (on the physical network, with overheads);
866  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
867  *         and does NOT mean that the message was not transmitted (DV)
868  */
869 static ssize_t
870 udp_plugin_send (void *cls,
871                   struct Session *s,
872                   const char *msgbuf, size_t msgbuf_size,
873                   unsigned int priority,
874                   struct GNUNET_TIME_Relative to,
875                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
876 {
877   struct Plugin *plugin = cls;
878   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
879
880   struct UDPMessageWrapper * udpw;
881   struct UDPMessage *udp;
882   char mbuf[mlen];
883   GNUNET_assert (plugin != NULL);
884   GNUNET_assert (s != NULL);
885
886   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
887   {
888     GNUNET_break (0);
889     return GNUNET_SYSERR;
890   }
891
892   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessions, &s->target.hashPubKey, s))
893   {
894     GNUNET_break (0);
895     return GNUNET_SYSERR;
896   }
897
898   LOG (GNUNET_ERROR_TYPE_DEBUG,
899        "UDP transmits %u-byte message to `%s' using address `%s'\n",
900          msgbuf_size,
901          GNUNET_i2s (&s->target),
902          GNUNET_a2s(s->sock_addr, s->addrlen));
903
904   /* Message */
905   udp = (struct UDPMessage *) mbuf;
906   udp->header.size = htons (mlen);
907   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
908   udp->reserved = htonl (0);
909   udp->sender = *plugin->env->my_identity;
910
911   if (mlen <= UDP_MTU)
912   {
913     udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + mlen);
914     udpw->session = s;
915     udpw->udp = (char *) &udpw[1];
916     udpw->msg_size = mlen;
917     udpw->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
918     udpw->cont = cont;
919     udpw->cont_cls = cont_cls;
920     udpw->frag_ctx = NULL;
921
922     memcpy (udpw->udp, udp, sizeof (struct UDPMessage));
923     memcpy (&udpw->udp[sizeof (struct UDPMessage)], msgbuf, msgbuf_size);
924
925     enqueue (plugin, udpw);
926   }
927   else
928   {
929     LOG (GNUNET_ERROR_TYPE_DEBUG,
930          "UDP has to fragment message \n");
931     if  (s->frag_ctx != NULL)
932       return GNUNET_SYSERR;
933     memcpy (&udp[1], msgbuf, msgbuf_size);
934     struct FragmentationContext * frag_ctx = GNUNET_malloc(sizeof (struct FragmentationContext));
935
936     frag_ctx->plugin = plugin;
937     frag_ctx->session = s;
938     frag_ctx->cont = cont;
939     frag_ctx->cont_cls = cont_cls;
940     frag_ctx->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
941     frag_ctx->bytes_to_send = mlen;
942     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
943               UDP_MTU,
944               &plugin->tracker,
945               s->last_expected_delay,
946               &udp->header,
947               &enqueue_fragment,
948               frag_ctx);
949
950     s->frag_ctx = frag_ctx;
951
952   }
953   return mlen;
954 }
955
956
957 /**
958  * Our external IP address/port mapping has changed.
959  *
960  * @param cls closure, the 'struct LocalAddrList'
961  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
962  *     the previous (now invalid) one
963  * @param addr either the previous or the new public IP address
964  * @param addrlen actual lenght of the address
965  */
966 static void
967 udp_nat_port_map_callback (void *cls, int add_remove,
968                            const struct sockaddr *addr, socklen_t addrlen)
969 {
970   struct Plugin *plugin = cls;
971   struct IPv4UdpAddress u4;
972   struct IPv6UdpAddress u6;
973   void *arg;
974   size_t args;
975
976   /* convert 'addr' to our internal format */
977   switch (addr->sa_family)
978   {
979   case AF_INET:
980     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
981     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
982     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
983     arg = &u4;
984     args = sizeof (u4);
985     break;
986   case AF_INET6:
987     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
988     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
989             sizeof (struct in6_addr));
990     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
991     arg = &u6;
992     args = sizeof (u6);
993     break;
994   default:
995     GNUNET_break (0);
996     return;
997   }
998   /* modify our published address list */
999   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
1000 }
1001
1002
1003
1004 /**
1005  * Message tokenizer has broken up an incomming message. Pass it on
1006  * to the service.
1007  *
1008  * @param cls the 'struct Plugin'
1009  * @param client the 'struct SourceInformation'
1010  * @param hdr the actual message
1011  */
1012 static void
1013 process_inbound_tokenized_messages (void *cls, void *client,
1014                                     const struct GNUNET_MessageHeader *hdr)
1015 {
1016   struct Plugin *plugin = cls;
1017   struct SourceInformation *si = client;
1018   struct GNUNET_ATS_Information ats[2];
1019   struct GNUNET_TIME_Relative delay;
1020
1021   GNUNET_assert (si->session != NULL);
1022   /* setup ATS */
1023   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1024   ats[0].value = htonl (1);
1025   ats[1] = si->session->ats;
1026   GNUNET_break (ntohl(ats[1].value) != GNUNET_ATS_NET_UNSPECIFIED);
1027
1028   delay = plugin->env->receive (plugin->env->cls,
1029                 &si->sender,
1030                 hdr,
1031                 (const struct GNUNET_ATS_Information *) &ats, 2,
1032                 NULL,
1033                 si->arg,
1034                 si->args);
1035   si->session->flow_delay_for_other_peer = delay;
1036 }
1037
1038
1039 /**
1040  * We've received a UDP Message.  Process it (pass contents to main service).
1041  *
1042  * @param plugin plugin context
1043  * @param msg the message
1044  * @param sender_addr sender address
1045  * @param sender_addr_len number of bytes in sender_addr
1046  */
1047 static void
1048 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1049                      const struct sockaddr *sender_addr,
1050                      socklen_t sender_addr_len)
1051 {
1052   struct SourceInformation si;
1053   struct Session * s = NULL;
1054   struct IPv4UdpAddress u4;
1055   struct IPv6UdpAddress u6;
1056   const void *arg;
1057   size_t args;
1058
1059   if (0 != ntohl (msg->reserved))
1060   {
1061     GNUNET_break_op (0);
1062     return;
1063   }
1064   if (ntohs (msg->header.size) <
1065       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
1066   {
1067     GNUNET_break_op (0);
1068     return;
1069   }
1070
1071   /* convert address */
1072   switch (sender_addr->sa_family)
1073   {
1074   case AF_INET:
1075     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
1076     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
1077     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1078     arg = &u4;
1079     args = sizeof (u4);
1080     break;
1081   case AF_INET6:
1082     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
1083     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
1084     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
1085     arg = &u6;
1086     args = sizeof (u6);
1087     break;
1088   default:
1089     GNUNET_break (0);
1090     return;
1091   }
1092 #if DEBUG_UDP
1093   LOG (GNUNET_ERROR_TYPE_DEBUG,
1094        "Received message with %u bytes from peer `%s' at `%s'\n",
1095        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1096        GNUNET_a2s (sender_addr, sender_addr_len));
1097 #endif
1098
1099   struct GNUNET_HELLO_Address * address = GNUNET_HELLO_address_allocate(&msg->sender, "udp", arg, args);
1100   s = udp_plugin_get_session(plugin, address);
1101   GNUNET_free (address);
1102
1103   /* iterate over all embedded messages */
1104   si.session = s;
1105   si.sender = msg->sender;
1106   si.arg = arg;
1107   si.args = args;
1108
1109   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
1110                              ntohs (msg->header.size) -
1111                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
1112 }
1113
1114
1115 /**
1116  * Scan the heap for a receive context with the given address.
1117  *
1118  * @param cls the 'struct FindReceiveContext'
1119  * @param node internal node of the heap
1120  * @param element value stored at the node (a 'struct ReceiveContext')
1121  * @param cost cost associated with the node
1122  * @return GNUNET_YES if we should continue to iterate,
1123  *         GNUNET_NO if not.
1124  */
1125 static int
1126 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1127                       void *element, GNUNET_CONTAINER_HeapCostType cost)
1128 {
1129   struct FindReceiveContext *frc = cls;
1130   struct DefragContext *e = element;
1131
1132   if ((frc->addr_len == e->addr_len) &&
1133       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1134   {
1135     frc->rc = e;
1136     return GNUNET_NO;
1137   }
1138   return GNUNET_YES;
1139 }
1140
1141
1142 /**
1143  * Process a defragmented message.
1144  *
1145  * @param cls the 'struct ReceiveContext'
1146  * @param msg the message
1147  */
1148 static void
1149 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1150 {
1151   struct DefragContext *rc = cls;
1152
1153   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1154   {
1155     GNUNET_break (0);
1156     return;
1157   }
1158   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1159   {
1160     GNUNET_break (0);
1161     return;
1162   }
1163   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1164                        rc->src_addr, rc->addr_len);
1165 }
1166
1167 struct LookupContext
1168 {
1169   const struct sockaddr * addr;
1170   size_t addrlen;
1171
1172   struct Session *res;
1173 };
1174
1175 static int
1176 lookup_session_by_addr_it (void *cls, const GNUNET_HashCode * key, void *value)
1177 {
1178   struct LookupContext *l_ctx = cls;
1179   struct Session * s = value;
1180
1181   if ((s->addrlen == l_ctx->addrlen) &&
1182       (0 == memcmp (s->sock_addr, l_ctx->addr, s->addrlen)))
1183   {
1184     l_ctx->res = s;
1185     return GNUNET_NO;
1186   }
1187   return GNUNET_YES;
1188 }
1189
1190 /**
1191  * Transmit an acknowledgement.
1192  *
1193  * @param cls the 'struct ReceiveContext'
1194  * @param id message ID (unused)
1195  * @param msg ack to transmit
1196  */
1197 static void
1198 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
1199 {
1200   struct DefragContext *rc = cls;
1201
1202   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
1203   struct UDP_ACK_Message *udp_ack;
1204   uint32_t delay = 0;
1205   struct UDPMessageWrapper *udpw;
1206   struct Session *s;
1207
1208   struct LookupContext l_ctx;
1209   l_ctx.addr = rc->src_addr;
1210   l_ctx.addrlen = rc->addr_len;
1211   l_ctx.res = NULL;
1212   GNUNET_CONTAINER_multihashmap_iterate (rc->plugin->sessions,
1213       &lookup_session_by_addr_it,
1214       &l_ctx);
1215   s = l_ctx.res;
1216
1217   GNUNET_assert (s != NULL);
1218
1219   if (s->flow_delay_for_other_peer.rel_value <= UINT32_MAX)
1220     delay = s->flow_delay_for_other_peer.rel_value;
1221
1222 #if DEBUG_UDP
1223   LOG (GNUNET_ERROR_TYPE_DEBUG,
1224        "Sending ACK to `%s' including delay of %u ms\n",
1225        GNUNET_a2s (rc->src_addr,
1226                    (rc->src_addr->sa_family ==
1227                     AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct
1228                                                                      sockaddr_in6)),
1229        delay);
1230 #endif
1231   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msize);
1232   udpw->cont = NULL;
1233   udpw->cont_cls = NULL;
1234   udpw->frag_ctx = NULL;
1235   udpw->msg_size = msize;
1236   udpw->session = s;
1237   udpw->timeout = GNUNET_TIME_absolute_get_forever();
1238   udpw->udp = (char *)&udpw[1];
1239
1240   udp_ack = (struct UDP_ACK_Message *) udpw->udp;
1241   udp_ack->header.size = htons ((uint16_t) msize);
1242   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
1243   udp_ack->delay = htonl (delay);
1244   udp_ack->sender = *rc->plugin->env->my_identity;
1245   memcpy (&udp_ack[1], msg, ntohs (msg->size));
1246
1247   enqueue (rc->plugin, udpw);
1248 }
1249
1250
1251 static void read_process_msg (struct Plugin *plugin,
1252     const struct GNUNET_MessageHeader *msg,
1253     char *addr,
1254     socklen_t fromlen)
1255 {
1256   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1257   {
1258     GNUNET_break_op (0);
1259     return;
1260   }
1261   process_udp_message (plugin, (const struct UDPMessage *) msg,
1262                        (const struct sockaddr *) addr, fromlen);
1263   return;
1264 }
1265
1266 static void read_process_ack (struct Plugin *plugin,
1267     const struct GNUNET_MessageHeader *msg,
1268     char *addr,
1269     socklen_t fromlen)
1270 {
1271   const struct GNUNET_MessageHeader *ack;
1272   const struct UDP_ACK_Message *udp_ack;
1273   struct LookupContext l_ctx;
1274   struct Session *s = NULL;
1275   struct GNUNET_TIME_Relative flow_delay;
1276
1277   if (ntohs (msg->size) <
1278       sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
1279   {
1280     GNUNET_break_op (0);
1281     return;
1282   }
1283
1284   udp_ack = (const struct UDP_ACK_Message *) msg;
1285
1286   l_ctx.addr = (const struct sockaddr *) addr;
1287   l_ctx.addrlen = fromlen;
1288   l_ctx.res = NULL;
1289   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
1290       &lookup_session_by_addr_it,
1291       &l_ctx);
1292   s = l_ctx.res;
1293
1294   if ((s == NULL) || (s->frag_ctx == NULL))
1295     return;
1296
1297   flow_delay.rel_value = (uint64_t) ntohl (udp_ack->delay);
1298   LOG (GNUNET_ERROR_TYPE_DEBUG, "We received a sending delay of %llu\n",
1299        flow_delay.rel_value);
1300   s->flow_delay_from_other_peer =
1301       GNUNET_TIME_relative_to_absolute (flow_delay);
1302
1303   ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
1304   if (ntohs (ack->size) !=
1305       ntohs (msg->size) - sizeof (struct UDP_ACK_Message))
1306   {
1307     GNUNET_break_op (0);
1308     return;
1309   }
1310
1311   if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (s->frag_ctx->frag, ack))
1312   {
1313 #if DEBUG_UDP
1314   LOG (GNUNET_ERROR_TYPE_DEBUG,
1315        "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1316        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1317        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1318 #endif
1319     return;
1320   }
1321
1322 #if DEBUG_UDP
1323   LOG (GNUNET_ERROR_TYPE_DEBUG,
1324        "FULL MESSAGE ACKed\n",
1325        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1326        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1327 #endif
1328   s->last_expected_delay = GNUNET_FRAGMENT_context_destroy (s->frag_ctx->frag);
1329
1330   struct UDPMessageWrapper * udpw = NULL;
1331   if (s->addrlen == sizeof (struct sockaddr_in6))
1332   {
1333     udpw = plugin->ipv6_queue_head;
1334     while (udpw!= NULL)
1335     {
1336       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1337       {
1338         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1339         GNUNET_free (udpw);
1340       }
1341       udpw = udpw->next;
1342     }
1343   }
1344   if (s->addrlen == sizeof (struct sockaddr_in))
1345   {
1346     udpw = plugin->ipv4_queue_head;
1347     while (udpw!= NULL)
1348     {
1349       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1350       {
1351         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1352         GNUNET_free (udpw);
1353       }
1354       udpw = udpw->next;
1355     }
1356   }
1357
1358   if (s->frag_ctx->cont != NULL)
1359     s->frag_ctx->cont
1360     (s->frag_ctx->cont_cls, &udp_ack->sender, GNUNET_OK);
1361   GNUNET_free (s->frag_ctx);
1362   s->frag_ctx = NULL;
1363   return;
1364 }
1365
1366 static void read_process_fragment (struct Plugin *plugin,
1367     const struct GNUNET_MessageHeader *msg,
1368     char *addr,
1369     socklen_t fromlen)
1370 {
1371   struct DefragContext *d_ctx;
1372   struct GNUNET_TIME_Absolute now;
1373   struct FindReceiveContext frc;
1374
1375
1376   frc.rc = NULL;
1377   frc.addr = (const struct sockaddr *) addr;
1378   frc.addr_len = fromlen;
1379
1380 #if DEBUG_UDP
1381   LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
1382        (unsigned int) ntohs (msg->size),
1383        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1384 #endif
1385
1386   /* Lookup existing receive context for this address */
1387   GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
1388                                  &find_receive_context,
1389                                  &frc);
1390   now = GNUNET_TIME_absolute_get ();
1391   d_ctx = frc.rc;
1392
1393   if (d_ctx == NULL)
1394   {
1395     /* Create a new defragmentation context */
1396     d_ctx = GNUNET_malloc (sizeof (struct DefragContext) + fromlen);
1397     memcpy (&d_ctx[1], addr, fromlen);
1398     d_ctx->src_addr = (const struct sockaddr *) &d_ctx[1];
1399     d_ctx->addr_len = fromlen;
1400     d_ctx->plugin = plugin;
1401     d_ctx->defrag =
1402         GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1403                                           UDP_MAX_MESSAGES_IN_DEFRAG, d_ctx,
1404                                           &fragment_msg_proc, &ack_proc);
1405     d_ctx->hnode =
1406         GNUNET_CONTAINER_heap_insert (plugin->defrag_ctxs, d_ctx,
1407                                       (GNUNET_CONTAINER_HeapCostType)
1408                                       now.abs_value);
1409 #if DEBUG_UDP
1410   LOG (GNUNET_ERROR_TYPE_DEBUG, "Created new defragmentation context for %u-byte fragment from `%s'\n",
1411        (unsigned int) ntohs (msg->size),
1412        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1413 #endif
1414   }
1415   else
1416   {
1417 #if DEBUG_UDP
1418   LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing defragmentation context for %u-byte fragment from `%s'\n",
1419        (unsigned int) ntohs (msg->size),
1420        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1421 #endif
1422   }
1423
1424   if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (d_ctx->defrag, msg))
1425   {
1426     /* keep this 'rc' from expiring */
1427     GNUNET_CONTAINER_heap_update_cost (plugin->defrag_ctxs, d_ctx->hnode,
1428                                        (GNUNET_CONTAINER_HeapCostType)
1429                                        now.abs_value);
1430   }
1431   if (GNUNET_CONTAINER_heap_get_size (plugin->defrag_ctxs) >
1432       UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1433   {
1434     /* remove 'rc' that was inactive the longest */
1435     d_ctx = GNUNET_CONTAINER_heap_remove_root (plugin->defrag_ctxs);
1436     GNUNET_assert (NULL != d_ctx);
1437     GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
1438     GNUNET_free (d_ctx);
1439   }
1440 }
1441
1442 /**
1443  * Read and process a message from the given socket.
1444  *
1445  * @param plugin the overall plugin
1446  * @param rsock socket to read from
1447  */
1448 static void
1449 udp_select_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
1450 {
1451   socklen_t fromlen;
1452   char addr[32];
1453   char buf[65536];
1454   ssize_t size;
1455   const struct GNUNET_MessageHeader *msg;
1456
1457   fromlen = sizeof (addr);
1458   memset (&addr, 0, sizeof (addr));
1459   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
1460                                       (struct sockaddr *) &addr, &fromlen);
1461
1462   if (size < sizeof (struct GNUNET_MessageHeader))
1463   {
1464     GNUNET_break_op (0);
1465     return;
1466   }
1467   msg = (const struct GNUNET_MessageHeader *) buf;
1468
1469   LOG (GNUNET_ERROR_TYPE_DEBUG,
1470        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) size,
1471        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
1472
1473   if (size != ntohs (msg->size))
1474   {
1475     GNUNET_break_op (0);
1476     return;
1477   }
1478
1479   switch (ntohs (msg->type))
1480   {
1481   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
1482     udp_broadcast_receive (plugin, &buf, size, addr, fromlen);
1483     return;
1484
1485   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
1486     read_process_msg (plugin, msg, addr, fromlen);
1487     return;
1488
1489   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
1490     read_process_ack (plugin, msg, addr, fromlen);;
1491     return;
1492
1493   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1494     read_process_fragment (plugin, msg, addr, fromlen);
1495     return;
1496
1497   default:
1498     GNUNET_break_op (0);
1499     return;
1500   }
1501 }
1502
1503 size_t
1504 udp_select_send (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *sock)
1505 {
1506   ssize_t sent;
1507   size_t slen;
1508   struct GNUNET_TIME_Absolute max;
1509   struct GNUNET_TIME_Absolute ;
1510
1511   struct UDPMessageWrapper *udpw = NULL;
1512
1513   if (sock == plugin->sockv4)
1514   {
1515     udpw = plugin->ipv4_queue_head;
1516   }
1517   else if (sock == plugin->sockv6)
1518   {
1519     udpw = plugin->ipv6_queue_head;
1520   }
1521   else
1522     GNUNET_break (0);
1523
1524   const struct sockaddr * sa = udpw->session->sock_addr;
1525   slen = udpw->session->addrlen;
1526
1527   max = GNUNET_TIME_absolute_max(udpw->timeout, GNUNET_TIME_absolute_get());
1528
1529   while (udpw != NULL)
1530   {
1531     if (max.abs_value != udpw->timeout.abs_value)
1532     {
1533       /* Message timed out */
1534
1535       if (udpw->cont != NULL)
1536         udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1537       if (udpw->frag_ctx != NULL)
1538       {
1539 #if DEBUG_UDP
1540         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Fragmented message for peer `%s' with size %u timed out\n",
1541             GNUNET_i2s(&udpw->session->target), udpw->frag_ctx->bytes_to_send);
1542 #endif
1543         udpw->session->last_expected_delay = GNUNET_FRAGMENT_context_destroy(udpw->frag_ctx->frag);
1544         GNUNET_free (udpw->frag_ctx);
1545         udpw->session->frag_ctx = NULL;
1546       }
1547       else
1548       {
1549 #if DEBUG_UDP
1550         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' with size %u timed out\n",
1551             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1552 #endif
1553       }
1554
1555       if (sock == plugin->sockv4)
1556       {
1557         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1558         GNUNET_free (udpw);
1559         udpw = plugin->ipv4_queue_head;
1560       }
1561       else if (sock == plugin->sockv6)
1562       {
1563         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1564         GNUNET_free (udpw);
1565         udpw = plugin->ipv6_queue_head;
1566       }
1567     }
1568     else
1569     {
1570       struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer);
1571       if (delta.rel_value == 0)
1572       {
1573         /* this message is not delayed */
1574         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is not delayed \n",
1575             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1576         break;
1577       }
1578       else
1579       {
1580         /* this message is delayed, try next */
1581         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is delayed for %llu \n",
1582             GNUNET_i2s(&udpw->session->target), udpw->msg_size,
1583             delta);
1584         udpw = udpw->next;
1585       }
1586     }
1587
1588   }
1589
1590   if (udpw == NULL)
1591   {
1592     /* No message left */
1593     return 0;
1594   }
1595
1596   sent = GNUNET_NETWORK_socket_sendto (sock, udpw->udp, udpw->msg_size, sa, slen);
1597
1598   if (GNUNET_SYSERR == sent)
1599   {
1600     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
1601     LOG (GNUNET_ERROR_TYPE_DEBUG,
1602          "UDP transmitted %u-byte message to %s (%d: %s)\n",
1603          (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
1604          (sent < 0) ? STRERROR (errno) : "ok");
1605     if (udpw->cont != NULL)
1606       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1607   }
1608   LOG (GNUNET_ERROR_TYPE_DEBUG,
1609        "UDP transmitted %u-byte message to %s (%d: %s)\n",
1610        (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
1611        (sent < 0) ? STRERROR (errno) : "ok");
1612
1613   /* This was just a message fragment */
1614   if (udpw->frag_ctx != NULL)
1615   {
1616     GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);
1617   }
1618   /* This was a complete message*/
1619   else
1620   {
1621     if (udpw->cont != NULL)
1622       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_OK);
1623   }
1624
1625   if (sock == plugin->sockv4)
1626     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1627   else if (sock == plugin->sockv6)
1628     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1629   GNUNET_free (udpw);
1630   udpw = NULL;
1631
1632   return sent;
1633 }
1634
1635 /**
1636  * We have been notified that our readset has something to read.  We don't
1637  * know which socket needs to be read, so we have to check each one
1638  * Then reschedule this function to be called again once more is available.
1639  *
1640  * @param cls the plugin handle
1641  * @param tc the scheduling context (for rescheduling this function again)
1642  */
1643 static void
1644 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1645 {
1646   struct Plugin *plugin = cls;
1647
1648   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1649   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1650     return;
1651
1652   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1653   {
1654     if ((NULL != plugin->sockv4) &&
1655       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
1656         udp_select_read (plugin, plugin->sockv4);
1657     if ((NULL != plugin->sockv6) &&
1658       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
1659         udp_select_read (plugin, plugin->sockv6);
1660   }
1661
1662   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1663   {
1664     if ((NULL != plugin->sockv4) && (plugin->ipv4_queue_head != NULL) &&
1665       (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv4)))
1666       {
1667         udp_select_send (plugin, plugin->sockv4);
1668       }
1669     if ((NULL != plugin->sockv6) && (plugin->ipv6_queue_head != NULL) &&
1670       (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv6)))
1671       {
1672         udp_select_send (plugin, plugin->sockv6);
1673       }
1674   }
1675
1676   plugin->select_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1677                                    GNUNET_SCHEDULER_NO_TASK,
1678                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1679                                    plugin->ws, &udp_plugin_select, plugin);
1680
1681 }
1682
1683
1684 static int
1685 setup_sockets (struct Plugin *plugin, struct sockaddr_in6 *serverAddrv6, struct sockaddr_in *serverAddrv4)
1686 {
1687   int tries;
1688   int sockets_created = 0;
1689   struct sockaddr *serverAddr;
1690   struct sockaddr *addrs[2];
1691   socklen_t addrlens[2];
1692   socklen_t addrlen;
1693
1694   /* Create IPv6 socket */
1695   if (plugin->enable_ipv6 == GNUNET_YES)
1696   {
1697     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1698     if (NULL == plugin->sockv6)
1699     {
1700       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Disabling IPv6 since it is not supported on this system!\n");
1701       plugin->enable_ipv6 = GNUNET_NO;
1702     }
1703     else
1704     {
1705 #if HAVE_SOCKADDR_IN_SIN_LEN
1706       serverAddrv6->sin6_len = sizeof (serverAddrv6);
1707 #endif
1708       serverAddrv6->sin6_family = AF_INET6;
1709       serverAddrv6->sin6_addr = in6addr_any;
1710       serverAddrv6->sin6_port = htons (plugin->port);
1711       addrlen = sizeof (struct sockaddr_in6);
1712       serverAddr = (struct sockaddr *) serverAddrv6;
1713 #if DEBUG_UDP
1714       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1715            ntohs (serverAddrv6->sin6_port));
1716 #endif
1717       tries = 0;
1718       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1719              GNUNET_OK)
1720       {
1721         serverAddrv6->sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1722 #if DEBUG_UDP
1723         LOG (GNUNET_ERROR_TYPE_DEBUG,
1724              "IPv6 Binding failed, trying new port %d\n",
1725              ntohs (serverAddrv6->sin6_port));
1726 #endif
1727         tries++;
1728         if (tries > 10)
1729         {
1730           GNUNET_NETWORK_socket_close (plugin->sockv6);
1731           plugin->sockv6 = NULL;
1732           break;
1733         }
1734       }
1735       if (plugin->sockv6 != NULL)
1736       {
1737 #if DEBUG_UDP
1738         LOG (GNUNET_ERROR_TYPE_DEBUG,
1739              "IPv6 socket created on port %d\n",
1740              ntohs (serverAddrv6->sin6_port));
1741 #endif
1742         addrs[sockets_created] = (struct sockaddr *) serverAddrv6;
1743         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
1744         sockets_created++;
1745       }
1746     }
1747   }
1748
1749   /* Create IPv4 socket */
1750   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1751   if (NULL == plugin->sockv4)
1752   {
1753     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1754   }
1755   else
1756   {
1757 #if HAVE_SOCKADDR_IN_SIN_LEN
1758     serverAddrv4->sin_len = sizeof (serverAddrv4);
1759 #endif
1760     serverAddrv4->sin_family = AF_INET;
1761     serverAddrv4->sin_addr.s_addr = INADDR_ANY;
1762     serverAddrv4->sin_port = htons (plugin->port);
1763     addrlen = sizeof (struct sockaddr_in);
1764     serverAddr = (struct sockaddr *) serverAddrv4;
1765
1766 #if DEBUG_UDP
1767     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1768          ntohs (serverAddrv4->sin_port));
1769 #endif
1770     tries = 0;
1771     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1772            GNUNET_OK)
1773     {
1774       serverAddrv4->sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1775 #if DEBUG_UDP
1776       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
1777            ntohs (serverAddrv4->sin_port));
1778 #endif
1779       tries++;
1780       if (tries > 10)
1781       {
1782         GNUNET_NETWORK_socket_close (plugin->sockv4);
1783         plugin->sockv4 = NULL;
1784         break;
1785       }
1786     }
1787     if (plugin->sockv4 != NULL)
1788     {
1789       addrs[sockets_created] = (struct sockaddr *) serverAddrv4;
1790       addrlens[sockets_created] = sizeof (struct sockaddr_in);
1791       sockets_created++;
1792     }
1793   }
1794
1795   /* Create file descriptors */
1796   plugin->rs = GNUNET_NETWORK_fdset_create ();
1797   plugin->ws = GNUNET_NETWORK_fdset_create ();
1798   GNUNET_NETWORK_fdset_zero (plugin->rs);
1799   GNUNET_NETWORK_fdset_zero (plugin->ws);
1800   if (NULL != plugin->sockv4)
1801   {
1802     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
1803     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv4);
1804   }
1805   if (NULL != plugin->sockv6)
1806   {
1807     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
1808     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv6);
1809   }
1810
1811   if (sockets_created == 0)
1812     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
1813
1814   plugin->select_task =
1815       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1816                                    GNUNET_SCHEDULER_NO_TASK,
1817                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1818                                    plugin->ws, &udp_plugin_select, plugin);
1819
1820   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
1821                            GNUNET_NO, plugin->port,
1822                            sockets_created,
1823                            (const struct sockaddr **) addrs, addrlens,
1824                            &udp_nat_port_map_callback, NULL, plugin);
1825
1826   return sockets_created;
1827 }
1828
1829
1830 /**
1831  * The exported method. Makes the core api available via a global and
1832  * returns the udp transport API.
1833  *
1834  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1835  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1836  */
1837 void *
1838 libgnunet_plugin_transport_udp_init (void *cls)
1839 {
1840   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1841   struct GNUNET_TRANSPORT_PluginFunctions *api;
1842   struct Plugin *plugin;
1843
1844   unsigned long long port;
1845   unsigned long long aport;
1846   unsigned long long broadcast;
1847   unsigned long long udp_max_bps;
1848   unsigned long long enable_v6;
1849   char * bind4_address;
1850   char * bind6_address;
1851   struct GNUNET_TIME_Relative interval;
1852
1853   struct sockaddr_in serverAddrv4;
1854   struct sockaddr_in6 serverAddrv6;
1855
1856   int res;
1857
1858   /* Get port number */
1859   if (GNUNET_OK !=
1860       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
1861                                              &port))
1862     port = 2086;
1863   if (GNUNET_OK !=
1864       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1865                                              "ADVERTISED_PORT", &aport))
1866     aport = port;
1867   if (port > 65535)
1868   {
1869     LOG (GNUNET_ERROR_TYPE_WARNING,
1870          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
1871          65535);
1872     return NULL;
1873   }
1874
1875   /* Protocols */
1876   if ((GNUNET_YES ==
1877        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
1878                                              "DISABLEV6")))
1879   {
1880     enable_v6 = GNUNET_NO;
1881   }
1882   else
1883     enable_v6 = GNUNET_YES;
1884
1885
1886   /* Addresses */
1887   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1888   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1889
1890   if (GNUNET_YES ==
1891       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1892                                              "BINDTO", &bind4_address))
1893   {
1894     LOG (GNUNET_ERROR_TYPE_DEBUG,
1895          "Binding udp plugin to specific address: `%s'\n",
1896          bind4_address);
1897     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
1898     {
1899       GNUNET_free (bind4_address);
1900       return NULL;
1901     }
1902   }
1903
1904   if (GNUNET_YES ==
1905       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1906                                              "BINDTO6", &bind6_address))
1907   {
1908     LOG (GNUNET_ERROR_TYPE_DEBUG,
1909          "Binding udp plugin to specific address: `%s'\n",
1910          bind6_address);
1911     if (1 !=
1912         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
1913     {
1914       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1915            bind6_address);
1916       GNUNET_free_non_null (bind4_address);
1917       GNUNET_free (bind6_address);
1918       return NULL;
1919     }
1920   }
1921
1922
1923   /* Enable neighbour discovery */
1924   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
1925                                             "BROADCAST");
1926   if (broadcast == GNUNET_SYSERR)
1927     broadcast = GNUNET_NO;
1928
1929   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-udp",
1930                                            "BROADCAST_INTERVAL", &interval))
1931   {
1932     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1933   }
1934
1935   /* Maximum datarate */
1936   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1937                                              "MAX_BPS", &udp_max_bps))
1938   {
1939     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1940   }
1941
1942   plugin = GNUNET_malloc (sizeof (struct Plugin));
1943   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1944
1945   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1946                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
1947
1948
1949   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
1950   plugin->defrag_ctxs = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1951   plugin->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
1952   plugin->port = port;
1953   plugin->aport = aport;
1954   plugin->broadcast_interval = interval;
1955   plugin->enable_ipv6 = enable_v6;
1956   plugin->env = env;
1957
1958   api->cls = plugin;
1959   api->send = NULL;
1960   api->disconnect = &udp_disconnect;
1961   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1962   api->address_to_string = &udp_address_to_string;
1963   api->check_address = &udp_plugin_check_address;
1964   api->get_session = &udp_plugin_get_session;
1965   api->send = &udp_plugin_send;
1966
1967   LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
1968   res = setup_sockets (plugin, &serverAddrv6, &serverAddrv4);
1969   if ((res == 0) || ((plugin->sockv4 == NULL) && (plugin->sockv6 == NULL)))
1970   {
1971     LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to create network sockets, plugin failed\n");
1972     GNUNET_free (plugin);
1973     GNUNET_free (api);
1974     return NULL;
1975   }
1976
1977   LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting broadcasting\n");
1978   if (broadcast == GNUNET_YES)
1979     setup_broadcast (plugin, &serverAddrv6, &serverAddrv4);
1980
1981
1982   GNUNET_free_non_null (bind4_address);
1983   GNUNET_free_non_null (bind6_address);
1984   return api;
1985 }
1986
1987 int heap_cleanup_iterator (void *cls,
1988                           struct GNUNET_CONTAINER_HeapNode *
1989                           node, void *element,
1990                           GNUNET_CONTAINER_HeapCostType
1991                           cost)
1992 {
1993   struct DefragContext * d_ctx = element;
1994
1995   GNUNET_CONTAINER_heap_remove_node (node);
1996   GNUNET_DEFRAGMENT_context_destroy(d_ctx->defrag);
1997   GNUNET_free (d_ctx);
1998
1999   return GNUNET_YES;
2000 }
2001
2002
2003 /**
2004  * The exported method. Makes the core api available via a global and
2005  * returns the udp transport API.
2006  *
2007  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2008  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
2009  */
2010 void *
2011 libgnunet_plugin_transport_udp_done (void *cls)
2012 {
2013   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2014   struct Plugin *plugin = api->cls;
2015   stop_broadcast (plugin);
2016
2017   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
2018   {
2019     GNUNET_SCHEDULER_cancel (plugin->select_task);
2020     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2021   }
2022
2023   /* Closing sockets */
2024   if (plugin->sockv4 != NULL)
2025   {
2026     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
2027     plugin->sockv4 = NULL;
2028   }
2029   if (plugin->sockv6 != NULL)
2030   {
2031     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
2032     plugin->sockv6 = NULL;
2033   }
2034   GNUNET_NETWORK_fdset_destroy (plugin->rs);
2035   GNUNET_NETWORK_fdset_destroy (plugin->ws);
2036   GNUNET_NAT_unregister (plugin->nat);
2037
2038   if (plugin->defrag_ctxs != NULL)
2039   {
2040     GNUNET_CONTAINER_heap_iterate(plugin->defrag_ctxs,
2041         heap_cleanup_iterator, NULL);
2042     GNUNET_CONTAINER_heap_destroy(plugin->defrag_ctxs);
2043     plugin->defrag_ctxs = NULL;
2044   }
2045   if (plugin->mst != NULL)
2046   {
2047     GNUNET_SERVER_mst_destroy(plugin->mst);
2048     plugin->mst = NULL;
2049   }
2050
2051   /* Clean up leftover messages */
2052   struct UDPMessageWrapper * udpw;
2053   udpw = plugin->ipv4_queue_head;
2054   while (udpw != NULL)
2055   {
2056     struct UDPMessageWrapper *tmp = udpw->next;
2057     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
2058     if (udpw->cont != NULL)
2059       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
2060     GNUNET_free (udpw);
2061     udpw = tmp;
2062   }
2063   udpw = plugin->ipv6_queue_head;
2064   while (udpw != NULL)
2065   {
2066     struct UDPMessageWrapper *tmp = udpw->next;
2067     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
2068     if (udpw->cont != NULL)
2069       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
2070     GNUNET_free (udpw);
2071     udpw = tmp;
2072   }
2073
2074   /* Clean up sessions */
2075 #if DEBUG_UDP
2076   LOG (GNUNET_ERROR_TYPE_DEBUG,
2077        "Cleaning up sessions\n");
2078 #endif
2079   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
2080   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
2081
2082   plugin->nat = NULL;
2083   GNUNET_free (plugin);
2084   GNUNET_free (api);
2085   return NULL;
2086 }
2087
2088
2089 /* end of plugin_transport_udp.c */