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