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