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