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