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