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