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