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