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