fix for printing address
[oweals/gnunet.git] / src / transport / plugin_transport_udp.c
1 /*
2  This file is part of GNUnet
3  (C) 2010-2013 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 #define UDP_SESSION_TIME_OUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
46
47 /**
48  * Number of messages we can defragment in parallel.  We only really
49  * defragment 1 message at a time, but if messages get re-ordered, we
50  * may want to keep knowledge about the previous message to avoid
51  * discarding the current message in favor of a single fragment of a
52  * previous message.  3 should be good since we don't expect massive
53  * message reorderings with UDP.
54  */
55 #define UDP_MAX_MESSAGES_IN_DEFRAG 3
56
57 /**
58  * We keep a defragmentation queue per sender address.  How many
59  * sender addresses do we support at the same time? Memory consumption
60  * is roughly a factor of 32k * UDP_MAX_MESSAGES_IN_DEFRAG times this
61  * value. (So 128 corresponds to 12 MB and should suffice for
62  * connecting to roughly 128 peers via UDP).
63  */
64 #define UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG 128
65
66 /**
67  * Running pretty printers: head
68  */
69 static struct PrettyPrinterContext *ppc_dll_head;
70
71 /**
72  * Running pretty printers: tail
73  */
74 static struct PrettyPrinterContext *ppc_dll_tail;
75
76 /**
77  * Closure for 'append_port'.
78  */
79 struct PrettyPrinterContext
80 {
81   /**
82    * DLL
83    */
84   struct PrettyPrinterContext *next;
85
86   /**
87    * DLL
88    */
89   struct PrettyPrinterContext *prev;
90
91   /**
92    * Timeout task
93    */
94   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
95
96   /**
97    * Resolver handle
98    */
99   struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
100
101   /**
102    * Function to call with the result.
103    */
104   GNUNET_TRANSPORT_AddressStringCallback asc;
105
106   /**
107    * Clsoure for 'asc'.
108    */
109   void *asc_cls;
110
111   /**
112    * Port to add after the IP address.
113    */
114   uint16_t port;
115
116   /**
117    * IPv6 address
118    */
119
120   int ipv6;
121
122   /**
123    * Options
124    */
125   uint32_t options;
126 };
127
128 enum UDP_MessageType
129 {
130   UNDEFINED = 0,
131   MSG_FRAGMENTED = 1,
132   MSG_FRAGMENTED_COMPLETE = 2,
133   MSG_UNFRAGMENTED = 3,
134   MSG_ACK = 4,
135   MSG_BEACON = 5
136 };
137
138 struct Session
139 {
140   /**
141    * Which peer is this session for?
142    */
143   struct GNUNET_PeerIdentity target;
144
145   /**
146    * Plugin this session belongs to.
147    */
148   struct Plugin *plugin;
149
150   /**
151    * Context for dealing with fragments.
152    */
153   struct UDP_FragmentationContext *frag_ctx;
154
155   /**
156    * Desired delay for next sending we send to other peer
157    */
158   struct GNUNET_TIME_Relative flow_delay_for_other_peer;
159
160   /**
161    * Desired delay for next sending we received from other peer
162    */
163   struct GNUNET_TIME_Absolute flow_delay_from_other_peer;
164
165   /**
166    * Session timeout task
167    */
168   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
169
170   /**
171    * expected delay for ACKs
172    */
173   struct GNUNET_TIME_Relative last_expected_ack_delay;
174
175   /**
176    * desired delay between UDP messages
177    */
178   struct GNUNET_TIME_Relative last_expected_msg_delay;
179
180   struct GNUNET_ATS_Information ats;
181
182   struct GNUNET_HELLO_Address *address;
183
184   /**
185    * Reference counter to indicate that this session is
186    * currently being used and must not be destroyed;
187    * setting @e in_destroy will destroy it as soon as
188    * possible.
189    */
190   unsigned int rc;
191
192   /**
193    * Is this session about to be destroyed (sometimes we cannot
194    * destroy a session immediately as below us on the stack
195    * there might be code that still uses it; in this case,
196    * @e rc is non-zero).
197    */
198   int in_destroy;
199 };
200
201 /**
202  * Closure for #session_cmp_it().
203  */
204 struct SessionCompareContext
205 {
206   struct Session *res;
207   const struct GNUNET_HELLO_Address *address;
208 };
209
210 /**
211  * Closure for #process_inbound_tokenized_messages().
212  */
213 struct SourceInformation
214 {
215   /**
216    * Sender identity.
217    */
218   struct GNUNET_PeerIdentity sender;
219
220   /**
221    * Source address.
222    */
223   const void *arg;
224
225   /**
226    * Associated session.
227    */
228   struct Session *session;
229
230   /**
231    * Number of bytes in source address.
232    */
233   size_t args;
234
235 };
236
237 /**
238  * Closure for #find_receive_context().
239  */
240 struct FindReceiveContext
241 {
242   /**
243    * Where to store the result.
244    */
245   struct DefragContext *rc;
246
247   /**
248    * Address to find.
249    */
250   const struct sockaddr *addr;
251
252   struct Session *session;
253
254   /**
255    * Number of bytes in @e addr.
256    */
257   socklen_t addr_len;
258
259 };
260
261 /**
262  * Data structure to track defragmentation contexts based
263  * on the source of the UDP traffic.
264  */
265 struct DefragContext
266 {
267
268   /**
269    * Defragmentation context.
270    */
271   struct GNUNET_DEFRAGMENT_Context *defrag;
272
273   /**
274    * Source address this receive context is for (allocated at the
275    * end of the struct).
276    */
277   const struct sockaddr *src_addr;
278
279   /**
280    * Reference to master plugin struct.
281    */
282   struct Plugin *plugin;
283
284   /**
285    * Node in the defrag heap.
286    */
287   struct GNUNET_CONTAINER_HeapNode *hnode;
288
289   /**
290    * Length of 'src_addr'
291    */
292   size_t addr_len;
293 };
294
295 /**
296  * Context to send fragmented messages
297  */
298 struct UDP_FragmentationContext
299 {
300   /**
301    * Next in linked list
302    */
303   struct UDP_FragmentationContext *next;
304
305   /**
306    * Previous in linked list
307    */
308   struct UDP_FragmentationContext *prev;
309
310   /**
311    * The plugin
312    */
313   struct Plugin *plugin;
314
315   /**
316    * Handle for GNUNET_FRAGMENT context
317    */
318   struct GNUNET_FRAGMENT_Context *frag;
319
320   /**
321    * The session this fragmentation context belongs to
322    */
323   struct Session *session;
324
325   /**
326    * Function to call upon completion of the transmission.
327    */
328   GNUNET_TRANSPORT_TransmitContinuation cont;
329
330   /**
331    * Closure for @e cont.
332    */
333   void *cont_cls;
334
335   /**
336    * Message timeout
337    */
338   struct GNUNET_TIME_Absolute timeout;
339
340   /**
341    * Payload size of original unfragmented message
342    */
343   size_t payload_size;
344
345   /**
346    * Bytes used to send all fragments on wire including UDP overhead
347    */
348   size_t on_wire_size;
349
350   unsigned int fragments_used;
351
352 };
353
354 struct UDP_MessageWrapper
355 {
356   /**
357    * Session this message belongs to
358    */
359   struct Session *session;
360
361   /**
362    * DLL of messages
363    * previous element
364    */
365   struct UDP_MessageWrapper *prev;
366
367   /**
368    * DLL of messages
369    * previous element
370    */
371   struct UDP_MessageWrapper *next;
372
373   /**
374    * Message type
375    * According to UDP_MessageType
376    */
377   int msg_type;
378
379   /**
380    * Message with size msg_size including UDP specific overhead
381    */
382   char *msg_buf;
383
384   /**
385    * Size of UDP message to send including UDP specific overhead
386    */
387   size_t msg_size;
388
389   /**
390    * Payload size of original message
391    */
392   size_t payload_size;
393
394   /**
395    * Message timeout
396    */
397   struct GNUNET_TIME_Absolute timeout;
398
399   /**
400    * Function to call upon completion of the transmission.
401    */
402   GNUNET_TRANSPORT_TransmitContinuation cont;
403
404   /**
405    * Closure for 'cont'.
406    */
407   void *cont_cls;
408
409   /**
410    * Fragmentation context
411    * frag_ctx == NULL if transport <= MTU
412    * frag_ctx != NULL if transport > MTU
413    */
414   struct UDP_FragmentationContext *frag_ctx;
415 };
416
417 /**
418  * UDP ACK Message-Packet header (after defragmentation).
419  */
420 struct UDP_ACK_Message
421 {
422   /**
423    * Message header.
424    */
425   struct GNUNET_MessageHeader header;
426
427   /**
428    * Desired delay for flow control
429    */
430   uint32_t delay;
431
432   /**
433    * What is the identity of the sender
434    */
435   struct GNUNET_PeerIdentity sender;
436
437 };
438
439 /**
440  * Address options
441  */
442 static uint32_t myoptions;
443
444 /**
445  * Encapsulation of all of the state of the plugin.
446  */
447 struct Plugin * plugin;
448
449 /**
450  * We have been notified that our readset has something to read.  We don't
451  * know which socket needs to be read, so we have to check each one
452  * Then reschedule this function to be called again once more is available.
453  *
454  * @param cls the plugin handle
455  * @param tc the scheduling context (for rescheduling this function again)
456  */
457 static void
458 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
459
460 /**
461  * We have been notified that our readset has something to read.  We don't
462  * know which socket needs to be read, so we have to check each one
463  * Then reschedule this function to be called again once more is available.
464  *
465  * @param cls the plugin handle
466  * @param tc the scheduling context (for rescheduling this function again)
467  */
468 static void
469 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
470
471 /**
472  * (re)schedule select tasks for this plugin.
473  *
474  * @param plugin plugin to reschedule
475  */
476 static void
477 schedule_select (struct Plugin *plugin)
478 {
479   struct GNUNET_TIME_Relative min_delay;
480   struct UDP_MessageWrapper *udpw;
481
482   if ((GNUNET_YES == plugin->enable_ipv4) && (NULL != plugin->sockv4))
483   {
484     /* Find a message ready to send:
485      * Flow delay from other peer is expired or not set (0) */
486     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
487     for (udpw = plugin->ipv4_queue_head; NULL != udpw; udpw = udpw->next)
488       min_delay = GNUNET_TIME_relative_min (min_delay,
489           GNUNET_TIME_absolute_get_remaining (
490               udpw->session->flow_delay_from_other_peer));
491
492     if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK )
493       GNUNET_SCHEDULER_cancel (plugin->select_task);
494
495     /* Schedule with:
496      * - write active set if message is ready
497      * - timeout minimum delay */
498     plugin->select_task = GNUNET_SCHEDULER_add_select (
499         GNUNET_SCHEDULER_PRIORITY_DEFAULT,
500         (0 == min_delay.rel_value_us) ?
501             GNUNET_TIME_UNIT_FOREVER_REL : min_delay, plugin->rs_v4,
502         (0 == min_delay.rel_value_us) ? plugin->ws_v4 : NULL,
503         &udp_plugin_select, plugin);
504   }
505   if ((GNUNET_YES == plugin->enable_ipv6) && (NULL != plugin->sockv6))
506   {
507     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
508     for (udpw = plugin->ipv6_queue_head; NULL != udpw; udpw = udpw->next)
509       min_delay = GNUNET_TIME_relative_min (min_delay,
510           GNUNET_TIME_absolute_get_remaining (
511               udpw->session->flow_delay_from_other_peer));
512
513     if (GNUNET_SCHEDULER_NO_TASK != plugin->select_task_v6)
514       GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
515     plugin->select_task_v6 = GNUNET_SCHEDULER_add_select (
516         GNUNET_SCHEDULER_PRIORITY_DEFAULT,
517         (0 == min_delay.rel_value_us) ?
518             GNUNET_TIME_UNIT_FOREVER_REL : min_delay, plugin->rs_v6,
519         (0 == min_delay.rel_value_us) ? plugin->ws_v6 : NULL,
520         &udp_plugin_select_v6, plugin);
521   }
522 }
523
524 /**
525  * Function called for a quick conversion of the binary address to
526  * a numeric address.  Note that the caller must not free the
527  * address and that the next call to this function is allowed
528  * to override the address again.
529  *
530  * @param cls closure
531  * @param addr binary address
532  * @param addrlen length of the address
533  * @return string representing the same address
534  */
535 const char *
536 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
537 {
538   static char rbuf[INET6_ADDRSTRLEN + 10];
539   char buf[INET6_ADDRSTRLEN];
540   const void *sb;
541   struct in_addr a4;
542   struct in6_addr a6;
543   const struct IPv4UdpAddress *t4;
544   const struct IPv6UdpAddress *t6;
545   int af;
546   uint16_t port;
547   uint32_t options;
548
549   if ((NULL != addr) && (addrlen == sizeof(struct IPv6UdpAddress)))
550   {
551     t6 = addr;
552     af = AF_INET6;
553     options = ntohl (t6->options);
554     port = ntohs (t6->u6_port);
555     memcpy (&a6, &t6->ipv6_addr, sizeof(a6));
556     sb = &a6;
557   }
558   else if ((NULL != addr) && (addrlen == sizeof(struct IPv4UdpAddress)))
559   {
560     t4 = addr;
561     af = AF_INET;
562     options = ntohl (t4->options);
563     port = ntohs (t4->u4_port);
564     memcpy (&a4, &t4->ipv4_addr, sizeof(a4));
565     sb = &a4;
566   }
567   else
568   {
569     return NULL ;
570   }
571   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
572
573   GNUNET_snprintf (rbuf, sizeof(rbuf),
574       (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u", PLUGIN_NAME, options,
575       buf, port);
576   return rbuf;
577 }
578
579 /**
580  * Function called to convert a string address to
581  * a binary address.
582  *
583  * @param cls closure ('struct Plugin*')
584  * @param addr string address
585  * @param addrlen length of the address
586  * @param buf location to store the buffer
587  * @param added location to store the number of bytes in the buffer.
588  *        If the function returns GNUNET_SYSERR, its contents are undefined.
589  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
590  */
591 static int
592 udp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
593     void **buf, size_t *added)
594 {
595   struct sockaddr_storage socket_address;
596   char *address;
597   char *plugin;
598   char *optionstr;
599   uint32_t options;
600
601   /* Format tcp.options.address:port */
602   address = NULL;
603   plugin = NULL;
604   optionstr = NULL;
605
606   if ((NULL == addr) || (addrlen == 0))
607   {
608     GNUNET_break(0);
609     return GNUNET_SYSERR;
610   }
611   if ('\0' != addr[addrlen - 1])
612   {
613     GNUNET_break(0);
614     return GNUNET_SYSERR;
615   }
616   if (strlen (addr) != addrlen - 1)
617   {
618     GNUNET_break(0);
619     return GNUNET_SYSERR;
620   }
621   plugin = GNUNET_strdup (addr);
622   optionstr = strchr (plugin, '.');
623   if (NULL == optionstr)
624   {
625     GNUNET_break(0);
626     GNUNET_free(plugin);
627     return GNUNET_SYSERR;
628   }
629   optionstr[0] = '\0';
630   optionstr++;
631   options = atol (optionstr);
632   address = strchr (optionstr, '.');
633   if (NULL == address)
634   {
635     GNUNET_break(0);
636     GNUNET_free(plugin);
637     return GNUNET_SYSERR;
638   }
639   address[0] = '\0';
640   address++;
641
642   if (GNUNET_OK
643       != GNUNET_STRINGS_to_address_ip (address, strlen (address),
644           &socket_address))
645   {
646     GNUNET_break(0);
647     GNUNET_free(plugin);
648     return GNUNET_SYSERR;
649   }
650
651   GNUNET_free(plugin);
652
653   switch (socket_address.ss_family)
654   {
655   case AF_INET:
656   {
657     struct IPv4UdpAddress *u4;
658     struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
659     u4 = GNUNET_new (struct IPv4UdpAddress);
660     u4->options = htonl (options);
661     u4->ipv4_addr = in4->sin_addr.s_addr;
662     u4->u4_port = in4->sin_port;
663     *buf = u4;
664     *added = sizeof(struct IPv4UdpAddress);
665     return GNUNET_OK;
666   }
667   case AF_INET6:
668   {
669     struct IPv6UdpAddress *u6;
670     struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
671     u6 = GNUNET_new (struct IPv6UdpAddress);
672     u6->options = htonl (options);
673     u6->ipv6_addr = in6->sin6_addr;
674     u6->u6_port = in6->sin6_port;
675     *buf = u6;
676     *added = sizeof(struct IPv6UdpAddress);
677     return GNUNET_OK;
678   }
679   default:
680     GNUNET_break(0);
681     return GNUNET_SYSERR;
682   }
683 }
684
685 static void
686 ppc_cancel_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
687 {
688   struct PrettyPrinterContext *ppc = cls;
689
690   ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
691   if (NULL != ppc->resolver_handle)
692   {
693     GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
694     ppc->resolver_handle = NULL;
695   }
696   GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, ppc);
697   GNUNET_free(ppc);
698 }
699
700 /**
701  * Append our port and forward the result.
702  *
703  * @param cls a 'struct PrettyPrinterContext'
704  * @param hostname result from DNS resolver
705  */
706 static void
707 append_port (void *cls, const char *hostname)
708 {
709   struct PrettyPrinterContext *ppc = cls;
710   struct PrettyPrinterContext *cur;
711   char *ret;
712
713   if (hostname == NULL )
714   {
715     ppc->asc (ppc->asc_cls, NULL );
716     GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, ppc);
717     GNUNET_SCHEDULER_cancel (ppc->timeout_task);
718     ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
719     ppc->resolver_handle = NULL;
720     GNUNET_free(ppc);
721     return;
722   }
723   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
724   {
725     if (cur == ppc)
726       break;
727   }
728   if (NULL == cur)
729   {
730     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Invalid callback for PPC %p \n", ppc);
731     return;
732   }
733
734   if (GNUNET_YES == ppc->ipv6)
735     GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname,
736         ppc->port);
737   else
738     GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname,
739         ppc->port);
740   ppc->asc (ppc->asc_cls, ret);
741   GNUNET_free(ret);
742 }
743
744 /**
745  * Convert the transports address to a nice, human-readable
746  * format.
747  *
748  * @param cls closure
749  * @param type name of the transport that generated the address
750  * @param addr one of the addresses of the host, NULL for the last address
751  *        the specific address format depends on the transport
752  * @param addrlen length of the address
753  * @param numeric should (IP) addresses be displayed in numeric form?
754  * @param timeout after how long should we give up?
755  * @param asc function to call on each string
756  * @param asc_cls closure for @a asc
757  */
758 static void
759 udp_plugin_address_pretty_printer (void *cls, const char *type,
760     const void *addr, size_t addrlen, int numeric,
761     struct GNUNET_TIME_Relative timeout,
762     GNUNET_TRANSPORT_AddressStringCallback asc, void *asc_cls)
763 {
764   struct PrettyPrinterContext *ppc;
765   const void *sb;
766   size_t sbs;
767   struct sockaddr_in a4;
768   struct sockaddr_in6 a6;
769   const struct IPv4UdpAddress *u4;
770   const struct IPv6UdpAddress *u6;
771   uint16_t port;
772   uint32_t options;
773
774   if (addrlen == sizeof(struct IPv6UdpAddress))
775   {
776     u6 = addr;
777     memset (&a6, 0, sizeof(a6));
778     a6.sin6_family = AF_INET6;
779 #if HAVE_SOCKADDR_IN_SIN_LEN
780     a6.sin6_len = sizeof (a6);
781 #endif
782     a6.sin6_port = u6->u6_port;
783     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof(struct in6_addr));
784     port = ntohs (u6->u6_port);
785     options = ntohl (u6->options);
786     sb = &a6;
787     sbs = sizeof(a6);
788   }
789   else if (addrlen == sizeof(struct IPv4UdpAddress))
790   {
791     u4 = addr;
792     memset (&a4, 0, sizeof(a4));
793     a4.sin_family = AF_INET;
794 #if HAVE_SOCKADDR_IN_SIN_LEN
795     a4.sin_len = sizeof (a4);
796 #endif
797     a4.sin_port = u4->u4_port;
798     a4.sin_addr.s_addr = u4->ipv4_addr;
799     port = ntohs (u4->u4_port);
800     options = ntohl (u4->options);
801     sb = &a4;
802     sbs = sizeof(a4);
803   }
804   else
805   {
806     /* invalid address */
807     GNUNET_break_op(0);
808     asc (asc_cls, NULL );
809     return;
810   }
811   ppc = GNUNET_new (struct PrettyPrinterContext);
812   ppc->asc = asc;
813   ppc->asc_cls = asc_cls;
814   ppc->port = port;
815   ppc->options = options;
816   if (addrlen == sizeof(struct IPv6UdpAddress))
817     ppc->ipv6 = GNUNET_YES;
818   else
819     ppc->ipv6 = GNUNET_NO;
820   ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (
821       GNUNET_TIME_relative_multiply (timeout, 2), &ppc_cancel_task, ppc);
822   GNUNET_CONTAINER_DLL_insert(ppc_dll_head, ppc_dll_tail, ppc);
823   ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
824       timeout, &append_port, ppc);
825 }
826
827 static void
828 call_continuation (struct UDP_MessageWrapper *udpw, int result)
829 {
830   size_t overhead;
831
832   LOG(GNUNET_ERROR_TYPE_DEBUG,
833       "Calling continuation for %u byte message to `%s' with result %s\n",
834       udpw->payload_size, GNUNET_i2s (&udpw->session->target),
835       (GNUNET_OK == result) ? "OK" : "SYSERR");
836
837   if (udpw->msg_size >= udpw->payload_size)
838     overhead = udpw->msg_size - udpw->payload_size;
839   else
840     overhead = udpw->msg_size;
841
842   switch (result)
843   {
844   case GNUNET_OK:
845     switch (udpw->msg_type)
846     {
847     case MSG_UNFRAGMENTED:
848       if (NULL != udpw->cont)
849       {
850         /* Transport continuation */
851         udpw->cont (udpw->cont_cls, &udpw->session->target, result,
852             udpw->payload_size, udpw->msg_size);
853       }
854       GNUNET_STATISTICS_update (plugin->env->stats,
855           "# UDP, unfragmented msgs, messages, sent, success", 1, GNUNET_NO);
856       GNUNET_STATISTICS_update (plugin->env->stats,
857           "# UDP, unfragmented msgs, bytes payload, sent, success",
858           udpw->payload_size, GNUNET_NO);
859       GNUNET_STATISTICS_update (plugin->env->stats,
860           "# UDP, unfragmented msgs, bytes overhead, sent, success", overhead,
861           GNUNET_NO);
862       GNUNET_STATISTICS_update (plugin->env->stats,
863           "# UDP, total, bytes overhead, sent", overhead, GNUNET_NO);
864       GNUNET_STATISTICS_update (plugin->env->stats,
865           "# UDP, total, bytes payload, sent", udpw->payload_size, GNUNET_NO);
866       break;
867     case MSG_FRAGMENTED_COMPLETE:
868       GNUNET_assert(NULL != udpw->frag_ctx);
869       if (udpw->frag_ctx->cont != NULL )
870         udpw->frag_ctx->cont (udpw->frag_ctx->cont_cls, &udpw->session->target,
871             GNUNET_OK, udpw->frag_ctx->payload_size,
872             udpw->frag_ctx->on_wire_size);
873       GNUNET_STATISTICS_update (plugin->env->stats,
874           "# UDP, fragmented msgs, messages, sent, success", 1, GNUNET_NO);
875       GNUNET_STATISTICS_update (plugin->env->stats,
876           "# UDP, fragmented msgs, bytes payload, sent, success",
877           udpw->payload_size, GNUNET_NO);
878       GNUNET_STATISTICS_update (plugin->env->stats,
879           "# UDP, fragmented msgs, bytes overhead, sent, success", overhead,
880           GNUNET_NO);
881       GNUNET_STATISTICS_update (plugin->env->stats,
882           "# UDP, total, bytes overhead, sent", overhead, GNUNET_NO);
883       GNUNET_STATISTICS_update (plugin->env->stats,
884           "# UDP, total, bytes payload, sent", udpw->payload_size, GNUNET_NO);
885       GNUNET_STATISTICS_update (plugin->env->stats,
886           "# UDP, fragmented msgs, messages, pending", -1, GNUNET_NO);
887       break;
888     case MSG_FRAGMENTED:
889       /* Fragmented message: enqueue next fragment */
890       if (NULL != udpw->cont)
891         udpw->cont (udpw->cont_cls, &udpw->session->target, result,
892             udpw->payload_size, udpw->msg_size);
893       GNUNET_STATISTICS_update (plugin->env->stats,
894           "# UDP, fragmented msgs, fragments, sent, success", 1, GNUNET_NO);
895       GNUNET_STATISTICS_update (plugin->env->stats,
896           "# UDP, fragmented msgs, fragments bytes, sent, success",
897           udpw->msg_size, GNUNET_NO);
898       break;
899     case MSG_ACK:
900       /* No continuation */
901       GNUNET_STATISTICS_update (plugin->env->stats,
902           "# UDP, ACK msgs, messages, sent, success", 1, GNUNET_NO);
903       GNUNET_STATISTICS_update (plugin->env->stats,
904           "# UDP, ACK msgs, bytes overhead, sent, success", overhead,
905           GNUNET_NO);
906       GNUNET_STATISTICS_update (plugin->env->stats,
907           "# UDP, total, bytes overhead, sent", overhead, GNUNET_NO);
908       break;
909     case MSG_BEACON:
910       GNUNET_break(0);
911       break;
912     default:
913       LOG(GNUNET_ERROR_TYPE_ERROR, "ERROR: %u\n", udpw->msg_type);
914       GNUNET_break(0);
915       break;
916     }
917     break;
918   case GNUNET_SYSERR:
919     switch (udpw->msg_type)
920     {
921     case MSG_UNFRAGMENTED:
922       /* Unfragmented message: failed to send */
923       if (NULL != udpw->cont)
924         udpw->cont (udpw->cont_cls, &udpw->session->target, result,
925             udpw->payload_size, overhead);
926       GNUNET_STATISTICS_update (plugin->env->stats,
927           "# UDP, unfragmented msgs, messages, sent, failure", 1, GNUNET_NO);
928       GNUNET_STATISTICS_update (plugin->env->stats,
929           "# UDP, unfragmented msgs, bytes payload, sent, failure",
930           udpw->payload_size, GNUNET_NO);
931       GNUNET_STATISTICS_update (plugin->env->stats,
932           "# UDP, unfragmented msgs, bytes overhead, sent, failure", overhead,
933           GNUNET_NO);
934       break;
935     case MSG_FRAGMENTED_COMPLETE:
936       GNUNET_assert(NULL != udpw->frag_ctx);
937       if (udpw->frag_ctx->cont != NULL )
938         udpw->frag_ctx->cont (udpw->frag_ctx->cont_cls, &udpw->session->target,
939             GNUNET_SYSERR, udpw->frag_ctx->payload_size,
940             udpw->frag_ctx->on_wire_size);
941       GNUNET_STATISTICS_update (plugin->env->stats,
942           "# UDP, fragmented msgs, messages, sent, failure", 1, GNUNET_NO);
943       GNUNET_STATISTICS_update (plugin->env->stats,
944           "# UDP, fragmented msgs, bytes payload, sent, failure",
945           udpw->payload_size, GNUNET_NO);
946       GNUNET_STATISTICS_update (plugin->env->stats,
947           "# UDP, fragmented msgs, bytes payload, sent, failure", overhead,
948           GNUNET_NO);
949       GNUNET_STATISTICS_update (plugin->env->stats,
950           "# UDP, fragmented msgs, bytes payload, sent, failure", overhead,
951           GNUNET_NO);
952       GNUNET_STATISTICS_update (plugin->env->stats,
953           "# UDP, fragmented msgs, messages, pending", -1, GNUNET_NO);
954       break;
955     case MSG_FRAGMENTED:
956       GNUNET_assert(NULL != udpw->frag_ctx);
957       /* Fragmented message: failed to send */
958       GNUNET_STATISTICS_update (plugin->env->stats,
959           "# UDP, fragmented msgs, fragments, sent, failure", 1, GNUNET_NO);
960       GNUNET_STATISTICS_update (plugin->env->stats,
961           "# UDP, fragmented msgs, fragments bytes, sent, failure",
962           udpw->msg_size, GNUNET_NO);
963       break;
964     case MSG_ACK:
965       /* ACK message: failed to send */
966       GNUNET_STATISTICS_update (plugin->env->stats,
967           "# UDP, ACK msgs, messages, sent, failure", 1, GNUNET_NO);
968       break;
969     case MSG_BEACON:
970       /* Beacon message: failed to send */
971       GNUNET_break(0);
972       break;
973     default:
974       GNUNET_break(0);
975       break;
976     }
977     break;
978   default:
979     GNUNET_break(0);
980     break;
981   }
982 }
983
984 /**
985  * Check if the given port is plausible (must be either our listen
986  * port or our advertised port).  If it is neither, we return
987  * #GNUNET_SYSERR.
988  *
989  * @param plugin global variables
990  * @param in_port port number to check
991  * @return #GNUNET_OK if port is either open_port or adv_port
992  */
993 static int
994 check_port (struct Plugin *plugin, uint16_t in_port)
995 {
996   if ((in_port == plugin->port) || (in_port == plugin->aport))
997     return GNUNET_OK;
998   return GNUNET_SYSERR;
999 }
1000
1001 /**
1002  * Function that will be called to check if a binary address for this
1003  * plugin is well-formed and corresponds to an address for THIS peer
1004  * (as per our configuration).  Naturally, if absolutely necessary,
1005  * plugins can be a bit conservative in their answer, but in general
1006  * plugins should make sure that the address does not redirect
1007  * traffic to a 3rd party that might try to man-in-the-middle our
1008  * traffic.
1009  *
1010  * @param cls closure, should be our handle to the Plugin
1011  * @param addr pointer to the address
1012  * @param addrlen length of @a addr
1013  * @return #GNUNET_OK if this is a plausible address for this peer
1014  *         and transport, #GNUNET_SYSERR if not
1015  *
1016  */
1017 static int
1018 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1019 {
1020   struct Plugin *plugin = cls;
1021   struct IPv4UdpAddress *v4;
1022   struct IPv6UdpAddress *v6;
1023
1024   if ((addrlen != sizeof(struct IPv4UdpAddress))
1025       && (addrlen != sizeof(struct IPv6UdpAddress)))
1026   {
1027     GNUNET_break_op(0);
1028     return GNUNET_SYSERR;
1029   }
1030   if (addrlen == sizeof(struct IPv4UdpAddress))
1031   {
1032     v4 = (struct IPv4UdpAddress *) addr;
1033     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
1034       return GNUNET_SYSERR;
1035     if (GNUNET_OK
1036         != GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1037             sizeof(struct in_addr)))
1038       return GNUNET_SYSERR;
1039   }
1040   else
1041   {
1042     v6 = (struct IPv6UdpAddress *) addr;
1043     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1044     {
1045       GNUNET_break_op(0);
1046       return GNUNET_SYSERR;
1047     }
1048     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
1049       return GNUNET_SYSERR;
1050     if (GNUNET_OK
1051         != GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1052             sizeof(struct in6_addr)))
1053       return GNUNET_SYSERR;
1054   }
1055   return GNUNET_OK;
1056 }
1057
1058 /**
1059  * Function to free last resources associated with a session.
1060  *
1061  * @param s session to free
1062  */
1063 static void
1064 free_session (struct Session *s)
1065 {
1066   if (NULL != s->frag_ctx)
1067   {
1068     GNUNET_FRAGMENT_context_destroy (s->frag_ctx->frag, NULL, NULL );
1069     GNUNET_free(s->frag_ctx);
1070     s->frag_ctx = NULL;
1071   }
1072   GNUNET_free(s);
1073 }
1074
1075 static void
1076 dequeue (struct Plugin *plugin, struct UDP_MessageWrapper * udpw)
1077 {
1078   if (plugin->bytes_in_buffer < udpw->msg_size)
1079     GNUNET_break(0);
1080   else
1081   {
1082     GNUNET_STATISTICS_update (plugin->env->stats,
1083         "# UDP, total, bytes in buffers", -(long long) udpw->msg_size,
1084         GNUNET_NO);
1085     plugin->bytes_in_buffer -= udpw->msg_size;
1086   }
1087   GNUNET_STATISTICS_update (plugin->env->stats, "# UDP, total, msgs in buffers",
1088       -1, GNUNET_NO);
1089   if (udpw->session->address->address_length == sizeof(struct sockaddr_in))
1090     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head,
1091         plugin->ipv4_queue_tail, udpw);
1092   if (udpw->session->address->address_length == sizeof(struct sockaddr_in6))
1093     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head,
1094         plugin->ipv6_queue_tail, udpw);
1095 }
1096
1097 static void
1098 fragmented_message_done (struct UDP_FragmentationContext *fc, int result)
1099 {
1100   struct UDP_MessageWrapper *udpw;
1101   struct UDP_MessageWrapper *tmp;
1102   struct UDP_MessageWrapper dummy;
1103   struct Session *s = fc->session;
1104
1105   LOG(GNUNET_ERROR_TYPE_DEBUG,
1106       "%p : Fragmented message removed with result %s\n", fc,
1107       (result == GNUNET_SYSERR) ? "FAIL" : "SUCCESS");
1108
1109   /* Call continuation for fragmented message */
1110   memset (&dummy, 0, sizeof(dummy));
1111   dummy.msg_type = MSG_FRAGMENTED_COMPLETE;
1112   dummy.msg_size = s->frag_ctx->on_wire_size;
1113   dummy.payload_size = s->frag_ctx->payload_size;
1114   dummy.frag_ctx = s->frag_ctx;
1115   dummy.cont = NULL;
1116   dummy.cont_cls = NULL;
1117   dummy.session = s;
1118
1119   call_continuation (&dummy, result);
1120
1121   /* Remove leftover fragments from queue */
1122   if (s->address->address_length == sizeof(struct sockaddr_in6))
1123   {
1124     udpw = plugin->ipv6_queue_head;
1125     while (NULL != udpw)
1126     {
1127       tmp = udpw->next;
1128       if ((udpw->frag_ctx != NULL )&& (udpw->frag_ctx == s->frag_ctx)){
1129       dequeue (plugin, udpw);
1130       call_continuation (udpw, GNUNET_SYSERR);
1131       GNUNET_free (udpw);
1132     }
1133       udpw = tmp;
1134     }
1135   }
1136   if (s->address->address_length == sizeof(struct sockaddr_in))
1137   {
1138     udpw = plugin->ipv4_queue_head;
1139     while (udpw != NULL )
1140     {
1141       tmp = udpw->next;
1142       if ((NULL != udpw->frag_ctx) && (udpw->frag_ctx == s->frag_ctx))
1143       {
1144         dequeue (plugin, udpw);
1145         call_continuation (udpw, GNUNET_SYSERR);
1146         GNUNET_free(udpw);
1147       }
1148       udpw = tmp;
1149     }
1150   }
1151
1152   /* Destroy fragmentation context */
1153   GNUNET_FRAGMENT_context_destroy (fc->frag, &s->last_expected_msg_delay,
1154       &s->last_expected_ack_delay);
1155   s->frag_ctx = NULL;
1156   GNUNET_free(fc);
1157 }
1158
1159 /**
1160  * Functions with this signature are called whenever we need
1161  * to close a session due to a disconnect or failure to
1162  * establish a connection.
1163  *
1164  * @param cls closure with the `struct Plugin`
1165  * @param s session to close down
1166  * @return #GNUNET_OK on success
1167  */
1168 static int
1169 udp_disconnect_session (void *cls, struct Session *s)
1170 {
1171   struct Plugin *plugin = cls;
1172   struct UDP_MessageWrapper *udpw;
1173   struct UDP_MessageWrapper *next;
1174
1175   GNUNET_assert(GNUNET_YES != s->in_destroy);
1176   LOG(GNUNET_ERROR_TYPE_DEBUG, "Session %p to peer `%s' address ended\n", s,
1177       GNUNET_i2s (&s->target),
1178       udp_address_to_string (NULL, s->address->address, s->address->address_length));
1179   /* stop timeout task */
1180   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
1181   {
1182     GNUNET_SCHEDULER_cancel (s->timeout_task);
1183     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1184   }
1185   if (NULL != s->frag_ctx)
1186   {
1187     /* Remove fragmented message due to disconnect */
1188     fragmented_message_done (s->frag_ctx, GNUNET_SYSERR);
1189   }
1190
1191   next = plugin->ipv4_queue_head;
1192   while (NULL != (udpw = next))
1193   {
1194     next = udpw->next;
1195     if (udpw->session == s)
1196     {
1197       dequeue (plugin, udpw);
1198       call_continuation (udpw, GNUNET_SYSERR);
1199       GNUNET_free(udpw);
1200     }
1201   }
1202   next = plugin->ipv6_queue_head;
1203   while (NULL != (udpw = next))
1204   {
1205     next = udpw->next;
1206     if (udpw->session == s)
1207     {
1208       dequeue (plugin, udpw);
1209       call_continuation (udpw, GNUNET_SYSERR);
1210       GNUNET_free(udpw);
1211     }
1212   }
1213   plugin->env->session_end (plugin->env->cls, &s->target, s);
1214
1215   if (NULL != s->frag_ctx)
1216   {
1217     if (NULL != s->frag_ctx->cont)
1218     {
1219       s->frag_ctx->cont (s->frag_ctx->cont_cls, &s->target, GNUNET_SYSERR,
1220           s->frag_ctx->payload_size, s->frag_ctx->on_wire_size);
1221       LOG(GNUNET_ERROR_TYPE_DEBUG,
1222           "Calling continuation for fragemented message to `%s' with result SYSERR\n",
1223           GNUNET_i2s (&s->target));
1224     }
1225   }
1226
1227   GNUNET_assert(
1228       GNUNET_YES == GNUNET_CONTAINER_multipeermap_remove (plugin->sessions, &s->target, s));
1229   GNUNET_STATISTICS_set (plugin->env->stats, "# UDP, sessions active",
1230       GNUNET_CONTAINER_multipeermap_size (plugin->sessions), GNUNET_NO);
1231   if (s->rc > 0)
1232     s->in_destroy = GNUNET_YES;
1233   else
1234   {
1235     GNUNET_HELLO_address_free (s->address);
1236     free_session (s);
1237   }
1238   return GNUNET_OK;
1239 }
1240
1241 /**
1242  * Function that is called to get the keepalive factor.
1243  * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1244  * calculate the interval between keepalive packets.
1245  *
1246  * @param cls closure with the `struct Plugin`
1247  * @return keepalive factor
1248  */
1249 static unsigned int
1250 udp_query_keepalive_factor (void *cls)
1251 {
1252   return 15;
1253 }
1254
1255 /**
1256  * Destroy a session, plugin is being unloaded.
1257  *
1258  * @param cls the `struct Plugin`
1259  * @param key hash of public key of target peer
1260  * @param value a `struct PeerSession *` to clean up
1261  * @return #GNUNET_OK (continue to iterate)
1262  */
1263 static int
1264 disconnect_and_free_it (void *cls, const struct GNUNET_PeerIdentity *key,
1265     void *value)
1266 {
1267   struct Plugin *plugin = cls;
1268
1269   udp_disconnect_session (plugin, value);
1270   return GNUNET_OK;
1271 }
1272
1273 /**
1274  * Disconnect from a remote node.  Clean up session if we have one for
1275  * this peer.
1276  *
1277  * @param cls closure for this call (should be handle to Plugin)
1278  * @param target the peeridentity of the peer to disconnect
1279  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the operation failed
1280  */
1281 static void
1282 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1283 {
1284   struct Plugin *plugin = cls;
1285
1286   LOG(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from peer `%s'\n",
1287       GNUNET_i2s (target));
1288   /* Clean up sessions */
1289   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions, target,
1290       &disconnect_and_free_it, plugin);
1291 }
1292
1293 /**
1294  * Session was idle, so disconnect it
1295  *
1296  * @param cls the `struct Session` to time out
1297  * @param tc scheduler context
1298  */
1299 static void
1300 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1301 {
1302   struct Session *s = cls;
1303
1304   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1305   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1306       "Session %p was idle for %s, disconnecting\n", s,
1307       GNUNET_STRINGS_relative_time_to_string (UDP_SESSION_TIME_OUT, GNUNET_YES));
1308   /* call session destroy function */
1309   udp_disconnect_session (s->plugin, s);
1310 }
1311
1312 /**
1313  * Increment session timeout due to activity
1314  *
1315  * @param s session to reschedule timeout activity for
1316  */
1317 static void
1318 reschedule_session_timeout (struct Session *s)
1319 {
1320   if (GNUNET_YES == s->in_destroy)
1321     return;
1322   GNUNET_assert(GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1323   GNUNET_SCHEDULER_cancel (s->timeout_task);
1324   s->timeout_task = GNUNET_SCHEDULER_add_delayed (UDP_SESSION_TIME_OUT,
1325       &session_timeout, s);
1326   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Timeout restarted for session %p\n", s);
1327 }
1328
1329 static struct Session *
1330 create_session (struct Plugin *plugin,
1331     const struct GNUNET_HELLO_Address *address)
1332 {
1333   struct Session *s;
1334
1335   s = GNUNET_new (struct Session);
1336   s->address = GNUNET_HELLO_address_copy (address);
1337   s->target = address->peer;
1338   s->last_expected_ack_delay = GNUNET_TIME_relative_multiply (
1339       GNUNET_TIME_UNIT_MILLISECONDS, 250);
1340   s->last_expected_msg_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1341   s->flow_delay_from_other_peer = GNUNET_TIME_UNIT_ZERO_ABS;
1342   s->flow_delay_for_other_peer = GNUNET_TIME_UNIT_ZERO;
1343   s->timeout_task = GNUNET_SCHEDULER_add_delayed (UDP_SESSION_TIME_OUT,
1344       &session_timeout, s);
1345   return s;
1346 }
1347
1348 static int
1349 session_cmp_it (void *cls, const struct GNUNET_PeerIdentity * key, void *value)
1350 {
1351   struct SessionCompareContext * cctx = cls;
1352   const struct GNUNET_HELLO_Address *address = cctx->address;
1353   struct Session *s = value;
1354
1355   LOG(GNUNET_ERROR_TYPE_DEBUG, "Comparing address %s <-> %s\n",
1356       udp_address_to_string (NULL, (void *) address->address, address->address_length),
1357       udp_address_to_string (NULL, s->address->address, s->address->address_length));
1358
1359   if (0 == GNUNET_HELLO_address_cmp(s->address, cctx->address))
1360   {
1361     cctx->res = s;
1362     return GNUNET_NO;
1363   }
1364   return GNUNET_YES;
1365 }
1366
1367 /**
1368  * Function obtain the network type for a session
1369  *
1370  * @param cls closure ('struct Plugin*')
1371  * @param session the session
1372  * @return the network type
1373  */
1374 static enum GNUNET_ATS_Network_Type
1375 udp_get_network (void *cls, struct Session *session)
1376 {
1377   return ntohl (session->ats.value);
1378 }
1379
1380 /**
1381  * Creates a new outbound session the transport service will use to
1382  * send data to the peer
1383  *
1384  * @param cls the plugin
1385  * @param address the address
1386  * @param inbound look for inbound session
1387  * @return the session or NULL of max connections exceeded
1388  */
1389 static struct Session *
1390 udp_plugin_lookup_session (void *cls,
1391     const struct GNUNET_HELLO_Address *address)
1392 {
1393   struct Plugin * plugin = cls;
1394   struct IPv6UdpAddress * udp_a6;
1395   struct IPv4UdpAddress * udp_a4;
1396
1397   GNUNET_assert(plugin != NULL);
1398   GNUNET_assert(address != NULL);
1399
1400   if ((address->address == NULL )||
1401   ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
1402       (address->address_length != sizeof (struct IPv6UdpAddress)))){
1403   LOG (GNUNET_ERROR_TYPE_WARNING,
1404       _("Trying to create session for address of unexpected length %u (should be %u or %u)\n"),
1405       address->address_length,
1406       sizeof (struct IPv4UdpAddress),
1407       sizeof (struct IPv6UdpAddress));
1408   return NULL;
1409 }
1410
1411   if (address->address_length == sizeof(struct IPv4UdpAddress))
1412   {
1413     if (plugin->sockv4 == NULL )
1414       return NULL ;
1415     udp_a4 = (struct IPv4UdpAddress *) address->address;
1416     if (udp_a4->u4_port == 0)
1417       return NULL ;
1418   }
1419
1420   if (address->address_length == sizeof(struct IPv6UdpAddress))
1421   {
1422     if (plugin->sockv6 == NULL )
1423       return NULL ;
1424     udp_a6 = (struct IPv6UdpAddress *) address->address;
1425     if (udp_a6->u6_port == 0)
1426       return NULL ;
1427   }
1428
1429   /* check if session already exists */
1430   struct SessionCompareContext cctx;
1431   cctx.address = address;
1432   cctx.res = NULL;
1433   LOG(GNUNET_ERROR_TYPE_ERROR,
1434       "Looking for existing session for peer `%s' `%s' \n",
1435       GNUNET_i2s (&address->peer),
1436       udp_address_to_string(NULL, address->address, address->address_length));
1437   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions, &address->peer,
1438       session_cmp_it, &cctx);
1439   if (cctx.res != NULL )
1440   {
1441     LOG(GNUNET_ERROR_TYPE_ERROR, "Found existing session %p\n", cctx.res);
1442     return cctx.res;
1443   }
1444   return NULL ;
1445 }
1446
1447 static int
1448 udp_address_is_inbound (const struct GNUNET_HELLO_Address *address)
1449 {
1450   if (GNUNET_HELLO_ADDRESS_INFO_INBOUND == (address->local_info & GNUNET_HELLO_ADDRESS_INFO_INBOUND))
1451     return GNUNET_YES;
1452   else
1453    return GNUNET_NO;
1454 }
1455
1456 static struct Session *
1457 udp_plugin_create_session (void *cls,
1458     const struct GNUNET_HELLO_Address *address)
1459 {
1460   struct Session *s;
1461   struct IPv4UdpAddress *udp_v4;
1462   struct IPv6UdpAddress *udp_v6;
1463
1464   s = create_session (plugin, address);
1465   if (sizeof (struct IPv4UdpAddress) == address->address_length)
1466   {
1467     struct sockaddr_in v4;
1468     udp_v4 = (struct IPv4UdpAddress *) address->address;
1469     memset (&v4, '\0', sizeof (v4));
1470     v4.sin_family = AF_INET;
1471 #if HAVE_SOCKADDR_IN_SIN_LEN
1472     v4->sin_len = sizeof (struct sockaddr_in);
1473 #endif
1474     v4.sin_port = udp_v4->u4_port;
1475     v4.sin_addr.s_addr = udp_v4->ipv4_addr;
1476     s->ats = plugin->env->get_address_type (plugin->env->cls,
1477         (const struct sockaddr *) &v4, sizeof (v4));
1478   }
1479   else if (sizeof (struct IPv6UdpAddress) == address->address_length)
1480   {
1481     struct sockaddr_in6 v6;
1482     udp_v6 = (struct IPv6UdpAddress *) address->address;
1483     memset (&v6, '\0', sizeof (v6));
1484     v6.sin6_family = AF_INET6;
1485 #if HAVE_SOCKADDR_IN_SIN_LEN
1486     v6->sin_len = sizeof (struct sockaddr_in6);
1487 #endif
1488     v6.sin6_port = udp_v6->u6_port;
1489     v6.sin6_addr = udp_v6->ipv6_addr;
1490     s->ats = plugin->env->get_address_type (plugin->env->cls,
1491         (const struct sockaddr *) &v6, sizeof (v6));
1492   }
1493
1494   if (NULL == s)
1495     return NULL ; /* protocol not supported or address invalid */
1496   LOG(GNUNET_ERROR_TYPE_ERROR,
1497       "Creating new %s session %p for peer `%s' address `%s'\n",
1498       (GNUNET_YES == udp_address_is_inbound(address)) ? "inbound" : "outbound",
1499       s, GNUNET_i2s (&address->peer),
1500       udp_address_to_string(NULL,address->address,address->address_length));
1501   GNUNET_assert(
1502       GNUNET_OK == GNUNET_CONTAINER_multipeermap_put (plugin->sessions, &s->target, s, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1503   GNUNET_STATISTICS_set (plugin->env->stats, "# UDP, sessions active",
1504       GNUNET_CONTAINER_multipeermap_size (plugin->sessions), GNUNET_NO);
1505   return s;
1506 }
1507
1508 static void
1509 udp_plugin_update_session_timeout (void *cls,
1510     const struct GNUNET_PeerIdentity *peer, struct Session *session)
1511 {
1512   if (GNUNET_YES
1513       != GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessions, peer,
1514           session))
1515   {
1516     GNUNET_break(0);
1517     return;
1518   }
1519
1520   /* Reschedule session timeout */
1521   reschedule_session_timeout (session);
1522 }
1523
1524 /**
1525  * Creates a new outbound session the transport service will use to send data to the
1526  * peer
1527  *
1528  * @param cls the plugin
1529  * @param address the address
1530  * @return the session or NULL of max connections exceeded
1531  */
1532 static struct Session *
1533 udp_plugin_get_session (void *cls, const struct GNUNET_HELLO_Address *address)
1534 {
1535   struct Session *s;
1536
1537   if (NULL == address)
1538   {
1539     GNUNET_break(0);
1540     return NULL ;
1541   }
1542   if ((address->address_length != sizeof(struct IPv4UdpAddress))
1543       && (address->address_length != sizeof(struct IPv6UdpAddress)))
1544     return NULL ;
1545
1546   /* otherwise create new */
1547   if (NULL != (s = udp_plugin_lookup_session (cls, address)))
1548     return s;
1549   return udp_plugin_create_session (cls, address);
1550 }
1551
1552 static void
1553 enqueue (struct Plugin *plugin, struct UDP_MessageWrapper * udpw)
1554 {
1555   if (plugin->bytes_in_buffer + udpw->msg_size > INT64_MAX)
1556     GNUNET_break(0);
1557   else
1558   {
1559     GNUNET_STATISTICS_update (plugin->env->stats,
1560         "# UDP, total, bytes in buffers", udpw->msg_size, GNUNET_NO);
1561     plugin->bytes_in_buffer += udpw->msg_size;
1562   }
1563   GNUNET_STATISTICS_update (plugin->env->stats, "# UDP, total, msgs in buffers",
1564       1, GNUNET_NO);
1565   if (udpw->session->address->address_length == sizeof(struct sockaddr_in))
1566     GNUNET_CONTAINER_DLL_insert(plugin->ipv4_queue_head,
1567         plugin->ipv4_queue_tail, udpw);
1568   if (udpw->session->address->address_length == sizeof(struct sockaddr_in6))
1569     GNUNET_CONTAINER_DLL_insert(plugin->ipv6_queue_head,
1570         plugin->ipv6_queue_tail, udpw);
1571 }
1572
1573 /**
1574  * Fragment message was transmitted via UDP, let fragmentation know
1575  * to send the next fragment now.
1576  *
1577  * @param cls the 'struct UDPMessageWrapper' of the fragment
1578  * @param target destination peer (ignored)
1579  * @param result GNUNET_OK on success (ignored)
1580  * @param payload bytes payload sent
1581  * @param physical bytes physical sent
1582  */
1583 static void
1584 send_next_fragment (void *cls, const struct GNUNET_PeerIdentity *target,
1585     int result, size_t payload, size_t physical)
1586 {
1587   struct UDP_MessageWrapper *udpw = cls;
1588
1589   GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);
1590 }
1591
1592 /**
1593  * Function that is called with messages created by the fragmentation
1594  * module.  In the case of the 'proc' callback of the
1595  * GNUNET_FRAGMENT_context_create function, this function must
1596  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
1597  *
1598  * @param cls closure, the 'struct FragmentationContext'
1599  * @param msg the message that was created
1600  */
1601 static void
1602 enqueue_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
1603 {
1604   struct UDP_FragmentationContext *frag_ctx = cls;
1605   struct Plugin *plugin = frag_ctx->plugin;
1606   struct UDP_MessageWrapper * udpw;
1607   size_t msg_len = ntohs (msg->size);
1608
1609   LOG(GNUNET_ERROR_TYPE_DEBUG, "Enqueuing fragment with %u bytes\n", msg_len);
1610   frag_ctx->fragments_used++;
1611   udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + msg_len);
1612   udpw->session = frag_ctx->session;
1613   udpw->msg_buf = (char *) &udpw[1];
1614   udpw->msg_size = msg_len;
1615   udpw->payload_size = msg_len; /*FIXME: minus fragment overhead */
1616   udpw->cont = &send_next_fragment;
1617   udpw->cont_cls = udpw;
1618   udpw->timeout = frag_ctx->timeout;
1619   udpw->frag_ctx = frag_ctx;
1620   udpw->msg_type = MSG_FRAGMENTED;
1621   memcpy (udpw->msg_buf, msg, msg_len);
1622   enqueue (plugin, udpw);
1623   schedule_select (plugin);
1624 }
1625
1626 /**
1627  * Function that can be used by the transport service to transmit
1628  * a message using the plugin.   Note that in the case of a
1629  * peer disconnecting, the continuation MUST be called
1630  * prior to the disconnect notification itself.  This function
1631  * will be called with this peer's HELLO message to initiate
1632  * a fresh connection to another peer.
1633  *
1634  * @param cls closure
1635  * @param s which session must be used
1636  * @param msgbuf the message to transmit
1637  * @param msgbuf_size number of bytes in 'msgbuf'
1638  * @param priority how important is the message (most plugins will
1639  *                 ignore message priority and just FIFO)
1640  * @param to how long to wait at most for the transmission (does not
1641  *                require plugins to discard the message after the timeout,
1642  *                just advisory for the desired delay; most plugins will ignore
1643  *                this as well)
1644  * @param cont continuation to call once the message has
1645  *        been transmitted (or if the transport is ready
1646  *        for the next transmission call; or if the
1647  *        peer disconnected...); can be NULL
1648  * @param cont_cls closure for cont
1649  * @return number of bytes used (on the physical network, with overheads);
1650  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1651  *         and does NOT mean that the message was not transmitted (DV)
1652  */
1653 static ssize_t
1654 udp_plugin_send (void *cls, struct Session *s, const char *msgbuf,
1655     size_t msgbuf_size, unsigned int priority, struct GNUNET_TIME_Relative to,
1656     GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1657 {
1658   struct Plugin *plugin = cls;
1659   size_t udpmlen = msgbuf_size + sizeof(struct UDPMessage);
1660   struct UDP_FragmentationContext * frag_ctx;
1661   struct UDP_MessageWrapper * udpw;
1662   struct UDPMessage *udp;
1663   char mbuf[udpmlen];
1664   GNUNET_assert(plugin != NULL);
1665   GNUNET_assert(s != NULL);
1666
1667   if ((s->address->address_length == sizeof(struct sockaddr_in6)) && (plugin->sockv6 == NULL ))
1668     return GNUNET_SYSERR;
1669   if ((s->address->address_length == sizeof(struct sockaddr_in)) && (plugin->sockv4 == NULL ))
1670     return GNUNET_SYSERR;
1671   if (udpmlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1672   {
1673     GNUNET_break(0);
1674     return GNUNET_SYSERR;
1675   }
1676   if (GNUNET_YES
1677       != GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessions,
1678           &s->target, s))
1679   {
1680     GNUNET_break(0);
1681     return GNUNET_SYSERR;
1682   }
1683   LOG(GNUNET_ERROR_TYPE_DEBUG,
1684       "UDP transmits %u-byte message to `%s' using address `%s'\n", udpmlen,
1685       GNUNET_i2s (&s->target), udp_address_to_string (NULL, s->address->address, s->address->address_length));
1686
1687   /* Message */
1688   udp = (struct UDPMessage *) mbuf;
1689   udp->header.size = htons (udpmlen);
1690   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
1691   udp->reserved = htonl (0);
1692   udp->sender = *plugin->env->my_identity;
1693
1694   /* We do not update the session time out here!
1695    * Otherwise this session will not timeout since we send keep alive before
1696    * session can timeout
1697    *
1698    * For UDP we update session timeout only on receive, this will cover keep
1699    * alives, since remote peer will reply with keep alive response!
1700    */
1701   if (udpmlen <= UDP_MTU)
1702   {
1703     /* unfragmented message */
1704     udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + udpmlen);
1705     udpw->session = s;
1706     udpw->msg_buf = (char *) &udpw[1];
1707     udpw->msg_size = udpmlen; /* message size with UDP overhead */
1708     udpw->payload_size = msgbuf_size; /* message size without UDP overhead */
1709     udpw->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), to);
1710     udpw->cont = cont;
1711     udpw->cont_cls = cont_cls;
1712     udpw->frag_ctx = NULL;
1713     udpw->msg_type = MSG_UNFRAGMENTED;
1714     memcpy (udpw->msg_buf, udp, sizeof(struct UDPMessage));
1715     memcpy (&udpw->msg_buf[sizeof(struct UDPMessage)], msgbuf, msgbuf_size);
1716     enqueue (plugin, udpw);
1717
1718     GNUNET_STATISTICS_update (plugin->env->stats,
1719         "# UDP, unfragmented msgs, messages, attempt", 1, GNUNET_NO);
1720     GNUNET_STATISTICS_update (plugin->env->stats,
1721         "# UDP, unfragmented msgs, bytes payload, attempt", udpw->payload_size,
1722         GNUNET_NO);
1723   }
1724   else
1725   {
1726     /* fragmented message */
1727     if (s->frag_ctx != NULL )
1728       return GNUNET_SYSERR;
1729     memcpy (&udp[1], msgbuf, msgbuf_size);
1730     frag_ctx = GNUNET_new (struct UDP_FragmentationContext);
1731     frag_ctx->plugin = plugin;
1732     frag_ctx->session = s;
1733     frag_ctx->cont = cont;
1734     frag_ctx->cont_cls = cont_cls;
1735     frag_ctx->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1736         to);
1737     frag_ctx->payload_size = msgbuf_size; /* unfragmented message size without UDP overhead */
1738     frag_ctx->on_wire_size = 0; /* bytes with UDP and fragmentation overhead */
1739     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
1740         UDP_MTU, &plugin->tracker, s->last_expected_msg_delay,
1741         s->last_expected_ack_delay, &udp->header, &enqueue_fragment, frag_ctx);
1742     s->frag_ctx = frag_ctx;
1743     GNUNET_STATISTICS_update (plugin->env->stats,
1744         "# UDP, fragmented msgs, messages, pending", 1, GNUNET_NO);
1745     GNUNET_STATISTICS_update (plugin->env->stats,
1746         "# UDP, fragmented msgs, messages, attempt", 1, GNUNET_NO);
1747     GNUNET_STATISTICS_update (plugin->env->stats,
1748         "# UDP, fragmented msgs, bytes payload, attempt",
1749         frag_ctx->payload_size, GNUNET_NO);
1750   }
1751   schedule_select (plugin);
1752   return udpmlen;
1753 }
1754
1755 /**
1756  * Our external IP address/port mapping has changed.
1757  *
1758  * @param cls closure, the 'struct LocalAddrList'
1759  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1760  *     the previous (now invalid) one
1761  * @param address either the previous or the new public IP address
1762  * @param addrlen actual lenght of the address
1763  */
1764 static void
1765 udp_nat_port_map_callback (void *cls, int add_remove,
1766     const struct sockaddr *addr, socklen_t addrlen)
1767 {
1768   struct Plugin *plugin = cls;
1769   struct GNUNET_HELLO_Address *address;
1770   struct IPv4UdpAddress u4;
1771   struct IPv6UdpAddress u6;
1772   void *arg;
1773   size_t args;
1774
1775   LOG(GNUNET_ERROR_TYPE_INFO, "NAT notification to %s address `%s'\n",
1776       (GNUNET_YES == add_remove) ? "add" : "remove",
1777       GNUNET_a2s (addr, addrlen));
1778
1779   /* convert 'address' to our internal format */
1780   switch (addr->sa_family)
1781   {
1782   case AF_INET:
1783     GNUNET_assert(addrlen == sizeof(struct sockaddr_in));
1784     memset (&u4, 0, sizeof(u4));
1785     u4.options = htonl (myoptions);
1786     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1787     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1788     if (0 == ((struct sockaddr_in *) addr)->sin_port)
1789       return;
1790     arg = &u4;
1791     args = sizeof(struct IPv4UdpAddress);
1792     break;
1793   case AF_INET6:
1794     GNUNET_assert(addrlen == sizeof(struct sockaddr_in6));
1795     memset (&u4, 0, sizeof(u4));
1796     u6.options = htonl (myoptions);
1797     if (0 == ((struct sockaddr_in6 *) addr)->sin6_port)
1798       return;
1799     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1800         sizeof(struct in6_addr));
1801     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1802     arg = &u6;
1803     args = sizeof(struct IPv6UdpAddress);
1804     break;
1805   default:
1806     GNUNET_break(0);
1807     return;
1808   }
1809   /* modify our published address list */
1810   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1811       PLUGIN_NAME, arg, args, GNUNET_HELLO_ADDRESS_INFO_NONE);
1812   plugin->env->notify_address (plugin->env->cls, add_remove, address);
1813   GNUNET_HELLO_address_free (address);
1814 }
1815
1816 /**
1817  * Message tokenizer has broken up an incomming message. Pass it on
1818  * to the service.
1819  *
1820  * @param cls the 'struct Plugin'
1821  * @param client the `struct SourceInformation`
1822  * @param hdr the actual message
1823  * @return #GNUNET_OK (always)
1824  */
1825 static int
1826 process_inbound_tokenized_messages (void *cls, void *client,
1827     const struct GNUNET_MessageHeader *hdr)
1828 {
1829   struct Plugin *plugin = cls;
1830   struct SourceInformation *si = client;
1831   struct GNUNET_TIME_Relative delay;
1832
1833   GNUNET_assert(si->session != NULL);
1834   if (GNUNET_YES == si->session->in_destroy)
1835     return GNUNET_OK;
1836   /* setup ATS */
1837   GNUNET_break(ntohl (si->session->ats.value) != GNUNET_ATS_NET_UNSPECIFIED);
1838   reschedule_session_timeout (si->session);
1839   delay = plugin->env->receive (plugin->env->cls, si->session->address, si->session, hdr);
1840   plugin->env->update_address_metrics (plugin->env->cls,
1841       si->session->address, si->session,
1842       &si->session->ats, 1);
1843   si->session->flow_delay_for_other_peer = delay;
1844   return GNUNET_OK;
1845 }
1846
1847 /**
1848  * We've received a UDP Message.  Process it (pass contents to main service).
1849  *
1850  * @param plugin plugin context
1851  * @param msg the message
1852  * @param sender_addr sender address
1853  * @param sender_addr_len number of bytes in sender_addr
1854  */
1855 static void
1856 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1857     const struct sockaddr *sender_addr, socklen_t sender_addr_len)
1858 {
1859   struct SourceInformation si;
1860   struct Session * s;
1861   struct GNUNET_HELLO_Address *address;
1862   struct IPv4UdpAddress u4;
1863   struct IPv6UdpAddress u6;
1864   const void *arg;
1865   size_t args;
1866
1867   if (0 != ntohl (msg->reserved))
1868   {
1869     GNUNET_break_op(0);
1870     return;
1871   }
1872   if (ntohs (msg->header.size)
1873       < sizeof(struct GNUNET_MessageHeader) + sizeof(struct UDPMessage))
1874   {
1875     GNUNET_break_op(0);
1876     return;
1877   }
1878
1879   /* convert address */
1880   switch (sender_addr->sa_family)
1881   {
1882   case AF_INET:
1883     GNUNET_assert(sender_addr_len == sizeof(struct sockaddr_in));
1884     memset (&u4, 0, sizeof(u4));
1885     u6.options = htonl (0);
1886     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
1887     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1888     arg = &u4;
1889     args = sizeof(u4);
1890     break;
1891   case AF_INET6:
1892     GNUNET_assert(sender_addr_len == sizeof(struct sockaddr_in6));
1893     memset (&u6, 0, sizeof(u6));
1894     u6.options = htonl (0);
1895     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
1896     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
1897     arg = &u6;
1898     args = sizeof(u6);
1899     break;
1900   default:
1901     GNUNET_break(0);
1902     return;
1903   }
1904   LOG(GNUNET_ERROR_TYPE_DEBUG,
1905       "Received message with %u bytes from peer `%s' at `%s'\n",
1906       (unsigned int ) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1907       GNUNET_a2s (sender_addr, sender_addr_len));
1908
1909   address = GNUNET_HELLO_address_allocate ( &msg->sender, PLUGIN_NAME,
1910       arg, args, GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1911   if (NULL == (s = udp_plugin_lookup_session (plugin, address)))
1912   {
1913     s = udp_plugin_create_session (plugin, address);
1914     plugin->env->session_start (NULL, address, s, NULL, 0);
1915   }
1916   GNUNET_free(address);
1917
1918   /* iterate over all embedded messages */
1919   si.session = s;
1920   si.sender = msg->sender;
1921   si.arg = arg;
1922   si.args = args;
1923   s->rc++;
1924   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
1925       ntohs (msg->header.size) - sizeof(struct UDPMessage), GNUNET_YES,
1926       GNUNET_NO);
1927   s->rc--;
1928   if ((0 == s->rc) && (GNUNET_YES == s->in_destroy))
1929     free_session (s);
1930 }
1931
1932 /**
1933  * Scan the heap for a receive context with the given address.
1934  *
1935  * @param cls the `struct FindReceiveContext`
1936  * @param node internal node of the heap
1937  * @param element value stored at the node (a 'struct ReceiveContext')
1938  * @param cost cost associated with the node
1939  * @return #GNUNET_YES if we should continue to iterate,
1940  *         #GNUNET_NO if not.
1941  */
1942 static int
1943 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1944     void *element, GNUNET_CONTAINER_HeapCostType cost)
1945 {
1946   struct FindReceiveContext *frc = cls;
1947   struct DefragContext *e = element;
1948
1949   if ((frc->addr_len == e->addr_len)
1950       && (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1951   {
1952     frc->rc = e;
1953     return GNUNET_NO;
1954   }
1955   return GNUNET_YES;
1956 }
1957
1958 /**
1959  * Process a defragmented message.
1960  *
1961  * @param cls the 'struct ReceiveContext'
1962  * @param msg the message
1963  */
1964 static void
1965 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1966 {
1967   struct DefragContext *rc = cls;
1968
1969   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1970   {
1971     GNUNET_break(0);
1972     return;
1973   }
1974   if (ntohs (msg->size) < sizeof(struct UDPMessage))
1975   {
1976     GNUNET_break(0);
1977     return;
1978   }
1979   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1980       rc->src_addr, rc->addr_len);
1981 }
1982
1983 struct LookupContext
1984 {
1985   struct Session *res;
1986
1987   const struct GNUNET_HELLO_Address *address;
1988
1989   int must_have_frag_ctx;
1990 };
1991
1992 static int
1993 lookup_session_by_addr_it (void *cls, const struct GNUNET_PeerIdentity *key,
1994     void *value)
1995 {
1996   struct LookupContext *l_ctx = cls;
1997   struct Session * s = value;
1998
1999   if ((GNUNET_YES == l_ctx->must_have_frag_ctx) && (NULL == s->frag_ctx))
2000     return GNUNET_YES;
2001
2002   if (0 == GNUNET_HELLO_address_cmp (s->address, l_ctx->address))
2003   {
2004     l_ctx->res = s;
2005     return GNUNET_YES;
2006   }
2007   return GNUNET_YES;
2008 }
2009
2010 /**
2011  * Transmit an acknowledgement.
2012  *
2013  * @param cls the 'struct ReceiveContext'
2014  * @param id message ID (unused)
2015  * @param msg ack to transmit
2016  */
2017 static void
2018 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
2019 {
2020   struct DefragContext *rc = cls;
2021   size_t msize = sizeof(struct UDP_ACK_Message) + ntohs (msg->size);
2022   struct UDP_ACK_Message *udp_ack;
2023   uint32_t delay = 0;
2024   struct UDP_MessageWrapper *udpw;
2025   struct Session *s;
2026   struct LookupContext l_ctx;
2027
2028   l_ctx.address = GNUNET_HELLO_address_allocate (NULL, PLUGIN_NAME, rc->src_addr,
2029       rc->addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE);
2030   l_ctx.res = NULL;
2031   l_ctx.must_have_frag_ctx = GNUNET_NO;
2032   GNUNET_CONTAINER_multipeermap_iterate (rc->plugin->sessions,
2033       &lookup_session_by_addr_it, &l_ctx);
2034   s = l_ctx.res;
2035
2036   if (NULL == s)
2037     return;
2038
2039   if (s->flow_delay_for_other_peer.rel_value_us <= UINT32_MAX)
2040     delay = s->flow_delay_for_other_peer.rel_value_us;
2041
2042   LOG(GNUNET_ERROR_TYPE_DEBUG, "Sending ACK to `%s' including delay of %s\n",
2043       GNUNET_a2s (rc->src_addr, (rc->src_addr->sa_family == AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct sockaddr_in6)),
2044       GNUNET_STRINGS_relative_time_to_string (s->flow_delay_for_other_peer, GNUNET_YES));
2045   udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + msize);
2046   udpw->msg_size = msize;
2047   udpw->payload_size = 0;
2048   udpw->session = s;
2049   udpw->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
2050   udpw->msg_buf = (char *) &udpw[1];
2051   udpw->msg_type = MSG_ACK;
2052   udp_ack = (struct UDP_ACK_Message *) udpw->msg_buf;
2053   udp_ack->header.size = htons ((uint16_t) msize);
2054   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
2055   udp_ack->delay = htonl (delay);
2056   udp_ack->sender = *rc->plugin->env->my_identity;
2057   memcpy (&udp_ack[1], msg, ntohs (msg->size));
2058   enqueue (rc->plugin, udpw);
2059 }
2060
2061 static void
2062 read_process_msg (struct Plugin *plugin, const struct GNUNET_MessageHeader *msg,
2063     const struct sockaddr *addr, socklen_t fromlen)
2064 {
2065   if (ntohs (msg->size) < sizeof(struct UDPMessage))
2066   {
2067     GNUNET_break_op(0);
2068     return;
2069   }
2070   process_udp_message (plugin, (const struct UDPMessage *) msg, addr, fromlen);
2071 }
2072
2073 static void
2074 read_process_ack (struct Plugin *plugin, const struct GNUNET_MessageHeader *msg,
2075     const struct sockaddr *addr, socklen_t fromlen)
2076 {
2077   const struct GNUNET_MessageHeader *ack;
2078   const struct UDP_ACK_Message *udp_ack;
2079   struct LookupContext l_ctx;
2080   struct Session *s;
2081   struct GNUNET_TIME_Relative flow_delay;
2082
2083   if (ntohs (msg->size)
2084       < sizeof(struct UDP_ACK_Message) + sizeof(struct GNUNET_MessageHeader))
2085   {
2086     GNUNET_break_op(0);
2087     return;
2088   }
2089   udp_ack = (const struct UDP_ACK_Message *) msg;
2090
2091   l_ctx.address = GNUNET_HELLO_address_allocate (NULL, PLUGIN_NAME,
2092       (const struct sockaddr *) addr, fromlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2093   l_ctx.res = NULL;
2094   l_ctx.must_have_frag_ctx = GNUNET_YES;
2095   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
2096       &lookup_session_by_addr_it, &l_ctx);
2097   s = l_ctx.res;
2098   if ((NULL == s) || (NULL == s->frag_ctx))
2099   {
2100     return;
2101   }
2102
2103   flow_delay.rel_value_us = (uint64_t) ntohl (udp_ack->delay);
2104   LOG(GNUNET_ERROR_TYPE_DEBUG, "We received a sending delay of %s\n",
2105       GNUNET_STRINGS_relative_time_to_string (flow_delay, GNUNET_YES));
2106   s->flow_delay_from_other_peer = GNUNET_TIME_relative_to_absolute (flow_delay);
2107
2108   ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
2109   if (ntohs (ack->size) != ntohs (msg->size) - sizeof(struct UDP_ACK_Message))
2110   {
2111     GNUNET_break_op(0);
2112     return;
2113   }
2114
2115   if (0
2116       != memcmp (&l_ctx.res->target, &udp_ack->sender,
2117           sizeof(struct GNUNET_PeerIdentity)))
2118     GNUNET_break(0);
2119   if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (s->frag_ctx->frag, ack))
2120   {
2121     LOG(GNUNET_ERROR_TYPE_DEBUG,
2122         "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
2123         (unsigned int ) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
2124         GNUNET_a2s (addr, fromlen));
2125     /* Expect more ACKs to arrive */
2126     return;
2127   }
2128
2129   LOG(GNUNET_ERROR_TYPE_DEBUG, "Message full ACK'ed\n",
2130       (unsigned int ) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
2131       GNUNET_a2s (addr, fromlen));
2132
2133   /* Remove fragmented message after successful sending */
2134   fragmented_message_done (s->frag_ctx, GNUNET_OK);
2135 }
2136
2137 static void
2138 read_process_fragment (struct Plugin *plugin,
2139     const struct GNUNET_MessageHeader *msg, const struct sockaddr *addr,
2140     socklen_t fromlen)
2141 {
2142   struct DefragContext *d_ctx;
2143   struct GNUNET_TIME_Absolute now;
2144   struct FindReceiveContext frc;
2145
2146   frc.rc = NULL;
2147   frc.addr = addr;
2148   frc.addr_len = fromlen;
2149
2150   LOG(GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
2151       (unsigned int ) ntohs (msg->size), GNUNET_a2s (addr, fromlen));
2152   /* Lookup existing receive context for this address */
2153   GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs, &find_receive_context,
2154       &frc);
2155   now = GNUNET_TIME_absolute_get ();
2156   d_ctx = frc.rc;
2157
2158   if (d_ctx == NULL )
2159   {
2160     /* Create a new defragmentation context */
2161     d_ctx = GNUNET_malloc (sizeof (struct DefragContext) + fromlen);
2162     memcpy (&d_ctx[1], addr, fromlen);
2163     d_ctx->src_addr = (const struct sockaddr *) &d_ctx[1];
2164     d_ctx->addr_len = fromlen;
2165     d_ctx->plugin = plugin;
2166     d_ctx->defrag = GNUNET_DEFRAGMENT_context_create (plugin->env->stats,
2167         UDP_MTU, UDP_MAX_MESSAGES_IN_DEFRAG, d_ctx, &fragment_msg_proc,
2168         &ack_proc);
2169     d_ctx->hnode = GNUNET_CONTAINER_heap_insert (plugin->defrag_ctxs, d_ctx,
2170         (GNUNET_CONTAINER_HeapCostType) now.abs_value_us);
2171     LOG(GNUNET_ERROR_TYPE_DEBUG,
2172         "Created new defragmentation context for %u-byte fragment from `%s'\n",
2173         (unsigned int ) ntohs (msg->size), GNUNET_a2s (addr, fromlen));
2174   }
2175   else
2176   {
2177     LOG(GNUNET_ERROR_TYPE_DEBUG,
2178         "Found existing defragmentation context for %u-byte fragment from `%s'\n",
2179         (unsigned int ) ntohs (msg->size), GNUNET_a2s (addr, fromlen));
2180   }
2181
2182   if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (d_ctx->defrag, msg))
2183   {
2184     /* keep this 'rc' from expiring */
2185     GNUNET_CONTAINER_heap_update_cost (plugin->defrag_ctxs, d_ctx->hnode,
2186         (GNUNET_CONTAINER_HeapCostType) now.abs_value_us);
2187   }
2188   if (GNUNET_CONTAINER_heap_get_size (plugin->defrag_ctxs) >
2189   UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
2190   {
2191     /* remove 'rc' that was inactive the longest */
2192     d_ctx = GNUNET_CONTAINER_heap_remove_root (plugin->defrag_ctxs);
2193     GNUNET_assert(NULL != d_ctx);
2194     GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
2195     GNUNET_free(d_ctx);
2196   }
2197 }
2198
2199 /**
2200  * Read and process a message from the given socket.
2201  *
2202  * @param plugin the overall plugin
2203  * @param rsock socket to read from
2204  */
2205 static void
2206 udp_select_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
2207 {
2208   socklen_t fromlen;
2209   struct sockaddr_storage addr;
2210   char buf[65536] GNUNET_ALIGN;
2211   ssize_t size;
2212   const struct GNUNET_MessageHeader *msg;
2213
2214   fromlen = sizeof(addr);
2215   memset (&addr, 0, sizeof(addr));
2216   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof(buf),
2217       (struct sockaddr *) &addr, &fromlen);
2218 #if MINGW
2219   /* On SOCK_DGRAM UDP sockets recvfrom might fail with a
2220    * WSAECONNRESET error to indicate that previous sendto() (yes, sendto!)
2221    * on this socket has failed.
2222    * Quote from MSDN:
2223    *   WSAECONNRESET - The virtual circuit was reset by the remote side
2224    *   executing a hard or abortive close. The application should close
2225    *   the socket; it is no longer usable. On a UDP-datagram socket this
2226    *   error indicates a previous send operation resulted in an ICMP Port
2227    *   Unreachable message.
2228    */
2229   if ( (-1 == size) && (ECONNRESET == errno) )
2230   return;
2231 #endif
2232   if (-1 == size)
2233   {
2234     LOG(GNUNET_ERROR_TYPE_DEBUG, "UDP failed to receive data: %s\n",
2235         STRERROR (errno));
2236     /* Connection failure or something. Not a protocol violation. */
2237     return;
2238   }
2239   if (size < sizeof(struct GNUNET_MessageHeader))
2240   {
2241     LOG(GNUNET_ERROR_TYPE_WARNING,
2242         "UDP got %u bytes, which is not enough for a GNUnet message header\n",
2243         (unsigned int ) size);
2244     /* _MAY_ be a connection failure (got partial message) */
2245     /* But it _MAY_ also be that the other side uses non-GNUnet protocol. */
2246     GNUNET_break_op(0);
2247     return;
2248   }
2249   msg = (const struct GNUNET_MessageHeader *) buf;
2250
2251   LOG(GNUNET_ERROR_TYPE_DEBUG,
2252       "UDP received %u-byte message from `%s' type %u\n", (unsigned int ) size,
2253       GNUNET_a2s ((const struct sockaddr * ) &addr, fromlen),
2254       ntohs (msg->type));
2255
2256   if (size != ntohs (msg->size))
2257   {
2258     GNUNET_break_op(0);
2259     return;
2260   }
2261
2262   GNUNET_STATISTICS_update (plugin->env->stats, "# UDP, total, bytes, received",
2263       size, GNUNET_NO);
2264
2265   switch (ntohs (msg->type))
2266   {
2267   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
2268     if (GNUNET_YES == plugin->enable_broadcasting_receiving)
2269       udp_broadcast_receive (plugin, buf, size, (const struct sockaddr *) &addr,
2270           fromlen);
2271     return;
2272   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
2273     read_process_msg (plugin, msg, (const struct sockaddr *) &addr, fromlen);
2274     return;
2275   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
2276     read_process_ack (plugin, msg, (const struct sockaddr *) &addr, fromlen);
2277     return;
2278   case GNUNET_MESSAGE_TYPE_FRAGMENT:
2279     read_process_fragment (plugin, msg, (const struct sockaddr *) &addr,
2280         fromlen);
2281     return;
2282   default:
2283     GNUNET_break_op(0);
2284     return;
2285   }
2286 }
2287
2288 static struct UDP_MessageWrapper *
2289 remove_timeout_messages_and_select (struct UDP_MessageWrapper *head,
2290     struct GNUNET_NETWORK_Handle *sock)
2291 {
2292   struct UDP_MessageWrapper *udpw = NULL;
2293   struct GNUNET_TIME_Relative remaining;
2294
2295   udpw = head;
2296   while (udpw != NULL )
2297   {
2298     /* Find messages with timeout */
2299     remaining = GNUNET_TIME_absolute_get_remaining (udpw->timeout);
2300     if (GNUNET_TIME_UNIT_ZERO.rel_value_us == remaining.rel_value_us)
2301     {
2302       /* Message timed out */
2303       switch (udpw->msg_type)
2304       {
2305       case MSG_UNFRAGMENTED:
2306         GNUNET_STATISTICS_update (plugin->env->stats,
2307             "# UDP, total, bytes, sent, timeout", udpw->msg_size, GNUNET_NO);
2308         GNUNET_STATISTICS_update (plugin->env->stats,
2309             "# UDP, total, messages, sent, timeout", 1, GNUNET_NO);
2310         GNUNET_STATISTICS_update (plugin->env->stats,
2311             "# UDP, unfragmented msgs, messages, sent, timeout", 1, GNUNET_NO);
2312         GNUNET_STATISTICS_update (plugin->env->stats,
2313             "# UDP, unfragmented msgs, bytes, sent, timeout",
2314             udpw->payload_size, GNUNET_NO);
2315         /* Not fragmented message */
2316         LOG(GNUNET_ERROR_TYPE_DEBUG,
2317             "Message for peer `%s' with size %u timed out\n",
2318             GNUNET_i2s (&udpw->session->target), udpw->payload_size);
2319         call_continuation (udpw, GNUNET_SYSERR);
2320         /* Remove message */
2321         dequeue (plugin, udpw);
2322         GNUNET_free(udpw);
2323         break;
2324       case MSG_FRAGMENTED:
2325         /* Fragmented message */
2326         GNUNET_STATISTICS_update (plugin->env->stats,
2327             "# UDP, total, bytes, sent, timeout", udpw->frag_ctx->on_wire_size,
2328             GNUNET_NO);
2329         GNUNET_STATISTICS_update (plugin->env->stats,
2330             "# UDP, total, messages, sent, timeout", 1, GNUNET_NO);
2331         call_continuation (udpw, GNUNET_SYSERR);
2332         LOG(GNUNET_ERROR_TYPE_DEBUG,
2333             "Fragment for message for peer `%s' with size %u timed out\n",
2334             GNUNET_i2s (&udpw->session->target), udpw->frag_ctx->payload_size);
2335
2336         GNUNET_STATISTICS_update (plugin->env->stats,
2337             "# UDP, fragmented msgs, messages, sent, timeout", 1, GNUNET_NO);
2338         GNUNET_STATISTICS_update (plugin->env->stats,
2339             "# UDP, fragmented msgs, bytes, sent, timeout",
2340             udpw->frag_ctx->payload_size, GNUNET_NO);
2341         /* Remove fragmented message due to timeout */
2342         fragmented_message_done (udpw->frag_ctx, GNUNET_SYSERR);
2343         break;
2344       case MSG_ACK:
2345         GNUNET_STATISTICS_update (plugin->env->stats,
2346             "# UDP, total, bytes, sent, timeout", udpw->msg_size, GNUNET_NO);
2347         GNUNET_STATISTICS_update (plugin->env->stats,
2348             "# UDP, total, messages, sent, timeout", 1, GNUNET_NO);
2349         LOG(GNUNET_ERROR_TYPE_DEBUG,
2350             "ACK Message for peer `%s' with size %u timed out\n",
2351             GNUNET_i2s (&udpw->session->target), udpw->payload_size);
2352         call_continuation (udpw, GNUNET_SYSERR);
2353         dequeue (plugin, udpw);
2354         GNUNET_free(udpw);
2355         break;
2356       default:
2357         break;
2358       }
2359       if (sock == plugin->sockv4)
2360         udpw = plugin->ipv4_queue_head;
2361       else if (sock == plugin->sockv6)
2362         udpw = plugin->ipv6_queue_head;
2363       else
2364       {
2365         GNUNET_break(0); /* should never happen */
2366         udpw = NULL;
2367       }
2368       GNUNET_STATISTICS_update (plugin->env->stats,
2369           "# messages dismissed due to timeout", 1, GNUNET_NO);
2370     }
2371     else
2372     {
2373       /* Message did not time out, check flow delay */
2374       remaining = GNUNET_TIME_absolute_get_remaining (
2375           udpw->session->flow_delay_from_other_peer);
2376       if (GNUNET_TIME_UNIT_ZERO.rel_value_us == remaining.rel_value_us)
2377       {
2378         /* this message is not delayed */
2379         LOG(GNUNET_ERROR_TYPE_DEBUG,
2380             "Message for peer `%s' (%u bytes) is not delayed \n",
2381             GNUNET_i2s (&udpw->session->target), udpw->payload_size);
2382         break; /* Found message to send, break */
2383       }
2384       else
2385       {
2386         /* Message is delayed, try next */
2387         LOG(GNUNET_ERROR_TYPE_DEBUG,
2388             "Message for peer `%s' (%u bytes) is delayed for %s\n",
2389             GNUNET_i2s (&udpw->session->target), udpw->payload_size,
2390             GNUNET_STRINGS_relative_time_to_string (remaining, GNUNET_YES));
2391         udpw = udpw->next;
2392       }
2393     }
2394   }
2395   return udpw;
2396 }
2397
2398 static void
2399 analyze_send_error (struct Plugin *plugin, const struct sockaddr * sa,
2400     socklen_t slen, int error)
2401 {
2402   static int network_down_error;
2403   struct GNUNET_ATS_Information type;
2404
2405   type = plugin->env->get_address_type (plugin->env->cls, sa, slen);
2406   if (((GNUNET_ATS_NET_LAN == ntohl (type.value))
2407       || (GNUNET_ATS_NET_WAN == ntohl (type.value)))
2408       && ((ENETUNREACH == errno)|| (ENETDOWN == errno)))
2409       {
2410         if ((network_down_error == GNUNET_NO) && (slen == sizeof (struct sockaddr_in)))
2411         {
2412           /* IPv4: "Network unreachable" or "Network down"
2413            *
2414            * This indicates we do not have connectivity
2415            */
2416           LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
2417               _("UDP could not transmit message to `%s': "
2418                   "Network seems down, please check your network configuration\n"),
2419               GNUNET_a2s (sa, slen));
2420         }
2421         if ((network_down_error == GNUNET_NO) && (slen == sizeof (struct sockaddr_in6)))
2422         {
2423           /* IPv6: "Network unreachable" or "Network down"
2424            *
2425            * This indicates that this system is IPv6 enabled, but does not
2426            * have a valid global IPv6 address assigned or we do not have
2427            * connectivity
2428            */
2429
2430           LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
2431               _("UDP could not transmit IPv6 message! "
2432                   "Please check your network configuration and disable IPv6 if your "
2433                   "connection does not have a global IPv6 address\n"));
2434         }
2435       }
2436       else
2437       {
2438         LOG (GNUNET_ERROR_TYPE_WARNING,
2439             "UDP could not transmit message to `%s': `%s'\n",
2440             GNUNET_a2s (sa, slen), STRERROR (error));
2441       }
2442     }
2443
2444 static size_t
2445 udp_select_send (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *sock)
2446 {
2447   const struct sockaddr * sa;
2448   ssize_t sent;
2449   socklen_t slen;
2450
2451   struct UDP_MessageWrapper *udpw = NULL;
2452
2453   /* Find message to send */
2454   udpw = remove_timeout_messages_and_select (
2455       (sock == plugin->sockv4) ?
2456           plugin->ipv4_queue_head : plugin->ipv6_queue_head, sock);
2457   if (NULL == udpw)
2458     return 0; /* No message to send */
2459
2460   sa = udpw->session->address->address;
2461   slen = udpw->session->address->address_length;
2462
2463   sent = GNUNET_NETWORK_socket_sendto (sock, udpw->msg_buf, udpw->msg_size, sa,
2464       slen);
2465
2466   if (GNUNET_SYSERR == sent)
2467   {
2468     /* Failure */
2469     analyze_send_error (plugin, sa, slen, errno);
2470     call_continuation (udpw, GNUNET_SYSERR);
2471     GNUNET_STATISTICS_update (plugin->env->stats,
2472         "# UDP, total, bytes, sent, failure", sent, GNUNET_NO);
2473     GNUNET_STATISTICS_update (plugin->env->stats,
2474         "# UDP, total, messages, sent, failure", 1, GNUNET_NO);
2475   }
2476   else
2477   {
2478     /* Success */
2479     LOG(GNUNET_ERROR_TYPE_DEBUG,
2480         "UDP transmitted %u-byte message to  `%s' `%s' (%d: %s)\n",
2481         (unsigned int ) (udpw->msg_size), GNUNET_i2s (&udpw->session->target),
2482         GNUNET_a2s (sa, slen), (int ) sent,
2483         (sent < 0) ? STRERROR (errno) : "ok");
2484     GNUNET_STATISTICS_update (plugin->env->stats,
2485         "# UDP, total, bytes, sent, success", sent, GNUNET_NO);
2486     GNUNET_STATISTICS_update (plugin->env->stats,
2487         "# UDP, total, messages, sent, success", 1, GNUNET_NO);
2488     if (NULL != udpw->frag_ctx)
2489       udpw->frag_ctx->on_wire_size += udpw->msg_size;
2490     call_continuation (udpw, GNUNET_OK);
2491   }
2492   dequeue (plugin, udpw);
2493   GNUNET_free(udpw);
2494   udpw = NULL;
2495
2496   return sent;
2497 }
2498
2499 /**
2500  * We have been notified that our readset has something to read.  We don't
2501  * know which socket needs to be read, so we have to check each one
2502  * Then reschedule this function to be called again once more is available.
2503  *
2504  * @param cls the plugin handle
2505  * @param tc the scheduling context (for rescheduling this function again)
2506  */
2507 static void
2508 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2509 {
2510   struct Plugin *plugin = cls;
2511
2512   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2513   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2514     return;
2515   if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
2516       && (NULL != plugin->sockv4)
2517       && (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
2518     udp_select_read (plugin, plugin->sockv4);
2519   if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY))
2520       && (NULL != plugin->sockv4) && (NULL != plugin->ipv4_queue_head)
2521       && (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv4)))
2522     udp_select_send (plugin, plugin->sockv4);
2523   schedule_select (plugin);
2524 }
2525
2526 /**
2527  * We have been notified that our readset has something to read.  We don't
2528  * know which socket needs to be read, so we have to check each one
2529  * Then reschedule this function to be called again once more is available.
2530  *
2531  * @param cls the plugin handle
2532  * @param tc the scheduling context (for rescheduling this function again)
2533  */
2534 static void
2535 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2536 {
2537   struct Plugin *plugin = cls;
2538
2539   plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2540   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2541     return;
2542   if (((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
2543       && (NULL != plugin->sockv6)
2544       && (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
2545     udp_select_read (plugin, plugin->sockv6);
2546   if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY))
2547       && (NULL != plugin->sockv6) && (plugin->ipv6_queue_head != NULL )&&
2548       (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv6)) )udp_select_send (plugin, plugin->sockv6);
2549   schedule_select (plugin);
2550 }
2551
2552 /**
2553  *
2554  * @return number of sockets that were successfully bound
2555  */
2556 static int
2557 setup_sockets (struct Plugin *plugin, const struct sockaddr_in6 *bind_v6,
2558     const struct sockaddr_in *bind_v4)
2559 {
2560   int tries;
2561   int sockets_created = 0;
2562   struct sockaddr_in6 server_addrv6;
2563   struct sockaddr_in server_addrv4;
2564   struct sockaddr *server_addr;
2565   struct sockaddr *addrs[2];
2566   socklen_t addrlens[2];
2567   socklen_t addrlen;
2568   int eno;
2569
2570   /* Create IPv6 socket */
2571   eno = EINVAL;
2572   if (plugin->enable_ipv6 == GNUNET_YES)
2573   {
2574     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
2575     if (NULL == plugin->sockv6)
2576     {
2577       LOG(GNUNET_ERROR_TYPE_WARNING,
2578           "Disabling IPv6 since it is not supported on this system!\n");
2579       plugin->enable_ipv6 = GNUNET_NO;
2580     }
2581     else
2582     {
2583       memset (&server_addrv6, '\0', sizeof(struct sockaddr_in6));
2584 #if HAVE_SOCKADDR_IN_SIN_LEN
2585       server_addrv6.sin6_len = sizeof (struct sockaddr_in6);
2586 #endif
2587       server_addrv6.sin6_family = AF_INET6;
2588       if (NULL != bind_v6)
2589         server_addrv6.sin6_addr = bind_v6->sin6_addr;
2590       else
2591         server_addrv6.sin6_addr = in6addr_any;
2592
2593       if (0 == plugin->port) /* autodetect */
2594         server_addrv6.sin6_port = htons (
2595             GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537)
2596                 + 32000);
2597       else
2598         server_addrv6.sin6_port = htons (plugin->port);
2599       addrlen = sizeof(struct sockaddr_in6);
2600       server_addr = (struct sockaddr *) &server_addrv6;
2601
2602       tries = 0;
2603       while (tries < 10)
2604       {
2605         LOG(GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 `%s'\n",
2606             GNUNET_a2s (server_addr, addrlen));
2607         /* binding */
2608         if (GNUNET_OK
2609             == GNUNET_NETWORK_socket_bind (plugin->sockv6, server_addr,
2610                 addrlen))
2611           break;
2612         eno = errno;
2613         if (0 != plugin->port)
2614         {
2615           tries = 10; /* fail */
2616           break; /* bind failed on specific port */
2617         }
2618         /* autodetect */
2619         server_addrv6.sin6_port = htons (
2620             GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537)
2621                 + 32000);
2622         tries++;
2623       }
2624       if (tries >= 10)
2625       {
2626         GNUNET_NETWORK_socket_close (plugin->sockv6);
2627         plugin->enable_ipv6 = GNUNET_NO;
2628         plugin->sockv6 = NULL;
2629       }
2630
2631       if (plugin->sockv6 != NULL )
2632       {
2633         LOG(GNUNET_ERROR_TYPE_DEBUG, "IPv6 socket created on port %s\n",
2634             GNUNET_a2s (server_addr, addrlen));
2635         addrs[sockets_created] = (struct sockaddr *) &server_addrv6;
2636         addrlens[sockets_created] = sizeof(struct sockaddr_in6);
2637         sockets_created++;
2638       }
2639       else
2640       {
2641         LOG(GNUNET_ERROR_TYPE_ERROR, "Failed to bind UDP socket to %s: %s\n",
2642             GNUNET_a2s (server_addr, addrlen), STRERROR (eno));
2643       }
2644     }
2645   }
2646
2647   /* Create IPv4 socket */
2648   eno = EINVAL;
2649   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
2650   if (NULL == plugin->sockv4)
2651   {
2652     GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "socket");
2653     LOG(GNUNET_ERROR_TYPE_WARNING,
2654         "Disabling IPv4 since it is not supported on this system!\n");
2655     plugin->enable_ipv4 = GNUNET_NO;
2656   }
2657   else
2658   {
2659     memset (&server_addrv4, '\0', sizeof(struct sockaddr_in));
2660 #if HAVE_SOCKADDR_IN_SIN_LEN
2661     server_addrv4.sin_len = sizeof (struct sockaddr_in);
2662 #endif
2663     server_addrv4.sin_family = AF_INET;
2664     if (NULL != bind_v4)
2665       server_addrv4.sin_addr = bind_v4->sin_addr;
2666     else
2667       server_addrv4.sin_addr.s_addr = INADDR_ANY;
2668
2669     if (0 == plugin->port)
2670       /* autodetect */
2671       server_addrv4.sin_port = htons (
2672           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537)
2673               + 32000);
2674     else
2675       server_addrv4.sin_port = htons (plugin->port);
2676
2677     addrlen = sizeof(struct sockaddr_in);
2678     server_addr = (struct sockaddr *) &server_addrv4;
2679
2680     tries = 0;
2681     while (tries < 10)
2682     {
2683       LOG(GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 `%s'\n",
2684           GNUNET_a2s (server_addr, addrlen));
2685
2686       /* binding */
2687       if (GNUNET_OK
2688           == GNUNET_NETWORK_socket_bind (plugin->sockv4, server_addr, addrlen))
2689         break;
2690       eno = errno;
2691       if (0 != plugin->port)
2692       {
2693         tries = 10; /* fail */
2694         break; /* bind failed on specific port */
2695       }
2696
2697       /* autodetect */
2698       server_addrv4.sin_port = htons (
2699           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537)
2700               + 32000);
2701       tries++;
2702     }
2703
2704     if (tries >= 10)
2705     {
2706       GNUNET_NETWORK_socket_close (plugin->sockv4);
2707       plugin->enable_ipv4 = GNUNET_NO;
2708       plugin->sockv4 = NULL;
2709     }
2710
2711     if (plugin->sockv4 != NULL )
2712     {
2713       LOG(GNUNET_ERROR_TYPE_DEBUG, "IPv4 socket created on port %s\n",
2714           GNUNET_a2s (server_addr, addrlen));
2715       addrs[sockets_created] = (struct sockaddr *) &server_addrv4;
2716       addrlens[sockets_created] = sizeof(struct sockaddr_in);
2717       sockets_created++;
2718     }
2719     else
2720     {
2721       LOG(GNUNET_ERROR_TYPE_ERROR, "Failed to bind UDP socket to %s: %s\n",
2722           GNUNET_a2s (server_addr, addrlen), STRERROR (eno));
2723     }
2724   }
2725
2726   if (0 == sockets_created)
2727   {
2728     LOG(GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
2729     return 0; /* No sockets created, return */
2730   }
2731
2732   /* Create file descriptors */
2733   if (plugin->enable_ipv4 == GNUNET_YES)
2734   {
2735     plugin->rs_v4 = GNUNET_NETWORK_fdset_create ();
2736     plugin->ws_v4 = GNUNET_NETWORK_fdset_create ();
2737     GNUNET_NETWORK_fdset_zero (plugin->rs_v4);
2738     GNUNET_NETWORK_fdset_zero (plugin->ws_v4);
2739     if (NULL != plugin->sockv4)
2740     {
2741       GNUNET_NETWORK_fdset_set (plugin->rs_v4, plugin->sockv4);
2742       GNUNET_NETWORK_fdset_set (plugin->ws_v4, plugin->sockv4);
2743     }
2744   }
2745
2746   if (plugin->enable_ipv6 == GNUNET_YES)
2747   {
2748     plugin->rs_v6 = GNUNET_NETWORK_fdset_create ();
2749     plugin->ws_v6 = GNUNET_NETWORK_fdset_create ();
2750     GNUNET_NETWORK_fdset_zero (plugin->rs_v6);
2751     GNUNET_NETWORK_fdset_zero (plugin->ws_v6);
2752     if (NULL != plugin->sockv6)
2753     {
2754       GNUNET_NETWORK_fdset_set (plugin->rs_v6, plugin->sockv6);
2755       GNUNET_NETWORK_fdset_set (plugin->ws_v6, plugin->sockv6);
2756     }
2757   }
2758
2759   schedule_select (plugin);
2760   plugin->nat = GNUNET_NAT_register (plugin->env->cfg, GNUNET_NO, plugin->port,
2761       sockets_created, (const struct sockaddr **) addrs, addrlens,
2762       &udp_nat_port_map_callback, NULL, plugin);
2763
2764   return sockets_created;
2765 }
2766
2767 /**
2768  * The exported method. Makes the core api available via a global and
2769  * returns the udp transport API.
2770  *
2771  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2772  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
2773  */
2774 void *
2775 libgnunet_plugin_transport_udp_init (void *cls)
2776 {
2777   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2778   struct GNUNET_TRANSPORT_PluginFunctions *api;
2779   struct Plugin *p;
2780   unsigned long long port;
2781   unsigned long long aport;
2782   unsigned long long udp_max_bps;
2783   unsigned long long enable_v6;
2784   unsigned long long enable_broadcasting;
2785   unsigned long long enable_broadcasting_recv;
2786   char * bind4_address;
2787   char * bind6_address;
2788   char * fancy_interval;
2789   struct GNUNET_TIME_Relative interval;
2790   struct sockaddr_in server_addrv4;
2791   struct sockaddr_in6 server_addrv6;
2792   int res;
2793   int have_bind4;
2794   int have_bind6;
2795
2796   if (NULL == env->receive)
2797   {
2798     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2799      initialze the plugin or the API */
2800     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2801     api->cls = NULL;
2802     api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2803     api->address_to_string = &udp_address_to_string;
2804     api->string_to_address = &udp_string_to_address;
2805     return api;
2806   }
2807
2808   GNUNET_assert(NULL != env->stats);
2809
2810   /* Get port number: port == 0 : autodetect a port,
2811    * > 0 : use this port, not given : 2086 default */
2812   if (GNUNET_OK
2813       != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2814           "PORT", &port))
2815     port = 2086;
2816   if (GNUNET_OK
2817       != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2818           "ADVERTISED_PORT", &aport))
2819     aport = port;
2820   if (port > 65535)
2821   {
2822     LOG(GNUNET_ERROR_TYPE_WARNING,
2823         _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
2824         65535);
2825     return NULL ;
2826   }
2827
2828   /* Protocols */
2829   if ((GNUNET_YES
2830       == GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat", "DISABLEV6")))
2831     enable_v6 = GNUNET_NO;
2832   else
2833     enable_v6 = GNUNET_YES;
2834
2835   /* Addresses */
2836   have_bind4 = GNUNET_NO;
2837   memset (&server_addrv4, 0, sizeof(server_addrv4));
2838   if (GNUNET_YES
2839       == GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2840           "BINDTO", &bind4_address))
2841   {
2842     LOG(GNUNET_ERROR_TYPE_DEBUG,
2843         "Binding udp plugin to specific address: `%s'\n", bind4_address);
2844     if (1 != inet_pton (AF_INET, bind4_address, &server_addrv4.sin_addr))
2845     {
2846       GNUNET_free(bind4_address);
2847       return NULL ;
2848     }
2849     have_bind4 = GNUNET_YES;
2850   }
2851   GNUNET_free_non_null(bind4_address);
2852   have_bind6 = GNUNET_NO;
2853   memset (&server_addrv6, 0, sizeof(server_addrv6));
2854   if (GNUNET_YES
2855       == GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2856           "BINDTO6", &bind6_address))
2857   {
2858     LOG(GNUNET_ERROR_TYPE_DEBUG,
2859         "Binding udp plugin to specific address: `%s'\n", bind6_address);
2860     if (1 != inet_pton (AF_INET6, bind6_address, &server_addrv6.sin6_addr))
2861     {
2862       LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
2863           bind6_address);
2864       GNUNET_free(bind6_address);
2865       return NULL ;
2866     }
2867     have_bind6 = GNUNET_YES;
2868   }
2869   GNUNET_free_non_null(bind6_address);
2870
2871   /* Initialize my flags */
2872   myoptions = 0;
2873
2874   /* Enable neighbour discovery */
2875   enable_broadcasting = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2876       "transport-udp", "BROADCAST");
2877   if (enable_broadcasting == GNUNET_SYSERR)
2878     enable_broadcasting = GNUNET_NO;
2879
2880   enable_broadcasting_recv = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2881       "transport-udp", "BROADCAST_RECEIVE");
2882   if (enable_broadcasting_recv == GNUNET_SYSERR)
2883     enable_broadcasting_recv = GNUNET_YES;
2884
2885   if (GNUNET_SYSERR
2886       == GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2887           "BROADCAST_INTERVAL", &fancy_interval))
2888   {
2889     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
2890   }
2891   else
2892   {
2893     if (GNUNET_SYSERR
2894         == GNUNET_STRINGS_fancy_time_to_relative (fancy_interval, &interval))
2895     {
2896       interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30);
2897     }
2898     GNUNET_free(fancy_interval);
2899   }
2900
2901   /* Maximum datarate */
2902   if (GNUNET_OK
2903       != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2904           "MAX_BPS", &udp_max_bps))
2905   {
2906     udp_max_bps = 1024 * 1024 * 50; /* 50 MB/s == infinity for practical purposes */
2907   }
2908
2909   p = GNUNET_new (struct Plugin);
2910   p->port = port;
2911   p->aport = aport;
2912   p->broadcast_interval = interval;
2913   p->enable_ipv6 = enable_v6;
2914   p->enable_ipv4 = GNUNET_YES; /* default */
2915   p->enable_broadcasting = enable_broadcasting;
2916   p->enable_broadcasting_receiving = enable_broadcasting_recv;
2917   p->env = env;
2918   p->sessions = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
2919   p->defrag_ctxs = GNUNET_CONTAINER_heap_create (
2920       GNUNET_CONTAINER_HEAP_ORDER_MIN);
2921   p->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, p);
2922   GNUNET_BANDWIDTH_tracker_init (&p->tracker,
2923       GNUNET_BANDWIDTH_value_init ((uint32_t) udp_max_bps), 30);
2924   plugin = p;
2925
2926   LOG(GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
2927   res = setup_sockets (p, (GNUNET_YES == have_bind6) ? &server_addrv6 : NULL,
2928       (GNUNET_YES == have_bind4) ? &server_addrv4 : NULL );
2929   if ((res == 0) || ((p->sockv4 == NULL )&& (p->sockv6 == NULL)))
2930   {
2931     LOG (GNUNET_ERROR_TYPE_ERROR,
2932         _("Failed to create network sockets, plugin failed\n"));
2933     GNUNET_CONTAINER_multipeermap_destroy (p->sessions);
2934     GNUNET_CONTAINER_heap_destroy (p->defrag_ctxs);
2935     GNUNET_SERVER_mst_destroy (p->mst);
2936     GNUNET_free (p);
2937     return NULL;
2938   }
2939
2940   /* Setup broadcasting and receiving beacons */
2941   setup_broadcast (p, &server_addrv6, &server_addrv4);
2942
2943   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2944   api->cls = p;
2945   api->send = NULL;
2946   api->disconnect_session = &udp_disconnect_session;
2947   api->query_keepalive_factor = &udp_query_keepalive_factor;
2948   api->disconnect_peer = &udp_disconnect;
2949   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2950   api->address_to_string = &udp_address_to_string;
2951   api->string_to_address = &udp_string_to_address;
2952   api->check_address = &udp_plugin_check_address;
2953   api->get_session = &udp_plugin_get_session;
2954   api->send = &udp_plugin_send;
2955   api->get_network = &udp_get_network;
2956   api->update_session_timeout = &udp_plugin_update_session_timeout;
2957   return api;
2958 }
2959
2960 static int
2961 heap_cleanup_iterator (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
2962     void *element, GNUNET_CONTAINER_HeapCostType cost)
2963 {
2964   struct DefragContext * d_ctx = element;
2965
2966   GNUNET_CONTAINER_heap_remove_node (node);
2967   GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
2968   GNUNET_free(d_ctx);
2969
2970   return GNUNET_YES;
2971 }
2972
2973 /**
2974  * The exported method. Makes the core api available via a global and
2975  * returns the udp transport API.
2976  *
2977  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2978  * @return NULL
2979  */
2980 void *
2981 libgnunet_plugin_transport_udp_done (void *cls)
2982 {
2983   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2984   struct Plugin *plugin = api->cls;
2985   struct PrettyPrinterContext *cur;
2986   struct PrettyPrinterContext *next;
2987
2988   if (NULL == plugin)
2989   {
2990     GNUNET_free(api);
2991     return NULL ;
2992   }
2993
2994   stop_broadcast (plugin);
2995   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK )
2996   {
2997     GNUNET_SCHEDULER_cancel (plugin->select_task);
2998     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2999   }
3000   if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK )
3001   {
3002     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
3003     plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
3004   }
3005
3006   /* Closing sockets */
3007   if (GNUNET_YES == plugin->enable_ipv4)
3008   {
3009     if (NULL != plugin->sockv4)
3010     {
3011       GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
3012       plugin->sockv4 = NULL;
3013     }
3014     GNUNET_NETWORK_fdset_destroy (plugin->rs_v4);
3015     GNUNET_NETWORK_fdset_destroy (plugin->ws_v4);
3016   }
3017   if (GNUNET_YES == plugin->enable_ipv6)
3018   {
3019     if (NULL != plugin->sockv6)
3020     {
3021       GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
3022       plugin->sockv6 = NULL;
3023
3024       GNUNET_NETWORK_fdset_destroy (plugin->rs_v6);
3025       GNUNET_NETWORK_fdset_destroy (plugin->ws_v6);
3026     }
3027   }
3028   if (NULL != plugin->nat)
3029   {
3030     GNUNET_NAT_unregister (plugin->nat);
3031     plugin->nat = NULL;
3032   }
3033   if (NULL != plugin->defrag_ctxs)
3034   {
3035     GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs, heap_cleanup_iterator,
3036         NULL );
3037     GNUNET_CONTAINER_heap_destroy (plugin->defrag_ctxs);
3038     plugin->defrag_ctxs = NULL;
3039   }
3040   if (plugin->mst != NULL )
3041   {
3042     GNUNET_SERVER_mst_destroy (plugin->mst);
3043     plugin->mst = NULL;
3044   }
3045
3046   /* Clean up leftover messages */
3047   struct UDP_MessageWrapper * udpw;
3048   udpw = plugin->ipv4_queue_head;
3049   while (udpw != NULL )
3050   {
3051     struct UDP_MessageWrapper *tmp = udpw->next;
3052     dequeue (plugin, udpw);
3053     call_continuation (udpw, GNUNET_SYSERR);
3054     GNUNET_free(udpw);
3055
3056     udpw = tmp;
3057   }
3058   udpw = plugin->ipv6_queue_head;
3059   while (udpw != NULL )
3060   {
3061     struct UDP_MessageWrapper *tmp = udpw->next;
3062     dequeue (plugin, udpw);
3063     call_continuation (udpw, GNUNET_SYSERR);
3064     GNUNET_free(udpw);
3065
3066     udpw = tmp;
3067   }
3068
3069   /* Clean up sessions */
3070   LOG(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up sessions\n");
3071   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3072       &disconnect_and_free_it, plugin);
3073   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
3074
3075   next = ppc_dll_head;
3076   for (cur = next; NULL != cur; cur = next)
3077   {
3078     next = cur->next;
3079     GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, cur);
3080     GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
3081     GNUNET_SCHEDULER_cancel (cur->timeout_task);
3082     GNUNET_free(cur);
3083     GNUNET_break(0);
3084   }
3085
3086   plugin->nat = NULL;
3087   GNUNET_free(plugin);
3088   GNUNET_free(api);
3089 #if DEBUG_MALLOC
3090   struct Allocation *allocation;
3091   while (NULL != ahead)
3092   {
3093     allocation = ahead;
3094     GNUNET_CONTAINER_DLL_remove (ahead, atail, allocation);
3095     GNUNET_free (allocation);
3096   }
3097   struct Allocator *allocator;
3098   while (NULL != aehead)
3099   {
3100     allocator = aehead;
3101     GNUNET_CONTAINER_DLL_remove (aehead, aetail, allocator);
3102     GNUNET_free (allocator);
3103   }
3104 #endif
3105   return NULL ;
3106 }
3107
3108 /* end of plugin_transport_udp.c */