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