splitting 'struct GNUNET_CRYPTO_EccPublicKey' into one struct for signing and another...
[oweals/gnunet.git] / src / transport / plugin_transport_udp.c
1 /*
2      This file is part of GNUnet
3      (C) 2010-2013 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  * Cancel timeout
468  */
469 static void
470 stop_session_timeout (struct Session *s)
471 {
472   GNUNET_assert (NULL != s);
473
474   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
475   {
476     GNUNET_SCHEDULER_cancel (s->timeout_task);
477     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
478     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
479                 "Timeout stopped for session %p canceled\n",
480                 s);
481   }
482 }
483
484
485 /**
486  * (re)schedule select tasks for this plugin.
487  *
488  * @param plugin plugin to reschedule
489  */
490 static void
491 schedule_select (struct Plugin *plugin)
492 {
493   struct GNUNET_TIME_Relative min_delay;
494   struct UDP_MessageWrapper *udpw;
495
496   if ((GNUNET_YES == plugin->enable_ipv4) && (NULL != plugin->sockv4))
497   {
498     /* Find a message ready to send:
499      * Flow delay from other peer is expired or not set (0) */
500     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
501     for (udpw = plugin->ipv4_queue_head; NULL != udpw; udpw = udpw->next)
502       min_delay = GNUNET_TIME_relative_min (min_delay,
503                                             GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer));
504     
505     if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
506       GNUNET_SCHEDULER_cancel(plugin->select_task);
507
508     /* Schedule with:
509      * - write active set if message is ready
510      * - timeout minimum delay */
511     plugin->select_task =
512       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
513                                    (0 == min_delay.rel_value_us) ? GNUNET_TIME_UNIT_FOREVER_REL : min_delay,
514                                    plugin->rs_v4,
515                                    (0 == min_delay.rel_value_us) ? plugin->ws_v4 : NULL,
516                                    &udp_plugin_select, plugin);  
517   }
518   if ((GNUNET_YES == plugin->enable_ipv6) && (NULL != plugin->sockv6))
519   {
520     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
521     for (udpw = plugin->ipv6_queue_head; NULL != udpw; udpw = udpw->next)
522       min_delay = GNUNET_TIME_relative_min (min_delay,
523                                             GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer));
524     
525     if (GNUNET_SCHEDULER_NO_TASK != plugin->select_task_v6)
526       GNUNET_SCHEDULER_cancel(plugin->select_task_v6);
527     plugin->select_task_v6 =
528       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
529                                    (0 == min_delay.rel_value_us) ? GNUNET_TIME_UNIT_FOREVER_REL : min_delay,
530                                    plugin->rs_v6,
531                                    (0 == min_delay.rel_value_us) ? plugin->ws_v6 : NULL,
532                                    &udp_plugin_select_v6, plugin);
533   }
534 }
535
536
537 /**
538  * Function called for a quick conversion of the binary address to
539  * a numeric address.  Note that the caller must not free the
540  * address and that the next call to this function is allowed
541  * to override the address again.
542  *
543  * @param cls closure
544  * @param addr binary address
545  * @param addrlen length of the address
546  * @return string representing the same address
547  */
548 const char *
549 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
550 {
551   static char rbuf[INET6_ADDRSTRLEN + 10];
552   char buf[INET6_ADDRSTRLEN];
553   const void *sb;
554   struct in_addr a4;
555   struct in6_addr a6;
556   const struct IPv4UdpAddress *t4;
557   const struct IPv6UdpAddress *t6;
558   int af;
559   uint16_t port;
560   uint32_t options;
561
562   if ((NULL != addr) && (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 ((NULL != addr) && (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), 
592                    (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u",
593                    PLUGIN_NAME, options, buf, port);
594   return rbuf;
595 }
596
597
598 /**
599  * Function called to convert a string address to
600  * a binary address.
601  *
602  * @param cls closure ('struct Plugin*')
603  * @param addr string address
604  * @param addrlen length of the address
605  * @param buf location to store the buffer
606  * @param added location to store the number of bytes in the buffer.
607  *        If the function returns GNUNET_SYSERR, its contents are undefined.
608  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
609  */
610 static int
611 udp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
612     void **buf, size_t *added)
613 {
614   struct sockaddr_storage socket_address;
615   char *address;
616   char *plugin;
617   char *optionstr;
618   uint32_t options;
619
620   /* Format tcp.options.address:port */
621   address = NULL;
622   plugin = NULL;
623   optionstr = NULL;
624
625   if ((NULL == addr) || (addrlen == 0))
626   {
627     GNUNET_break (0);
628     return GNUNET_SYSERR;
629   }
630   if ('\0' != addr[addrlen - 1])
631   {
632     GNUNET_break (0);
633     return GNUNET_SYSERR;
634   }
635   if (strlen (addr) != addrlen - 1)
636   {
637     GNUNET_break (0);
638     return GNUNET_SYSERR;
639   }
640   plugin = GNUNET_strdup (addr);
641   optionstr = strchr (plugin, '.');
642   if (NULL == optionstr)
643   {
644     GNUNET_break (0);
645     GNUNET_free (plugin);
646     return GNUNET_SYSERR;
647   }
648   optionstr[0] = '\0';
649   optionstr ++;
650   options = atol (optionstr);
651   address = strchr (optionstr, '.');
652   if (NULL == address)
653   {
654     GNUNET_break (0);
655     GNUNET_free (plugin);
656     return GNUNET_SYSERR;
657   }
658   address[0] = '\0';
659   address ++;
660
661   if (GNUNET_OK !=
662       GNUNET_STRINGS_to_address_ip (address, strlen (address),
663                                     &socket_address))
664   {
665     GNUNET_break (0);
666     GNUNET_free (plugin);
667     return GNUNET_SYSERR;
668   }
669
670   GNUNET_free (plugin);
671
672   switch (socket_address.ss_family)
673   {
674   case AF_INET:
675     {
676       struct IPv4UdpAddress *u4;
677       struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
678       u4 = GNUNET_malloc (sizeof (struct IPv4UdpAddress));
679       u4->options =  htonl (options);
680       u4->ipv4_addr = in4->sin_addr.s_addr;
681       u4->u4_port = in4->sin_port;
682       *buf = u4;
683       *added = sizeof (struct IPv4UdpAddress);
684       return GNUNET_OK;
685     }
686   case AF_INET6:
687     {
688       struct IPv6UdpAddress *u6;
689       struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
690       u6 = GNUNET_malloc (sizeof (struct IPv6UdpAddress));
691       u6->options =  htonl (options);
692       u6->ipv6_addr = in6->sin6_addr;
693       u6->u6_port = in6->sin6_port;
694       *buf = u6;
695       *added = sizeof (struct IPv6UdpAddress);
696       return GNUNET_OK;
697     }
698   default:
699     GNUNET_break (0);
700     return GNUNET_SYSERR;
701   }
702 }
703
704
705 static void
706 ppc_cancel_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
707 {
708         struct PrettyPrinterContext *ppc = cls;
709         /* GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PPC %p was not removed!\n", ppc); */
710         ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
711         if (NULL != ppc->resolver_handle)
712         {
713                 GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
714                 ppc->resolver_handle = NULL;
715         }
716
717         GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
718         GNUNET_free (ppc);
719 }
720
721
722 /**
723  * Append our port and forward the result.
724  *
725  * @param cls a 'struct PrettyPrinterContext'
726  * @param hostname result from DNS resolver
727  */
728 static void
729 append_port (void *cls, const char *hostname)
730 {
731   struct PrettyPrinterContext *ppc = cls;
732   struct PrettyPrinterContext *cur;
733   char *ret;
734         /* GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "PPC callback: %p `%s'\n",ppc, hostname); */
735   if (hostname == NULL)
736   {
737     ppc->asc (ppc->asc_cls, NULL);
738     GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
739     GNUNET_SCHEDULER_cancel (ppc->timeout_task);
740     ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
741     ppc->resolver_handle = NULL;
742         /* GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "PPC %p was removed!\n", ppc); */
743     GNUNET_free (ppc);
744     return;
745   }
746   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
747   {
748         if (cur == ppc)
749                 break;
750   }
751   if (NULL == cur)
752   {
753         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid callback for PPC %p \n", ppc);
754         return;
755   }
756
757   if (GNUNET_YES == ppc->ipv6)
758     GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
759   else
760     GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
761   ppc->asc (ppc->asc_cls, ret);
762   GNUNET_free (ret);
763 }
764
765 /**
766  * Convert the transports address to a nice, human-readable
767  * format.
768  *
769  * @param cls closure
770  * @param type name of the transport that generated the address
771  * @param addr one of the addresses of the host, NULL for the last address
772  *        the specific address format depends on the transport
773  * @param addrlen length of the address
774  * @param numeric should (IP) addresses be displayed in numeric form?
775  * @param timeout after how long should we give up?
776  * @param asc function to call on each string
777  * @param asc_cls closure for asc
778  */
779 static void
780 udp_plugin_address_pretty_printer (void *cls, const char *type,
781                                    const void *addr, size_t addrlen,
782                                    int numeric,
783                                    struct GNUNET_TIME_Relative timeout,
784                                    GNUNET_TRANSPORT_AddressStringCallback asc,
785                                    void *asc_cls)
786 {
787   struct PrettyPrinterContext *ppc;
788   const void *sb;
789   size_t sbs;
790   struct sockaddr_in a4;
791   struct sockaddr_in6 a6;
792   const struct IPv4UdpAddress *u4;
793   const struct IPv6UdpAddress *u6;
794   uint16_t port;
795   uint32_t options;
796
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
1144 static void
1145 fragmented_message_done (struct UDP_FragmentationContext *fc, int result)
1146 {
1147   struct UDP_MessageWrapper *udpw;
1148   struct UDP_MessageWrapper *tmp;
1149   struct UDP_MessageWrapper dummy;
1150   struct Session *s = fc->session;
1151
1152   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1153        "%p : Fragmented message removed with result %s\n",
1154        fc,
1155        (result == GNUNET_SYSERR) ? "FAIL" : "SUCCESS");
1156   
1157   /* Call continuation for fragmented message */
1158   memset (&dummy, 0, sizeof (dummy));
1159   dummy.msg_type = MSG_FRAGMENTED_COMPLETE;
1160   dummy.msg_size = s->frag_ctx->on_wire_size;
1161   dummy.payload_size = s->frag_ctx->payload_size;
1162   dummy.frag_ctx = s->frag_ctx;
1163   dummy.cont = NULL;
1164   dummy.cont_cls = NULL;
1165   dummy.session = s;
1166
1167   call_continuation (&dummy, result);
1168
1169   /* Remove leftover fragments from queue */
1170   if (s->addrlen == sizeof (struct sockaddr_in6))
1171   {
1172     udpw = plugin->ipv6_queue_head;
1173     while (NULL != udpw)
1174     {
1175       tmp = udpw->next;
1176       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1177       {
1178         dequeue (plugin, udpw);
1179         call_continuation (udpw, GNUNET_SYSERR);
1180         GNUNET_free (udpw);
1181       }
1182       udpw = tmp;
1183     }
1184   }
1185   if (s->addrlen == sizeof (struct sockaddr_in))
1186   {
1187     udpw = plugin->ipv4_queue_head;
1188     while (udpw!= NULL)
1189     {
1190       tmp = udpw->next;
1191       if ((NULL != udpw->frag_ctx) && (udpw->frag_ctx == s->frag_ctx))
1192       {
1193         dequeue (plugin, udpw);
1194         call_continuation (udpw, GNUNET_SYSERR);
1195         GNUNET_free (udpw);
1196       }
1197       udpw = tmp;
1198     }
1199   }
1200
1201   /* Destroy fragmentation context */
1202   GNUNET_FRAGMENT_context_destroy (fc->frag,
1203                                      &s->last_expected_msg_delay,
1204                                      &s->last_expected_ack_delay);
1205   s->frag_ctx = NULL;
1206   GNUNET_free (fc );
1207 }
1208
1209 /**
1210  * Functions with this signature are called whenever we need
1211  * to close a session due to a disconnect or failure to
1212  * establish a connection.
1213  *
1214  * @param s session to close down
1215  */
1216 static void
1217 disconnect_session (struct Session *s)
1218 {
1219   struct UDP_MessageWrapper *udpw;
1220   struct UDP_MessageWrapper *next;
1221
1222   GNUNET_assert (GNUNET_YES != s->in_destroy);
1223   LOG (GNUNET_ERROR_TYPE_DEBUG,
1224        "Session %p to peer `%s' address ended \n",
1225          s,
1226          GNUNET_i2s (&s->target),
1227          GNUNET_a2s (s->sock_addr, s->addrlen));
1228   stop_session_timeout (s);
1229
1230   if (NULL != s->frag_ctx)
1231   {
1232     /* Remove fragmented message due to disconnect */
1233     fragmented_message_done (s->frag_ctx, GNUNET_SYSERR);
1234   }
1235
1236   next = plugin->ipv4_queue_head;
1237   while (NULL != (udpw = next))
1238   {
1239     next = udpw->next;
1240     if (udpw->session == s)
1241     {
1242       dequeue (plugin, udpw);
1243       call_continuation(udpw, GNUNET_SYSERR);
1244       GNUNET_free (udpw);
1245     }
1246   }
1247   next = plugin->ipv6_queue_head;
1248   while (NULL != (udpw = next))
1249   {
1250     next = udpw->next;
1251     if (udpw->session == s)
1252     {
1253       dequeue (plugin, udpw);
1254       call_continuation(udpw, GNUNET_SYSERR);
1255       GNUNET_free (udpw);
1256     }
1257   }
1258   plugin->env->session_end (plugin->env->cls, &s->target, s);
1259
1260   if (NULL != s->frag_ctx)
1261   {
1262     if (NULL != s->frag_ctx->cont)
1263     {
1264       s->frag_ctx->cont (s->frag_ctx->cont_cls, &s->target, GNUNET_SYSERR,
1265                          s->frag_ctx->payload_size, s->frag_ctx->on_wire_size);
1266       LOG (GNUNET_ERROR_TYPE_DEBUG,
1267           "Calling continuation for fragemented message to `%s' with result SYSERR\n",
1268           GNUNET_i2s (&s->target));
1269     }
1270   }
1271
1272   GNUNET_assert (GNUNET_YES ==
1273                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
1274                                                        &s->target.hashPubKey,
1275                                                        s));
1276   GNUNET_STATISTICS_set(plugin->env->stats,
1277                         "# UDP, sessions active",
1278                         GNUNET_CONTAINER_multihashmap_size(plugin->sessions),
1279                         GNUNET_NO);
1280   if (s->rc > 0)
1281     s->in_destroy = GNUNET_YES;
1282   else
1283     free_session (s);
1284 }
1285
1286 /**
1287  * Destroy a session, plugin is being unloaded.
1288  *
1289  * @param cls unused
1290  * @param key hash of public key of target peer
1291  * @param value a 'struct PeerSession*' to clean up
1292  * @return GNUNET_OK (continue to iterate)
1293  */
1294 static int
1295 disconnect_and_free_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1296 {
1297   disconnect_session(value);
1298   return GNUNET_OK;
1299 }
1300
1301
1302 /**
1303  * Disconnect from a remote node.  Clean up session if we have one for this peer
1304  *
1305  * @param cls closure for this call (should be handle to Plugin)
1306  * @param target the peeridentity of the peer to disconnect
1307  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
1308  */
1309 static void
1310 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1311 {
1312   struct Plugin *plugin = cls;
1313   GNUNET_assert (plugin != NULL);
1314
1315   GNUNET_assert (target != NULL);
1316   LOG (GNUNET_ERROR_TYPE_DEBUG,
1317        "Disconnecting from peer `%s'\n", GNUNET_i2s (target));
1318   /* Clean up sessions */
1319   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessions, &target->hashPubKey, &disconnect_and_free_it, plugin);
1320 }
1321
1322
1323 /**
1324  * Session was idle, so disconnect it
1325  */
1326 static void
1327 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1328 {
1329   GNUNET_assert (NULL != cls);
1330   struct Session *s = cls;
1331
1332   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1334               "Session %p was idle for %s, disconnecting\n",
1335               s,
1336               GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1337                                                       GNUNET_YES));
1338   /* call session destroy function */
1339   disconnect_session (s);
1340 }
1341
1342
1343 /**
1344  * Start session timeout
1345  */
1346 static void
1347 start_session_timeout (struct Session *s)
1348 {
1349   GNUNET_assert (NULL != s);
1350   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
1351   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1352                                                    &session_timeout,
1353                                                    s);
1354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1355               "Timeout for session %p set to %s\n",
1356               s,
1357               GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1358                                                       GNUNET_YES));
1359 }
1360
1361
1362 /**
1363  * Increment session timeout due to activity
1364  */
1365 static void
1366 reschedule_session_timeout (struct Session *s)
1367 {
1368   GNUNET_assert (NULL != s);
1369   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1370
1371   GNUNET_SCHEDULER_cancel (s->timeout_task);
1372   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1373                                                    &session_timeout,
1374                                                    s);
1375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1376               "Timeout rescheduled for session %p set to %s\n",
1377               s, 
1378               GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1379                                                       GNUNET_YES));
1380 }
1381
1382
1383 static struct Session *
1384 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
1385                 const void *addr, size_t addrlen,
1386                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1387 {
1388   struct Session *s;
1389   const struct IPv4UdpAddress *t4;
1390   const struct IPv6UdpAddress *t6;
1391   struct sockaddr_in *v4;
1392   struct sockaddr_in6 *v6;
1393   size_t len;
1394
1395   if (NULL == addr)
1396   {
1397         GNUNET_break (0);
1398         return NULL;
1399   }
1400
1401   switch (addrlen)
1402   {
1403   case sizeof (struct IPv4UdpAddress):
1404     if (NULL == plugin->sockv4)
1405     {
1406       LOG (GNUNET_ERROR_TYPE_DEBUG,
1407            "Could not create session for peer `%s' address `%s': IPv4 is not enabled\n",
1408            GNUNET_i2s(target),
1409            udp_address_to_string(NULL, addr, addrlen));
1410       return NULL;
1411     }
1412     t4 = addr;
1413     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
1414     len = sizeof (struct sockaddr_in);
1415     v4 = (struct sockaddr_in *) &s[1];
1416     v4->sin_family = AF_INET;
1417 #if HAVE_SOCKADDR_IN_SIN_LEN
1418     v4->sin_len = sizeof (struct sockaddr_in);
1419 #endif
1420     v4->sin_port = t4->u4_port;
1421     v4->sin_addr.s_addr = t4->ipv4_addr;
1422     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
1423     break;
1424   case sizeof (struct IPv6UdpAddress):
1425     if (NULL == plugin->sockv6)
1426     {
1427       LOG (GNUNET_ERROR_TYPE_INFO,
1428            "Could not create session for peer `%s' address `%s': IPv6 is not enabled\n",
1429            GNUNET_i2s(target),
1430            udp_address_to_string(NULL, addr, addrlen));
1431       return NULL;
1432     }
1433     t6 = addr;
1434     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
1435     len = sizeof (struct sockaddr_in6);
1436     v6 = (struct sockaddr_in6 *) &s[1];
1437     v6->sin6_family = AF_INET6;
1438 #if HAVE_SOCKADDR_IN_SIN_LEN
1439     v6->sin6_len = sizeof (struct sockaddr_in6);
1440 #endif
1441     v6->sin6_port = t6->u6_port;
1442     v6->sin6_addr = t6->ipv6_addr;
1443     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
1444     break;
1445   default:
1446     /* Must have a valid address to send to */
1447     GNUNET_STATISTICS_update (plugin->env->stats,
1448                               gettext_noop
1449                               ("# requests to create session with invalid address"),
1450                               1, GNUNET_NO);
1451     return NULL;
1452   }
1453   s->addrlen = len;
1454   s->target = *target;
1455   s->sock_addr = (const struct sockaddr *) &s[1];
1456   s->last_expected_ack_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250);
1457   s->last_expected_msg_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1458   s->flow_delay_from_other_peer = GNUNET_TIME_UNIT_ZERO_ABS;
1459   s->flow_delay_for_other_peer = GNUNET_TIME_UNIT_ZERO;
1460   s->inbound = GNUNET_NO;
1461   start_session_timeout (s);
1462   return s;
1463 }
1464
1465
1466 static int
1467 session_cmp_it (void *cls,
1468                 const struct GNUNET_HashCode * key,
1469                 void *value)
1470 {
1471   struct SessionCompareContext * cctx = cls;
1472   const struct GNUNET_HELLO_Address *address = cctx->addr;
1473   struct Session *s = value;
1474
1475   socklen_t s_addrlen = s->addrlen;
1476
1477   LOG (GNUNET_ERROR_TYPE_DEBUG,
1478        "Comparing address %s <-> %s\n",
1479        udp_address_to_string (NULL, (void *) address->address, 
1480                               address->address_length),
1481        GNUNET_a2s (s->sock_addr, s->addrlen));
1482   if ((address->address_length == sizeof (struct IPv4UdpAddress)) &&
1483       (s_addrlen == sizeof (struct sockaddr_in)))
1484   {
1485     struct IPv4UdpAddress * u4 = NULL;
1486     u4 = (struct IPv4UdpAddress *) address->address;
1487     GNUNET_assert (NULL != u4);
1488     const struct sockaddr_in *s4 = (const struct sockaddr_in *) s->sock_addr;
1489     if ((0 == memcmp ((const void *) &u4->ipv4_addr,(const void *) &s4->sin_addr, sizeof (struct in_addr))) &&
1490         (u4->u4_port == s4->sin_port))
1491     {
1492       cctx->res = s;
1493       return GNUNET_NO;
1494     }
1495
1496   }
1497   if ((address->address_length == sizeof (struct IPv6UdpAddress)) &&
1498       (s_addrlen == sizeof (struct sockaddr_in6)))
1499   {
1500     struct IPv6UdpAddress * u6 = NULL;
1501     u6 = (struct IPv6UdpAddress *) address->address;
1502     GNUNET_assert (NULL != u6);
1503     const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) s->sock_addr;
1504     if ((0 == memcmp (&u6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr))) &&
1505         (u6->u6_port == s6->sin6_port))
1506     {
1507       cctx->res = s;
1508       return GNUNET_NO;
1509     }
1510   }
1511   return GNUNET_YES;
1512 }
1513
1514
1515 /**
1516  * Function obtain the network type for a session
1517  *
1518  * @param cls closure ('struct Plugin*')
1519  * @param session the session
1520  * @return the network type in HBO or GNUNET_SYSERR
1521  */
1522 static enum GNUNET_ATS_Network_Type
1523 udp_get_network (void *cls, 
1524                  struct Session *session)
1525 {
1526   return ntohl (session->ats.value);
1527 }
1528
1529
1530 /**
1531  * Creates a new outbound session the transport service will use to send data to the
1532  * peer
1533  *
1534  * @param cls the plugin
1535  * @param address the address
1536  * @return the session or NULL of max connections exceeded
1537  */
1538 static struct Session *
1539 udp_plugin_lookup_session (void *cls,
1540                            const struct GNUNET_HELLO_Address *address)
1541 {
1542   struct Plugin * plugin = cls;
1543   struct IPv6UdpAddress * udp_a6;
1544   struct IPv4UdpAddress * udp_a4;
1545
1546   GNUNET_assert (plugin != NULL);
1547   GNUNET_assert (address != NULL);
1548
1549
1550   if ((address->address == NULL) ||
1551       ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
1552       (address->address_length != sizeof (struct IPv6UdpAddress))))
1553   {
1554     LOG (GNUNET_ERROR_TYPE_WARNING,
1555         _("Trying to create session for address of unexpected length %u (should be %u or %u)\n"),
1556         address->address_length,
1557         sizeof (struct IPv4UdpAddress),
1558         sizeof (struct IPv6UdpAddress));
1559     return NULL;
1560   }
1561
1562   if (address->address_length == sizeof (struct IPv4UdpAddress))
1563   {
1564     if (plugin->sockv4 == NULL)
1565       return NULL;
1566     udp_a4 = (struct IPv4UdpAddress *) address->address;
1567     if (udp_a4->u4_port == 0)
1568       return NULL;
1569   }
1570
1571   if (address->address_length == sizeof (struct IPv6UdpAddress))
1572   {
1573     if (plugin->sockv6 == NULL)
1574       return NULL;
1575     udp_a6 = (struct IPv6UdpAddress *) address->address;
1576     if (udp_a6->u6_port == 0)
1577       return NULL;
1578   }
1579
1580   /* check if session already exists */
1581   struct SessionCompareContext cctx;
1582   cctx.addr = address;
1583   cctx.res = NULL;
1584   LOG (GNUNET_ERROR_TYPE_DEBUG,
1585        "Looking for existing session for peer `%s' `%s' \n", 
1586        GNUNET_i2s (&address->peer), 
1587        udp_address_to_string(NULL, address->address, address->address_length));
1588   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessions, &address->peer.hashPubKey, session_cmp_it, &cctx);
1589   if (cctx.res != NULL)
1590   {
1591     LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p\n", cctx.res);
1592     return cctx.res;
1593   }
1594   return NULL;
1595 }
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;
1603
1604   s = create_session (plugin,
1605                       &address->peer,
1606                       address->address,
1607                       address->address_length,
1608                       NULL, NULL);
1609   if (NULL == s)
1610     return NULL; /* protocol not supported or address invalid */
1611   LOG (GNUNET_ERROR_TYPE_DEBUG,
1612        "Creating new session %p for peer `%s' address `%s'\n",
1613        s,
1614        GNUNET_i2s(&address->peer),
1615        udp_address_to_string(NULL,address->address,address->address_length));
1616   GNUNET_assert (GNUNET_OK ==
1617                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
1618                                                     &s->target.hashPubKey,
1619                                                     s,
1620                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1621   GNUNET_STATISTICS_set(plugin->env->stats,
1622                         "# UDP, sessions active",
1623                         GNUNET_CONTAINER_multihashmap_size(plugin->sessions),
1624                         GNUNET_NO);
1625   return s;
1626 }
1627
1628
1629 /**
1630  * Creates a new outbound session the transport service will use to send data to the
1631  * peer
1632  *
1633  * @param cls the plugin
1634  * @param address the address
1635  * @return the session or NULL of max connections exceeded
1636  */
1637 static struct Session *
1638 udp_plugin_get_session (void *cls,
1639                         const struct GNUNET_HELLO_Address *address)
1640 {
1641   struct Session *s;
1642
1643   if (NULL == address)
1644   {
1645     GNUNET_break (0);
1646     return NULL;
1647   }
1648   if ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
1649       (address->address_length != sizeof (struct IPv6UdpAddress)))
1650     return NULL;
1651
1652   /* otherwise create new */
1653   if (NULL != (s = udp_plugin_lookup_session (cls, address)))
1654     return s;
1655   return udp_plugin_create_session (cls, address);
1656 }
1657
1658
1659 static void 
1660 enqueue (struct Plugin *plugin, struct UDP_MessageWrapper * udpw)
1661 {
1662   if (plugin->bytes_in_buffer + udpw->msg_size > INT64_MAX)
1663       GNUNET_break (0);
1664   else
1665   {
1666     GNUNET_STATISTICS_update (plugin->env->stats,
1667                               "# UDP, total, bytes in buffers",
1668                               udpw->msg_size, GNUNET_NO);
1669     plugin->bytes_in_buffer += udpw->msg_size;
1670   }
1671   GNUNET_STATISTICS_update (plugin->env->stats,
1672                             "# UDP, total, msgs in buffers",
1673                             1, GNUNET_NO);
1674   if (udpw->session->addrlen == sizeof (struct sockaddr_in))
1675     GNUNET_CONTAINER_DLL_insert (plugin->ipv4_queue_head,
1676                                  plugin->ipv4_queue_tail, udpw);
1677   if (udpw->session->addrlen == sizeof (struct sockaddr_in6))
1678     GNUNET_CONTAINER_DLL_insert (plugin->ipv6_queue_head,
1679                                  plugin->ipv6_queue_tail, udpw);
1680 }
1681
1682
1683
1684 /**
1685  * Fragment message was transmitted via UDP, let fragmentation know
1686  * to send the next fragment now.
1687  *
1688  * @param cls the 'struct UDPMessageWrapper' of the fragment
1689  * @param target destination peer (ignored)
1690  * @param result GNUNET_OK on success (ignored)
1691  * @param payload bytes payload sent
1692  * @param physical bytes physical sent
1693  */
1694 static void
1695 send_next_fragment (void *cls,
1696                     const struct GNUNET_PeerIdentity *target,
1697                     int result, size_t payload, size_t physical)
1698 {
1699   struct UDP_MessageWrapper *udpw = cls;
1700
1701   GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);  
1702 }
1703
1704
1705 /**
1706  * Function that is called with messages created by the fragmentation
1707  * module.  In the case of the 'proc' callback of the
1708  * GNUNET_FRAGMENT_context_create function, this function must
1709  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
1710  *
1711  * @param cls closure, the 'struct FragmentationContext'
1712  * @param msg the message that was created
1713  */
1714 static void
1715 enqueue_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
1716 {
1717   struct UDP_FragmentationContext *frag_ctx = cls;
1718   struct Plugin *plugin = frag_ctx->plugin;
1719   struct UDP_MessageWrapper * udpw;
1720   size_t msg_len = ntohs (msg->size);
1721  
1722   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1723        "Enqueuing fragment with %u bytes\n", msg_len);
1724   frag_ctx->fragments_used ++;
1725   udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + msg_len);
1726   udpw->session = frag_ctx->session;
1727   udpw->msg_buf = (char *) &udpw[1];
1728   udpw->msg_size = msg_len;
1729   udpw->payload_size = msg_len; /*FIXME: minus fragment overhead */
1730   udpw->cont = &send_next_fragment;
1731   udpw->cont_cls = udpw;
1732   udpw->timeout = frag_ctx->timeout;
1733   udpw->frag_ctx = frag_ctx;
1734   udpw->msg_type = MSG_FRAGMENTED;
1735   memcpy (udpw->msg_buf, msg, msg_len);
1736   enqueue (plugin, udpw);
1737   schedule_select (plugin);
1738 }
1739
1740
1741 /**
1742  * Function that can be used by the transport service to transmit
1743  * a message using the plugin.   Note that in the case of a
1744  * peer disconnecting, the continuation MUST be called
1745  * prior to the disconnect notification itself.  This function
1746  * will be called with this peer's HELLO message to initiate
1747  * a fresh connection to another peer.
1748  *
1749  * @param cls closure
1750  * @param s which session must be used
1751  * @param msgbuf the message to transmit
1752  * @param msgbuf_size number of bytes in 'msgbuf'
1753  * @param priority how important is the message (most plugins will
1754  *                 ignore message priority and just FIFO)
1755  * @param to how long to wait at most for the transmission (does not
1756  *                require plugins to discard the message after the timeout,
1757  *                just advisory for the desired delay; most plugins will ignore
1758  *                this as well)
1759  * @param cont continuation to call once the message has
1760  *        been transmitted (or if the transport is ready
1761  *        for the next transmission call; or if the
1762  *        peer disconnected...); can be NULL
1763  * @param cont_cls closure for cont
1764  * @return number of bytes used (on the physical network, with overheads);
1765  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1766  *         and does NOT mean that the message was not transmitted (DV)
1767  */
1768 static ssize_t
1769 udp_plugin_send (void *cls,
1770                   struct Session *s,
1771                   const char *msgbuf, size_t msgbuf_size,
1772                   unsigned int priority,
1773                   struct GNUNET_TIME_Relative to,
1774                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1775 {
1776   struct Plugin *plugin = cls;
1777   size_t udpmlen = msgbuf_size + sizeof (struct UDPMessage);
1778   struct UDP_FragmentationContext * frag_ctx;
1779   struct UDP_MessageWrapper * udpw;
1780   struct UDPMessage *udp;
1781   char mbuf[udpmlen];
1782   GNUNET_assert (plugin != NULL);
1783   GNUNET_assert (s != NULL);
1784
1785   if ((s->addrlen == sizeof (struct sockaddr_in6)) && (plugin->sockv6 == NULL))
1786     return GNUNET_SYSERR;
1787   if ((s->addrlen == sizeof (struct sockaddr_in)) && (plugin->sockv4 == NULL))
1788     return GNUNET_SYSERR;
1789   if (udpmlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1790   {
1791     GNUNET_break (0);
1792     return GNUNET_SYSERR;
1793   }
1794   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessions, &s->target.hashPubKey, s))
1795   {
1796     GNUNET_break (0);
1797     return GNUNET_SYSERR;
1798   }
1799   LOG (GNUNET_ERROR_TYPE_DEBUG,
1800        "UDP transmits %u-byte message to `%s' using address `%s'\n",
1801        udpmlen,
1802        GNUNET_i2s (&s->target),
1803        GNUNET_a2s(s->sock_addr, s->addrlen));
1804
1805
1806   /* Message */
1807   udp = (struct UDPMessage *) mbuf;
1808   udp->header.size = htons (udpmlen);
1809   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
1810   udp->reserved = htonl (0);
1811   udp->sender = *plugin->env->my_identity;
1812
1813   reschedule_session_timeout(s);
1814   if (udpmlen <= UDP_MTU)
1815   {
1816     /* unfragmented message */
1817     udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + udpmlen);
1818     udpw->session = s;
1819     udpw->msg_buf = (char *) &udpw[1];
1820     udpw->msg_size = udpmlen; /* message size with UDP overhead */
1821     udpw->payload_size = msgbuf_size; /* message size without UDP overhead */
1822     udpw->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1823     udpw->cont = cont;
1824     udpw->cont_cls = cont_cls;
1825     udpw->frag_ctx = NULL;
1826     udpw->msg_type = MSG_UNFRAGMENTED;
1827     memcpy (udpw->msg_buf, udp, sizeof (struct UDPMessage));
1828     memcpy (&udpw->msg_buf[sizeof (struct UDPMessage)], msgbuf, msgbuf_size);
1829     enqueue (plugin, udpw);
1830
1831     GNUNET_STATISTICS_update (plugin->env->stats,
1832                               "# UDP, unfragmented msgs, messages, attempt",
1833                               1, GNUNET_NO);
1834     GNUNET_STATISTICS_update (plugin->env->stats,
1835                               "# UDP, unfragmented msgs, bytes payload, attempt",
1836                               udpw->payload_size, GNUNET_NO);
1837   }
1838   else
1839   {
1840     /* fragmented message */
1841     if  (s->frag_ctx != NULL)
1842       return GNUNET_SYSERR;
1843     memcpy (&udp[1], msgbuf, msgbuf_size);
1844     frag_ctx = GNUNET_malloc (sizeof (struct UDP_FragmentationContext));
1845     frag_ctx->plugin = plugin;
1846     frag_ctx->session = s;
1847     frag_ctx->cont = cont;
1848     frag_ctx->cont_cls = cont_cls;
1849     frag_ctx->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1850     frag_ctx->payload_size = msgbuf_size; /* unfragmented message size without UDP overhead */
1851     frag_ctx->on_wire_size = 0; /* bytes with UDP and fragmentation overhead */
1852     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
1853                                                      UDP_MTU,
1854                                                      &plugin->tracker,
1855                                                      s->last_expected_msg_delay, 
1856                                                      s->last_expected_ack_delay, 
1857                                                      &udp->header,
1858                                                      &enqueue_fragment,
1859                                                      frag_ctx);    
1860     s->frag_ctx = frag_ctx;
1861     GNUNET_STATISTICS_update (plugin->env->stats,
1862                               "# UDP, fragmented msgs, messages, pending",
1863                               1, GNUNET_NO);
1864     GNUNET_STATISTICS_update (plugin->env->stats,
1865                               "# UDP, fragmented msgs, messages, attempt",
1866                               1, GNUNET_NO);
1867     GNUNET_STATISTICS_update (plugin->env->stats,
1868                               "# UDP, fragmented msgs, bytes payload, attempt",
1869                               frag_ctx->payload_size, GNUNET_NO);
1870   }
1871   schedule_select (plugin);
1872   return udpmlen;
1873 }
1874
1875
1876 /**
1877  * Our external IP address/port mapping has changed.
1878  *
1879  * @param cls closure, the 'struct LocalAddrList'
1880  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1881  *     the previous (now invalid) one
1882  * @param addr either the previous or the new public IP address
1883  * @param addrlen actual lenght of the address
1884  */
1885 static void
1886 udp_nat_port_map_callback (void *cls, int add_remove,
1887                            const struct sockaddr *addr, socklen_t addrlen)
1888 {
1889   struct Plugin *plugin = cls;
1890   struct IPv4UdpAddress u4;
1891   struct IPv6UdpAddress u6;
1892   void *arg;
1893   size_t args;
1894
1895   LOG (GNUNET_ERROR_TYPE_INFO,
1896        "NAT notification to %s address `%s'\n",
1897        (GNUNET_YES == add_remove) ? "add" : "remove",
1898        GNUNET_a2s (addr, addrlen));
1899
1900   /* convert 'addr' to our internal format */
1901   switch (addr->sa_family)
1902   {
1903   case AF_INET:
1904     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1905     memset (&u4, 0, sizeof (u4));
1906     u4.options = htonl(myoptions);
1907     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1908     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1909     if (0 == ((struct sockaddr_in *) addr)->sin_port)
1910         return;
1911     arg = &u4;
1912     args = sizeof (struct IPv4UdpAddress);
1913     break;
1914   case AF_INET6:
1915     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1916     memset (&u4, 0, sizeof (u4));
1917     u6.options = htonl(myoptions);
1918     if (0 == ((struct sockaddr_in6 *) addr)->sin6_port)
1919         return;
1920     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1921             sizeof (struct in6_addr));
1922     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1923     arg = &u6;
1924     args = sizeof (struct IPv6UdpAddress);
1925     break;
1926   default:
1927     GNUNET_break (0);
1928     return;
1929   }
1930   /* modify our published address list */
1931   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args, "udp");
1932 }
1933
1934
1935
1936 /**
1937  * Message tokenizer has broken up an incomming message. Pass it on
1938  * to the service.
1939  *
1940  * @param cls the 'struct Plugin'
1941  * @param client the 'struct SourceInformation'
1942  * @param hdr the actual message
1943  */
1944 static int
1945 process_inbound_tokenized_messages (void *cls, void *client,
1946                                     const struct GNUNET_MessageHeader *hdr)
1947 {
1948   struct Plugin *plugin = cls;
1949   struct SourceInformation *si = client;
1950   struct GNUNET_TIME_Relative delay;
1951
1952   GNUNET_assert (si->session != NULL);
1953   if (GNUNET_YES == si->session->in_destroy)
1954     return GNUNET_OK;
1955   /* setup ATS */
1956   GNUNET_break (ntohl(si->session->ats.value) != GNUNET_ATS_NET_UNSPECIFIED);
1957   delay = plugin->env->receive (plugin->env->cls,
1958                                 &si->sender,
1959                                 hdr,
1960                                 si->session,
1961                  (GNUNET_YES == si->session->inbound) ? NULL : si->arg,
1962                  (GNUNET_YES == si->session->inbound) ? 0 : si->args);
1963
1964   plugin->env->update_address_metrics (plugin->env->cls,
1965                                        &si->sender,
1966                                          (GNUNET_YES == si->session->inbound) ? NULL : si->arg,
1967                                          (GNUNET_YES == si->session->inbound) ? 0 : si->args,
1968                                        si->session,
1969                                        &si->session->ats, 1);
1970
1971   si->session->flow_delay_for_other_peer = delay;
1972   reschedule_session_timeout(si->session);
1973   return GNUNET_OK;
1974 }
1975
1976
1977 /**
1978  * We've received a UDP Message.  Process it (pass contents to main service).
1979  *
1980  * @param plugin plugin context
1981  * @param msg the message
1982  * @param sender_addr sender address
1983  * @param sender_addr_len number of bytes in sender_addr
1984  */
1985 static void
1986 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1987                      const struct sockaddr *sender_addr,
1988                      socklen_t sender_addr_len)
1989 {
1990   struct SourceInformation si;
1991   struct Session * s;
1992   struct IPv4UdpAddress u4;
1993   struct IPv6UdpAddress u6;
1994   const void *arg;
1995   size_t args;
1996
1997   if (0 != ntohl (msg->reserved))
1998   {
1999     GNUNET_break_op (0);
2000     return;
2001   }
2002   if (ntohs (msg->header.size) <
2003       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
2004   {
2005     GNUNET_break_op (0);
2006     return;
2007   }
2008
2009   /* convert address */
2010   switch (sender_addr->sa_family)
2011   {
2012   case AF_INET:
2013     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
2014     memset (&u4, 0, sizeof (u4));
2015     u6.options = htonl (0);
2016     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
2017     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
2018     arg = &u4;
2019     args = sizeof (u4);
2020     break;
2021   case AF_INET6:
2022     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
2023     memset (&u6, 0, sizeof (u6));
2024     u6.options = htonl (0);
2025     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
2026     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
2027     arg = &u6;
2028     args = sizeof (u6);
2029     break;
2030   default:
2031     GNUNET_break (0);
2032     return;
2033   }
2034   LOG (GNUNET_ERROR_TYPE_DEBUG,
2035        "Received message with %u bytes from peer `%s' at `%s'\n",
2036        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
2037        GNUNET_a2s (sender_addr, sender_addr_len));
2038
2039   struct GNUNET_HELLO_Address * address = GNUNET_HELLO_address_allocate(&msg->sender, "udp", arg, args);
2040   if (NULL == (s = udp_plugin_lookup_session (plugin, address)))
2041   {
2042                 s = udp_plugin_create_session(plugin, address);
2043                 s->inbound = GNUNET_YES;
2044           plugin->env->session_start (NULL, &address->peer, PLUGIN_NAME,
2045                         (GNUNET_YES == s->inbound) ? NULL : address->address,
2046                         (GNUNET_YES == s->inbound) ? 0 : address->address_length,
2047                   s, NULL, 0);
2048   }
2049   GNUNET_free (address);
2050
2051   /* iterate over all embedded messages */
2052   si.session = s;
2053   si.sender = msg->sender;
2054   si.arg = arg;
2055   si.args = args;
2056   s->rc++;
2057   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
2058                              ntohs (msg->header.size) -
2059                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
2060   s->rc--;
2061   if ( (0 == s->rc) && (GNUNET_YES == s->in_destroy))
2062     free_session (s);
2063 }
2064
2065
2066 /**
2067  * Scan the heap for a receive context with the given address.
2068  *
2069  * @param cls the 'struct FindReceiveContext'
2070  * @param node internal node of the heap
2071  * @param element value stored at the node (a 'struct ReceiveContext')
2072  * @param cost cost associated with the node
2073  * @return GNUNET_YES if we should continue to iterate,
2074  *         GNUNET_NO if not.
2075  */
2076 static int
2077 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
2078                       void *element, GNUNET_CONTAINER_HeapCostType cost)
2079 {
2080   struct FindReceiveContext *frc = cls;
2081   struct DefragContext *e = element;
2082
2083   if ((frc->addr_len == e->addr_len) &&
2084       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
2085   {
2086     frc->rc = e;
2087     return GNUNET_NO;
2088   }
2089   return GNUNET_YES;
2090 }
2091
2092
2093 /**
2094  * Process a defragmented message.
2095  *
2096  * @param cls the 'struct ReceiveContext'
2097  * @param msg the message
2098  */
2099 static void
2100 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
2101 {
2102   struct DefragContext *rc = cls;
2103
2104   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
2105   {
2106     GNUNET_break (0);
2107     return;
2108   }
2109   if (ntohs (msg->size) < sizeof (struct UDPMessage))
2110   {
2111     GNUNET_break (0);
2112     return;
2113   }
2114   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
2115                        rc->src_addr, rc->addr_len);
2116 }
2117
2118
2119 struct LookupContext
2120 {
2121   const struct sockaddr * addr;
2122
2123   struct Session *res;
2124
2125   size_t addrlen;
2126 };
2127
2128
2129 static int
2130 lookup_session_by_addr_it (void *cls, const struct GNUNET_HashCode * key, void *value)
2131 {
2132   struct LookupContext *l_ctx = cls;
2133   struct Session * s = value;
2134
2135   if ((s->addrlen == l_ctx->addrlen) &&
2136       (0 == memcmp (s->sock_addr, l_ctx->addr, s->addrlen)))
2137   {
2138     l_ctx->res = s;
2139     return GNUNET_NO;
2140   }
2141   return GNUNET_YES;
2142 }
2143
2144
2145 /**
2146  * Transmit an acknowledgement.
2147  *
2148  * @param cls the 'struct ReceiveContext'
2149  * @param id message ID (unused)
2150  * @param msg ack to transmit
2151  */
2152 static void
2153 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
2154 {
2155   struct DefragContext *rc = cls;
2156   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
2157   struct UDP_ACK_Message *udp_ack;
2158   uint32_t delay = 0;
2159   struct UDP_MessageWrapper *udpw;
2160   struct Session *s;
2161   struct LookupContext l_ctx;
2162
2163   l_ctx.addr = rc->src_addr;
2164   l_ctx.addrlen = rc->addr_len;
2165   l_ctx.res = NULL;
2166   GNUNET_CONTAINER_multihashmap_iterate (rc->plugin->sessions,
2167       &lookup_session_by_addr_it,
2168       &l_ctx);
2169   s = l_ctx.res;
2170
2171   if (NULL == s)
2172     return;
2173
2174   if (s->flow_delay_for_other_peer.rel_value_us <= UINT32_MAX)
2175     delay = s->flow_delay_for_other_peer.rel_value_us;
2176
2177   LOG (GNUNET_ERROR_TYPE_DEBUG,
2178        "Sending ACK to `%s' including delay of %s\n",
2179        GNUNET_a2s (rc->src_addr,
2180                    (rc->src_addr->sa_family ==
2181                     AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct
2182                                                                      sockaddr_in6)),
2183        GNUNET_STRINGS_relative_time_to_string (s->flow_delay_for_other_peer,
2184                                                GNUNET_YES));
2185   udpw = GNUNET_malloc (sizeof (struct UDP_MessageWrapper) + msize);
2186   udpw->msg_size = msize;
2187   udpw->payload_size = 0;
2188   udpw->session = s;
2189   udpw->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
2190   udpw->msg_buf = (char *)&udpw[1];
2191   udpw->msg_type = MSG_ACK;
2192   udp_ack = (struct UDP_ACK_Message *) udpw->msg_buf;
2193   udp_ack->header.size = htons ((uint16_t) msize);
2194   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
2195   udp_ack->delay = htonl (delay);
2196   udp_ack->sender = *rc->plugin->env->my_identity;
2197   memcpy (&udp_ack[1], msg, ntohs (msg->size));
2198   enqueue (rc->plugin, udpw);
2199 }
2200
2201
2202 static void 
2203 read_process_msg (struct Plugin *plugin,
2204                   const struct GNUNET_MessageHeader *msg,
2205                   const char *addr,
2206                   socklen_t fromlen)
2207 {
2208   if (ntohs (msg->size) < sizeof (struct UDPMessage))
2209   {
2210     GNUNET_break_op (0);
2211     return;
2212   }
2213   process_udp_message (plugin, (const struct UDPMessage *) msg,
2214                        (const struct sockaddr *) addr, fromlen);
2215 }
2216
2217
2218 static void 
2219 read_process_ack (struct Plugin *plugin,
2220                   const struct GNUNET_MessageHeader *msg,
2221                   char *addr,
2222                   socklen_t fromlen)
2223 {
2224   const struct GNUNET_MessageHeader *ack;
2225   const struct UDP_ACK_Message *udp_ack;
2226   struct LookupContext l_ctx;
2227   struct Session *s;
2228   struct GNUNET_TIME_Relative flow_delay;
2229
2230   if (ntohs (msg->size) <
2231       sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
2232   {
2233     GNUNET_break_op (0);
2234     return;
2235   }
2236   udp_ack = (const struct UDP_ACK_Message *) msg;
2237   l_ctx.addr = (const struct sockaddr *) addr;
2238   l_ctx.addrlen = fromlen;
2239   l_ctx.res = NULL;
2240   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
2241                                          &lookup_session_by_addr_it,
2242                                          &l_ctx);
2243   s = l_ctx.res;
2244
2245   if ((NULL == s) || (NULL == s->frag_ctx))
2246   {
2247     return;
2248   }
2249
2250   flow_delay.rel_value_us = (uint64_t) ntohl (udp_ack->delay);
2251   LOG (GNUNET_ERROR_TYPE_DEBUG, 
2252        "We received a sending delay of %s\n",
2253        GNUNET_STRINGS_relative_time_to_string (flow_delay,
2254                                                GNUNET_YES));
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_us);
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_us);
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
2451 static struct UDP_MessageWrapper *
2452 remove_timeout_messages_and_select (struct UDP_MessageWrapper *head,
2453                                     struct GNUNET_NETWORK_Handle *sock)
2454 {
2455   struct UDP_MessageWrapper *udpw = NULL;
2456   struct GNUNET_TIME_Relative remaining;
2457
2458   udpw = head;
2459   while (udpw != NULL)
2460   {
2461     /* Find messages with timeout */
2462     remaining = GNUNET_TIME_absolute_get_remaining (udpw->timeout);
2463     if (GNUNET_TIME_UNIT_ZERO.rel_value_us == remaining.rel_value_us)
2464     {
2465       /* Message timed out */
2466       switch (udpw->msg_type) {
2467         case MSG_UNFRAGMENTED:
2468           GNUNET_STATISTICS_update (plugin->env->stats,
2469                                     "# UDP, total, bytes, sent, timeout",
2470                                     udpw->msg_size, GNUNET_NO);
2471           GNUNET_STATISTICS_update (plugin->env->stats,
2472                                     "# UDP, total, messages, sent, timeout",
2473                                     1, GNUNET_NO);
2474           GNUNET_STATISTICS_update (plugin->env->stats,
2475                                     "# UDP, unfragmented msgs, messages, sent, timeout",
2476                                     1, GNUNET_NO);
2477           GNUNET_STATISTICS_update (plugin->env->stats,
2478                                     "# UDP, unfragmented msgs, bytes, sent, timeout",
2479                                     udpw->payload_size, GNUNET_NO);
2480           /* Not fragmented message */
2481           LOG (GNUNET_ERROR_TYPE_DEBUG,
2482                "Message for peer `%s' with size %u timed out\n",
2483                GNUNET_i2s(&udpw->session->target), udpw->payload_size);
2484           call_continuation (udpw, GNUNET_SYSERR);
2485           /* Remove message */
2486           dequeue (plugin, udpw);
2487           GNUNET_free (udpw);
2488           break;
2489         case MSG_FRAGMENTED:
2490           /* Fragmented message */
2491           GNUNET_STATISTICS_update (plugin->env->stats,
2492                                     "# UDP, total, bytes, sent, timeout",
2493                                     udpw->frag_ctx->on_wire_size, GNUNET_NO);
2494           GNUNET_STATISTICS_update (plugin->env->stats,
2495                                     "# UDP, total, messages, sent, timeout",
2496                                     1, GNUNET_NO);
2497           call_continuation (udpw, GNUNET_SYSERR);
2498           LOG (GNUNET_ERROR_TYPE_DEBUG,
2499                "Fragment for message for peer `%s' with size %u timed out\n",
2500                GNUNET_i2s(&udpw->session->target), udpw->frag_ctx->payload_size);
2501
2502
2503           GNUNET_STATISTICS_update (plugin->env->stats,
2504                                     "# UDP, fragmented msgs, messages, sent, timeout",
2505                                     1, GNUNET_NO);
2506           GNUNET_STATISTICS_update (plugin->env->stats,
2507                                     "# UDP, fragmented msgs, bytes, sent, timeout",
2508                                     udpw->frag_ctx->payload_size, GNUNET_NO);
2509           /* Remove fragmented message due to timeout */
2510           fragmented_message_done (udpw->frag_ctx, GNUNET_SYSERR);
2511           break;
2512         case MSG_ACK:
2513           GNUNET_STATISTICS_update (plugin->env->stats,
2514                                     "# UDP, total, bytes, sent, timeout",
2515                                     udpw->msg_size, GNUNET_NO);
2516           GNUNET_STATISTICS_update (plugin->env->stats,
2517                                     "# UDP, total, messages, sent, timeout",
2518                                     1, GNUNET_NO);
2519           LOG (GNUNET_ERROR_TYPE_DEBUG,
2520                "ACK Message for peer `%s' with size %u timed out\n",
2521                GNUNET_i2s(&udpw->session->target), udpw->payload_size);
2522           call_continuation (udpw, GNUNET_SYSERR);
2523           dequeue (plugin, udpw);
2524           GNUNET_free (udpw);
2525           break;
2526         default:
2527           break;
2528       }
2529       if (sock == plugin->sockv4)
2530         udpw = plugin->ipv4_queue_head;
2531       else if (sock == plugin->sockv6)
2532         udpw = plugin->ipv6_queue_head;
2533       else
2534       {
2535         GNUNET_break (0); /* should never happen */
2536         udpw = NULL;
2537       }
2538       GNUNET_STATISTICS_update (plugin->env->stats,
2539                                 "# messages dismissed due to timeout",
2540                                 1, GNUNET_NO);
2541     }
2542     else
2543     {
2544       /* Message did not time out, check flow delay */
2545       remaining = GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer);
2546       if (GNUNET_TIME_UNIT_ZERO.rel_value_us == remaining.rel_value_us)
2547       {
2548         /* this message is not delayed */
2549         LOG (GNUNET_ERROR_TYPE_DEBUG, 
2550              "Message for peer `%s' (%u bytes) is not delayed \n",
2551              GNUNET_i2s(&udpw->session->target), udpw->payload_size);
2552         break; /* Found message to send, break */
2553       }
2554       else
2555       {
2556         /* Message is delayed, try next */
2557         LOG (GNUNET_ERROR_TYPE_DEBUG,
2558              "Message for peer `%s' (%u bytes) is delayed for %s\n",
2559              GNUNET_i2s(&udpw->session->target), udpw->payload_size, 
2560              GNUNET_STRINGS_relative_time_to_string (remaining,
2561                                                      GNUNET_YES));
2562         udpw = udpw->next;
2563       }
2564     }
2565   }
2566   return udpw;
2567 }
2568
2569
2570 static void
2571 analyze_send_error (struct Plugin *plugin,
2572                     const struct sockaddr * sa,
2573                     socklen_t slen,
2574                     int error)
2575 {
2576   static int network_down_error;
2577   struct GNUNET_ATS_Information type;
2578
2579  type = plugin->env->get_address_type (plugin->env->cls,sa, slen);
2580  if (((GNUNET_ATS_NET_LAN == ntohl(type.value)) || (GNUNET_ATS_NET_WAN == ntohl(type.value))) &&
2581      ((ENETUNREACH == errno) || (ENETDOWN == errno)))
2582  {
2583    if ((network_down_error == GNUNET_NO) && (slen == sizeof (struct sockaddr_in)))
2584    {
2585      /* IPv4: "Network unreachable" or "Network down"
2586       *
2587       * This indicates we do not have connectivity
2588       */
2589      LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
2590          _("UDP could not transmit message to `%s': "
2591            "Network seems down, please check your network configuration\n"),
2592          GNUNET_a2s (sa, slen));
2593    }
2594    if ((network_down_error == GNUNET_NO) && (slen == sizeof (struct sockaddr_in6)))
2595    {
2596      /* IPv6: "Network unreachable" or "Network down"
2597       *
2598       * This indicates that this system is IPv6 enabled, but does not
2599       * have a valid global IPv6 address assigned or we do not have
2600       * connectivity
2601       */
2602
2603     LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
2604         _("UDP could not transmit message to `%s': "
2605           "Please check your network configuration and disable IPv6 if your "
2606           "connection does not have a global IPv6 address\n"),
2607         GNUNET_a2s (sa, slen));
2608    }
2609  }
2610  else
2611  {
2612    LOG (GNUNET_ERROR_TYPE_WARNING,
2613       "UDP could not transmit message to `%s': `%s'\n",
2614       GNUNET_a2s (sa, slen), STRERROR (error));
2615  }
2616 }
2617
2618
2619 static size_t
2620 udp_select_send (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *sock)
2621 {
2622   const struct sockaddr * sa;
2623   ssize_t sent;
2624   socklen_t slen;
2625
2626   struct UDP_MessageWrapper *udpw = NULL;
2627
2628   /* Find message to send */
2629   udpw = remove_timeout_messages_and_select ((sock == plugin->sockv4) ? plugin->ipv4_queue_head : plugin->ipv6_queue_head,
2630                                              sock);
2631   if (NULL == udpw)
2632     return 0; /* No message to send */
2633
2634   sa = udpw->session->sock_addr;
2635   slen = udpw->session->addrlen;
2636
2637   sent = GNUNET_NETWORK_socket_sendto (sock, udpw->msg_buf, udpw->msg_size, sa, slen);
2638
2639   if (GNUNET_SYSERR == sent)
2640   {
2641     /* Failure */
2642     analyze_send_error (plugin, sa, slen, errno);
2643     call_continuation(udpw, GNUNET_SYSERR);
2644     GNUNET_STATISTICS_update (plugin->env->stats,
2645                             "# UDP, total, bytes, sent, failure",
2646                             sent, GNUNET_NO);
2647     GNUNET_STATISTICS_update (plugin->env->stats,
2648                               "# UDP, total, messages, sent, failure",
2649                               1, GNUNET_NO);
2650   }
2651   else
2652   {
2653     /* Success */
2654     LOG (GNUNET_ERROR_TYPE_DEBUG,
2655          "UDP transmitted %u-byte message to  `%s' `%s' (%d: %s)\n",
2656          (unsigned int) (udpw->msg_size), GNUNET_i2s(&udpw->session->target) ,GNUNET_a2s (sa, slen), (int) sent,
2657          (sent < 0) ? STRERROR (errno) : "ok");
2658     GNUNET_STATISTICS_update (plugin->env->stats,
2659                               "# UDP, total, bytes, sent, success",
2660                               sent, GNUNET_NO);
2661     GNUNET_STATISTICS_update (plugin->env->stats,
2662                               "# UDP, total, messages, sent, success",
2663                               1, GNUNET_NO);
2664     if (NULL != udpw->frag_ctx)
2665         udpw->frag_ctx->on_wire_size += udpw->msg_size;
2666     call_continuation (udpw, GNUNET_OK);
2667   }
2668   dequeue (plugin, udpw);
2669   GNUNET_free (udpw);
2670   udpw = NULL;
2671
2672   return sent;
2673 }
2674
2675
2676 /**
2677  * We have been notified that our readset has something to read.  We don't
2678  * know which socket needs to be read, so we have to check each one
2679  * Then reschedule this function to be called again once more is available.
2680  *
2681  * @param cls the plugin handle
2682  * @param tc the scheduling context (for rescheduling this function again)
2683  */
2684 static void
2685 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2686 {
2687   struct Plugin *plugin = cls;
2688
2689   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2690   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2691     return;
2692   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
2693        (NULL != plugin->sockv4) &&
2694        (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)) )
2695     udp_select_read (plugin, plugin->sockv4);
2696   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
2697        (NULL != plugin->sockv4) && 
2698        (NULL != plugin->ipv4_queue_head) &&
2699        (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv4)) )
2700     udp_select_send (plugin, plugin->sockv4);   
2701   schedule_select (plugin);
2702 }
2703
2704
2705 /**
2706  * We have been notified that our readset has something to read.  We don't
2707  * know which socket needs to be read, so we have to check each one
2708  * Then reschedule this function to be called again once more is available.
2709  *
2710  * @param cls the plugin handle
2711  * @param tc the scheduling context (for rescheduling this function again)
2712  */
2713 static void
2714 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2715 {
2716   struct Plugin *plugin = cls;
2717
2718   plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2719   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2720     return;
2721   if ( ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0) &&
2722        (NULL != plugin->sockv6) &&
2723        (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)) )
2724     udp_select_read (plugin, plugin->sockv6);
2725   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
2726        (NULL != plugin->sockv6) && (plugin->ipv6_queue_head != NULL) &&
2727        (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv6)) )    
2728     udp_select_send (plugin, plugin->sockv6);
2729   schedule_select (plugin);
2730 }
2731
2732
2733 /**
2734  *
2735  * @return number of sockets that were successfully bound
2736  */
2737 static int
2738 setup_sockets (struct Plugin *plugin, 
2739                const struct sockaddr_in6 *bind_v6,
2740                const struct sockaddr_in *bind_v4)
2741 {
2742   int tries;
2743   int sockets_created = 0;
2744   struct sockaddr_in6 serverAddrv6;
2745   struct sockaddr_in serverAddrv4;
2746   struct sockaddr *serverAddr;
2747   struct sockaddr *addrs[2];
2748   socklen_t addrlens[2];
2749   socklen_t addrlen;
2750   int eno;
2751
2752   /* Create IPv6 socket */
2753   eno = EINVAL;
2754   if (plugin->enable_ipv6 == GNUNET_YES)
2755   {
2756     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
2757     if (NULL == plugin->sockv6)
2758     {
2759         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
2760       LOG (GNUNET_ERROR_TYPE_WARNING, "Disabling IPv6 since it is not supported on this system!\n");
2761       plugin->enable_ipv6 = GNUNET_NO;
2762     }
2763     else
2764     {
2765         memset (&serverAddrv6, '\0', sizeof (struct sockaddr_in6));
2766 #if HAVE_SOCKADDR_IN_SIN_LEN
2767       serverAddrv6.sin6_len = sizeof (struct sockaddr_in6);
2768 #endif
2769       serverAddrv6.sin6_family = AF_INET6;
2770       if (NULL != bind_v6)
2771         serverAddrv6.sin6_addr = bind_v6->sin6_addr;
2772       else
2773         serverAddrv6.sin6_addr = in6addr_any;
2774
2775       if (0 == plugin->port) /* autodetect */
2776                 serverAddrv6.sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);
2777       else
2778                 serverAddrv6.sin6_port = htons (plugin->port);
2779       addrlen = sizeof (struct sockaddr_in6);
2780       serverAddr = (struct sockaddr *) &serverAddrv6;
2781
2782       tries = 0;
2783       while (tries < 10)
2784       {
2785                 LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 `%s'\n",
2786                                  GNUNET_a2s (serverAddr, addrlen));
2787                 /* binding */
2788                 if (GNUNET_OK == GNUNET_NETWORK_socket_bind (plugin->sockv6,
2789                                                              serverAddr, addrlen, 0))
2790                         break;
2791                 eno = errno;
2792                 if (0 != plugin->port)
2793                 {
2794                                 tries = 10; /* fail */
2795                                 break; /* bind failed on specific port */
2796                 }
2797                 /* autodetect */
2798                 serverAddrv6.sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);
2799                 tries ++;
2800       }
2801       if (tries >= 10)
2802       {
2803         GNUNET_NETWORK_socket_close (plugin->sockv6);
2804         plugin->enable_ipv6 = GNUNET_NO;
2805         plugin->sockv6 = NULL;
2806       }
2807
2808       if (plugin->sockv6 != NULL)
2809       {
2810         LOG (GNUNET_ERROR_TYPE_DEBUG,
2811              "IPv6 socket created on port %s\n",
2812              GNUNET_a2s (serverAddr, addrlen));
2813         addrs[sockets_created] = (struct sockaddr *) &serverAddrv6;
2814         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
2815         sockets_created++;
2816       }
2817       else
2818       {
2819           LOG (GNUNET_ERROR_TYPE_ERROR,
2820                "Failed to bind UDP socket to %s: %s\n",
2821                GNUNET_a2s (serverAddr, addrlen),
2822                STRERROR (eno));
2823       }
2824     }
2825   }
2826
2827   /* Create IPv4 socket */
2828   eno = EINVAL;
2829   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
2830   if (NULL == plugin->sockv4)
2831   {
2832     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
2833     LOG (GNUNET_ERROR_TYPE_WARNING, "Disabling IPv4 since it is not supported on this system!\n");
2834     plugin->enable_ipv4 = GNUNET_NO;
2835   }
2836   else
2837   {
2838     memset (&serverAddrv4, '\0', sizeof (struct sockaddr_in));
2839 #if HAVE_SOCKADDR_IN_SIN_LEN
2840     serverAddrv4.sin_len = sizeof (struct sockaddr_in);
2841 #endif
2842     serverAddrv4.sin_family = AF_INET;
2843     if (NULL != bind_v4)
2844       serverAddrv4.sin_addr = bind_v4->sin_addr;
2845     else
2846       serverAddrv4.sin_addr.s_addr = INADDR_ANY;
2847     
2848     if (0 == plugin->port)
2849       /* autodetect */
2850       serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);
2851     else
2852       serverAddrv4.sin_port = htons (plugin->port);
2853     
2854     
2855     addrlen = sizeof (struct sockaddr_in);
2856     serverAddr = (struct sockaddr *) &serverAddrv4;
2857     
2858     tries = 0;
2859     while (tries < 10)
2860     {
2861       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 `%s'\n",
2862                         GNUNET_a2s (serverAddr, addrlen));
2863       
2864       /* binding */
2865       if (GNUNET_OK == GNUNET_NETWORK_socket_bind (plugin->sockv4,
2866                                                    serverAddr, addrlen, 0))
2867                 break;
2868       eno = errno;
2869       if (0 != plugin->port)
2870       {
2871                 tries = 10; /* fail */
2872                 break; /* bind failed on specific port */
2873       }
2874       
2875       /* autodetect */
2876       serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);
2877       tries ++;
2878     }
2879     
2880     if (tries >= 10)
2881     {
2882       GNUNET_NETWORK_socket_close (plugin->sockv4);
2883       plugin->enable_ipv4 = GNUNET_NO;
2884       plugin->sockv4 = NULL;
2885     }
2886     
2887     if (plugin->sockv4 != NULL)
2888     {
2889       LOG (GNUNET_ERROR_TYPE_DEBUG,
2890                 "IPv4 socket created on port %s\n", GNUNET_a2s (serverAddr, addrlen));
2891       addrs[sockets_created] = (struct sockaddr *) &serverAddrv4;
2892       addrlens[sockets_created] = sizeof (struct sockaddr_in);
2893       sockets_created++;
2894     }
2895     else
2896     {             
2897       LOG (GNUNET_ERROR_TYPE_ERROR,
2898                 "Failed to bind UDP socket to %s: %s\n",
2899                 GNUNET_a2s (serverAddr, addrlen), STRERROR (eno));
2900     }
2901   }
2902   
2903   if (0 == sockets_created)
2904   {
2905                 LOG (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
2906                 return 0; /* No sockets created, return */
2907   }
2908
2909   /* Create file descriptors */
2910   if (plugin->enable_ipv4 == GNUNET_YES)
2911   {
2912                         plugin->rs_v4 = GNUNET_NETWORK_fdset_create ();
2913                         plugin->ws_v4 = GNUNET_NETWORK_fdset_create ();
2914                         GNUNET_NETWORK_fdset_zero (plugin->rs_v4);
2915                         GNUNET_NETWORK_fdset_zero (plugin->ws_v4);
2916                         if (NULL != plugin->sockv4)
2917                         {
2918                                 GNUNET_NETWORK_fdset_set (plugin->rs_v4, plugin->sockv4);
2919                                 GNUNET_NETWORK_fdset_set (plugin->ws_v4, plugin->sockv4);
2920                         }
2921   }
2922
2923   if (plugin->enable_ipv6 == GNUNET_YES)
2924   {
2925     plugin->rs_v6 = GNUNET_NETWORK_fdset_create ();
2926     plugin->ws_v6 = GNUNET_NETWORK_fdset_create ();
2927     GNUNET_NETWORK_fdset_zero (plugin->rs_v6);
2928     GNUNET_NETWORK_fdset_zero (plugin->ws_v6);
2929     if (NULL != plugin->sockv6)
2930     {
2931       GNUNET_NETWORK_fdset_set (plugin->rs_v6, plugin->sockv6);
2932       GNUNET_NETWORK_fdset_set (plugin->ws_v6, plugin->sockv6);
2933     }
2934   }
2935
2936   schedule_select (plugin);
2937   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2938                            GNUNET_NO, plugin->port,
2939                            sockets_created,
2940                            (const struct sockaddr **) addrs, addrlens,
2941                            &udp_nat_port_map_callback, NULL, plugin);
2942
2943   return sockets_created;
2944 }
2945
2946
2947 /**
2948  * The exported method. Makes the core api available via a global and
2949  * returns the udp transport API.
2950  *
2951  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2952  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
2953  */
2954 void *
2955 libgnunet_plugin_transport_udp_init (void *cls)
2956 {
2957   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2958   struct GNUNET_TRANSPORT_PluginFunctions *api;
2959   struct Plugin *p;
2960   unsigned long long port;
2961   unsigned long long aport;
2962   unsigned long long broadcast;
2963   unsigned long long udp_max_bps;
2964   unsigned long long enable_v6;
2965   char * bind4_address;
2966   char * bind6_address;
2967   char * fancy_interval;
2968   struct GNUNET_TIME_Relative interval;
2969   struct sockaddr_in serverAddrv4;
2970   struct sockaddr_in6 serverAddrv6;
2971   int res;
2972   int have_bind4;
2973   int have_bind6;
2974
2975   if (NULL == env->receive)
2976   {
2977     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2978        initialze the plugin or the API */
2979     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2980     api->cls = NULL;
2981     api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2982     api->address_to_string = &udp_address_to_string;
2983     api->string_to_address = &udp_string_to_address;
2984     return api;
2985   }
2986
2987   GNUNET_assert (NULL != env->stats);
2988
2989   /* Get port number: port == 0 : autodetect a port,
2990    *                                                                                            > 0 : use this port,
2991    *                                                              not given : 2086 default */
2992   if (GNUNET_OK !=
2993       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
2994                                              &port))
2995     port = 2086;
2996   if (GNUNET_OK !=
2997       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2998                                              "ADVERTISED_PORT", &aport))
2999     aport = port;
3000   if (port > 65535)
3001   {
3002     LOG (GNUNET_ERROR_TYPE_WARNING,
3003          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
3004          65535);
3005     return NULL;
3006   }
3007
3008   /* Protocols */
3009   if ((GNUNET_YES ==
3010        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
3011                                              "DISABLEV6")))
3012     enable_v6 = GNUNET_NO;
3013   else
3014     enable_v6 = GNUNET_YES;
3015
3016   /* Addresses */
3017   have_bind4 = GNUNET_NO;
3018   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
3019   if (GNUNET_YES ==
3020       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
3021                                              "BINDTO", &bind4_address))
3022   {
3023     LOG (GNUNET_ERROR_TYPE_DEBUG,
3024          "Binding udp plugin to specific address: `%s'\n",
3025          bind4_address);
3026     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
3027     {
3028       GNUNET_free (bind4_address);
3029       return NULL;
3030     }
3031     have_bind4 = GNUNET_YES;
3032   }
3033   GNUNET_free_non_null (bind4_address);
3034   have_bind6 = GNUNET_NO;
3035   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
3036   if (GNUNET_YES ==
3037       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
3038                                              "BINDTO6", &bind6_address))
3039   {
3040     LOG (GNUNET_ERROR_TYPE_DEBUG,
3041          "Binding udp plugin to specific address: `%s'\n",
3042          bind6_address);
3043     if (1 !=
3044         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
3045     {
3046       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
3047            bind6_address);
3048       GNUNET_free (bind6_address);
3049       return NULL;
3050     }
3051     have_bind6 = GNUNET_YES;
3052   }
3053   GNUNET_free_non_null (bind6_address);
3054
3055   /* Initialize my flags */
3056   myoptions = 0;
3057
3058   /* Enable neighbour discovery */
3059   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
3060                                             "BROADCAST");
3061   if (broadcast == GNUNET_SYSERR)
3062     broadcast = GNUNET_NO;
3063
3064   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
3065                                            "BROADCAST_INTERVAL", &fancy_interval))
3066   {
3067     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
3068   }
3069   else
3070   {
3071      if (GNUNET_SYSERR == GNUNET_STRINGS_fancy_time_to_relative(fancy_interval, &interval))
3072      {
3073        interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30);
3074      }
3075      GNUNET_free (fancy_interval);
3076   }
3077
3078   /* Maximum datarate */
3079   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
3080                                              "MAX_BPS", &udp_max_bps))
3081   {
3082     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
3083   }
3084
3085   p = GNUNET_malloc (sizeof (struct Plugin));
3086   p->port = port;
3087   p->aport = aport;
3088   p->broadcast_interval = interval;
3089   p->enable_ipv6 = enable_v6;
3090   p->enable_ipv4 = GNUNET_YES; /* default */
3091   p->env = env;
3092   p->sessions = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
3093   p->defrag_ctxs = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3094   p->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, p);
3095   GNUNET_BANDWIDTH_tracker_init (&p->tracker,
3096                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
3097   plugin = p;
3098
3099   LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
3100   res = setup_sockets (p, (GNUNET_YES == have_bind6) ? &serverAddrv6 : NULL,
3101                                                                                 (GNUNET_YES == have_bind4) ? &serverAddrv4 : NULL);
3102   if ((res == 0) || ((p->sockv4 == NULL) && (p->sockv6 == NULL)))
3103   {
3104     LOG (GNUNET_ERROR_TYPE_ERROR,
3105          _("Failed to create network sockets, plugin failed\n"));
3106     GNUNET_CONTAINER_multihashmap_destroy (p->sessions);
3107     GNUNET_CONTAINER_heap_destroy (p->defrag_ctxs);
3108     GNUNET_SERVER_mst_destroy (p->mst);
3109     GNUNET_free (p);
3110     return NULL;
3111   }
3112   else if (broadcast == GNUNET_YES)
3113   {
3114     LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting broadcasting\n");
3115     setup_broadcast (p, &serverAddrv6, &serverAddrv4);
3116   }
3117
3118   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
3119   api->cls = p;
3120   api->send = NULL;
3121   api->disconnect = &udp_disconnect;
3122   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
3123   api->address_to_string = &udp_address_to_string;
3124   api->string_to_address = &udp_string_to_address;
3125   api->check_address = &udp_plugin_check_address;
3126   api->get_session = &udp_plugin_get_session;
3127   api->send = &udp_plugin_send;
3128   api->get_network = &udp_get_network;
3129
3130   return api;
3131 }
3132
3133
3134 static int
3135 heap_cleanup_iterator (void *cls,
3136                        struct GNUNET_CONTAINER_HeapNode *
3137                        node, void *element,
3138                        GNUNET_CONTAINER_HeapCostType
3139                        cost)
3140 {
3141   struct DefragContext * d_ctx = element;
3142
3143   GNUNET_CONTAINER_heap_remove_node (node);
3144   GNUNET_DEFRAGMENT_context_destroy(d_ctx->defrag);
3145   GNUNET_free (d_ctx);
3146
3147   return GNUNET_YES;
3148 }
3149
3150
3151 /**
3152  * The exported method. Makes the core api available via a global and
3153  * returns the udp transport API.
3154  *
3155  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
3156  * @return NULL
3157  */
3158 void *
3159 libgnunet_plugin_transport_udp_done (void *cls)
3160 {
3161   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3162   struct Plugin *plugin = api->cls;
3163   struct PrettyPrinterContext *cur;
3164   struct PrettyPrinterContext *next;
3165
3166   if (NULL == plugin)
3167   {
3168     GNUNET_free (api);
3169     return NULL;
3170   }
3171
3172   stop_broadcast (plugin);
3173   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
3174   {
3175     GNUNET_SCHEDULER_cancel (plugin->select_task);
3176     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
3177   }
3178   if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
3179   {
3180     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
3181     plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
3182   }
3183
3184   /* Closing sockets */
3185   if (GNUNET_YES ==plugin->enable_ipv4)
3186   {
3187                 if (plugin->sockv4 != NULL)
3188                 {
3189                         GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
3190                         plugin->sockv4 = NULL;
3191                 }
3192                 GNUNET_NETWORK_fdset_destroy (plugin->rs_v4);
3193                 GNUNET_NETWORK_fdset_destroy (plugin->ws_v4);
3194   }
3195   if (GNUNET_YES ==plugin->enable_ipv6)
3196   {
3197                 if (plugin->sockv6 != NULL)
3198                 {
3199                         GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
3200                         plugin->sockv6 = NULL;
3201
3202                         GNUNET_NETWORK_fdset_destroy (plugin->rs_v6);
3203                         GNUNET_NETWORK_fdset_destroy (plugin->ws_v6);
3204                 }
3205   }
3206   if (NULL != plugin->nat)
3207         GNUNET_NAT_unregister (plugin->nat);
3208
3209   if (plugin->defrag_ctxs != NULL)
3210   {
3211     GNUNET_CONTAINER_heap_iterate(plugin->defrag_ctxs,
3212         heap_cleanup_iterator, NULL);
3213     GNUNET_CONTAINER_heap_destroy(plugin->defrag_ctxs);
3214     plugin->defrag_ctxs = NULL;
3215   }
3216   if (plugin->mst != NULL)
3217   {
3218     GNUNET_SERVER_mst_destroy(plugin->mst);
3219     plugin->mst = NULL;
3220   }
3221
3222   /* Clean up leftover messages */
3223   struct UDP_MessageWrapper * udpw;
3224   udpw = plugin->ipv4_queue_head;
3225   while (udpw != NULL)
3226   {
3227     struct UDP_MessageWrapper *tmp = udpw->next;
3228     dequeue (plugin, udpw);
3229     call_continuation(udpw, GNUNET_SYSERR);
3230     GNUNET_free (udpw);
3231
3232     udpw = tmp;
3233   }
3234   udpw = plugin->ipv6_queue_head;
3235   while (udpw != NULL)
3236   {
3237     struct UDP_MessageWrapper *tmp = udpw->next;
3238     dequeue (plugin, udpw);
3239     call_continuation(udpw, GNUNET_SYSERR);
3240     GNUNET_free (udpw);
3241
3242     udpw = tmp;
3243   }
3244
3245   /* Clean up sessions */
3246   LOG (GNUNET_ERROR_TYPE_DEBUG,
3247        "Cleaning up sessions\n");
3248   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
3249   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
3250
3251   next = ppc_dll_head;
3252   for (cur = next; NULL != cur; cur = next)
3253   {
3254         next = cur->next;
3255         GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, cur);
3256         GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
3257         GNUNET_SCHEDULER_cancel (cur->timeout_task);
3258         GNUNET_free (cur);
3259         GNUNET_break (0);
3260   }
3261
3262   plugin->nat = NULL;
3263   GNUNET_free (plugin);
3264   GNUNET_free (api);
3265 #if DEBUG_MALLOC
3266   struct Allocation *allocation;
3267   while (NULL != ahead)
3268   {
3269       allocation = ahead;
3270       GNUNET_CONTAINER_DLL_remove (ahead, atail, allocation);
3271       GNUNET_free (allocation);
3272   }
3273   struct Allocator *allocator;
3274   while (NULL != aehead)
3275   {
3276       allocator = aehead;
3277       GNUNET_CONTAINER_DLL_remove (aehead, aetail, allocator);
3278       GNUNET_free (allocator);
3279   }
3280 #endif
3281   return NULL;
3282 }
3283
3284
3285 /* end of plugin_transport_udp.c */