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