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