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