-some fixes for monkey
[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
67 /**
68  * Closure for 'append_port'.
69  */
70 struct PrettyPrinterContext
71 {
72   /**
73    * Function to call with the result.
74    */
75   GNUNET_TRANSPORT_AddressStringCallback asc;
76
77   /**
78    * Clsoure for 'asc'.
79    */
80   void *asc_cls;
81
82   /**
83    * Port to add after the IP address.
84    */
85   uint16_t port;
86 };
87
88
89 struct Session
90 {
91   /**
92    * Which peer is this session for?
93    */
94   struct GNUNET_PeerIdentity target;
95
96   struct FragmentationContext * frag_ctx;
97
98   /**
99    * Address of the other peer
100    */
101   const struct sockaddr *sock_addr;
102
103   /**
104    * Desired delay for next sending we send to other peer
105    */
106   struct GNUNET_TIME_Relative flow_delay_for_other_peer;
107
108   /**
109    * Desired delay for next sending we received from other peer
110    */
111   struct GNUNET_TIME_Absolute flow_delay_from_other_peer;
112
113   /**
114    * Session timeout task
115    */
116   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
117
118   /**
119    * expected delay for ACKs
120    */
121   struct GNUNET_TIME_Relative last_expected_delay;
122
123   struct GNUNET_ATS_Information ats;
124
125   size_t addrlen;
126
127
128   unsigned int rc;
129
130   int in_destroy;
131 };
132
133
134 struct SessionCompareContext
135 {
136   struct Session *res;
137   const struct GNUNET_HELLO_Address *addr;
138 };
139
140
141 /**
142  * Closure for 'process_inbound_tokenized_messages'
143  */
144 struct SourceInformation
145 {
146   /**
147    * Sender identity.
148    */
149   struct GNUNET_PeerIdentity sender;
150
151   /**
152    * Source address.
153    */
154   const void *arg;
155
156   struct Session *session;
157   /**
158    * Number of bytes in source address.
159    */
160   size_t args;
161
162 };
163
164
165 /**
166  * Closure for 'find_receive_context'.
167  */
168 struct FindReceiveContext
169 {
170   /**
171    * Where to store the result.
172    */
173   struct DefragContext *rc;
174
175   /**
176    * Address to find.
177    */
178   const struct sockaddr *addr;
179
180   struct Session *session;
181
182   /**
183    * Number of bytes in 'addr'.
184    */
185   socklen_t addr_len;
186
187 };
188
189
190
191 /**
192  * Data structure to track defragmentation contexts based
193  * on the source of the UDP traffic.
194  */
195 struct DefragContext
196 {
197
198   /**
199    * Defragmentation context.
200    */
201   struct GNUNET_DEFRAGMENT_Context *defrag;
202
203   /**
204    * Source address this receive context is for (allocated at the
205    * end of the struct).
206    */
207   const struct sockaddr *src_addr;
208
209   /**
210    * Reference to master plugin struct.
211    */
212   struct Plugin *plugin;
213
214   /**
215    * Node in the defrag heap.
216    */
217   struct GNUNET_CONTAINER_HeapNode *hnode;
218
219   /**
220    * Length of 'src_addr'
221    */
222   size_t addr_len;
223 };
224
225
226
227 /**
228  * Closure for 'process_inbound_tokenized_messages'
229  */
230 struct FragmentationContext
231 {
232   struct FragmentationContext * next;
233   struct FragmentationContext * prev;
234
235   struct Plugin * plugin;
236   struct GNUNET_FRAGMENT_Context * frag;
237   struct Session * session;
238
239   /**
240    * Function to call upon completion of the transmission.
241    */
242   GNUNET_TRANSPORT_TransmitContinuation cont;
243
244   /**
245    * Closure for 'cont'.
246    */
247   void *cont_cls;
248
249   struct GNUNET_TIME_Absolute timeout;
250
251   size_t bytes_to_send;
252 };
253
254
255 struct UDPMessageWrapper
256 {
257   struct Session *session;
258   struct UDPMessageWrapper *prev;
259   struct UDPMessageWrapper *next;
260   char *udp;
261
262   /**
263    * Function to call upon completion of the transmission.
264    */
265   GNUNET_TRANSPORT_TransmitContinuation cont;
266
267   /**
268    * Closure for 'cont'.
269    */
270   void *cont_cls;
271
272   struct FragmentationContext *frag_ctx;
273
274   size_t msg_size;
275
276   struct GNUNET_TIME_Absolute timeout;
277 };
278
279
280 /**
281  * UDP ACK Message-Packet header (after defragmentation).
282  */
283 struct UDP_ACK_Message
284 {
285   /**
286    * Message header.
287    */
288   struct GNUNET_MessageHeader header;
289
290   /**
291    * Desired delay for flow control
292    */
293   uint32_t delay;
294
295   /**
296    * What is the identity of the sender
297    */
298   struct GNUNET_PeerIdentity sender;
299
300 };
301
302 /**
303  * Encapsulation of all of the state of the plugin.
304  */
305 struct Plugin * plugin;
306
307
308 /**
309  * We have been notified that our readset has something to read.  We don't
310  * know which socket needs to be read, so we have to check each one
311  * Then reschedule this function to be called again once more is available.
312  *
313  * @param cls the plugin handle
314  * @param tc the scheduling context (for rescheduling this function again)
315  */
316 static void
317 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
318
319
320 /**
321  * We have been notified that our readset has something to read.  We don't
322  * know which socket needs to be read, so we have to check each one
323  * Then reschedule this function to be called again once more is available.
324  *
325  * @param cls the plugin handle
326  * @param tc the scheduling context (for rescheduling this function again)
327  */
328 static void
329 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
330
331
332 /**
333  * Start session timeout
334  */
335 static void
336 start_session_timeout (struct Session *s);
337
338 /**
339  * Increment session timeout due to activity
340  */
341 static void
342 reschedule_session_timeout (struct Session *s);
343
344 /**
345  * Cancel timeout
346  */
347 static void
348 stop_session_timeout (struct Session *s);
349
350
351 /**
352  * (re)schedule select tasks for this plugin.
353  *
354  * @param plugin plugin to reschedule
355  */
356 static void
357 schedule_select (struct Plugin *plugin)
358 {
359   struct GNUNET_TIME_Relative min_delay;
360   struct UDPMessageWrapper *udpw;
361
362   if (NULL != plugin->sockv4)
363   {
364     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
365     for (udpw = plugin->ipv4_queue_head; NULL != udpw; udpw = udpw->next)
366       min_delay = GNUNET_TIME_relative_min (min_delay,
367                                             GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer));
368     
369     if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
370       GNUNET_SCHEDULER_cancel(plugin->select_task);
371     plugin->select_task =
372       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
373                                    (0 == min_delay.rel_value) ? GNUNET_TIME_UNIT_FOREVER_REL : min_delay,
374                                    plugin->rs_v4,
375                                    (0 == min_delay.rel_value) ? plugin->ws_v4 : NULL,
376                                    &udp_plugin_select, plugin);  
377   }
378   if (NULL != plugin->sockv6)
379   {
380     min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
381     for (udpw = plugin->ipv6_queue_head; NULL != udpw; udpw = udpw->next)
382       min_delay = GNUNET_TIME_relative_min (min_delay,
383                                             GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer));
384     
385     if (GNUNET_SCHEDULER_NO_TASK != plugin->select_task_v6)
386       GNUNET_SCHEDULER_cancel(plugin->select_task_v6);
387     plugin->select_task_v6 =
388       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
389                                    (0 == min_delay.rel_value) ? GNUNET_TIME_UNIT_FOREVER_REL : min_delay,
390                                    plugin->rs_v6,
391                                    (0 == min_delay.rel_value) ? plugin->ws_v6 : NULL,
392                                    &udp_plugin_select_v6, plugin);
393   }
394 }
395
396
397 /**
398  * Function called for a quick conversion of the binary address to
399  * a numeric address.  Note that the caller must not free the
400  * address and that the next call to this function is allowed
401  * to override the address again.
402  *
403  * @param cls closure
404  * @param addr binary address
405  * @param addrlen length of the address
406  * @return string representing the same address
407  */
408 const char *
409 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
410 {
411   static char rbuf[INET6_ADDRSTRLEN + 10];
412   char buf[INET6_ADDRSTRLEN];
413   const void *sb;
414   struct in_addr a4;
415   struct in6_addr a6;
416   const struct IPv4UdpAddress *t4;
417   const struct IPv6UdpAddress *t6;
418   int af;
419   uint16_t port;
420
421   if (addrlen == sizeof (struct IPv6UdpAddress))
422   {
423     t6 = addr;
424     af = AF_INET6;
425     port = ntohs (t6->u6_port);
426     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
427     sb = &a6;
428   }
429   else if (addrlen == sizeof (struct IPv4UdpAddress))
430   {
431     t4 = addr;
432     af = AF_INET;
433     port = ntohs (t4->u4_port);
434     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
435     sb = &a4;
436   }
437   else
438   {
439     GNUNET_break_op (0);
440     return NULL;
441   }
442   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
443   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
444                    buf, port);
445   return rbuf;
446 }
447
448
449 /**
450  * Function called to convert a string address to
451  * a binary address.
452  *
453  * @param cls closure ('struct Plugin*')
454  * @param addr string address
455  * @param addrlen length of the address
456  * @param buf location to store the buffer
457  * @param added location to store the number of bytes in the buffer.
458  *        If the function returns GNUNET_SYSERR, its contents are undefined.
459  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
460  */
461 static int
462 udp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
463     void **buf, size_t *added)
464 {
465   struct sockaddr_storage socket_address;
466   
467   if ((NULL == addr) || (0 == addrlen))
468   {
469     GNUNET_break (0);
470     return GNUNET_SYSERR;
471   }
472
473   if ('\0' != addr[addrlen - 1])
474   {
475     return GNUNET_SYSERR;
476   }
477
478   if (strlen (addr) != addrlen - 1)
479   {
480     return GNUNET_SYSERR;
481   }
482
483   if (GNUNET_OK != GNUNET_STRINGS_to_address_ip (addr, strlen (addr),
484                                                  &socket_address))
485   {
486     return GNUNET_SYSERR;
487   }
488
489   switch (socket_address.ss_family)
490   {
491   case AF_INET:
492     {
493       struct IPv4UdpAddress *u4;
494       struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
495       u4 = GNUNET_malloc (sizeof (struct IPv4UdpAddress));
496       u4->ipv4_addr = in4->sin_addr.s_addr;
497       u4->u4_port = in4->sin_port;
498       *buf = u4;
499       *added = sizeof (struct IPv4UdpAddress);
500       return GNUNET_OK;
501     }
502   case AF_INET6:
503     {
504       struct IPv6UdpAddress *u6;
505       struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
506       u6 = GNUNET_malloc (sizeof (struct IPv6UdpAddress));
507       u6->ipv6_addr = in6->sin6_addr;
508       u6->u6_port = in6->sin6_port;
509       *buf = u6;
510       *added = sizeof (struct IPv6UdpAddress);
511       return GNUNET_OK;
512     }
513   default:
514     GNUNET_break (0);
515     return GNUNET_SYSERR;
516   }
517 }
518
519
520 /**
521  * Append our port and forward the result.
522  *
523  * @param cls a 'struct PrettyPrinterContext'
524  * @param hostname result from DNS resolver
525  */
526 static void
527 append_port (void *cls, const char *hostname)
528 {
529   struct PrettyPrinterContext *ppc = cls;
530   char *ret;
531
532   if (hostname == NULL)
533   {
534     ppc->asc (ppc->asc_cls, NULL);
535     GNUNET_free (ppc);
536     return;
537   }
538   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
539   ppc->asc (ppc->asc_cls, ret);
540   GNUNET_free (ret);
541 }
542
543
544 /**
545  * Convert the transports address to a nice, human-readable
546  * format.
547  *
548  * @param cls closure
549  * @param type name of the transport that generated the address
550  * @param addr one of the addresses of the host, NULL for the last address
551  *        the specific address format depends on the transport
552  * @param addrlen length of the address
553  * @param numeric should (IP) addresses be displayed in numeric form?
554  * @param timeout after how long should we give up?
555  * @param asc function to call on each string
556  * @param asc_cls closure for asc
557  */
558 static void
559 udp_plugin_address_pretty_printer (void *cls, const char *type,
560                                    const void *addr, size_t addrlen,
561                                    int numeric,
562                                    struct GNUNET_TIME_Relative timeout,
563                                    GNUNET_TRANSPORT_AddressStringCallback asc,
564                                    void *asc_cls)
565 {
566   struct PrettyPrinterContext *ppc;
567   const void *sb;
568   size_t sbs;
569   struct sockaddr_in a4;
570   struct sockaddr_in6 a6;
571   const struct IPv4UdpAddress *u4;
572   const struct IPv6UdpAddress *u6;
573   uint16_t port;
574
575   if (addrlen == sizeof (struct IPv6UdpAddress))
576   {
577     u6 = addr;
578     memset (&a6, 0, sizeof (a6));
579     a6.sin6_family = AF_INET6;
580 #if HAVE_SOCKADDR_IN_SIN_LEN
581     a6.sin6_len = sizeof (a6);
582 #endif
583     a6.sin6_port = u6->u6_port;
584     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
585     port = ntohs (u6->u6_port);
586     sb = &a6;
587     sbs = sizeof (a6);
588   }
589   else if (addrlen == sizeof (struct IPv4UdpAddress))
590   {
591     u4 = addr;
592     memset (&a4, 0, sizeof (a4));
593     a4.sin_family = AF_INET;
594 #if HAVE_SOCKADDR_IN_SIN_LEN
595     a4.sin_len = sizeof (a4);
596 #endif
597     a4.sin_port = u4->u4_port;
598     a4.sin_addr.s_addr = u4->ipv4_addr;
599     port = ntohs (u4->u4_port);
600     sb = &a4;
601     sbs = sizeof (a4);
602   }
603   else if (0 == addrlen)
604   {
605     asc (asc_cls, "<inbound connection>");
606     asc (asc_cls, NULL);
607     return;
608   }
609   else
610   {
611     /* invalid address */
612     GNUNET_break_op (0);
613     asc (asc_cls, NULL);
614     return;
615   }
616   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
617   ppc->asc = asc;
618   ppc->asc_cls = asc_cls;
619   ppc->port = port;
620   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
621 }
622
623
624 static void
625 call_continuation (struct UDPMessageWrapper *udpw, int result)
626 {
627   LOG (GNUNET_ERROR_TYPE_DEBUG,
628       "Calling continuation for %u byte message to `%s' with result %s\n",
629       udpw->msg_size, GNUNET_i2s (&udpw->session->target),
630       (GNUNET_OK == result) ? "OK" : "SYSERR");
631   if (NULL != udpw->cont)
632   {
633     udpw->cont (udpw->cont_cls, &udpw->session->target,result);
634   }
635
636 }
637
638
639 /**
640  * Check if the given port is plausible (must be either our listen
641  * port or our advertised port).  If it is neither, we return
642  * GNUNET_SYSERR.
643  *
644  * @param plugin global variables
645  * @param in_port port number to check
646  * @return GNUNET_OK if port is either open_port or adv_port
647  */
648 static int
649 check_port (struct Plugin *plugin, uint16_t in_port)
650 {
651   if ((in_port == plugin->port) || (in_port == plugin->aport))
652     return GNUNET_OK;
653   return GNUNET_SYSERR;
654 }
655
656
657 /**
658  * Function that will be called to check if a binary address for this
659  * plugin is well-formed and corresponds to an address for THIS peer
660  * (as per our configuration).  Naturally, if absolutely necessary,
661  * plugins can be a bit conservative in their answer, but in general
662  * plugins should make sure that the address does not redirect
663  * traffic to a 3rd party that might try to man-in-the-middle our
664  * traffic.
665  *
666  * @param cls closure, should be our handle to the Plugin
667  * @param addr pointer to the address
668  * @param addrlen length of addr
669  * @return GNUNET_OK if this is a plausible address for this peer
670  *         and transport, GNUNET_SYSERR if not
671  *
672  */
673 static int
674 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
675 {
676   struct Plugin *plugin = cls;
677   struct IPv4UdpAddress *v4;
678   struct IPv6UdpAddress *v6;
679
680   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
681       (addrlen != sizeof (struct IPv6UdpAddress)))
682   {
683     GNUNET_break_op (0);
684     return GNUNET_SYSERR;
685   }
686   if (addrlen == sizeof (struct IPv4UdpAddress))
687   {
688     v4 = (struct IPv4UdpAddress *) addr;
689     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
690       return GNUNET_SYSERR;
691     if (GNUNET_OK !=
692         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
693                                  sizeof (struct in_addr)))
694       return GNUNET_SYSERR;
695   }
696   else
697   {
698     v6 = (struct IPv6UdpAddress *) addr;
699     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
700     {
701       GNUNET_break_op (0);
702       return GNUNET_SYSERR;
703     }
704     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
705       return GNUNET_SYSERR;
706     if (GNUNET_OK !=
707         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
708                                  sizeof (struct in6_addr)))
709       return GNUNET_SYSERR;
710   }
711   return GNUNET_OK;
712 }
713
714
715 /**
716  * Task to free resources associated with a session.
717  *
718  * @param s session to free
719  */
720 static void
721 free_session (struct Session *s)
722 {
723   if (s->frag_ctx != NULL)
724   {
725     GNUNET_FRAGMENT_context_destroy(s->frag_ctx->frag);
726     GNUNET_free (s->frag_ctx);
727     s->frag_ctx = NULL;
728   }
729   GNUNET_free (s);
730 }
731
732
733 /**
734  * Functions with this signature are called whenever we need
735  * to close a session due to a disconnect or failure to
736  * establish a connection.
737  *
738  * @param s session to close down
739  */
740 static void
741 disconnect_session (struct Session *s)
742 {
743   struct UDPMessageWrapper *udpw;
744   struct UDPMessageWrapper *next;
745
746   GNUNET_assert (GNUNET_YES != s->in_destroy);
747   LOG (GNUNET_ERROR_TYPE_DEBUG,
748        "Session %p to peer `%s' address ended \n",
749          s,
750          GNUNET_i2s (&s->target),
751          GNUNET_a2s (s->sock_addr, s->addrlen));
752   stop_session_timeout (s);
753   next = plugin->ipv4_queue_head;
754   while (NULL != (udpw = next))
755   {
756     next = udpw->next;
757     if (udpw->session == s)
758     {
759       GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
760       call_continuation(udpw, GNUNET_SYSERR);
761       GNUNET_free (udpw);
762     }
763   }
764   next = plugin->ipv6_queue_head;
765   while (NULL != (udpw = next))
766   {
767     next = udpw->next;
768     if (udpw->session == s)
769     {
770       GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
771       call_continuation(udpw, GNUNET_SYSERR);
772       GNUNET_free (udpw);
773     }
774     udpw = next;
775   }
776   plugin->env->session_end (plugin->env->cls, &s->target, s);
777
778   if (NULL != s->frag_ctx)
779   {
780     if (NULL != s->frag_ctx->cont)
781     {
782       s->frag_ctx->cont (s->frag_ctx->cont_cls, &s->target, GNUNET_SYSERR);
783       LOG (GNUNET_ERROR_TYPE_DEBUG,
784           "Calling continuation for fragemented message to `%s' with result SYSERR\n",
785           GNUNET_i2s (&s->target));
786     }
787   }
788
789   GNUNET_assert (GNUNET_YES ==
790                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
791                                                        &s->target.hashPubKey,
792                                                        s));
793   GNUNET_STATISTICS_set(plugin->env->stats,
794                         "# UDP sessions active",
795                         GNUNET_CONTAINER_multihashmap_size(plugin->sessions),
796                         GNUNET_NO);
797   if (s->rc > 0)
798     s->in_destroy = GNUNET_YES;
799   else
800     free_session (s);
801 }
802
803 /**
804  * Destroy a session, plugin is being unloaded.
805  *
806  * @param cls unused
807  * @param key hash of public key of target peer
808  * @param value a 'struct PeerSession*' to clean up
809  * @return GNUNET_OK (continue to iterate)
810  */
811 static int
812 disconnect_and_free_it (void *cls, const struct GNUNET_HashCode * key, void *value)
813 {
814   disconnect_session(value);
815   return GNUNET_OK;
816 }
817
818
819 /**
820  * Disconnect from a remote node.  Clean up session if we have one for this peer
821  *
822  * @param cls closure for this call (should be handle to Plugin)
823  * @param target the peeridentity of the peer to disconnect
824  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
825  */
826 static void
827 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
828 {
829   struct Plugin *plugin = cls;
830   GNUNET_assert (plugin != NULL);
831
832   GNUNET_assert (target != NULL);
833   LOG (GNUNET_ERROR_TYPE_DEBUG,
834        "Disconnecting from peer `%s'\n", GNUNET_i2s (target));
835   /* Clean up sessions */
836   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessions, &target->hashPubKey, &disconnect_and_free_it, plugin);
837 }
838
839
840 /**
841  * Session was idle, so disconnect it
842  */
843 static void
844 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
845 {
846   GNUNET_assert (NULL != cls);
847   struct Session *s = cls;
848
849   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
850   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
851               "Session %p was idle for %llu ms, disconnecting\n",
852               s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
853   /* call session destroy function */
854   disconnect_session (s);
855 }
856
857
858 /**
859  * Start session timeout
860  */
861 static void
862 start_session_timeout (struct Session *s)
863 {
864   GNUNET_assert (NULL != s);
865   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
866   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
867                                                    &session_timeout,
868                                                    s);
869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
870               "Timeout for session %p set to %llu ms\n",
871               s,  (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
872 }
873
874
875 /**
876  * Increment session timeout due to activity
877  */
878 static void
879 reschedule_session_timeout (struct Session *s)
880 {
881   GNUNET_assert (NULL != s);
882   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
883
884   GNUNET_SCHEDULER_cancel (s->timeout_task);
885   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
886                                                    &session_timeout,
887                                                    s);
888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
889               "Timeout rescheduled for session %p set to %llu ms\n",
890               s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
891 }
892
893
894 /**
895  * Cancel timeout
896  */
897 static void
898 stop_session_timeout (struct Session *s)
899 {
900   GNUNET_assert (NULL != s);
901
902   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
903   {
904     GNUNET_SCHEDULER_cancel (s->timeout_task);
905     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
906     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
907                 "Timeout stopped for session %p canceled\n",
908                 s, (unsigned long long) GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value);
909   }
910 }
911
912
913 static struct Session *
914 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
915                 const void *addr, size_t addrlen,
916                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
917 {
918   struct Session *s;
919   const struct IPv4UdpAddress *t4;
920   const struct IPv6UdpAddress *t6;
921   struct sockaddr_in *v4;
922   struct sockaddr_in6 *v6;
923   size_t len;
924
925   switch (addrlen)
926   {
927   case sizeof (struct IPv4UdpAddress):
928     if (NULL == plugin->sockv4)
929     {
930       return NULL;
931     }
932     t4 = addr;
933     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
934     len = sizeof (struct sockaddr_in);
935     v4 = (struct sockaddr_in *) &s[1];
936     v4->sin_family = AF_INET;
937 #if HAVE_SOCKADDR_IN_SIN_LEN
938     v4->sin_len = sizeof (struct sockaddr_in);
939 #endif
940     v4->sin_port = t4->u4_port;
941     v4->sin_addr.s_addr = t4->ipv4_addr;
942     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
943     break;
944   case sizeof (struct IPv6UdpAddress):
945     if (NULL == plugin->sockv6)
946     {
947       return NULL;
948     }
949     t6 = addr;
950     s =
951         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
952     len = sizeof (struct sockaddr_in6);
953     v6 = (struct sockaddr_in6 *) &s[1];
954     v6->sin6_family = AF_INET6;
955 #if HAVE_SOCKADDR_IN_SIN_LEN
956     v6->sin6_len = sizeof (struct sockaddr_in6);
957 #endif
958     v6->sin6_port = t6->u6_port;
959     v6->sin6_addr = t6->ipv6_addr;
960     s->ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
961     break;
962   default:
963     /* Must have a valid address to send to */
964     GNUNET_break_op (0);
965     return NULL;
966   }
967   s->addrlen = len;
968   s->target = *target;
969   s->sock_addr = (const struct sockaddr *) &s[1];
970   s->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
971   start_session_timeout (s);
972   return s;
973 }
974
975
976 static int
977 session_cmp_it (void *cls,
978                 const struct GNUNET_HashCode * key,
979                 void *value)
980 {
981   struct SessionCompareContext * cctx = cls;
982   const struct GNUNET_HELLO_Address *address = cctx->addr;
983   struct Session *s = value;
984
985   socklen_t s_addrlen = s->addrlen;
986
987   LOG (GNUNET_ERROR_TYPE_DEBUG, "Comparing  address %s <-> %s\n",
988       udp_address_to_string (NULL, (void *) address->address, address->address_length),
989       GNUNET_a2s (s->sock_addr, s->addrlen));
990   if ((address->address_length == sizeof (struct IPv4UdpAddress)) &&
991       (s_addrlen == sizeof (struct sockaddr_in)))
992   {
993     struct IPv4UdpAddress * u4 = NULL;
994     u4 = (struct IPv4UdpAddress *) address->address;
995     const struct sockaddr_in *s4 = (const struct sockaddr_in *) s->sock_addr;
996     if ((0 == memcmp ((const void *) &u4->ipv4_addr,(const void *) &s4->sin_addr, sizeof (struct in_addr))) &&
997         (u4->u4_port == s4->sin_port))
998     {
999       cctx->res = s;
1000       return GNUNET_NO;
1001     }
1002
1003   }
1004   if ((address->address_length == sizeof (struct IPv6UdpAddress)) &&
1005       (s_addrlen == sizeof (struct sockaddr_in6)))
1006   {
1007     struct IPv6UdpAddress * u6 = NULL;
1008     u6 = (struct IPv6UdpAddress *) address->address;
1009     const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) s->sock_addr;
1010     if ((0 == memcmp (&u6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr))) &&
1011         (u6->u6_port == s6->sin6_port))
1012     {
1013       cctx->res = s;
1014       return GNUNET_NO;
1015     }
1016   }
1017   return GNUNET_YES;
1018 }
1019
1020
1021 /**
1022  * Creates a new outbound session the transport service will use to send data to the
1023  * peer
1024  *
1025  * @param cls the plugin
1026  * @param address the address
1027  * @return the session or NULL of max connections exceeded
1028  */
1029 static struct Session *
1030 udp_plugin_get_session (void *cls,
1031                   const struct GNUNET_HELLO_Address *address)
1032 {
1033   struct Session * s = NULL;
1034   struct Plugin * plugin = cls;
1035   struct IPv6UdpAddress * udp_a6;
1036   struct IPv4UdpAddress * udp_a4;
1037
1038   GNUNET_assert (plugin != NULL);
1039   GNUNET_assert (address != NULL);
1040
1041
1042   if ((address->address == NULL) ||
1043       ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
1044       (address->address_length != sizeof (struct IPv6UdpAddress))))
1045   {
1046     GNUNET_break (0);
1047     return NULL;
1048   }
1049
1050   if (address->address_length == sizeof (struct IPv4UdpAddress))
1051   {
1052     if (plugin->sockv4 == NULL)
1053       return NULL;
1054     udp_a4 = (struct IPv4UdpAddress *) address->address;
1055     if (udp_a4->u4_port == 0)
1056       return NULL;
1057   }
1058
1059   if (address->address_length == sizeof (struct IPv6UdpAddress))
1060   {
1061     if (plugin->sockv6 == NULL)
1062       return NULL;
1063     udp_a6 = (struct IPv6UdpAddress *) address->address;
1064     if (udp_a6->u6_port == 0)
1065       return NULL;
1066   }
1067
1068   /* check if session already exists */
1069   struct SessionCompareContext cctx;
1070   cctx.addr = address;
1071   cctx.res = NULL;
1072   LOG (GNUNET_ERROR_TYPE_DEBUG,
1073        "Looking for existing session for peer `%s' `%s' \n", 
1074        GNUNET_i2s (&address->peer), 
1075        udp_address_to_string(NULL, address->address, address->address_length));
1076   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessions, &address->peer.hashPubKey, session_cmp_it, &cctx);
1077   if (cctx.res != NULL)
1078   {
1079     LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p\n", cctx.res);
1080     return cctx.res;
1081   }
1082
1083   /* otherwise create new */
1084   s = create_session (plugin,
1085       &address->peer,
1086       address->address,
1087       address->address_length,
1088       NULL, NULL);
1089   LOG (GNUNET_ERROR_TYPE_DEBUG,
1090        "Creating new session %p for peer `%s' address `%s'\n",
1091        s,
1092        GNUNET_i2s(&address->peer),
1093        udp_address_to_string(NULL,address->address,address->address_length));
1094   GNUNET_assert (GNUNET_OK ==
1095                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
1096                                                     &s->target.hashPubKey,
1097                                                     s,
1098                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1099
1100   GNUNET_STATISTICS_set(plugin->env->stats,
1101                         "# UDP sessions active",
1102                         GNUNET_CONTAINER_multihashmap_size(plugin->sessions),
1103                         GNUNET_NO);
1104
1105   return s;
1106 }
1107
1108
1109 static void 
1110 enqueue (struct Plugin *plugin, struct UDPMessageWrapper * udpw)
1111 {
1112
1113   if (udpw->session->addrlen == sizeof (struct sockaddr_in))
1114     GNUNET_CONTAINER_DLL_insert(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1115   if (udpw->session->addrlen == sizeof (struct sockaddr_in6))
1116     GNUNET_CONTAINER_DLL_insert(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1117 }
1118
1119
1120 /**
1121  * Fragment message was transmitted via UDP, let fragmentation know
1122  * to send the next fragment now.
1123  *
1124  * @param cls the 'struct UDPMessageWrapper' of the fragment
1125  * @param target destination peer (ignored)
1126  * @param result GNUNET_OK on success (ignored)
1127  */
1128 static void
1129 send_next_fragment (void *cls,
1130                     const struct GNUNET_PeerIdentity *target,
1131                     int result)
1132 {
1133   struct UDPMessageWrapper *udpw = cls;
1134
1135   GNUNET_FRAGMENT_context_transmission_done (udpw->frag_ctx->frag);  
1136 }
1137
1138
1139 /**
1140  * Function that is called with messages created by the fragmentation
1141  * module.  In the case of the 'proc' callback of the
1142  * GNUNET_FRAGMENT_context_create function, this function must
1143  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
1144  *
1145  * @param cls closure, the 'struct FragmentationContext'
1146  * @param msg the message that was created
1147  */
1148 static void
1149 enqueue_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
1150 {
1151   struct FragmentationContext *frag_ctx = cls;
1152   struct Plugin *plugin = frag_ctx->plugin;
1153   struct UDPMessageWrapper * udpw;
1154   size_t msg_len = ntohs (msg->size);
1155  
1156   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1157        "Enqueuing fragment with %u bytes %u\n", msg_len , sizeof (struct UDPMessageWrapper));
1158   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msg_len);
1159   udpw->session = frag_ctx->session;
1160   udpw->udp = (char *) &udpw[1];
1161
1162   udpw->msg_size = msg_len;
1163   udpw->cont = &send_next_fragment;
1164   udpw->cont_cls = udpw;
1165   udpw->timeout = frag_ctx->timeout;
1166   udpw->frag_ctx = frag_ctx;
1167   memcpy (udpw->udp, msg, msg_len);
1168   enqueue (plugin, udpw);
1169   schedule_select (plugin);
1170 }
1171
1172
1173 /**
1174  * Function that can be used by the transport service to transmit
1175  * a message using the plugin.   Note that in the case of a
1176  * peer disconnecting, the continuation MUST be called
1177  * prior to the disconnect notification itself.  This function
1178  * will be called with this peer's HELLO message to initiate
1179  * a fresh connection to another peer.
1180  *
1181  * @param cls closure
1182  * @param s which session must be used
1183  * @param msgbuf the message to transmit
1184  * @param msgbuf_size number of bytes in 'msgbuf'
1185  * @param priority how important is the message (most plugins will
1186  *                 ignore message priority and just FIFO)
1187  * @param to how long to wait at most for the transmission (does not
1188  *                require plugins to discard the message after the timeout,
1189  *                just advisory for the desired delay; most plugins will ignore
1190  *                this as well)
1191  * @param cont continuation to call once the message has
1192  *        been transmitted (or if the transport is ready
1193  *        for the next transmission call; or if the
1194  *        peer disconnected...); can be NULL
1195  * @param cont_cls closure for cont
1196  * @return number of bytes used (on the physical network, with overheads);
1197  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1198  *         and does NOT mean that the message was not transmitted (DV)
1199  */
1200 static ssize_t
1201 udp_plugin_send (void *cls,
1202                   struct Session *s,
1203                   const char *msgbuf, size_t msgbuf_size,
1204                   unsigned int priority,
1205                   struct GNUNET_TIME_Relative to,
1206                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1207 {
1208   struct Plugin *plugin = cls;
1209   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
1210   struct UDPMessageWrapper * udpw;
1211   struct UDPMessage *udp;
1212   char mbuf[mlen];
1213   GNUNET_assert (plugin != NULL);
1214   GNUNET_assert (s != NULL);
1215
1216   if ((s->addrlen == sizeof (struct sockaddr_in6)) && (plugin->sockv6 == NULL))
1217     return GNUNET_SYSERR;
1218   if ((s->addrlen == sizeof (struct sockaddr_in)) && (plugin->sockv4 == NULL))
1219     return GNUNET_SYSERR;
1220   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1221   {
1222     GNUNET_break (0);
1223     return GNUNET_SYSERR;
1224   }
1225   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessions, &s->target.hashPubKey, s))
1226   {
1227     GNUNET_break (0);
1228     return GNUNET_SYSERR;
1229   }
1230   LOG (GNUNET_ERROR_TYPE_DEBUG,
1231        "UDP transmits %u-byte message to `%s' using address `%s'\n",
1232        mlen,
1233        GNUNET_i2s (&s->target),
1234        GNUNET_a2s(s->sock_addr, s->addrlen));
1235   
1236   GNUNET_STATISTICS_update (plugin->env->stats,
1237                             "# bytes currently in UDP buffers",
1238                             msgbuf_size, GNUNET_NO);
1239   GNUNET_STATISTICS_update (plugin->env->stats,
1240                             "# bytes payload asked to transmit via UDP",
1241                             msgbuf_size, GNUNET_NO);
1242
1243
1244   /* Message */
1245   udp = (struct UDPMessage *) mbuf;
1246   udp->header.size = htons (mlen);
1247   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
1248   udp->reserved = htonl (0);
1249   udp->sender = *plugin->env->my_identity;
1250
1251   reschedule_session_timeout(s);
1252   if (mlen <= UDP_MTU)
1253   {
1254     udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + mlen);
1255     udpw->session = s;
1256     udpw->udp = (char *) &udpw[1];
1257     udpw->msg_size = mlen;
1258     udpw->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1259     udpw->cont = cont;
1260     udpw->cont_cls = cont_cls;
1261     udpw->frag_ctx = NULL;
1262     memcpy (udpw->udp, udp, sizeof (struct UDPMessage));
1263     memcpy (&udpw->udp[sizeof (struct UDPMessage)], msgbuf, msgbuf_size);
1264     enqueue (plugin, udpw);
1265   }
1266   else
1267   {
1268     LOG (GNUNET_ERROR_TYPE_DEBUG,
1269          "UDP has to fragment message\n");
1270     if  (s->frag_ctx != NULL)
1271       return GNUNET_SYSERR;
1272     memcpy (&udp[1], msgbuf, msgbuf_size);
1273     struct FragmentationContext * frag_ctx = GNUNET_malloc(sizeof (struct FragmentationContext));
1274
1275     frag_ctx->plugin = plugin;
1276     frag_ctx->session = s;
1277     frag_ctx->cont = cont;
1278     frag_ctx->cont_cls = cont_cls;
1279     frag_ctx->timeout = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), to);
1280     frag_ctx->bytes_to_send = mlen;
1281     frag_ctx->frag = GNUNET_FRAGMENT_context_create (plugin->env->stats,
1282               UDP_MTU,
1283               &plugin->tracker,
1284               s->last_expected_delay,
1285               &udp->header,
1286               &enqueue_fragment,
1287               frag_ctx);
1288
1289     s->frag_ctx = frag_ctx;
1290   }
1291   schedule_select (plugin);
1292   return mlen;
1293 }
1294
1295
1296 /**
1297  * Our external IP address/port mapping has changed.
1298  *
1299  * @param cls closure, the 'struct LocalAddrList'
1300  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1301  *     the previous (now invalid) one
1302  * @param addr either the previous or the new public IP address
1303  * @param addrlen actual lenght of the address
1304  */
1305 static void
1306 udp_nat_port_map_callback (void *cls, int add_remove,
1307                            const struct sockaddr *addr, socklen_t addrlen)
1308 {
1309   struct Plugin *plugin = cls;
1310   struct IPv4UdpAddress u4;
1311   struct IPv6UdpAddress u6;
1312   void *arg;
1313   size_t args;
1314
1315   /* convert 'addr' to our internal format */
1316   switch (addr->sa_family)
1317   {
1318   case AF_INET:
1319     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1320     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1321     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1322     arg = &u4;
1323     args = sizeof (u4);
1324     break;
1325   case AF_INET6:
1326     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1327     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1328             sizeof (struct in6_addr));
1329     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1330     arg = &u6;
1331     args = sizeof (u6);
1332     break;
1333   default:
1334     GNUNET_break (0);
1335     return;
1336   }
1337   /* modify our published address list */
1338   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args, "udp");
1339 }
1340
1341
1342
1343 /**
1344  * Message tokenizer has broken up an incomming message. Pass it on
1345  * to the service.
1346  *
1347  * @param cls the 'struct Plugin'
1348  * @param client the 'struct SourceInformation'
1349  * @param hdr the actual message
1350  */
1351 static int
1352 process_inbound_tokenized_messages (void *cls, void *client,
1353                                     const struct GNUNET_MessageHeader *hdr)
1354 {
1355   struct Plugin *plugin = cls;
1356   struct SourceInformation *si = client;
1357   struct GNUNET_ATS_Information ats[2];
1358   struct GNUNET_TIME_Relative delay;
1359
1360   GNUNET_assert (si->session != NULL);
1361   if (GNUNET_YES == si->session->in_destroy)
1362     return GNUNET_OK;
1363   /* setup ATS */
1364   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1365   ats[0].value = htonl (1);
1366   ats[1] = si->session->ats;
1367   GNUNET_break (ntohl(ats[1].value) != GNUNET_ATS_NET_UNSPECIFIED);
1368   delay = plugin->env->receive (plugin->env->cls,
1369                                 &si->sender,
1370                                 hdr,
1371                                 (const struct GNUNET_ATS_Information *) &ats, 2,
1372                                 si->session,
1373                                 si->arg,
1374                                 si->args);
1375   si->session->flow_delay_for_other_peer = delay;
1376   reschedule_session_timeout(si->session);
1377   return GNUNET_OK;
1378 }
1379
1380
1381 /**
1382  * We've received a UDP Message.  Process it (pass contents to main service).
1383  *
1384  * @param plugin plugin context
1385  * @param msg the message
1386  * @param sender_addr sender address
1387  * @param sender_addr_len number of bytes in sender_addr
1388  */
1389 static void
1390 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1391                      const struct sockaddr *sender_addr,
1392                      socklen_t sender_addr_len)
1393 {
1394   struct SourceInformation si;
1395   struct Session * s;
1396   struct IPv4UdpAddress u4;
1397   struct IPv6UdpAddress u6;
1398   const void *arg;
1399   size_t args;
1400
1401   if (0 != ntohl (msg->reserved))
1402   {
1403     GNUNET_break_op (0);
1404     return;
1405   }
1406   if (ntohs (msg->header.size) <
1407       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
1408   {
1409     GNUNET_break_op (0);
1410     return;
1411   }
1412
1413   /* convert address */
1414   switch (sender_addr->sa_family)
1415   {
1416   case AF_INET:
1417     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
1418     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
1419     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1420     arg = &u4;
1421     args = sizeof (u4);
1422     break;
1423   case AF_INET6:
1424     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
1425     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
1426     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
1427     arg = &u6;
1428     args = sizeof (u6);
1429     break;
1430   default:
1431     GNUNET_break (0);
1432     return;
1433   }
1434   LOG (GNUNET_ERROR_TYPE_DEBUG,
1435        "Received message with %u bytes from peer `%s' at `%s'\n",
1436        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1437        GNUNET_a2s (sender_addr, sender_addr_len));
1438
1439   struct GNUNET_HELLO_Address * address = GNUNET_HELLO_address_allocate(&msg->sender, "udp", arg, args);
1440   s = udp_plugin_get_session(plugin, address);
1441   GNUNET_free (address);
1442
1443   /* iterate over all embedded messages */
1444   si.session = s;
1445   si.sender = msg->sender;
1446   si.arg = arg;
1447   si.args = args;
1448   s->rc++;
1449   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
1450                              ntohs (msg->header.size) -
1451                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
1452   s->rc--;
1453   if ( (0 == s->rc) && (GNUNET_YES == s->in_destroy))
1454     free_session (s);
1455 }
1456
1457
1458 /**
1459  * Scan the heap for a receive context with the given address.
1460  *
1461  * @param cls the 'struct FindReceiveContext'
1462  * @param node internal node of the heap
1463  * @param element value stored at the node (a 'struct ReceiveContext')
1464  * @param cost cost associated with the node
1465  * @return GNUNET_YES if we should continue to iterate,
1466  *         GNUNET_NO if not.
1467  */
1468 static int
1469 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1470                       void *element, GNUNET_CONTAINER_HeapCostType cost)
1471 {
1472   struct FindReceiveContext *frc = cls;
1473   struct DefragContext *e = element;
1474
1475   if ((frc->addr_len == e->addr_len) &&
1476       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1477   {
1478     frc->rc = e;
1479     return GNUNET_NO;
1480   }
1481   return GNUNET_YES;
1482 }
1483
1484
1485 /**
1486  * Process a defragmented message.
1487  *
1488  * @param cls the 'struct ReceiveContext'
1489  * @param msg the message
1490  */
1491 static void
1492 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1493 {
1494   struct DefragContext *rc = cls;
1495
1496   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1497   {
1498     GNUNET_break (0);
1499     return;
1500   }
1501   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1502   {
1503     GNUNET_break (0);
1504     return;
1505   }
1506   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1507                        rc->src_addr, rc->addr_len);
1508 }
1509
1510
1511 struct LookupContext
1512 {
1513   const struct sockaddr * addr;
1514
1515   struct Session *res;
1516
1517   size_t addrlen;
1518 };
1519
1520
1521 static int
1522 lookup_session_by_addr_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1523 {
1524   struct LookupContext *l_ctx = cls;
1525   struct Session * s = value;
1526
1527   if ((s->addrlen == l_ctx->addrlen) &&
1528       (0 == memcmp (s->sock_addr, l_ctx->addr, s->addrlen)))
1529   {
1530     l_ctx->res = s;
1531     return GNUNET_NO;
1532   }
1533   return GNUNET_YES;
1534 }
1535
1536
1537 /**
1538  * Transmit an acknowledgement.
1539  *
1540  * @param cls the 'struct ReceiveContext'
1541  * @param id message ID (unused)
1542  * @param msg ack to transmit
1543  */
1544 static void
1545 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
1546 {
1547   struct DefragContext *rc = cls;
1548   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
1549   struct UDP_ACK_Message *udp_ack;
1550   uint32_t delay = 0;
1551   struct UDPMessageWrapper *udpw;
1552   struct Session *s;
1553
1554   struct LookupContext l_ctx;
1555   l_ctx.addr = rc->src_addr;
1556   l_ctx.addrlen = rc->addr_len;
1557   l_ctx.res = NULL;
1558   GNUNET_CONTAINER_multihashmap_iterate (rc->plugin->sessions,
1559       &lookup_session_by_addr_it,
1560       &l_ctx);
1561   s = l_ctx.res;
1562
1563   if (NULL == s)
1564     return;
1565
1566   if (s->flow_delay_for_other_peer.rel_value <= UINT32_MAX)
1567     delay = s->flow_delay_for_other_peer.rel_value;
1568
1569   LOG (GNUNET_ERROR_TYPE_DEBUG,
1570        "Sending ACK to `%s' including delay of %u ms\n",
1571        GNUNET_a2s (rc->src_addr,
1572                    (rc->src_addr->sa_family ==
1573                     AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct
1574                                                                      sockaddr_in6)),
1575        delay);
1576   udpw = GNUNET_malloc (sizeof (struct UDPMessageWrapper) + msize);
1577   udpw->msg_size = msize;
1578   udpw->session = s;
1579   udpw->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1580   udpw->udp = (char *)&udpw[1];
1581   udp_ack = (struct UDP_ACK_Message *) udpw->udp;
1582   udp_ack->header.size = htons ((uint16_t) msize);
1583   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
1584   udp_ack->delay = htonl (delay);
1585   udp_ack->sender = *rc->plugin->env->my_identity;
1586   memcpy (&udp_ack[1], msg, ntohs (msg->size));
1587
1588   enqueue (rc->plugin, udpw);
1589 }
1590
1591
1592 static void 
1593 read_process_msg (struct Plugin *plugin,
1594                   const struct GNUNET_MessageHeader *msg,
1595                   const char *addr,
1596                   socklen_t fromlen)
1597 {
1598   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1599   {
1600     GNUNET_break_op (0);
1601     return;
1602   }
1603   process_udp_message (plugin, (const struct UDPMessage *) msg,
1604                        (const struct sockaddr *) addr, fromlen);
1605 }
1606
1607
1608 static void 
1609 read_process_ack (struct Plugin *plugin,
1610                   const struct GNUNET_MessageHeader *msg,
1611                   char *addr,
1612                   socklen_t fromlen)
1613 {
1614   const struct GNUNET_MessageHeader *ack;
1615   const struct UDP_ACK_Message *udp_ack;
1616   struct LookupContext l_ctx;
1617   struct Session *s;
1618   struct GNUNET_TIME_Relative flow_delay;
1619
1620   if (ntohs (msg->size) <
1621       sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
1622   {
1623     GNUNET_break_op (0);
1624     return;
1625   }
1626   udp_ack = (const struct UDP_ACK_Message *) msg;
1627   l_ctx.addr = (const struct sockaddr *) addr;
1628   l_ctx.addrlen = fromlen;
1629   l_ctx.res = NULL;
1630   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
1631       &lookup_session_by_addr_it,
1632       &l_ctx);
1633   s = l_ctx.res;
1634
1635   if ((s == NULL) || (s->frag_ctx == NULL))
1636     return;
1637
1638   flow_delay.rel_value = (uint64_t) ntohl (udp_ack->delay);
1639   LOG (GNUNET_ERROR_TYPE_DEBUG, "We received a sending delay of %llu\n",
1640        flow_delay.rel_value);
1641   s->flow_delay_from_other_peer =
1642       GNUNET_TIME_relative_to_absolute (flow_delay);
1643
1644   ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
1645   if (ntohs (ack->size) !=
1646       ntohs (msg->size) - sizeof (struct UDP_ACK_Message))
1647   {
1648     GNUNET_break_op (0);
1649     return;
1650   }
1651
1652   if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (s->frag_ctx->frag, ack))
1653   {
1654     LOG (GNUNET_ERROR_TYPE_DEBUG,
1655          "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1656          (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1657          GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1658     return;
1659   }
1660
1661   LOG (GNUNET_ERROR_TYPE_DEBUG,
1662        "FULL MESSAGE ACKed\n",
1663        (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1664        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1665   s->last_expected_delay = GNUNET_FRAGMENT_context_destroy (s->frag_ctx->frag);
1666
1667   struct UDPMessageWrapper * udpw;
1668   struct UDPMessageWrapper * tmp;
1669   if (s->addrlen == sizeof (struct sockaddr_in6))
1670   {
1671     udpw = plugin->ipv6_queue_head;
1672     while (NULL != udpw)
1673     {
1674       tmp = udpw->next;
1675       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1676       {
1677         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1678         GNUNET_free (udpw);
1679       }
1680       udpw = tmp;
1681     }
1682   }
1683   if (s->addrlen == sizeof (struct sockaddr_in))
1684   {
1685     udpw = plugin->ipv4_queue_head;
1686     while (udpw!= NULL)
1687     {
1688       tmp = udpw->next;
1689       if ((udpw->frag_ctx != NULL) && (udpw->frag_ctx == s->frag_ctx))
1690       {
1691         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1692         GNUNET_free (udpw);
1693       }
1694       udpw = tmp;
1695     }
1696   }
1697
1698   if (s->frag_ctx->cont != NULL)
1699   {
1700     LOG (GNUNET_ERROR_TYPE_DEBUG,
1701         "Calling continuation for fragmented message to `%s' with result %s\n",
1702         GNUNET_i2s (&s->target), "OK");
1703     s->frag_ctx->cont (s->frag_ctx->cont_cls, &udp_ack->sender, GNUNET_OK);
1704   }
1705
1706   GNUNET_free (s->frag_ctx);
1707   s->frag_ctx = NULL;
1708 }
1709
1710
1711 static void 
1712 read_process_fragment (struct Plugin *plugin,
1713                        const struct GNUNET_MessageHeader *msg,
1714                        char *addr,
1715                        socklen_t fromlen)
1716 {
1717   struct DefragContext *d_ctx;
1718   struct GNUNET_TIME_Absolute now;
1719   struct FindReceiveContext frc;
1720
1721   frc.rc = NULL;
1722   frc.addr = (const struct sockaddr *) addr;
1723   frc.addr_len = fromlen;
1724
1725   LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
1726        (unsigned int) ntohs (msg->size),
1727        GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1728   /* Lookup existing receive context for this address */
1729   GNUNET_CONTAINER_heap_iterate (plugin->defrag_ctxs,
1730                                  &find_receive_context,
1731                                  &frc);
1732   now = GNUNET_TIME_absolute_get ();
1733   d_ctx = frc.rc;
1734
1735   if (d_ctx == NULL)
1736   {
1737     /* Create a new defragmentation context */
1738     d_ctx = GNUNET_malloc (sizeof (struct DefragContext) + fromlen);
1739     memcpy (&d_ctx[1], addr, fromlen);
1740     d_ctx->src_addr = (const struct sockaddr *) &d_ctx[1];
1741     d_ctx->addr_len = fromlen;
1742     d_ctx->plugin = plugin;
1743     d_ctx->defrag =
1744         GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1745                                           UDP_MAX_MESSAGES_IN_DEFRAG, d_ctx,
1746                                           &fragment_msg_proc, &ack_proc);
1747     d_ctx->hnode =
1748         GNUNET_CONTAINER_heap_insert (plugin->defrag_ctxs, d_ctx,
1749                                       (GNUNET_CONTAINER_HeapCostType)
1750                                       now.abs_value);
1751     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1752          "Created new defragmentation context for %u-byte fragment from `%s'\n",
1753          (unsigned int) ntohs (msg->size),
1754          GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1755   }
1756   else
1757   {
1758     LOG (GNUNET_ERROR_TYPE_DEBUG,
1759          "Found existing defragmentation context for %u-byte fragment from `%s'\n",
1760          (unsigned int) ntohs (msg->size),
1761          GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1762   }
1763
1764   if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (d_ctx->defrag, msg))
1765   {
1766     /* keep this 'rc' from expiring */
1767     GNUNET_CONTAINER_heap_update_cost (plugin->defrag_ctxs, d_ctx->hnode,
1768                                        (GNUNET_CONTAINER_HeapCostType)
1769                                        now.abs_value);
1770   }
1771   if (GNUNET_CONTAINER_heap_get_size (plugin->defrag_ctxs) >
1772       UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1773   {
1774     /* remove 'rc' that was inactive the longest */
1775     d_ctx = GNUNET_CONTAINER_heap_remove_root (plugin->defrag_ctxs);
1776     GNUNET_assert (NULL != d_ctx);
1777     GNUNET_DEFRAGMENT_context_destroy (d_ctx->defrag);
1778     GNUNET_free (d_ctx);
1779   }
1780 }
1781
1782
1783 /**
1784  * Read and process a message from the given socket.
1785  *
1786  * @param plugin the overall plugin
1787  * @param rsock socket to read from
1788  */
1789 static void
1790 udp_select_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
1791 {
1792   socklen_t fromlen;
1793   char addr[32];
1794   char buf[65536] GNUNET_ALIGN;
1795   ssize_t size;
1796   const struct GNUNET_MessageHeader *msg;
1797
1798   fromlen = sizeof (addr);
1799   memset (&addr, 0, sizeof (addr));
1800   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
1801                                       (struct sockaddr *) &addr, &fromlen);
1802 #if MINGW
1803   /* On SOCK_DGRAM UDP sockets recvfrom might fail with a
1804    * WSAECONNRESET error to indicate that previous sendto() (???)
1805    * on this socket has failed.
1806    */
1807   if ( (-1 == size) && (ECONNRESET == errno) )
1808     return;
1809 #endif
1810   if ( (-1 == size) || (size < sizeof (struct GNUNET_MessageHeader)))
1811   {
1812     GNUNET_break_op (0);
1813     return;
1814   }
1815   msg = (const struct GNUNET_MessageHeader *) buf;
1816
1817   LOG (GNUNET_ERROR_TYPE_DEBUG,
1818        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) size,
1819        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
1820
1821   if (size != ntohs (msg->size))
1822   {
1823     GNUNET_break_op (0);
1824     return;
1825   }
1826
1827   GNUNET_STATISTICS_update (plugin->env->stats,
1828                             "# bytes received via UDP",
1829                             size, GNUNET_NO);
1830
1831   switch (ntohs (msg->type))
1832   {
1833   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
1834     udp_broadcast_receive (plugin, &buf, size, addr, fromlen);
1835     return;
1836
1837   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
1838     read_process_msg (plugin, msg, addr, fromlen);
1839     return;
1840
1841   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
1842     read_process_ack (plugin, msg, addr, fromlen);
1843     return;
1844
1845   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1846     read_process_fragment (plugin, msg, addr, fromlen);
1847     return;
1848
1849   default:
1850     GNUNET_break_op (0);
1851     return;
1852   }
1853 }
1854
1855
1856 static size_t
1857 udp_select_send (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *sock)
1858 {
1859   ssize_t sent;
1860   size_t slen;
1861   struct GNUNET_TIME_Absolute max;
1862   struct UDPMessageWrapper *udpw = NULL;
1863   static int network_down_error;
1864
1865   if (sock == plugin->sockv4)
1866   {
1867     udpw = plugin->ipv4_queue_head;
1868   }
1869   else if (sock == plugin->sockv6)
1870   {
1871     udpw = plugin->ipv6_queue_head;
1872   }
1873   else
1874   {
1875     GNUNET_break (0);
1876     return 0;
1877   }
1878
1879   const struct sockaddr * sa = udpw->session->sock_addr;
1880   slen = udpw->session->addrlen;
1881
1882   max = GNUNET_TIME_absolute_max (udpw->timeout, GNUNET_TIME_absolute_get());
1883
1884   while (udpw != NULL)
1885   {
1886     if (max.abs_value != udpw->timeout.abs_value)
1887     {
1888       /* Message timed out */
1889       call_continuation(udpw, GNUNET_SYSERR);
1890       if (udpw->frag_ctx != NULL)
1891       {
1892         LOG (GNUNET_ERROR_TYPE_DEBUG,
1893              "Fragmented message for peer `%s' with size %u timed out\n",
1894              GNUNET_i2s(&udpw->session->target), udpw->frag_ctx->bytes_to_send);
1895         udpw->session->last_expected_delay = GNUNET_FRAGMENT_context_destroy (udpw->frag_ctx->frag);
1896         GNUNET_free (udpw->frag_ctx);
1897         udpw->session->frag_ctx = NULL;
1898       }
1899       else
1900       {
1901         LOG (GNUNET_ERROR_TYPE_DEBUG, 
1902              "Message for peer `%s' with size %u timed out\n",
1903              GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1904       }
1905
1906       if (sock == plugin->sockv4)
1907       {
1908         GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
1909         GNUNET_free (udpw);
1910         udpw = plugin->ipv4_queue_head;
1911       }
1912       else if (sock == plugin->sockv6)
1913       {
1914         GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
1915         GNUNET_free (udpw);
1916         udpw = plugin->ipv6_queue_head;
1917       }
1918     }
1919     else
1920     {
1921       struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_remaining (udpw->session->flow_delay_from_other_peer);
1922       if (delta.rel_value == 0)
1923       {
1924         /* this message is not delayed */
1925         LOG (GNUNET_ERROR_TYPE_DEBUG, 
1926              "Message for peer `%s' (%u bytes) is not delayed \n",
1927              GNUNET_i2s(&udpw->session->target), udpw->msg_size);
1928         break;
1929       }
1930       else
1931       {
1932         /* this message is delayed, try next */
1933         LOG (GNUNET_ERROR_TYPE_DEBUG,
1934              "Message for peer `%s' (%u bytes) is delayed for %llu \n",
1935              GNUNET_i2s(&udpw->session->target), udpw->msg_size,
1936              delta);
1937         udpw = udpw->next;
1938       }
1939     }
1940   }
1941
1942   if (udpw == NULL)
1943   {
1944     /* No message left */
1945     return 0;
1946   }
1947
1948   sent = GNUNET_NETWORK_socket_sendto (sock, udpw->udp, udpw->msg_size, sa, slen);
1949
1950   if (GNUNET_SYSERR == sent)
1951   {
1952     const struct GNUNET_ATS_Information type = plugin->env->get_address_type
1953         (plugin->env->cls,sa, slen);
1954
1955     if (((GNUNET_ATS_NET_LAN == ntohl(type.value)) || (GNUNET_ATS_NET_WAN == ntohl(type.value))) &&
1956         ((ENETUNREACH == errno) || (ENETDOWN == errno)))
1957     {
1958       if ((network_down_error == GNUNET_NO) && (slen == sizeof (struct sockaddr_in)))
1959       {
1960         /* IPv4: "Network unreachable" or "Network down"
1961          *
1962          * This indicates we do not have connectivity
1963          */
1964         LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
1965             _("UDP could not transmit message to `%s': "
1966               "Network seems down, please check your network configuration\n"),
1967             GNUNET_a2s (sa, slen));
1968       }
1969       if ((network_down_error == GNUNET_NO) && (slen == sizeof (struct sockaddr_in6)))
1970       {
1971         /* IPv6: "Network unreachable" or "Network down"
1972          *
1973          * This indicates that this system is IPv6 enabled, but does not
1974          * have a valid global IPv6 address assigned or we do not have
1975          * connectivity
1976          */
1977
1978        LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
1979            _("UDP could not transmit message to `%s': "
1980              "Please check your network configuration and disable IPv6 if your "
1981              "connection does not have a global IPv6 address\n"),
1982            GNUNET_a2s (sa, slen));
1983       }
1984     }
1985     else
1986     {
1987       LOG (GNUNET_ERROR_TYPE_WARNING,
1988          "UDP could not transmit %u-byte message to `%s': `%s'\n",
1989          (unsigned int) (udpw->msg_size), GNUNET_a2s (sa, slen),
1990          STRERROR (errno));
1991     }
1992     call_continuation(udpw, GNUNET_SYSERR);
1993   }
1994   else
1995   {
1996     LOG (GNUNET_ERROR_TYPE_DEBUG,
1997          "UDP transmitted %u-byte message to  `%s' `%s' (%d: %s)\n",
1998          (unsigned int) (udpw->msg_size), GNUNET_i2s(&udpw->session->target) ,GNUNET_a2s (sa, slen), (int) sent,
1999          (sent < 0) ? STRERROR (errno) : "ok");
2000     GNUNET_STATISTICS_update (plugin->env->stats,
2001                               "# bytes transmitted via UDP",
2002                               sent, GNUNET_NO);
2003     call_continuation(udpw, GNUNET_OK);
2004     network_down_error = GNUNET_NO;
2005   }
2006
2007   GNUNET_STATISTICS_update (plugin->env->stats,
2008                             "# bytes currently in UDP buffers",
2009                             -udpw->msg_size, GNUNET_NO);
2010
2011   if (sock == plugin->sockv4)
2012     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
2013   else if (sock == plugin->sockv6)
2014     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
2015   GNUNET_free (udpw);
2016   udpw = NULL;
2017
2018   return sent;
2019 }
2020
2021
2022 /**
2023  * We have been notified that our readset has something to read.  We don't
2024  * know which socket needs to be read, so we have to check each one
2025  * Then reschedule this function to be called again once more is available.
2026  *
2027  * @param cls the plugin handle
2028  * @param tc the scheduling context (for rescheduling this function again)
2029  */
2030 static void
2031 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2032 {
2033   struct Plugin *plugin = cls;
2034
2035   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2036   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2037     return;
2038   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
2039        (NULL != plugin->sockv4) &&
2040        (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)) )
2041     udp_select_read (plugin, plugin->sockv4);
2042   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
2043        (NULL != plugin->sockv4) && 
2044        (NULL != plugin->ipv4_queue_head) &&
2045        (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv4)) )
2046     udp_select_send (plugin, plugin->sockv4);   
2047   schedule_select (plugin);
2048 }
2049
2050
2051 /**
2052  * We have been notified that our readset has something to read.  We don't
2053  * know which socket needs to be read, so we have to check each one
2054  * Then reschedule this function to be called again once more is available.
2055  *
2056  * @param cls the plugin handle
2057  * @param tc the scheduling context (for rescheduling this function again)
2058  */
2059 static void
2060 udp_plugin_select_v6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2061 {
2062   struct Plugin *plugin = cls;
2063
2064   plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2065   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2066     return;
2067   if ( ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0) &&
2068        (NULL != plugin->sockv6) &&
2069        (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)) )
2070     udp_select_read (plugin, plugin->sockv6);
2071   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
2072        (NULL != plugin->sockv6) && (plugin->ipv6_queue_head != NULL) &&
2073        (GNUNET_NETWORK_fdset_isset (tc->write_ready, plugin->sockv6)) )    
2074     udp_select_send (plugin, plugin->sockv6);
2075   schedule_select (plugin);
2076 }
2077
2078
2079 static int
2080 setup_sockets (struct Plugin *plugin, struct sockaddr_in6 *serverAddrv6, struct sockaddr_in *serverAddrv4)
2081 {
2082   int tries;
2083   int sockets_created = 0;
2084   struct sockaddr *serverAddr;
2085   struct sockaddr *addrs[2];
2086   socklen_t addrlens[2];
2087   socklen_t addrlen;
2088
2089   /* Create IPv6 socket */
2090   if (plugin->enable_ipv6 == GNUNET_YES)
2091   {
2092     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
2093     if (NULL == plugin->sockv6)
2094     {
2095       LOG (GNUNET_ERROR_TYPE_WARNING, "Disabling IPv6 since it is not supported on this system!\n");
2096       plugin->enable_ipv6 = GNUNET_NO;
2097     }
2098     else
2099     {
2100 #if HAVE_SOCKADDR_IN_SIN_LEN
2101       serverAddrv6->sin6_len = sizeof (serverAddrv6);
2102 #endif
2103       serverAddrv6->sin6_family = AF_INET6;
2104       serverAddrv6->sin6_addr = in6addr_any;
2105       serverAddrv6->sin6_port = htons (plugin->port);
2106       addrlen = sizeof (struct sockaddr_in6);
2107       serverAddr = (struct sockaddr *) serverAddrv6;
2108       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
2109            ntohs (serverAddrv6->sin6_port));
2110       tries = 0;
2111       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
2112              GNUNET_OK)
2113       {
2114         serverAddrv6->sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
2115         LOG (GNUNET_ERROR_TYPE_DEBUG,
2116              "IPv6 Binding failed, trying new port %d\n",
2117              ntohs (serverAddrv6->sin6_port));
2118         tries++;
2119         if (tries > 10)
2120         {
2121           GNUNET_NETWORK_socket_close (plugin->sockv6);
2122           plugin->sockv6 = NULL;
2123           break;
2124         }
2125       }
2126       if (plugin->sockv6 != NULL)
2127       {
2128         LOG (GNUNET_ERROR_TYPE_DEBUG,
2129              "IPv6 socket created on port %d\n",
2130              ntohs (serverAddrv6->sin6_port));
2131         addrs[sockets_created] = (struct sockaddr *) serverAddrv6;
2132         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
2133         sockets_created++;
2134       }
2135     }
2136   }
2137
2138   /* Create IPv4 socket */
2139   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
2140   if (NULL == plugin->sockv4)
2141   {
2142     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
2143   }
2144   else
2145   {
2146 #if HAVE_SOCKADDR_IN_SIN_LEN
2147     serverAddrv4->sin_len = sizeof (serverAddrv4);
2148 #endif
2149     serverAddrv4->sin_family = AF_INET;
2150     serverAddrv4->sin_addr.s_addr = INADDR_ANY;
2151     serverAddrv4->sin_port = htons (plugin->port);
2152     addrlen = sizeof (struct sockaddr_in);
2153     serverAddr = (struct sockaddr *) serverAddrv4;
2154
2155     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
2156          ntohs (serverAddrv4->sin_port));
2157     tries = 0;
2158     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
2159            GNUNET_OK)
2160     {
2161       serverAddrv4->sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
2162       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
2163            ntohs (serverAddrv4->sin_port));
2164       tries++;
2165       if (tries > 10)
2166       {
2167         GNUNET_NETWORK_socket_close (plugin->sockv4);
2168         plugin->sockv4 = NULL;
2169         break;
2170       }
2171     }
2172     if (plugin->sockv4 != NULL)
2173     {
2174       addrs[sockets_created] = (struct sockaddr *) serverAddrv4;
2175       addrlens[sockets_created] = sizeof (struct sockaddr_in);
2176       sockets_created++;
2177     }
2178   }
2179
2180   /* Create file descriptors */
2181   plugin->rs_v4 = GNUNET_NETWORK_fdset_create ();
2182   plugin->ws_v4 = GNUNET_NETWORK_fdset_create ();
2183   GNUNET_NETWORK_fdset_zero (plugin->rs_v4);
2184   GNUNET_NETWORK_fdset_zero (plugin->ws_v4);
2185   if (NULL != plugin->sockv4)
2186   {
2187     GNUNET_NETWORK_fdset_set (plugin->rs_v4, plugin->sockv4);
2188     GNUNET_NETWORK_fdset_set (plugin->ws_v4, plugin->sockv4);
2189   }
2190
2191   if (0 == sockets_created)
2192     LOG (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
2193   if (plugin->enable_ipv6 == GNUNET_YES)
2194   {
2195     plugin->rs_v6 = GNUNET_NETWORK_fdset_create ();
2196     plugin->ws_v6 = GNUNET_NETWORK_fdset_create ();
2197     GNUNET_NETWORK_fdset_zero (plugin->rs_v6);
2198     GNUNET_NETWORK_fdset_zero (plugin->ws_v6);
2199     if (NULL != plugin->sockv6)
2200     {
2201       GNUNET_NETWORK_fdset_set (plugin->rs_v6, plugin->sockv6);
2202       GNUNET_NETWORK_fdset_set (plugin->ws_v6, plugin->sockv6);
2203     }
2204   }
2205   schedule_select (plugin);
2206   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2207                            GNUNET_NO, plugin->port,
2208                            sockets_created,
2209                            (const struct sockaddr **) addrs, addrlens,
2210                            &udp_nat_port_map_callback, NULL, plugin);
2211
2212   return sockets_created;
2213 }
2214
2215
2216 /**
2217  * The exported method. Makes the core api available via a global and
2218  * returns the udp transport API.
2219  *
2220  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2221  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
2222  */
2223 void *
2224 libgnunet_plugin_transport_udp_init (void *cls)
2225 {
2226   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2227   struct GNUNET_TRANSPORT_PluginFunctions *api;
2228   struct Plugin *p;
2229   unsigned long long port;
2230   unsigned long long aport;
2231   unsigned long long broadcast;
2232   unsigned long long udp_max_bps;
2233   unsigned long long enable_v6;
2234   char * bind4_address;
2235   char * bind6_address;
2236   char * fancy_interval;
2237   struct GNUNET_TIME_Relative interval;
2238   struct sockaddr_in serverAddrv4;
2239   struct sockaddr_in6 serverAddrv6;
2240   int res;
2241
2242   if (NULL == env->receive)
2243   {
2244     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2245        initialze the plugin or the API */
2246     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2247     api->cls = NULL;
2248     api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2249     api->address_to_string = &udp_address_to_string;
2250     api->string_to_address = &udp_string_to_address;
2251     return api;
2252   }
2253
2254   GNUNET_assert( NULL != env->stats);
2255
2256   /* Get port number */
2257   if (GNUNET_OK !=
2258       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
2259                                              &port))
2260     port = 2086;
2261   if (GNUNET_OK !=
2262       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2263                                              "ADVERTISED_PORT", &aport))
2264     aport = port;
2265   if (port > 65535)
2266   {
2267     LOG (GNUNET_ERROR_TYPE_WARNING,
2268          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
2269          65535);
2270     return NULL;
2271   }
2272
2273   /* Protocols */
2274   if ((GNUNET_YES ==
2275        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
2276                                              "DISABLEV6")))
2277   {
2278     enable_v6 = GNUNET_NO;
2279   }
2280   else
2281     enable_v6 = GNUNET_YES;
2282
2283   /* Addresses */
2284   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
2285   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
2286
2287   if (GNUNET_YES ==
2288       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2289                                              "BINDTO", &bind4_address))
2290   {
2291     LOG (GNUNET_ERROR_TYPE_DEBUG,
2292          "Binding udp plugin to specific address: `%s'\n",
2293          bind4_address);
2294     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
2295     {
2296       GNUNET_free (bind4_address);
2297       return NULL;
2298     }
2299   }
2300
2301   if (GNUNET_YES ==
2302       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2303                                              "BINDTO6", &bind6_address))
2304   {
2305     LOG (GNUNET_ERROR_TYPE_DEBUG,
2306          "Binding udp plugin to specific address: `%s'\n",
2307          bind6_address);
2308     if (1 !=
2309         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
2310     {
2311       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
2312            bind6_address);
2313       GNUNET_free_non_null (bind4_address);
2314       GNUNET_free (bind6_address);
2315       return NULL;
2316     }
2317   }
2318
2319   /* Enable neighbour discovery */
2320   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
2321                                             "BROADCAST");
2322   if (broadcast == GNUNET_SYSERR)
2323     broadcast = GNUNET_NO;
2324
2325   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2326                                            "BROADCAST_INTERVAL", &fancy_interval))
2327   {
2328     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
2329   }
2330   else
2331   {
2332      if (GNUNET_SYSERR == GNUNET_STRINGS_fancy_time_to_relative(fancy_interval, &interval))
2333      {
2334        interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30);
2335      }
2336      GNUNET_free (fancy_interval);
2337   }
2338
2339   /* Maximum datarate */
2340   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2341                                              "MAX_BPS", &udp_max_bps))
2342   {
2343     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
2344   }
2345
2346   p = GNUNET_malloc (sizeof (struct Plugin));
2347   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2348
2349   GNUNET_BANDWIDTH_tracker_init (&p->tracker,
2350                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
2351   p->sessions = GNUNET_CONTAINER_multihashmap_create (10);
2352   p->defrag_ctxs = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2353   p->mst = GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, p);
2354   p->port = port;
2355   p->aport = aport;
2356   p->broadcast_interval = interval;
2357   p->enable_ipv6 = enable_v6;
2358   p->env = env;
2359
2360   plugin = p;
2361
2362   api->cls = p;
2363   api->send = NULL;
2364   api->disconnect = &udp_disconnect;
2365   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2366   api->address_to_string = &udp_address_to_string;
2367   api->string_to_address = &udp_string_to_address;
2368   api->check_address = &udp_plugin_check_address;
2369   api->get_session = &udp_plugin_get_session;
2370   api->send = &udp_plugin_send;
2371
2372   LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting up sockets\n");
2373   res = setup_sockets (p, &serverAddrv6, &serverAddrv4);
2374   if ((res == 0) || ((p->sockv4 == NULL) && (p->sockv6 == NULL)))
2375   {
2376     LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to create network sockets, plugin failed\n");
2377     GNUNET_free (p);
2378     GNUNET_free (api);
2379     return NULL;
2380   }
2381
2382   if (broadcast == GNUNET_YES)
2383   {
2384     LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting broadcasting\n");
2385     setup_broadcast (p, &serverAddrv6, &serverAddrv4);
2386   }
2387
2388   GNUNET_free_non_null (bind4_address);
2389   GNUNET_free_non_null (bind6_address);
2390   return api;
2391 }
2392
2393
2394 static int
2395 heap_cleanup_iterator (void *cls,
2396                        struct GNUNET_CONTAINER_HeapNode *
2397                        node, void *element,
2398                        GNUNET_CONTAINER_HeapCostType
2399                        cost)
2400 {
2401   struct DefragContext * d_ctx = element;
2402
2403   GNUNET_CONTAINER_heap_remove_node (node);
2404   GNUNET_DEFRAGMENT_context_destroy(d_ctx->defrag);
2405   GNUNET_free (d_ctx);
2406
2407   return GNUNET_YES;
2408 }
2409
2410
2411 /**
2412  * The exported method. Makes the core api available via a global and
2413  * returns the udp transport API.
2414  *
2415  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2416  * @return NULL
2417  */
2418 void *
2419 libgnunet_plugin_transport_udp_done (void *cls)
2420 {
2421   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2422   struct Plugin *plugin = api->cls;
2423
2424   if (NULL == plugin)
2425   {
2426     GNUNET_free (api);
2427     return NULL;
2428   }
2429
2430   stop_broadcast (plugin);
2431   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
2432   {
2433     GNUNET_SCHEDULER_cancel (plugin->select_task);
2434     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2435   }
2436   if (plugin->select_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2437   {
2438     GNUNET_SCHEDULER_cancel (plugin->select_task_v6);
2439     plugin->select_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2440   }
2441
2442   /* Closing sockets */
2443   if (plugin->sockv4 != NULL)
2444   {
2445     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
2446     plugin->sockv4 = NULL;
2447   }
2448   GNUNET_NETWORK_fdset_destroy (plugin->rs_v4);
2449   GNUNET_NETWORK_fdset_destroy (plugin->ws_v4);
2450
2451   if (plugin->sockv6 != NULL)
2452   {
2453     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
2454     plugin->sockv6 = NULL;
2455
2456     GNUNET_NETWORK_fdset_destroy (plugin->rs_v6);
2457     GNUNET_NETWORK_fdset_destroy (plugin->ws_v6);
2458   }
2459
2460   GNUNET_NAT_unregister (plugin->nat);
2461
2462   if (plugin->defrag_ctxs != NULL)
2463   {
2464     GNUNET_CONTAINER_heap_iterate(plugin->defrag_ctxs,
2465         heap_cleanup_iterator, NULL);
2466     GNUNET_CONTAINER_heap_destroy(plugin->defrag_ctxs);
2467     plugin->defrag_ctxs = NULL;
2468   }
2469   if (plugin->mst != NULL)
2470   {
2471     GNUNET_SERVER_mst_destroy(plugin->mst);
2472     plugin->mst = NULL;
2473   }
2474
2475   /* Clean up leftover messages */
2476   struct UDPMessageWrapper * udpw;
2477   udpw = plugin->ipv4_queue_head;
2478   while (udpw != NULL)
2479   {
2480     struct UDPMessageWrapper *tmp = udpw->next;
2481     GNUNET_CONTAINER_DLL_remove(plugin->ipv4_queue_head, plugin->ipv4_queue_tail, udpw);
2482     call_continuation(udpw, GNUNET_SYSERR);
2483     GNUNET_free (udpw);
2484     udpw = tmp;
2485   }
2486   udpw = plugin->ipv6_queue_head;
2487   while (udpw != NULL)
2488   {
2489     struct UDPMessageWrapper *tmp = udpw->next;
2490     GNUNET_CONTAINER_DLL_remove(plugin->ipv6_queue_head, plugin->ipv6_queue_tail, udpw);
2491     call_continuation(udpw, GNUNET_SYSERR);
2492     GNUNET_free (udpw);
2493     udpw = tmp;
2494   }
2495
2496   /* Clean up sessions */
2497   LOG (GNUNET_ERROR_TYPE_DEBUG,
2498        "Cleaning up sessions\n");
2499   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
2500   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
2501
2502   plugin->nat = NULL;
2503   GNUNET_free (plugin);
2504   GNUNET_free (api);
2505   return NULL;
2506 }
2507
2508
2509 /* end of plugin_transport_udp.c */