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