818c61fb3ac3ef32cabdc764abf770329b9eb02b
[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  * We have been notified that our readset has something to read.  We don't
294  * know which socket needs to be read, so we have to check each one
295  * Then reschedule this function to be called again once more is available.
296  *
297  * @param cls the plugin handle
298  * @param tc the scheduling context (for rescheduling this function again)
299  */
300 static void
301 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
302
303 /**
304  * We have been notified that our readset has something to read.  We don't
305  * know which socket needs to be read, so we have to check each one
306  * Then reschedule this function to be called again once more is available.
307  *
308  * @param cls the plugin handle
309  * @param tc the scheduling context (for rescheduling this function again)
310  */
311 static void
312 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
313
314 /**
315  * Function called for a quick conversion of the binary address to
316  * a numeric address.  Note that the caller must not free the
317  * address and that the next call to this function is allowed
318  * to override the address again.
319  *
320  * @param cls closure
321  * @param addr binary address
322  * @param addrlen length of the address
323  * @return string representing the same address
324  */
325 const char *
326 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
327 {
328   static char rbuf[INET6_ADDRSTRLEN + 10];
329   char buf[INET6_ADDRSTRLEN];
330   const void *sb;
331   struct in_addr a4;
332   struct in6_addr a6;
333   const struct IPv4UdpAddress *t4;
334   const struct IPv6UdpAddress *t6;
335   int af;
336   uint16_t port;
337
338   if (addrlen == sizeof (struct IPv6UdpAddress))
339   {
340     t6 = addr;
341     af = AF_INET6;
342     port = ntohs (t6->u6_port);
343     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
344     sb = &a6;
345   }
346   else if (addrlen == sizeof (struct IPv4UdpAddress))
347   {
348     t4 = addr;
349     af = AF_INET;
350     port = ntohs (t4->u4_port);
351     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
352     sb = &a4;
353   }
354   else
355   {
356     GNUNET_break_op (0);
357     return NULL;
358   }
359   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
360   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
361                    buf, port);
362   return rbuf;
363 }
364
365
366 /**
367  * Function called to convert a string address to
368  * a binary address.
369  *
370  * @param cls closure ('struct Plugin*')
371  * @param addr string address
372  * @param addrlen length of the address
373  * @param buf location to store the buffer
374  * @param added location to store the number of bytes in the buffer.
375  *        If the function returns GNUNET_SYSERR, its contents are undefined.
376  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
377  */
378 int
379 udp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
380     void **buf, size_t *added)
381 {
382   struct sockaddr_storage socket_address;
383   int ret = GNUNET_STRINGS_to_address_ip (addr, addrlen,
384     &socket_address);
385
386   if (ret != GNUNET_OK)
387     return GNUNET_SYSERR;
388
389   if (socket_address.ss_family == AF_INET)
390   {
391     struct IPv4UdpAddress *u4;
392     struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
393     u4 = GNUNET_malloc (sizeof (struct IPv4UdpAddress));
394     u4->ipv4_addr = in4->sin_addr.s_addr;
395     u4->u4_port = in4->sin_port;
396     *buf = u4;
397     *added = sizeof (struct IPv4UdpAddress);
398   }
399   else if (socket_address.ss_family == AF_INET6)
400   {
401     struct IPv6UdpAddress *u6;
402     struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
403     u6 = GNUNET_malloc (sizeof (struct IPv6UdpAddress));
404     u6->ipv6_addr = in6->sin6_addr;
405     u6->u6_port = in6->sin6_port;
406     *buf = u6;
407     *added = sizeof (struct IPv6UdpAddress);
408   }
409   return GNUNET_SYSERR;
410 }
411
412
413 /**
414  * Append our port and forward the result.
415  *
416  * @param cls a 'struct PrettyPrinterContext'
417  * @param hostname result from DNS resolver
418  */
419 static void
420 append_port (void *cls, const char *hostname)
421 {
422   struct PrettyPrinterContext *ppc = cls;
423   char *ret;
424
425   if (hostname == NULL)
426   {
427     ppc->asc (ppc->asc_cls, NULL);
428     GNUNET_free (ppc);
429     return;
430   }
431   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
432   ppc->asc (ppc->asc_cls, ret);
433   GNUNET_free (ret);
434 }
435
436
437 /**
438  * Convert the transports address to a nice, human-readable
439  * format.
440  *
441  * @param cls closure
442  * @param type name of the transport that generated the address
443  * @param addr one of the addresses of the host, NULL for the last address
444  *        the specific address format depends on the transport
445  * @param addrlen length of the address
446  * @param numeric should (IP) addresses be displayed in numeric form?
447  * @param timeout after how long should we give up?
448  * @param asc function to call on each string
449  * @param asc_cls closure for asc
450  */
451 static void
452 udp_plugin_address_pretty_printer (void *cls, const char *type,
453                                    const void *addr, size_t addrlen,
454                                    int numeric,
455                                    struct GNUNET_TIME_Relative timeout,
456                                    GNUNET_TRANSPORT_AddressStringCallback asc,
457                                    void *asc_cls)
458 {
459   struct PrettyPrinterContext *ppc;
460   const void *sb;
461   size_t sbs;
462   struct sockaddr_in a4;
463   struct sockaddr_in6 a6;
464   const struct IPv4UdpAddress *u4;
465   const struct IPv6UdpAddress *u6;
466   uint16_t port;
467
468   if (addrlen == sizeof (struct IPv6UdpAddress))
469   {
470     u6 = addr;
471     memset (&a6, 0, sizeof (a6));
472     a6.sin6_family = AF_INET6;
473 #if HAVE_SOCKADDR_IN_SIN_LEN
474     a6.sin6_len = sizeof (a6);
475 #endif
476     a6.sin6_port = u6->u6_port;
477     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
478     port = ntohs (u6->u6_port);
479     sb = &a6;
480     sbs = sizeof (a6);
481   }
482   else if (addrlen == sizeof (struct IPv4UdpAddress))
483   {
484     u4 = addr;
485     memset (&a4, 0, sizeof (a4));
486     a4.sin_family = AF_INET;
487 #if HAVE_SOCKADDR_IN_SIN_LEN
488     a4.sin_len = sizeof (a4);
489 #endif
490     a4.sin_port = u4->u4_port;
491     a4.sin_addr.s_addr = u4->ipv4_addr;
492     port = ntohs (u4->u4_port);
493     sb = &a4;
494     sbs = sizeof (a4);
495   }
496   else
497   {
498     /* invalid address */
499     GNUNET_break_op (0);
500     asc (asc_cls, NULL);
501     return;
502   }
503   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
504   ppc->asc = asc;
505   ppc->asc_cls = asc_cls;
506   ppc->port = port;
507   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
508 }
509
510
511 /**
512  * Check if the given port is plausible (must be either our listen
513  * port or our advertised port).  If it is neither, we return
514  * GNUNET_SYSERR.
515  *
516  * @param plugin global variables
517  * @param in_port port number to check
518  * @return GNUNET_OK if port is either open_port or adv_port
519  */
520 static int
521 check_port (struct Plugin *plugin, uint16_t in_port)
522 {
523   if ((in_port == plugin->port) || (in_port == plugin->aport))
524     return GNUNET_OK;
525   return GNUNET_SYSERR;
526 }
527
528
529
530 /**
531  * Function that will be called to check if a binary address for this
532  * plugin is well-formed and corresponds to an address for THIS peer
533  * (as per our configuration).  Naturally, if absolutely necessary,
534  * plugins can be a bit conservative in their answer, but in general
535  * plugins should make sure that the address does not redirect
536  * traffic to a 3rd party that might try to man-in-the-middle our
537  * traffic.
538  *
539  * @param cls closure, should be our handle to the Plugin
540  * @param addr pointer to the address
541  * @param addrlen length of addr
542  * @return GNUNET_OK if this is a plausible address for this peer
543  *         and transport, GNUNET_SYSERR if not
544  *
545  */
546 static int
547 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
548 {
549   struct Plugin *plugin = cls;
550   struct IPv4UdpAddress *v4;
551   struct IPv6UdpAddress *v6;
552
553   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
554       (addrlen != sizeof (struct IPv6UdpAddress)))
555   {
556     GNUNET_break_op (0);
557     return GNUNET_SYSERR;
558   }
559   if (addrlen == sizeof (struct IPv4UdpAddress))
560   {
561     v4 = (struct IPv4UdpAddress *) addr;
562     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
563       return GNUNET_SYSERR;
564     if (GNUNET_OK !=
565         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
566                                  sizeof (struct in_addr)))
567       return GNUNET_SYSERR;
568   }
569   else
570   {
571     v6 = (struct IPv6UdpAddress *) addr;
572     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
573     {
574       GNUNET_break_op (0);
575       return GNUNET_SYSERR;
576     }
577     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
578       return GNUNET_SYSERR;
579     if (GNUNET_OK !=
580         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
581                                  sizeof (struct in6_addr)))
582       return GNUNET_SYSERR;
583   }
584   return GNUNET_OK;
585 }
586
587
588 /**
589  * Destroy a session, plugin is being unloaded.
590  *
591  * @param cls unused
592  * @param key hash of public key of target peer
593  * @param value a 'struct PeerSession*' to clean up
594  * @return GNUNET_OK (continue to iterate)
595  */
596 static int
597 disconnect_and_free_it (void *cls, const GNUNET_HashCode * key, void *value)
598 {
599   struct Plugin *plugin = cls;
600   struct Session *s = value;
601   struct UDPMessageWrapper *udpw;
602   struct UDPMessageWrapper *next;
603
604 #if DEBUG_UDP
605   LOG (GNUNET_ERROR_TYPE_DEBUG,
606        "Session %p to peer `%s' address ended \n",
607          s,
608          GNUNET_i2s (&s->target),
609          GNUNET_a2s (s->sock_addr, s->addrlen));
610 #endif
611
612   if (s->frag_ctx != NULL)
613   {
614     GNUNET_FRAGMENT_context_destroy(s->frag_ctx->frag);
615     GNUNET_free (s->frag_ctx);
616     s->frag_ctx = NULL;
617   }
618
619   udpw = plugin->ipv4_queue_head;
620   while (udpw != NULL)
621   {
622     next = udpw->next;
623     if (udpw->session == s)
624     {
625       GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
626
627       if (udpw->cont != NULL)
628         udpw->cont (udpw->cont_cls, &s->target, GNUNET_SYSERR);
629       GNUNET_free (udpw);
630     }
631     udpw = next;
632   }
633
634   udpw = plugin->ipv6_queue_head;
635   while (udpw != NULL)
636   {
637     next = udpw->next;
638     if (udpw->session == s)
639     {
640       GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
641
642       if (udpw->cont != NULL)
643         udpw->cont (udpw->cont_cls, &s->target, GNUNET_SYSERR);
644       GNUNET_free (udpw);
645     }
646     udpw = next;
647   }
648
649   plugin->env->session_end (plugin->env->cls, &s->target, s);
650
651   GNUNET_assert (GNUNET_YES ==
652                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
653                                                        &s->target.hashPubKey,
654                                                        s));
655
656
657   GNUNET_free (s);
658   return GNUNET_OK;
659 }
660
661
662 /**
663  * Disconnect from a remote node.  Clean up session if we have one for this peer
664  *
665  * @param cls closure for this call (should be handle to Plugin)
666  * @param target the peeridentity of the peer to disconnect
667  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
668  */
669 static void
670 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
671 {
672   struct Plugin *plugin = cls;
673   GNUNET_assert (plugin != NULL);
674
675   GNUNET_assert (target != NULL);
676 #if DEBUG_UDP
677   LOG (GNUNET_ERROR_TYPE_DEBUG,
678        "Disconnecting from peer `%s'\n", GNUNET_i2s (target));
679 #endif
680   /* Clean up sessions */
681   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessions, &target->hashPubKey, &disconnect_and_free_it, plugin);
682 }
683
684 static struct Session *
685 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
686                 const void *addr, size_t addrlen,
687                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
688 {
689   struct Session *s;
690   const struct IPv4UdpAddress *t4;
691   const struct IPv6UdpAddress *t6;
692   struct sockaddr_in *v4;
693   struct sockaddr_in6 *v6;
694   size_t len;
695
696   switch (addrlen)
697   {
698   case sizeof (struct IPv4UdpAddress):
699     if (NULL == plugin->sockv4)
700     {
701       return NULL;
702     }
703     t4 = addr;
704     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
705     len = sizeof (struct sockaddr_in);
706     v4 = (struct sockaddr_in *) &s[1];
707     v4->sin_family = AF_INET;
708 #if HAVE_SOCKADDR_IN_SIN_LEN
709     v4->sin_len = sizeof (struct sockaddr_in);
710 #endif
711     v4->sin_port = t4->u4_port;
712     v4->sin_addr.s_addr = t4->ipv4_addr;
713     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
714     break;
715   case sizeof (struct IPv6UdpAddress):
716     if (NULL == plugin->sockv6)
717     {
718       return NULL;
719     }
720     t6 = addr;
721     s =
722         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
723     len = sizeof (struct sockaddr_in6);
724     v6 = (struct sockaddr_in6 *) &s[1];
725     v6->sin6_family = AF_INET6;
726 #if HAVE_SOCKADDR_IN_SIN_LEN
727     v6->sin6_len = sizeof (struct sockaddr_in6);
728 #endif
729     v6->sin6_port = t6->u6_port;
730     v6->sin6_addr = t6->ipv6_addr;
731     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
732     break;
733   default:
734     /* Must have a valid address to send to */
735     GNUNET_break_op (0);
736     return NULL;
737   }
738
739   s->addrlen = len;
740   s->target = *target;
741   s->sock_addr = (const struct sockaddr *) &s[1];
742   s->flow_delay_for_other_peer = GNUNET_TIME_relative_get_zero();
743   s->flow_delay_from_other_peer = GNUNET_TIME_absolute_get_zero();
744   s->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
745
746   return s;
747 }
748
749 static int session_cmp_it (void *cls,
750                            const GNUNET_HashCode * key,
751                            void *value)
752 {
753   struct SessionCompareContext * cctx = cls;
754   const struct GNUNET_HELLO_Address *address = cctx->addr;
755   struct Session *s = value;
756
757   socklen_t s_addrlen = s->addrlen;
758
759 #if VERBOSE_UDP
760   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Comparing  address %s <-> %s\n",
761       udp_address_to_string (NULL, (void *) address->address, address->address_length),
762       GNUNET_a2s (s->sock_addr, s->addrlen));
763 #endif
764
765   if ((address->address_length == sizeof (struct IPv4UdpAddress)) &&
766       (s_addrlen == sizeof (struct sockaddr_in)))
767   {
768     struct IPv4UdpAddress * u4 = NULL;
769     u4 = (struct IPv4UdpAddress *) address->address;
770     const struct sockaddr_in *s4 = (const struct sockaddr_in *) s->sock_addr;
771     if ((0 == memcmp ((const void *) &u4->ipv4_addr,(const void *) &s4->sin_addr, sizeof (struct in_addr))) &&
772         (u4->u4_port == s4->sin_port))
773     {
774       cctx->res = s;
775       return GNUNET_NO;
776     }
777
778   }
779   if ((address->address_length == sizeof (struct IPv6UdpAddress)) &&
780       (s_addrlen == sizeof (struct sockaddr_in6)))
781   {
782     struct IPv6UdpAddress * u6 = NULL;
783     u6 = (struct IPv6UdpAddress *) address->address;
784     const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) s->sock_addr;
785     if ((0 == memcmp (&u6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr))) &&
786         (u6->u6_port == s6->sin6_port))
787     {
788       cctx->res = s;
789       return GNUNET_NO;
790     }
791   }
792
793
794   return GNUNET_YES;
795 }
796
797
798 /**
799  * Creates a new outbound session the transport service will use to send data to the
800  * peer
801  *
802  * @param cls the plugin
803  * @param address the address
804  * @return the session or NULL of max connections exceeded
805  */
806 static struct Session *
807 udp_plugin_get_session (void *cls,
808                   const struct GNUNET_HELLO_Address *address)
809 {
810   struct Session * s = NULL;
811   struct Plugin * plugin = cls;
812   struct IPv6UdpAddress * udp_a6;
813   struct IPv4UdpAddress * udp_a4;
814
815   GNUNET_assert (plugin != NULL);
816   GNUNET_assert (address != NULL);
817
818
819   if ((address->address == NULL) ||
820       ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
821       (address->address_length != sizeof (struct IPv6UdpAddress))))
822   {
823     GNUNET_break (0);
824     return NULL;
825   }
826
827   if (address->address_length == sizeof (struct IPv4UdpAddress))
828   {
829     if (plugin->sockv4 == NULL)
830       return NULL;
831     udp_a4 = (struct IPv4UdpAddress *) address->address;
832     if (udp_a4->u4_port == 0)
833       return NULL;
834   }
835
836   if (address->address_length == sizeof (struct IPv6UdpAddress))
837   {
838     if (plugin->sockv6 == NULL)
839       return NULL;
840     udp_a6 = (struct IPv6UdpAddress *) address->address;
841     if (udp_a6->u6_port == 0)
842       return NULL;
843   }
844
845   /* check if session already exists */
846   struct SessionCompareContext cctx;
847   cctx.addr = address;
848   cctx.res = NULL;
849 #if VERBOSE_UDP
850   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));
851 #endif
852   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessions, &address->peer.hashPubKey, session_cmp_it, &cctx);
853   if (cctx.res != NULL)
854   {
855 #if VERBOSE_UDP
856     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p\n", cctx.res);
857 #endif
858     return cctx.res;
859   }
860
861   /* otherwise create new */
862   s = create_session (plugin,
863       &address->peer,
864       address->address,
865       address->address_length,
866       NULL, NULL);
867 #if VERBOSE
868     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
869               "Creating new session %p for peer `%s' address `%s'\n",
870               s,
871               GNUNET_i2s(&address->peer),
872               udp_address_to_string(NULL,address->address,address->address_length));
873 #endif
874   GNUNET_assert (GNUNET_OK ==
875                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
876                                                     &s->target.hashPubKey,
877                                                     s,
878                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
879
880   return s;
881 }
882
883 static void enqueue (struct Plugin *plugin, struct UDPMessageWrapper * udpw)
884 {
885
886   if (udpw->session->addrlen == sizeof (struct sockaddr_in))
887     GNUNET_CONTAINER_DLL_insert(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
888   if (udpw->session->addrlen == sizeof (struct sockaddr_in6))
889     GNUNET_CONTAINER_DLL_insert(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
890 }
891
892 /**
893  * Function that is called with messages created by the fragmentation
894  * module.  In the case of the 'proc' callback of the
895  * GNUNET_FRAGMENT_context_create function, this function must
896  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
897  *
898  * @param cls closure, the 'struct FragmentationContext'
899  * @param msg the message that was created
900  */
901 static void
902 enqueue_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
903 {
904   struct FragmentationContext *frag_ctx = cls;
905   struct Plugin *plugin = frag_ctx->plugin;
906   struct UDPMessageWrapper * udpw;
907   struct Session *s;
908
909   size_t msg_len = ntohs (msg->size);
910
911 #if VERBOSE_UDP
912   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Enqueuing fragment with %u bytes %u\n", msg_len , sizeof (struct UDPMessageWrapper));
913 #endif
914
915   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msg_len);
916   udpw->session = frag_ctx->session;
917   s = udpw->session;
918   udpw->udp = (char *) &udpw[1];
919
920   udpw->msg_size = msg_len;
921   udpw->cont = frag_ctx->cont;
922   udpw->cont_cls = frag_ctx->cont_cls;
923   udpw->timeout = frag_ctx->timeout;
924   udpw->frag_ctx = frag_ctx;
925   memcpy (udpw->udp, msg, msg_len);
926
927   enqueue (plugin, udpw);
928
929
930   if (s->addrlen == sizeof (struct sockaddr_in))
931   {
932     if (plugin->with_v4_ws == GNUNET_NO)
933     {
934       if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
935         GNUNET_SCHEDULER_cancel(plugin->select_task);
936
937       plugin->select_task =
938           GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
939                                        GNUNET_TIME_UNIT_FOREVER_REL,
940                                        plugin->rs_v4,
941                                        plugin->ws_v4,
942                                        &udp_plugin_select, plugin);
943       plugin->with_v4_ws = GNUNET_YES;
944     }
945   }
946
947   else if (s->addrlen == sizeof (struct sockaddr_in6))
948   {
949     if (plugin->with_v6_ws == GNUNET_NO)
950     {
951       if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
952         GNUNET_SCHEDULER_cancel(plugin->select_task_v6);
953
954       plugin->select_task_v6 =
955           GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
956                                        GNUNET_TIME_UNIT_FOREVER_REL,
957                                        plugin->rs_v6,
958                                        plugin->ws_v6,
959                                        &udp_plugin_select_v6, plugin);
960       plugin->with_v6_ws = GNUNET_YES;
961     }
962   }
963
964 }
965
966
967
968
969 /**
970  * Function that can be used by the transport service to transmit
971  * a message using the plugin.   Note that in the case of a
972  * peer disconnecting, the continuation MUST be called
973  * prior to the disconnect notification itself.  This function
974  * will be called with this peer's HELLO message to initiate
975  * a fresh connection to another peer.
976  *
977  * @param cls closure
978  * @param s which session must be used
979  * @param msgbuf the message to transmit
980  * @param msgbuf_size number of bytes in 'msgbuf'
981  * @param priority how important is the message (most plugins will
982  *                 ignore message priority and just FIFO)
983  * @param to how long to wait at most for the transmission (does not
984  *                require plugins to discard the message after the timeout,
985  *                just advisory for the desired delay; most plugins will ignore
986  *                this as well)
987  * @param cont continuation to call once the message has
988  *        been transmitted (or if the transport is ready
989  *        for the next transmission call; or if the
990  *        peer disconnected...); can be NULL
991  * @param cont_cls closure for cont
992  * @return number of bytes used (on the physical network, with overheads);
993  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
994  *         and does NOT mean that the message was not transmitted (DV)
995  */
996 static ssize_t
997 udp_plugin_send (void *cls,
998                   struct Session *s,
999                   const char *msgbuf, size_t msgbuf_size,
1000                   unsigned int priority,
1001                   struct GNUNET_TIME_Relative to,
1002                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1003 {
1004   struct Plugin *plugin = cls;
1005   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
1006
1007   struct UDPMessageWrapper * udpw;
1008   struct UDPMessage *udp;
1009   char mbuf[mlen];
1010   GNUNET_assert (plugin != NULL);
1011   GNUNET_assert (s != NULL);
1012
1013   if ((s->addrlen == sizeof (struct sockaddr_in6)) && (plugin->sockv6 == NULL))
1014     return GNUNET_SYSERR;
1015
1016    if ((s->addrlen == sizeof (struct sockaddr_in)) && (plugin->sockv4 == NULL))
1017      return GNUNET_SYSERR;
1018
1019
1020   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1021   {
1022     GNUNET_break (0);
1023     return GNUNET_SYSERR;
1024   }
1025
1026   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessions, &s->target.hashPubKey, s))
1027   {
1028     GNUNET_break (0);
1029     return GNUNET_SYSERR;
1030   }
1031
1032   LOG (GNUNET_ERROR_TYPE_DEBUG,
1033        "UDP transmits %u-byte message to `%s' using address `%s'\n",
1034          msgbuf_size,
1035          GNUNET_i2s (&s->target),
1036          GNUNET_a2s(s->sock_addr, s->addrlen));
1037
1038   /* Message */
1039   udp = (struct UDPMessage *) mbuf;
1040   udp->header.size = htons (mlen);
1041   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
1042   udp->reserved = htonl (0);
1043   udp->sender = *plugin->env->my_identity;
1044
1045   if (mlen <= UDP_MTU)
1046   {
1047     udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + mlen);
1048     udpw->session = s;
1049     udpw->udp = (char *) &udpw[1];
1050     udpw->msg_size = mlen;
1051     udpw->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1052     udpw->cont = cont;
1053     udpw->cont_cls = cont_cls;
1054     udpw->frag_ctx = NULL;
1055
1056     memcpy (udpw->udp, udp, sizeof (struct UDPMessage));
1057     memcpy (&udpw->udp[sizeof (struct UDPMessage)], msgbuf, msgbuf_size);
1058
1059     enqueue (plugin, udpw);
1060   }
1061   else
1062   {
1063     LOG (GNUNET_ERROR_TYPE_DEBUG,
1064          "UDP has to fragment message \n");
1065     if  (s->frag_ctx != NULL)
1066       return GNUNET_SYSERR;
1067     memcpy (&udp[1], msgbuf, msgbuf_size);
1068     struct FragmentationContext * frag_ctx = GNUNET_malloc(sizeof (struct FragmentationContext));
1069
1070     frag_ctx->plugin = plugin;
1071     frag_ctx->session = s;
1072     frag_ctx->cont = cont;
1073     frag_ctx->cont_cls = cont_cls;
1074     frag_ctx->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1075     frag_ctx->bytes_to_send = mlen;
1076     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
1077               UDP_MTU,
1078               &plugin->tracker,
1079               s->last_expected_delay,
1080               &udp->header,
1081               &enqueue_fragment,
1082               frag_ctx);
1083
1084     s->frag_ctx = frag_ctx;
1085
1086   }
1087
1088   if (s->addrlen == sizeof (struct sockaddr_in))
1089   {
1090     if (plugin->with_v4_ws == GNUNET_NO)
1091     {
1092       if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1093         GNUNET_SCHEDULER_cancel(plugin->select_task);
1094
1095       plugin->select_task =
1096           GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1097                                        GNUNET_TIME_UNIT_FOREVER_REL,
1098                                        plugin->rs_v4,
1099                                        plugin->ws_v4,
1100                                        &udp_plugin_select, plugin);
1101       plugin->with_v4_ws = GNUNET_YES;
1102     }
1103   }
1104
1105   else if (s->addrlen == sizeof (struct sockaddr_in6))
1106   {
1107     if (plugin->with_v6_ws == GNUNET_NO)
1108     {
1109       if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1110         GNUNET_SCHEDULER_cancel(plugin->select_task_v6);
1111
1112       plugin->select_task_v6 =
1113         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1114                                      GNUNET_TIME_UNIT_FOREVER_REL,
1115                                      plugin->rs_v6,
1116                                      plugin->ws_v6,
1117                                      &udp_plugin_select_v6, plugin);
1118       plugin->with_v6_ws = GNUNET_YES;
1119     }
1120   }
1121
1122   return mlen;
1123 }
1124
1125
1126 /**
1127  * Our external IP address/port mapping has changed.
1128  *
1129  * @param cls closure, the 'struct LocalAddrList'
1130  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1131  *     the previous (now invalid) one
1132  * @param addr either the previous or the new public IP address
1133  * @param addrlen actual lenght of the address
1134  */
1135 static void
1136 udp_nat_port_map_callback (void *cls, int add_remove,
1137                            const struct sockaddr *addr, socklen_t addrlen)
1138 {
1139   struct Plugin *plugin = cls;
1140   struct IPv4UdpAddress u4;
1141   struct IPv6UdpAddress u6;
1142   void *arg;
1143   size_t args;
1144
1145   /* convert 'addr' to our internal format */
1146   switch (addr->sa_family)
1147   {
1148   case AF_INET:
1149     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1150     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1151     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1152     arg = &u4;
1153     args = sizeof (u4);
1154     break;
1155   case AF_INET6:
1156     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1157     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1158             sizeof (struct in6_addr));
1159     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1160     arg = &u6;
1161     args = sizeof (u6);
1162     break;
1163   default:
1164     GNUNET_break (0);
1165     return;
1166   }
1167   /* modify our published address list */
1168   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
1169 }
1170
1171
1172
1173 /**
1174  * Message tokenizer has broken up an incomming message. Pass it on
1175  * to the service.
1176  *
1177  * @param cls the 'struct Plugin'
1178  * @param client the 'struct SourceInformation'
1179  * @param hdr the actual message
1180  */
1181 static void
1182 process_inbound_tokenized_messages (void *cls, void *client,
1183                                     const struct GNUNET_MessageHeader *hdr)
1184 {
1185   struct Plugin *plugin = cls;
1186   struct SourceInformation *si = client;
1187   struct GNUNET_ATS_Information ats[2];
1188   struct GNUNET_TIME_Relative delay;
1189
1190   GNUNET_assert (si->session != NULL);
1191   /* setup ATS */
1192   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1193   ats[0].value = htonl (1);
1194   ats[1] = si->session->ats;
1195   GNUNET_break (ntohl(ats[1].value) != GNUNET_ATS_NET_UNSPECIFIED);
1196
1197   delay = plugin->env->receive (plugin->env->cls,
1198                 &si->sender,
1199                 hdr,
1200                 (const struct GNUNET_ATS_Information *) &ats, 2,
1201                 NULL,
1202                 si->arg,
1203                 si->args);
1204   si->session->flow_delay_for_other_peer = delay;
1205 }
1206
1207
1208 /**
1209  * We've received a UDP Message.  Process it (pass contents to main service).
1210  *
1211  * @param plugin plugin context
1212  * @param msg the message
1213  * @param sender_addr sender address
1214  * @param sender_addr_len number of bytes in sender_addr
1215  */
1216 static void
1217 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1218                      const struct sockaddr *sender_addr,
1219                      socklen_t sender_addr_len)
1220 {
1221   struct SourceInformation si;
1222   struct Session * s = NULL;
1223   struct IPv4UdpAddress u4;
1224   struct IPv6UdpAddress u6;
1225   const void *arg;
1226   size_t args;
1227
1228   if (0 != ntohl (msg->reserved))
1229   {
1230     GNUNET_break_op (0);
1231     return;
1232   }
1233   if (ntohs (msg->header.size) <
1234       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
1235   {
1236     GNUNET_break_op (0);
1237     return;
1238   }
1239
1240   /* convert address */
1241   switch (sender_addr->sa_family)
1242   {
1243   case AF_INET:
1244     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
1245     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
1246     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1247     arg = &u4;
1248     args = sizeof (u4);
1249     break;
1250   case AF_INET6:
1251     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
1252     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
1253     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
1254     arg = &u6;
1255     args = sizeof (u6);
1256     break;
1257   default:
1258     GNUNET_break (0);
1259     return;
1260   }
1261 #if DEBUG_UDP
1262   LOG (GNUNET_ERROR_TYPE_DEBUG,
1263        "Received message with %u bytes from peer `%s' at `%s'\n",
1264        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1265        GNUNET_a2s (sender_addr, sender_addr_len));
1266 #endif
1267
1268   struct GNUNET_HELLO_Address * address = GNUNET_HELLO_address_allocate(&msg->sender, "udp", arg, args);
1269   s = udp_plugin_get_session(plugin, address);
1270   GNUNET_free (address);
1271
1272   /* iterate over all embedded messages */
1273   si.session = s;
1274   si.sender = msg->sender;
1275   si.arg = arg;
1276   si.args = args;
1277
1278   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
1279                              ntohs (msg->header.size) -
1280                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
1281 }
1282
1283
1284 /**
1285  * Scan the heap for a receive context with the given address.
1286  *
1287  * @param cls the 'struct FindReceiveContext'
1288  * @param node internal node of the heap
1289  * @param element value stored at the node (a 'struct ReceiveContext')
1290  * @param cost cost associated with the node
1291  * @return GNUNET_YES if we should continue to iterate,
1292  *         GNUNET_NO if not.
1293  */
1294 static int
1295 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1296                       void *element, GNUNET_CONTAINER_HeapCostType cost)
1297 {
1298   struct FindReceiveContext *frc = cls;
1299   struct DefragContext *e = element;
1300
1301   if ((frc->addr_len == e->addr_len) &&
1302       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1303   {
1304     frc->rc = e;
1305     return GNUNET_NO;
1306   }
1307   return GNUNET_YES;
1308 }
1309
1310
1311 /**
1312  * Process a defragmented message.
1313  *
1314  * @param cls the 'struct ReceiveContext'
1315  * @param msg the message
1316  */
1317 static void
1318 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1319 {
1320   struct DefragContext *rc = cls;
1321
1322   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1323   {
1324     GNUNET_break (0);
1325     return;
1326   }
1327   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1328   {
1329     GNUNET_break (0);
1330     return;
1331   }
1332   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1333                        rc->src_addr, rc->addr_len);
1334 }
1335
1336 struct LookupContext
1337 {
1338   const struct sockaddr * addr;
1339   size_t addrlen;
1340
1341   struct Session *res;
1342 };
1343
1344 static int
1345 lookup_session_by_addr_it (void *cls, const GNUNET_HashCode * key, void *value)
1346 {
1347   struct LookupContext *l_ctx = cls;
1348   struct Session * s = value;
1349
1350   if ((s->addrlen == l_ctx->addrlen) &&
1351       (0 == memcmp (s->sock_addr, l_ctx->addr, s->addrlen)))
1352   {
1353     l_ctx->res = s;
1354     return GNUNET_NO;
1355   }
1356   return GNUNET_YES;
1357 }
1358
1359 /**
1360  * Transmit an acknowledgement.
1361  *
1362  * @param cls the 'struct ReceiveContext'
1363  * @param id message ID (unused)
1364  * @param msg ack to transmit
1365  */
1366 static void
1367 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
1368 {
1369   struct DefragContext *rc = cls;
1370
1371   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
1372   struct UDP_ACK_Message *udp_ack;
1373   uint32_t delay = 0;
1374   struct UDPMessageWrapper *udpw;
1375   struct Session *s;
1376
1377   struct LookupContext l_ctx;
1378   l_ctx.addr = rc->src_addr;
1379   l_ctx.addrlen = rc->addr_len;
1380   l_ctx.res = NULL;
1381   GNUNET_CONTAINER_multihashmap_iterate (rc->plugin->sessions,
1382       &lookup_session_by_addr_it,
1383       &l_ctx);
1384   s = l_ctx.res;
1385
1386   if (NULL == s)
1387     return;
1388
1389   if (s->flow_delay_for_other_peer.rel_value <= UINT32_MAX)
1390     delay = s->flow_delay_for_other_peer.rel_value;
1391
1392 #if DEBUG_UDP
1393   LOG (GNUNET_ERROR_TYPE_DEBUG,
1394        "Sending ACK to `%s' including delay of %u ms\n",
1395        GNUNET_a2s (rc->src_addr,
1396                    (rc->src_addr->sa_family ==
1397                     AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct
1398                                                                      sockaddr_in6)),
1399        delay);
1400 #endif
1401   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msize);
1402   udpw->cont = NULL;
1403   udpw->cont_cls = NULL;
1404   udpw->frag_ctx = NULL;
1405   udpw->msg_size = msize;
1406   udpw->session = s;
1407   udpw->timeout = GNUNET_TIME_absolute_get_forever();
1408   udpw->udp = (char *)&udpw[1];
1409
1410   udp_ack = (struct UDP_ACK_Message *) udpw->udp;
1411   udp_ack->header.size = htons ((uint16_t) msize);
1412   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
1413   udp_ack->delay = htonl (delay);
1414   udp_ack->sender = *rc->plugin->env->my_identity;
1415   memcpy (&udp_ack[1], msg, ntohs (msg->size));
1416
1417   enqueue (rc->plugin, udpw);
1418 }
1419
1420
1421 static void read_process_msg (struct Plugin *plugin,
1422     const struct GNUNET_MessageHeader *msg,
1423     char *addr,
1424     socklen_t fromlen)
1425 {
1426   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1427   {
1428     GNUNET_break_op (0);
1429     return;
1430   }
1431   process_udp_message (plugin, (const struct UDPMessage *) msg,
1432                        (const struct sockaddr *) addr, fromlen);
1433   return;
1434 }
1435
1436 static void read_process_ack (struct Plugin *plugin,
1437     const struct GNUNET_MessageHeader *msg,
1438     char *addr,
1439     socklen_t fromlen)
1440 {
1441   const struct GNUNET_MessageHeader *ack;
1442   const struct UDP_ACK_Message *udp_ack;
1443   struct LookupContext l_ctx;
1444   struct Session *s = NULL;
1445   struct GNUNET_TIME_Relative flow_delay;
1446
1447   if (ntohs (msg->size) <
1448       sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
1449   {
1450     GNUNET_break_op (0);
1451     return;
1452   }
1453
1454   udp_ack = (const struct UDP_ACK_Message *) msg;
1455
1456   l_ctx.addr = (const struct sockaddr *) addr;
1457   l_ctx.addrlen = fromlen;
1458   l_ctx.res = NULL;
1459   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
1460       &lookup_session_by_addr_it,
1461       &l_ctx);
1462   s = l_ctx.res;
1463
1464   if ((s == NULL) || (s->frag_ctx == NULL))
1465     return;
1466
1467   flow_delay.rel_value = (uint64_t) ntohl (udp_ack->delay);
1468   LOG (GNUNET_ERROR_TYPE_DEBUG, "We received a sending delay of %llu\n",
1469        flow_delay.rel_value);
1470   s->flow_delay_from_other_peer =
1471       GNUNET_TIME_relative_to_absolute (flow_delay);
1472
1473   ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
1474   if (ntohs (ack->size) !=
1475       ntohs (msg->size) - sizeof (struct UDP_ACK_Message))
1476   {
1477     GNUNET_break_op (0);
1478     return;
1479   }
1480
1481   if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (s->frag_ctx->frag, ack))
1482   {
1483 #if DEBUG_UDP
1484   LOG (GNUNET_ERROR_TYPE_DEBUG,
1485        "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1486        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1487        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1488 #endif
1489     return;
1490   }
1491
1492 #if DEBUG_UDP
1493   LOG (GNUNET_ERROR_TYPE_DEBUG,
1494        "FULL MESSAGE ACKed\n",
1495        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1496        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1497 #endif
1498   s->last_expected_delay = GNUNET_FRAGMENT_context_destroy (s->frag_ctx->frag);
1499
1500   struct UDPMessageWrapper * udpw = NULL;
1501   if (s->addrlen == sizeof (struct sockaddr_in6))
1502   {
1503     udpw = plugin->ipv6_queue_head;
1504     while (udpw!= NULL)
1505     {
1506       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1507       {
1508         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1509         GNUNET_free (udpw);
1510       }
1511       udpw = udpw->next;
1512     }
1513   }
1514   if (s->addrlen == sizeof (struct sockaddr_in))
1515   {
1516     udpw = plugin->ipv4_queue_head;
1517     while (udpw!= NULL)
1518     {
1519       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1520       {
1521         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1522         GNUNET_free (udpw);
1523       }
1524       udpw = udpw->next;
1525     }
1526   }
1527
1528   if (s->frag_ctx->cont != NULL)
1529     s->frag_ctx->cont
1530     (s->frag_ctx->cont_cls, &udp_ack->sender, GNUNET_OK);
1531   GNUNET_free (s->frag_ctx);
1532   s->frag_ctx = NULL;
1533   return;
1534 }
1535
1536 static void read_process_fragment (struct Plugin *plugin,
1537     const struct GNUNET_MessageHeader *msg,
1538     char *addr,
1539     socklen_t fromlen)
1540 {
1541   struct DefragContext *d_ctx;
1542   struct GNUNET_TIME_Absolute now;
1543   struct FindReceiveContext frc;
1544
1545
1546   frc.rc = NULL;
1547   frc.addr = (const struct sockaddr *) addr;
1548   frc.addr_len = fromlen;
1549
1550 #if DEBUG_UDP
1551   LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
1552        (unsigned int) ntohs (msg->size),
1553        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1554 #endif
1555
1556   /* Lookup existing receive context for this address */
1557   GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
1558                                  &find_receive_context,
1559                                  &frc);
1560   now = GNUNET_TIME_absolute_get ();
1561   d_ctx = frc.rc;
1562
1563   if (d_ctx == NULL)
1564   {
1565     /* Create a new defragmentation context */
1566     d_ctx = GNUNET_malloc (sizeof (struct DefragContext) + fromlen);
1567     memcpy (&d_ctx[1], addr, fromlen);
1568     d_ctx->src_addr = (const struct sockaddr *) &d_ctx[1];
1569     d_ctx->addr_len = fromlen;
1570     d_ctx->plugin = plugin;
1571     d_ctx->defrag =
1572         GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1573                                           UDP_MAX_MESSAGES_IN_DEFRAG, d_ctx,
1574                                           &fragment_msg_proc, &ack_proc);
1575     d_ctx->hnode =
1576         GNUNET_CONTAINER_heap_insert (plugin->defrag_ctxs, d_ctx,
1577                                       (GNUNET_CONTAINER_HeapCostType)
1578                                       now.abs_value);
1579 #if DEBUG_UDP
1580   LOG (GNUNET_ERROR_TYPE_DEBUG, "Created new defragmentation context for %u-byte fragment from `%s'\n",
1581        (unsigned int) ntohs (msg->size),
1582        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1583 #endif
1584   }
1585   else
1586   {
1587 #if DEBUG_UDP
1588   LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing defragmentation context for %u-byte fragment from `%s'\n",
1589        (unsigned int) ntohs (msg->size),
1590        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1591 #endif
1592   }
1593
1594   if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (d_ctx->defrag, msg))
1595   {
1596     /* keep this 'rc' from expiring */
1597     GNUNET_CONTAINER_heap_update_cost (plugin->defrag_ctxs, d_ctx->hnode,
1598                                        (GNUNET_CONTAINER_HeapCostType)
1599                                        now.abs_value);
1600   }
1601   if (GNUNET_CONTAINER_heap_get_size (plugin->defrag_ctxs) >
1602       UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1603   {
1604     /* remove 'rc' that was inactive the longest */
1605     d_ctx = GNUNET_CONTAINER_heap_remove_root (plugin->defrag_ctxs);
1606     GNUNET_assert (NULL != d_ctx);
1607     GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
1608     GNUNET_free (d_ctx);
1609   }
1610 }
1611
1612 /**
1613  * Read and process a message from the given socket.
1614  *
1615  * @param plugin the overall plugin
1616  * @param rsock socket to read from
1617  */
1618 static void
1619 udp_select_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
1620 {
1621   socklen_t fromlen;
1622   char addr[32];
1623   char buf[65536];
1624   ssize_t size;
1625   const struct GNUNET_MessageHeader *msg;
1626
1627   fromlen = sizeof (addr);
1628   memset (&addr, 0, sizeof (addr));
1629   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
1630                                       (struct sockaddr *) &addr, &fromlen);
1631
1632   if (size < sizeof (struct GNUNET_MessageHeader))
1633   {
1634     GNUNET_break_op (0);
1635     return;
1636   }
1637   msg = (const struct GNUNET_MessageHeader *) buf;
1638
1639   LOG (GNUNET_ERROR_TYPE_DEBUG,
1640        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) size,
1641        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
1642
1643   if (size != ntohs (msg->size))
1644   {
1645     GNUNET_break_op (0);
1646     return;
1647   }
1648
1649   switch (ntohs (msg->type))
1650   {
1651   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
1652     udp_broadcast_receive (plugin, &buf, size, addr, fromlen);
1653     return;
1654
1655   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
1656     read_process_msg (plugin, msg, addr, fromlen);
1657     return;
1658
1659   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
1660     read_process_ack (plugin, msg, addr, fromlen);;
1661     return;
1662
1663   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1664     read_process_fragment (plugin, msg, addr, fromlen);
1665     return;
1666
1667   default:
1668     GNUNET_break_op (0);
1669     return;
1670   }
1671 }
1672
1673 size_t
1674 udp_select_send (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *sock)
1675 {
1676   ssize_t sent;
1677   size_t slen;
1678   struct GNUNET_TIME_Absolute max;
1679   struct GNUNET_TIME_Absolute ;
1680
1681   struct UDPMessageWrapper *udpw = NULL;
1682
1683   if (sock == plugin->sockv4)
1684   {
1685     udpw = plugin->ipv4_queue_head;
1686   }
1687   else if (sock == plugin->sockv6)
1688   {
1689     udpw = plugin->ipv6_queue_head;
1690   }
1691   else
1692   {
1693     GNUNET_break (0);
1694     return 0;
1695   }
1696
1697   const struct sockaddr * sa = udpw->session->sock_addr;
1698   slen = udpw->session->addrlen;
1699
1700   max = GNUNET_TIME_absolute_max(udpw->timeout, GNUNET_TIME_absolute_get());
1701
1702   while (udpw != NULL)
1703   {
1704     if (max.abs_value != udpw->timeout.abs_value)
1705     {
1706       /* Message timed out */
1707
1708       if (udpw->cont != NULL)
1709         udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1710       if (udpw->frag_ctx != NULL)
1711       {
1712 #if DEBUG_UDP
1713         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Fragmented message for peer `%s' with size %u timed out\n",
1714             GNUNET_i2s(&udpw->session->target), udpw->frag_ctx->bytes_to_send);
1715 #endif
1716         udpw->session->last_expected_delay = GNUNET_FRAGMENT_context_destroy(udpw->frag_ctx->frag);
1717         GNUNET_free (udpw->frag_ctx);
1718         udpw->session->frag_ctx = NULL;
1719       }
1720       else
1721       {
1722 #if DEBUG_UDP
1723         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' with size %u timed out\n",
1724             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1725 #endif
1726       }
1727
1728       if (sock == plugin->sockv4)
1729       {
1730         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1731         GNUNET_free (udpw);
1732         udpw = plugin->ipv4_queue_head;
1733       }
1734       else if (sock == plugin->sockv6)
1735       {
1736         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1737         GNUNET_free (udpw);
1738         udpw = plugin->ipv6_queue_head;
1739       }
1740     }
1741     else
1742     {
1743       struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer);
1744       if (delta.rel_value == 0)
1745       {
1746         /* this message is not delayed */
1747         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is not delayed \n",
1748             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1749         break;
1750       }
1751       else
1752       {
1753         /* this message is delayed, try next */
1754         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is delayed for %llu \n",
1755             GNUNET_i2s(&udpw->session->target), udpw->msg_size,
1756             delta);
1757         udpw = udpw->next;
1758       }
1759     }
1760   }
1761
1762   if (udpw == NULL)
1763   {
1764     /* No message left */
1765     return 0;
1766   }
1767
1768   sent = GNUNET_NETWORK_socket_sendto (sock, udpw->udp, udpw->msg_size, sa, slen);
1769
1770   if (GNUNET_SYSERR == sent)
1771   {
1772     LOG (GNUNET_ERROR_TYPE_ERROR,
1773          "UDP could not transmit %u-byte message to `%s': `%s'\n",
1774          (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen),
1775          STRERROR (errno));
1776     if (udpw->cont != NULL)
1777       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1778   }
1779   else
1780   {
1781     LOG (GNUNET_ERROR_TYPE_DEBUG,
1782          "UDP transmitted %u-byte message to `%s' (%d: %s)\n",
1783          (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
1784          (sent < 0) ? STRERROR (errno) : "ok");
1785   }
1786   /* This was just a message fragment */
1787   if (udpw->frag_ctx != NULL)
1788   {
1789     GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);
1790   }
1791   /* This was a complete message*/
1792   else
1793   {
1794     if (udpw->cont != NULL)
1795       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_OK);
1796   }
1797
1798   if (sock == plugin->sockv4)
1799     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1800   else if (sock == plugin->sockv6)
1801     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1802   GNUNET_free (udpw);
1803   udpw = NULL;
1804
1805   return sent;
1806 }
1807
1808 /**
1809  * We have been notified that our readset has something to read.  We don't
1810  * know which socket needs to be read, so we have to check each one
1811  * Then reschedule this function to be called again once more is available.
1812  *
1813  * @param cls the plugin handle
1814  * @param tc the scheduling context (for rescheduling this function again)
1815  */
1816 static void
1817 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1818 {
1819   struct Plugin *plugin = cls;
1820
1821   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1822   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1823     return;
1824   plugin->with_v4_ws = GNUNET_NO;
1825
1826   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1827   {
1828     if ((NULL != plugin->sockv4) &&
1829       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
1830         udp_select_read (plugin, plugin->sockv4);
1831
1832   }
1833
1834   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1835   {
1836     if ((NULL != plugin->sockv4) && (plugin->ipv4_queue_head != NULL) &&
1837       (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv4)))
1838       {
1839         udp_select_send (plugin, plugin->sockv4);
1840       }
1841   }
1842
1843   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1844     GNUNET_SCHEDULER_cancel (plugin->select_task);
1845   plugin->select_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1846                                    GNUNET_TIME_UNIT_FOREVER_REL,
1847                                    plugin->rs_v4,
1848                                    (plugin->ipv4_queue_head != NULL) ? plugin->ws_v4 : NULL,
1849                                    &udp_plugin_select, plugin);
1850   if (plugin->ipv4_queue_head != NULL)
1851     plugin->with_v4_ws = GNUNET_YES;
1852   else
1853     plugin->with_v4_ws = GNUNET_NO;
1854 }
1855
1856
1857 /**
1858  * We have been notified that our readset has something to read.  We don't
1859  * know which socket needs to be read, so we have to check each one
1860  * Then reschedule this function to be called again once more is available.
1861  *
1862  * @param cls the plugin handle
1863  * @param tc the scheduling context (for rescheduling this function again)
1864  */
1865 static void
1866 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1867 {
1868   struct Plugin *plugin = cls;
1869
1870   plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1871   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1872     return;
1873
1874   plugin->with_v6_ws = GNUNET_NO;
1875   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1876   {
1877     if ((NULL != plugin->sockv6) &&
1878       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
1879         udp_select_read (plugin, plugin->sockv6);
1880   }
1881
1882   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1883   {
1884     if ((NULL != plugin->sockv6) && (plugin->ipv6_queue_head != NULL) &&
1885       (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv6)))
1886       {
1887         udp_select_send (plugin, plugin->sockv6);
1888       }
1889   }
1890   if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1891     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
1892   plugin->select_task_v6 = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1893                                    GNUNET_TIME_UNIT_FOREVER_REL,
1894                                    plugin->rs_v6,
1895                                    (plugin->ipv6_queue_head != NULL) ? plugin->ws_v6 : NULL,
1896                                    &udp_plugin_select_v6, plugin);
1897   if (plugin->ipv6_queue_head != NULL)
1898     plugin->with_v6_ws = GNUNET_YES;
1899   else
1900     plugin->with_v6_ws = GNUNET_NO;
1901 }
1902
1903
1904 static int
1905 setup_sockets (struct Plugin *plugin, struct sockaddr_in6 *serverAddrv6, struct sockaddr_in *serverAddrv4)
1906 {
1907   int tries;
1908   int sockets_created = 0;
1909   struct sockaddr *serverAddr;
1910   struct sockaddr *addrs[2];
1911   socklen_t addrlens[2];
1912   socklen_t addrlen;
1913
1914   /* Create IPv6 socket */
1915   if (plugin->enable_ipv6 == GNUNET_YES)
1916   {
1917     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1918     if (NULL == plugin->sockv6)
1919     {
1920       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Disabling IPv6 since it is not supported on this system!\n");
1921       plugin->enable_ipv6 = GNUNET_NO;
1922     }
1923     else
1924     {
1925 #if HAVE_SOCKADDR_IN_SIN_LEN
1926       serverAddrv6->sin6_len = sizeof (serverAddrv6);
1927 #endif
1928       serverAddrv6->sin6_family = AF_INET6;
1929       serverAddrv6->sin6_addr = in6addr_any;
1930       serverAddrv6->sin6_port = htons (plugin->port);
1931       addrlen = sizeof (struct sockaddr_in6);
1932       serverAddr = (struct sockaddr *) serverAddrv6;
1933 #if DEBUG_UDP
1934       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1935            ntohs (serverAddrv6->sin6_port));
1936 #endif
1937       tries = 0;
1938       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1939              GNUNET_OK)
1940       {
1941         serverAddrv6->sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1942 #if DEBUG_UDP
1943         LOG (GNUNET_ERROR_TYPE_DEBUG,
1944              "IPv6 Binding failed, trying new port %d\n",
1945              ntohs (serverAddrv6->sin6_port));
1946 #endif
1947         tries++;
1948         if (tries > 10)
1949         {
1950           GNUNET_NETWORK_socket_close (plugin->sockv6);
1951           plugin->sockv6 = NULL;
1952           break;
1953         }
1954       }
1955       if (plugin->sockv6 != NULL)
1956       {
1957 #if DEBUG_UDP
1958         LOG (GNUNET_ERROR_TYPE_DEBUG,
1959              "IPv6 socket created on port %d\n",
1960              ntohs (serverAddrv6->sin6_port));
1961 #endif
1962         addrs[sockets_created] = (struct sockaddr *) serverAddrv6;
1963         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
1964         sockets_created++;
1965       }
1966     }
1967   }
1968
1969   /* Create IPv4 socket */
1970   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1971   if (NULL == plugin->sockv4)
1972   {
1973     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1974   }
1975   else
1976   {
1977 #if HAVE_SOCKADDR_IN_SIN_LEN
1978     serverAddrv4->sin_len = sizeof (serverAddrv4);
1979 #endif
1980     serverAddrv4->sin_family = AF_INET;
1981     serverAddrv4->sin_addr.s_addr = INADDR_ANY;
1982     serverAddrv4->sin_port = htons (plugin->port);
1983     addrlen = sizeof (struct sockaddr_in);
1984     serverAddr = (struct sockaddr *) serverAddrv4;
1985
1986 #if DEBUG_UDP
1987     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1988          ntohs (serverAddrv4->sin_port));
1989 #endif
1990     tries = 0;
1991     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1992            GNUNET_OK)
1993     {
1994       serverAddrv4->sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1995 #if DEBUG_UDP
1996       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
1997            ntohs (serverAddrv4->sin_port));
1998 #endif
1999       tries++;
2000       if (tries > 10)
2001       {
2002         GNUNET_NETWORK_socket_close (plugin->sockv4);
2003         plugin->sockv4 = NULL;
2004         break;
2005       }
2006     }
2007     if (plugin->sockv4 != NULL)
2008     {
2009       addrs[sockets_created] = (struct sockaddr *) serverAddrv4;
2010       addrlens[sockets_created] = sizeof (struct sockaddr_in);
2011       sockets_created++;
2012     }
2013   }
2014
2015   /* Create file descriptors */
2016   plugin->rs_v4 = GNUNET_NETWORK_fdset_create ();
2017   plugin->ws_v4 = GNUNET_NETWORK_fdset_create ();
2018   GNUNET_NETWORK_fdset_zero (plugin->rs_v4);
2019   GNUNET_NETWORK_fdset_zero (plugin->ws_v4);
2020   if (NULL != plugin->sockv4)
2021   {
2022     GNUNET_NETWORK_fdset_set (plugin->rs_v4, plugin->sockv4);
2023     GNUNET_NETWORK_fdset_set (plugin->ws_v4, plugin->sockv4);
2024   }
2025
2026   if (sockets_created == 0)
2027     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
2028
2029   plugin->select_task =
2030       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2031                                    GNUNET_TIME_UNIT_FOREVER_REL,
2032                                    plugin->rs_v4,
2033                                    NULL,
2034                                    &udp_plugin_select, plugin);
2035   plugin->with_v4_ws = GNUNET_NO;
2036
2037   if (plugin->enable_ipv6 == GNUNET_YES)
2038   {
2039     plugin->rs_v6 = GNUNET_NETWORK_fdset_create ();
2040     plugin->ws_v6 = GNUNET_NETWORK_fdset_create ();
2041     GNUNET_NETWORK_fdset_zero (plugin->rs_v6);
2042     GNUNET_NETWORK_fdset_zero (plugin->ws_v6);
2043     if (NULL != plugin->sockv6)
2044     {
2045       GNUNET_NETWORK_fdset_set (plugin->rs_v6, plugin->sockv6);
2046       GNUNET_NETWORK_fdset_set (plugin->ws_v6, plugin->sockv6);
2047     }
2048
2049     plugin->select_task_v6 =
2050         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2051                                      GNUNET_TIME_UNIT_FOREVER_REL,
2052                                      plugin->rs_v6,
2053                                      NULL,
2054                                      &udp_plugin_select_v6, plugin);
2055     plugin->with_v6_ws = GNUNET_NO;
2056   }
2057
2058   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2059                            GNUNET_NO, plugin->port,
2060                            sockets_created,
2061                            (const struct sockaddr **) addrs, addrlens,
2062                            &udp_nat_port_map_callback, NULL, plugin);
2063
2064   return sockets_created;
2065 }
2066
2067
2068 /**
2069  * The exported method. Makes the core api available via a global and
2070  * returns the udp transport API.
2071  *
2072  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2073  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
2074  */
2075 void *
2076 libgnunet_plugin_transport_udp_init (void *cls)
2077 {
2078   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2079   struct GNUNET_TRANSPORT_PluginFunctions *api;
2080   struct Plugin *plugin;
2081
2082   unsigned long long port;
2083   unsigned long long aport;
2084   unsigned long long broadcast;
2085   unsigned long long udp_max_bps;
2086   unsigned long long enable_v6;
2087   char * bind4_address;
2088   char * bind6_address;
2089   struct GNUNET_TIME_Relative interval;
2090
2091   struct sockaddr_in serverAddrv4;
2092   struct sockaddr_in6 serverAddrv6;
2093
2094   int res;
2095
2096   if (NULL == env->receive)
2097   {
2098     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2099        initialze the plugin or the API */
2100     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2101     api->cls = NULL;
2102     api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2103     api->address_to_string = &udp_address_to_string;
2104     api->string_to_address = &udp_string_to_address;
2105     return api;
2106   }
2107
2108   /* Get port number */
2109   if (GNUNET_OK !=
2110       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
2111                                              &port))
2112     port = 2086;
2113   if (GNUNET_OK !=
2114       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2115                                              "ADVERTISED_PORT", &aport))
2116     aport = port;
2117   if (port > 65535)
2118   {
2119     LOG (GNUNET_ERROR_TYPE_WARNING,
2120          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
2121          65535);
2122     return NULL;
2123   }
2124
2125   /* Protocols */
2126   if ((GNUNET_YES ==
2127        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
2128                                              "DISABLEV6")))
2129   {
2130     enable_v6 = GNUNET_NO;
2131   }
2132   else
2133     enable_v6 = GNUNET_YES;
2134
2135
2136   /* Addresses */
2137   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
2138   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
2139
2140   if (GNUNET_YES ==
2141       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2142                                              "BINDTO", &bind4_address))
2143   {
2144     LOG (GNUNET_ERROR_TYPE_DEBUG,
2145          "Binding udp plugin to specific address: `%s'\n",
2146          bind4_address);
2147     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
2148     {
2149       GNUNET_free (bind4_address);
2150       return NULL;
2151     }
2152   }
2153
2154   if (GNUNET_YES ==
2155       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2156                                              "BINDTO6", &bind6_address))
2157   {
2158     LOG (GNUNET_ERROR_TYPE_DEBUG,
2159          "Binding udp plugin to specific address: `%s'\n",
2160          bind6_address);
2161     if (1 !=
2162         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
2163     {
2164       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
2165            bind6_address);
2166       GNUNET_free_non_null (bind4_address);
2167       GNUNET_free (bind6_address);
2168       return NULL;
2169     }
2170   }
2171
2172
2173   /* Enable neighbour discovery */
2174   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
2175                                             "BROADCAST");
2176   if (broadcast == GNUNET_SYSERR)
2177     broadcast = GNUNET_NO;
2178
2179   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-udp",
2180                                            "BROADCAST_INTERVAL", &interval))
2181   {
2182     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
2183   }
2184
2185   /* Maximum datarate */
2186   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2187                                              "MAX_BPS", &udp_max_bps))
2188   {
2189     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
2190   }
2191
2192   plugin = GNUNET_malloc (sizeof (struct Plugin));
2193   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2194
2195   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
2196                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
2197
2198
2199   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
2200   plugin->defrag_ctxs = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2201   plugin->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
2202   plugin->port = port;
2203   plugin->aport = aport;
2204   plugin->broadcast_interval = interval;
2205   plugin->enable_ipv6 = enable_v6;
2206   plugin->env = env;
2207
2208   api->cls = plugin;
2209   api->send = NULL;
2210   api->disconnect = &udp_disconnect;
2211   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2212   api->address_to_string = &udp_address_to_string;
2213   api->string_to_address = &udp_string_to_address;
2214   api->check_address = &udp_plugin_check_address;
2215   api->get_session = &udp_plugin_get_session;
2216   api->send = &udp_plugin_send;
2217
2218   LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
2219   res = setup_sockets (plugin, &serverAddrv6, &serverAddrv4);
2220   if ((res == 0) || ((plugin->sockv4 == NULL) && (plugin->sockv6 == NULL)))
2221   {
2222     LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to create network sockets, plugin failed\n");
2223     GNUNET_free (plugin);
2224     GNUNET_free (api);
2225     return NULL;
2226   }
2227
2228   LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting broadcasting\n");
2229   if (broadcast == GNUNET_YES)
2230     setup_broadcast (plugin, &serverAddrv6, &serverAddrv4);
2231
2232
2233   GNUNET_free_non_null (bind4_address);
2234   GNUNET_free_non_null (bind6_address);
2235   return api;
2236 }
2237
2238
2239 static int
2240 heap_cleanup_iterator (void *cls,
2241                        struct GNUNET_CONTAINER_HeapNode *
2242                        node, void *element,
2243                        GNUNET_CONTAINER_HeapCostType
2244                        cost)
2245 {
2246   struct DefragContext * d_ctx = element;
2247
2248   GNUNET_CONTAINER_heap_remove_node (node);
2249   GNUNET_DEFRAGMENT_context_destroy(d_ctx->defrag);
2250   GNUNET_free (d_ctx);
2251
2252   return GNUNET_YES;
2253 }
2254
2255
2256 /**
2257  * The exported method. Makes the core api available via a global and
2258  * returns the udp transport API.
2259  *
2260  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2261  * @return NULL
2262  */
2263 void *
2264 libgnunet_plugin_transport_udp_done (void *cls)
2265 {
2266   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2267   struct Plugin *plugin = api->cls;
2268
2269   if (NULL == plugin)
2270   {
2271     GNUNET_free (api);
2272     return NULL;
2273   }
2274
2275   stop_broadcast (plugin);
2276
2277   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
2278   {
2279     GNUNET_SCHEDULER_cancel (plugin->select_task);
2280     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2281   }
2282   if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2283   {
2284     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
2285     plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2286   }
2287
2288   /* Closing sockets */
2289   if (plugin->sockv4 != NULL)
2290   {
2291     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
2292     plugin->sockv4 = NULL;
2293   }
2294   GNUNET_NETWORK_fdset_destroy (plugin->rs_v4);
2295   GNUNET_NETWORK_fdset_destroy (plugin->ws_v4);
2296
2297   if (plugin->sockv6 != NULL)
2298   {
2299     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
2300     plugin->sockv6 = NULL;
2301
2302     GNUNET_NETWORK_fdset_destroy (plugin->rs_v6);
2303     GNUNET_NETWORK_fdset_destroy (plugin->ws_v6);
2304   }
2305
2306   GNUNET_NAT_unregister (plugin->nat);
2307
2308   if (plugin->defrag_ctxs != NULL)
2309   {
2310     GNUNET_CONTAINER_heap_iterate(plugin->defrag_ctxs,
2311         heap_cleanup_iterator, NULL);
2312     GNUNET_CONTAINER_heap_destroy(plugin->defrag_ctxs);
2313     plugin->defrag_ctxs = NULL;
2314   }
2315   if (plugin->mst != NULL)
2316   {
2317     GNUNET_SERVER_mst_destroy(plugin->mst);
2318     plugin->mst = NULL;
2319   }
2320
2321   /* Clean up leftover messages */
2322   struct UDPMessageWrapper * udpw;
2323   udpw = plugin->ipv4_queue_head;
2324   while (udpw != NULL)
2325   {
2326     struct UDPMessageWrapper *tmp = udpw->next;
2327     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
2328     if (udpw->cont != NULL)
2329       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
2330     GNUNET_free (udpw);
2331     udpw = tmp;
2332   }
2333   udpw = plugin->ipv6_queue_head;
2334   while (udpw != NULL)
2335   {
2336     struct UDPMessageWrapper *tmp = udpw->next;
2337     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
2338     if (udpw->cont != NULL)
2339       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
2340     GNUNET_free (udpw);
2341     udpw = tmp;
2342   }
2343
2344   /* Clean up sessions */
2345 #if DEBUG_UDP
2346   LOG (GNUNET_ERROR_TYPE_DEBUG,
2347        "Cleaning up sessions\n");
2348 #endif
2349   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
2350   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
2351
2352   plugin->nat = NULL;
2353   GNUNET_free (plugin);
2354   GNUNET_free (api);
2355   return NULL;
2356 }
2357
2358
2359 /* end of plugin_transport_udp.c */