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