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