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