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