e5be889773393d89cd952dc7a3af938d792bb71a
[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   plugin->env->session_end (plugin->env->cls, &s->target, s);
545
546   if (s->frag_ctx != NULL)
547   {
548     GNUNET_FRAGMENT_context_destroy(s->frag_ctx->frag);
549     GNUNET_free (s->frag_ctx);
550     s->frag_ctx = NULL;
551   }
552
553   udpw = plugin->msg_head;
554   while (udpw != NULL)
555   {
556     next = udpw->next;
557     if (udpw->session == s)
558     {
559       GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, udpw);
560
561       if (udpw->cont != NULL)
562         udpw->cont (udpw->cont_cls, &s->target, GNUNET_SYSERR);
563       GNUNET_free (udpw);
564     }
565     udpw = next;
566   }
567
568   GNUNET_assert (GNUNET_YES ==
569                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
570                                                        &s->target.hashPubKey,
571                                                        s));
572
573
574   GNUNET_free (s);
575   return GNUNET_OK;
576 }
577
578
579 /**
580  * Disconnect from a remote node.  Clean up session if we have one for this peer
581  *
582  * @param cls closure for this call (should be handle to Plugin)
583  * @param target the peeridentity of the peer to disconnect
584  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
585  */
586 static void
587 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
588 {
589   struct Plugin *plugin = cls;
590   GNUNET_assert (plugin != NULL);
591
592   GNUNET_assert (target != NULL);
593 #if DEBUG_UDP
594   LOG (GNUNET_ERROR_TYPE_DEBUG,
595        "Disconnecting from peer `%s'\n", GNUNET_i2s (target));
596 #endif
597   /* Clean up sessions */
598   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessions, &target->hashPubKey, &disconnect_and_free_it, plugin);
599 }
600
601 static struct Session *
602 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
603                 const void *addr, size_t addrlen,
604                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
605 {
606   struct Session *s;
607   const struct IPv4UdpAddress *t4;
608   const struct IPv6UdpAddress *t6;
609   struct sockaddr_in *v4;
610   struct sockaddr_in6 *v6;
611   size_t len;
612
613   switch (addrlen)
614   {
615   case sizeof (struct IPv4UdpAddress):
616     if (NULL == plugin->sockv4)
617     {
618       return NULL;
619     }
620     t4 = addr;
621     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
622     len = sizeof (struct sockaddr_in);
623     v4 = (struct sockaddr_in *) &s[1];
624     v4->sin_family = AF_INET;
625 #if HAVE_SOCKADDR_IN_SIN_LEN
626     v4->sin_len = sizeof (struct sockaddr_in);
627 #endif
628     v4->sin_port = t4->u4_port;
629     v4->sin_addr.s_addr = t4->ipv4_addr;
630     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
631     break;
632   case sizeof (struct IPv6UdpAddress):
633     if (NULL == plugin->sockv6)
634     {
635       return NULL;
636     }
637     t6 = addr;
638     s =
639         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
640     len = sizeof (struct sockaddr_in6);
641     v6 = (struct sockaddr_in6 *) &s[1];
642     v6->sin6_family = AF_INET6;
643 #if HAVE_SOCKADDR_IN_SIN_LEN
644     v6->sin6_len = sizeof (struct sockaddr_in6);
645 #endif
646     v6->sin6_port = t6->u6_port;
647     v6->sin6_addr = t6->ipv6_addr;
648     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
649     break;
650   default:
651     /* Must have a valid address to send to */
652     GNUNET_break_op (0);
653     return NULL;
654   }
655
656   s->addrlen = len;
657   s->target = *target;
658   s->sock_addr = (const struct sockaddr *) &s[1];
659   s->flow_delay_for_other_peer = GNUNET_TIME_relative_get_zero();
660   s->flow_delay_from_other_peer = GNUNET_TIME_absolute_get_zero();
661   s->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
662
663   return s;
664 }
665
666 static int session_cmp_it (void *cls,
667                            const GNUNET_HashCode * key,
668                            void *value)
669 {
670   struct SessionCompareContext * cctx = cls;
671   const struct GNUNET_HELLO_Address *address = cctx->addr;
672   struct Session *s = value;
673
674   socklen_t s_addrlen = s->addrlen;
675
676 #if VERBOSE_UDP
677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Comparing  address %s <-> %s\n",
678       udp_address_to_string (NULL, (void *) address->address, address->address_length),
679       GNUNET_a2s (s->sock_addr, s->addrlen));
680 #endif
681
682   if ((address->address_length == sizeof (struct IPv4UdpAddress)) &&
683       (s_addrlen == sizeof (struct sockaddr_in)))
684   {
685     struct IPv4UdpAddress * u4 = NULL;
686     u4 = (struct IPv4UdpAddress *) address->address;
687     const struct sockaddr_in *s4 = (const struct sockaddr_in *) s->sock_addr;
688     if ((0 == memcmp ((const void *) &u4->ipv4_addr,(const void *) &s4->sin_addr, sizeof (struct in_addr))) &&
689         (u4->u4_port == s4->sin_port))
690     {
691       cctx->res = s;
692       return GNUNET_NO;
693     }
694
695   }
696   if ((address->address_length == sizeof (struct IPv6UdpAddress)) &&
697       (s_addrlen == sizeof (struct sockaddr_in6)))
698   {
699     struct IPv6UdpAddress * u6 = NULL;
700     u6 = (struct IPv6UdpAddress *) address->address;
701     const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) s->sock_addr;
702     if ((0 == memcmp (&u6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr))) &&
703         (u6->u6_port == s6->sin6_port))
704     {
705       cctx->res = s;
706       return GNUNET_NO;
707     }
708   }
709
710
711   return GNUNET_YES;
712 }
713
714
715 /**
716  * Creates a new outbound session the transport service will use to send data to the
717  * peer
718  *
719  * @param cls the plugin
720  * @param address the address
721  * @return the session or NULL of max connections exceeded
722  */
723 static struct Session *
724 udp_plugin_get_session (void *cls,
725                   const struct GNUNET_HELLO_Address *address)
726 {
727   struct Session * s = NULL;
728   struct Plugin * plugin = cls;
729
730   GNUNET_assert (plugin != NULL);
731   GNUNET_assert (address != NULL);
732
733   if ((address->address == NULL) ||
734       ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
735       (address->address_length != sizeof (struct IPv6UdpAddress))))
736   {
737     GNUNET_break (0);
738     return NULL;
739   }
740
741   /* check if session already exists */
742   struct SessionCompareContext cctx;
743   cctx.addr = address;
744   cctx.res = NULL;
745 #if VERBOSE_UDP
746   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));
747 #endif
748   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessions, &address->peer.hashPubKey, session_cmp_it, &cctx);
749   if (cctx.res != NULL)
750   {
751 #if VERBOSE_UDP
752     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p\n", cctx.res);
753 #endif
754     return cctx.res;
755   }
756
757   /* otherwise create new */
758   s = create_session (plugin,
759       &address->peer,
760       address->address,
761       address->address_length,
762       NULL, NULL);
763 #if VERBOSE
764     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
765               "Creating new session %p for peer `%s' address `%s'\n",
766               s,
767               GNUNET_i2s(&address->peer),
768               udp_address_to_string(NULL,address->address,address->address_length));
769 #endif
770   GNUNET_assert (GNUNET_OK ==
771                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
772                                                     &s->target.hashPubKey,
773                                                     s,
774                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
775
776   return s;
777 }
778
779 /**
780  * Function that is called with messages created by the fragmentation
781  * module.  In the case of the 'proc' callback of the
782  * GNUNET_FRAGMENT_context_create function, this function must
783  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
784  *
785  * @param cls closure, the 'struct FragmentationContext'
786  * @param msg the message that was created
787  */
788 static void
789 enqueue_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
790 {
791   struct FragmentationContext *frag_ctx = cls;
792   struct Plugin *plugin = frag_ctx->plugin;
793   struct UDPMessageWrapper * udpw;
794
795   size_t msg_len = ntohs (msg->size);
796
797 #if VERBOSE_UDP
798   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Enqueuing fragment with %u bytes %u\n", msg_len , sizeof (struct UDPMessageWrapper));
799 #endif
800
801   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msg_len);
802   udpw->session = frag_ctx->session;
803   udpw->udp = (char *) &udpw[1];
804
805   udpw->msg_size = msg_len;
806   udpw->cont = frag_ctx->cont;
807   udpw->cont_cls = frag_ctx->cont_cls;
808   udpw->timeout = frag_ctx->timeout;
809   udpw->frag_ctx = frag_ctx;
810   memcpy (udpw->udp, msg, msg_len);
811
812   GNUNET_CONTAINER_DLL_insert(plugin->msg_head, plugin->msg_tail, udpw);
813 }
814
815
816 /**
817  * Function that can be used by the transport service to transmit
818  * a message using the plugin.   Note that in the case of a
819  * peer disconnecting, the continuation MUST be called
820  * prior to the disconnect notification itself.  This function
821  * will be called with this peer's HELLO message to initiate
822  * a fresh connection to another peer.
823  *
824  * @param cls closure
825  * @param s which session must be used
826  * @param msgbuf the message to transmit
827  * @param msgbuf_size number of bytes in 'msgbuf'
828  * @param priority how important is the message (most plugins will
829  *                 ignore message priority and just FIFO)
830  * @param to how long to wait at most for the transmission (does not
831  *                require plugins to discard the message after the timeout,
832  *                just advisory for the desired delay; most plugins will ignore
833  *                this as well)
834  * @param cont continuation to call once the message has
835  *        been transmitted (or if the transport is ready
836  *        for the next transmission call; or if the
837  *        peer disconnected...); can be NULL
838  * @param cont_cls closure for cont
839  * @return number of bytes used (on the physical network, with overheads);
840  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
841  *         and does NOT mean that the message was not transmitted (DV)
842  */
843 static ssize_t
844 udp_plugin_send (void *cls,
845                   struct Session *s,
846                   const char *msgbuf, size_t msgbuf_size,
847                   unsigned int priority,
848                   struct GNUNET_TIME_Relative to,
849                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
850 {
851   struct Plugin *plugin = cls;
852   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
853
854   struct UDPMessageWrapper * udpw;
855   struct UDPMessage *udp;
856   char mbuf[mlen];
857   GNUNET_assert (plugin != NULL);
858   GNUNET_assert (s != NULL);
859
860   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
861   {
862     GNUNET_break (0);
863     return GNUNET_SYSERR;
864   }
865
866   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessions, &s->target.hashPubKey, s))
867   {
868     GNUNET_break (0);
869     return GNUNET_SYSERR;
870   }
871
872   LOG (GNUNET_ERROR_TYPE_DEBUG,
873        "UDP transmits %u-byte message to `%s' using address `%s'\n",
874          msgbuf_size,
875          GNUNET_i2s (&s->target),
876          GNUNET_a2s(s->sock_addr, s->addrlen));
877
878   /* Message */
879   udp = (struct UDPMessage *) mbuf;
880   udp->header.size = htons (mlen);
881   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
882   udp->reserved = htonl (0);
883   udp->sender = *plugin->env->my_identity;
884
885   if (mlen <= UDP_MTU)
886   {
887     udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + mlen);
888     udpw->session = s;
889     udpw->udp = (char *) &udpw[1];
890     udpw->msg_size = mlen;
891     udpw->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
892     udpw->cont = cont;
893     udpw->cont_cls = cont_cls;
894     udpw->frag_ctx = NULL;
895
896     memcpy (udpw->udp, udp, sizeof (struct UDPMessage));
897     memcpy (&udpw->udp[sizeof (struct UDPMessage)], msgbuf, msgbuf_size);
898
899     GNUNET_CONTAINER_DLL_insert(plugin->msg_head, plugin->msg_tail, udpw);
900   }
901   else
902   {
903     LOG (GNUNET_ERROR_TYPE_DEBUG,
904          "UDP has to fragment message \n");
905     if  (s->frag_ctx != NULL)
906       return GNUNET_SYSERR;
907     memcpy (&udp[1], msgbuf, msgbuf_size);
908     struct FragmentationContext * frag_ctx = GNUNET_malloc(sizeof (struct FragmentationContext));
909
910     frag_ctx->plugin = plugin;
911     frag_ctx->session = s;
912     frag_ctx->cont = cont;
913     frag_ctx->cont_cls = cont_cls;
914     frag_ctx->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
915     frag_ctx->bytes_to_send = mlen;
916     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
917               UDP_MTU,
918               &plugin->tracker,
919               s->last_expected_delay,
920               &udp->header,
921               &enqueue_fragment,
922               frag_ctx);
923
924     s->frag_ctx = frag_ctx;
925
926   }
927   return mlen;
928 }
929
930
931 /**
932  * Our external IP address/port mapping has changed.
933  *
934  * @param cls closure, the 'struct LocalAddrList'
935  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
936  *     the previous (now invalid) one
937  * @param addr either the previous or the new public IP address
938  * @param addrlen actual lenght of the address
939  */
940 static void
941 udp_nat_port_map_callback (void *cls, int add_remove,
942                            const struct sockaddr *addr, socklen_t addrlen)
943 {
944   struct Plugin *plugin = cls;
945   struct IPv4UdpAddress u4;
946   struct IPv6UdpAddress u6;
947   void *arg;
948   size_t args;
949
950   /* convert 'addr' to our internal format */
951   switch (addr->sa_family)
952   {
953   case AF_INET:
954     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
955     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
956     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
957     arg = &u4;
958     args = sizeof (u4);
959     break;
960   case AF_INET6:
961     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
962     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
963             sizeof (struct in6_addr));
964     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
965     arg = &u6;
966     args = sizeof (u6);
967     break;
968   default:
969     GNUNET_break (0);
970     return;
971   }
972   /* modify our published address list */
973   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
974 }
975
976
977
978 /**
979  * Message tokenizer has broken up an incomming message. Pass it on
980  * to the service.
981  *
982  * @param cls the 'struct Plugin'
983  * @param client the 'struct SourceInformation'
984  * @param hdr the actual message
985  */
986 static void
987 process_inbound_tokenized_messages (void *cls, void *client,
988                                     const struct GNUNET_MessageHeader *hdr)
989 {
990   struct Plugin *plugin = cls;
991   struct SourceInformation *si = client;
992   struct GNUNET_ATS_Information ats[2];
993   struct GNUNET_TIME_Relative delay;
994
995   GNUNET_assert (si->session != NULL);
996   /* setup ATS */
997   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
998   ats[0].value = htonl (1);
999   ats[1] = si->session->ats;
1000   GNUNET_break (ntohl(ats[1].value) != GNUNET_ATS_NET_UNSPECIFIED);
1001
1002   delay = plugin->env->receive (plugin->env->cls,
1003                 &si->sender,
1004                 hdr,
1005                 (const struct GNUNET_ATS_Information *) &ats, 2,
1006                 NULL,
1007                 si->arg,
1008                 si->args);
1009   si->session->flow_delay_for_other_peer = delay;
1010 }
1011
1012
1013 /**
1014  * We've received a UDP Message.  Process it (pass contents to main service).
1015  *
1016  * @param plugin plugin context
1017  * @param msg the message
1018  * @param sender_addr sender address
1019  * @param sender_addr_len number of bytes in sender_addr
1020  */
1021 static void
1022 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1023                      const struct sockaddr *sender_addr,
1024                      socklen_t sender_addr_len)
1025 {
1026   struct SourceInformation si;
1027   struct Session * s = NULL;
1028   struct IPv4UdpAddress u4;
1029   struct IPv6UdpAddress u6;
1030   struct GNUNET_ATS_Information ats;
1031   const void *arg;
1032   size_t args;
1033
1034   if (0 != ntohl (msg->reserved))
1035   {
1036     GNUNET_break_op (0);
1037     return;
1038   }
1039   if (ntohs (msg->header.size) <
1040       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
1041   {
1042     GNUNET_break_op (0);
1043     return;
1044   }
1045
1046   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1047   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
1048   /* convert address */
1049   switch (sender_addr->sa_family)
1050   {
1051   case AF_INET:
1052     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
1053     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
1054     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1055     arg = &u4;
1056     args = sizeof (u4);
1057     break;
1058   case AF_INET6:
1059     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
1060     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
1061     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
1062     arg = &u6;
1063     args = sizeof (u6);
1064     break;
1065   default:
1066     GNUNET_break (0);
1067     return;
1068   }
1069 #if DEBUG_UDP
1070   LOG (GNUNET_ERROR_TYPE_DEBUG,
1071        "Received message with %u bytes from peer `%s' at `%s'\n",
1072        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1073        GNUNET_a2s (sender_addr, sender_addr_len));
1074 #endif
1075
1076   struct GNUNET_HELLO_Address * address = GNUNET_HELLO_address_allocate(&msg->sender, "udp", arg, args);
1077   s = udp_plugin_get_session(plugin, address);
1078   GNUNET_free (address);
1079
1080   /* iterate over all embedded messages */
1081   si.session = s;
1082   si.sender = msg->sender;
1083   si.arg = arg;
1084   si.args = args;
1085
1086   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
1087                              ntohs (msg->header.size) -
1088                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
1089 }
1090
1091
1092 /**
1093  * Scan the heap for a receive context with the given address.
1094  *
1095  * @param cls the 'struct FindReceiveContext'
1096  * @param node internal node of the heap
1097  * @param element value stored at the node (a 'struct ReceiveContext')
1098  * @param cost cost associated with the node
1099  * @return GNUNET_YES if we should continue to iterate,
1100  *         GNUNET_NO if not.
1101  */
1102 static int
1103 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1104                       void *element, GNUNET_CONTAINER_HeapCostType cost)
1105 {
1106   struct FindReceiveContext *frc = cls;
1107   struct DefragContext *e = element;
1108
1109   if ((frc->addr_len == e->addr_len) &&
1110       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1111   {
1112     frc->rc = e;
1113     return GNUNET_NO;
1114   }
1115   return GNUNET_YES;
1116 }
1117
1118
1119 /**
1120  * Process a defragmented message.
1121  *
1122  * @param cls the 'struct ReceiveContext'
1123  * @param msg the message
1124  */
1125 static void
1126 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1127 {
1128   struct DefragContext *rc = cls;
1129
1130   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1131   {
1132     GNUNET_break (0);
1133     return;
1134   }
1135   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1136   {
1137     GNUNET_break (0);
1138     return;
1139   }
1140   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1141                        rc->src_addr, rc->addr_len);
1142 }
1143
1144 struct LookupContext
1145 {
1146   const struct sockaddr * addr;
1147   size_t addrlen;
1148
1149   struct Session *res;
1150 };
1151
1152 static int
1153 lookup_session_by_addr_it (void *cls, const GNUNET_HashCode * key, void *value)
1154 {
1155   struct LookupContext *l_ctx = cls;
1156   struct Session * s = value;
1157
1158   if ((s->addrlen == l_ctx->addrlen) &&
1159       (0 == memcmp (s->sock_addr, l_ctx->addr, s->addrlen)))
1160   {
1161     l_ctx->res = s;
1162     return GNUNET_NO;
1163   }
1164   return GNUNET_YES;
1165 }
1166
1167 /**
1168  * Transmit an acknowledgement.
1169  *
1170  * @param cls the 'struct ReceiveContext'
1171  * @param id message ID (unused)
1172  * @param msg ack to transmit
1173  */
1174 static void
1175 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
1176 {
1177   struct DefragContext *rc = cls;
1178
1179   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
1180   struct UDP_ACK_Message *udp_ack;
1181   uint32_t delay = 0;
1182   struct UDPMessageWrapper *udpw;
1183   struct Session *s;
1184
1185   struct LookupContext l_ctx;
1186   l_ctx.addr = rc->src_addr;
1187   l_ctx.addrlen = rc->addr_len;
1188   l_ctx.res = NULL;
1189   GNUNET_CONTAINER_multihashmap_iterate (rc->plugin->sessions,
1190       &lookup_session_by_addr_it,
1191       &l_ctx);
1192   s = l_ctx.res;
1193
1194   GNUNET_assert (s != NULL);
1195
1196   if (s->flow_delay_for_other_peer.rel_value <= UINT32_MAX)
1197     delay = s->flow_delay_for_other_peer.rel_value;
1198
1199 #if DEBUG_UDP
1200   LOG (GNUNET_ERROR_TYPE_DEBUG,
1201        "Sending ACK to `%s' including delay of %u ms\n",
1202        GNUNET_a2s (rc->src_addr,
1203                    (rc->src_addr->sa_family ==
1204                     AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct
1205                                                                      sockaddr_in6)),
1206        delay);
1207 #endif
1208   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msize);
1209   udpw->cont = NULL;
1210   udpw->cont_cls = NULL;
1211   udpw->frag_ctx = NULL;
1212   udpw->msg_size = msize;
1213   udpw->session = s;
1214   udpw->timeout = GNUNET_TIME_absolute_get_forever();
1215   udpw->udp = (char *)&udpw[1];
1216
1217   udp_ack = (struct UDP_ACK_Message *) udpw->udp;
1218   udp_ack->header.size = htons ((uint16_t) msize);
1219   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
1220   udp_ack->delay = htonl (delay);
1221   udp_ack->sender = *rc->plugin->env->my_identity;
1222   memcpy (&udp_ack[1], msg, ntohs (msg->size));
1223
1224   GNUNET_CONTAINER_DLL_insert(rc->plugin->msg_head, rc->plugin->msg_tail, udpw);
1225 }
1226
1227
1228 static void read_process_msg (struct Plugin *plugin,
1229     const struct GNUNET_MessageHeader *msg,
1230     char *addr,
1231     socklen_t fromlen)
1232 {
1233   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1234   {
1235     GNUNET_break_op (0);
1236     return;
1237   }
1238   process_udp_message (plugin, (const struct UDPMessage *) msg,
1239                        (const struct sockaddr *) addr, fromlen);
1240   return;
1241 }
1242
1243 static void read_process_ack (struct Plugin *plugin,
1244     const struct GNUNET_MessageHeader *msg,
1245     char *addr,
1246     socklen_t fromlen)
1247 {
1248   const struct GNUNET_MessageHeader *ack;
1249   const struct UDP_ACK_Message *udp_ack;
1250   struct LookupContext l_ctx;
1251   struct Session *s = NULL;
1252   struct GNUNET_TIME_Relative flow_delay;
1253
1254   if (ntohs (msg->size) <
1255       sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
1256   {
1257     GNUNET_break_op (0);
1258     return;
1259   }
1260
1261   udp_ack = (const struct UDP_ACK_Message *) msg;
1262
1263   l_ctx.addr = (const struct sockaddr *) addr;
1264   l_ctx.addrlen = fromlen;
1265   l_ctx.res = NULL;
1266   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
1267       &lookup_session_by_addr_it,
1268       &l_ctx);
1269   s = l_ctx.res;
1270
1271   if ((s == NULL) || (s->frag_ctx == NULL))
1272     return;
1273
1274   flow_delay.rel_value = (uint64_t) ntohl (udp_ack->delay);
1275   LOG (GNUNET_ERROR_TYPE_DEBUG, "We received a sending delay of %llu\n",
1276        flow_delay.rel_value);
1277   s->flow_delay_from_other_peer =
1278       GNUNET_TIME_relative_to_absolute (flow_delay);
1279
1280   ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
1281   if (ntohs (ack->size) !=
1282       ntohs (msg->size) - sizeof (struct UDP_ACK_Message))
1283   {
1284     GNUNET_break_op (0);
1285     return;
1286   }
1287
1288   if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (s->frag_ctx->frag, ack))
1289   {
1290 #if DEBUG_UDP
1291   LOG (GNUNET_ERROR_TYPE_DEBUG,
1292        "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1293        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1294        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1295 #endif
1296     return;
1297   }
1298
1299 #if DEBUG_UDP
1300   LOG (GNUNET_ERROR_TYPE_DEBUG,
1301        "FULL MESSAGE ACKed\n",
1302        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1303        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1304 #endif
1305   s->last_expected_delay = GNUNET_FRAGMENT_context_destroy (s->frag_ctx->frag);
1306
1307   struct UDPMessageWrapper * udpw = plugin->msg_head;
1308   while (udpw!= NULL)
1309   {
1310     if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1311     {
1312       GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, udpw);
1313       GNUNET_free (udpw);
1314     }
1315     udpw = udpw->next;
1316   }
1317
1318   if (s->frag_ctx->cont != NULL)
1319     s->frag_ctx->cont
1320     (s->frag_ctx->cont_cls, &udp_ack->sender, GNUNET_OK);
1321   GNUNET_free (s->frag_ctx);
1322   s->frag_ctx = NULL;
1323   return;
1324 }
1325
1326 static void read_process_fragment (struct Plugin *plugin,
1327     const struct GNUNET_MessageHeader *msg,
1328     char *addr,
1329     socklen_t fromlen)
1330 {
1331   struct DefragContext *d_ctx;
1332   struct GNUNET_TIME_Absolute now;
1333   struct FindReceiveContext frc;
1334
1335
1336   frc.rc = NULL;
1337   frc.addr = (const struct sockaddr *) addr;
1338   frc.addr_len = fromlen;
1339
1340 #if DEBUG_UDP
1341   LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
1342        (unsigned int) ntohs (msg->size),
1343        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1344 #endif
1345
1346   /* Lookup existing receive context for this address */
1347   GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
1348                                  &find_receive_context,
1349                                  &frc);
1350   now = GNUNET_TIME_absolute_get ();
1351   d_ctx = frc.rc;
1352
1353   if (d_ctx == NULL)
1354   {
1355     /* Create a new defragmentation context */
1356     d_ctx = GNUNET_malloc (sizeof (struct DefragContext) + fromlen);
1357     memcpy (&d_ctx[1], addr, fromlen);
1358     d_ctx->src_addr = (const struct sockaddr *) &d_ctx[1];
1359     d_ctx->addr_len = fromlen;
1360     d_ctx->plugin = plugin;
1361     d_ctx->defrag =
1362         GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1363                                           UDP_MAX_MESSAGES_IN_DEFRAG, d_ctx,
1364                                           &fragment_msg_proc, &ack_proc);
1365     d_ctx->hnode =
1366         GNUNET_CONTAINER_heap_insert (plugin->defrag_ctxs, d_ctx,
1367                                       (GNUNET_CONTAINER_HeapCostType)
1368                                       now.abs_value);
1369 #if DEBUG_UDP
1370   LOG (GNUNET_ERROR_TYPE_DEBUG, "Created new defragmentation context for %u-byte fragment from `%s'\n",
1371        (unsigned int) ntohs (msg->size),
1372        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1373 #endif
1374   }
1375   else
1376   {
1377 #if DEBUG_UDP
1378   LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing defragmentation context for %u-byte fragment from `%s'\n",
1379        (unsigned int) ntohs (msg->size),
1380        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1381 #endif
1382   }
1383
1384   if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (d_ctx->defrag, msg))
1385   {
1386     /* keep this 'rc' from expiring */
1387     GNUNET_CONTAINER_heap_update_cost (plugin->defrag_ctxs, d_ctx->hnode,
1388                                        (GNUNET_CONTAINER_HeapCostType)
1389                                        now.abs_value);
1390   }
1391   if (GNUNET_CONTAINER_heap_get_size (plugin->defrag_ctxs) >
1392       UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1393   {
1394     /* remove 'rc' that was inactive the longest */
1395     d_ctx = GNUNET_CONTAINER_heap_remove_root (plugin->defrag_ctxs);
1396     GNUNET_assert (NULL != d_ctx);
1397     GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
1398     GNUNET_free (d_ctx);
1399   }
1400 }
1401
1402 /**
1403  * Read and process a message from the given socket.
1404  *
1405  * @param plugin the overall plugin
1406  * @param rsock socket to read from
1407  */
1408 static void
1409 udp_select_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
1410 {
1411   socklen_t fromlen;
1412   char addr[32];
1413   char buf[65536];
1414   ssize_t size;
1415   const struct GNUNET_MessageHeader *msg;
1416
1417   fromlen = sizeof (addr);
1418   memset (&addr, 0, sizeof (addr));
1419   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
1420                                       (struct sockaddr *) &addr, &fromlen);
1421
1422   if (size < sizeof (struct GNUNET_MessageHeader))
1423   {
1424     GNUNET_break_op (0);
1425     return;
1426   }
1427   msg = (const struct GNUNET_MessageHeader *) buf;
1428
1429   LOG (GNUNET_ERROR_TYPE_DEBUG,
1430        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) size,
1431        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
1432
1433   if (size != ntohs (msg->size))
1434   {
1435     GNUNET_break_op (0);
1436     return;
1437   }
1438
1439   switch (ntohs (msg->type))
1440   {
1441   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
1442     udp_broadcast_receive (plugin, &buf, size, addr, fromlen);
1443     return;
1444
1445   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
1446     read_process_msg (plugin, msg, addr, fromlen);
1447     return;
1448
1449   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
1450     read_process_ack (plugin, msg, addr, fromlen);;
1451     return;
1452
1453   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1454     read_process_fragment (plugin, msg, addr, fromlen);
1455     return;
1456
1457   default:
1458     GNUNET_break_op (0);
1459     return;
1460   }
1461 }
1462
1463 size_t
1464 udp_select_send (struct Plugin *plugin)
1465 {
1466   ssize_t sent;
1467   size_t slen;
1468   struct GNUNET_TIME_Absolute max;
1469   struct GNUNET_TIME_Absolute ;
1470
1471   struct UDPMessageWrapper *udpw = plugin->msg_head;
1472   const struct sockaddr * sa = udpw->session->sock_addr;
1473
1474   max = GNUNET_TIME_absolute_max(udpw->timeout, GNUNET_TIME_absolute_get());
1475
1476   while (udpw != NULL)
1477   {
1478     if (max.abs_value != udpw->timeout.abs_value)
1479     {
1480       /* Message timed out */
1481
1482       if (udpw->cont != NULL)
1483         udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1484       if (udpw->frag_ctx != NULL)
1485       {
1486 #if DEBUG_UDP
1487         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Fragmented message for peer `%s' with size %u timed out\n",
1488             GNUNET_i2s(&udpw->session->target), udpw->frag_ctx->bytes_to_send);
1489 #endif
1490         udpw->session->last_expected_delay = GNUNET_FRAGMENT_context_destroy(udpw->frag_ctx->frag);
1491         GNUNET_free (udpw->frag_ctx);
1492         udpw->session->frag_ctx = NULL;
1493       }
1494       else
1495       {
1496 #if DEBUG_UDP
1497         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' with size %u timed out\n",
1498             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1499 #endif
1500       }
1501
1502       GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, udpw);
1503       GNUNET_free (udpw);
1504       udpw = plugin->msg_head;
1505     }
1506     else
1507     {
1508       struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer);
1509       if (delta.rel_value == 0)
1510       {
1511         /* this message is not delayed */
1512         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is not delayed \n",
1513             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1514         break;
1515       }
1516       else
1517       {
1518         /* this message is delayed, try next */
1519         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is delayed for %llu \n",
1520             GNUNET_i2s(&udpw->session->target), udpw->msg_size,
1521             delta);
1522         udpw = udpw->next;
1523       }
1524     }
1525
1526   }
1527
1528   if (udpw == NULL)
1529   {
1530     /* No message left */
1531     return 0;
1532   }
1533
1534   switch (sa->sa_family)
1535   {
1536   case AF_INET:
1537     if (NULL == plugin->sockv4)
1538       return 0;
1539     sent =
1540         GNUNET_NETWORK_socket_sendto (plugin->sockv4, udpw->udp, udpw->msg_size,
1541                                       sa, slen = sizeof (struct sockaddr_in));
1542     break;
1543   case AF_INET6:
1544     if (NULL == plugin->sockv6)
1545       return 0;
1546     sent =
1547         GNUNET_NETWORK_socket_sendto (plugin->sockv6, udpw->udp, udpw->msg_size,
1548                                       sa, slen = sizeof (struct sockaddr_in6));
1549     break;
1550   default:
1551     GNUNET_break (0);
1552     return 0;
1553   }
1554   if (GNUNET_SYSERR == sent)
1555   {
1556     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
1557     LOG (GNUNET_ERROR_TYPE_DEBUG,
1558          "UDP transmitted %u-byte message to %s (%d: %s)\n",
1559          (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
1560          (sent < 0) ? STRERROR (errno) : "ok");
1561     if (udpw->cont != NULL)
1562       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1563   }
1564   LOG (GNUNET_ERROR_TYPE_DEBUG,
1565        "UDP transmitted %u-byte message to %s (%d: %s)\n",
1566        (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
1567        (sent < 0) ? STRERROR (errno) : "ok");
1568
1569   /* This was just a message fragment */
1570   if (udpw->frag_ctx != NULL)
1571   {
1572     GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);
1573   }
1574   /* This was a complete message*/
1575   else
1576   {
1577     if (udpw->cont != NULL)
1578       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_OK);
1579   }
1580
1581   GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, udpw);
1582   GNUNET_free (udpw);
1583
1584   return sent;
1585 }
1586
1587 /**
1588  * We have been notified that our readset has something to read.  We don't
1589  * know which socket needs to be read, so we have to check each one
1590  * Then reschedule this function to be called again once more is available.
1591  *
1592  * @param cls the plugin handle
1593  * @param tc the scheduling context (for rescheduling this function again)
1594  */
1595 static void
1596 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1597 {
1598   struct Plugin *plugin = cls;
1599
1600   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1601   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1602     return;
1603
1604   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1605   {
1606     if ((NULL != plugin->sockv4) &&
1607       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
1608         udp_select_read (plugin, plugin->sockv4);
1609     if ((NULL != plugin->sockv6) &&
1610       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
1611         udp_select_read (plugin, plugin->sockv6);
1612   }
1613
1614   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1615   {
1616     if (plugin->msg_head != NULL)
1617       udp_select_send (plugin);
1618   }
1619
1620   plugin->select_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1621                                    GNUNET_SCHEDULER_NO_TASK,
1622                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1623                                    plugin->ws, &udp_plugin_select, plugin);
1624
1625 }
1626
1627
1628 static int
1629 setup_sockets (struct Plugin *plugin, struct sockaddr_in6 *serverAddrv6, struct sockaddr_in *serverAddrv4)
1630 {
1631   int tries;
1632   int sockets_created = 0;
1633   struct sockaddr *serverAddr;
1634   struct sockaddr *addrs[2];
1635   socklen_t addrlens[2];
1636   socklen_t addrlen;
1637
1638   /* Create IPv6 socket */
1639   if (plugin->enable_ipv6 == GNUNET_YES)
1640   {
1641     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1642     if (NULL == plugin->sockv6)
1643     {
1644       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Disabling IPv6 since it is not supported on this system!\n");
1645       plugin->enable_ipv6 = GNUNET_NO;
1646     }
1647     else
1648     {
1649 #if HAVE_SOCKADDR_IN_SIN_LEN
1650       serverAddrv6->sin6_len = sizeof (serverAddrv6);
1651 #endif
1652       serverAddrv6->sin6_family = AF_INET6;
1653       serverAddrv6->sin6_addr = in6addr_any;
1654       serverAddrv6->sin6_port = htons (plugin->port);
1655       addrlen = sizeof (struct sockaddr_in6);
1656       serverAddr = (struct sockaddr *) serverAddrv6;
1657 #if DEBUG_UDP
1658       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1659            ntohs (serverAddrv6->sin6_port));
1660 #endif
1661       tries = 0;
1662       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1663              GNUNET_OK)
1664       {
1665         serverAddrv6->sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1666 #if DEBUG_UDP
1667         LOG (GNUNET_ERROR_TYPE_DEBUG,
1668              "IPv6 Binding failed, trying new port %d\n",
1669              ntohs (serverAddrv6->sin6_port));
1670 #endif
1671         tries++;
1672         if (tries > 10)
1673         {
1674           GNUNET_NETWORK_socket_close (plugin->sockv6);
1675           plugin->sockv6 = NULL;
1676           break;
1677         }
1678       }
1679       if (plugin->sockv6 != NULL)
1680       {
1681 #if DEBUG_UDP
1682         LOG (GNUNET_ERROR_TYPE_DEBUG,
1683              "IPv6 socket created on port %d\n",
1684              ntohs (serverAddrv6->sin6_port));
1685 #endif
1686         addrs[sockets_created] = (struct sockaddr *) serverAddrv6;
1687         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
1688         sockets_created++;
1689       }
1690     }
1691   }
1692
1693   /* Create IPv4 socket */
1694   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1695   if (NULL == plugin->sockv4)
1696   {
1697     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1698   }
1699   else
1700   {
1701 #if HAVE_SOCKADDR_IN_SIN_LEN
1702     serverAddrv4->sin_len = sizeof (serverAddrv4);
1703 #endif
1704     serverAddrv4->sin_family = AF_INET;
1705     serverAddrv4->sin_addr.s_addr = INADDR_ANY;
1706     serverAddrv4->sin_port = htons (plugin->port);
1707     addrlen = sizeof (struct sockaddr_in);
1708     serverAddr = (struct sockaddr *) serverAddrv4;
1709
1710 #if DEBUG_UDP
1711     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1712          ntohs (serverAddrv4->sin_port));
1713 #endif
1714     tries = 0;
1715     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1716            GNUNET_OK)
1717     {
1718       serverAddrv4->sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1719 #if DEBUG_UDP
1720       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
1721            ntohs (serverAddrv4->sin_port));
1722 #endif
1723       tries++;
1724       if (tries > 10)
1725       {
1726         GNUNET_NETWORK_socket_close (plugin->sockv4);
1727         plugin->sockv4 = NULL;
1728         break;
1729       }
1730     }
1731     if (plugin->sockv4 != NULL)
1732     {
1733       addrs[sockets_created] = (struct sockaddr *) serverAddrv4;
1734       addrlens[sockets_created] = sizeof (struct sockaddr_in);
1735       sockets_created++;
1736     }
1737   }
1738
1739   /* Create file descriptors */
1740   plugin->rs = GNUNET_NETWORK_fdset_create ();
1741   plugin->ws = GNUNET_NETWORK_fdset_create ();
1742   GNUNET_NETWORK_fdset_zero (plugin->rs);
1743   GNUNET_NETWORK_fdset_zero (plugin->ws);
1744   if (NULL != plugin->sockv4)
1745   {
1746     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
1747     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv4);
1748   }
1749   if (NULL != plugin->sockv6)
1750   {
1751     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
1752     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv6);
1753   }
1754
1755   if (sockets_created == 0)
1756     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
1757
1758   plugin->select_task =
1759       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1760                                    GNUNET_SCHEDULER_NO_TASK,
1761                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1762                                    plugin->ws, &udp_plugin_select, plugin);
1763
1764   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
1765                            GNUNET_NO, plugin->port,
1766                            sockets_created,
1767                            (const struct sockaddr **) addrs, addrlens,
1768                            &udp_nat_port_map_callback, NULL, plugin);
1769
1770   return sockets_created;
1771 }
1772
1773
1774 /**
1775  * The exported method. Makes the core api available via a global and
1776  * returns the udp transport API.
1777  *
1778  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1779  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1780  */
1781 void *
1782 libgnunet_plugin_transport_udp_init (void *cls)
1783 {
1784   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1785   struct GNUNET_TRANSPORT_PluginFunctions *api;
1786   struct Plugin *plugin;
1787
1788   unsigned long long port;
1789   unsigned long long aport;
1790   unsigned long long broadcast;
1791   unsigned long long udp_max_bps;
1792   unsigned long long enable_v6;
1793   char * bind4_address;
1794   char * bind6_address;
1795   struct GNUNET_TIME_Relative interval;
1796
1797   struct sockaddr_in serverAddrv4;
1798   struct sockaddr_in6 serverAddrv6;
1799
1800   int res;
1801
1802   /* Get port number */
1803   if (GNUNET_OK !=
1804       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
1805                                              &port))
1806     port = 2086;
1807   if (GNUNET_OK !=
1808       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1809                                              "ADVERTISED_PORT", &aport))
1810     aport = port;
1811   if (port > 65535)
1812   {
1813     LOG (GNUNET_ERROR_TYPE_WARNING,
1814          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
1815          65535);
1816     return NULL;
1817   }
1818
1819   /* Protocols */
1820   if ((GNUNET_YES ==
1821        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
1822                                              "DISABLEV6")))
1823   {
1824     enable_v6 = GNUNET_NO;
1825   }
1826   else
1827     enable_v6 = GNUNET_YES;
1828
1829
1830   /* Addresses */
1831   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1832   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1833
1834   if (GNUNET_YES ==
1835       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1836                                              "BINDTO", &bind4_address))
1837   {
1838     LOG (GNUNET_ERROR_TYPE_DEBUG,
1839          "Binding udp plugin to specific address: `%s'\n",
1840          bind4_address);
1841     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
1842     {
1843       GNUNET_free (bind4_address);
1844       return NULL;
1845     }
1846   }
1847
1848   if (GNUNET_YES ==
1849       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1850                                              "BINDTO6", &bind6_address))
1851   {
1852     LOG (GNUNET_ERROR_TYPE_DEBUG,
1853          "Binding udp plugin to specific address: `%s'\n",
1854          bind6_address);
1855     if (1 !=
1856         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
1857     {
1858       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1859            bind6_address);
1860       GNUNET_free_non_null (bind4_address);
1861       GNUNET_free (bind6_address);
1862       return NULL;
1863     }
1864   }
1865
1866
1867   /* Enable neighbour discovery */
1868   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
1869                                             "BROADCAST");
1870   if (broadcast == GNUNET_SYSERR)
1871     broadcast = GNUNET_NO;
1872
1873   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-udp",
1874                                            "BROADCAST_INTERVAL", &interval))
1875   {
1876     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1877   }
1878
1879   /* Maximum datarate */
1880   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1881                                              "MAX_BPS", &udp_max_bps))
1882   {
1883     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1884   }
1885
1886   plugin = GNUNET_malloc (sizeof (struct Plugin));
1887   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1888
1889   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1890                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
1891
1892
1893   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
1894   plugin->defrag_ctxs = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1895   plugin->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
1896   plugin->port = port;
1897   plugin->aport = aport;
1898   plugin->broadcast_interval = interval;
1899   plugin->enable_ipv6 = enable_v6;
1900   plugin->env = env;
1901
1902   api->cls = plugin;
1903   api->send = NULL;
1904   api->disconnect = &udp_disconnect;
1905   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1906   api->address_to_string = &udp_address_to_string;
1907   api->check_address = &udp_plugin_check_address;
1908   api->get_session = &udp_plugin_get_session;
1909   api->send = &udp_plugin_send;
1910
1911   LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
1912   res = setup_sockets (plugin, &serverAddrv6, &serverAddrv4);
1913   if ((res == 0) || ((plugin->sockv4 == NULL) && (plugin->sockv6 == NULL)))
1914   {
1915     LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to create network sockets, plugin failed\n");
1916     GNUNET_free (plugin);
1917     GNUNET_free (api);
1918     return NULL;
1919   }
1920
1921   LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting broadcasting\n");
1922   if (broadcast == GNUNET_YES)
1923     setup_broadcast (plugin, &serverAddrv6, &serverAddrv4);
1924
1925
1926   GNUNET_free_non_null (bind4_address);
1927   GNUNET_free_non_null (bind6_address);
1928   return api;
1929 }
1930
1931 int heap_cleanup_iterator (void *cls,
1932                           struct GNUNET_CONTAINER_HeapNode *
1933                           node, void *element,
1934                           GNUNET_CONTAINER_HeapCostType
1935                           cost)
1936 {
1937   struct DefragContext * d_ctx = element;
1938
1939   GNUNET_CONTAINER_heap_remove_node (node);
1940   GNUNET_DEFRAGMENT_context_destroy(d_ctx->defrag);
1941   GNUNET_free (d_ctx);
1942
1943   return GNUNET_YES;
1944 }
1945
1946
1947 /**
1948  * The exported method. Makes the core api available via a global and
1949  * returns the udp transport API.
1950  *
1951  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1952  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1953  */
1954 void *
1955 libgnunet_plugin_transport_udp_done (void *cls)
1956 {
1957   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1958   struct Plugin *plugin = api->cls;
1959   stop_broadcast (plugin);
1960
1961   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1962   {
1963     GNUNET_SCHEDULER_cancel (plugin->select_task);
1964     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1965   }
1966
1967   /* Closing sockets */
1968   if (plugin->sockv4 != NULL)
1969   {
1970     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
1971     plugin->sockv4 = NULL;
1972   }
1973   if (plugin->sockv6 != NULL)
1974   {
1975     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
1976     plugin->sockv6 = NULL;
1977   }
1978   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1979   GNUNET_NETWORK_fdset_destroy (plugin->ws);
1980   GNUNET_NAT_unregister (plugin->nat);
1981
1982   if (plugin->defrag_ctxs != NULL)
1983   {
1984     GNUNET_CONTAINER_heap_iterate(plugin->defrag_ctxs,
1985         heap_cleanup_iterator, NULL);
1986     GNUNET_CONTAINER_heap_destroy(plugin->defrag_ctxs);
1987     plugin->defrag_ctxs = NULL;
1988   }
1989   if (plugin->mst != NULL)
1990   {
1991     GNUNET_SERVER_mst_destroy(plugin->mst);
1992     plugin->mst = NULL;
1993   }
1994
1995   /* Clean up leftover messages */
1996   struct UDPMessageWrapper *udpw = plugin->msg_head;
1997   while (udpw != NULL)
1998   {
1999     struct UDPMessageWrapper *tmp = udpw->next;
2000     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, udpw);
2001     if (udpw->cont != NULL)
2002       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
2003     GNUNET_free (udpw);
2004     udpw = tmp;
2005   }
2006
2007   /* Clean up sessions */
2008 #if DEBUG_UDP
2009   LOG (GNUNET_ERROR_TYPE_DEBUG,
2010        "Cleaning up sessions\n");
2011 #endif
2012   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
2013   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
2014
2015   plugin->nat = NULL;
2016   GNUNET_free (plugin);
2017   GNUNET_free (api);
2018   return NULL;
2019 }
2020
2021
2022 /* end of plugin_transport_udp.c */