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