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