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