4f422cfa05cac8e9534a7f3b56c8af4dc4681d68
[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_SCHEDULER_NO_TASK,
940                                        GNUNET_TIME_UNIT_FOREVER_REL,
941                                        plugin->rs_v4,
942                                        plugin->ws_v4,
943                                        &udp_plugin_select, plugin);
944       plugin->with_v4_ws = GNUNET_YES;
945     }
946   }
947
948   else if (s->addrlen == sizeof (struct sockaddr_in6))
949   {
950     if (plugin->with_v6_ws == GNUNET_NO)
951     {
952       if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
953         GNUNET_SCHEDULER_cancel(plugin->select_task_v6);
954
955       plugin->select_task_v6 =
956           GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
957                                        GNUNET_SCHEDULER_NO_TASK,
958                                        GNUNET_TIME_UNIT_FOREVER_REL,
959                                        plugin->rs_v6,
960                                        plugin->ws_v6,
961                                        &udp_plugin_select_v6, plugin);
962       plugin->with_v6_ws = GNUNET_YES;
963     }
964   }
965
966 }
967
968
969
970
971 /**
972  * Function that can be used by the transport service to transmit
973  * a message using the plugin.   Note that in the case of a
974  * peer disconnecting, the continuation MUST be called
975  * prior to the disconnect notification itself.  This function
976  * will be called with this peer's HELLO message to initiate
977  * a fresh connection to another peer.
978  *
979  * @param cls closure
980  * @param s which session must be used
981  * @param msgbuf the message to transmit
982  * @param msgbuf_size number of bytes in 'msgbuf'
983  * @param priority how important is the message (most plugins will
984  *                 ignore message priority and just FIFO)
985  * @param to how long to wait at most for the transmission (does not
986  *                require plugins to discard the message after the timeout,
987  *                just advisory for the desired delay; most plugins will ignore
988  *                this as well)
989  * @param cont continuation to call once the message has
990  *        been transmitted (or if the transport is ready
991  *        for the next transmission call; or if the
992  *        peer disconnected...); can be NULL
993  * @param cont_cls closure for cont
994  * @return number of bytes used (on the physical network, with overheads);
995  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
996  *         and does NOT mean that the message was not transmitted (DV)
997  */
998 static ssize_t
999 udp_plugin_send (void *cls,
1000                   struct Session *s,
1001                   const char *msgbuf, size_t msgbuf_size,
1002                   unsigned int priority,
1003                   struct GNUNET_TIME_Relative to,
1004                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1005 {
1006   struct Plugin *plugin = cls;
1007   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
1008
1009   struct UDPMessageWrapper * udpw;
1010   struct UDPMessage *udp;
1011   char mbuf[mlen];
1012   GNUNET_assert (plugin != NULL);
1013   GNUNET_assert (s != NULL);
1014
1015   if ((s->addrlen == sizeof (struct sockaddr_in6)) && (plugin->sockv6 == NULL))
1016     return GNUNET_SYSERR;
1017
1018    if ((s->addrlen == sizeof (struct sockaddr_in)) && (plugin->sockv4 == NULL))
1019      return GNUNET_SYSERR;
1020
1021
1022   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1023   {
1024     GNUNET_break (0);
1025     return GNUNET_SYSERR;
1026   }
1027
1028   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessions, &s->target.hashPubKey, s))
1029   {
1030     GNUNET_break (0);
1031     return GNUNET_SYSERR;
1032   }
1033
1034   LOG (GNUNET_ERROR_TYPE_DEBUG,
1035        "UDP transmits %u-byte message to `%s' using address `%s'\n",
1036          msgbuf_size,
1037          GNUNET_i2s (&s->target),
1038          GNUNET_a2s(s->sock_addr, s->addrlen));
1039
1040   /* Message */
1041   udp = (struct UDPMessage *) mbuf;
1042   udp->header.size = htons (mlen);
1043   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
1044   udp->reserved = htonl (0);
1045   udp->sender = *plugin->env->my_identity;
1046
1047   if (mlen <= UDP_MTU)
1048   {
1049     udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + mlen);
1050     udpw->session = s;
1051     udpw->udp = (char *) &udpw[1];
1052     udpw->msg_size = mlen;
1053     udpw->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1054     udpw->cont = cont;
1055     udpw->cont_cls = cont_cls;
1056     udpw->frag_ctx = NULL;
1057
1058     memcpy (udpw->udp, udp, sizeof (struct UDPMessage));
1059     memcpy (&udpw->udp[sizeof (struct UDPMessage)], msgbuf, msgbuf_size);
1060
1061     enqueue (plugin, udpw);
1062   }
1063   else
1064   {
1065     LOG (GNUNET_ERROR_TYPE_DEBUG,
1066          "UDP has to fragment message \n");
1067     if  (s->frag_ctx != NULL)
1068       return GNUNET_SYSERR;
1069     memcpy (&udp[1], msgbuf, msgbuf_size);
1070     struct FragmentationContext * frag_ctx = GNUNET_malloc(sizeof (struct FragmentationContext));
1071
1072     frag_ctx->plugin = plugin;
1073     frag_ctx->session = s;
1074     frag_ctx->cont = cont;
1075     frag_ctx->cont_cls = cont_cls;
1076     frag_ctx->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1077     frag_ctx->bytes_to_send = mlen;
1078     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
1079               UDP_MTU,
1080               &plugin->tracker,
1081               s->last_expected_delay,
1082               &udp->header,
1083               &enqueue_fragment,
1084               frag_ctx);
1085
1086     s->frag_ctx = frag_ctx;
1087
1088   }
1089
1090   if (s->addrlen == sizeof (struct sockaddr_in))
1091   {
1092     if (plugin->with_v4_ws == GNUNET_NO)
1093     {
1094       if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1095         GNUNET_SCHEDULER_cancel(plugin->select_task);
1096
1097       plugin->select_task =
1098           GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1099                                        GNUNET_SCHEDULER_NO_TASK,
1100                                        GNUNET_TIME_UNIT_FOREVER_REL,
1101                                        plugin->rs_v4,
1102                                        plugin->ws_v4,
1103                                        &udp_plugin_select, plugin);
1104       plugin->with_v4_ws = GNUNET_YES;
1105     }
1106   }
1107
1108   else if (s->addrlen == sizeof (struct sockaddr_in6))
1109   {
1110     if (plugin->with_v6_ws == GNUNET_NO)
1111     {
1112       if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1113         GNUNET_SCHEDULER_cancel(plugin->select_task_v6);
1114
1115       plugin->select_task_v6 =
1116         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1117                                      GNUNET_SCHEDULER_NO_TASK,
1118                                      GNUNET_TIME_UNIT_FOREVER_REL,
1119                                      plugin->rs_v6,
1120                                      plugin->ws_v6,
1121                                      &udp_plugin_select_v6, plugin);
1122       plugin->with_v6_ws = GNUNET_YES;
1123     }
1124   }
1125
1126   return mlen;
1127 }
1128
1129
1130 /**
1131  * Our external IP address/port mapping has changed.
1132  *
1133  * @param cls closure, the 'struct LocalAddrList'
1134  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1135  *     the previous (now invalid) one
1136  * @param addr either the previous or the new public IP address
1137  * @param addrlen actual lenght of the address
1138  */
1139 static void
1140 udp_nat_port_map_callback (void *cls, int add_remove,
1141                            const struct sockaddr *addr, socklen_t addrlen)
1142 {
1143   struct Plugin *plugin = cls;
1144   struct IPv4UdpAddress u4;
1145   struct IPv6UdpAddress u6;
1146   void *arg;
1147   size_t args;
1148
1149   /* convert 'addr' to our internal format */
1150   switch (addr->sa_family)
1151   {
1152   case AF_INET:
1153     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1154     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1155     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1156     arg = &u4;
1157     args = sizeof (u4);
1158     break;
1159   case AF_INET6:
1160     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1161     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1162             sizeof (struct in6_addr));
1163     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1164     arg = &u6;
1165     args = sizeof (u6);
1166     break;
1167   default:
1168     GNUNET_break (0);
1169     return;
1170   }
1171   /* modify our published address list */
1172   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
1173 }
1174
1175
1176
1177 /**
1178  * Message tokenizer has broken up an incomming message. Pass it on
1179  * to the service.
1180  *
1181  * @param cls the 'struct Plugin'
1182  * @param client the 'struct SourceInformation'
1183  * @param hdr the actual message
1184  */
1185 static void
1186 process_inbound_tokenized_messages (void *cls, void *client,
1187                                     const struct GNUNET_MessageHeader *hdr)
1188 {
1189   struct Plugin *plugin = cls;
1190   struct SourceInformation *si = client;
1191   struct GNUNET_ATS_Information ats[2];
1192   struct GNUNET_TIME_Relative delay;
1193
1194   GNUNET_assert (si->session != NULL);
1195   /* setup ATS */
1196   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1197   ats[0].value = htonl (1);
1198   ats[1] = si->session->ats;
1199   GNUNET_break (ntohl(ats[1].value) != GNUNET_ATS_NET_UNSPECIFIED);
1200
1201   delay = plugin->env->receive (plugin->env->cls,
1202                 &si->sender,
1203                 hdr,
1204                 (const struct GNUNET_ATS_Information *) &ats, 2,
1205                 NULL,
1206                 si->arg,
1207                 si->args);
1208   si->session->flow_delay_for_other_peer = delay;
1209 }
1210
1211
1212 /**
1213  * We've received a UDP Message.  Process it (pass contents to main service).
1214  *
1215  * @param plugin plugin context
1216  * @param msg the message
1217  * @param sender_addr sender address
1218  * @param sender_addr_len number of bytes in sender_addr
1219  */
1220 static void
1221 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1222                      const struct sockaddr *sender_addr,
1223                      socklen_t sender_addr_len)
1224 {
1225   struct SourceInformation si;
1226   struct Session * s = NULL;
1227   struct IPv4UdpAddress u4;
1228   struct IPv6UdpAddress u6;
1229   const void *arg;
1230   size_t args;
1231
1232   if (0 != ntohl (msg->reserved))
1233   {
1234     GNUNET_break_op (0);
1235     return;
1236   }
1237   if (ntohs (msg->header.size) <
1238       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
1239   {
1240     GNUNET_break_op (0);
1241     return;
1242   }
1243
1244   /* convert address */
1245   switch (sender_addr->sa_family)
1246   {
1247   case AF_INET:
1248     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
1249     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
1250     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1251     arg = &u4;
1252     args = sizeof (u4);
1253     break;
1254   case AF_INET6:
1255     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
1256     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
1257     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
1258     arg = &u6;
1259     args = sizeof (u6);
1260     break;
1261   default:
1262     GNUNET_break (0);
1263     return;
1264   }
1265 #if DEBUG_UDP
1266   LOG (GNUNET_ERROR_TYPE_DEBUG,
1267        "Received message with %u bytes from peer `%s' at `%s'\n",
1268        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1269        GNUNET_a2s (sender_addr, sender_addr_len));
1270 #endif
1271
1272   struct GNUNET_HELLO_Address * address = GNUNET_HELLO_address_allocate(&msg->sender, "udp", arg, args);
1273   s = udp_plugin_get_session(plugin, address);
1274   GNUNET_free (address);
1275
1276   /* iterate over all embedded messages */
1277   si.session = s;
1278   si.sender = msg->sender;
1279   si.arg = arg;
1280   si.args = args;
1281
1282   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
1283                              ntohs (msg->header.size) -
1284                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
1285 }
1286
1287
1288 /**
1289  * Scan the heap for a receive context with the given address.
1290  *
1291  * @param cls the 'struct FindReceiveContext'
1292  * @param node internal node of the heap
1293  * @param element value stored at the node (a 'struct ReceiveContext')
1294  * @param cost cost associated with the node
1295  * @return GNUNET_YES if we should continue to iterate,
1296  *         GNUNET_NO if not.
1297  */
1298 static int
1299 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1300                       void *element, GNUNET_CONTAINER_HeapCostType cost)
1301 {
1302   struct FindReceiveContext *frc = cls;
1303   struct DefragContext *e = element;
1304
1305   if ((frc->addr_len == e->addr_len) &&
1306       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1307   {
1308     frc->rc = e;
1309     return GNUNET_NO;
1310   }
1311   return GNUNET_YES;
1312 }
1313
1314
1315 /**
1316  * Process a defragmented message.
1317  *
1318  * @param cls the 'struct ReceiveContext'
1319  * @param msg the message
1320  */
1321 static void
1322 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1323 {
1324   struct DefragContext *rc = cls;
1325
1326   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1327   {
1328     GNUNET_break (0);
1329     return;
1330   }
1331   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1332   {
1333     GNUNET_break (0);
1334     return;
1335   }
1336   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1337                        rc->src_addr, rc->addr_len);
1338 }
1339
1340 struct LookupContext
1341 {
1342   const struct sockaddr * addr;
1343   size_t addrlen;
1344
1345   struct Session *res;
1346 };
1347
1348 static int
1349 lookup_session_by_addr_it (void *cls, const GNUNET_HashCode * key, void *value)
1350 {
1351   struct LookupContext *l_ctx = cls;
1352   struct Session * s = value;
1353
1354   if ((s->addrlen == l_ctx->addrlen) &&
1355       (0 == memcmp (s->sock_addr, l_ctx->addr, s->addrlen)))
1356   {
1357     l_ctx->res = s;
1358     return GNUNET_NO;
1359   }
1360   return GNUNET_YES;
1361 }
1362
1363 /**
1364  * Transmit an acknowledgement.
1365  *
1366  * @param cls the 'struct ReceiveContext'
1367  * @param id message ID (unused)
1368  * @param msg ack to transmit
1369  */
1370 static void
1371 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
1372 {
1373   struct DefragContext *rc = cls;
1374
1375   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
1376   struct UDP_ACK_Message *udp_ack;
1377   uint32_t delay = 0;
1378   struct UDPMessageWrapper *udpw;
1379   struct Session *s;
1380
1381   struct LookupContext l_ctx;
1382   l_ctx.addr = rc->src_addr;
1383   l_ctx.addrlen = rc->addr_len;
1384   l_ctx.res = NULL;
1385   GNUNET_CONTAINER_multihashmap_iterate (rc->plugin->sessions,
1386       &lookup_session_by_addr_it,
1387       &l_ctx);
1388   s = l_ctx.res;
1389
1390   GNUNET_assert (s != NULL);
1391
1392   if (s->flow_delay_for_other_peer.rel_value <= UINT32_MAX)
1393     delay = s->flow_delay_for_other_peer.rel_value;
1394
1395 #if DEBUG_UDP
1396   LOG (GNUNET_ERROR_TYPE_DEBUG,
1397        "Sending ACK to `%s' including delay of %u ms\n",
1398        GNUNET_a2s (rc->src_addr,
1399                    (rc->src_addr->sa_family ==
1400                     AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct
1401                                                                      sockaddr_in6)),
1402        delay);
1403 #endif
1404   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msize);
1405   udpw->cont = NULL;
1406   udpw->cont_cls = NULL;
1407   udpw->frag_ctx = NULL;
1408   udpw->msg_size = msize;
1409   udpw->session = s;
1410   udpw->timeout = GNUNET_TIME_absolute_get_forever();
1411   udpw->udp = (char *)&udpw[1];
1412
1413   udp_ack = (struct UDP_ACK_Message *) udpw->udp;
1414   udp_ack->header.size = htons ((uint16_t) msize);
1415   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
1416   udp_ack->delay = htonl (delay);
1417   udp_ack->sender = *rc->plugin->env->my_identity;
1418   memcpy (&udp_ack[1], msg, ntohs (msg->size));
1419
1420   enqueue (rc->plugin, udpw);
1421 }
1422
1423
1424 static void read_process_msg (struct Plugin *plugin,
1425     const struct GNUNET_MessageHeader *msg,
1426     char *addr,
1427     socklen_t fromlen)
1428 {
1429   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1430   {
1431     GNUNET_break_op (0);
1432     return;
1433   }
1434   process_udp_message (plugin, (const struct UDPMessage *) msg,
1435                        (const struct sockaddr *) addr, fromlen);
1436   return;
1437 }
1438
1439 static void read_process_ack (struct Plugin *plugin,
1440     const struct GNUNET_MessageHeader *msg,
1441     char *addr,
1442     socklen_t fromlen)
1443 {
1444   const struct GNUNET_MessageHeader *ack;
1445   const struct UDP_ACK_Message *udp_ack;
1446   struct LookupContext l_ctx;
1447   struct Session *s = NULL;
1448   struct GNUNET_TIME_Relative flow_delay;
1449
1450   if (ntohs (msg->size) <
1451       sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
1452   {
1453     GNUNET_break_op (0);
1454     return;
1455   }
1456
1457   udp_ack = (const struct UDP_ACK_Message *) msg;
1458
1459   l_ctx.addr = (const struct sockaddr *) addr;
1460   l_ctx.addrlen = fromlen;
1461   l_ctx.res = NULL;
1462   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
1463       &lookup_session_by_addr_it,
1464       &l_ctx);
1465   s = l_ctx.res;
1466
1467   if ((s == NULL) || (s->frag_ctx == NULL))
1468     return;
1469
1470   flow_delay.rel_value = (uint64_t) ntohl (udp_ack->delay);
1471   LOG (GNUNET_ERROR_TYPE_DEBUG, "We received a sending delay of %llu\n",
1472        flow_delay.rel_value);
1473   s->flow_delay_from_other_peer =
1474       GNUNET_TIME_relative_to_absolute (flow_delay);
1475
1476   ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
1477   if (ntohs (ack->size) !=
1478       ntohs (msg->size) - sizeof (struct UDP_ACK_Message))
1479   {
1480     GNUNET_break_op (0);
1481     return;
1482   }
1483
1484   if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (s->frag_ctx->frag, ack))
1485   {
1486 #if DEBUG_UDP
1487   LOG (GNUNET_ERROR_TYPE_DEBUG,
1488        "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1489        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1490        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1491 #endif
1492     return;
1493   }
1494
1495 #if DEBUG_UDP
1496   LOG (GNUNET_ERROR_TYPE_DEBUG,
1497        "FULL MESSAGE ACKed\n",
1498        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1499        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1500 #endif
1501   s->last_expected_delay = GNUNET_FRAGMENT_context_destroy (s->frag_ctx->frag);
1502
1503   struct UDPMessageWrapper * udpw = NULL;
1504   if (s->addrlen == sizeof (struct sockaddr_in6))
1505   {
1506     udpw = plugin->ipv6_queue_head;
1507     while (udpw!= NULL)
1508     {
1509       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1510       {
1511         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1512         GNUNET_free (udpw);
1513       }
1514       udpw = udpw->next;
1515     }
1516   }
1517   if (s->addrlen == sizeof (struct sockaddr_in))
1518   {
1519     udpw = plugin->ipv4_queue_head;
1520     while (udpw!= NULL)
1521     {
1522       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1523       {
1524         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1525         GNUNET_free (udpw);
1526       }
1527       udpw = udpw->next;
1528     }
1529   }
1530
1531   if (s->frag_ctx->cont != NULL)
1532     s->frag_ctx->cont
1533     (s->frag_ctx->cont_cls, &udp_ack->sender, GNUNET_OK);
1534   GNUNET_free (s->frag_ctx);
1535   s->frag_ctx = NULL;
1536   return;
1537 }
1538
1539 static void read_process_fragment (struct Plugin *plugin,
1540     const struct GNUNET_MessageHeader *msg,
1541     char *addr,
1542     socklen_t fromlen)
1543 {
1544   struct DefragContext *d_ctx;
1545   struct GNUNET_TIME_Absolute now;
1546   struct FindReceiveContext frc;
1547
1548
1549   frc.rc = NULL;
1550   frc.addr = (const struct sockaddr *) addr;
1551   frc.addr_len = fromlen;
1552
1553 #if DEBUG_UDP
1554   LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
1555        (unsigned int) ntohs (msg->size),
1556        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1557 #endif
1558
1559   /* Lookup existing receive context for this address */
1560   GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
1561                                  &find_receive_context,
1562                                  &frc);
1563   now = GNUNET_TIME_absolute_get ();
1564   d_ctx = frc.rc;
1565
1566   if (d_ctx == NULL)
1567   {
1568     /* Create a new defragmentation context */
1569     d_ctx = GNUNET_malloc (sizeof (struct DefragContext) + fromlen);
1570     memcpy (&d_ctx[1], addr, fromlen);
1571     d_ctx->src_addr = (const struct sockaddr *) &d_ctx[1];
1572     d_ctx->addr_len = fromlen;
1573     d_ctx->plugin = plugin;
1574     d_ctx->defrag =
1575         GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1576                                           UDP_MAX_MESSAGES_IN_DEFRAG, d_ctx,
1577                                           &fragment_msg_proc, &ack_proc);
1578     d_ctx->hnode =
1579         GNUNET_CONTAINER_heap_insert (plugin->defrag_ctxs, d_ctx,
1580                                       (GNUNET_CONTAINER_HeapCostType)
1581                                       now.abs_value);
1582 #if DEBUG_UDP
1583   LOG (GNUNET_ERROR_TYPE_DEBUG, "Created new defragmentation context for %u-byte fragment from `%s'\n",
1584        (unsigned int) ntohs (msg->size),
1585        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1586 #endif
1587   }
1588   else
1589   {
1590 #if DEBUG_UDP
1591   LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing defragmentation context for %u-byte fragment from `%s'\n",
1592        (unsigned int) ntohs (msg->size),
1593        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1594 #endif
1595   }
1596
1597   if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (d_ctx->defrag, msg))
1598   {
1599     /* keep this 'rc' from expiring */
1600     GNUNET_CONTAINER_heap_update_cost (plugin->defrag_ctxs, d_ctx->hnode,
1601                                        (GNUNET_CONTAINER_HeapCostType)
1602                                        now.abs_value);
1603   }
1604   if (GNUNET_CONTAINER_heap_get_size (plugin->defrag_ctxs) >
1605       UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1606   {
1607     /* remove 'rc' that was inactive the longest */
1608     d_ctx = GNUNET_CONTAINER_heap_remove_root (plugin->defrag_ctxs);
1609     GNUNET_assert (NULL != d_ctx);
1610     GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
1611     GNUNET_free (d_ctx);
1612   }
1613 }
1614
1615 /**
1616  * Read and process a message from the given socket.
1617  *
1618  * @param plugin the overall plugin
1619  * @param rsock socket to read from
1620  */
1621 static void
1622 udp_select_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
1623 {
1624   socklen_t fromlen;
1625   char addr[32];
1626   char buf[65536];
1627   ssize_t size;
1628   const struct GNUNET_MessageHeader *msg;
1629
1630   fromlen = sizeof (addr);
1631   memset (&addr, 0, sizeof (addr));
1632   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
1633                                       (struct sockaddr *) &addr, &fromlen);
1634
1635   if (size < sizeof (struct GNUNET_MessageHeader))
1636   {
1637     GNUNET_break_op (0);
1638     return;
1639   }
1640   msg = (const struct GNUNET_MessageHeader *) buf;
1641
1642   LOG (GNUNET_ERROR_TYPE_DEBUG,
1643        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) size,
1644        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
1645
1646   if (size != ntohs (msg->size))
1647   {
1648     GNUNET_break_op (0);
1649     return;
1650   }
1651
1652   switch (ntohs (msg->type))
1653   {
1654   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
1655     udp_broadcast_receive (plugin, &buf, size, addr, fromlen);
1656     return;
1657
1658   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
1659     read_process_msg (plugin, msg, addr, fromlen);
1660     return;
1661
1662   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
1663     read_process_ack (plugin, msg, addr, fromlen);;
1664     return;
1665
1666   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1667     read_process_fragment (plugin, msg, addr, fromlen);
1668     return;
1669
1670   default:
1671     GNUNET_break_op (0);
1672     return;
1673   }
1674 }
1675
1676 size_t
1677 udp_select_send (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *sock)
1678 {
1679   ssize_t sent;
1680   size_t slen;
1681   struct GNUNET_TIME_Absolute max;
1682   struct GNUNET_TIME_Absolute ;
1683
1684   struct UDPMessageWrapper *udpw = NULL;
1685
1686   if (sock == plugin->sockv4)
1687   {
1688     udpw = plugin->ipv4_queue_head;
1689   }
1690   else if (sock == plugin->sockv6)
1691   {
1692     udpw = plugin->ipv6_queue_head;
1693   }
1694   else
1695   {
1696     GNUNET_break (0);
1697     return 0;
1698   }
1699
1700   const struct sockaddr * sa = udpw->session->sock_addr;
1701   slen = udpw->session->addrlen;
1702
1703   max = GNUNET_TIME_absolute_max(udpw->timeout, GNUNET_TIME_absolute_get());
1704
1705   while (udpw != NULL)
1706   {
1707     if (max.abs_value != udpw->timeout.abs_value)
1708     {
1709       /* Message timed out */
1710
1711       if (udpw->cont != NULL)
1712         udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1713       if (udpw->frag_ctx != NULL)
1714       {
1715 #if DEBUG_UDP
1716         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Fragmented message for peer `%s' with size %u timed out\n",
1717             GNUNET_i2s(&udpw->session->target), udpw->frag_ctx->bytes_to_send);
1718 #endif
1719         udpw->session->last_expected_delay = GNUNET_FRAGMENT_context_destroy(udpw->frag_ctx->frag);
1720         GNUNET_free (udpw->frag_ctx);
1721         udpw->session->frag_ctx = NULL;
1722       }
1723       else
1724       {
1725 #if DEBUG_UDP
1726         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' with size %u timed out\n",
1727             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1728 #endif
1729       }
1730
1731       if (sock == plugin->sockv4)
1732       {
1733         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1734         GNUNET_free (udpw);
1735         udpw = plugin->ipv4_queue_head;
1736       }
1737       else if (sock == plugin->sockv6)
1738       {
1739         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1740         GNUNET_free (udpw);
1741         udpw = plugin->ipv6_queue_head;
1742       }
1743     }
1744     else
1745     {
1746       struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer);
1747       if (delta.rel_value == 0)
1748       {
1749         /* this message is not delayed */
1750         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is not delayed \n",
1751             GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1752         break;
1753       }
1754       else
1755       {
1756         /* this message is delayed, try next */
1757         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message for peer `%s' (%u bytes) is delayed for %llu \n",
1758             GNUNET_i2s(&udpw->session->target), udpw->msg_size,
1759             delta);
1760         udpw = udpw->next;
1761       }
1762     }
1763
1764   }
1765
1766   if (udpw == NULL)
1767   {
1768     /* No message left */
1769     return 0;
1770   }
1771
1772   sent = GNUNET_NETWORK_socket_sendto (sock, udpw->udp, udpw->msg_size, sa, slen);
1773
1774   if (GNUNET_SYSERR == sent)
1775   {
1776     LOG (GNUNET_ERROR_TYPE_ERROR,
1777          "UDP could not transmit %u-byte message to `%s': `%s'\n",
1778          (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen),
1779          STRERROR (errno));
1780     if (udpw->cont != NULL)
1781       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
1782   }
1783   LOG (GNUNET_ERROR_TYPE_DEBUG,
1784        "UDP transmitted %u-byte message to `%s' (%d: %s)\n",
1785        (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen), (int) sent,
1786        (sent < 0) ? STRERROR (errno) : "ok");
1787
1788   /* This was just a message fragment */
1789   if (udpw->frag_ctx != NULL)
1790   {
1791     GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);
1792   }
1793   /* This was a complete message*/
1794   else
1795   {
1796     if (udpw->cont != NULL)
1797       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_OK);
1798   }
1799
1800   if (sock == plugin->sockv4)
1801     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1802   else if (sock == plugin->sockv6)
1803     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1804   GNUNET_free (udpw);
1805   udpw = NULL;
1806
1807   return sent;
1808 }
1809
1810 /**
1811  * We have been notified that our readset has something to read.  We don't
1812  * know which socket needs to be read, so we have to check each one
1813  * Then reschedule this function to be called again once more is available.
1814  *
1815  * @param cls the plugin handle
1816  * @param tc the scheduling context (for rescheduling this function again)
1817  */
1818 static void
1819 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1820 {
1821   struct Plugin *plugin = cls;
1822
1823   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1824   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1825     return;
1826   plugin->with_v4_ws = GNUNET_NO;
1827
1828   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1829   {
1830     if ((NULL != plugin->sockv4) &&
1831       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
1832         udp_select_read (plugin, plugin->sockv4);
1833
1834   }
1835
1836   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1837   {
1838     if ((NULL != plugin->sockv4) && (plugin->ipv4_queue_head != NULL) &&
1839       (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv4)))
1840       {
1841         udp_select_send (plugin, plugin->sockv4);
1842       }
1843   }
1844
1845   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1846     GNUNET_SCHEDULER_cancel (plugin->select_task);
1847   plugin->select_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1848                                    GNUNET_SCHEDULER_NO_TASK,
1849                                    GNUNET_TIME_UNIT_FOREVER_REL,
1850                                    plugin->rs_v4,
1851                                    (plugin->ipv4_queue_head != NULL) ? plugin->ws_v4 : NULL,
1852                                    &udp_plugin_select, plugin);
1853   if (plugin->ipv4_queue_head != NULL)
1854     plugin->with_v4_ws = GNUNET_YES;
1855   else
1856     plugin->with_v4_ws = GNUNET_NO;
1857 }
1858
1859
1860 /**
1861  * We have been notified that our readset has something to read.  We don't
1862  * know which socket needs to be read, so we have to check each one
1863  * Then reschedule this function to be called again once more is available.
1864  *
1865  * @param cls the plugin handle
1866  * @param tc the scheduling context (for rescheduling this function again)
1867  */
1868 static void
1869 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1870 {
1871   struct Plugin *plugin = cls;
1872
1873   plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1874   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1875     return;
1876
1877   plugin->with_v6_ws = GNUNET_NO;
1878   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1879   {
1880     if ((NULL != plugin->sockv6) &&
1881       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
1882         udp_select_read (plugin, plugin->sockv6);
1883   }
1884
1885   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1886   {
1887     if ((NULL != plugin->sockv6) && (plugin->ipv6_queue_head != NULL) &&
1888       (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv6)))
1889       {
1890         udp_select_send (plugin, plugin->sockv6);
1891       }
1892   }
1893   if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1894     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
1895   plugin->select_task_v6 = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1896                                    GNUNET_SCHEDULER_NO_TASK,
1897                                    GNUNET_TIME_UNIT_FOREVER_REL,
1898                                    plugin->rs_v6,
1899                                    (plugin->ipv6_queue_head != NULL) ? plugin->ws_v6 : NULL,
1900                                    &udp_plugin_select_v6, plugin);
1901   if (plugin->ipv6_queue_head != NULL)
1902     plugin->with_v6_ws = GNUNET_YES;
1903   else
1904     plugin->with_v6_ws = GNUNET_NO;
1905 }
1906
1907
1908 static int
1909 setup_sockets (struct Plugin *plugin, struct sockaddr_in6 *serverAddrv6, struct sockaddr_in *serverAddrv4)
1910 {
1911   int tries;
1912   int sockets_created = 0;
1913   struct sockaddr *serverAddr;
1914   struct sockaddr *addrs[2];
1915   socklen_t addrlens[2];
1916   socklen_t addrlen;
1917
1918   /* Create IPv6 socket */
1919   if (plugin->enable_ipv6 == GNUNET_YES)
1920   {
1921     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1922     if (NULL == plugin->sockv6)
1923     {
1924       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Disabling IPv6 since it is not supported on this system!\n");
1925       plugin->enable_ipv6 = GNUNET_NO;
1926     }
1927     else
1928     {
1929 #if HAVE_SOCKADDR_IN_SIN_LEN
1930       serverAddrv6->sin6_len = sizeof (serverAddrv6);
1931 #endif
1932       serverAddrv6->sin6_family = AF_INET6;
1933       serverAddrv6->sin6_addr = in6addr_any;
1934       serverAddrv6->sin6_port = htons (plugin->port);
1935       addrlen = sizeof (struct sockaddr_in6);
1936       serverAddr = (struct sockaddr *) serverAddrv6;
1937 #if DEBUG_UDP
1938       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1939            ntohs (serverAddrv6->sin6_port));
1940 #endif
1941       tries = 0;
1942       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1943              GNUNET_OK)
1944       {
1945         serverAddrv6->sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1946 #if DEBUG_UDP
1947         LOG (GNUNET_ERROR_TYPE_DEBUG,
1948              "IPv6 Binding failed, trying new port %d\n",
1949              ntohs (serverAddrv6->sin6_port));
1950 #endif
1951         tries++;
1952         if (tries > 10)
1953         {
1954           GNUNET_NETWORK_socket_close (plugin->sockv6);
1955           plugin->sockv6 = NULL;
1956           break;
1957         }
1958       }
1959       if (plugin->sockv6 != NULL)
1960       {
1961 #if DEBUG_UDP
1962         LOG (GNUNET_ERROR_TYPE_DEBUG,
1963              "IPv6 socket created on port %d\n",
1964              ntohs (serverAddrv6->sin6_port));
1965 #endif
1966         addrs[sockets_created] = (struct sockaddr *) serverAddrv6;
1967         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
1968         sockets_created++;
1969       }
1970     }
1971   }
1972
1973   /* Create IPv4 socket */
1974   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1975   if (NULL == plugin->sockv4)
1976   {
1977     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1978   }
1979   else
1980   {
1981 #if HAVE_SOCKADDR_IN_SIN_LEN
1982     serverAddrv4->sin_len = sizeof (serverAddrv4);
1983 #endif
1984     serverAddrv4->sin_family = AF_INET;
1985     serverAddrv4->sin_addr.s_addr = INADDR_ANY;
1986     serverAddrv4->sin_port = htons (plugin->port);
1987     addrlen = sizeof (struct sockaddr_in);
1988     serverAddr = (struct sockaddr *) serverAddrv4;
1989
1990 #if DEBUG_UDP
1991     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1992          ntohs (serverAddrv4->sin_port));
1993 #endif
1994     tries = 0;
1995     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1996            GNUNET_OK)
1997     {
1998       serverAddrv4->sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1999 #if DEBUG_UDP
2000       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
2001            ntohs (serverAddrv4->sin_port));
2002 #endif
2003       tries++;
2004       if (tries > 10)
2005       {
2006         GNUNET_NETWORK_socket_close (plugin->sockv4);
2007         plugin->sockv4 = NULL;
2008         break;
2009       }
2010     }
2011     if (plugin->sockv4 != NULL)
2012     {
2013       addrs[sockets_created] = (struct sockaddr *) serverAddrv4;
2014       addrlens[sockets_created] = sizeof (struct sockaddr_in);
2015       sockets_created++;
2016     }
2017   }
2018
2019   /* Create file descriptors */
2020   plugin->rs_v4 = GNUNET_NETWORK_fdset_create ();
2021   plugin->ws_v4 = GNUNET_NETWORK_fdset_create ();
2022   GNUNET_NETWORK_fdset_zero (plugin->rs_v4);
2023   GNUNET_NETWORK_fdset_zero (plugin->ws_v4);
2024   if (NULL != plugin->sockv4)
2025   {
2026     GNUNET_NETWORK_fdset_set (plugin->rs_v4, plugin->sockv4);
2027     GNUNET_NETWORK_fdset_set (plugin->ws_v4, plugin->sockv4);
2028   }
2029
2030   if (sockets_created == 0)
2031     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
2032
2033   plugin->select_task =
2034       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2035                                    GNUNET_SCHEDULER_NO_TASK,
2036                                    GNUNET_TIME_UNIT_FOREVER_REL,
2037                                    plugin->rs_v4,
2038                                    NULL,
2039                                    &udp_plugin_select, plugin);
2040   plugin->with_v4_ws = GNUNET_NO;
2041
2042   if (plugin->enable_ipv6 == GNUNET_YES)
2043   {
2044     plugin->rs_v6 = GNUNET_NETWORK_fdset_create ();
2045     plugin->ws_v6 = GNUNET_NETWORK_fdset_create ();
2046     GNUNET_NETWORK_fdset_zero (plugin->rs_v6);
2047     GNUNET_NETWORK_fdset_zero (plugin->ws_v6);
2048     if (NULL != plugin->sockv6)
2049     {
2050       GNUNET_NETWORK_fdset_set (plugin->rs_v6, plugin->sockv6);
2051       GNUNET_NETWORK_fdset_set (plugin->ws_v6, plugin->sockv6);
2052     }
2053
2054     plugin->select_task_v6 =
2055         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2056                                      GNUNET_SCHEDULER_NO_TASK,
2057                                      GNUNET_TIME_UNIT_FOREVER_REL,
2058                                      plugin->rs_v6,
2059                                      NULL,
2060                                      &udp_plugin_select_v6, plugin);
2061     plugin->with_v6_ws = GNUNET_NO;
2062   }
2063
2064   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2065                            GNUNET_NO, plugin->port,
2066                            sockets_created,
2067                            (const struct sockaddr **) addrs, addrlens,
2068                            &udp_nat_port_map_callback, NULL, plugin);
2069
2070   return sockets_created;
2071 }
2072
2073
2074 /**
2075  * The exported method. Makes the core api available via a global and
2076  * returns the udp transport API.
2077  *
2078  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2079  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
2080  */
2081 void *
2082 libgnunet_plugin_transport_udp_init (void *cls)
2083 {
2084   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2085   struct GNUNET_TRANSPORT_PluginFunctions *api;
2086   struct Plugin *plugin;
2087
2088   unsigned long long port;
2089   unsigned long long aport;
2090   unsigned long long broadcast;
2091   unsigned long long udp_max_bps;
2092   unsigned long long enable_v6;
2093   char * bind4_address;
2094   char * bind6_address;
2095   struct GNUNET_TIME_Relative interval;
2096
2097   struct sockaddr_in serverAddrv4;
2098   struct sockaddr_in6 serverAddrv6;
2099
2100   int res;
2101
2102   if (NULL == env->receive)
2103   {
2104     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2105        initialze the plugin or the API */
2106     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2107     api->cls = NULL;
2108     api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2109     api->address_to_string = &udp_address_to_string;
2110     api->string_to_address = &udp_string_to_address;
2111     return api;
2112   }
2113
2114   /* Get port number */
2115   if (GNUNET_OK !=
2116       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
2117                                              &port))
2118     port = 2086;
2119   if (GNUNET_OK !=
2120       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2121                                              "ADVERTISED_PORT", &aport))
2122     aport = port;
2123   if (port > 65535)
2124   {
2125     LOG (GNUNET_ERROR_TYPE_WARNING,
2126          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
2127          65535);
2128     return NULL;
2129   }
2130
2131   /* Protocols */
2132   if ((GNUNET_YES ==
2133        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
2134                                              "DISABLEV6")))
2135   {
2136     enable_v6 = GNUNET_NO;
2137   }
2138   else
2139     enable_v6 = GNUNET_YES;
2140
2141
2142   /* Addresses */
2143   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
2144   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
2145
2146   if (GNUNET_YES ==
2147       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2148                                              "BINDTO", &bind4_address))
2149   {
2150     LOG (GNUNET_ERROR_TYPE_DEBUG,
2151          "Binding udp plugin to specific address: `%s'\n",
2152          bind4_address);
2153     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
2154     {
2155       GNUNET_free (bind4_address);
2156       return NULL;
2157     }
2158   }
2159
2160   if (GNUNET_YES ==
2161       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2162                                              "BINDTO6", &bind6_address))
2163   {
2164     LOG (GNUNET_ERROR_TYPE_DEBUG,
2165          "Binding udp plugin to specific address: `%s'\n",
2166          bind6_address);
2167     if (1 !=
2168         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
2169     {
2170       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
2171            bind6_address);
2172       GNUNET_free_non_null (bind4_address);
2173       GNUNET_free (bind6_address);
2174       return NULL;
2175     }
2176   }
2177
2178
2179   /* Enable neighbour discovery */
2180   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
2181                                             "BROADCAST");
2182   if (broadcast == GNUNET_SYSERR)
2183     broadcast = GNUNET_NO;
2184
2185   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-udp",
2186                                            "BROADCAST_INTERVAL", &interval))
2187   {
2188     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
2189   }
2190
2191   /* Maximum datarate */
2192   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2193                                              "MAX_BPS", &udp_max_bps))
2194   {
2195     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
2196   }
2197
2198   plugin = GNUNET_malloc (sizeof (struct Plugin));
2199   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2200
2201   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
2202                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
2203
2204
2205   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
2206   plugin->defrag_ctxs = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2207   plugin->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
2208   plugin->port = port;
2209   plugin->aport = aport;
2210   plugin->broadcast_interval = interval;
2211   plugin->enable_ipv6 = enable_v6;
2212   plugin->env = env;
2213
2214   api->cls = plugin;
2215   api->send = NULL;
2216   api->disconnect = &udp_disconnect;
2217   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2218   api->address_to_string = &udp_address_to_string;
2219   api->string_to_address = &udp_string_to_address;
2220   api->check_address = &udp_plugin_check_address;
2221   api->get_session = &udp_plugin_get_session;
2222   api->send = &udp_plugin_send;
2223
2224   LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
2225   res = setup_sockets (plugin, &serverAddrv6, &serverAddrv4);
2226   if ((res == 0) || ((plugin->sockv4 == NULL) && (plugin->sockv6 == NULL)))
2227   {
2228     LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to create network sockets, plugin failed\n");
2229     GNUNET_free (plugin);
2230     GNUNET_free (api);
2231     return NULL;
2232   }
2233
2234   LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting broadcasting\n");
2235   if (broadcast == GNUNET_YES)
2236     setup_broadcast (plugin, &serverAddrv6, &serverAddrv4);
2237
2238
2239   GNUNET_free_non_null (bind4_address);
2240   GNUNET_free_non_null (bind6_address);
2241   return api;
2242 }
2243
2244
2245 static int
2246 heap_cleanup_iterator (void *cls,
2247                        struct GNUNET_CONTAINER_HeapNode *
2248                        node, void *element,
2249                        GNUNET_CONTAINER_HeapCostType
2250                        cost)
2251 {
2252   struct DefragContext * d_ctx = element;
2253
2254   GNUNET_CONTAINER_heap_remove_node (node);
2255   GNUNET_DEFRAGMENT_context_destroy(d_ctx->defrag);
2256   GNUNET_free (d_ctx);
2257
2258   return GNUNET_YES;
2259 }
2260
2261
2262 /**
2263  * The exported method. Makes the core api available via a global and
2264  * returns the udp transport API.
2265  *
2266  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2267  * @return NULL
2268  */
2269 void *
2270 libgnunet_plugin_transport_udp_done (void *cls)
2271 {
2272   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2273   struct Plugin *plugin = api->cls;
2274
2275   if (NULL == plugin)
2276   {
2277     GNUNET_free (api);
2278     return NULL;
2279   }
2280
2281   stop_broadcast (plugin);
2282
2283   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
2284   {
2285     GNUNET_SCHEDULER_cancel (plugin->select_task);
2286     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2287   }
2288   if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2289   {
2290     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
2291     plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2292   }
2293
2294   /* Closing sockets */
2295   if (plugin->sockv4 != NULL)
2296   {
2297     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
2298     plugin->sockv4 = NULL;
2299   }
2300   GNUNET_NETWORK_fdset_destroy (plugin->rs_v4);
2301   GNUNET_NETWORK_fdset_destroy (plugin->ws_v4);
2302
2303   if (plugin->sockv6 != NULL)
2304   {
2305     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
2306     plugin->sockv6 = NULL;
2307
2308     GNUNET_NETWORK_fdset_destroy (plugin->rs_v6);
2309     GNUNET_NETWORK_fdset_destroy (plugin->ws_v6);
2310   }
2311
2312   GNUNET_NAT_unregister (plugin->nat);
2313
2314   if (plugin->defrag_ctxs != NULL)
2315   {
2316     GNUNET_CONTAINER_heap_iterate(plugin->defrag_ctxs,
2317         heap_cleanup_iterator, NULL);
2318     GNUNET_CONTAINER_heap_destroy(plugin->defrag_ctxs);
2319     plugin->defrag_ctxs = NULL;
2320   }
2321   if (plugin->mst != NULL)
2322   {
2323     GNUNET_SERVER_mst_destroy(plugin->mst);
2324     plugin->mst = NULL;
2325   }
2326
2327   /* Clean up leftover messages */
2328   struct UDPMessageWrapper * udpw;
2329   udpw = plugin->ipv4_queue_head;
2330   while (udpw != NULL)
2331   {
2332     struct UDPMessageWrapper *tmp = udpw->next;
2333     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
2334     if (udpw->cont != NULL)
2335       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
2336     GNUNET_free (udpw);
2337     udpw = tmp;
2338   }
2339   udpw = plugin->ipv6_queue_head;
2340   while (udpw != NULL)
2341   {
2342     struct UDPMessageWrapper *tmp = udpw->next;
2343     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
2344     if (udpw->cont != NULL)
2345       udpw->cont (udpw->cont_cls, &udpw->session->target, GNUNET_SYSERR);
2346     GNUNET_free (udpw);
2347     udpw = tmp;
2348   }
2349
2350   /* Clean up sessions */
2351 #if DEBUG_UDP
2352   LOG (GNUNET_ERROR_TYPE_DEBUG,
2353        "Cleaning up sessions\n");
2354 #endif
2355   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
2356   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
2357
2358   plugin->nat = NULL;
2359   GNUNET_free (plugin);
2360   GNUNET_free (api);
2361   return NULL;
2362 }
2363
2364
2365 /* end of plugin_transport_udp.c */