cced16ffd21fdd0cbf91ba5b8c40ac361bbdf2eb
[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   if (session->cont != NULL)
329     session->cont (session->cont_cls, target, GNUNET_SYSERR);
330   GNUNET_free (session);
331 }
332
333
334 /**
335  * Actually send out the message.
336  *
337  * @param plugin the plugin
338  * @param send_handle which handle to send message on
339  * @param target who should receive this message (ignored by UDP)
340  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
341  * @param msgbuf_size the size of the msgbuf to send
342  * @param priority how important is the message (ignored by UDP)
343  * @param timeout when should we time out (give up) if we can not transmit?
344  * @param addr the addr to send the message to, needs to be a sockaddr for us
345  * @param addrlen the len of addr
346  * @param cont continuation to call once the message has
347  *        been transmitted (or if the transport is ready
348  *        for the next transmission call; or if the
349  *        peer disconnected...)
350  * @param cont_cls closure for cont
351  * @return the number of bytes written
352  */
353 static ssize_t
354 udp_send (struct Plugin *plugin, const struct sockaddr *sa,
355           const struct GNUNET_MessageHeader *msg)
356 {
357   ssize_t sent;
358   size_t slen;
359
360   switch (sa->sa_family)
361   {
362   case AF_INET:
363     if (NULL == plugin->sockv4)
364       return 0;
365     sent =
366         GNUNET_NETWORK_socket_sendto (plugin->sockv4, msg, ntohs (msg->size),
367                                       sa, slen = sizeof (struct sockaddr_in));
368     break;
369   case AF_INET6:
370     if (NULL == plugin->sockv6)
371       return 0;
372     sent =
373         GNUNET_NETWORK_socket_sendto (plugin->sockv6, msg, ntohs (msg->size),
374                                       sa, slen = sizeof (struct sockaddr_in6));
375     break;
376   default:
377     GNUNET_break (0);
378     return 0;
379   }
380   if (GNUNET_SYSERR == sent)
381     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "sendto");
382 #if DEBUG_UDP
383   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
384               "UDP transmited %u-byte message to %s (%d: %s)\n",
385               (unsigned int) ntohs (msg->size), GNUNET_a2s (sa, slen),
386               (int) sent, (sent < 0) ? STRERROR (errno) : "ok");
387 #endif
388   return sent;
389 }
390
391
392 /**
393  * Function that is called with messages created by the fragmentation
394  * module.  In the case of the 'proc' callback of the
395  * GNUNET_FRAGMENT_context_create function, this function must
396  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
397  *
398  * @param cls closure, the 'struct PeerSession'
399  * @param msg the message that was created
400  */
401 static void
402 send_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
403 {
404   struct PeerSession *session = cls;
405
406   udp_send (session->plugin, session->sock_addr, msg);
407   GNUNET_FRAGMENT_context_transmission_done (session->frag);
408 }
409
410 static const char *
411 udp_address_to_string (void *cls, const void *addr, size_t addrlen);
412
413 /**
414  * Function that can be used by the transport service to transmit
415  * a message using the plugin.
416  *
417  * @param cls closure
418  * @param target who should receive this message (ignored by UDP)
419  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
420  * @param msgbuf_size the size of the msgbuf to send
421  * @param priority how important is the message (ignored by UDP)
422  * @param timeout when should we time out (give up) if we can not transmit?
423  * @param session identifier used for this session (NULL for UDP)
424  * @param addr the addr to send the message to
425  * @param addrlen the len of addr
426  * @param force_address not used, we had better have an address to send to
427  *        because we are stateless!!
428  * @param cont continuation to call once the message has
429  *        been transmitted (or if the transport is ready
430  *        for the next transmission call; or if the
431  *        peer disconnected...)
432  * @param cont_cls closure for cont
433  *
434  * @return the number of bytes written (may return 0 and the message can
435  *         still be transmitted later!)
436  */
437 static ssize_t
438 udp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
439                  const char *msgbuf, size_t msgbuf_size, unsigned int priority,
440                  struct GNUNET_TIME_Relative timeout, struct Session *session,
441                  const void *addr, size_t addrlen, int force_address,
442                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
443 {
444   struct Plugin *plugin = cls;
445   struct PeerSession *peer_session;
446   const struct IPv4UdpAddress *t4;
447   const struct IPv6UdpAddress *t6;
448   struct sockaddr_in *v4;
449   struct sockaddr_in6 *v6;
450   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
451   char mbuf[mlen];
452   struct UDPMessage *udp;
453
454   if (force_address == GNUNET_SYSERR)
455     return GNUNET_SYSERR;
456   GNUNET_assert (NULL == session);
457   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
458   {
459     GNUNET_break (0);
460     return GNUNET_SYSERR;
461   }
462   switch (addrlen)
463   {
464   case sizeof (struct IPv4UdpAddress):
465     if (NULL == plugin->sockv4)
466     {
467       if (cont != NULL)
468         cont (cont_cls, target, GNUNET_SYSERR);
469       return 0;
470     }
471     t4 = addr;
472     peer_session =
473         GNUNET_malloc (sizeof (struct PeerSession) +
474                        sizeof (struct sockaddr_in));
475     v4 = (struct sockaddr_in *) &peer_session[1];
476     v4->sin_family = AF_INET;
477 #if HAVE_SOCKADDR_IN_SIN_LEN
478     v4->sin_len = sizeof (struct sockaddr_in);
479 #endif
480     v4->sin_port = t4->u4_port;
481     v4->sin_addr.s_addr = t4->ipv4_addr;
482     break;
483   case sizeof (struct IPv6UdpAddress):
484     if (NULL == plugin->sockv6)
485     {
486       if (cont != NULL)
487         cont (cont_cls, target, GNUNET_SYSERR);
488       return 0;
489     }
490     t6 = addr;
491     peer_session =
492         GNUNET_malloc (sizeof (struct PeerSession) +
493                        sizeof (struct sockaddr_in6));
494     v6 = (struct sockaddr_in6 *) &peer_session[1];
495     v6->sin6_family = AF_INET6;
496 #if HAVE_SOCKADDR_IN_SIN_LEN
497     v6->sin6_len = sizeof (struct sockaddr_in6);
498 #endif
499     v6->sin6_port = t6->u6_port;
500     v6->sin6_addr = t6->ipv6_addr;
501     break;
502   default:
503     /* Must have a valid address to send to */
504     GNUNET_break_op (0);
505     return GNUNET_SYSERR;
506   }
507   udp = (struct UDPMessage *) mbuf;
508   udp->header.size = htons (mlen);
509   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
510   udp->reserved = htonl (0);
511   udp->sender = *plugin->env->my_identity;
512   memcpy (&udp[1], msgbuf, msgbuf_size);
513   peer_session->target = *target;
514   peer_session->plugin = plugin;
515   peer_session->sock_addr = (const struct sockaddr *) &peer_session[1];
516   peer_session->cont = cont;
517   peer_session->cont_cls = cont_cls;
518   if (mlen <= UDP_MTU)
519   {
520     mlen = udp_send (plugin, peer_session->sock_addr, &udp->header);
521     if (cont != NULL)
522       cont (cont_cls, target, (mlen > 0) ? GNUNET_OK : GNUNET_SYSERR);
523     GNUNET_free_non_null (peer_session);
524   }
525   else
526   {
527     GNUNET_assert (GNUNET_OK ==
528                    GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
529                                                       &target->hashPubKey,
530                                                       peer_session,
531                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
532     peer_session->frag =
533         GNUNET_FRAGMENT_context_create (plugin->env->stats, UDP_MTU,
534                                         &plugin->tracker,
535                                         plugin->last_expected_delay,
536                                         &udp->header, &send_fragment,
537                                         peer_session);
538   }
539   return mlen;
540 }
541
542
543 /**
544  * Closure for 'process_inbound_tokenized_messages'
545  */
546 struct SourceInformation
547 {
548   /**
549    * Sender identity.
550    */
551   struct GNUNET_PeerIdentity sender;
552
553   /**
554    * Source address.
555    */
556   const void *arg;
557
558   /**
559    * Number of bytes in source address.
560    */
561   size_t args;
562 };
563
564
565 /**
566  * Message tokenizer has broken up an incomming message. Pass it on
567  * to the service.
568  *
569  * @param cls the 'struct Plugin'
570  * @param client the 'struct SourceInformation'
571  * @param hdr the actual message
572  */
573 static void
574 process_inbound_tokenized_messages (void *cls, void *client,
575                                     const struct GNUNET_MessageHeader *hdr)
576 {
577   struct Plugin *plugin = cls;
578   struct SourceInformation *si = client;
579   struct GNUNET_TRANSPORT_ATS_Information distance[2];
580
581   /* setup ATS */
582   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
583   distance[0].value = htonl (1);
584   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
585   distance[1].value = htonl (0);
586
587   plugin->env->receive (plugin->env->cls, &si->sender, hdr, distance, 2, NULL,
588                         si->arg, si->args);
589 }
590
591
592 /**
593  * We've received a UDP Message.  Process it (pass contents to main service).
594  *
595  * @param plugin plugin context
596  * @param msg the message
597  * @param sender_addr sender address
598  * @param sender_addr_len number of bytes in sender_addr
599  */
600 static void
601 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
602                      const struct sockaddr *sender_addr,
603                      socklen_t sender_addr_len)
604 {
605   struct SourceInformation si;
606   struct IPv4UdpAddress u4;
607   struct IPv6UdpAddress u6;
608   const void *arg;
609   size_t args;
610
611   if (0 != ntohl (msg->reserved))
612   {
613     GNUNET_break_op (0);
614     return;
615   }
616   if (ntohs (msg->header.size) <
617       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
618   {
619     GNUNET_break_op (0);
620     return;
621   }
622
623   /* convert address */
624   switch (sender_addr->sa_family)
625   {
626   case AF_INET:
627     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
628     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
629     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
630     arg = &u4;
631     args = sizeof (u4);
632     break;
633   case AF_INET6:
634     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
635     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
636     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
637     arg = &u6;
638     args = sizeof (u6);
639     break;
640   default:
641     GNUNET_break (0);
642     return;
643   }
644 #if DEBUG_UDP
645   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp",
646                    "Received message with %u bytes from peer `%s' at `%s'\n",
647                    (unsigned int) ntohs (msg->header.size),
648                    GNUNET_i2s (&msg->sender), GNUNET_a2s (sender_addr,
649                                                           sender_addr_len));
650 #endif
651
652   /* iterate over all embedded messages */
653   si.sender = msg->sender;
654   si.arg = arg;
655   si.args = args;
656   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
657                              ntohs (msg->header.size) -
658                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
659 }
660
661
662 /**
663  * Process a defragmented message.
664  *
665  * @param cls the 'struct ReceiveContext'
666  * @param msg the message
667  */
668 static void
669 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
670 {
671   struct ReceiveContext *rc = cls;
672
673   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
674   {
675     GNUNET_break (0);
676     return;
677   }
678   if (ntohs (msg->size) < sizeof (struct UDPMessage))
679   {
680     GNUNET_break (0);
681     return;
682   }
683   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
684                        rc->src_addr, rc->addr_len);
685 }
686
687
688 /**
689  * Transmit an acknowledgement.
690  *
691  * @param cls the 'struct ReceiveContext'
692  * @param id message ID (unused)
693  * @param msg ack to transmit
694  */
695 static void
696 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
697 {
698   struct ReceiveContext *rc = cls;
699   size_t msize = sizeof (struct UDPMessage) + ntohs (msg->size);
700   char buf[msize];
701   struct UDPMessage *udp;
702
703 #if DEBUG_UDP
704   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "udp", "Sending ACK to `%s'\n",
705                    GNUNET_a2s (rc->src_addr,
706                                (rc->src_addr->sa_family ==
707                                 AF_INET) ? sizeof (struct sockaddr_in) :
708                                sizeof (struct sockaddr_in6)));
709 #endif
710   udp = (struct UDPMessage *) buf;
711   udp->header.size = htons ((uint16_t) msize);
712   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
713   udp->reserved = htonl (0);
714   udp->sender = *rc->plugin->env->my_identity;
715   memcpy (&udp[1], msg, ntohs (msg->size));
716   (void) udp_send (rc->plugin, rc->src_addr, &udp->header);
717 }
718
719
720 /**
721  * Closure for 'find_receive_context'.
722  */
723 struct FindReceiveContext
724 {
725   /**
726    * Where to store the result.
727    */
728   struct ReceiveContext *rc;
729
730   /**
731    * Address to find.
732    */
733   const struct sockaddr *addr;
734
735   /**
736    * Number of bytes in 'addr'.
737    */
738   socklen_t addr_len;
739 };
740
741
742 /**
743  * Scan the heap for a receive context with the given address.
744  *
745  * @param cls the 'struct FindReceiveContext'
746  * @param node internal node of the heap
747  * @param element value stored at the node (a 'struct ReceiveContext')
748  * @param cost cost associated with the node
749  * @return GNUNET_YES if we should continue to iterate,
750  *         GNUNET_NO if not.
751  */
752 static int
753 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
754                       void *element, GNUNET_CONTAINER_HeapCostType cost)
755 {
756   struct FindReceiveContext *frc = cls;
757   struct ReceiveContext *e = element;
758
759   if ((frc->addr_len == e->addr_len) &&
760       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
761   {
762     frc->rc = e;
763     return GNUNET_NO;
764   }
765   return GNUNET_YES;
766 }
767
768
769 /**
770  * Read and process a message from the given socket.
771  *
772  * @param plugin the overall plugin
773  * @param rsock socket to read from
774  */
775 static void
776 udp_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
777 {
778   socklen_t fromlen;
779   char addr[32];
780   char buf[65536];
781   ssize_t ret;
782   const struct GNUNET_MessageHeader *msg;
783   const struct GNUNET_MessageHeader *ack;
784   struct PeerSession *peer_session;
785   const struct UDPMessage *udp;
786   struct ReceiveContext *rc;
787   struct GNUNET_TIME_Absolute now;
788   struct FindReceiveContext frc;
789
790   fromlen = sizeof (addr);
791   memset (&addr, 0, sizeof (addr));
792   ret =
793       GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
794                                       (struct sockaddr *) &addr, &fromlen);
795   if (ret < sizeof (struct GNUNET_MessageHeader))
796   {
797     GNUNET_break_op (0);
798     return;
799   }
800 #if DEBUG_UDP
801   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
802               "UDP received %u-byte message from `%s'\n", (unsigned int) ret,
803               GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
804 #endif
805   msg = (const struct GNUNET_MessageHeader *) buf;
806   if (ret != ntohs (msg->size))
807   {
808     GNUNET_break_op (0);
809     return;
810   }
811   switch (ntohs (msg->type))
812   {
813   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
814     if (ntohs (msg->size) < sizeof (struct UDPMessage))
815     {
816       GNUNET_break_op (0);
817       return;
818     }
819     process_udp_message (plugin, (const struct UDPMessage *) msg,
820                          (const struct sockaddr *) addr, fromlen);
821     return;
822   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
823     if (ntohs (msg->size) <
824         sizeof (struct UDPMessage) + sizeof (struct GNUNET_MessageHeader))
825     {
826       GNUNET_break_op (0);
827       return;
828     }
829     udp = (const struct UDPMessage *) msg;
830     if (ntohl (udp->reserved) != 0)
831     {
832       GNUNET_break_op (0);
833       return;
834     }
835     ack = (const struct GNUNET_MessageHeader *) &udp[1];
836     if (ntohs (ack->size) != ntohs (msg->size) - sizeof (struct UDPMessage))
837     {
838       GNUNET_break_op (0);
839       return;
840     }
841 #if DEBUG_UDP
842     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
843                 "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
844                 (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp->sender),
845                 GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
846 #endif
847
848     peer_session = find_session (plugin, &udp->sender);
849     if (NULL == peer_session)
850     {
851 #if DEBUG_UDP
852       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                   "Session for ACK not found, dropping ACK!\n");
854 #endif
855       return;
856     }
857     if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (peer_session->frag, ack))
858       return;
859     GNUNET_assert (GNUNET_OK ==
860                    GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
861                                                          &udp->
862                                                          sender.hashPubKey,
863                                                          peer_session));
864     plugin->last_expected_delay =
865         GNUNET_FRAGMENT_context_destroy (peer_session->frag);
866     if (peer_session->cont != NULL)
867       peer_session->cont (peer_session->cont_cls, &udp->sender, GNUNET_OK);
868     GNUNET_free (peer_session);
869     return;
870   case GNUNET_MESSAGE_TYPE_FRAGMENT:
871     frc.rc = NULL;
872     frc.addr = (const struct sockaddr *) addr;
873     frc.addr_len = fromlen;
874     GNUNET_CONTAINER_heap_iterate (plugin->defrags, &find_receive_context,
875                                    &frc);
876     now = GNUNET_TIME_absolute_get ();
877     rc = frc.rc;
878     if (rc == NULL)
879     {
880       /* need to create a new RC */
881       rc = GNUNET_malloc (sizeof (struct ReceiveContext) + fromlen);
882       memcpy (&rc[1], addr, fromlen);
883       rc->src_addr = (const struct sockaddr *) &rc[1];
884       rc->addr_len = fromlen;
885       rc->plugin = plugin;
886       rc->defrag =
887           GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
888                                             UDP_MAX_MESSAGES_IN_DEFRAG, rc,
889                                             &fragment_msg_proc, &ack_proc);
890       rc->hnode =
891           GNUNET_CONTAINER_heap_insert (plugin->defrags, rc,
892                                         (GNUNET_CONTAINER_HeapCostType)
893                                         now.abs_value);
894     }
895 #if DEBUG_UDP
896     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
897                 "UDP processes %u-byte fragment from `%s'\n",
898                 (unsigned int) ntohs (msg->size),
899                 GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
900 #endif
901
902     if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (rc->defrag, msg))
903     {
904       /* keep this 'rc' from expiring */
905       GNUNET_CONTAINER_heap_update_cost (plugin->defrags, rc->hnode,
906                                          (GNUNET_CONTAINER_HeapCostType)
907                                          now.abs_value);
908     }
909     if (GNUNET_CONTAINER_heap_get_size (plugin->defrags) >
910         UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
911     {
912       /* remove 'rc' that was inactive the longest */
913       rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags);
914       GNUNET_assert (NULL != rc);
915       GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
916       GNUNET_free (rc);
917     }
918     return;
919   default:
920     GNUNET_break_op (0);
921     return;
922   }
923 }
924
925
926 /**
927  * We have been notified that our writeset has something to read.  We don't
928  * know which socket needs to be read, so we have to check each one
929  * Then reschedule this function to be called again once more is available.
930  *
931  * @param cls the plugin handle
932  * @param tc the scheduling context (for rescheduling this function again)
933  */
934 static void
935 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
936 {
937   struct Plugin *plugin = cls;
938
939   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
940   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
941     return;
942   if ((NULL != plugin->sockv4) &&
943       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
944     udp_read (plugin, plugin->sockv4);
945   if ((NULL != plugin->sockv6) &&
946       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
947     udp_read (plugin, plugin->sockv6);
948   plugin->select_task =
949       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
950                                    GNUNET_SCHEDULER_NO_TASK,
951                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
952                                    NULL, &udp_plugin_select, plugin);
953
954 }
955
956
957 /**
958  * Check if the given port is plausible (must be either our listen
959  * port or our advertised port).  If it is neither, we return
960  * GNUNET_SYSERR.
961  *
962  * @param plugin global variables
963  * @param in_port port number to check
964  * @return GNUNET_OK if port is either open_port or adv_port
965  */
966 static int
967 check_port (struct Plugin *plugin, uint16_t in_port)
968 {
969   if ((in_port == plugin->port) || (in_port == plugin->aport))
970     return GNUNET_OK;
971   return GNUNET_SYSERR;
972 }
973
974
975 /**
976  * Function that will be called to check if a binary address for this
977  * plugin is well-formed and corresponds to an address for THIS peer
978  * (as per our configuration).  Naturally, if absolutely necessary,
979  * plugins can be a bit conservative in their answer, but in general
980  * plugins should make sure that the address does not redirect
981  * traffic to a 3rd party that might try to man-in-the-middle our
982  * traffic.
983  *
984  * @param cls closure, should be our handle to the Plugin
985  * @param addr pointer to the address
986  * @param addrlen length of addr
987  * @return GNUNET_OK if this is a plausible address for this peer
988  *         and transport, GNUNET_SYSERR if not
989  *
990  */
991 static int
992 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
993 {
994   struct Plugin *plugin = cls;
995   struct IPv4UdpAddress *v4;
996   struct IPv6UdpAddress *v6;
997
998   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
999       (addrlen != sizeof (struct IPv6UdpAddress)))
1000   {
1001     GNUNET_break_op (0);
1002     return GNUNET_SYSERR;
1003   }
1004   if (addrlen == sizeof (struct IPv4UdpAddress))
1005   {
1006     v4 = (struct IPv4UdpAddress *) addr;
1007     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
1008       return GNUNET_SYSERR;
1009     if (GNUNET_OK !=
1010         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1011                                  sizeof (struct in_addr)))
1012       return GNUNET_SYSERR;
1013   }
1014   else
1015   {
1016     v6 = (struct IPv6UdpAddress *) addr;
1017     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1018     {
1019       GNUNET_break_op (0);
1020       return GNUNET_SYSERR;
1021     }
1022     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
1023       return GNUNET_SYSERR;
1024     if (GNUNET_OK !=
1025         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1026                                  sizeof (struct in6_addr)))
1027       return GNUNET_SYSERR;
1028   }
1029   return GNUNET_OK;
1030 }
1031
1032
1033 /**
1034  * Function called for a quick conversion of the binary address to
1035  * a numeric address.  Note that the caller must not free the
1036  * address and that the next call to this function is allowed
1037  * to override the address again.
1038  *
1039  * @param cls closure
1040  * @param addr binary address
1041  * @param addrlen length of the address
1042  * @return string representing the same address
1043  */
1044 static const char *
1045 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
1046 {
1047   static char rbuf[INET6_ADDRSTRLEN + 10];
1048   char buf[INET6_ADDRSTRLEN];
1049   const void *sb;
1050   struct in_addr a4;
1051   struct in6_addr a6;
1052   const struct IPv4UdpAddress *t4;
1053   const struct IPv6UdpAddress *t6;
1054   int af;
1055   uint16_t port;
1056
1057   if (addrlen == sizeof (struct IPv6UdpAddress))
1058   {
1059     t6 = addr;
1060     af = AF_INET6;
1061     port = ntohs (t6->u6_port);
1062     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
1063     sb = &a6;
1064   }
1065   else if (addrlen == sizeof (struct IPv4UdpAddress))
1066   {
1067     t4 = addr;
1068     af = AF_INET;
1069     port = ntohs (t4->u4_port);
1070     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
1071     sb = &a4;
1072   }
1073   else
1074   {
1075     GNUNET_break_op (0);
1076     return NULL;
1077   }
1078   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
1079   GNUNET_snprintf (rbuf, sizeof (rbuf), "%s:%u", buf, port);
1080   return rbuf;
1081 }
1082
1083
1084 /**
1085  * Closure for 'append_port'.
1086  */
1087 struct PrettyPrinterContext
1088 {
1089   /**
1090    * Function to call with the result.
1091    */
1092   GNUNET_TRANSPORT_AddressStringCallback asc;
1093
1094   /**
1095    * Clsoure for 'asc'.
1096    */
1097   void *asc_cls;
1098
1099   /**
1100    * Port to add after the IP address.
1101    */
1102   uint16_t port;
1103 };
1104
1105
1106 /**
1107  * Append our port and forward the result.
1108  *
1109  * @param cls a 'struct PrettyPrinterContext'
1110  * @param hostname result from DNS resolver
1111  */
1112 static void
1113 append_port (void *cls, const char *hostname)
1114 {
1115   struct PrettyPrinterContext *ppc = cls;
1116   char *ret;
1117
1118   if (hostname == NULL)
1119   {
1120     ppc->asc (ppc->asc_cls, NULL);
1121     GNUNET_free (ppc);
1122     return;
1123   }
1124   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1125   ppc->asc (ppc->asc_cls, ret);
1126   GNUNET_free (ret);
1127 }
1128
1129
1130 /**
1131  * Convert the transports address to a nice, human-readable
1132  * format.
1133  *
1134  * @param cls closure
1135  * @param type name of the transport that generated the address
1136  * @param addr one of the addresses of the host, NULL for the last address
1137  *        the specific address format depends on the transport
1138  * @param addrlen length of the address
1139  * @param numeric should (IP) addresses be displayed in numeric form?
1140  * @param timeout after how long should we give up?
1141  * @param asc function to call on each string
1142  * @param asc_cls closure for asc
1143  */
1144 static void
1145 udp_plugin_address_pretty_printer (void *cls, const char *type,
1146                                    const void *addr, size_t addrlen,
1147                                    int numeric,
1148                                    struct GNUNET_TIME_Relative timeout,
1149                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1150                                    void *asc_cls)
1151 {
1152   struct PrettyPrinterContext *ppc;
1153   const void *sb;
1154   size_t sbs;
1155   struct sockaddr_in a4;
1156   struct sockaddr_in6 a6;
1157   const struct IPv4UdpAddress *u4;
1158   const struct IPv6UdpAddress *u6;
1159   uint16_t port;
1160
1161   if (addrlen == sizeof (struct IPv6UdpAddress))
1162   {
1163     u6 = addr;
1164     memset (&a6, 0, sizeof (a6));
1165     a6.sin6_family = AF_INET6;
1166 #if HAVE_SOCKADDR_IN_SIN_LEN
1167     a6.sin6_len = sizeof (a6);
1168 #endif
1169     a6.sin6_port = u6->u6_port;
1170     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
1171     port = ntohs (u6->u6_port);
1172     sb = &a6;
1173     sbs = sizeof (a6);
1174   }
1175   else if (addrlen == sizeof (struct IPv4UdpAddress))
1176   {
1177     u4 = addr;
1178     memset (&a4, 0, sizeof (a4));
1179     a4.sin_family = AF_INET;
1180 #if HAVE_SOCKADDR_IN_SIN_LEN
1181     a4.sin_len = sizeof (a4);
1182 #endif
1183     a4.sin_port = u4->u4_port;
1184     a4.sin_addr.s_addr = u4->ipv4_addr;
1185     port = ntohs (u4->u4_port);
1186     sb = &a4;
1187     sbs = sizeof (a4);
1188   }
1189   else
1190   {
1191     /* invalid address */
1192     GNUNET_break_op (0);
1193     asc (asc_cls, NULL);
1194     return;
1195   }
1196   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1197   ppc->asc = asc;
1198   ppc->asc_cls = asc_cls;
1199   ppc->port = port;
1200   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1201 }
1202
1203
1204 /**
1205  * Our external IP address/port mapping has changed.
1206  *
1207  * @param cls closure, the 'struct LocalAddrList'
1208  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1209  *     the previous (now invalid) one
1210  * @param addr either the previous or the new public IP address
1211  * @param addrlen actual lenght of the address
1212  */
1213 static void
1214 udp_nat_port_map_callback (void *cls, int add_remove,
1215                            const struct sockaddr *addr, socklen_t addrlen)
1216 {
1217   struct Plugin *plugin = cls;
1218   struct IPv4UdpAddress u4;
1219   struct IPv6UdpAddress u6;
1220   void *arg;
1221   size_t args;
1222
1223   /* convert 'addr' to our internal format */
1224   switch (addr->sa_family)
1225   {
1226   case AF_INET:
1227     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1228     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1229     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1230     arg = &u4;
1231     args = sizeof (u4);
1232     break;
1233   case AF_INET6:
1234     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1235     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1236             sizeof (struct in6_addr));
1237     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1238     arg = &u6;
1239     args = sizeof (u6);
1240     break;
1241   default:
1242     GNUNET_break (0);
1243     return;
1244   }
1245   /* modify our published address list */
1246   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
1247 }
1248
1249
1250 /**
1251  * The exported method. Makes the core api available via a global and
1252  * returns the udp transport API.
1253  *
1254  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1255  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1256  */
1257 void *
1258 libgnunet_plugin_transport_udp_init (void *cls)
1259 {
1260   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1261   unsigned long long port;
1262   unsigned long long aport;
1263   struct GNUNET_TRANSPORT_PluginFunctions *api;
1264   struct Plugin *plugin;
1265   int sockets_created;
1266   struct sockaddr_in serverAddrv4;
1267   struct sockaddr_in6 serverAddrv6;
1268   struct sockaddr *serverAddr;
1269   struct sockaddr *addrs[2];
1270   socklen_t addrlens[2];
1271   socklen_t addrlen;
1272   unsigned int tries;
1273   unsigned long long udp_max_bps;
1274
1275   if (GNUNET_OK !=
1276       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
1277                                              &port))
1278     port = 2086;
1279   if (GNUNET_OK !=
1280       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1281                                              "MAX_BPS", &udp_max_bps))
1282     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1283   if (GNUNET_OK !=
1284       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1285                                              "ADVERTISED_PORT", &aport))
1286     aport = port;
1287   if (port > 65535)
1288   {
1289     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1290                 _("Given `%s' option is out of range: %llu > %u\n"), "PORT",
1291                 port, 65535);
1292     return NULL;
1293   }
1294   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1295   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1296
1297   plugin = GNUNET_malloc (sizeof (struct Plugin));
1298   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1299                                  GNUNET_BANDWIDTH_value_init ((uint32_t)
1300                                                               udp_max_bps), 30);
1301   plugin->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
1302   plugin->port = port;
1303   plugin->aport = aport;
1304   plugin->env = env;
1305   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1306   api->cls = plugin;
1307
1308   api->send = &udp_plugin_send;
1309   api->disconnect = &udp_disconnect;
1310   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1311   api->address_to_string = &udp_address_to_string;
1312   api->check_address = &udp_plugin_check_address;
1313
1314   if (GNUNET_YES ==
1315       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1316                                              "BINDTO", &plugin->bind4_address))
1317   {
1318     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1319                 "Binding udp plugin to specific address: `%s'\n",
1320                 plugin->bind4_address);
1321     if (1 != inet_pton (AF_INET, plugin->bind4_address, &serverAddrv4.sin_addr))
1322     {
1323       GNUNET_free (plugin->bind4_address);
1324       GNUNET_free (plugin);
1325       GNUNET_free (api);
1326       return NULL;
1327     }
1328   }
1329
1330   if (GNUNET_YES ==
1331       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1332                                              "BINDTO6", &plugin->bind6_address))
1333   {
1334     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1335                 "Binding udp plugin to specific address: `%s'\n",
1336                 plugin->bind6_address);
1337     if (1 !=
1338         inet_pton (AF_INET6, plugin->bind6_address, &serverAddrv6.sin6_addr))
1339     {
1340       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1341                   plugin->bind6_address);
1342       GNUNET_free_non_null (plugin->bind4_address);
1343       GNUNET_free (plugin->bind6_address);
1344       GNUNET_free (plugin);
1345       GNUNET_free (api);
1346       return NULL;
1347     }
1348   }
1349
1350   plugin->defrags =
1351       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1352   plugin->sessions =
1353       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
1354                                             * 2);
1355   sockets_created = 0;
1356   if ((GNUNET_YES !=
1357        GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "nat",
1358                                              "DISABLEV6")))
1359   {
1360     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1361     if (NULL == plugin->sockv6)
1362     {
1363       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1364     }
1365     else
1366     {
1367 #if HAVE_SOCKADDR_IN_SIN_LEN
1368       serverAddrv6.sin6_len = sizeof (serverAddrv6);
1369 #endif
1370       serverAddrv6.sin6_family = AF_INET6;
1371       serverAddrv6.sin6_addr = in6addr_any;
1372       serverAddrv6.sin6_port = htons (plugin->port);
1373       addrlen = sizeof (serverAddrv6);
1374       serverAddr = (struct sockaddr *) &serverAddrv6;
1375 #if DEBUG_UDP
1376       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1377                   ntohs (serverAddrv6.sin6_port));
1378 #endif
1379       tries = 0;
1380       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1381              GNUNET_OK)
1382       {
1383         serverAddrv6.sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1384 #if DEBUG_UDP
1385         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1386                     "IPv6 Binding failed, trying new port %d\n",
1387                     ntohs (serverAddrv6.sin6_port));
1388 #endif
1389         tries++;
1390         if (tries > 10)
1391         {
1392           GNUNET_NETWORK_socket_close (plugin->sockv6);
1393           plugin->sockv6 = NULL;
1394           break;
1395         }
1396       }
1397       if (plugin->sockv6 != NULL)
1398       {
1399         addrs[sockets_created] = (struct sockaddr *) &serverAddrv6;
1400         addrlens[sockets_created] = sizeof (serverAddrv6);
1401         sockets_created++;
1402       }
1403     }
1404   }
1405
1406   plugin->mst =
1407       GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
1408   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1409   if (NULL == plugin->sockv4)
1410   {
1411     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1412   }
1413   else
1414   {
1415 #if HAVE_SOCKADDR_IN_SIN_LEN
1416     serverAddrv4.sin_len = sizeof (serverAddrv4);
1417 #endif
1418     serverAddrv4.sin_family = AF_INET;
1419     serverAddrv4.sin_addr.s_addr = INADDR_ANY;
1420     serverAddrv4.sin_port = htons (plugin->port);
1421     addrlen = sizeof (serverAddrv4);
1422     serverAddr = (struct sockaddr *) &serverAddrv4;
1423 #if DEBUG_UDP
1424     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1425                 ntohs (serverAddrv4.sin_port));
1426 #endif
1427     tries = 0;
1428     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1429            GNUNET_OK)
1430     {
1431       serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1432 #if DEBUG_UDP
1433       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1434                   "IPv4 Binding failed, trying new port %d\n",
1435                   ntohs (serverAddrv4.sin_port));
1436 #endif
1437       tries++;
1438       if (tries > 10)
1439       {
1440         GNUNET_NETWORK_socket_close (plugin->sockv4);
1441         plugin->sockv4 = NULL;
1442         break;
1443       }
1444     }
1445     if (plugin->sockv4 != NULL)
1446     {
1447       addrs[sockets_created] = (struct sockaddr *) &serverAddrv4;
1448       addrlens[sockets_created] = sizeof (serverAddrv4);
1449       sockets_created++;
1450     }
1451   }
1452
1453   plugin->rs = GNUNET_NETWORK_fdset_create ();
1454   GNUNET_NETWORK_fdset_zero (plugin->rs);
1455   if (NULL != plugin->sockv4)
1456     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
1457   if (NULL != plugin->sockv6)
1458     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
1459
1460   plugin->select_task =
1461       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1462                                    GNUNET_SCHEDULER_NO_TASK,
1463                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1464                                    NULL, &udp_plugin_select, plugin);
1465   if (sockets_created == 0)
1466     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
1467   plugin->nat =
1468       GNUNET_NAT_register (env->cfg, GNUNET_NO, port, sockets_created,
1469                            (const struct sockaddr **) addrs, addrlens,
1470                            &udp_nat_port_map_callback, NULL, plugin);
1471   return api;
1472 }
1473
1474
1475 /**
1476  * Destroy a session, plugin is being unloaded.
1477  *
1478  * @param cls unused
1479  * @param key hash of public key of target peer
1480  * @param value a 'struct PeerSession*' to clean up
1481  * @return GNUNET_OK (continue to iterate)
1482  */
1483 static int
1484 destroy_session (void *cls, const GNUNET_HashCode * key, void *value)
1485 {
1486   struct PeerSession *peer_session = value;
1487
1488   GNUNET_FRAGMENT_context_destroy (peer_session->frag);
1489   GNUNET_free (peer_session);
1490   return GNUNET_OK;
1491 }
1492
1493
1494 /**
1495  * Shutdown the plugin.
1496  *
1497  * @param cls our 'struct GNUNET_TRANSPORT_PluginFunctions'
1498  * @return NULL
1499  */
1500 void *
1501 libgnunet_plugin_transport_udp_done (void *cls)
1502 {
1503   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1504   struct Plugin *plugin = api->cls;
1505   struct ReceiveContext *rc;
1506
1507   /* FIXME: clean up heap and hashmap */
1508   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &destroy_session,
1509                                          NULL);
1510   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1511   plugin->sessions = NULL;
1512   while (NULL != (rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags)))
1513   {
1514     GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
1515     GNUNET_free (rc);
1516   }
1517   GNUNET_CONTAINER_heap_destroy (plugin->defrags);
1518
1519   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1520   {
1521     GNUNET_SCHEDULER_cancel (plugin->select_task);
1522     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1523   }
1524   if (plugin->sockv4 != NULL)
1525   {
1526     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
1527     plugin->sockv4 = NULL;
1528   }
1529   if (plugin->sockv6 != NULL)
1530   {
1531     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
1532     plugin->sockv6 = NULL;
1533   }
1534   GNUNET_SERVER_mst_destroy (plugin->mst);
1535   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1536   GNUNET_NAT_unregister (plugin->nat);
1537   plugin->nat = NULL;
1538   GNUNET_free (plugin);
1539   GNUNET_free (api);
1540   return NULL;
1541 }
1542
1543 /* end of plugin_transport_udp.c */