removing ats functions from plugins, instead provide callback function
[oweals/gnunet.git] / src / transport / plugin_transport_udp_new.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 NAT punching
24  *        transport service
25  * @author Christian Grothoff
26  * @author Nathan Evans
27  */
28 #include "platform.h"
29 #include "gnunet_hello_lib.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_fragmentation_lib.h"
32 #include "gnunet_nat_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_resolver_service.h"
35 #include "gnunet_signatures.h"
36 #include "gnunet_constants.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
41
42 #define LOG(kind,...) GNUNET_log_from (kind, "transport-udp", __VA_ARGS__)
43
44
45 #define DEBUG_UDP GNUNET_EXTRA_LOGGING
46
47 /**
48  * MTU for fragmentation subsystem.  Should be conservative since
49  * all communicating peers MUST work with this MTU.
50  */
51 #define UDP_MTU 1400
52
53 /**
54  * Number of messages we can defragment in parallel.  We only really
55  * defragment 1 message at a time, but if messages get re-ordered, we
56  * may want to keep knowledge about the previous message to avoid
57  * discarding the current message in favor of a single fragment of a
58  * previous message.  3 should be good since we don't expect massive
59  * message reorderings with UDP.
60  */
61 #define UDP_MAX_MESSAGES_IN_DEFRAG 3
62
63 /**
64  * We keep a defragmentation queue per sender address.  How many
65  * sender addresses do we support at the same time? Memory consumption
66  * is roughly a factor of 32k * UDP_MAX_MESSAGES_IN_DEFRAG times this
67  * value. (So 128 corresponds to 12 MB and should suffice for
68  * connecting to roughly 128 peers via UDP).
69  */
70 #define UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG 128
71
72
73 /**
74  * UDP Message-Packet header (after defragmentation).
75  */
76 struct UDPMessage
77 {
78   /**
79    * Message header.
80    */
81   struct GNUNET_MessageHeader header;
82
83   /**
84    * Always zero for now.
85    */
86   uint32_t reserved;
87
88   /**
89    * What is the identity of the sender
90    */
91   struct GNUNET_PeerIdentity sender;
92
93 };
94
95
96 /**
97  * UDP ACK Message-Packet header (after defragmentation).
98  */
99 struct UDP_ACK_Message
100 {
101   /**
102    * Message header.
103    */
104   struct GNUNET_MessageHeader header;
105
106   /**
107    * Desired delay for flow control
108    */
109   uint32_t delay;
110
111   /**
112    * What is the identity of the sender
113    */
114   struct GNUNET_PeerIdentity sender;
115 };
116
117
118 /**
119  * Network format for IPv4 addresses.
120  */
121 struct IPv4UdpAddress
122 {
123   /**
124    * IPv4 address, in network byte order.
125    */
126   uint32_t ipv4_addr GNUNET_PACKED;
127
128   /**
129    * Port number, in network byte order.
130    */
131   uint16_t u4_port GNUNET_PACKED;
132 };
133
134
135 /**
136  * Network format for IPv6 addresses.
137  */
138 struct IPv6UdpAddress
139 {
140
141   /**
142    * IPv6 address.
143    */
144   struct in6_addr ipv6_addr GNUNET_PACKED;
145
146   /**
147    * Port number, in network byte order.
148    */
149   uint16_t u6_port GNUNET_PACKED;
150 };
151
152
153 /* Forward definition */
154 struct Plugin;
155
156
157 /**
158  * Session with another peer.  FIXME: why not make this into
159  * a regular 'struct Session' and pass it around!?
160  */
161 struct Session
162 {
163
164   /**
165    * Which peer is this session for or from?
166    */
167   struct GNUNET_PeerIdentity target;
168
169   /**
170    * Pointer to the global plugin struct.
171    */
172   struct Plugin *plugin;
173
174   /**
175    * Address of the other peer
176    */
177   const struct sockaddr *sock_addr;
178
179   size_t addrlen;
180
181   /**
182    * Function to call upon completion of the transmission.
183    */
184   GNUNET_TRANSPORT_TransmitContinuation cont;
185
186   /**
187    * Closure for 'cont'.
188    */
189   void *cont_cls;
190
191   /**
192    * Current outgoing message to this peer.
193    */
194   struct GNUNET_FRAGMENT_Context *frag;
195
196   /*
197    * Is this a reliable, bidirectional connection?
198    * YES if we already received a message with this session
199    */
200   int bidirectional;
201
202   /*
203    * Task invalidating this session if idle
204    */
205   GNUNET_SCHEDULER_TaskIdentifier invalidation_task;
206
207   /*
208    * Desired delay for next sending we send to other peer
209    */
210   struct GNUNET_TIME_Relative flow_delay_for_other_peer;
211
212   /*
213    * Desired delay for next sending we received from other peer
214    */
215   struct GNUNET_TIME_Absolute flow_delay_from_other_peer;
216 };
217
218 /**
219  * Encapsulation of all of the state of the plugin.
220  */
221 struct Plugin
222 {
223
224   /**
225    * Our environment.
226    */
227   struct GNUNET_TRANSPORT_PluginEnvironment *env;
228
229   /**
230    * Session of peers with whom we are currently connected,
231    * map of peer identity to 'struct PeerSession'.
232    */
233   struct GNUNET_CONTAINER_MultiHashMap *sessions;
234
235   /**
236    * Heap with all of our defragmentation activities.
237    */
238   struct GNUNET_CONTAINER_Heap *defrags;
239
240   /**
241    * ID of select task
242    */
243   GNUNET_SCHEDULER_TaskIdentifier select_task;
244
245   /**
246    * Tokenizer for inbound messages.
247    */
248   struct GNUNET_SERVER_MessageStreamTokenizer *mst;
249
250   /**
251    * Bandwidth tracker to limit global UDP traffic.
252    */
253   struct GNUNET_BANDWIDTH_Tracker tracker;
254
255   /**
256    * Address we were told to bind to exclusively (IPv4).
257    */
258   char *bind4_address;
259
260   /**
261    * Address we were told to bind to exclusively (IPv6).
262    */
263   char *bind6_address;
264
265   /**
266    * Handle to NAT traversal support.
267    */
268   struct GNUNET_NAT_Handle *nat;
269
270   /**
271    * FD Read set
272    */
273   struct GNUNET_NETWORK_FDSet *rs;
274
275   /**
276    * The read socket for IPv4
277    */
278   struct GNUNET_NETWORK_Handle *sockv4;
279
280   /**
281    * The read socket for IPv6
282    */
283   struct GNUNET_NETWORK_Handle *sockv6;
284
285   /**
286    * expected delay for ACKs
287    */
288   struct GNUNET_TIME_Relative last_expected_delay;
289
290   /**
291    * Port we listen on.
292    */
293   uint16_t port;
294
295   /**
296    * Port we advertise on.
297    */
298   uint16_t aport;
299
300 };
301
302 int
303 delete_session_iterator (void *cls, const GNUNET_HashCode * key, void *value)
304 {
305   struct Session *s = (struct Session *) value;
306
307   if (s->invalidation_task != GNUNET_SCHEDULER_NO_TASK)
308   {
309     GNUNET_SCHEDULER_cancel (s->invalidation_task);
310     s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
311   }
312   GNUNET_CONTAINER_multihashmap_remove (s->plugin->sessions, key, s);
313
314   GNUNET_free (s);
315   return GNUNET_YES;
316 }
317
318 /**
319  * Disconnect from a remote node.  Clean up session if we have one for this peer
320  *
321  * @param cls closure for this call (should be handle to Plugin)
322  * @param target the peeridentity of the peer to disconnect
323  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
324  */
325 static void
326 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
327 {
328   struct Plugin *plugin = cls;
329
330   GNUNET_CONTAINER_multihashmap_get_multiple (plugin, &target->hashPubKey,
331                                               &delete_session_iterator, NULL);
332
333 }
334
335
336 /**
337  * Actually send out the message.
338  *
339  * @param plugin the plugin
340  * @param sa the address to send the message to
341  * @param msg message to transmit
342  * @return the number of bytes written
343  */
344 static ssize_t
345 udp_send (struct Plugin *plugin, const struct sockaddr *sa,
346           const struct GNUNET_MessageHeader *msg)
347 {
348   ssize_t sent;
349   size_t slen;
350
351   switch (sa->sa_family)
352   {
353   case AF_INET:
354     if (NULL == plugin->sockv4)
355       return 0;
356     sent =
357         GNUNET_NETWORK_socket_sendto (plugin->sockv4, msg, ntohs (msg->size),
358                                       sa, slen = sizeof (struct sockaddr_in));
359     break;
360   case AF_INET6:
361     if (NULL == plugin->sockv6)
362       return 0;
363     sent =
364         GNUNET_NETWORK_socket_sendto (plugin->sockv6, msg, ntohs (msg->size),
365                                       sa, slen = sizeof (struct sockaddr_in6));
366     break;
367   default:
368     GNUNET_break (0);
369     return 0;
370   }
371   if (GNUNET_SYSERR == sent)
372   {
373     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
374     LOG (GNUNET_ERROR_TYPE_ERROR,
375          "UDP transmited %u-byte message to %s (%d: %s)\n",
376          (unsigned int) ntohs (msg->size), GNUNET_a2s (sa, slen), (int) sent,
377          (sent < 0) ? STRERROR (errno) : "ok");
378
379   }
380   LOG (GNUNET_ERROR_TYPE_DEBUG,
381        "UDP transmited %u-byte message to %s (%d: %s)\n",
382        (unsigned int) ntohs (msg->size), GNUNET_a2s (sa, slen), (int) sent,
383        (sent < 0) ? STRERROR (errno) : "ok");
384   return sent;
385 }
386
387
388 static struct Session *
389 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
390                 const void *addr, size_t addrlen,
391                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
392 {
393   struct Session *s;
394   const struct IPv4UdpAddress *t4;
395   const struct IPv6UdpAddress *t6;
396   struct sockaddr_in *v4;
397   struct sockaddr_in6 *v6;
398   size_t len;
399
400   switch (addrlen)
401   {
402   case sizeof (struct IPv4UdpAddress):
403     if (NULL == plugin->sockv4)
404     {
405       return NULL;
406     }
407     t4 = addr;
408     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
409     len = sizeof (struct sockaddr_in);
410     v4 = (struct sockaddr_in *) &s[1];
411     v4->sin_family = AF_INET;
412 #if HAVE_SOCKADDR_IN_SIN_LEN
413     v4->sin_len = sizeof (struct sockaddr_in);
414 #endif
415     v4->sin_port = t4->u4_port;
416     v4->sin_addr.s_addr = t4->ipv4_addr;
417     break;
418   case sizeof (struct IPv6UdpAddress):
419     if (NULL == plugin->sockv6)
420     {
421       return NULL;
422     }
423     t6 = addr;
424     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
425     len = sizeof (struct sockaddr_in6);
426     v6 = (struct sockaddr_in6 *) &s[1];
427     v6->sin6_family = AF_INET6;
428 #if HAVE_SOCKADDR_IN_SIN_LEN
429     v6->sin6_len = sizeof (struct sockaddr_in6);
430 #endif
431     v6->sin6_port = t6->u6_port;
432     v6->sin6_addr = t6->ipv6_addr;
433     break;
434   default:
435     /* Must have a valid address to send to */
436     GNUNET_break_op (0);
437     return NULL;
438   }
439
440   s->valid_until = GNUNET_TIME_absolute_get_zero ();
441   s->flow_delay_for_other_peer = GNUNET_TIME_relative_get_zero ();
442   s->flow_delay_from_other_peer = GNUNET_TIME_absolute_get_zero ();
443   s->bidirectional = GNUNET_NO;
444   s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
445   s->addrlen = len;
446   s->target = *target;
447   s->plugin = plugin;
448   s->sock_addr = (const struct sockaddr *) &s[1];
449   s->cont = cont;
450   s->cont_cls = cont_cls;
451
452   return s;
453 }
454
455 static void
456 invalidation_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
457 {
458   struct Session *s = cls;
459
460   s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
461   LOG (GNUNET_ERROR_TYPE_ERROR, "Session %X (`%s') is now invalid\n", s,
462        GNUNET_a2s (s->sock_addr, s->addrlen));
463
464   s->plugin->env->session_end (s->plugin->env->cls, &s->target, s);
465   GNUNET_assert (GNUNET_YES ==
466                  GNUNET_CONTAINER_multihashmap_remove (s->plugin->sessions,
467                                                        &s->target.hashPubKey,
468                                                        s));
469   GNUNET_free (s);
470 }
471
472 static const char *
473 udp_address_to_string (void *cls, const void *addr, size_t addrlen);
474
475 /**
476  * Function that is called with messages created by the fragmentation
477  * module.  In the case of the 'proc' callback of the
478  * GNUNET_FRAGMENT_context_create function, this function must
479  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
480  *
481  * @param cls closure, the 'struct PeerSession'
482  * @param msg the message that was created
483  */
484 static void
485 send_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
486 {
487   struct Session *s = cls;
488
489   udp_send (session->plugin, session->sock_addr, msg);
490   GNUNET_FRAGMENT_context_transmission_done (session->frag);
491 }
492
493 /**
494  * Function that can be used by the transport service to transmit
495  * a message using the plugin.
496  *
497  * @param cls closure
498  * @param target who should receive this message (ignored by UDP)
499  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
500  * @param msgbuf_size the size of the msgbuf to send
501  * @param priority how important is the message (ignored by UDP)
502  * @param timeout when should we time out (give up) if we can not transmit?
503  * @param session identifier used for this session (NULL for UDP)
504  * @param addr the addr to send the message to
505  * @param addrlen the len of addr
506  * @param force_address not used, we had better have an address to send to
507  *        because we are stateless!!
508  * @param cont continuation to call once the message has
509  *        been transmitted (or if the transport is ready
510  *        for the next transmission call; or if the
511  *        peer disconnected...)
512  * @param cont_cls closure for cont
513  *
514  * @return the number of bytes written (may return 0 and the message can
515  *         still be transmitted later!)
516  */
517 static ssize_t
518 udp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
519                  const char *msgbuf, size_t msgbuf_size, unsigned int priority,
520                  struct GNUNET_TIME_Relative timeout, struct Session *session,
521                  const void *addr, size_t addrlen, int force_address,
522                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
523 {
524   struct Plugin *plugin = cls;
525   struct Session *s;
526   const struct IPv4UdpAddress *t4;
527   const struct IPv6UdpAddress *t6;
528   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
529   char mbuf[mlen];
530   struct UDPMessage *udp;
531
532   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
533   {
534     GNUNET_break (0);
535     return GNUNET_SYSERR;
536   }
537
538   LOG (GNUNET_ERROR_TYPE_DEBUG,
539        "UDP transmits %u-byte message to `%s' using address `%s' session 0x%X mode %i\n",
540        msgbuf_size, GNUNET_i2s (target), udp_address_to_string (NULL, addr,
541                                                                 addrlen),
542        session, force_address);
543
544   /* no valid address given */
545   if ((addr = NULL) || (addrlen == 0))
546   {
547     GNUNET_break (0);
548     return GNUNET_SYSERR;
549   }
550
551   if (session != NULL)
552   {
553     s = find_session (target, addr, addrlen);
554     if (s != session)
555     {
556       /* found a conflicting session for this peer */
557       GNUNET_break (0);
558       return GNUNET_SYSERR;
559     }
560   }
561   else
562   {
563     /* use a reliable transmission but no session given */
564     if (force_address == GNUNET_SYSERR)
565       return GNUNET_SYSERR;
566     /* create new session */
567     s = create_session (plugin, target, addr, addrlen, cont, cont_cls);
568     GNUNET_CONTAINER_multihashmap_put (plugin->sessions, &target->hashPubKey, s,
569                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
570     /* schedule invalidation task */
571     s->invalidation_task =
572         GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
573                                       &invalidation_task, NULL);
574   }
575
576   /* Message */
577   udp = (struct UDPMessage *) mbuf;
578   udp->header.size = htons (mlen);
579   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
580   udp->reserved = htonl (0);
581   udp->sender = *plugin->env->my_identity;
582   memcpy (&udp[1], msgbuf, msgbuf_size);
583
584   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
585
586   if (s->flow_delay_from_other_peer.abs_value > now.abs_value)
587   {
588     struct GNUNET_TIME_Relative delta =
589         GNUNET_TIME_absolute_get_difference (now,
590                                              s->flow_delay_from_other_peer);
591
592     LOG (GNUNET_ERROR_TYPE_DEBUG, "We try to send to early! Should in %llu!\n",
593          delta.rel_value);
594   }
595   else
596     LOG (GNUNET_ERROR_TYPE_DEBUG, "We can send!\n");
597
598
599   /* send without fragmentation */
600   if (mlen <= UDP_MTU)
601   {
602     mlen = udp_send (plugin, peer_session->sock_addr, &udp->header);
603     if (cont != NULL)
604       cont (cont_cls, target, (mlen > 0) ? GNUNET_OK : GNUNET_SYSERR);
605     GNUNET_free_non_null (peer_session);
606   }
607   /* send with fragmentation */
608   else
609   {
610     s->frag =
611         GNUNET_FRAGMENT_context_create (plugin->env->stats, UDP_MTU,
612                                         &plugin->tracker,
613                                         plugin->last_expected_delay,
614                                         &udp->header, &send_fragment, s);
615   }
616   return mlen;
617 }
618
619
620 /**
621  * Message tokenizer has broken up an incomming message. Pass it on
622  * to the service.
623  *
624  * @param cls the 'struct Plugin'
625  * @param client the Session
626  * @param hdr the actual message
627  */
628 static void
629 process_inbound_tokenized_messages (void *cls, void *client,
630                                     const struct GNUNET_MessageHeader *hdr)
631 {
632   struct Plugin *plugin = cls;
633   struct Session *s = client;
634   struct GNUNET_ATS_Information distance;
635   struct GNUNET_TIME_Relative delay;
636
637   /* setup ATS */
638   distance.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
639   distance.value = htonl (1);
640
641   LOG (GNUNET_ERROR_TYPE_DEBUG, "Giving Session %X %s  to transport\n",
642        s->session, GNUNET_i2s (&s->target));
643   delay =
644       plugin->env->receive (plugin->env->cls, &s->target, hdr, &distance, 1, s,
645                             // FIXME: USE UDP ADDRESSES!!!!
646                             s->sock_addr, s->addrlen);
647   s->flow_delay_for_other_peer = delay;
648 }
649
650
651 /**
652  * We've received a UDP Message.  Process it (pass contents to main service).
653  *
654  * @param plugin plugin context
655  * @param msg the message
656  * @param sender_addr sender address
657  * @param sender_addr_len number of bytes in sender_addr
658  */
659 static void
660 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
661                      const struct sockaddr *sender_addr,
662                      socklen_t sender_addr_len)
663 {
664   struct IPv4UdpAddress u4;
665   struct IPv6UdpAddress u6;
666   const void *arg;
667   size_t args;
668
669   if (0 != ntohl (msg->reserved))
670   {
671     GNUNET_break_op (0);
672     return;
673   }
674   if (ntohs (msg->header.size) <
675       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
676   {
677     GNUNET_break_op (0);
678     return;
679   }
680
681   /* convert address */
682   switch (sender_addr->sa_family)
683   {
684   case AF_INET:
685     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
686     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
687     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
688     arg = &u4;
689     args = sizeof (u4);
690     break;
691   case AF_INET6:
692     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
693     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
694     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
695     arg = &u6;
696     args = sizeof (u6);
697     break;
698   default:
699     GNUNET_break (0);
700     return;
701   }
702 #if DEBUG_UDP
703   LOG (GNUNET_ERROR_TYPE_DEBUG,
704        "Received message with %u bytes from peer `%s' at `%s'\n",
705        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
706        GNUNET_a2s (sender_addr, sender_addr_len));
707 #endif
708
709   const struct UDPMessage *udp_msg = (const struct UDPMessage *) msg;
710
711   LOG (GNUNET_ERROR_TYPE_DEBUG,
712        "Lookup inbound UDP sessions for peer `%s' address `%s'\n",
713        GNUNET_i2s (&udp_msg->sender), udp_address_to_string (NULL, arg, args));
714
715   /* create a session for inbound connections */
716   struct Session *s = NULL;
717
718   s = find_inbound_session (plugin, &udp_msg->sender, sender_addr,
719                             sender_addr_len);
720
721   if (s != NULL)
722   {
723     LOG (GNUNET_ERROR_TYPE_DEBUG,
724          "Found existing inbound UDP sessions 0x%X for peer `%s' address `%s'\n",
725          s, GNUNET_i2s (&s->target), udp_address_to_string (NULL, arg, args));
726   }
727   else
728   {
729     s = create_session (plugin, &udp_msg->sender, arg, args, NULL, NULL);
730     LOG (GNUNET_ERROR_TYPE_DEBUG,
731          "Creating inbound UDP sessions 0x%X for peer `%s' address `%s'\n", s,
732          GNUNET_i2s (&s->target), udp_address_to_string (NULL, arg, args));
733
734     GNUNET_assert (GNUNET_OK ==
735                    GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
736                                                       &s->target.hashPubKey, s,
737                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
738   }
739   s->valid_until =
740       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
741                                 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
742   if (s->invalidation_task != GNUNET_SCHEDULER_NO_TASK)
743   {
744     GNUNET_SCHEDULER_cancel (s->invalidation_task);
745     s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
746     LOG (GNUNET_ERROR_TYPE_DEBUG, "Rescheduling %X' `%s'\n", s,
747          udp_address_to_string (NULL, arg, args));
748   }
749   s->invalidation_task =
750       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
751                                     &invalidation_task, s);
752   /* we received from peer, so session is bidirectional and reliable */
753   s->bidirectional = GNUNET_YES;
754
755   GNUNET_SERVER_mst_receive (plugin->mst, &s, (const char *) &msg[1],
756                              ntohs (msg->header.size) -
757                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
758 }
759
760
761 /**
762  * Read and process a message from the given socket.
763  *
764  * @param plugin the overall plugin
765  * @param rsock socket to read from
766  */
767 static void
768 udp_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
769 {
770   socklen_t fromlen;
771   char addr[32];
772   char buf[65536];
773   ssize_t ret;
774   const struct GNUNET_MessageHeader *msg;
775   const struct GNUNET_MessageHeader *ack;
776   struct Session *peer_session;
777   const struct UDP_ACK_Message *udp_ack;
778   struct ReceiveContext *rc;
779   struct GNUNET_TIME_Absolute now;
780   struct FindReceiveContext frc;
781   struct Session *s = NULL;
782   struct GNUNET_TIME_Relative flow_delay;
783
784   fromlen = sizeof (addr);
785   memset (&addr, 0, sizeof (addr));
786   ret =
787       GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
788                                       (struct sockaddr *) &addr, &fromlen);
789   if (ret < sizeof (struct GNUNET_MessageHeader))
790   {
791     GNUNET_break_op (0);
792     return;
793   }
794   msg = (const struct GNUNET_MessageHeader *) buf;
795
796   LOG (GNUNET_ERROR_TYPE_DEBUG,
797        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) ret,
798        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
799
800   if (ret != ntohs (msg->size))
801   {
802     GNUNET_break_op (0);
803     return;
804   }
805
806   switch (ntohs (msg->type))
807   {
808   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
809     if (ntohs (msg->size) < sizeof (struct UDPMessage))
810     {
811       GNUNET_break_op (0);
812       return;
813     }
814     process_udp_message (plugin, (const struct UDPMessage *) msg,
815                          (const struct sockaddr *) addr, fromlen);
816     return;
817
818   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
819     if (ntohs (msg->size) <
820         sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
821     {
822       GNUNET_break_op (0);
823       return;
824     }
825     udp_ack = (const struct UDP_ACK_Message *) msg;
826     LOG (GNUNET_ERROR_TYPE_DEBUG,
827          "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
828          (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp->sender),
829          GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
830
831     // TODO Guess a session from address, give it defragmenter and check in process_udp if guess was right
832     s = guess_session (plugin->sessions, addr, addrlen);
833     if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (peer_session->frag, ack))
834       // ... other stuff
835       return;
836
837   case GNUNET_MESSAGE_TYPE_FRAGMENT:
838     LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
839          (unsigned int) ntohs (msg->size),
840          GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
841     // TODO Guess a session from address, give it defragmenter and check in process_udp if guess was right
842     s = guess_session (plugin->sessions, addr, addrlen);
843     if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (rc->defrag, msg))
844       // other stuff
845       return;
846   default:
847     GNUNET_break_op (0);
848     return;
849   }
850 }
851
852
853 /**
854  * We have been notified that our writeset has something to read.  We don't
855  * know which socket needs to be read, so we have to check each one
856  * Then reschedule this function to be called again once more is available.
857  *
858  * @param cls the plugin handle
859  * @param tc the scheduling context (for rescheduling this function again)
860  */
861 static void
862 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
863 {
864   struct Plugin *plugin = cls;
865
866   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
867   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
868     return;
869   if ((NULL != plugin->sockv4) &&
870       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
871     udp_read (plugin, plugin->sockv4);
872   if ((NULL != plugin->sockv6) &&
873       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
874     udp_read (plugin, plugin->sockv6);
875   plugin->select_task =
876       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
877                                    GNUNET_SCHEDULER_NO_TASK,
878                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
879                                    NULL, &udp_plugin_select, plugin);
880
881 }
882
883
884 /**
885  * Check if the given port is plausible (must be either our listen
886  * port or our advertised port).  If it is neither, we return
887  * GNUNET_SYSERR.
888  *
889  * @param plugin global variables
890  * @param in_port port number to check
891  * @return GNUNET_OK if port is either open_port or adv_port
892  */
893 static int
894 check_port (struct Plugin *plugin, uint16_t in_port)
895 {
896   if ((in_port == plugin->port) || (in_port == plugin->aport))
897     return GNUNET_OK;
898   return GNUNET_SYSERR;
899 }
900
901
902 /**
903  * Function that will be called to check if a binary address for this
904  * plugin is well-formed and corresponds to an address for THIS peer
905  * (as per our configuration).  Naturally, if absolutely necessary,
906  * plugins can be a bit conservative in their answer, but in general
907  * plugins should make sure that the address does not redirect
908  * traffic to a 3rd party that might try to man-in-the-middle our
909  * traffic.
910  *
911  * @param cls closure, should be our handle to the Plugin
912  * @param addr pointer to the address
913  * @param addrlen length of addr
914  * @return GNUNET_OK if this is a plausible address for this peer
915  *         and transport, GNUNET_SYSERR if not
916  *
917  */
918 static int
919 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
920 {
921   struct Plugin *plugin = cls;
922   struct IPv4UdpAddress *v4;
923   struct IPv6UdpAddress *v6;
924
925   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
926       (addrlen != sizeof (struct IPv6UdpAddress)))
927   {
928     GNUNET_break_op (0);
929     return GNUNET_SYSERR;
930   }
931   if (addrlen == sizeof (struct IPv4UdpAddress))
932   {
933     v4 = (struct IPv4UdpAddress *) addr;
934     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
935       return GNUNET_SYSERR;
936     if (GNUNET_OK !=
937         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
938                                  sizeof (struct in_addr)))
939       return GNUNET_SYSERR;
940   }
941   else
942   {
943     v6 = (struct IPv6UdpAddress *) addr;
944     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
945     {
946       GNUNET_break_op (0);
947       return GNUNET_SYSERR;
948     }
949     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
950       return GNUNET_SYSERR;
951     if (GNUNET_OK !=
952         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
953                                  sizeof (struct in6_addr)))
954       return GNUNET_SYSERR;
955   }
956   return GNUNET_OK;
957 }
958
959
960 /**
961  * Function called for a quick conversion of the binary address to
962  * a numeric address.  Note that the caller must not free the
963  * address and that the next call to this function is allowed
964  * to override the address again.
965  *
966  * @param cls closure
967  * @param addr binary address
968  * @param addrlen length of the address
969  * @return string representing the same address
970  */
971 static const char *
972 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
973 {
974   static char rbuf[INET6_ADDRSTRLEN + 10];
975   char buf[INET6_ADDRSTRLEN];
976   const void *sb;
977   struct in_addr a4;
978   struct in6_addr a6;
979   const struct IPv4UdpAddress *t4;
980   const struct IPv6UdpAddress *t6;
981   int af;
982   uint16_t port;
983
984   if (addrlen == sizeof (struct IPv6UdpAddress))
985   {
986     t6 = addr;
987     af = AF_INET6;
988     port = ntohs (t6->u6_port);
989     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
990     sb = &a6;
991   }
992   else if (addrlen == sizeof (struct IPv4UdpAddress))
993   {
994     t4 = addr;
995     af = AF_INET;
996     port = ntohs (t4->u4_port);
997     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
998     sb = &a4;
999   }
1000   else
1001   {
1002     GNUNET_break_op (0);
1003     return NULL;
1004   }
1005   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
1006   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
1007                    buf, port);
1008   return rbuf;
1009 }
1010
1011
1012 /**
1013  * Closure for 'append_port'.
1014  */
1015 struct PrettyPrinterContext
1016 {
1017   /**
1018    * Function to call with the result.
1019    */
1020   GNUNET_TRANSPORT_AddressStringCallback asc;
1021
1022   /**
1023    * Clsoure for 'asc'.
1024    */
1025   void *asc_cls;
1026
1027   /**
1028    * Port to add after the IP address.
1029    */
1030   uint16_t port;
1031 };
1032
1033
1034 /**
1035  * Append our port and forward the result.
1036  *
1037  * @param cls a 'struct PrettyPrinterContext'
1038  * @param hostname result from DNS resolver
1039  */
1040 static void
1041 append_port (void *cls, const char *hostname)
1042 {
1043   struct PrettyPrinterContext *ppc = cls;
1044   char *ret;
1045
1046   if (hostname == NULL)
1047   {
1048     ppc->asc (ppc->asc_cls, NULL);
1049     GNUNET_free (ppc);
1050     return;
1051   }
1052   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1053   ppc->asc (ppc->asc_cls, ret);
1054   GNUNET_free (ret);
1055 }
1056
1057
1058 /**
1059  * Convert the transports address to a nice, human-readable
1060  * format.
1061  *
1062  * @param cls closure
1063  * @param type name of the transport that generated the address
1064  * @param addr one of the addresses of the host, NULL for the last address
1065  *        the specific address format depends on the transport
1066  * @param addrlen length of the address
1067  * @param numeric should (IP) addresses be displayed in numeric form?
1068  * @param timeout after how long should we give up?
1069  * @param asc function to call on each string
1070  * @param asc_cls closure for asc
1071  */
1072 static void
1073 udp_plugin_address_pretty_printer (void *cls, const char *type,
1074                                    const void *addr, size_t addrlen,
1075                                    int numeric,
1076                                    struct GNUNET_TIME_Relative timeout,
1077                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1078                                    void *asc_cls)
1079 {
1080   struct PrettyPrinterContext *ppc;
1081   const void *sb;
1082   size_t sbs;
1083   struct sockaddr_in a4;
1084   struct sockaddr_in6 a6;
1085   const struct IPv4UdpAddress *u4;
1086   const struct IPv6UdpAddress *u6;
1087   uint16_t port;
1088
1089   if (addrlen == sizeof (struct IPv6UdpAddress))
1090   {
1091     u6 = addr;
1092     memset (&a6, 0, sizeof (a6));
1093     a6.sin6_family = AF_INET6;
1094 #if HAVE_SOCKADDR_IN_SIN_LEN
1095     a6.sin6_len = sizeof (a6);
1096 #endif
1097     a6.sin6_port = u6->u6_port;
1098     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
1099     port = ntohs (u6->u6_port);
1100     sb = &a6;
1101     sbs = sizeof (a6);
1102   }
1103   else if (addrlen == sizeof (struct IPv4UdpAddress))
1104   {
1105     u4 = addr;
1106     memset (&a4, 0, sizeof (a4));
1107     a4.sin_family = AF_INET;
1108 #if HAVE_SOCKADDR_IN_SIN_LEN
1109     a4.sin_len = sizeof (a4);
1110 #endif
1111     a4.sin_port = u4->u4_port;
1112     a4.sin_addr.s_addr = u4->ipv4_addr;
1113     port = ntohs (u4->u4_port);
1114     sb = &a4;
1115     sbs = sizeof (a4);
1116   }
1117   else
1118   {
1119     /* invalid address */
1120     GNUNET_break_op (0);
1121     asc (asc_cls, NULL);
1122     return;
1123   }
1124   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1125   ppc->asc = asc;
1126   ppc->asc_cls = asc_cls;
1127   ppc->port = port;
1128   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1129 }
1130
1131
1132 /**
1133  * Our external IP address/port mapping has changed.
1134  *
1135  * @param cls closure, the 'struct LocalAddrList'
1136  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1137  *     the previous (now invalid) one
1138  * @param addr either the previous or the new public IP address
1139  * @param addrlen actual lenght of the address
1140  */
1141 static void
1142 udp_nat_port_map_callback (void *cls, int add_remove,
1143                            const struct sockaddr *addr, socklen_t addrlen)
1144 {
1145   struct Plugin *plugin = cls;
1146   struct IPv4UdpAddress u4;
1147   struct IPv6UdpAddress u6;
1148   void *arg;
1149   size_t args;
1150
1151   /* convert 'addr' to our internal format */
1152   switch (addr->sa_family)
1153   {
1154   case AF_INET:
1155     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1156     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1157     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1158     arg = &u4;
1159     args = sizeof (u4);
1160     break;
1161   case AF_INET6:
1162     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1163     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1164             sizeof (struct in6_addr));
1165     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1166     arg = &u6;
1167     args = sizeof (u6);
1168     break;
1169   default:
1170     GNUNET_break (0);
1171     return;
1172   }
1173   /* modify our published address list */
1174   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
1175 }
1176
1177
1178 /**
1179  * The exported method. Makes the core api available via a global and
1180  * returns the udp transport API.
1181  *
1182  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1183  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1184  */
1185 void *
1186 libgnunet_plugin_transport_udp_init (void *cls)
1187 {
1188   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1189   unsigned long long port;
1190   unsigned long long aport;
1191   struct GNUNET_TRANSPORT_PluginFunctions *api;
1192   struct Plugin *plugin;
1193   int sockets_created;
1194   struct sockaddr_in serverAddrv4;
1195   struct sockaddr_in6 serverAddrv6;
1196   struct sockaddr *serverAddr;
1197   struct sockaddr *addrs[2];
1198   socklen_t addrlens[2];
1199   socklen_t addrlen;
1200   unsigned int tries;
1201   unsigned long long udp_max_bps;
1202
1203   if (GNUNET_OK !=
1204       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
1205                                              &port))
1206     port = 2086;
1207   if (GNUNET_OK !=
1208       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1209                                              "MAX_BPS", &udp_max_bps))
1210     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1211   if (GNUNET_OK !=
1212       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1213                                              "ADVERTISED_PORT", &aport))
1214     aport = port;
1215   if (port > 65535)
1216   {
1217     LOG (GNUNET_ERROR_TYPE_WARNING,
1218          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
1219          65535);
1220     return NULL;
1221   }
1222   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1223   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1224
1225   plugin = GNUNET_malloc (sizeof (struct Plugin));
1226   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1227                                  GNUNET_BANDWIDTH_value_init ((uint32_t)
1228                                                               udp_max_bps), 30);
1229   plugin->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
1230   plugin->port = port;
1231   plugin->aport = aport;
1232   plugin->env = env;
1233   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1234   api->cls = plugin;
1235
1236   api->send = &udp_plugin_send;
1237   api->disconnect = &udp_disconnect;
1238   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1239   api->address_to_string = &udp_address_to_string;
1240   api->check_address = &udp_plugin_check_address;
1241
1242   if (GNUNET_YES ==
1243       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1244                                              "BINDTO", &plugin->bind4_address))
1245   {
1246     LOG (GNUNET_ERROR_TYPE_DEBUG,
1247          "Binding udp plugin to specific address: `%s'\n",
1248          plugin->bind4_address);
1249     if (1 != inet_pton (AF_INET, plugin->bind4_address, &serverAddrv4.sin_addr))
1250     {
1251       GNUNET_free (plugin->bind4_address);
1252       GNUNET_free (plugin);
1253       GNUNET_free (api);
1254       return NULL;
1255     }
1256   }
1257
1258   if (GNUNET_YES ==
1259       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1260                                              "BINDTO6", &plugin->bind6_address))
1261   {
1262     LOG (GNUNET_ERROR_TYPE_DEBUG,
1263          "Binding udp plugin to specific address: `%s'\n",
1264          plugin->bind6_address);
1265     if (1 !=
1266         inet_pton (AF_INET6, plugin->bind6_address, &serverAddrv6.sin6_addr))
1267     {
1268       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1269            plugin->bind6_address);
1270       GNUNET_free_non_null (plugin->bind4_address);
1271       GNUNET_free (plugin->bind6_address);
1272       GNUNET_free (plugin);
1273       GNUNET_free (api);
1274       return NULL;
1275     }
1276   }
1277
1278   plugin->defrags =
1279       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1280   plugin->sessions =
1281       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
1282                                             * 2);
1283   plugin->inbound_sessions =
1284       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
1285                                             * 2);
1286   sockets_created = 0;
1287   if ((GNUNET_YES !=
1288        GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "nat",
1289                                              "DISABLEV6")))
1290   {
1291     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1292     if (NULL == plugin->sockv6)
1293     {
1294       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1295     }
1296     else
1297     {
1298 #if HAVE_SOCKADDR_IN_SIN_LEN
1299       serverAddrv6.sin6_len = sizeof (serverAddrv6);
1300 #endif
1301       serverAddrv6.sin6_family = AF_INET6;
1302       serverAddrv6.sin6_addr = in6addr_any;
1303       serverAddrv6.sin6_port = htons (plugin->port);
1304       addrlen = sizeof (serverAddrv6);
1305       serverAddr = (struct sockaddr *) &serverAddrv6;
1306 #if DEBUG_UDP
1307       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1308            ntohs (serverAddrv6.sin6_port));
1309 #endif
1310       tries = 0;
1311       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1312              GNUNET_OK)
1313       {
1314         serverAddrv6.sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1315 #if DEBUG_UDP
1316         LOG (GNUNET_ERROR_TYPE_DEBUG,
1317              "IPv6 Binding failed, trying new port %d\n",
1318              ntohs (serverAddrv6.sin6_port));
1319 #endif
1320         tries++;
1321         if (tries > 10)
1322         {
1323           GNUNET_NETWORK_socket_close (plugin->sockv6);
1324           plugin->sockv6 = NULL;
1325           break;
1326         }
1327       }
1328       if (plugin->sockv6 != NULL)
1329       {
1330         addrs[sockets_created] = (struct sockaddr *) &serverAddrv6;
1331         addrlens[sockets_created] = sizeof (serverAddrv6);
1332         sockets_created++;
1333       }
1334     }
1335   }
1336
1337   plugin->mst =
1338       GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
1339   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1340   if (NULL == plugin->sockv4)
1341   {
1342     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1343   }
1344   else
1345   {
1346 #if HAVE_SOCKADDR_IN_SIN_LEN
1347     serverAddrv4.sin_len = sizeof (serverAddrv4);
1348 #endif
1349     serverAddrv4.sin_family = AF_INET;
1350     serverAddrv4.sin_addr.s_addr = INADDR_ANY;
1351     serverAddrv4.sin_port = htons (plugin->port);
1352     addrlen = sizeof (serverAddrv4);
1353     serverAddr = (struct sockaddr *) &serverAddrv4;
1354 #if DEBUG_UDP
1355     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1356          ntohs (serverAddrv4.sin_port));
1357 #endif
1358     tries = 0;
1359     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1360            GNUNET_OK)
1361     {
1362       serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1363 #if DEBUG_UDP
1364       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
1365            ntohs (serverAddrv4.sin_port));
1366 #endif
1367       tries++;
1368       if (tries > 10)
1369       {
1370         GNUNET_NETWORK_socket_close (plugin->sockv4);
1371         plugin->sockv4 = NULL;
1372         break;
1373       }
1374     }
1375     if (plugin->sockv4 != NULL)
1376     {
1377       addrs[sockets_created] = (struct sockaddr *) &serverAddrv4;
1378       addrlens[sockets_created] = sizeof (serverAddrv4);
1379       sockets_created++;
1380     }
1381   }
1382
1383   plugin->rs = GNUNET_NETWORK_fdset_create ();
1384   GNUNET_NETWORK_fdset_zero (plugin->rs);
1385   if (NULL != plugin->sockv4)
1386     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
1387   if (NULL != plugin->sockv6)
1388     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
1389
1390   plugin->select_task =
1391       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1392                                    GNUNET_SCHEDULER_NO_TASK,
1393                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1394                                    NULL, &udp_plugin_select, plugin);
1395   if (sockets_created == 0)
1396     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
1397   plugin->nat =
1398       GNUNET_NAT_register (env->cfg, GNUNET_NO, port, sockets_created,
1399                            (const struct sockaddr **) addrs, addrlens,
1400                            &udp_nat_port_map_callback, NULL, plugin);
1401   return api;
1402 }
1403
1404 /**
1405  * Shutdown the plugin.
1406  *
1407  * @param cls our 'struct GNUNET_TRANSPORT_PluginFunctions'
1408  * @return NULL
1409  */
1410 void *
1411 libgnunet_plugin_transport_udp_done (void *cls)
1412 {
1413   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1414   struct Plugin *plugin = api->cls;
1415   struct ReceiveContext *rc;
1416
1417   /* FIXME: clean up heap and hashmap */
1418   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &destroy_session,
1419                                          NULL);
1420   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1421   plugin->sessions = NULL;
1422   GNUNET_CONTAINER_multihashmap_iterate (plugin->inbound_sessions,
1423                                          &destroy_inbound_session, NULL);
1424   GNUNET_CONTAINER_multihashmap_destroy (plugin->inbound_sessions);
1425   plugin->inbound_sessions = NULL;
1426   while (NULL != (rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags)))
1427   {
1428     GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
1429     GNUNET_free (rc);
1430   }
1431   GNUNET_CONTAINER_heap_destroy (plugin->defrags);
1432
1433   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1434   {
1435     GNUNET_SCHEDULER_cancel (plugin->select_task);
1436     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1437   }
1438   if (plugin->sockv4 != NULL)
1439   {
1440     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
1441     plugin->sockv4 = NULL;
1442   }
1443   if (plugin->sockv6 != NULL)
1444   {
1445     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
1446     plugin->sockv6 = NULL;
1447   }
1448   GNUNET_SERVER_mst_destroy (plugin->mst);
1449   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1450   GNUNET_NAT_unregister (plugin->nat);
1451   plugin->nat = NULL;
1452   GNUNET_free (plugin);
1453   GNUNET_free (api);
1454   return NULL;
1455 }
1456
1457 /* end of plugin_transport_udp.c */