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