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