Merge branch 'master' of gnunet.org:gnunet
[oweals/gnunet.git] / src / transport / plugin_transport_udp.c
1 /*
2  This file is part of GNUnet
3  Copyright (C) 2010-2017 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18  Boston, MA 02110-1301, 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_service.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 /**
46  * After how much inactivity should a UDP session time out?
47  */
48 #define UDP_SESSION_TIME_OUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
49
50 /**
51  * Number of messages we can defragment in parallel.  We only really
52  * defragment 1 message at a time, but if messages get re-ordered, we
53  * may want to keep knowledge about the previous message to avoid
54  * discarding the current message in favor of a single fragment of a
55  * previous message.  3 should be good since we don't expect massive
56  * message reorderings with UDP.
57  */
58 #define UDP_MAX_MESSAGES_IN_DEFRAG 3
59
60 /**
61  * We keep a defragmentation queue per sender address.  How many
62  * sender addresses do we support at the same time? Memory consumption
63  * is roughly a factor of 32k * #UDP_MAX_MESSAGES_IN_DEFRAG times this
64  * value. (So 128 corresponds to 12 MB and should suffice for
65  * connecting to roughly 128 peers via UDP).
66  */
67 #define UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG 128
68
69
70 /**
71  * UDP Message-Packet header (after defragmentation).
72  */
73 struct UDPMessage
74 {
75   /**
76    * Message header.
77    */
78   struct GNUNET_MessageHeader header;
79
80   /**
81    * Always zero for now.
82    */
83   uint32_t reserved;
84
85   /**
86    * What is the identity of the sender
87    */
88   struct GNUNET_PeerIdentity sender;
89
90 };
91
92
93 /**
94  * Closure for #append_port().
95  */
96 struct PrettyPrinterContext
97 {
98   /**
99    * DLL
100    */
101   struct PrettyPrinterContext *next;
102
103   /**
104    * DLL
105    */
106   struct PrettyPrinterContext *prev;
107
108   /**
109    * Our plugin.
110    */
111   struct Plugin *plugin;
112
113   /**
114    * Resolver handle
115    */
116   struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
117
118   /**
119    * Function to call with the result.
120    */
121   GNUNET_TRANSPORT_AddressStringCallback asc;
122
123   /**
124    * Clsoure for @e asc.
125    */
126   void *asc_cls;
127
128   /**
129    * Timeout task
130    */
131   struct GNUNET_SCHEDULER_Task *timeout_task;
132
133   /**
134    * Is this an IPv6 address?
135    */
136   int ipv6;
137
138   /**
139    * Options
140    */
141   uint32_t options;
142
143   /**
144    * Port to add after the IP address.
145    */
146   uint16_t port;
147
148 };
149
150
151 /**
152  * Session with another peer.
153  */
154 struct GNUNET_ATS_Session
155 {
156   /**
157    * Which peer is this session for?
158    */
159   struct GNUNET_PeerIdentity target;
160
161   /**
162    * Tokenizer for inbound messages.
163    */
164   struct GNUNET_MessageStreamTokenizer *mst;
165
166   /**
167    * Plugin this session belongs to.
168    */
169   struct Plugin *plugin;
170
171   /**
172    * Context for dealing with fragments.
173    */
174   struct UDP_FragmentationContext *frag_ctx;
175
176   /**
177    * Desired delay for next sending we send to other peer
178    */
179   struct GNUNET_TIME_Relative flow_delay_for_other_peer;
180
181   /**
182    * Desired delay for transmissions we received from other peer.
183    * This is for full messages, the value needs to be adjusted for
184    * fragmented messages.
185    */
186   struct GNUNET_TIME_Relative flow_delay_from_other_peer;
187
188   /**
189    * Session timeout task
190    */
191   struct GNUNET_SCHEDULER_Task *timeout_task;
192
193   /**
194    * When does this session time out?
195    */
196   struct GNUNET_TIME_Absolute timeout;
197
198   /**
199    * What time did we last transmit?
200    */
201   struct GNUNET_TIME_Absolute last_transmit_time;
202
203   /**
204    * expected delay for ACKs
205    */
206   struct GNUNET_TIME_Relative last_expected_ack_delay;
207
208   /**
209    * desired delay between UDP messages
210    */
211   struct GNUNET_TIME_Relative last_expected_msg_delay;
212
213   /**
214    * Our own address.
215    */
216   struct GNUNET_HELLO_Address *address;
217
218   /**
219    * Number of bytes waiting for transmission to this peer.
220    */
221   unsigned long long bytes_in_queue;
222
223   /**
224    * Number of messages waiting for transmission to this peer.
225    */
226   unsigned int msgs_in_queue;
227
228   /**
229    * Reference counter to indicate that this session is
230    * currently being used and must not be destroyed;
231    * setting @e in_destroy will destroy it as soon as
232    * possible.
233    */
234   unsigned int rc;
235
236   /**
237    * Network type of the address.
238    */
239   enum GNUNET_ATS_Network_Type scope;
240
241   /**
242    * Is this session about to be destroyed (sometimes we cannot
243    * destroy a session immediately as below us on the stack
244    * there might be code that still uses it; in this case,
245    * @e rc is non-zero).
246    */
247   int in_destroy;
248 };
249
250
251
252 /**
253  * Data structure to track defragmentation contexts based
254  * on the source of the UDP traffic.
255  */
256 struct DefragContext
257 {
258
259   /**
260    * Defragmentation context.
261    */
262   struct GNUNET_DEFRAGMENT_Context *defrag;
263
264   /**
265    * Reference to master plugin struct.
266    */
267   struct Plugin *plugin;
268
269   /**
270    * Node in the defrag heap.
271    */
272   struct GNUNET_CONTAINER_HeapNode *hnode;
273
274   /**
275    * Source address this receive context is for (allocated at the
276    * end of the struct).
277    */
278   const union UdpAddress *udp_addr;
279
280   /**
281    * Who's message(s) are we defragmenting here?
282    * Only initialized once we succeeded and
283    * @e have_sender is set.
284    */
285   struct GNUNET_PeerIdentity sender;
286
287   /**
288    * Length of @e udp_addr.
289    */
290   size_t udp_addr_len;
291
292   /**
293    * Network type the address belongs to.
294    */
295   enum GNUNET_ATS_Network_Type network_type;
296
297   /**
298    * Has the @e sender field been initialized yet?
299    */
300   int have_sender;
301 };
302
303
304 /**
305  * Context to send fragmented messages
306  */
307 struct UDP_FragmentationContext
308 {
309   /**
310    * Next in linked list
311    */
312   struct UDP_FragmentationContext *next;
313
314   /**
315    * Previous in linked list
316    */
317   struct UDP_FragmentationContext *prev;
318
319   /**
320    * The plugin
321    */
322   struct Plugin *plugin;
323
324   /**
325    * Handle for fragmentation.
326    */
327   struct GNUNET_FRAGMENT_Context *frag;
328
329   /**
330    * The session this fragmentation context belongs to
331    */
332   struct GNUNET_ATS_Session *session;
333
334   /**
335    * Function to call upon completion of the transmission.
336    */
337   GNUNET_TRANSPORT_TransmitContinuation cont;
338
339   /**
340    * Closure for @e cont.
341    */
342   void *cont_cls;
343
344   /**
345    * Start time.
346    */
347   struct GNUNET_TIME_Absolute start_time;
348
349   /**
350    * Transmission time for the next fragment.  Incremented by
351    * the @e flow_delay_from_other_peer for each fragment when
352    * we setup the fragments.
353    */
354   struct GNUNET_TIME_Absolute next_frag_time;
355
356   /**
357    * Desired delay for transmissions we received from other peer.
358    * Adjusted to be per fragment (UDP_MTU), even though on the
359    * wire it was for "full messages".
360    */
361   struct GNUNET_TIME_Relative flow_delay_from_other_peer;
362
363   /**
364    * Message timeout
365    */
366   struct GNUNET_TIME_Absolute timeout;
367
368   /**
369    * Payload size of original unfragmented message
370    */
371   size_t payload_size;
372
373   /**
374    * Bytes used to send all fragments on wire including UDP overhead
375    */
376   size_t on_wire_size;
377
378 };
379
380
381 /**
382  * Function called when a message is removed from the
383  * transmission queue.
384  *
385  * @param cls closure
386  * @param udpw message wrapper finished
387  * @param result #GNUNET_OK on success (message was sent)
388  *               #GNUNET_SYSERR if the target disconnected
389  *               or we had a timeout or other trouble sending
390  */
391 typedef void
392 (*QueueContinuation) (void *cls,
393                       struct UDP_MessageWrapper *udpw,
394                       int result);
395
396
397 /**
398  * Information we track for each message in the queue.
399  */
400 struct UDP_MessageWrapper
401 {
402   /**
403    * Session this message belongs to
404    */
405   struct GNUNET_ATS_Session *session;
406
407   /**
408    * DLL of messages, previous element
409    */
410   struct UDP_MessageWrapper *prev;
411
412   /**
413    * DLL of messages, next element
414    */
415   struct UDP_MessageWrapper *next;
416
417   /**
418    * Message with @e msg_size bytes including UDP-specific overhead.
419    */
420   char *msg_buf;
421
422   /**
423    * Function to call once the message wrapper is being removed
424    * from the queue (with success or failure).
425    */
426   QueueContinuation qc;
427
428   /**
429    * Closure for @e qc.
430    */
431   void *qc_cls;
432
433   /**
434    * External continuation to call upon completion of the
435    * transmission, NULL if this queue entry is not for a
436    * message from the application.
437    */
438   GNUNET_TRANSPORT_TransmitContinuation cont;
439
440   /**
441    * Closure for @e cont.
442    */
443   void *cont_cls;
444
445   /**
446    * Fragmentation context.
447    * frag_ctx == NULL if transport <= MTU
448    * frag_ctx != NULL if transport > MTU
449    */
450   struct UDP_FragmentationContext *frag_ctx;
451
452   /**
453    * Message enqueue time.
454    */
455   struct GNUNET_TIME_Absolute start_time;
456
457   /**
458    * Desired transmission time for this message, based on the
459    * flow limiting information we got from the other peer.
460    */
461   struct GNUNET_TIME_Absolute transmission_time;
462
463   /**
464    * Message timeout.
465    */
466   struct GNUNET_TIME_Absolute timeout;
467
468   /**
469    * Size of UDP message to send, including UDP-specific overhead.
470    */
471   size_t msg_size;
472
473   /**
474    * Payload size of original message.
475    */
476   size_t payload_size;
477
478 };
479
480
481 GNUNET_NETWORK_STRUCT_BEGIN
482
483 /**
484  * UDP ACK Message-Packet header.
485  */
486 struct UDP_ACK_Message
487 {
488   /**
489    * Message header.
490    */
491   struct GNUNET_MessageHeader header;
492
493   /**
494    * Desired delay for flow control, in us (in NBO).
495    * A value of UINT32_MAX indicates that the other
496    * peer wants us to disconnect.
497    */
498   uint32_t delay GNUNET_PACKED;
499
500   /**
501    * What is the identity of the sender
502    */
503   struct GNUNET_PeerIdentity sender;
504
505 };
506
507 GNUNET_NETWORK_STRUCT_END
508
509
510 /* ************************* Monitoring *********** */
511
512
513 /**
514  * If a session monitor is attached, notify it about the new
515  * session state.
516  *
517  * @param plugin our plugin
518  * @param session session that changed state
519  * @param state new state of the session
520  */
521 static void
522 notify_session_monitor (struct Plugin *plugin,
523                         struct GNUNET_ATS_Session *session,
524                         enum GNUNET_TRANSPORT_SessionState state)
525 {
526   struct GNUNET_TRANSPORT_SessionInfo info;
527
528   if (NULL == plugin->sic)
529     return;
530   if (GNUNET_YES == session->in_destroy)
531     return; /* already destroyed, just RC>0 left-over actions */
532   memset (&info,
533           0,
534           sizeof (info));
535   info.state = state;
536   info.is_inbound = GNUNET_SYSERR; /* hard to say */
537   info.num_msg_pending = session->msgs_in_queue;
538   info.num_bytes_pending = session->bytes_in_queue;
539   /* info.receive_delay remains zero as this is not supported by UDP
540      (cannot selectively not receive from 'some' peer while continuing
541      to receive from others) */
542   info.session_timeout = session->timeout;
543   info.address = session->address;
544   plugin->sic (plugin->sic_cls,
545                session,
546                &info);
547 }
548
549
550 /**
551  * Return information about the given session to the monitor callback.
552  *
553  * @param cls the `struct Plugin` with the monitor callback (`sic`)
554  * @param peer peer we send information about
555  * @param value our `struct GNUNET_ATS_Session` to send information about
556  * @return #GNUNET_OK (continue to iterate)
557  */
558 static int
559 send_session_info_iter (void *cls,
560                         const struct GNUNET_PeerIdentity *peer,
561                         void *value)
562 {
563   struct Plugin *plugin = cls;
564   struct GNUNET_ATS_Session *session = value;
565
566   notify_session_monitor (plugin,
567                           session,
568                           GNUNET_TRANSPORT_SS_INIT);
569   notify_session_monitor (plugin,
570                           session,
571                           GNUNET_TRANSPORT_SS_UP);
572   return GNUNET_OK;
573 }
574
575
576 /**
577  * Begin monitoring sessions of a plugin.  There can only
578  * be one active monitor per plugin (i.e. if there are
579  * multiple monitors, the transport service needs to
580  * multiplex the generated events over all of them).
581  *
582  * @param cls closure of the plugin
583  * @param sic callback to invoke, NULL to disable monitor;
584  *            plugin will being by iterating over all active
585  *            sessions immediately and then enter monitor mode
586  * @param sic_cls closure for @a sic
587  */
588 static void
589 udp_plugin_setup_monitor (void *cls,
590                           GNUNET_TRANSPORT_SessionInfoCallback sic,
591                           void *sic_cls)
592 {
593   struct Plugin *plugin = cls;
594
595   plugin->sic = sic;
596   plugin->sic_cls = sic_cls;
597   if (NULL != sic)
598   {
599     GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
600                                            &send_session_info_iter,
601                                            plugin);
602     /* signal end of first iteration */
603     sic (sic_cls,
604          NULL,
605          NULL);
606   }
607 }
608
609
610 /* ****************** Little Helpers ****************** */
611
612
613 /**
614  * Function to free last resources associated with a session.
615  *
616  * @param s session to free
617  */
618 static void
619 free_session (struct GNUNET_ATS_Session *s)
620 {
621   if (NULL != s->address)
622   {
623     GNUNET_HELLO_address_free (s->address);
624     s->address = NULL;
625   }
626   if (NULL != s->frag_ctx)
627   {
628     GNUNET_FRAGMENT_context_destroy (s->frag_ctx->frag,
629                                      NULL,
630                                      NULL);
631     GNUNET_free (s->frag_ctx);
632     s->frag_ctx = NULL;
633   }
634   if (NULL != s->mst)
635   {
636     GNUNET_MST_destroy (s->mst);
637     s->mst = NULL;
638   }
639   GNUNET_free (s);
640 }
641
642
643 /**
644  * Function that is called to get the keepalive factor.
645  * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
646  * calculate the interval between keepalive packets.
647  *
648  * @param cls closure with the `struct Plugin`
649  * @return keepalive factor
650  */
651 static unsigned int
652 udp_query_keepalive_factor (void *cls)
653 {
654   return 15;
655 }
656
657
658 /**
659  * Function obtain the network type for a session
660  *
661  * @param cls closure (`struct Plugin *`)
662  * @param session the session
663  * @return the network type
664  */
665 static enum GNUNET_ATS_Network_Type
666 udp_plugin_get_network (void *cls,
667                         struct GNUNET_ATS_Session *session)
668 {
669   return session->scope;
670 }
671
672
673 /**
674  * Function obtain the network type for an address.
675  *
676  * @param cls closure (`struct Plugin *`)
677  * @param address the address
678  * @return the network type
679  */
680 static enum GNUNET_ATS_Network_Type
681 udp_plugin_get_network_for_address (void *cls,
682                                     const struct GNUNET_HELLO_Address *address)
683 {
684   struct Plugin *plugin = cls;
685   size_t addrlen;
686   struct sockaddr_in a4;
687   struct sockaddr_in6 a6;
688   const struct IPv4UdpAddress *u4;
689   const struct IPv6UdpAddress *u6;
690   const void *sb;
691   size_t sbs;
692
693   addrlen = address->address_length;
694   if (addrlen == sizeof(struct IPv6UdpAddress))
695   {
696     GNUNET_assert (NULL != address->address); /* make static analysis happy */
697     u6 = address->address;
698     memset (&a6, 0, sizeof(a6));
699 #if HAVE_SOCKADDR_IN_SIN_LEN
700     a6.sin6_len = sizeof (a6);
701 #endif
702     a6.sin6_family = AF_INET6;
703     a6.sin6_port = u6->u6_port;
704     GNUNET_memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof(struct in6_addr));
705     sb = &a6;
706     sbs = sizeof(a6);
707   }
708   else if (addrlen == sizeof(struct IPv4UdpAddress))
709   {
710     GNUNET_assert (NULL != address->address); /* make static analysis happy */
711     u4 = address->address;
712     memset (&a4, 0, sizeof(a4));
713 #if HAVE_SOCKADDR_IN_SIN_LEN
714     a4.sin_len = sizeof (a4);
715 #endif
716     a4.sin_family = AF_INET;
717     a4.sin_port = u4->u4_port;
718     a4.sin_addr.s_addr = u4->ipv4_addr;
719     sb = &a4;
720     sbs = sizeof(a4);
721   }
722   else
723   {
724     GNUNET_break (0);
725     return GNUNET_ATS_NET_UNSPECIFIED;
726   }
727   return plugin->env->get_address_type (plugin->env->cls,
728                                         sb,
729                                         sbs);
730 }
731
732
733 /* ******************* Event loop ******************** */
734
735 /**
736  * We have been notified that our readset has something to read.  We don't
737  * know which socket needs to be read, so we have to check each one
738  * Then reschedule this function to be called again once more is available.
739  *
740  * @param cls the plugin handle
741  */
742 static void
743 udp_plugin_select_v4 (void *cls);
744
745
746 /**
747  * We have been notified that our readset has something to read.  We don't
748  * know which socket needs to be read, so we have to check each one
749  * Then reschedule this function to be called again once more is available.
750  *
751  * @param cls the plugin handle
752  */
753 static void
754 udp_plugin_select_v6 (void *cls);
755
756
757 /**
758  * (re)schedule IPv4-select tasks for this plugin.
759  *
760  * @param plugin plugin to reschedule
761  */
762 static void
763 schedule_select_v4 (struct Plugin *plugin)
764 {
765   struct GNUNET_TIME_Relative min_delay;
766   struct GNUNET_TIME_Relative delay;
767   struct UDP_MessageWrapper *udpw;
768   struct UDP_MessageWrapper *min_udpw;
769
770   if ( (GNUNET_YES == plugin->enable_ipv4) &&
771        (NULL != plugin->sockv4) )
772   {
773     /* Find a message ready to send:
774      * Flow delay from other peer is expired or not set (0) */
775     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
776     min_udpw = NULL;
777     for (udpw = plugin->ipv4_queue_head; NULL != udpw; udpw = udpw->next)
778     {
779       delay = GNUNET_TIME_absolute_get_remaining (udpw->transmission_time);
780       if (delay.rel_value_us < min_delay.rel_value_us)
781       {
782         min_delay = delay;
783         min_udpw = udpw;
784       }
785     }
786     if (NULL != plugin->select_task_v4)
787       GNUNET_SCHEDULER_cancel (plugin->select_task_v4);
788     if (NULL != min_udpw)
789     {
790       if (min_delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
791       {
792         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
793                     "Calculated flow delay for UDPv4 at %s for %s\n",
794                     GNUNET_STRINGS_relative_time_to_string (min_delay,
795                                                             GNUNET_YES),
796                     GNUNET_i2s (&min_udpw->session->target));
797       }
798       else
799       {
800         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801                     "Calculated flow delay for UDPv4 at %s for %s\n",
802                     GNUNET_STRINGS_relative_time_to_string (min_delay,
803                                                             GNUNET_YES),
804                     GNUNET_i2s (&min_udpw->session->target));
805       }
806     }
807     plugin->select_task_v4
808       = GNUNET_SCHEDULER_add_read_net (min_delay,
809                                        plugin->sockv4,
810                                        &udp_plugin_select_v4,
811                                        plugin);
812   }
813 }
814
815
816 /**
817  * (re)schedule IPv6-select tasks for this plugin.
818  *
819  * @param plugin plugin to reschedule
820  */
821 static void
822 schedule_select_v6 (struct Plugin *plugin)
823 {
824   struct GNUNET_TIME_Relative min_delay;
825   struct GNUNET_TIME_Relative delay;
826   struct UDP_MessageWrapper *udpw;
827   struct UDP_MessageWrapper *min_udpw;
828
829   if ( (GNUNET_YES == plugin->enable_ipv6) &&
830        (NULL != plugin->sockv6) )
831   {
832     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
833     min_udpw = NULL;
834     for (udpw = plugin->ipv6_queue_head; NULL != udpw; udpw = udpw->next)
835     {
836       delay = GNUNET_TIME_absolute_get_remaining (udpw->transmission_time);
837       if (delay.rel_value_us < min_delay.rel_value_us)
838       {
839         min_delay = delay;
840         min_udpw = udpw;
841       }
842     }
843     if (NULL != plugin->select_task_v6)
844       GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
845     if (NULL != min_udpw)
846     {
847       if (min_delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
848       {
849         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
850                     "Calculated flow delay for UDPv6 at %s for %s\n",
851                     GNUNET_STRINGS_relative_time_to_string (min_delay,
852                                                             GNUNET_YES),
853                     GNUNET_i2s (&min_udpw->session->target));
854       }
855       else
856       {
857         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
858                     "Calculated flow delay for UDPv6 at %s for %s\n",
859                     GNUNET_STRINGS_relative_time_to_string (min_delay,
860                                                             GNUNET_YES),
861                     GNUNET_i2s (&min_udpw->session->target));
862       }
863     }
864     plugin->select_task_v6
865       = GNUNET_SCHEDULER_add_read_net (min_delay,
866                                        plugin->sockv6,
867                                        &udp_plugin_select_v6,
868                                        plugin);
869   }
870 }
871
872
873 /* ******************* Address to string and back ***************** */
874
875
876 /**
877  * Function called for a quick conversion of the binary address to
878  * a numeric address.  Note that the caller must not free the
879  * address and that the next call to this function is allowed
880  * to override the address again.
881  *
882  * @param cls closure
883  * @param addr binary address (a `union UdpAddress`)
884  * @param addrlen length of the @a addr
885  * @return string representing the same address
886  */
887 const char *
888 udp_address_to_string (void *cls,
889                        const void *addr,
890                        size_t addrlen)
891 {
892   static char rbuf[INET6_ADDRSTRLEN + 10];
893   char buf[INET6_ADDRSTRLEN];
894   const void *sb;
895   struct in_addr a4;
896   struct in6_addr a6;
897   const struct IPv4UdpAddress *t4;
898   const struct IPv6UdpAddress *t6;
899   int af;
900   uint16_t port;
901   uint32_t options;
902
903   if (NULL == addr)
904   {
905     GNUNET_break_op (0);
906     return NULL;
907   }
908
909   if (addrlen == sizeof(struct IPv6UdpAddress))
910   {
911     t6 = addr;
912     af = AF_INET6;
913     options = ntohl (t6->options);
914     port = ntohs (t6->u6_port);
915     a6 = t6->ipv6_addr;
916     sb = &a6;
917   }
918   else if (addrlen == sizeof(struct IPv4UdpAddress))
919   {
920     t4 = addr;
921     af = AF_INET;
922     options = ntohl (t4->options);
923     port = ntohs (t4->u4_port);
924     a4.s_addr = t4->ipv4_addr;
925     sb = &a4;
926   }
927   else
928   {
929     GNUNET_break_op (0);
930     return NULL;
931   }
932   inet_ntop (af,
933              sb,
934              buf,
935              INET6_ADDRSTRLEN);
936   GNUNET_snprintf (rbuf,
937                    sizeof(rbuf),
938                    (af == AF_INET6)
939                    ? "%s.%u.[%s]:%u"
940                    : "%s.%u.%s:%u",
941                    PLUGIN_NAME,
942                    options,
943                    buf,
944                    port);
945   return rbuf;
946 }
947
948
949 /**
950  * Function called to convert a string address to a binary address.
951  *
952  * @param cls closure (`struct Plugin *`)
953  * @param addr string address
954  * @param addrlen length of the address
955  * @param buf location to store the buffer
956  * @param added location to store the number of bytes in the buffer.
957  *        If the function returns #GNUNET_SYSERR, its contents are undefined.
958  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
959  */
960 static int
961 udp_string_to_address (void *cls,
962                        const char *addr,
963                        uint16_t addrlen,
964                        void **buf,
965                        size_t *added)
966 {
967   struct sockaddr_storage socket_address;
968   char *address;
969   char *plugin;
970   char *optionstr;
971   uint32_t options;
972
973   /* Format tcp.options.address:port */
974   address = NULL;
975   plugin = NULL;
976   optionstr = NULL;
977
978   if ((NULL == addr) || (0 == addrlen))
979   {
980     GNUNET_break (0);
981     return GNUNET_SYSERR;
982   }
983   if ('\0' != addr[addrlen - 1])
984   {
985     GNUNET_break (0);
986     return GNUNET_SYSERR;
987   }
988   if (strlen (addr) != addrlen - 1)
989   {
990     GNUNET_break (0);
991     return GNUNET_SYSERR;
992   }
993   plugin = GNUNET_strdup (addr);
994   optionstr = strchr (plugin, '.');
995   if (NULL == optionstr)
996   {
997     GNUNET_break (0);
998     GNUNET_free (plugin);
999     return GNUNET_SYSERR;
1000   }
1001   optionstr[0] = '\0';
1002   optionstr++;
1003   options = atol (optionstr);
1004   address = strchr (optionstr, '.');
1005   if (NULL == address)
1006   {
1007     GNUNET_break (0);
1008     GNUNET_free (plugin);
1009     return GNUNET_SYSERR;
1010   }
1011   address[0] = '\0';
1012   address++;
1013
1014   if (GNUNET_OK !=
1015       GNUNET_STRINGS_to_address_ip (address,
1016                                     strlen (address),
1017                                     &socket_address))
1018   {
1019     GNUNET_break (0);
1020     GNUNET_free (plugin);
1021     return GNUNET_SYSERR;
1022   }
1023   GNUNET_free(plugin);
1024
1025   switch (socket_address.ss_family)
1026   {
1027   case AF_INET:
1028     {
1029       struct IPv4UdpAddress *u4;
1030       const struct sockaddr_in *in4 = (const struct sockaddr_in *) &socket_address;
1031
1032       u4 = GNUNET_new (struct IPv4UdpAddress);
1033       u4->options = htonl (options);
1034       u4->ipv4_addr = in4->sin_addr.s_addr;
1035       u4->u4_port = in4->sin_port;
1036       *buf = u4;
1037       *added = sizeof (struct IPv4UdpAddress);
1038       return GNUNET_OK;
1039     }
1040   case AF_INET6:
1041     {
1042       struct IPv6UdpAddress *u6;
1043       const struct sockaddr_in6 *in6 = (const struct sockaddr_in6 *) &socket_address;
1044
1045       u6 = GNUNET_new (struct IPv6UdpAddress);
1046       u6->options = htonl (options);
1047       u6->ipv6_addr = in6->sin6_addr;
1048       u6->u6_port = in6->sin6_port;
1049       *buf = u6;
1050       *added = sizeof (struct IPv6UdpAddress);
1051       return GNUNET_OK;
1052     }
1053   default:
1054     GNUNET_break (0);
1055     return GNUNET_SYSERR;
1056   }
1057 }
1058
1059
1060 /**
1061  * Append our port and forward the result.
1062  *
1063  * @param cls a `struct PrettyPrinterContext *`
1064  * @param hostname result from DNS resolver
1065  */
1066 static void
1067 append_port (void *cls,
1068              const char *hostname)
1069 {
1070   struct PrettyPrinterContext *ppc = cls;
1071   struct Plugin *plugin = ppc->plugin;
1072   char *ret;
1073
1074   if (NULL == hostname)
1075   {
1076     /* Final call, done */
1077     GNUNET_CONTAINER_DLL_remove (plugin->ppc_dll_head,
1078                                  plugin->ppc_dll_tail,
1079                                  ppc);
1080     ppc->resolver_handle = NULL;
1081     ppc->asc (ppc->asc_cls,
1082               NULL,
1083               GNUNET_OK);
1084     GNUNET_free (ppc);
1085     return;
1086   }
1087   if (GNUNET_YES == ppc->ipv6)
1088     GNUNET_asprintf (&ret,
1089                      "%s.%u.[%s]:%d",
1090                      PLUGIN_NAME,
1091                      ppc->options,
1092                      hostname,
1093                      ppc->port);
1094   else
1095     GNUNET_asprintf (&ret,
1096                      "%s.%u.%s:%d",
1097                      PLUGIN_NAME,
1098                      ppc->options,
1099                      hostname,
1100                      ppc->port);
1101   ppc->asc (ppc->asc_cls,
1102             ret,
1103             GNUNET_OK);
1104   GNUNET_free (ret);
1105 }
1106
1107
1108 /**
1109  * Convert the transports address to a nice, human-readable format.
1110  *
1111  * @param cls closure with the `struct Plugin *`
1112  * @param type name of the transport that generated the address
1113  * @param addr one of the addresses of the host, NULL for the last address
1114  *        the specific address format depends on the transport;
1115  *        a `union UdpAddress`
1116  * @param addrlen length of the address
1117  * @param numeric should (IP) addresses be displayed in numeric form?
1118  * @param timeout after how long should we give up?
1119  * @param asc function to call on each string
1120  * @param asc_cls closure for @a asc
1121  */
1122 static void
1123 udp_plugin_address_pretty_printer (void *cls,
1124                                    const char *type,
1125                                    const void *addr,
1126                                    size_t addrlen,
1127                                    int numeric,
1128                                    struct GNUNET_TIME_Relative timeout,
1129                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1130                                    void *asc_cls)
1131 {
1132   struct Plugin *plugin = cls;
1133   struct PrettyPrinterContext *ppc;
1134   const struct sockaddr *sb;
1135   size_t sbs;
1136   struct sockaddr_in a4;
1137   struct sockaddr_in6 a6;
1138   const struct IPv4UdpAddress *u4;
1139   const struct IPv6UdpAddress *u6;
1140   uint16_t port;
1141   uint32_t options;
1142
1143   if (addrlen == sizeof(struct IPv6UdpAddress))
1144   {
1145     u6 = addr;
1146     memset (&a6,
1147             0,
1148             sizeof (a6));
1149     a6.sin6_family = AF_INET6;
1150 #if HAVE_SOCKADDR_IN_SIN_LEN
1151     a6.sin6_len = sizeof (a6);
1152 #endif
1153     a6.sin6_port = u6->u6_port;
1154     a6.sin6_addr = u6->ipv6_addr;
1155     port = ntohs (u6->u6_port);
1156     options = ntohl (u6->options);
1157     sb = (const struct sockaddr *) &a6;
1158     sbs = sizeof (a6);
1159   }
1160   else if (addrlen == sizeof (struct IPv4UdpAddress))
1161   {
1162     u4 = addr;
1163     memset (&a4,
1164             0,
1165             sizeof(a4));
1166     a4.sin_family = AF_INET;
1167 #if HAVE_SOCKADDR_IN_SIN_LEN
1168     a4.sin_len = sizeof (a4);
1169 #endif
1170     a4.sin_port = u4->u4_port;
1171     a4.sin_addr.s_addr = u4->ipv4_addr;
1172     port = ntohs (u4->u4_port);
1173     options = ntohl (u4->options);
1174     sb = (const struct sockaddr *) &a4;
1175     sbs = sizeof(a4);
1176   }
1177   else
1178   {
1179     /* invalid address */
1180     GNUNET_break_op (0);
1181     asc (asc_cls,
1182          NULL,
1183          GNUNET_SYSERR);
1184     asc (asc_cls,
1185          NULL,
1186          GNUNET_OK);
1187     return;
1188   }
1189   ppc = GNUNET_new (struct PrettyPrinterContext);
1190   ppc->plugin = plugin;
1191   ppc->asc = asc;
1192   ppc->asc_cls = asc_cls;
1193   ppc->port = port;
1194   ppc->options = options;
1195   if (addrlen == sizeof (struct IPv6UdpAddress))
1196     ppc->ipv6 = GNUNET_YES;
1197   else
1198     ppc->ipv6 = GNUNET_NO;
1199   GNUNET_CONTAINER_DLL_insert (plugin->ppc_dll_head,
1200                                plugin->ppc_dll_tail,
1201                                ppc);
1202   ppc->resolver_handle
1203     = GNUNET_RESOLVER_hostname_get (sb,
1204                                     sbs,
1205                                     ! numeric,
1206                                     timeout,
1207                                     &append_port,
1208                                     ppc);
1209 }
1210
1211
1212 /**
1213  * Check if the given port is plausible (must be either our listen
1214  * port or our advertised port).  If it is neither, we return
1215  * #GNUNET_SYSERR.
1216  *
1217  * @param plugin global variables
1218  * @param in_port port number to check
1219  * @return #GNUNET_OK if port is either our open or advertised port
1220  */
1221 static int
1222 check_port (const struct Plugin *plugin,
1223             uint16_t in_port)
1224 {
1225   if ( (plugin->port == in_port) ||
1226        (plugin->aport == in_port) )
1227     return GNUNET_OK;
1228   return GNUNET_SYSERR;
1229 }
1230
1231
1232 /**
1233  * Function that will be called to check if a binary address for this
1234  * plugin is well-formed and corresponds to an address for THIS peer
1235  * (as per our configuration).  Naturally, if absolutely necessary,
1236  * plugins can be a bit conservative in their answer, but in general
1237  * plugins should make sure that the address does not redirect
1238  * traffic to a 3rd party that might try to man-in-the-middle our
1239  * traffic.
1240  *
1241  * @param cls closure, should be our handle to the Plugin
1242  * @param addr pointer to a `union UdpAddress`
1243  * @param addrlen length of @a addr
1244  * @return #GNUNET_OK if this is a plausible address for this peer
1245  *         and transport, #GNUNET_SYSERR if not
1246  */
1247 static int
1248 udp_plugin_check_address (void *cls,
1249                           const void *addr,
1250                           size_t addrlen)
1251 {
1252   struct Plugin *plugin = cls;
1253   const struct IPv4UdpAddress *v4;
1254   const struct IPv6UdpAddress *v6;
1255
1256   if (sizeof(struct IPv4UdpAddress) == addrlen)
1257   {
1258     struct sockaddr_in s4;
1259
1260     v4 = (const struct IPv4UdpAddress *) addr;
1261     if (GNUNET_OK != check_port (plugin,
1262                                  ntohs (v4->u4_port)))
1263       return GNUNET_SYSERR;
1264     memset (&s4, 0, sizeof (s4));
1265     s4.sin_family = AF_INET;
1266 #if HAVE_SOCKADDR_IN_SIN_LEN
1267     s4.sin_len = sizeof (s4);
1268 #endif
1269     s4.sin_port = v4->u4_port;
1270     s4.sin_addr.s_addr = v4->ipv4_addr;
1271
1272     if (GNUNET_OK !=
1273         GNUNET_NAT_test_address (plugin->nat,
1274                                  &s4,
1275                                  sizeof (struct sockaddr_in)))
1276       return GNUNET_SYSERR;
1277   }
1278   else if (sizeof(struct IPv6UdpAddress) == addrlen)
1279   {
1280     struct sockaddr_in6 s6;
1281
1282     v6 = (const struct IPv6UdpAddress *) addr;
1283     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1284       return GNUNET_OK; /* plausible, if unlikely... */
1285     memset (&s6, 0, sizeof (s6));
1286     s6.sin6_family = AF_INET6;
1287 #if HAVE_SOCKADDR_IN_SIN_LEN
1288     s6.sin6_len = sizeof (s6);
1289 #endif
1290     s6.sin6_port = v6->u6_port;
1291     s6.sin6_addr = v6->ipv6_addr;
1292
1293     if (GNUNET_OK !=
1294         GNUNET_NAT_test_address (plugin->nat,
1295                                  &s6,
1296                                  sizeof(struct sockaddr_in6)))
1297       return GNUNET_SYSERR;
1298   }
1299   else
1300   {
1301     GNUNET_break_op (0);
1302     return GNUNET_SYSERR;
1303   }
1304   return GNUNET_OK;
1305 }
1306
1307
1308 /**
1309  * Our external IP address/port mapping has changed.
1310  *
1311  * @param cls closure, the `struct Plugin`
1312  * @param add_remove #GNUNET_YES to mean the new public IP address,
1313  *                   #GNUNET_NO to mean the previous (now invalid) one
1314  * @param ac address class the address belongs to
1315  * @param addr either the previous or the new public IP address
1316  * @param addrlen actual length of the @a addr
1317  */
1318 static void
1319 udp_nat_port_map_callback (void *cls,
1320                            int add_remove,
1321                            enum GNUNET_NAT_AddressClass ac,
1322                            const struct sockaddr *addr,
1323                            socklen_t addrlen)
1324 {
1325   struct Plugin *plugin = cls;
1326   struct GNUNET_HELLO_Address *address;
1327   struct IPv4UdpAddress u4;
1328   struct IPv6UdpAddress u6;
1329   void *arg;
1330   size_t args;
1331
1332   LOG (GNUNET_ERROR_TYPE_DEBUG,
1333        (GNUNET_YES == add_remove)
1334        ? "NAT notification to add address `%s'\n"
1335        : "NAT notification to remove address `%s'\n",
1336        GNUNET_a2s (addr,
1337                    addrlen));
1338   /* convert 'address' to our internal format */
1339   switch (addr->sa_family)
1340   {
1341   case AF_INET:
1342     {
1343       const struct sockaddr_in *i4;
1344
1345       GNUNET_assert (sizeof(struct sockaddr_in) == addrlen);
1346       i4 = (const struct sockaddr_in *) addr;
1347       if (0 == ntohs (i4->sin_port))
1348         return; /* Port = 0 means unmapped, ignore these for UDP. */
1349       memset (&u4,
1350               0,
1351               sizeof(u4));
1352       u4.options = htonl (plugin->myoptions);
1353       u4.ipv4_addr = i4->sin_addr.s_addr;
1354       u4.u4_port = i4->sin_port;
1355       arg = &u4;
1356       args = sizeof (struct IPv4UdpAddress);
1357       break;
1358     }
1359   case AF_INET6:
1360     {
1361       const struct sockaddr_in6 *i6;
1362
1363       GNUNET_assert (sizeof(struct sockaddr_in6) == addrlen);
1364       i6 = (const struct sockaddr_in6 *) addr;
1365       if (0 == ntohs (i6->sin6_port))
1366         return; /* Port = 0 means unmapped, ignore these for UDP. */
1367       memset (&u6,
1368               0,
1369               sizeof(u6));
1370       u6.options = htonl (plugin->myoptions);
1371       u6.ipv6_addr = i6->sin6_addr;
1372       u6.u6_port = i6->sin6_port;
1373       arg = &u6;
1374       args = sizeof (struct IPv6UdpAddress);
1375       break;
1376     }
1377   default:
1378     GNUNET_break (0);
1379     return;
1380   }
1381   /* modify our published address list */
1382   /* TODO: use 'ac' here in the future... */
1383   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1384                                            PLUGIN_NAME,
1385                                            arg,
1386                                            args,
1387                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
1388   plugin->env->notify_address (plugin->env->cls,
1389                                add_remove,
1390                                address);
1391   GNUNET_HELLO_address_free (address);
1392 }
1393
1394
1395 /* ********************* Finding sessions ******************* */
1396
1397
1398 /**
1399  * Closure for #session_cmp_it().
1400  */
1401 struct GNUNET_ATS_SessionCompareContext
1402 {
1403   /**
1404    * Set to session matching the address.
1405    */
1406   struct GNUNET_ATS_Session *res;
1407
1408   /**
1409    * Address we are looking for.
1410    */
1411   const struct GNUNET_HELLO_Address *address;
1412 };
1413
1414
1415 /**
1416  * Find a session with a matching address.
1417  *
1418  * @param cls the `struct GNUNET_ATS_SessionCompareContext *`
1419  * @param key peer identity (unused)
1420  * @param value the `struct GNUNET_ATS_Session *`
1421  * @return #GNUNET_NO if we found the session, #GNUNET_OK if not
1422  */
1423 static int
1424 session_cmp_it (void *cls,
1425                 const struct GNUNET_PeerIdentity *key,
1426                 void *value)
1427 {
1428   struct GNUNET_ATS_SessionCompareContext *cctx = cls;
1429   struct GNUNET_ATS_Session *s = value;
1430
1431   if (0 == GNUNET_HELLO_address_cmp (s->address,
1432                                      cctx->address))
1433   {
1434     GNUNET_assert (GNUNET_NO == s->in_destroy);
1435     cctx->res = s;
1436     return GNUNET_NO;
1437   }
1438   return GNUNET_OK;
1439 }
1440
1441
1442 /**
1443  * Locate an existing session the transport service is using to
1444  * send data to another peer.  Performs some basic sanity checks
1445  * on the address and then tries to locate a matching session.
1446  *
1447  * @param cls the plugin
1448  * @param address the address we should locate the session by
1449  * @return the session if it exists, or NULL if it is not found
1450  */
1451 static struct GNUNET_ATS_Session *
1452 udp_plugin_lookup_session (void *cls,
1453                            const struct GNUNET_HELLO_Address *address)
1454 {
1455   struct Plugin *plugin = cls;
1456   const struct IPv6UdpAddress *udp_a6;
1457   const struct IPv4UdpAddress *udp_a4;
1458   struct GNUNET_ATS_SessionCompareContext cctx;
1459
1460   if (NULL == address->address)
1461   {
1462     GNUNET_break (0);
1463     return NULL;
1464   }
1465   if (sizeof(struct IPv4UdpAddress) == address->address_length)
1466   {
1467     if (NULL == plugin->sockv4)
1468       return NULL;
1469     udp_a4 = (const struct IPv4UdpAddress *) address->address;
1470     if (0 == udp_a4->u4_port)
1471     {
1472       GNUNET_break (0);
1473       return NULL;
1474     }
1475   }
1476   else if (sizeof(struct IPv6UdpAddress) == address->address_length)
1477   {
1478     if (NULL == plugin->sockv6)
1479       return NULL;
1480     udp_a6 = (const struct IPv6UdpAddress *) address->address;
1481     if (0 == udp_a6->u6_port)
1482     {
1483       GNUNET_break (0);
1484       return NULL;
1485     }
1486   }
1487   else
1488   {
1489     GNUNET_break (0);
1490     return NULL;
1491   }
1492
1493   /* check if session already exists */
1494   cctx.address = address;
1495   cctx.res = NULL;
1496   LOG (GNUNET_ERROR_TYPE_DEBUG,
1497        "Looking for existing session for peer `%s' with address `%s'\n",
1498        GNUNET_i2s (&address->peer),
1499        udp_address_to_string (plugin,
1500                               address->address,
1501                               address->address_length));
1502   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
1503                                               &address->peer,
1504                                               &session_cmp_it,
1505                                               &cctx);
1506   if (NULL == cctx.res)
1507     return NULL;
1508   LOG (GNUNET_ERROR_TYPE_DEBUG,
1509        "Found existing session %p\n",
1510        cctx.res);
1511   return cctx.res;
1512 }
1513
1514
1515 /* ********************** Timeout ****************** */
1516
1517
1518 /**
1519  * Increment session timeout due to activity.
1520  *
1521  * @param s session to reschedule timeout activity for
1522  */
1523 static void
1524 reschedule_session_timeout (struct GNUNET_ATS_Session *s)
1525 {
1526   if (GNUNET_YES == s->in_destroy)
1527     return;
1528   GNUNET_assert (NULL != s->timeout_task);
1529   s->timeout = GNUNET_TIME_relative_to_absolute (UDP_SESSION_TIME_OUT);
1530 }
1531
1532
1533
1534 /**
1535  * Function that will be called whenever the transport service wants to
1536  * notify the plugin that a session is still active and in use and
1537  * therefore the session timeout for this session has to be updated
1538  *
1539  * @param cls closure with the `struct Plugin`
1540  * @param peer which peer was the session for
1541  * @param session which session is being updated
1542  */
1543 static void
1544 udp_plugin_update_session_timeout (void *cls,
1545                                    const struct GNUNET_PeerIdentity *peer,
1546                                    struct GNUNET_ATS_Session *session)
1547 {
1548   struct Plugin *plugin = cls;
1549
1550   if (GNUNET_YES !=
1551       GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessions,
1552                                                     peer,
1553                                                     session))
1554   {
1555     GNUNET_break (0);
1556     return;
1557   }
1558   /* Reschedule session timeout */
1559   reschedule_session_timeout (session);
1560 }
1561
1562
1563 /* ************************* Sending ************************ */
1564
1565
1566 /**
1567  * Remove the given message from the transmission queue and
1568  * update all applicable statistics.
1569  *
1570  * @param plugin the UDP plugin
1571  * @param udpw message wrapper to dequeue
1572  */
1573 static void
1574 dequeue (struct Plugin *plugin,
1575          struct UDP_MessageWrapper *udpw)
1576 {
1577   struct GNUNET_ATS_Session *session = udpw->session;
1578
1579   if (plugin->bytes_in_buffer < udpw->msg_size)
1580   {
1581     GNUNET_break (0);
1582   }
1583   else
1584   {
1585     GNUNET_STATISTICS_update (plugin->env->stats,
1586                               "# UDP, total bytes in send buffers",
1587                               - (long long) udpw->msg_size,
1588                               GNUNET_NO);
1589     plugin->bytes_in_buffer -= udpw->msg_size;
1590   }
1591   GNUNET_STATISTICS_update (plugin->env->stats,
1592                             "# UDP, total messages in send buffers",
1593                             -1,
1594                             GNUNET_NO);
1595   if (sizeof(struct IPv4UdpAddress) == udpw->session->address->address_length)
1596   {
1597     GNUNET_CONTAINER_DLL_remove (plugin->ipv4_queue_head,
1598                                  plugin->ipv4_queue_tail,
1599                                  udpw);
1600   }
1601   else if (sizeof(struct IPv6UdpAddress) == udpw->session->address->address_length)
1602   {
1603     GNUNET_CONTAINER_DLL_remove (plugin->ipv6_queue_head,
1604                                  plugin->ipv6_queue_tail,
1605                                  udpw);
1606   }
1607   else
1608   {
1609     GNUNET_break (0);
1610     return;
1611   }
1612   GNUNET_assert (session->msgs_in_queue > 0);
1613   session->msgs_in_queue--;
1614   GNUNET_assert (session->bytes_in_queue >= udpw->msg_size);
1615   session->bytes_in_queue -= udpw->msg_size;
1616 }
1617
1618
1619 /**
1620  * Enqueue a message for transmission and update statistics.
1621  *
1622  * @param plugin the UDP plugin
1623  * @param udpw message wrapper to queue
1624  */
1625 static void
1626 enqueue (struct Plugin *plugin,
1627          struct UDP_MessageWrapper *udpw)
1628 {
1629   struct GNUNET_ATS_Session *session = udpw->session;
1630
1631   if (GNUNET_YES == session->in_destroy)
1632   {
1633     GNUNET_break (0);
1634     return;
1635   }
1636   if (plugin->bytes_in_buffer > INT64_MAX - udpw->msg_size)
1637   {
1638     GNUNET_break (0);
1639   }
1640   else
1641   {
1642     GNUNET_STATISTICS_update (plugin->env->stats,
1643                               "# UDP, total bytes in send buffers",
1644                               udpw->msg_size,
1645                               GNUNET_NO);
1646     plugin->bytes_in_buffer += udpw->msg_size;
1647   }
1648   GNUNET_STATISTICS_update (plugin->env->stats,
1649                             "# UDP, total messages in send buffers",
1650                             1,
1651                             GNUNET_NO);
1652   if (sizeof (struct IPv4UdpAddress) == udpw->session->address->address_length)
1653   {
1654     GNUNET_CONTAINER_DLL_insert(plugin->ipv4_queue_head,
1655                                 plugin->ipv4_queue_tail,
1656                                 udpw);
1657   }
1658   else if (sizeof (struct IPv6UdpAddress) == udpw->session->address->address_length)
1659   {
1660     GNUNET_CONTAINER_DLL_insert (plugin->ipv6_queue_head,
1661                                  plugin->ipv6_queue_tail,
1662                                  udpw);
1663   }
1664   else
1665   {
1666     GNUNET_break (0);
1667     udpw->cont (udpw->cont_cls,
1668                 &session->target,
1669                 GNUNET_SYSERR,
1670                 udpw->msg_size,
1671                 0);
1672     GNUNET_free (udpw);
1673     return;
1674   }
1675   session->msgs_in_queue++;
1676   session->bytes_in_queue += udpw->msg_size;
1677 }
1678
1679
1680 /**
1681  * We have completed our (attempt) to transmit a message that had to
1682  * be fragmented -- either because we got an ACK saying that all
1683  * fragments were received, or because of timeout / disconnect.  Clean
1684  * up our state.
1685  *
1686  * @param frag_ctx fragmentation context to clean up
1687  * @param result #GNUNET_OK if we succeeded (got ACK),
1688  *               #GNUNET_SYSERR if the transmission failed
1689  */
1690 static void
1691 fragmented_message_done (struct UDP_FragmentationContext *frag_ctx,
1692                          int result)
1693 {
1694   struct Plugin *plugin = frag_ctx->plugin;
1695   struct GNUNET_ATS_Session *s = frag_ctx->session;
1696   struct UDP_MessageWrapper *udpw;
1697   struct UDP_MessageWrapper *tmp;
1698   size_t overhead;
1699   struct GNUNET_TIME_Relative delay;
1700
1701   LOG (GNUNET_ERROR_TYPE_DEBUG,
1702        "%p: Fragmented message removed with result %s\n",
1703        frag_ctx,
1704        (result == GNUNET_SYSERR) ? "FAIL" : "SUCCESS");
1705   /* Call continuation for fragmented message */
1706   if (frag_ctx->on_wire_size >= frag_ctx->payload_size)
1707     overhead = frag_ctx->on_wire_size - frag_ctx->payload_size;
1708   else
1709     overhead = frag_ctx->on_wire_size;
1710   delay = GNUNET_TIME_absolute_get_duration (frag_ctx->start_time);
1711   if (delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
1712   {
1713     LOG (GNUNET_ERROR_TYPE_WARNING,
1714          "Fragmented message acknowledged after %s (expected at %s)\n",
1715          GNUNET_STRINGS_relative_time_to_string (delay,
1716                                                  GNUNET_YES),
1717          GNUNET_STRINGS_absolute_time_to_string (frag_ctx->next_frag_time));
1718   }
1719   else
1720   {
1721     LOG (GNUNET_ERROR_TYPE_DEBUG,
1722          "Fragmented message acknowledged after %s (expected at %s)\n",
1723          GNUNET_STRINGS_relative_time_to_string (delay,
1724                                                  GNUNET_YES),
1725          GNUNET_STRINGS_absolute_time_to_string (frag_ctx->next_frag_time));
1726   }
1727
1728   if (NULL != frag_ctx->cont)
1729     frag_ctx->cont (frag_ctx->cont_cls,
1730                     &s->target,
1731                     result,
1732                     s->frag_ctx->payload_size,
1733                     frag_ctx->on_wire_size);
1734   GNUNET_STATISTICS_update (plugin->env->stats,
1735                             "# UDP, fragmented messages active",
1736                             -1,
1737                             GNUNET_NO);
1738
1739   if (GNUNET_OK == result)
1740   {
1741     GNUNET_STATISTICS_update (plugin->env->stats,
1742                               "# UDP, fragmented msgs, messages, sent, success",
1743                               1,
1744                               GNUNET_NO);
1745     GNUNET_STATISTICS_update (plugin->env->stats,
1746                               "# UDP, fragmented msgs, bytes payload, sent, success",
1747                               s->frag_ctx->payload_size,
1748                               GNUNET_NO);
1749     GNUNET_STATISTICS_update (plugin->env->stats,
1750                               "# UDP, fragmented msgs, bytes overhead, sent, success",
1751                               overhead,
1752                               GNUNET_NO);
1753     GNUNET_STATISTICS_update (plugin->env->stats,
1754                               "# UDP, total, bytes overhead, sent",
1755                               overhead,
1756                               GNUNET_NO);
1757     GNUNET_STATISTICS_update (plugin->env->stats,
1758                               "# UDP, total, bytes payload, sent",
1759                               s->frag_ctx->payload_size,
1760                               GNUNET_NO);
1761   }
1762   else
1763   {
1764     GNUNET_STATISTICS_update (plugin->env->stats,
1765                               "# UDP, fragmented msgs, messages, sent, failure",
1766                               1,
1767                               GNUNET_NO);
1768     GNUNET_STATISTICS_update (plugin->env->stats,
1769                               "# UDP, fragmented msgs, bytes payload, sent, failure",
1770                               s->frag_ctx->payload_size,
1771                               GNUNET_NO);
1772     GNUNET_STATISTICS_update (plugin->env->stats,
1773                               "# UDP, fragmented msgs, bytes payload, sent, failure",
1774                               overhead,
1775                               GNUNET_NO);
1776     GNUNET_STATISTICS_update (plugin->env->stats,
1777                               "# UDP, fragmented msgs, bytes payload, sent, failure",
1778                               overhead,
1779                               GNUNET_NO);
1780   }
1781
1782   /* Remove remaining fragments from queue, no need to transmit those
1783      any longer. */
1784   if (s->address->address_length == sizeof(struct IPv6UdpAddress))
1785   {
1786     udpw = plugin->ipv6_queue_head;
1787     while (NULL != udpw)
1788     {
1789       tmp = udpw->next;
1790       if ( (udpw->frag_ctx != NULL) &&
1791            (udpw->frag_ctx == frag_ctx) )
1792       {
1793         dequeue (plugin,
1794                  udpw);
1795         GNUNET_free (udpw);
1796       }
1797       udpw = tmp;
1798     }
1799   }
1800   if (s->address->address_length == sizeof(struct IPv4UdpAddress))
1801   {
1802     udpw = plugin->ipv4_queue_head;
1803     while (NULL != udpw)
1804     {
1805       tmp = udpw->next;
1806       if ( (NULL != udpw->frag_ctx) &&
1807            (udpw->frag_ctx == frag_ctx) )
1808       {
1809         dequeue (plugin,
1810                  udpw);
1811         GNUNET_free (udpw);
1812       }
1813       udpw = tmp;
1814     }
1815   }
1816   notify_session_monitor (s->plugin,
1817                           s,
1818                           GNUNET_TRANSPORT_SS_UPDATE);
1819   GNUNET_FRAGMENT_context_destroy (frag_ctx->frag,
1820                                    &s->last_expected_msg_delay,
1821                                    &s->last_expected_ack_delay);
1822   s->frag_ctx = NULL;
1823   GNUNET_free (frag_ctx);
1824 }
1825
1826
1827 /**
1828  * We are finished with a fragment in the message queue.
1829  * Notify the continuation and update statistics.
1830  *
1831  * @param cls the `struct Plugin *`
1832  * @param udpw the queue entry
1833  * @param result #GNUNET_OK on success, #GNUNET_SYSERR on failure
1834  */
1835 static void
1836 qc_fragment_sent (void *cls,
1837                   struct UDP_MessageWrapper *udpw,
1838                   int result)
1839 {
1840   struct Plugin *plugin = cls;
1841
1842   GNUNET_assert (NULL != udpw->frag_ctx);
1843   if (GNUNET_OK == result)
1844   {
1845     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1846                 "Fragment of message with %u bytes transmitted to %s\n",
1847                 (unsigned int) udpw->payload_size,
1848                 GNUNET_i2s (&udpw->session->target));
1849     GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);
1850     GNUNET_STATISTICS_update (plugin->env->stats,
1851                               "# UDP, fragmented msgs, fragments, sent, success",
1852                               1,
1853                               GNUNET_NO);
1854     GNUNET_STATISTICS_update (plugin->env->stats,
1855                               "# UDP, fragmented msgs, fragments bytes, sent, success",
1856                               udpw->msg_size,
1857                               GNUNET_NO);
1858   }
1859   else
1860   {
1861     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1862                 "Failed to transmit fragment of message with %u bytes to %s\n",
1863                 (unsigned int) udpw->payload_size,
1864                 GNUNET_i2s (&udpw->session->target));
1865     fragmented_message_done (udpw->frag_ctx,
1866                              GNUNET_SYSERR);
1867     GNUNET_STATISTICS_update (plugin->env->stats,
1868                               "# UDP, fragmented msgs, fragments, sent, failure",
1869                               1,
1870                               GNUNET_NO);
1871     GNUNET_STATISTICS_update (plugin->env->stats,
1872                               "# UDP, fragmented msgs, fragments bytes, sent, failure",
1873                               udpw->msg_size,
1874                               GNUNET_NO);
1875   }
1876 }
1877
1878
1879 /**
1880  * Function that is called with messages created by the fragmentation
1881  * module.  In the case of the `proc` callback of the
1882  * #GNUNET_FRAGMENT_context_create() function, this function must
1883  * eventually call #GNUNET_FRAGMENT_context_transmission_done().
1884  *
1885  * @param cls closure, the `struct UDP_FragmentationContext`
1886  * @param msg the message that was created
1887  */
1888 static void
1889 enqueue_fragment (void *cls,
1890                   const struct GNUNET_MessageHeader *msg)
1891 {
1892   struct UDP_FragmentationContext *frag_ctx = cls;
1893   struct Plugin *plugin = frag_ctx->plugin;
1894   struct UDP_MessageWrapper *udpw;
1895   struct GNUNET_ATS_Session *session = frag_ctx->session;
1896   size_t msg_len = ntohs (msg->size);
1897
1898   LOG (GNUNET_ERROR_TYPE_DEBUG,
1899        "Enqueuing fragment with %u bytes\n",
1900        msg_len);
1901   udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + msg_len);
1902   udpw->session = session;
1903   udpw->msg_buf = (char *) &udpw[1];
1904   udpw->msg_size = msg_len;
1905   udpw->payload_size = msg_len; /* FIXME: minus fragment overhead */
1906   udpw->timeout = frag_ctx->timeout;
1907   udpw->start_time = frag_ctx->start_time;
1908   udpw->transmission_time = frag_ctx->next_frag_time;
1909   frag_ctx->next_frag_time
1910     = GNUNET_TIME_absolute_add (frag_ctx->next_frag_time,
1911                                 frag_ctx->flow_delay_from_other_peer);
1912   udpw->frag_ctx = frag_ctx;
1913   udpw->qc = &qc_fragment_sent;
1914   udpw->qc_cls = plugin;
1915   GNUNET_memcpy (udpw->msg_buf,
1916           msg,
1917           msg_len);
1918   enqueue (plugin,
1919            udpw);
1920   if (session->address->address_length == sizeof (struct IPv4UdpAddress))
1921     schedule_select_v4 (plugin);
1922   else
1923     schedule_select_v6 (plugin);
1924 }
1925
1926
1927 /**
1928  * We are finished with a message from the message queue.
1929  * Notify the continuation and update statistics.
1930  *
1931  * @param cls the `struct Plugin *`
1932  * @param udpw the queue entry
1933  * @param result #GNUNET_OK on success, #GNUNET_SYSERR on failure
1934  */
1935 static void
1936 qc_message_sent (void *cls,
1937                  struct UDP_MessageWrapper *udpw,
1938                  int result)
1939 {
1940   struct Plugin *plugin = cls;
1941   size_t overhead;
1942   struct GNUNET_TIME_Relative delay;
1943
1944   if (udpw->msg_size >= udpw->payload_size)
1945     overhead = udpw->msg_size - udpw->payload_size;
1946   else
1947     overhead = udpw->msg_size;
1948
1949   if (NULL != udpw->cont)
1950   {
1951     delay = GNUNET_TIME_absolute_get_duration (udpw->start_time);
1952     if (delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
1953     {
1954       LOG (GNUNET_ERROR_TYPE_WARNING,
1955            "Message sent via UDP with delay of %s\n",
1956            GNUNET_STRINGS_relative_time_to_string (delay,
1957                                                    GNUNET_YES));
1958     }
1959     else
1960     {
1961       LOG (GNUNET_ERROR_TYPE_DEBUG,
1962            "Message sent via UDP with delay of %s\n",
1963            GNUNET_STRINGS_relative_time_to_string (delay,
1964                                                    GNUNET_YES));
1965     }
1966     udpw->cont (udpw->cont_cls,
1967                 &udpw->session->target,
1968                 result,
1969                 udpw->payload_size,
1970                 overhead);
1971   }
1972   if (GNUNET_OK == result)
1973   {
1974     GNUNET_STATISTICS_update (plugin->env->stats,
1975                               "# UDP, unfragmented msgs, messages, sent, success",
1976                               1,
1977                               GNUNET_NO);
1978     GNUNET_STATISTICS_update (plugin->env->stats,
1979                               "# UDP, unfragmented msgs, bytes payload, sent, success",
1980                               udpw->payload_size,
1981                               GNUNET_NO);
1982     GNUNET_STATISTICS_update (plugin->env->stats,
1983                               "# UDP, unfragmented msgs, bytes overhead, sent, success",
1984                               overhead,
1985                               GNUNET_NO);
1986     GNUNET_STATISTICS_update (plugin->env->stats,
1987                               "# UDP, total, bytes overhead, sent",
1988                               overhead,
1989                               GNUNET_NO);
1990     GNUNET_STATISTICS_update (plugin->env->stats,
1991                               "# UDP, total, bytes payload, sent",
1992                               udpw->payload_size,
1993                               GNUNET_NO);
1994   }
1995   else
1996   {
1997     GNUNET_STATISTICS_update (plugin->env->stats,
1998                               "# UDP, unfragmented msgs, messages, sent, failure",
1999                               1,
2000                               GNUNET_NO);
2001     GNUNET_STATISTICS_update (plugin->env->stats,
2002                               "# UDP, unfragmented msgs, bytes payload, sent, failure",
2003                               udpw->payload_size,
2004                               GNUNET_NO);
2005     GNUNET_STATISTICS_update (plugin->env->stats,
2006                               "# UDP, unfragmented msgs, bytes overhead, sent, failure",
2007                               overhead,
2008                               GNUNET_NO);
2009   }
2010 }
2011
2012
2013 /**
2014  * Function that can be used by the transport service to transmit a
2015  * message using the plugin.  Note that in the case of a peer
2016  * disconnecting, the continuation MUST be called prior to the
2017  * disconnect notification itself.  This function will be called with
2018  * this peer's HELLO message to initiate a fresh connection to another
2019  * peer.
2020  *
2021  * @param cls closure
2022  * @param s which session must be used
2023  * @param msgbuf the message to transmit
2024  * @param msgbuf_size number of bytes in @a msgbuf
2025  * @param priority how important is the message (most plugins will
2026  *                 ignore message priority and just FIFO)
2027  * @param to how long to wait at most for the transmission (does not
2028  *                require plugins to discard the message after the timeout,
2029  *                just advisory for the desired delay; most plugins will ignore
2030  *                this as well)
2031  * @param cont continuation to call once the message has
2032  *        been transmitted (or if the transport is ready
2033  *        for the next transmission call; or if the
2034  *        peer disconnected...); can be NULL
2035  * @param cont_cls closure for @a cont
2036  * @return number of bytes used (on the physical network, with overheads);
2037  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
2038  *         and does NOT mean that the message was not transmitted (DV)
2039  */
2040 static ssize_t
2041 udp_plugin_send (void *cls,
2042                  struct GNUNET_ATS_Session *s,
2043                  const char *msgbuf,
2044                  size_t msgbuf_size,
2045                  unsigned int priority,
2046                  struct GNUNET_TIME_Relative to,
2047                  GNUNET_TRANSPORT_TransmitContinuation cont,
2048                  void *cont_cls)
2049 {
2050   struct Plugin *plugin = cls;
2051   size_t udpmlen = msgbuf_size + sizeof(struct UDPMessage);
2052   struct UDP_FragmentationContext *frag_ctx;
2053   struct UDP_MessageWrapper *udpw;
2054   struct UDPMessage *udp;
2055   char mbuf[udpmlen] GNUNET_ALIGN;
2056   struct GNUNET_TIME_Relative latency;
2057
2058   if ( (sizeof(struct IPv6UdpAddress) == s->address->address_length) &&
2059        (NULL == plugin->sockv6) )
2060     return GNUNET_SYSERR;
2061   if ( (sizeof(struct IPv4UdpAddress) == s->address->address_length) &&
2062        (NULL == plugin->sockv4) )
2063     return GNUNET_SYSERR;
2064   if (udpmlen >= GNUNET_MAX_MESSAGE_SIZE)
2065   {
2066     GNUNET_break (0);
2067     return GNUNET_SYSERR;
2068   }
2069   if (GNUNET_YES !=
2070       GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessions,
2071                                                     &s->target,
2072                                                     s))
2073   {
2074     GNUNET_break (0);
2075     return GNUNET_SYSERR;
2076   }
2077   LOG (GNUNET_ERROR_TYPE_DEBUG,
2078        "UDP transmits %u-byte message to `%s' using address `%s'\n",
2079        udpmlen,
2080        GNUNET_i2s (&s->target),
2081        udp_address_to_string (plugin,
2082                               s->address->address,
2083                               s->address->address_length));
2084
2085   udp = (struct UDPMessage *) mbuf;
2086   udp->header.size = htons (udpmlen);
2087   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
2088   udp->reserved = htonl (0);
2089   udp->sender = *plugin->env->my_identity;
2090
2091   /* We do not update the session time out here!  Otherwise this
2092    * session will not timeout since we send keep alive before session
2093    * can timeout.
2094    *
2095    * For UDP we update session timeout only on receive, this will
2096    * cover keep alives, since remote peer will reply with keep alive
2097    * responses!
2098    */
2099   if (udpmlen <= UDP_MTU)
2100   {
2101     /* unfragmented message */
2102     udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + udpmlen);
2103     udpw->session = s;
2104     udpw->msg_buf = (char *) &udpw[1];
2105     udpw->msg_size = udpmlen; /* message size with UDP overhead */
2106     udpw->payload_size = msgbuf_size; /* message size without UDP overhead */
2107     udpw->start_time = GNUNET_TIME_absolute_get ();
2108     udpw->timeout = GNUNET_TIME_relative_to_absolute (to);
2109     udpw->transmission_time = s->last_transmit_time;
2110     s->last_transmit_time
2111       = GNUNET_TIME_absolute_add (s->last_transmit_time,
2112                                   s->flow_delay_from_other_peer);
2113     udpw->cont = cont;
2114     udpw->cont_cls = cont_cls;
2115     udpw->frag_ctx = NULL;
2116     udpw->qc = &qc_message_sent;
2117     udpw->qc_cls = plugin;
2118     GNUNET_memcpy (udpw->msg_buf,
2119             udp,
2120             sizeof (struct UDPMessage));
2121     GNUNET_memcpy (&udpw->msg_buf[sizeof(struct UDPMessage)],
2122             msgbuf,
2123             msgbuf_size);
2124     enqueue (plugin,
2125              udpw);
2126     GNUNET_STATISTICS_update (plugin->env->stats,
2127                               "# UDP, unfragmented messages queued total",
2128                               1,
2129                               GNUNET_NO);
2130     GNUNET_STATISTICS_update (plugin->env->stats,
2131                               "# UDP, unfragmented bytes payload queued total",
2132                               msgbuf_size,
2133                               GNUNET_NO);
2134     if (s->address->address_length == sizeof (struct IPv4UdpAddress))
2135       schedule_select_v4 (plugin);
2136     else
2137       schedule_select_v6 (plugin);
2138   }
2139   else
2140   {
2141     /* fragmented message */
2142     if (NULL != s->frag_ctx)
2143       return GNUNET_SYSERR;
2144     GNUNET_memcpy (&udp[1],
2145             msgbuf,
2146             msgbuf_size);
2147     frag_ctx = GNUNET_new (struct UDP_FragmentationContext);
2148     frag_ctx->plugin = plugin;
2149     frag_ctx->session = s;
2150     frag_ctx->cont = cont;
2151     frag_ctx->cont_cls = cont_cls;
2152     frag_ctx->start_time = GNUNET_TIME_absolute_get ();
2153     frag_ctx->next_frag_time = s->last_transmit_time;
2154     frag_ctx->flow_delay_from_other_peer
2155       = GNUNET_TIME_relative_divide (s->flow_delay_from_other_peer,
2156                                      1 + (msgbuf_size /
2157                                           UDP_MTU));
2158     frag_ctx->timeout = GNUNET_TIME_relative_to_absolute (to);
2159     frag_ctx->payload_size = msgbuf_size; /* unfragmented message size without UDP overhead */
2160     frag_ctx->on_wire_size = 0; /* bytes with UDP and fragmentation overhead */
2161     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
2162                                                      UDP_MTU,
2163                                                      &plugin->tracker,
2164                                                      s->last_expected_msg_delay,
2165                                                      s->last_expected_ack_delay,
2166                                                      &udp->header,
2167                                                      &enqueue_fragment,
2168                                                      frag_ctx);
2169     s->frag_ctx = frag_ctx;
2170     s->last_transmit_time = frag_ctx->next_frag_time;
2171     latency = GNUNET_TIME_absolute_get_remaining (s->last_transmit_time);
2172     if (latency.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
2173       LOG (GNUNET_ERROR_TYPE_WARNING,
2174            "Enqueued fragments will take %s for transmission to %s (queue size: %u)\n",
2175            GNUNET_STRINGS_relative_time_to_string (latency,
2176                                                    GNUNET_YES),
2177            GNUNET_i2s (&s->target),
2178            (unsigned int) s->msgs_in_queue);
2179     else
2180       LOG (GNUNET_ERROR_TYPE_DEBUG,
2181            "Enqueued fragments will take %s for transmission to %s (queue size: %u)\n",
2182            GNUNET_STRINGS_relative_time_to_string (latency,
2183                                                    GNUNET_YES),
2184            GNUNET_i2s (&s->target),
2185            (unsigned int) s->msgs_in_queue);
2186
2187     GNUNET_STATISTICS_update (plugin->env->stats,
2188                               "# UDP, fragmented messages active",
2189                               1,
2190                               GNUNET_NO);
2191     GNUNET_STATISTICS_update (plugin->env->stats,
2192                               "# UDP, fragmented messages, total",
2193                               1,
2194                               GNUNET_NO);
2195     GNUNET_STATISTICS_update (plugin->env->stats,
2196                               "# UDP, fragmented bytes (payload)",
2197                               frag_ctx->payload_size,
2198                               GNUNET_NO);
2199   }
2200   notify_session_monitor (s->plugin,
2201                           s,
2202                           GNUNET_TRANSPORT_SS_UPDATE);
2203   return udpmlen;
2204 }
2205
2206
2207 /* ********************** Receiving ********************** */
2208
2209
2210 /**
2211  * Closure for #find_receive_context().
2212  */
2213 struct FindReceiveContext
2214 {
2215   /**
2216    * Where to store the result.
2217    */
2218   struct DefragContext *rc;
2219
2220   /**
2221    * Session associated with this context.
2222    */
2223   struct GNUNET_ATS_Session *session;
2224
2225   /**
2226    * Address to find.
2227    */
2228   const union UdpAddress *udp_addr;
2229
2230   /**
2231    * Number of bytes in @e udp_addr.
2232    */
2233   size_t udp_addr_len;
2234
2235 };
2236
2237
2238 /**
2239  * Scan the heap for a receive context with the given address.
2240  *
2241  * @param cls the `struct FindReceiveContext`
2242  * @param node internal node of the heap
2243  * @param element value stored at the node (a `struct ReceiveContext`)
2244  * @param cost cost associated with the node
2245  * @return #GNUNET_YES if we should continue to iterate,
2246  *         #GNUNET_NO if not.
2247  */
2248 static int
2249 find_receive_context (void *cls,
2250                       struct GNUNET_CONTAINER_HeapNode *node,
2251                       void *element,
2252                       GNUNET_CONTAINER_HeapCostType cost)
2253 {
2254   struct FindReceiveContext *frc = cls;
2255   struct DefragContext *e = element;
2256
2257   if ( (frc->udp_addr_len == e->udp_addr_len) &&
2258        (0 == memcmp (frc->udp_addr,
2259                      e->udp_addr,
2260                      frc->udp_addr_len)) )
2261   {
2262     frc->rc = e;
2263     return GNUNET_NO;
2264   }
2265   return GNUNET_YES;
2266 }
2267
2268
2269 /**
2270  * Functions with this signature are called whenever we need to close
2271  * a session due to a disconnect or failure to establish a connection.
2272  *
2273  * @param cls closure with the `struct Plugin`
2274  * @param s session to close down
2275  * @return #GNUNET_OK on success
2276  */
2277 static int
2278 udp_disconnect_session (void *cls,
2279                         struct GNUNET_ATS_Session *s)
2280 {
2281   struct Plugin *plugin = cls;
2282   struct UDP_MessageWrapper *udpw;
2283   struct UDP_MessageWrapper *next;
2284   struct FindReceiveContext frc;
2285
2286   GNUNET_assert (GNUNET_YES != s->in_destroy);
2287   LOG (GNUNET_ERROR_TYPE_DEBUG,
2288        "Session %p to peer `%s' at address %s ended\n",
2289        s,
2290        GNUNET_i2s (&s->target),
2291        udp_address_to_string (plugin,
2292                               s->address->address,
2293                               s->address->address_length));
2294   if (NULL != s->timeout_task)
2295   {
2296     GNUNET_SCHEDULER_cancel (s->timeout_task);
2297     s->timeout_task = NULL;
2298   }
2299   if (NULL != s->frag_ctx)
2300   {
2301     /* Remove fragmented message due to disconnect */
2302     fragmented_message_done (s->frag_ctx,
2303                              GNUNET_SYSERR);
2304   }
2305   GNUNET_assert (GNUNET_YES ==
2306                  GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
2307                                                        &s->target,
2308                                                        s));
2309   frc.rc = NULL;
2310   frc.udp_addr = s->address->address;
2311   frc.udp_addr_len = s->address->address_length;
2312   /* Lookup existing receive context for this address */
2313   if (NULL != plugin->defrag_ctxs)
2314   {
2315     GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
2316                                    &find_receive_context,
2317                                    &frc);
2318     if (NULL != frc.rc)
2319     {
2320       struct DefragContext *d_ctx = frc.rc;
2321
2322       GNUNET_CONTAINER_heap_remove_node (d_ctx->hnode);
2323       GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
2324       GNUNET_free (d_ctx);
2325     }
2326   }
2327   s->in_destroy = GNUNET_YES;
2328   next = plugin->ipv4_queue_head;
2329   while (NULL != (udpw = next))
2330   {
2331     next = udpw->next;
2332     if (udpw->session == s)
2333     {
2334       dequeue (plugin,
2335                udpw);
2336       udpw->qc (udpw->qc_cls,
2337                 udpw,
2338                 GNUNET_SYSERR);
2339       GNUNET_free (udpw);
2340     }
2341   }
2342   next = plugin->ipv6_queue_head;
2343   while (NULL != (udpw = next))
2344   {
2345     next = udpw->next;
2346     if (udpw->session == s)
2347     {
2348       dequeue (plugin,
2349                udpw);
2350       udpw->qc (udpw->qc_cls,
2351                 udpw,
2352                 GNUNET_SYSERR);
2353       GNUNET_free (udpw);
2354     }
2355   }
2356   if ( (NULL != s->frag_ctx) &&
2357        (NULL != s->frag_ctx->cont) )
2358   {
2359     /* The 'frag_ctx' itself will be freed in #free_session() a bit
2360        later, as it might be in use right now */
2361     LOG (GNUNET_ERROR_TYPE_DEBUG,
2362          "Calling continuation for fragemented message to `%s' with result SYSERR\n",
2363          GNUNET_i2s (&s->target));
2364     s->frag_ctx->cont (s->frag_ctx->cont_cls,
2365                        &s->target,
2366                        GNUNET_SYSERR,
2367                        s->frag_ctx->payload_size,
2368                        s->frag_ctx->on_wire_size);
2369   }
2370   notify_session_monitor (s->plugin,
2371                           s,
2372                           GNUNET_TRANSPORT_SS_DONE);
2373   plugin->env->session_end (plugin->env->cls,
2374                             s->address,
2375                             s);
2376   GNUNET_STATISTICS_set (plugin->env->stats,
2377                          "# UDP sessions active",
2378                          GNUNET_CONTAINER_multipeermap_size (plugin->sessions),
2379                          GNUNET_NO);
2380   if (0 == s->rc)
2381     free_session (s);
2382   return GNUNET_OK;
2383 }
2384
2385
2386 /**
2387  * Handle a #GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK message.
2388  *
2389  * @param plugin the UDP plugin
2390  * @param msg the (presumed) UDP ACK message
2391  * @param udp_addr sender address
2392  * @param udp_addr_len number of bytes in @a udp_addr
2393  */
2394 static void
2395 read_process_ack (struct Plugin *plugin,
2396                   const struct GNUNET_MessageHeader *msg,
2397                   const union UdpAddress *udp_addr,
2398                   socklen_t udp_addr_len)
2399 {
2400   const struct GNUNET_MessageHeader *ack;
2401   const struct UDP_ACK_Message *udp_ack;
2402   struct GNUNET_HELLO_Address *address;
2403   struct GNUNET_ATS_Session *s;
2404   struct GNUNET_TIME_Relative flow_delay;
2405
2406   /* check message format */
2407   if (ntohs (msg->size)
2408       < sizeof(struct UDP_ACK_Message) + sizeof(struct GNUNET_MessageHeader))
2409   {
2410     GNUNET_break_op (0);
2411     return;
2412   }
2413   udp_ack = (const struct UDP_ACK_Message *) msg;
2414   ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
2415   if (ntohs (ack->size) != ntohs (msg->size) - sizeof(struct UDP_ACK_Message))
2416   {
2417     GNUNET_break_op(0);
2418     return;
2419   }
2420
2421   /* Locate session */
2422   address = GNUNET_HELLO_address_allocate (&udp_ack->sender,
2423                                            PLUGIN_NAME,
2424                                            udp_addr,
2425                                            udp_addr_len,
2426                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
2427   s = udp_plugin_lookup_session (plugin,
2428                                  address);
2429   if (NULL == s)
2430   {
2431     LOG (GNUNET_ERROR_TYPE_WARNING,
2432          "UDP session of address %s for ACK not found\n",
2433          udp_address_to_string (plugin,
2434                                 address->address,
2435                                 address->address_length));
2436     GNUNET_HELLO_address_free (address);
2437     return;
2438   }
2439   if (NULL == s->frag_ctx)
2440   {
2441     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2442          "Fragmentation context of address %s for ACK (%s) not found\n",
2443          udp_address_to_string (plugin,
2444                                 address->address,
2445                                 address->address_length),
2446          GNUNET_FRAGMENT_print_ack (ack));
2447     GNUNET_HELLO_address_free (address);
2448     return;
2449   }
2450   GNUNET_HELLO_address_free (address);
2451
2452   /* evaluate flow delay: how long should we wait between messages? */
2453   if (UINT32_MAX == ntohl (udp_ack->delay))
2454   {
2455     /* Other peer asked for us to terminate the session */
2456     LOG (GNUNET_ERROR_TYPE_INFO,
2457          "Asked to disconnect UDP session of %s\n",
2458          GNUNET_i2s (&udp_ack->sender));
2459     udp_disconnect_session (plugin,
2460                             s);
2461     return;
2462   }
2463   flow_delay.rel_value_us = (uint64_t) ntohl (udp_ack->delay);
2464   if (flow_delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
2465     LOG (GNUNET_ERROR_TYPE_WARNING,
2466          "We received a sending delay of %s for %s\n",
2467          GNUNET_STRINGS_relative_time_to_string (flow_delay,
2468                                                  GNUNET_YES),
2469          GNUNET_i2s (&udp_ack->sender));
2470   else
2471     LOG (GNUNET_ERROR_TYPE_DEBUG,
2472          "We received a sending delay of %s for %s\n",
2473          GNUNET_STRINGS_relative_time_to_string (flow_delay,
2474                                                  GNUNET_YES),
2475          GNUNET_i2s (&udp_ack->sender));
2476   /* Flow delay is for the reassembled packet, however, our delay
2477      is per packet, so we need to adjust: */
2478   s->flow_delay_from_other_peer = flow_delay;
2479
2480   /* Handle ACK */
2481   if (GNUNET_OK !=
2482       GNUNET_FRAGMENT_process_ack (s->frag_ctx->frag,
2483                                    ack))
2484   {
2485     LOG (GNUNET_ERROR_TYPE_DEBUG,
2486          "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
2487          (unsigned int) ntohs (msg->size),
2488          GNUNET_i2s (&udp_ack->sender),
2489          udp_address_to_string (plugin,
2490                                 udp_addr,
2491                                 udp_addr_len));
2492     /* Expect more ACKs to arrive */
2493     return;
2494   }
2495
2496   /* Remove fragmented message after successful sending */
2497   LOG (GNUNET_ERROR_TYPE_DEBUG,
2498        "Message from %s at %s full ACK'ed\n",
2499        GNUNET_i2s (&udp_ack->sender),
2500        udp_address_to_string (plugin,
2501                               udp_addr,
2502                               udp_addr_len));
2503   fragmented_message_done (s->frag_ctx,
2504                            GNUNET_OK);
2505 }
2506
2507
2508 /**
2509  * Message tokenizer has broken up an incomming message. Pass it on
2510  * to the service.
2511  *
2512  * @param cls the `struct GNUNET_ATS_Session *`
2513  * @param hdr the actual message
2514  * @return #GNUNET_OK (always)
2515  */
2516 static int
2517 process_inbound_tokenized_messages (void *cls,
2518                                     const struct GNUNET_MessageHeader *hdr)
2519 {
2520   struct GNUNET_ATS_Session *session = cls;
2521   struct Plugin *plugin = session->plugin;
2522
2523   if (GNUNET_YES == session->in_destroy)
2524     return GNUNET_OK;
2525   reschedule_session_timeout (session);
2526   session->flow_delay_for_other_peer
2527     = plugin->env->receive (plugin->env->cls,
2528                             session->address,
2529                             session,
2530                             hdr);
2531   return GNUNET_OK;
2532 }
2533
2534
2535 /**
2536  * Destroy a session, plugin is being unloaded.
2537  *
2538  * @param cls the `struct Plugin`
2539  * @param key hash of public key of target peer
2540  * @param value a `struct PeerSession *` to clean up
2541  * @return #GNUNET_OK (continue to iterate)
2542  */
2543 static int
2544 disconnect_and_free_it (void *cls,
2545                         const struct GNUNET_PeerIdentity *key,
2546                         void *value)
2547 {
2548   struct Plugin *plugin = cls;
2549
2550   udp_disconnect_session (plugin,
2551                           value);
2552   return GNUNET_OK;
2553 }
2554
2555
2556 /**
2557  * Disconnect from a remote node.  Clean up session if we have one for
2558  * this peer.
2559  *
2560  * @param cls closure for this call (should be handle to Plugin)
2561  * @param target the peeridentity of the peer to disconnect
2562  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the operation failed
2563  */
2564 static void
2565 udp_disconnect (void *cls,
2566                 const struct GNUNET_PeerIdentity *target)
2567 {
2568   struct Plugin *plugin = cls;
2569
2570   LOG (GNUNET_ERROR_TYPE_DEBUG,
2571        "Disconnecting from peer `%s'\n",
2572        GNUNET_i2s (target));
2573   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
2574                                               target,
2575                                               &disconnect_and_free_it,
2576                                               plugin);
2577 }
2578
2579
2580 /**
2581  * Session was idle, so disconnect it.
2582  *
2583  * @param cls the `struct GNUNET_ATS_Session` to time out
2584  */
2585 static void
2586 session_timeout (void *cls)
2587 {
2588   struct GNUNET_ATS_Session *s = cls;
2589   struct Plugin *plugin = s->plugin;
2590   struct GNUNET_TIME_Relative left;
2591
2592   s->timeout_task = NULL;
2593   left = GNUNET_TIME_absolute_get_remaining (s->timeout);
2594   if (left.rel_value_us > 0)
2595   {
2596     /* not actually our turn yet, but let's at least update
2597        the monitor, it may think we're about to die ... */
2598     notify_session_monitor (s->plugin,
2599                             s,
2600                             GNUNET_TRANSPORT_SS_UPDATE);
2601     s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
2602                                                     &session_timeout,
2603                                                     s);
2604     return;
2605   }
2606   LOG (GNUNET_ERROR_TYPE_DEBUG,
2607        "Session %p was idle for %s, disconnecting\n",
2608        s,
2609        GNUNET_STRINGS_relative_time_to_string (UDP_SESSION_TIME_OUT,
2610                                                GNUNET_YES));
2611   /* call session destroy function */
2612   udp_disconnect_session (plugin,
2613                           s);
2614 }
2615
2616
2617 /**
2618  * Allocate a new session for the given endpoint address.
2619  * Note that this function does not inform the service
2620  * of the new session, this is the responsibility of the
2621  * caller (if needed).
2622  *
2623  * @param cls the `struct Plugin`
2624  * @param address address of the other peer to use
2625  * @param network_type network type the address belongs to
2626  * @return NULL on error, otherwise session handle
2627  */
2628 static struct GNUNET_ATS_Session *
2629 udp_plugin_create_session (void *cls,
2630                            const struct GNUNET_HELLO_Address *address,
2631                            enum GNUNET_ATS_Network_Type network_type)
2632 {
2633   struct Plugin *plugin = cls;
2634   struct GNUNET_ATS_Session *s;
2635
2636   s = GNUNET_new (struct GNUNET_ATS_Session);
2637   s->mst = GNUNET_MST_create (&process_inbound_tokenized_messages,
2638                               s);
2639   s->plugin = plugin;
2640   s->address = GNUNET_HELLO_address_copy (address);
2641   s->target = address->peer;
2642   s->last_transmit_time = GNUNET_TIME_absolute_get ();
2643   s->last_expected_ack_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2644                                                               250);
2645   s->last_expected_msg_delay = GNUNET_TIME_UNIT_MILLISECONDS;
2646   s->flow_delay_from_other_peer = GNUNET_TIME_UNIT_ZERO;
2647   s->flow_delay_for_other_peer = GNUNET_TIME_UNIT_ZERO;
2648   s->timeout = GNUNET_TIME_relative_to_absolute (UDP_SESSION_TIME_OUT);
2649   s->timeout_task = GNUNET_SCHEDULER_add_delayed (UDP_SESSION_TIME_OUT,
2650                                                   &session_timeout,
2651                                                   s);
2652   s->scope = network_type;
2653
2654   LOG (GNUNET_ERROR_TYPE_DEBUG,
2655        "Creating new session %p for peer `%s' address `%s'\n",
2656        s,
2657        GNUNET_i2s (&address->peer),
2658        udp_address_to_string (plugin,
2659                               address->address,
2660                               address->address_length));
2661   GNUNET_assert (GNUNET_OK ==
2662                  GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
2663                                                     &s->target,
2664                                                     s,
2665                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
2666   GNUNET_STATISTICS_set (plugin->env->stats,
2667                          "# UDP sessions active",
2668                          GNUNET_CONTAINER_multipeermap_size (plugin->sessions),
2669                          GNUNET_NO);
2670   notify_session_monitor (plugin,
2671                           s,
2672                           GNUNET_TRANSPORT_SS_INIT);
2673   return s;
2674 }
2675
2676
2677 /**
2678  * Creates a new outbound session the transport service will use to
2679  * send data to the peer.
2680  *
2681  * @param cls the `struct Plugin *`
2682  * @param address the address
2683  * @return the session or NULL of max connections exceeded
2684  */
2685 static struct GNUNET_ATS_Session *
2686 udp_plugin_get_session (void *cls,
2687                         const struct GNUNET_HELLO_Address *address)
2688 {
2689   struct Plugin *plugin = cls;
2690   struct GNUNET_ATS_Session *s;
2691   enum GNUNET_ATS_Network_Type network_type = GNUNET_ATS_NET_UNSPECIFIED;
2692   const struct IPv4UdpAddress *udp_v4;
2693   const struct IPv6UdpAddress *udp_v6;
2694
2695   if (NULL == address)
2696   {
2697     GNUNET_break (0);
2698     return NULL;
2699   }
2700   if ( (address->address_length != sizeof(struct IPv4UdpAddress)) &&
2701        (address->address_length != sizeof(struct IPv6UdpAddress)) )
2702   {
2703     GNUNET_break_op (0);
2704     return NULL;
2705   }
2706   if (NULL != (s = udp_plugin_lookup_session (cls,
2707                                               address)))
2708     return s;
2709
2710   /* need to create new session */
2711   if (sizeof (struct IPv4UdpAddress) == address->address_length)
2712   {
2713     struct sockaddr_in v4;
2714
2715     udp_v4 = (const struct IPv4UdpAddress *) address->address;
2716     memset (&v4, '\0', sizeof (v4));
2717     v4.sin_family = AF_INET;
2718 #if HAVE_SOCKADDR_IN_SIN_LEN
2719     v4.sin_len = sizeof (struct sockaddr_in);
2720 #endif
2721     v4.sin_port = udp_v4->u4_port;
2722     v4.sin_addr.s_addr = udp_v4->ipv4_addr;
2723     network_type = plugin->env->get_address_type (plugin->env->cls,
2724                                                   (const struct sockaddr *) &v4,
2725                                                   sizeof (v4));
2726   }
2727   if (sizeof (struct IPv6UdpAddress) == address->address_length)
2728   {
2729     struct sockaddr_in6 v6;
2730
2731     udp_v6 = (const struct IPv6UdpAddress *) address->address;
2732     memset (&v6, '\0', sizeof (v6));
2733     v6.sin6_family = AF_INET6;
2734 #if HAVE_SOCKADDR_IN_SIN_LEN
2735     v6.sin6_len = sizeof (struct sockaddr_in6);
2736 #endif
2737     v6.sin6_port = udp_v6->u6_port;
2738     v6.sin6_addr = udp_v6->ipv6_addr;
2739     network_type = plugin->env->get_address_type (plugin->env->cls,
2740                                                   (const struct sockaddr *) &v6,
2741                                                   sizeof (v6));
2742   }
2743   GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != network_type);
2744   return udp_plugin_create_session (cls,
2745                                     address,
2746                                     network_type);
2747 }
2748
2749
2750 /**
2751  * We've received a UDP Message.  Process it (pass contents to main service).
2752  *
2753  * @param plugin plugin context
2754  * @param msg the message
2755  * @param udp_addr sender address
2756  * @param udp_addr_len number of bytes in @a udp_addr
2757  * @param network_type network type the address belongs to
2758  */
2759 static void
2760 process_udp_message (struct Plugin *plugin,
2761                      const struct UDPMessage *msg,
2762                      const union UdpAddress *udp_addr,
2763                      size_t udp_addr_len,
2764                      enum GNUNET_ATS_Network_Type network_type)
2765 {
2766   struct GNUNET_ATS_Session *s;
2767   struct GNUNET_HELLO_Address *address;
2768
2769   GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != network_type);
2770   if (0 != ntohl (msg->reserved))
2771   {
2772     GNUNET_break_op(0);
2773     return;
2774   }
2775   if (ntohs (msg->header.size)
2776       < sizeof(struct GNUNET_MessageHeader) + sizeof(struct UDPMessage))
2777   {
2778     GNUNET_break_op(0);
2779     return;
2780   }
2781
2782   address = GNUNET_HELLO_address_allocate (&msg->sender,
2783                                            PLUGIN_NAME,
2784                                            udp_addr,
2785                                            udp_addr_len,
2786                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
2787   if (NULL ==
2788       (s = udp_plugin_lookup_session (plugin,
2789                                       address)))
2790   {
2791     s = udp_plugin_create_session (plugin,
2792                                    address,
2793                                    network_type);
2794     plugin->env->session_start (plugin->env->cls,
2795                                 address,
2796                                 s,
2797                                 s->scope);
2798     notify_session_monitor (plugin,
2799                             s,
2800                             GNUNET_TRANSPORT_SS_UP);
2801   }
2802   GNUNET_free (address);
2803
2804   s->rc++;
2805   GNUNET_MST_from_buffer (s->mst,
2806                           (const char *) &msg[1],
2807                           ntohs (msg->header.size) - sizeof(struct UDPMessage),
2808                           GNUNET_YES,
2809                           GNUNET_NO);
2810   s->rc--;
2811   if ( (0 == s->rc) &&
2812        (GNUNET_YES == s->in_destroy) )
2813     free_session (s);
2814 }
2815
2816
2817 /**
2818  * Process a defragmented message.
2819  *
2820  * @param cls the `struct DefragContext *`
2821  * @param msg the message
2822  */
2823 static void
2824 fragment_msg_proc (void *cls,
2825                    const struct GNUNET_MessageHeader *msg)
2826 {
2827   struct DefragContext *dc = cls;
2828   const struct UDPMessage *um;
2829
2830   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
2831   {
2832     GNUNET_break_op (0);
2833     return;
2834   }
2835   if (ntohs (msg->size) < sizeof(struct UDPMessage))
2836   {
2837     GNUNET_break_op (0);
2838     return;
2839   }
2840   um = (const struct UDPMessage *) msg;
2841   dc->sender = um->sender;
2842   dc->have_sender = GNUNET_YES;
2843   process_udp_message (dc->plugin,
2844                        um,
2845                        dc->udp_addr,
2846                        dc->udp_addr_len,
2847                        dc->network_type);
2848 }
2849
2850
2851 /**
2852  * We finished sending an acknowledgement.  Update
2853  * statistics.
2854  *
2855  * @param cls the `struct Plugin`
2856  * @param udpw message queue entry of the ACK
2857  * @param result #GNUNET_OK if the transmission worked,
2858  *               #GNUNET_SYSERR if we failed to send the ACK
2859  */
2860 static void
2861 ack_message_sent (void *cls,
2862                   struct UDP_MessageWrapper *udpw,
2863                   int result)
2864 {
2865   struct Plugin *plugin = cls;
2866
2867   if (GNUNET_OK == result)
2868   {
2869     GNUNET_STATISTICS_update (plugin->env->stats,
2870                               "# UDP, ACK messages sent",
2871                               1,
2872                               GNUNET_NO);
2873   }
2874   else
2875   {
2876     GNUNET_STATISTICS_update (plugin->env->stats,
2877                               "# UDP, ACK transmissions failed",
2878                               1,
2879                               GNUNET_NO);
2880   }
2881 }
2882
2883
2884 /**
2885  * Transmit an acknowledgement.
2886  *
2887  * @param cls the `struct DefragContext *`
2888  * @param id message ID (unused)
2889  * @param msg ack to transmit
2890  */
2891 static void
2892 ack_proc (void *cls,
2893           uint32_t id,
2894           const struct GNUNET_MessageHeader *msg)
2895 {
2896   struct DefragContext *rc = cls;
2897   struct Plugin *plugin = rc->plugin;
2898   size_t msize = sizeof(struct UDP_ACK_Message) + ntohs (msg->size);
2899   struct UDP_ACK_Message *udp_ack;
2900   uint32_t delay;
2901   struct UDP_MessageWrapper *udpw;
2902   struct GNUNET_ATS_Session *s;
2903   struct GNUNET_HELLO_Address *address;
2904
2905   if (GNUNET_NO == rc->have_sender)
2906   {
2907     /* tried to defragment but never succeeded, hence will not ACK */
2908     /* This can happen if we just lost msgs */
2909     GNUNET_STATISTICS_update (plugin->env->stats,
2910                               "# UDP, fragments discarded without ACK",
2911                               1,
2912                               GNUNET_NO);
2913     return;
2914   }
2915   address = GNUNET_HELLO_address_allocate (&rc->sender,
2916                                            PLUGIN_NAME,
2917                                            rc->udp_addr,
2918                                            rc->udp_addr_len,
2919                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
2920   s = udp_plugin_lookup_session (plugin,
2921                                  address);
2922   GNUNET_HELLO_address_free (address);
2923   if (NULL == s)
2924   {
2925     LOG (GNUNET_ERROR_TYPE_ERROR,
2926          "Trying to transmit ACK to peer `%s' but no session found!\n",
2927          udp_address_to_string (plugin,
2928                                 rc->udp_addr,
2929                                 rc->udp_addr_len));
2930     GNUNET_CONTAINER_heap_remove_node (rc->hnode);
2931     GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
2932     GNUNET_free (rc);
2933     GNUNET_STATISTICS_update (plugin->env->stats,
2934                               "# UDP, ACK transmissions failed",
2935                               1,
2936                               GNUNET_NO);
2937     return;
2938   }
2939   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us ==
2940       s->flow_delay_for_other_peer.rel_value_us)
2941     delay = UINT32_MAX;
2942   else if (s->flow_delay_for_other_peer.rel_value_us < UINT32_MAX)
2943     delay = s->flow_delay_for_other_peer.rel_value_us;
2944   else
2945     delay = UINT32_MAX - 1; /* largest value we can communicate */
2946   LOG (GNUNET_ERROR_TYPE_DEBUG,
2947        "Sending ACK to `%s' including delay of %s\n",
2948        udp_address_to_string (plugin,
2949                               rc->udp_addr,
2950                               rc->udp_addr_len),
2951        GNUNET_STRINGS_relative_time_to_string (s->flow_delay_for_other_peer,
2952                                                GNUNET_YES));
2953   udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + msize);
2954   udpw->msg_size = msize;
2955   udpw->payload_size = 0;
2956   udpw->session = s;
2957   udpw->start_time = GNUNET_TIME_absolute_get ();
2958   udpw->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
2959   udpw->msg_buf = (char *) &udpw[1];
2960   udpw->qc = &ack_message_sent;
2961   udpw->qc_cls = plugin;
2962   udp_ack = (struct UDP_ACK_Message *) udpw->msg_buf;
2963   udp_ack->header.size = htons ((uint16_t) msize);
2964   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
2965   udp_ack->delay = htonl (delay);
2966   udp_ack->sender = *plugin->env->my_identity;
2967   GNUNET_memcpy (&udp_ack[1],
2968           msg,
2969           ntohs (msg->size));
2970   enqueue (plugin,
2971            udpw);
2972   notify_session_monitor (plugin,
2973                           s,
2974                           GNUNET_TRANSPORT_SS_UPDATE);
2975   if (s->address->address_length == sizeof (struct IPv4UdpAddress))
2976     schedule_select_v4 (plugin);
2977   else
2978     schedule_select_v6 (plugin);
2979 }
2980
2981
2982 /**
2983  * We received a fragment, process it.
2984  *
2985  * @param plugin our plugin
2986  * @param msg a message of type #GNUNET_MESSAGE_TYPE_FRAGMENT
2987  * @param udp_addr sender address
2988  * @param udp_addr_len number of bytes in @a udp_addr
2989  * @param network_type network type the address belongs to
2990  */
2991 static void
2992 read_process_fragment (struct Plugin *plugin,
2993                        const struct GNUNET_MessageHeader *msg,
2994                        const union UdpAddress *udp_addr,
2995                        size_t udp_addr_len,
2996                        enum GNUNET_ATS_Network_Type network_type)
2997 {
2998   struct DefragContext *d_ctx;
2999   struct GNUNET_TIME_Absolute now;
3000   struct FindReceiveContext frc;
3001
3002   frc.rc = NULL;
3003   frc.udp_addr = udp_addr;
3004   frc.udp_addr_len = udp_addr_len;
3005
3006   /* Lookup existing receive context for this address */
3007   GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
3008                                  &find_receive_context,
3009                                  &frc);
3010   now = GNUNET_TIME_absolute_get ();
3011   d_ctx = frc.rc;
3012
3013   if (NULL == d_ctx)
3014   {
3015     /* Create a new defragmentation context */
3016     d_ctx = GNUNET_malloc (sizeof (struct DefragContext) + udp_addr_len);
3017     GNUNET_memcpy (&d_ctx[1],
3018             udp_addr,
3019             udp_addr_len);
3020     d_ctx->udp_addr = (const union UdpAddress *) &d_ctx[1];
3021     d_ctx->udp_addr_len = udp_addr_len;
3022     d_ctx->network_type = network_type;
3023     d_ctx->plugin = plugin;
3024     d_ctx->defrag = GNUNET_DEFRAGMENT_context_create (plugin->env->stats,
3025                                                       UDP_MTU,
3026                                                       UDP_MAX_MESSAGES_IN_DEFRAG,
3027                                                       d_ctx,
3028                                                       &fragment_msg_proc,
3029                                                       &ack_proc);
3030     d_ctx->hnode = GNUNET_CONTAINER_heap_insert (plugin->defrag_ctxs,
3031                                                  d_ctx,
3032                                                  (GNUNET_CONTAINER_HeapCostType) now.abs_value_us);
3033     LOG (GNUNET_ERROR_TYPE_DEBUG,
3034          "Created new defragmentation context for %u-byte fragment from `%s'\n",
3035          (unsigned int) ntohs (msg->size),
3036          udp_address_to_string (plugin,
3037                                 udp_addr,
3038                                 udp_addr_len));
3039   }
3040   else
3041   {
3042     LOG (GNUNET_ERROR_TYPE_DEBUG,
3043          "Found existing defragmentation context for %u-byte fragment from `%s'\n",
3044          (unsigned int) ntohs (msg->size),
3045          udp_address_to_string (plugin,
3046                                 udp_addr,
3047                                 udp_addr_len));
3048   }
3049
3050   if (GNUNET_OK ==
3051       GNUNET_DEFRAGMENT_process_fragment (d_ctx->defrag,
3052                                           msg))
3053   {
3054     /* keep this 'rc' from expiring */
3055     GNUNET_CONTAINER_heap_update_cost (d_ctx->hnode,
3056                                        (GNUNET_CONTAINER_HeapCostType) now.abs_value_us);
3057   }
3058   if (GNUNET_CONTAINER_heap_get_size (plugin->defrag_ctxs) >
3059       UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
3060   {
3061     /* remove 'rc' that was inactive the longest */
3062     d_ctx = GNUNET_CONTAINER_heap_remove_root (plugin->defrag_ctxs);
3063     GNUNET_assert (NULL != d_ctx);
3064     GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
3065     GNUNET_free (d_ctx);
3066     GNUNET_STATISTICS_update (plugin->env->stats,
3067                               "# UDP, Defragmentations aborted",
3068                               1,
3069                               GNUNET_NO);
3070   }
3071 }
3072
3073
3074 /**
3075  * Read and process a message from the given socket.
3076  *
3077  * @param plugin the overall plugin
3078  * @param rsock socket to read from
3079  */
3080 static void
3081 udp_select_read (struct Plugin *plugin,
3082                  struct GNUNET_NETWORK_Handle *rsock)
3083 {
3084   socklen_t fromlen;
3085   struct sockaddr_storage addr;
3086   char buf[65536] GNUNET_ALIGN;
3087   ssize_t size;
3088   const struct GNUNET_MessageHeader *msg;
3089   struct IPv4UdpAddress v4;
3090   struct IPv6UdpAddress v6;
3091   const struct sockaddr *sa;
3092   const struct sockaddr_in *sa4;
3093   const struct sockaddr_in6 *sa6;
3094   const union UdpAddress *int_addr;
3095   size_t int_addr_len;
3096   enum GNUNET_ATS_Network_Type network_type;
3097
3098   fromlen = sizeof (addr);
3099   memset (&addr,
3100           0,
3101           sizeof(addr));
3102   size = GNUNET_NETWORK_socket_recvfrom (rsock,
3103                                          buf,
3104                                          sizeof (buf),
3105                                          (struct sockaddr *) &addr,
3106                                          &fromlen);
3107   sa = (const struct sockaddr *) &addr;
3108 #if MINGW
3109   /* On SOCK_DGRAM UDP sockets recvfrom might fail with a
3110    * WSAECONNRESET error to indicate that previous sendto() (yes, sendto!)
3111    * on this socket has failed.
3112    * Quote from MSDN:
3113    *   WSAECONNRESET - The virtual circuit was reset by the remote side
3114    *   executing a hard or abortive close. The application should close
3115    *   the socket; it is no longer usable. On a UDP-datagram socket this
3116    *   error indicates a previous send operation resulted in an ICMP Port
3117    *   Unreachable message.
3118    */
3119   if ( (-1 == size) &&
3120        (ECONNRESET == errno) )
3121     return;
3122 #endif
3123   if (-1 == size)
3124   {
3125     LOG (GNUNET_ERROR_TYPE_DEBUG,
3126          "UDP failed to receive data: %s\n",
3127          STRERROR (errno));
3128     /* Connection failure or something. Not a protocol violation. */
3129     return;
3130   }
3131
3132   /* Check if this is a STUN packet */
3133   if (GNUNET_NO !=
3134       GNUNET_NAT_stun_handle_packet (plugin->nat,
3135                                      (const struct sockaddr *) &addr,
3136                                      fromlen,
3137                                      buf,
3138                                      size))
3139     return; /* was STUN, do not process further */
3140
3141   if (size < sizeof(struct GNUNET_MessageHeader))
3142   {
3143     LOG (GNUNET_ERROR_TYPE_WARNING,
3144          "UDP got %u bytes from %s, which is not enough for a GNUnet message header\n",
3145          (unsigned int ) size,
3146          GNUNET_a2s (sa,
3147                      fromlen));
3148     /* _MAY_ be a connection failure (got partial message) */
3149     /* But it _MAY_ also be that the other side uses non-GNUnet protocol. */
3150     GNUNET_break_op (0);
3151     return;
3152   }
3153
3154   msg = (const struct GNUNET_MessageHeader *) buf;
3155   LOG (GNUNET_ERROR_TYPE_DEBUG,
3156        "UDP received %u-byte message from `%s' type %u\n",
3157        (unsigned int) size,
3158        GNUNET_a2s (sa,
3159                    fromlen),
3160        ntohs (msg->type));
3161   if (size != ntohs (msg->size))
3162   {
3163     LOG (GNUNET_ERROR_TYPE_WARNING,
3164          "UDP malformed message (size %u) header from %s\n",
3165          (unsigned int) size,
3166          GNUNET_a2s (sa,
3167                      fromlen));
3168     GNUNET_break_op (0);
3169     return;
3170   }
3171   GNUNET_STATISTICS_update (plugin->env->stats,
3172                             "# UDP, total bytes received",
3173                             size,
3174                             GNUNET_NO);
3175   network_type = plugin->env->get_address_type (plugin->env->cls,
3176                                                 sa,
3177                                                 fromlen);
3178   switch (sa->sa_family)
3179   {
3180   case AF_INET:
3181     sa4 = (const struct sockaddr_in *) &addr;
3182     v4.options = 0;
3183     v4.ipv4_addr = sa4->sin_addr.s_addr;
3184     v4.u4_port = sa4->sin_port;
3185     int_addr = (union UdpAddress *) &v4;
3186     int_addr_len = sizeof (v4);
3187     break;
3188   case AF_INET6:
3189     sa6 = (const struct sockaddr_in6 *) &addr;
3190     v6.options = 0;
3191     v6.ipv6_addr = sa6->sin6_addr;
3192     v6.u6_port = sa6->sin6_port;
3193     int_addr = (union UdpAddress *) &v6;
3194     int_addr_len = sizeof (v6);
3195     break;
3196   default:
3197     GNUNET_break (0);
3198     return;
3199   }
3200
3201   switch (ntohs (msg->type))
3202   {
3203   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
3204     if (GNUNET_YES == plugin->enable_broadcasting_receiving)
3205       udp_broadcast_receive (plugin,
3206                              buf,
3207                              size,
3208                              int_addr,
3209                              int_addr_len,
3210                              network_type);
3211     return;
3212   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
3213     if (ntohs (msg->size) < sizeof(struct UDPMessage))
3214     {
3215       GNUNET_break_op(0);
3216       return;
3217     }
3218     process_udp_message (plugin,
3219                          (const struct UDPMessage *) msg,
3220                          int_addr,
3221                          int_addr_len,
3222                          network_type);
3223     return;
3224   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
3225     read_process_ack (plugin,
3226                       msg,
3227                       int_addr,
3228                       int_addr_len);
3229     return;
3230   case GNUNET_MESSAGE_TYPE_FRAGMENT:
3231     read_process_fragment (plugin,
3232                            msg,
3233                            int_addr,
3234                            int_addr_len,
3235                            network_type);
3236     return;
3237   default:
3238     GNUNET_break_op(0);
3239     return;
3240   }
3241 }
3242
3243
3244 /**
3245  * Removes messages from the transmission queue that have
3246  * timed out, and then selects a message that should be
3247  * transmitted next.
3248  *
3249  * @param plugin the UDP plugin
3250  * @param sock which socket should we process the queue for (v4 or v6)
3251  * @return message selected for transmission, or NULL for none
3252  */
3253 static struct UDP_MessageWrapper *
3254 remove_timeout_messages_and_select (struct Plugin *plugin,
3255                                     struct GNUNET_NETWORK_Handle *sock)
3256 {
3257   struct UDP_MessageWrapper *udpw;
3258   struct GNUNET_TIME_Relative remaining;
3259   struct GNUNET_ATS_Session *session;
3260   int removed;
3261
3262   removed = GNUNET_NO;
3263   udpw = (sock == plugin->sockv4)
3264     ? plugin->ipv4_queue_head
3265     : plugin->ipv6_queue_head;
3266   while (NULL != udpw)
3267   {
3268     session = udpw->session;
3269     /* Find messages with timeout */
3270     remaining = GNUNET_TIME_absolute_get_remaining (udpw->timeout);
3271     if (GNUNET_TIME_UNIT_ZERO.rel_value_us == remaining.rel_value_us)
3272     {
3273       /* Message timed out */
3274       removed = GNUNET_YES;
3275       dequeue (plugin,
3276                udpw);
3277       udpw->qc (udpw->qc_cls,
3278                 udpw,
3279                 GNUNET_SYSERR);
3280       GNUNET_free (udpw);
3281
3282       if (sock == plugin->sockv4)
3283       {
3284         udpw = plugin->ipv4_queue_head;
3285       }
3286       else if (sock == plugin->sockv6)
3287       {
3288         udpw = plugin->ipv6_queue_head;
3289       }
3290       else
3291       {
3292         GNUNET_break (0); /* should never happen */
3293         udpw = NULL;
3294       }
3295       GNUNET_STATISTICS_update (plugin->env->stats,
3296                                 "# messages discarded due to timeout",
3297                                 1,
3298                                 GNUNET_NO);
3299     }
3300     else
3301     {
3302       /* Message did not time out, check transmission time */
3303       remaining = GNUNET_TIME_absolute_get_remaining (udpw->transmission_time);
3304       if (0 == remaining.rel_value_us)
3305       {
3306         /* this message is not delayed */
3307         LOG (GNUNET_ERROR_TYPE_DEBUG,
3308              "Message for peer `%s' (%u bytes) is not delayed \n",
3309              GNUNET_i2s (&udpw->session->target),
3310              udpw->payload_size);
3311         break; /* Found message to send, break */
3312       }
3313       else
3314       {
3315         /* Message is delayed, try next */
3316         LOG (GNUNET_ERROR_TYPE_DEBUG,
3317              "Message for peer `%s' (%u bytes) is delayed for %s\n",
3318              GNUNET_i2s (&udpw->session->target),
3319              udpw->payload_size,
3320              GNUNET_STRINGS_relative_time_to_string (remaining,
3321                                                      GNUNET_YES));
3322         udpw = udpw->next;
3323       }
3324     }
3325   }
3326   if (GNUNET_YES == removed)
3327     notify_session_monitor (session->plugin,
3328                             session,
3329                             GNUNET_TRANSPORT_SS_UPDATE);
3330   return udpw;
3331 }
3332
3333
3334 /**
3335  * We failed to transmit a message via UDP. Generate
3336  * a descriptive error message.
3337  *
3338  * @param plugin our plugin
3339  * @param sa target address we were trying to reach
3340  * @param slen number of bytes in @a sa
3341  * @param error the errno value returned from the sendto() call
3342  */
3343 static void
3344 analyze_send_error (struct Plugin *plugin,
3345                     const struct sockaddr *sa,
3346                     socklen_t slen,
3347                     int error)
3348 {
3349   enum GNUNET_ATS_Network_Type type;
3350
3351   type = plugin->env->get_address_type (plugin->env->cls,
3352                                         sa,
3353                                         slen);
3354   if ( ( (GNUNET_ATS_NET_LAN == type) ||
3355          (GNUNET_ATS_NET_WAN == type) ) &&
3356        ( (ENETUNREACH == errno) ||
3357          (ENETDOWN == errno) ) )
3358   {
3359     if (slen == sizeof (struct sockaddr_in))
3360     {
3361       /* IPv4: "Network unreachable" or "Network down"
3362        *
3363        * This indicates we do not have connectivity
3364        */
3365       LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
3366            _("UDP could not transmit message to `%s': "
3367              "Network seems down, please check your network configuration\n"),
3368            GNUNET_a2s (sa,
3369                        slen));
3370     }
3371     if (slen == sizeof (struct sockaddr_in6))
3372     {
3373       /* IPv6: "Network unreachable" or "Network down"
3374        *
3375        * This indicates that this system is IPv6 enabled, but does not
3376        * have a valid global IPv6 address assigned or we do not have
3377        * connectivity
3378        */
3379       LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
3380            _("UDP could not transmit IPv6 message! "
3381              "Please check your network configuration and disable IPv6 if your "
3382              "connection does not have a global IPv6 address\n"));
3383     }
3384   }
3385   else
3386   {
3387     LOG (GNUNET_ERROR_TYPE_WARNING,
3388          "UDP could not transmit message to `%s': `%s'\n",
3389          GNUNET_a2s (sa,
3390                      slen),
3391          STRERROR (error));
3392   }
3393 }
3394
3395
3396 /**
3397  * It is time to try to transmit a UDP message.  Select one
3398  * and send.
3399  *
3400  * @param plugin the plugin
3401  * @param sock which socket (v4/v6) to send on
3402  */
3403 static void
3404 udp_select_send (struct Plugin *plugin,
3405                  struct GNUNET_NETWORK_Handle *sock)
3406 {
3407   ssize_t sent;
3408   socklen_t slen;
3409   const struct sockaddr *a;
3410   const struct IPv4UdpAddress *u4;
3411   struct sockaddr_in a4;
3412   const struct IPv6UdpAddress *u6;
3413   struct sockaddr_in6 a6;
3414   struct UDP_MessageWrapper *udpw;
3415
3416   /* Find message(s) to send */
3417   while (NULL != (udpw = remove_timeout_messages_and_select (plugin,
3418                                                              sock)))
3419   {
3420     if (sizeof (struct IPv4UdpAddress) == udpw->session->address->address_length)
3421     {
3422       u4 = udpw->session->address->address;
3423       memset (&a4,
3424               0,
3425               sizeof(a4));
3426       a4.sin_family = AF_INET;
3427 #if HAVE_SOCKADDR_IN_SIN_LEN
3428       a4.sin_len = sizeof (a4);
3429 #endif
3430       a4.sin_port = u4->u4_port;
3431       a4.sin_addr.s_addr = u4->ipv4_addr;
3432       a = (const struct sockaddr *) &a4;
3433       slen = sizeof (a4);
3434     }
3435     else if (sizeof (struct IPv6UdpAddress) == udpw->session->address->address_length)
3436     {
3437       u6 = udpw->session->address->address;
3438       memset (&a6,
3439               0,
3440               sizeof(a6));
3441       a6.sin6_family = AF_INET6;
3442 #if HAVE_SOCKADDR_IN_SIN_LEN
3443       a6.sin6_len = sizeof (a6);
3444 #endif
3445       a6.sin6_port = u6->u6_port;
3446       a6.sin6_addr = u6->ipv6_addr;
3447       a = (const struct sockaddr *) &a6;
3448       slen = sizeof (a6);
3449     }
3450     else
3451     {
3452       GNUNET_break (0);
3453       dequeue (plugin,
3454                udpw);
3455       udpw->qc (udpw->qc_cls,
3456                 udpw,
3457                 GNUNET_SYSERR);
3458       notify_session_monitor (plugin,
3459                               udpw->session,
3460                               GNUNET_TRANSPORT_SS_UPDATE);
3461       GNUNET_free (udpw);
3462       continue;
3463     }
3464     sent = GNUNET_NETWORK_socket_sendto (sock,
3465                                          udpw->msg_buf,
3466                                          udpw->msg_size,
3467                                          a,
3468                                          slen);
3469     udpw->session->last_transmit_time
3470       = GNUNET_TIME_absolute_max (GNUNET_TIME_absolute_get (),
3471                                   udpw->session->last_transmit_time);
3472     dequeue (plugin,
3473              udpw);
3474     if (GNUNET_SYSERR == sent)
3475     {
3476       /* Failure */
3477       analyze_send_error (plugin,
3478                           a,
3479                           slen,
3480                           errno);
3481       udpw->qc (udpw->qc_cls,
3482                 udpw,
3483                 GNUNET_SYSERR);
3484       GNUNET_STATISTICS_update (plugin->env->stats,
3485                                 "# UDP, total, bytes, sent, failure",
3486                                 sent,
3487                                 GNUNET_NO);
3488       GNUNET_STATISTICS_update (plugin->env->stats,
3489                                 "# UDP, total, messages, sent, failure",
3490                                 1,
3491                                 GNUNET_NO);
3492     }
3493     else
3494     {
3495       /* Success */
3496       LOG (GNUNET_ERROR_TYPE_DEBUG,
3497            "UDP transmitted %u-byte message to  `%s' `%s' (%d: %s)\n",
3498            (unsigned int) (udpw->msg_size),
3499            GNUNET_i2s (&udpw->session->target),
3500            GNUNET_a2s (a,
3501                        slen),
3502            (int ) sent,
3503            (sent < 0) ? STRERROR (errno) : "ok");
3504       GNUNET_STATISTICS_update (plugin->env->stats,
3505                                 "# UDP, total, bytes, sent, success",
3506                                 sent,
3507                                 GNUNET_NO);
3508       GNUNET_STATISTICS_update (plugin->env->stats,
3509                                 "# UDP, total, messages, sent, success",
3510                                 1,
3511                                 GNUNET_NO);
3512       if (NULL != udpw->frag_ctx)
3513         udpw->frag_ctx->on_wire_size += udpw->msg_size;
3514       udpw->qc (udpw->qc_cls,
3515                 udpw,
3516                 GNUNET_OK);
3517     }
3518     notify_session_monitor (plugin,
3519                             udpw->session,
3520                             GNUNET_TRANSPORT_SS_UPDATE);
3521     GNUNET_free (udpw);
3522   }
3523 }
3524
3525
3526 /* ***************** Event loop (part 2) *************** */
3527
3528
3529 /**
3530  * We have been notified that our readset has something to read.  We don't
3531  * know which socket needs to be read, so we have to check each one
3532  * Then reschedule this function to be called again once more is available.
3533  *
3534  * @param cls the plugin handle
3535  */
3536 static void
3537 udp_plugin_select_v4 (void *cls)
3538 {
3539   struct Plugin *plugin = cls;
3540   const struct GNUNET_SCHEDULER_TaskContext *tc;
3541
3542   plugin->select_task_v4 = NULL;
3543   if (NULL == plugin->sockv4)
3544     return;
3545   tc = GNUNET_SCHEDULER_get_task_context ();
3546   if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
3547       (GNUNET_NETWORK_fdset_isset (tc->read_ready,
3548                                    plugin->sockv4)))
3549     udp_select_read (plugin,
3550                      plugin->sockv4);
3551   udp_select_send (plugin,
3552                    plugin->sockv4);
3553   schedule_select_v4 (plugin);
3554 }
3555
3556
3557 /**
3558  * We have been notified that our readset has something to read.  We don't
3559  * know which socket needs to be read, so we have to check each one
3560  * Then reschedule this function to be called again once more is available.
3561  *
3562  * @param cls the plugin handle
3563  */
3564 static void
3565 udp_plugin_select_v6 (void *cls)
3566 {
3567   struct Plugin *plugin = cls;
3568   const struct GNUNET_SCHEDULER_TaskContext *tc;
3569
3570   plugin->select_task_v6 = NULL;
3571   if (NULL == plugin->sockv6)
3572     return;
3573   tc = GNUNET_SCHEDULER_get_task_context ();
3574   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
3575        (GNUNET_NETWORK_fdset_isset (tc->read_ready,
3576                                     plugin->sockv6)) )
3577     udp_select_read (plugin,
3578                      plugin->sockv6);
3579
3580   udp_select_send (plugin,
3581                    plugin->sockv6);
3582   schedule_select_v6 (plugin);
3583 }
3584
3585
3586 /* ******************* Initialization *************** */
3587
3588
3589 /**
3590  * Setup the UDP sockets (for IPv4 and IPv6) for the plugin.
3591  *
3592  * @param plugin the plugin to initialize
3593  * @param bind_v6 IPv6 address to bind to (can be NULL, for 'any')
3594  * @param bind_v4 IPv4 address to bind to (can be NULL, for 'any')
3595  * @return number of sockets that were successfully bound
3596  */
3597 static unsigned int
3598 setup_sockets (struct Plugin *plugin,
3599                const struct sockaddr_in6 *bind_v6,
3600                const struct sockaddr_in *bind_v4)
3601 {
3602   int tries;
3603   unsigned int sockets_created = 0;
3604   struct sockaddr_in6 server_addrv6;
3605   struct sockaddr_in server_addrv4;
3606   const struct sockaddr *server_addr;
3607   const struct sockaddr *addrs[2];
3608   socklen_t addrlens[2];
3609   socklen_t addrlen;
3610   int eno;
3611
3612   /* Create IPv6 socket */
3613   eno = EINVAL;
3614   if (GNUNET_YES == plugin->enable_ipv6)
3615   {
3616     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6,
3617                                                    SOCK_DGRAM,
3618                                                    0);
3619     if (NULL == plugin->sockv6)
3620     {
3621       LOG (GNUNET_ERROR_TYPE_INFO,
3622            _("Disabling IPv6 since it is not supported on this system!\n"));
3623       plugin->enable_ipv6 = GNUNET_NO;
3624     }
3625     else
3626     {
3627       memset (&server_addrv6,
3628               0,
3629               sizeof(struct sockaddr_in6));
3630 #if HAVE_SOCKADDR_IN_SIN_LEN
3631       server_addrv6.sin6_len = sizeof (struct sockaddr_in6);
3632 #endif
3633       server_addrv6.sin6_family = AF_INET6;
3634       if (NULL != bind_v6)
3635         server_addrv6.sin6_addr = bind_v6->sin6_addr;
3636       else
3637         server_addrv6.sin6_addr = in6addr_any;
3638
3639       if (0 == plugin->port) /* autodetect */
3640         server_addrv6.sin6_port
3641           = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG,
3642                                              33537)
3643                    + 32000);
3644       else
3645         server_addrv6.sin6_port = htons (plugin->port);
3646       addrlen = sizeof (struct sockaddr_in6);
3647       server_addr = (const struct sockaddr *) &server_addrv6;
3648
3649       tries = 0;
3650       while (tries < 10)
3651       {
3652         LOG(GNUNET_ERROR_TYPE_DEBUG,
3653             "Binding to IPv6 `%s'\n",
3654             GNUNET_a2s (server_addr,
3655                         addrlen));
3656         /* binding */
3657         if (GNUNET_OK ==
3658             GNUNET_NETWORK_socket_bind (plugin->sockv6,
3659                                         server_addr,
3660                                         addrlen))
3661           break;
3662         eno = errno;
3663         if (0 != plugin->port)
3664         {
3665           tries = 10; /* fail immediately */
3666           break; /* bind failed on specific port */
3667         }
3668         /* autodetect */
3669         server_addrv6.sin6_port
3670           = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG,
3671                                              33537)
3672                    + 32000);
3673         tries++;
3674       }
3675       if (tries >= 10)
3676       {
3677         GNUNET_NETWORK_socket_close (plugin->sockv6);
3678         plugin->enable_ipv6 = GNUNET_NO;
3679         plugin->sockv6 = NULL;
3680       }
3681       else
3682       {
3683         plugin->port = ntohs (server_addrv6.sin6_port);
3684       }
3685       if (NULL != plugin->sockv6)
3686       {
3687         LOG (GNUNET_ERROR_TYPE_DEBUG,
3688              "IPv6 UDP socket created listinging at %s\n",
3689              GNUNET_a2s (server_addr,
3690                          addrlen));
3691         addrs[sockets_created] = server_addr;
3692         addrlens[sockets_created] = addrlen;
3693         sockets_created++;
3694       }
3695       else
3696       {
3697         LOG (GNUNET_ERROR_TYPE_WARNING,
3698              _("Failed to bind UDP socket to %s: %s\n"),
3699              GNUNET_a2s (server_addr,
3700                          addrlen),
3701              STRERROR (eno));
3702       }
3703     }
3704   }
3705
3706   /* Create IPv4 socket */
3707   eno = EINVAL;
3708   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET,
3709                                                  SOCK_DGRAM,
3710                                                  0);
3711   if (NULL == plugin->sockv4)
3712   {
3713     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
3714                          "socket");
3715     LOG (GNUNET_ERROR_TYPE_INFO,
3716          _("Disabling IPv4 since it is not supported on this system!\n"));
3717     plugin->enable_ipv4 = GNUNET_NO;
3718   }
3719   else
3720   {
3721     memset (&server_addrv4,
3722             0,
3723             sizeof(struct sockaddr_in));
3724 #if HAVE_SOCKADDR_IN_SIN_LEN
3725     server_addrv4.sin_len = sizeof (struct sockaddr_in);
3726 #endif
3727     server_addrv4.sin_family = AF_INET;
3728     if (NULL != bind_v4)
3729       server_addrv4.sin_addr = bind_v4->sin_addr;
3730     else
3731       server_addrv4.sin_addr.s_addr = INADDR_ANY;
3732
3733     if (0 == plugin->port)
3734       /* autodetect */
3735       server_addrv4.sin_port
3736         = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG,
3737                                            33537)
3738                  + 32000);
3739     else
3740       server_addrv4.sin_port = htons (plugin->port);
3741
3742     addrlen = sizeof (struct sockaddr_in);
3743     server_addr = (const struct sockaddr *) &server_addrv4;
3744
3745     tries = 0;
3746     while (tries < 10)
3747     {
3748       LOG (GNUNET_ERROR_TYPE_DEBUG,
3749            "Binding to IPv4 `%s'\n",
3750            GNUNET_a2s (server_addr,
3751                        addrlen));
3752
3753       /* binding */
3754       if (GNUNET_OK ==
3755           GNUNET_NETWORK_socket_bind (plugin->sockv4,
3756                                       server_addr,
3757                                       addrlen))
3758         break;
3759       eno = errno;
3760       if (0 != plugin->port)
3761       {
3762         tries = 10; /* fail */
3763         break; /* bind failed on specific port */
3764       }
3765
3766       /* autodetect */
3767       server_addrv4.sin_port
3768         = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG,
3769                                            33537)
3770                  + 32000);
3771       tries++;
3772     }
3773     if (tries >= 10)
3774     {
3775       GNUNET_NETWORK_socket_close (plugin->sockv4);
3776       plugin->enable_ipv4 = GNUNET_NO;
3777       plugin->sockv4 = NULL;
3778     }
3779     else
3780     {
3781       plugin->port = ntohs (server_addrv4.sin_port);
3782     }
3783
3784     if (NULL != plugin->sockv4)
3785     {
3786       LOG (GNUNET_ERROR_TYPE_DEBUG,
3787            "IPv4 socket created on port %s\n",
3788            GNUNET_a2s (server_addr,
3789                        addrlen));
3790       addrs[sockets_created] = server_addr;
3791       addrlens[sockets_created] = addrlen;
3792       sockets_created++;
3793     }
3794     else
3795     {
3796       LOG (GNUNET_ERROR_TYPE_ERROR,
3797            _("Failed to bind UDP socket to %s: %s\n"),
3798            GNUNET_a2s (server_addr,
3799                        addrlen),
3800            STRERROR (eno));
3801     }
3802   }
3803
3804   if (0 == sockets_created)
3805   {
3806     LOG (GNUNET_ERROR_TYPE_WARNING,
3807          _("Failed to open UDP sockets\n"));
3808     return 0; /* No sockets created, return */
3809   }
3810   schedule_select_v4 (plugin);
3811   schedule_select_v6 (plugin);
3812   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
3813                                      "transport-udp",
3814                                      IPPROTO_UDP,
3815                                      sockets_created,
3816                                      addrs,
3817                                      addrlens,
3818                                      &udp_nat_port_map_callback,
3819                                      NULL,
3820                                      plugin);
3821   return sockets_created;
3822 }
3823
3824
3825 /**
3826  * The exported method. Makes the core api available via a global and
3827  * returns the udp transport API.
3828  *
3829  * @param cls our `struct GNUNET_TRANSPORT_PluginEnvironment`
3830  * @return our `struct GNUNET_TRANSPORT_PluginFunctions`
3831  */
3832 void *
3833 libgnunet_plugin_transport_udp_init (void *cls)
3834 {
3835   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3836   struct GNUNET_TRANSPORT_PluginFunctions *api;
3837   struct Plugin *p;
3838   unsigned long long port;
3839   unsigned long long aport;
3840   unsigned long long udp_max_bps;
3841   unsigned long long enable_v6;
3842   unsigned long long enable_broadcasting;
3843   unsigned long long enable_broadcasting_recv;
3844   char *bind4_address;
3845   char *bind6_address;
3846   struct GNUNET_TIME_Relative interval;
3847   struct sockaddr_in server_addrv4;
3848   struct sockaddr_in6 server_addrv6;
3849   unsigned int res;
3850   int have_bind4;
3851   int have_bind6;
3852
3853   if (NULL == env->receive)
3854   {
3855     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3856      initialze the plugin or the API */
3857     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3858     api->cls = NULL;
3859     api->address_pretty_printer = &udp_plugin_address_pretty_printer;
3860     api->address_to_string = &udp_address_to_string;
3861     api->string_to_address = &udp_string_to_address;
3862     return api;
3863   }
3864
3865   /* Get port number: port == 0 : autodetect a port,
3866    * > 0 : use this port, not given : 2086 default */
3867   if (GNUNET_OK !=
3868       GNUNET_CONFIGURATION_get_value_number (env->cfg,
3869                                              "transport-udp",
3870                                              "PORT",
3871                                              &port))
3872     port = 2086;
3873   if (port > 65535)
3874   {
3875     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
3876                                "transport-udp",
3877                                "PORT",
3878                                _("must be in [0,65535]"));
3879     return NULL;
3880   }
3881   if (GNUNET_OK !=
3882       GNUNET_CONFIGURATION_get_value_number (env->cfg,
3883                                              "transport-udp",
3884                                              "ADVERTISED_PORT",
3885                                              &aport))
3886     aport = port;
3887   if (aport > 65535)
3888   {
3889     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
3890                                "transport-udp",
3891                                "ADVERTISED_PORT",
3892                                _("must be in [0,65535]"));
3893     return NULL;
3894   }
3895
3896   if (GNUNET_YES ==
3897       GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3898                                             "nat",
3899                                             "DISABLEV6"))
3900     enable_v6 = GNUNET_NO;
3901   else
3902     enable_v6 = GNUNET_YES;
3903
3904   have_bind4 = GNUNET_NO;
3905   memset (&server_addrv4,
3906           0,
3907           sizeof (server_addrv4));
3908   if (GNUNET_YES ==
3909       GNUNET_CONFIGURATION_get_value_string (env->cfg,
3910                                              "transport-udp",
3911                                              "BINDTO",
3912                                              &bind4_address))
3913   {
3914     LOG (GNUNET_ERROR_TYPE_DEBUG,
3915          "Binding UDP plugin to specific address: `%s'\n",
3916          bind4_address);
3917     if (1 != inet_pton (AF_INET,
3918                         bind4_address,
3919                         &server_addrv4.sin_addr))
3920     {
3921       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
3922                                  "transport-udp",
3923                                  "BINDTO",
3924                                  _("must be valid IPv4 address"));
3925       GNUNET_free (bind4_address);
3926       return NULL;
3927     }
3928     have_bind4 = GNUNET_YES;
3929   }
3930   GNUNET_free_non_null (bind4_address);
3931   have_bind6 = GNUNET_NO;
3932   memset (&server_addrv6,
3933           0,
3934           sizeof (server_addrv6));
3935   if (GNUNET_YES ==
3936       GNUNET_CONFIGURATION_get_value_string (env->cfg,
3937                                              "transport-udp",
3938                                              "BINDTO6",
3939                                              &bind6_address))
3940   {
3941     LOG (GNUNET_ERROR_TYPE_DEBUG,
3942          "Binding udp plugin to specific address: `%s'\n",
3943          bind6_address);
3944     if (1 != inet_pton (AF_INET6,
3945                         bind6_address,
3946                         &server_addrv6.sin6_addr))
3947     {
3948       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
3949                                  "transport-udp",
3950                                  "BINDTO6",
3951                                  _("must be valid IPv6 address"));
3952       GNUNET_free (bind6_address);
3953       return NULL;
3954     }
3955     have_bind6 = GNUNET_YES;
3956   }
3957   GNUNET_free_non_null (bind6_address);
3958
3959   enable_broadcasting = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3960                                                               "transport-udp",
3961                                                               "BROADCAST");
3962   if (enable_broadcasting == GNUNET_SYSERR)
3963     enable_broadcasting = GNUNET_NO;
3964
3965   enable_broadcasting_recv = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3966                                                                    "transport-udp",
3967                                                                    "BROADCAST_RECEIVE");
3968   if (enable_broadcasting_recv == GNUNET_SYSERR)
3969     enable_broadcasting_recv = GNUNET_YES;
3970
3971   if (GNUNET_SYSERR ==
3972       GNUNET_CONFIGURATION_get_value_time (env->cfg,
3973                                            "transport-udp",
3974                                            "BROADCAST_INTERVAL",
3975                                            &interval))
3976   {
3977     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
3978                                               10);
3979   }
3980   if (GNUNET_OK !=
3981       GNUNET_CONFIGURATION_get_value_number (env->cfg,
3982                                              "transport-udp",
3983                                              "MAX_BPS",
3984                                              &udp_max_bps))
3985   {
3986     /* 50 MB/s == infinity for practical purposes */
3987     udp_max_bps = 1024 * 1024 * 50;
3988   }
3989
3990   p = GNUNET_new (struct Plugin);
3991   p->port = port;
3992   p->aport = aport;
3993   p->broadcast_interval = interval;
3994   p->enable_ipv6 = enable_v6;
3995   p->enable_ipv4 = GNUNET_YES; /* default */
3996   p->enable_broadcasting = enable_broadcasting;
3997   p->enable_broadcasting_receiving = enable_broadcasting_recv;
3998   p->env = env;
3999   p->sessions = GNUNET_CONTAINER_multipeermap_create (16,
4000                                                       GNUNET_NO);
4001   p->defrag_ctxs = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4002   GNUNET_BANDWIDTH_tracker_init (&p->tracker,
4003                                  NULL,
4004                                  NULL,
4005                                  GNUNET_BANDWIDTH_value_init ((uint32_t) udp_max_bps),
4006                                  30);
4007   res = setup_sockets (p,
4008                        (GNUNET_YES == have_bind6) ? &server_addrv6 : NULL,
4009                        (GNUNET_YES == have_bind4) ? &server_addrv4 : NULL);
4010   if ( (0 == res) ||
4011        ( (NULL == p->sockv4) &&
4012          (NULL == p->sockv6) ) )
4013   {
4014     LOG (GNUNET_ERROR_TYPE_ERROR,
4015         _("Failed to create UDP network sockets\n"));
4016     GNUNET_CONTAINER_multipeermap_destroy (p->sessions);
4017     GNUNET_CONTAINER_heap_destroy (p->defrag_ctxs);
4018     if (NULL != p->nat)
4019       GNUNET_NAT_unregister (p->nat);
4020     GNUNET_free (p);
4021     return NULL;
4022   }
4023
4024   /* Setup broadcasting and receiving beacons */
4025   setup_broadcast (p,
4026                    &server_addrv6,
4027                    &server_addrv4);
4028
4029   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
4030   api->cls = p;
4031   api->disconnect_session = &udp_disconnect_session;
4032   api->query_keepalive_factor = &udp_query_keepalive_factor;
4033   api->disconnect_peer = &udp_disconnect;
4034   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
4035   api->address_to_string = &udp_address_to_string;
4036   api->string_to_address = &udp_string_to_address;
4037   api->check_address = &udp_plugin_check_address;
4038   api->get_session = &udp_plugin_get_session;
4039   api->send = &udp_plugin_send;
4040   api->get_network = &udp_plugin_get_network;
4041   api->get_network_for_address = &udp_plugin_get_network_for_address;
4042   api->update_session_timeout = &udp_plugin_update_session_timeout;
4043   api->setup_monitor = &udp_plugin_setup_monitor;
4044   return api;
4045 }
4046
4047
4048 /**
4049  * Function called on each entry in the defragmentation heap to
4050  * clean it up.
4051  *
4052  * @param cls NULL
4053  * @param node node in the heap (to be removed)
4054  * @param element a `struct DefragContext` to be cleaned up
4055  * @param cost unused
4056  * @return #GNUNET_YES
4057  */
4058 static int
4059 heap_cleanup_iterator (void *cls,
4060                        struct GNUNET_CONTAINER_HeapNode *node,
4061                        void *element,
4062                        GNUNET_CONTAINER_HeapCostType cost)
4063 {
4064   struct DefragContext *d_ctx = element;
4065
4066   GNUNET_CONTAINER_heap_remove_node (node);
4067   GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
4068   GNUNET_free (d_ctx);
4069   return GNUNET_YES;
4070 }
4071
4072
4073 /**
4074  * The exported method. Makes the core api available via a global and
4075  * returns the udp transport API.
4076  *
4077  * @param cls our `struct GNUNET_TRANSPORT_PluginEnvironment`
4078  * @return NULL
4079  */
4080 void *
4081 libgnunet_plugin_transport_udp_done (void *cls)
4082 {
4083   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
4084   struct Plugin *plugin = api->cls;
4085   struct PrettyPrinterContext *cur;
4086   struct UDP_MessageWrapper *udpw;
4087
4088   if (NULL == plugin)
4089   {
4090     GNUNET_free (api);
4091     return NULL;
4092   }
4093   stop_broadcast (plugin);
4094   if (NULL != plugin->select_task_v4)
4095   {
4096     GNUNET_SCHEDULER_cancel (plugin->select_task_v4);
4097     plugin->select_task_v4 = NULL;
4098   }
4099   if (NULL != plugin->select_task_v6)
4100   {
4101     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
4102     plugin->select_task_v6 = NULL;
4103   }
4104   if (NULL != plugin->sockv4)
4105   {
4106     GNUNET_break (GNUNET_OK ==
4107                   GNUNET_NETWORK_socket_close (plugin->sockv4));
4108     plugin->sockv4 = NULL;
4109   }
4110   if (NULL != plugin->sockv6)
4111   {
4112     GNUNET_break (GNUNET_OK ==
4113                   GNUNET_NETWORK_socket_close (plugin->sockv6));
4114     plugin->sockv6 = NULL;
4115   }
4116   if (NULL != plugin->nat)
4117   {
4118     GNUNET_NAT_unregister (plugin->nat);
4119     plugin->nat = NULL;
4120   }
4121   if (NULL != plugin->defrag_ctxs)
4122   {
4123     GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
4124                                    &heap_cleanup_iterator,
4125                                    NULL);
4126     GNUNET_CONTAINER_heap_destroy (plugin->defrag_ctxs);
4127     plugin->defrag_ctxs = NULL;
4128   }
4129   while (NULL != (udpw = plugin->ipv4_queue_head))
4130   {
4131     dequeue (plugin,
4132              udpw);
4133     udpw->qc (udpw->qc_cls,
4134               udpw,
4135               GNUNET_SYSERR);
4136     GNUNET_free (udpw);
4137   }
4138   while (NULL != (udpw = plugin->ipv6_queue_head))
4139   {
4140     dequeue (plugin,
4141              udpw);
4142     udpw->qc (udpw->qc_cls,
4143               udpw,
4144               GNUNET_SYSERR);
4145     GNUNET_free (udpw);
4146   }
4147   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
4148                                          &disconnect_and_free_it,
4149                                          plugin);
4150   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
4151
4152   while (NULL != (cur = plugin->ppc_dll_head))
4153   {
4154     GNUNET_break (0);
4155     GNUNET_CONTAINER_DLL_remove (plugin->ppc_dll_head,
4156                                  plugin->ppc_dll_tail,
4157                                  cur);
4158     GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
4159     if (NULL != cur->timeout_task)
4160     {
4161       GNUNET_SCHEDULER_cancel (cur->timeout_task);
4162       cur->timeout_task = NULL;
4163     }
4164     GNUNET_free (cur);
4165   }
4166   GNUNET_free (plugin);
4167   GNUNET_free (api);
4168   return NULL;
4169 }
4170
4171 /* end of plugin_transport_udp.c */