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