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