9812416de66aedc0906d127b06181c824405a1ce
[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   si->session->flow_delay_for_other_peer = delay;
865 }
866
867 static void
868 invalidation_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
869 {
870   struct Session * s = cls;
871   s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
872   LOG (GNUNET_ERROR_TYPE_ERROR,
873                    "Session %X (`%s') is now invalid\n", s, GNUNET_a2s (s->sock_addr,s->addrlen));
874
875   s->plugin->env->session_end(s->plugin->env->cls, &s->target, s);
876   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(s->plugin->inbound_sessions, &s->target.hashPubKey, s));
877   GNUNET_free (s);
878 }
879
880
881 /**
882  * We've received a UDP Message.  Process it (pass contents to main service).
883  *
884  * @param plugin plugin context
885  * @param msg the message
886  * @param sender_addr sender address
887  * @param sender_addr_len number of bytes in sender_addr
888  */
889 static void
890 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
891                      const struct sockaddr *sender_addr,
892                      socklen_t sender_addr_len)
893 {
894   struct SourceInformation si;
895   struct IPv4UdpAddress u4;
896   struct IPv6UdpAddress u6;
897   const void *arg;
898   size_t args;
899
900   if (0 != ntohl (msg->reserved))
901   {
902     GNUNET_break_op (0);
903     return;
904   }
905   if (ntohs (msg->header.size) <
906       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
907   {
908     GNUNET_break_op (0);
909     return;
910   }
911
912   /* convert address */
913   switch (sender_addr->sa_family)
914   {
915   case AF_INET:
916     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
917     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
918     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
919     arg = &u4;
920     args = sizeof (u4);
921     break;
922   case AF_INET6:
923     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
924     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
925     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
926     arg = &u6;
927     args = sizeof (u6);
928     break;
929   default:
930     GNUNET_break (0);
931     return;
932   }
933 #if DEBUG_UDP
934   LOG (GNUNET_ERROR_TYPE_DEBUG,
935                    "Received message with %u bytes from peer `%s' at `%s'\n",
936                    (unsigned int) ntohs (msg->header.size),
937                    GNUNET_i2s (&msg->sender), GNUNET_a2s (sender_addr,
938                                                           sender_addr_len));
939 #endif
940
941   /* create a session for inbound connections */
942   const struct UDPMessage * udp_msg = (const struct UDPMessage *) msg;
943   LOG (GNUNET_ERROR_TYPE_DEBUG,
944               "Lookup inbound UDP sessions for peer `%s' address `%s'\n",
945               GNUNET_i2s (&udp_msg->sender),
946               udp_address_to_string(NULL, arg, args));
947
948   struct Session * s = NULL;
949   s = find_inbound_session (plugin, &udp_msg->sender, sender_addr, sender_addr_len);
950
951   if (s != NULL)
952   {
953     LOG (GNUNET_ERROR_TYPE_DEBUG,
954                 "Found existing inbound UDP sessions 0x%X for peer `%s' address `%s'\n",
955                 s,
956                 GNUNET_i2s (&s->target),
957                 udp_address_to_string(NULL, arg, args));
958   }
959   else
960   {
961     s = create_session (plugin, &udp_msg->sender, arg, args, NULL, NULL);
962     LOG (GNUNET_ERROR_TYPE_DEBUG,
963                 "Creating inbound UDP sessions 0x%X for peer `%s' address `%s'\n",
964                 s,
965                 GNUNET_i2s (&s->target),
966                 udp_address_to_string(NULL, arg, args));
967
968     GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (plugin->inbound_sessions,
969                                                       &s->target.hashPubKey,
970                                                       s,
971                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
972   }
973   s->valid_until = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
974   if (s->invalidation_task != GNUNET_SCHEDULER_NO_TASK)
975   {
976     GNUNET_SCHEDULER_cancel(s->invalidation_task);
977     s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
978     LOG (GNUNET_ERROR_TYPE_DEBUG,
979                 "Rescheduling %X' `%s'\n",
980                 s, udp_address_to_string(NULL, arg, args));
981   }
982   s->invalidation_task = GNUNET_SCHEDULER_add_delayed(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &invalidation_task, s);
983   /* iterate over all embedded messages */
984   si.sender = msg->sender;
985   si.arg = arg;
986   si.args = args;
987   si.session = s;
988   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
989                              ntohs (msg->header.size) -
990                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
991 }
992
993
994 /**
995  * Process a defragmented message.
996  *
997  * @param cls the 'struct ReceiveContext'
998  * @param msg the message
999  */
1000 static void
1001 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1002 {
1003   struct ReceiveContext *rc = cls;
1004
1005   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1006   {
1007     GNUNET_break (0);
1008     return;
1009   }
1010   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1011   {
1012     GNUNET_break (0);
1013     return;
1014   }
1015   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1016                        rc->src_addr, rc->addr_len);
1017 }
1018
1019
1020 /**
1021  * Transmit an acknowledgement.
1022  *
1023  * @param cls the 'struct ReceiveContext'
1024  * @param id message ID (unused)
1025  * @param msg ack to transmit
1026  */
1027 static void
1028 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
1029 {
1030   struct ReceiveContext *rc = cls;
1031
1032   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
1033   char buf[msize];
1034   struct UDP_ACK_Message *udp_ack;
1035   uint32_t delay = 0;
1036
1037   struct Session *s;
1038   s = find_inbound_session_by_addr (rc->plugin, rc->src_addr, rc->addr_len);
1039   if (s != NULL)
1040   {
1041     if (s->flow_delay_for_other_peer.rel_value <= UINT32_MAX)
1042       delay = s->flow_delay_for_other_peer.rel_value;
1043     else
1044       delay = UINT32_MAX;
1045   }
1046
1047
1048 #if DEBUG_UDP
1049   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending ACK to `%s' including delay of %u ms\n",
1050                    GNUNET_a2s (rc->src_addr,
1051                                (rc->src_addr->sa_family ==
1052                                 AF_INET) ? sizeof (struct sockaddr_in) :
1053                                sizeof (struct sockaddr_in6)),
1054                                delay);
1055 #endif
1056   udp_ack = (struct UDP_ACK_Message *) buf;
1057   udp_ack->header.size = htons ((uint16_t) msize);
1058   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
1059   udp_ack->delay = htonl (delay);
1060   udp_ack->sender = *rc->plugin->env->my_identity;
1061   memcpy (&udp_ack[1], msg, ntohs (msg->size));
1062   (void) udp_send (rc->plugin, rc->src_addr, &udp_ack->header);
1063 }
1064
1065
1066 /**
1067  * Closure for 'find_receive_context'.
1068  */
1069 struct FindReceiveContext
1070 {
1071   /**
1072    * Where to store the result.
1073    */
1074   struct ReceiveContext *rc;
1075
1076   /**
1077    * Address to find.
1078    */
1079   const struct sockaddr *addr;
1080
1081   /**
1082    * Number of bytes in 'addr'.
1083    */
1084   socklen_t addr_len;
1085
1086   struct Session * session;
1087 };
1088
1089
1090 /**
1091  * Scan the heap for a receive context with the given address.
1092  *
1093  * @param cls the 'struct FindReceiveContext'
1094  * @param node internal node of the heap
1095  * @param element value stored at the node (a 'struct ReceiveContext')
1096  * @param cost cost associated with the node
1097  * @return GNUNET_YES if we should continue to iterate,
1098  *         GNUNET_NO if not.
1099  */
1100 static int
1101 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1102                       void *element, GNUNET_CONTAINER_HeapCostType cost)
1103 {
1104   struct FindReceiveContext *frc = cls;
1105   struct ReceiveContext *e = element;
1106
1107   if ((frc->addr_len == e->addr_len) &&
1108       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1109   {
1110     frc->rc = e;
1111     return GNUNET_NO;
1112   }
1113   return GNUNET_YES;
1114 }
1115
1116
1117 /**
1118  * Read and process a message from the given socket.
1119  *
1120  * @param plugin the overall plugin
1121  * @param rsock socket to read from
1122  */
1123 static void
1124 udp_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
1125 {
1126   socklen_t fromlen;
1127   char addr[32];
1128   char buf[65536];
1129   ssize_t ret;
1130   const struct GNUNET_MessageHeader *msg;
1131   const struct GNUNET_MessageHeader *ack;
1132   struct Session *peer_session;
1133   const struct UDP_ACK_Message *udp_ack;
1134   struct ReceiveContext *rc;
1135   struct GNUNET_TIME_Absolute now;
1136   struct FindReceiveContext frc;
1137   struct Session * s = NULL;
1138   struct GNUNET_TIME_Relative flow_delay;
1139
1140   fromlen = sizeof (addr);
1141   memset (&addr, 0, sizeof (addr));
1142   ret =
1143       GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
1144                                       (struct sockaddr *) &addr, &fromlen);
1145   if (ret < sizeof (struct GNUNET_MessageHeader))
1146   {
1147     GNUNET_break_op (0);
1148     return;
1149   }
1150   msg = (const struct GNUNET_MessageHeader *) buf;
1151
1152   LOG (GNUNET_ERROR_TYPE_DEBUG,
1153               "UDP received %u-byte message from `%s' type %i\n", (unsigned int) ret,
1154               GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs(msg->type));
1155
1156   if (ret != ntohs (msg->size))
1157   {
1158     GNUNET_break_op (0);
1159     return;
1160   }
1161   switch (ntohs (msg->type))
1162   {
1163   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
1164     if (ntohs (msg->size) < sizeof (struct UDPMessage))
1165     {
1166       GNUNET_break_op (0);
1167       return;
1168     }
1169     process_udp_message (plugin, (const struct UDPMessage *) msg,
1170                          (const struct sockaddr *) addr, fromlen);
1171     return;
1172   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
1173
1174     if (ntohs (msg->size) <
1175         sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
1176     {
1177       GNUNET_break_op (0);
1178       return;
1179     }
1180     udp_ack = (const struct UDP_ACK_Message *) msg;
1181     s = find_inbound_session(plugin, &udp_ack->sender, addr, fromlen);
1182     if (s != NULL)
1183     {
1184       flow_delay.rel_value = (uint64_t) ntohl(udp_ack->delay);
1185
1186       LOG (GNUNET_ERROR_TYPE_DEBUG,
1187                   "We received a sending delay of %llu\n", flow_delay.rel_value);
1188
1189       s->flow_delay_from_other_peer = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), flow_delay);
1190     }
1191     ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
1192     if (ntohs (ack->size) != ntohs (msg->size) - sizeof (struct UDP_ACK_Message))
1193     {
1194       GNUNET_break_op (0);
1195       return;
1196     }
1197 #if DEBUG_UDP
1198     LOG (GNUNET_ERROR_TYPE_DEBUG,
1199                 "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1200                 (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp->sender),
1201                 GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1202 #endif
1203
1204     peer_session = find_session (plugin, &udp_ack->sender);
1205     if (NULL == peer_session)
1206     {
1207 #if DEBUG_UDP
1208       LOG (GNUNET_ERROR_TYPE_DEBUG,
1209                   "Session for ACK not found, dropping ACK!\n");
1210 #endif
1211       return;
1212     }
1213     if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (peer_session->frag, ack))
1214       return;
1215     GNUNET_assert (GNUNET_OK ==
1216                    GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
1217                                                          &udp_ack->
1218                                                          sender.hashPubKey,
1219                                                          peer_session));
1220     plugin->last_expected_delay =
1221         GNUNET_FRAGMENT_context_destroy (peer_session->frag);
1222     if (peer_session->cont != NULL)
1223       peer_session->cont (peer_session->cont_cls, &udp_ack->sender, GNUNET_OK);
1224     GNUNET_free (peer_session);
1225     return;
1226   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1227     frc.rc = NULL;
1228     frc.addr = (const struct sockaddr *) addr;
1229     frc.addr_len = fromlen;
1230     GNUNET_CONTAINER_heap_iterate (plugin->defrags, &find_receive_context,
1231                                    &frc);
1232     now = GNUNET_TIME_absolute_get ();
1233     rc = frc.rc;
1234     if (rc == NULL)
1235     {
1236       /* need to create a new RC */
1237       rc = GNUNET_malloc (sizeof (struct ReceiveContext) + fromlen);
1238       memcpy (&rc[1], addr, fromlen);
1239       rc->src_addr = (const struct sockaddr *) &rc[1];
1240       rc->addr_len = fromlen;
1241       rc->plugin = plugin;
1242       rc->defrag =
1243           GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1244                                             UDP_MAX_MESSAGES_IN_DEFRAG, rc,
1245                                             &fragment_msg_proc, &ack_proc);
1246       rc->hnode =
1247           GNUNET_CONTAINER_heap_insert (plugin->defrags, rc,
1248                                         (GNUNET_CONTAINER_HeapCostType)
1249                                         now.abs_value);
1250     }
1251 #if DEBUG_UDP
1252     LOG (GNUNET_ERROR_TYPE_DEBUG,
1253                 "UDP processes %u-byte fragment from `%s'\n",
1254                 (unsigned int) ntohs (msg->size),
1255                 GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1256 #endif
1257
1258     if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (rc->defrag, msg))
1259     {
1260       /* keep this 'rc' from expiring */
1261       GNUNET_CONTAINER_heap_update_cost (plugin->defrags, rc->hnode,
1262                                          (GNUNET_CONTAINER_HeapCostType)
1263                                          now.abs_value);
1264     }
1265     if (GNUNET_CONTAINER_heap_get_size (plugin->defrags) >
1266         UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1267     {
1268       /* remove 'rc' that was inactive the longest */
1269       rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags);
1270       GNUNET_assert (NULL != rc);
1271       GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
1272       GNUNET_free (rc);
1273     }
1274     return;
1275   default:
1276     GNUNET_break_op (0);
1277     return;
1278   }
1279 }
1280
1281
1282 /**
1283  * We have been notified that our writeset has something to read.  We don't
1284  * know which socket needs to be read, so we have to check each one
1285  * Then reschedule this function to be called again once more is available.
1286  *
1287  * @param cls the plugin handle
1288  * @param tc the scheduling context (for rescheduling this function again)
1289  */
1290 static void
1291 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1292 {
1293   struct Plugin *plugin = cls;
1294
1295   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1296   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1297     return;
1298   if ((NULL != plugin->sockv4) &&
1299       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
1300     udp_read (plugin, plugin->sockv4);
1301   if ((NULL != plugin->sockv6) &&
1302       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
1303     udp_read (plugin, plugin->sockv6);
1304   plugin->select_task =
1305       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1306                                    GNUNET_SCHEDULER_NO_TASK,
1307                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1308                                    NULL, &udp_plugin_select, plugin);
1309
1310 }
1311
1312
1313 /**
1314  * Check if the given port is plausible (must be either our listen
1315  * port or our advertised port).  If it is neither, we return
1316  * GNUNET_SYSERR.
1317  *
1318  * @param plugin global variables
1319  * @param in_port port number to check
1320  * @return GNUNET_OK if port is either open_port or adv_port
1321  */
1322 static int
1323 check_port (struct Plugin *plugin, uint16_t in_port)
1324 {
1325   if ((in_port == plugin->port) || (in_port == plugin->aport))
1326     return GNUNET_OK;
1327   return GNUNET_SYSERR;
1328 }
1329
1330
1331 /**
1332  * Function that will be called to check if a binary address for this
1333  * plugin is well-formed and corresponds to an address for THIS peer
1334  * (as per our configuration).  Naturally, if absolutely necessary,
1335  * plugins can be a bit conservative in their answer, but in general
1336  * plugins should make sure that the address does not redirect
1337  * traffic to a 3rd party that might try to man-in-the-middle our
1338  * traffic.
1339  *
1340  * @param cls closure, should be our handle to the Plugin
1341  * @param addr pointer to the address
1342  * @param addrlen length of addr
1343  * @return GNUNET_OK if this is a plausible address for this peer
1344  *         and transport, GNUNET_SYSERR if not
1345  *
1346  */
1347 static int
1348 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1349 {
1350   struct Plugin *plugin = cls;
1351   struct IPv4UdpAddress *v4;
1352   struct IPv6UdpAddress *v6;
1353
1354   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
1355       (addrlen != sizeof (struct IPv6UdpAddress)))
1356   {
1357     GNUNET_break_op (0);
1358     return GNUNET_SYSERR;
1359   }
1360   if (addrlen == sizeof (struct IPv4UdpAddress))
1361   {
1362     v4 = (struct IPv4UdpAddress *) addr;
1363     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
1364       return GNUNET_SYSERR;
1365     if (GNUNET_OK !=
1366         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1367                                  sizeof (struct in_addr)))
1368       return GNUNET_SYSERR;
1369   }
1370   else
1371   {
1372     v6 = (struct IPv6UdpAddress *) addr;
1373     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1374     {
1375       GNUNET_break_op (0);
1376       return GNUNET_SYSERR;
1377     }
1378     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
1379       return GNUNET_SYSERR;
1380     if (GNUNET_OK !=
1381         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1382                                  sizeof (struct in6_addr)))
1383       return GNUNET_SYSERR;
1384   }
1385   return GNUNET_OK;
1386 }
1387
1388
1389 /**
1390  * Function called for a quick conversion of the binary address to
1391  * a numeric address.  Note that the caller must not free the
1392  * address and that the next call to this function is allowed
1393  * to override the address again.
1394  *
1395  * @param cls closure
1396  * @param addr binary address
1397  * @param addrlen length of the address
1398  * @return string representing the same address
1399  */
1400 static const char *
1401 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
1402 {
1403   static char rbuf[INET6_ADDRSTRLEN + 10];
1404   char buf[INET6_ADDRSTRLEN];
1405   const void *sb;
1406   struct in_addr a4;
1407   struct in6_addr a6;
1408   const struct IPv4UdpAddress *t4;
1409   const struct IPv6UdpAddress *t6;
1410   int af;
1411   uint16_t port;
1412
1413   if (addrlen == sizeof (struct IPv6UdpAddress))
1414   {
1415     t6 = addr;
1416     af = AF_INET6;
1417     port = ntohs (t6->u6_port);
1418     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
1419     sb = &a6;
1420   }
1421   else if (addrlen == sizeof (struct IPv4UdpAddress))
1422   {
1423     t4 = addr;
1424     af = AF_INET;
1425     port = ntohs (t4->u4_port);
1426     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
1427     sb = &a4;
1428   }
1429   else
1430   {
1431     GNUNET_break_op (0);
1432     return NULL;
1433   }
1434   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
1435   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
1436                    buf, port);
1437   return rbuf;
1438 }
1439
1440
1441 /**
1442  * Closure for 'append_port'.
1443  */
1444 struct PrettyPrinterContext
1445 {
1446   /**
1447    * Function to call with the result.
1448    */
1449   GNUNET_TRANSPORT_AddressStringCallback asc;
1450
1451   /**
1452    * Clsoure for 'asc'.
1453    */
1454   void *asc_cls;
1455
1456   /**
1457    * Port to add after the IP address.
1458    */
1459   uint16_t port;
1460 };
1461
1462
1463 /**
1464  * Append our port and forward the result.
1465  *
1466  * @param cls a 'struct PrettyPrinterContext'
1467  * @param hostname result from DNS resolver
1468  */
1469 static void
1470 append_port (void *cls, const char *hostname)
1471 {
1472   struct PrettyPrinterContext *ppc = cls;
1473   char *ret;
1474
1475   if (hostname == NULL)
1476   {
1477     ppc->asc (ppc->asc_cls, NULL);
1478     GNUNET_free (ppc);
1479     return;
1480   }
1481   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1482   ppc->asc (ppc->asc_cls, ret);
1483   GNUNET_free (ret);
1484 }
1485
1486
1487 /**
1488  * Convert the transports address to a nice, human-readable
1489  * format.
1490  *
1491  * @param cls closure
1492  * @param type name of the transport that generated the address
1493  * @param addr one of the addresses of the host, NULL for the last address
1494  *        the specific address format depends on the transport
1495  * @param addrlen length of the address
1496  * @param numeric should (IP) addresses be displayed in numeric form?
1497  * @param timeout after how long should we give up?
1498  * @param asc function to call on each string
1499  * @param asc_cls closure for asc
1500  */
1501 static void
1502 udp_plugin_address_pretty_printer (void *cls, const char *type,
1503                                    const void *addr, size_t addrlen,
1504                                    int numeric,
1505                                    struct GNUNET_TIME_Relative timeout,
1506                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1507                                    void *asc_cls)
1508 {
1509   struct PrettyPrinterContext *ppc;
1510   const void *sb;
1511   size_t sbs;
1512   struct sockaddr_in a4;
1513   struct sockaddr_in6 a6;
1514   const struct IPv4UdpAddress *u4;
1515   const struct IPv6UdpAddress *u6;
1516   uint16_t port;
1517
1518   if (addrlen == sizeof (struct IPv6UdpAddress))
1519   {
1520     u6 = addr;
1521     memset (&a6, 0, sizeof (a6));
1522     a6.sin6_family = AF_INET6;
1523 #if HAVE_SOCKADDR_IN_SIN_LEN
1524     a6.sin6_len = sizeof (a6);
1525 #endif
1526     a6.sin6_port = u6->u6_port;
1527     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
1528     port = ntohs (u6->u6_port);
1529     sb = &a6;
1530     sbs = sizeof (a6);
1531   }
1532   else if (addrlen == sizeof (struct IPv4UdpAddress))
1533   {
1534     u4 = addr;
1535     memset (&a4, 0, sizeof (a4));
1536     a4.sin_family = AF_INET;
1537 #if HAVE_SOCKADDR_IN_SIN_LEN
1538     a4.sin_len = sizeof (a4);
1539 #endif
1540     a4.sin_port = u4->u4_port;
1541     a4.sin_addr.s_addr = u4->ipv4_addr;
1542     port = ntohs (u4->u4_port);
1543     sb = &a4;
1544     sbs = sizeof (a4);
1545   }
1546   else
1547   {
1548     /* invalid address */
1549     GNUNET_break_op (0);
1550     asc (asc_cls, NULL);
1551     return;
1552   }
1553   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1554   ppc->asc = asc;
1555   ppc->asc_cls = asc_cls;
1556   ppc->port = port;
1557   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1558 }
1559
1560
1561 /**
1562  * Our external IP address/port mapping has changed.
1563  *
1564  * @param cls closure, the 'struct LocalAddrList'
1565  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
1566  *     the previous (now invalid) one
1567  * @param addr either the previous or the new public IP address
1568  * @param addrlen actual lenght of the address
1569  */
1570 static void
1571 udp_nat_port_map_callback (void *cls, int add_remove,
1572                            const struct sockaddr *addr, socklen_t addrlen)
1573 {
1574   struct Plugin *plugin = cls;
1575   struct IPv4UdpAddress u4;
1576   struct IPv6UdpAddress u6;
1577   void *arg;
1578   size_t args;
1579
1580   /* convert 'addr' to our internal format */
1581   switch (addr->sa_family)
1582   {
1583   case AF_INET:
1584     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
1585     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1586     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
1587     arg = &u4;
1588     args = sizeof (u4);
1589     break;
1590   case AF_INET6:
1591     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
1592     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
1593             sizeof (struct in6_addr));
1594     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1595     arg = &u6;
1596     args = sizeof (u6);
1597     break;
1598   default:
1599     GNUNET_break (0);
1600     return;
1601   }
1602   /* modify our published address list */
1603   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
1604 }
1605
1606
1607 /**
1608  * The exported method. Makes the core api available via a global and
1609  * returns the udp transport API.
1610  *
1611  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1612  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1613  */
1614 void *
1615 libgnunet_plugin_transport_udp_init (void *cls)
1616 {
1617   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1618   unsigned long long port;
1619   unsigned long long aport;
1620   struct GNUNET_TRANSPORT_PluginFunctions *api;
1621   struct Plugin *plugin;
1622   int sockets_created;
1623   struct sockaddr_in serverAddrv4;
1624   struct sockaddr_in6 serverAddrv6;
1625   struct sockaddr *serverAddr;
1626   struct sockaddr *addrs[2];
1627   socklen_t addrlens[2];
1628   socklen_t addrlen;
1629   unsigned int tries;
1630   unsigned long long udp_max_bps;
1631
1632   if (GNUNET_OK !=
1633       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
1634                                              &port))
1635     port = 2086;
1636   if (GNUNET_OK !=
1637       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1638                                              "MAX_BPS", &udp_max_bps))
1639     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1640   if (GNUNET_OK !=
1641       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1642                                              "ADVERTISED_PORT", &aport))
1643     aport = port;
1644   if (port > 65535)
1645   {
1646     LOG (GNUNET_ERROR_TYPE_WARNING,
1647                 _("Given `%s' option is out of range: %llu > %u\n"), "PORT",
1648                 port, 65535);
1649     return NULL;
1650   }
1651   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
1652   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
1653
1654   plugin = GNUNET_malloc (sizeof (struct Plugin));
1655   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1656                                  GNUNET_BANDWIDTH_value_init ((uint32_t)
1657                                                               udp_max_bps), 30);
1658   plugin->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
1659   plugin->port = port;
1660   plugin->aport = aport;
1661   plugin->env = env;
1662   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1663   api->cls = plugin;
1664
1665   api->send = &udp_plugin_send;
1666   api->disconnect = &udp_disconnect;
1667   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1668   api->address_to_string = &udp_address_to_string;
1669   api->check_address = &udp_plugin_check_address;
1670
1671   if (GNUNET_YES ==
1672       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1673                                              "BINDTO", &plugin->bind4_address))
1674   {
1675     LOG (GNUNET_ERROR_TYPE_DEBUG,
1676                 "Binding udp plugin to specific address: `%s'\n",
1677                 plugin->bind4_address);
1678     if (1 != inet_pton (AF_INET, plugin->bind4_address, &serverAddrv4.sin_addr))
1679     {
1680       GNUNET_free (plugin->bind4_address);
1681       GNUNET_free (plugin);
1682       GNUNET_free (api);
1683       return NULL;
1684     }
1685   }
1686
1687   if (GNUNET_YES ==
1688       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
1689                                              "BINDTO6", &plugin->bind6_address))
1690   {
1691     LOG (GNUNET_ERROR_TYPE_DEBUG,
1692                 "Binding udp plugin to specific address: `%s'\n",
1693                 plugin->bind6_address);
1694     if (1 !=
1695         inet_pton (AF_INET6, plugin->bind6_address, &serverAddrv6.sin6_addr))
1696     {
1697       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1698                   plugin->bind6_address);
1699       GNUNET_free_non_null (plugin->bind4_address);
1700       GNUNET_free (plugin->bind6_address);
1701       GNUNET_free (plugin);
1702       GNUNET_free (api);
1703       return NULL;
1704     }
1705   }
1706
1707   plugin->defrags =
1708       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1709   plugin->sessions =
1710       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
1711                                             * 2);
1712   plugin->inbound_sessions =
1713       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
1714                                             * 2);
1715   sockets_created = 0;
1716   if ((GNUNET_YES !=
1717        GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "nat",
1718                                              "DISABLEV6")))
1719   {
1720     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
1721     if (NULL == plugin->sockv6)
1722     {
1723       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1724     }
1725     else
1726     {
1727 #if HAVE_SOCKADDR_IN_SIN_LEN
1728       serverAddrv6.sin6_len = sizeof (serverAddrv6);
1729 #endif
1730       serverAddrv6.sin6_family = AF_INET6;
1731       serverAddrv6.sin6_addr = in6addr_any;
1732       serverAddrv6.sin6_port = htons (plugin->port);
1733       addrlen = sizeof (serverAddrv6);
1734       serverAddr = (struct sockaddr *) &serverAddrv6;
1735 #if DEBUG_UDP
1736       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
1737                   ntohs (serverAddrv6.sin6_port));
1738 #endif
1739       tries = 0;
1740       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
1741              GNUNET_OK)
1742       {
1743         serverAddrv6.sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
1744 #if DEBUG_UDP
1745         LOG (GNUNET_ERROR_TYPE_DEBUG,
1746                     "IPv6 Binding failed, trying new port %d\n",
1747                     ntohs (serverAddrv6.sin6_port));
1748 #endif
1749         tries++;
1750         if (tries > 10)
1751         {
1752           GNUNET_NETWORK_socket_close (plugin->sockv6);
1753           plugin->sockv6 = NULL;
1754           break;
1755         }
1756       }
1757       if (plugin->sockv6 != NULL)
1758       {
1759         addrs[sockets_created] = (struct sockaddr *) &serverAddrv6;
1760         addrlens[sockets_created] = sizeof (serverAddrv6);
1761         sockets_created++;
1762       }
1763     }
1764   }
1765
1766   plugin->mst =
1767       GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
1768   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
1769   if (NULL == plugin->sockv4)
1770   {
1771     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
1772   }
1773   else
1774   {
1775 #if HAVE_SOCKADDR_IN_SIN_LEN
1776     serverAddrv4.sin_len = sizeof (serverAddrv4);
1777 #endif
1778     serverAddrv4.sin_family = AF_INET;
1779     serverAddrv4.sin_addr.s_addr = INADDR_ANY;
1780     serverAddrv4.sin_port = htons (plugin->port);
1781     addrlen = sizeof (serverAddrv4);
1782     serverAddr = (struct sockaddr *) &serverAddrv4;
1783 #if DEBUG_UDP
1784     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
1785                 ntohs (serverAddrv4.sin_port));
1786 #endif
1787     tries = 0;
1788     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
1789            GNUNET_OK)
1790     {
1791       serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
1792 #if DEBUG_UDP
1793       LOG (GNUNET_ERROR_TYPE_DEBUG,
1794                   "IPv4 Binding failed, trying new port %d\n",
1795                   ntohs (serverAddrv4.sin_port));
1796 #endif
1797       tries++;
1798       if (tries > 10)
1799       {
1800         GNUNET_NETWORK_socket_close (plugin->sockv4);
1801         plugin->sockv4 = NULL;
1802         break;
1803       }
1804     }
1805     if (plugin->sockv4 != NULL)
1806     {
1807       addrs[sockets_created] = (struct sockaddr *) &serverAddrv4;
1808       addrlens[sockets_created] = sizeof (serverAddrv4);
1809       sockets_created++;
1810     }
1811   }
1812
1813   plugin->rs = GNUNET_NETWORK_fdset_create ();
1814   GNUNET_NETWORK_fdset_zero (plugin->rs);
1815   if (NULL != plugin->sockv4)
1816     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
1817   if (NULL != plugin->sockv6)
1818     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
1819
1820   plugin->select_task =
1821       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1822                                    GNUNET_SCHEDULER_NO_TASK,
1823                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1824                                    NULL, &udp_plugin_select, plugin);
1825   if (sockets_created == 0)
1826     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
1827   plugin->nat =
1828       GNUNET_NAT_register (env->cfg, GNUNET_NO, port, sockets_created,
1829                            (const struct sockaddr **) addrs, addrlens,
1830                            &udp_nat_port_map_callback, NULL, plugin);
1831   return api;
1832 }
1833
1834 /**
1835  * Shutdown the plugin.
1836  *
1837  * @param cls our 'struct GNUNET_TRANSPORT_PluginFunctions'
1838  * @return NULL
1839  */
1840 void *
1841 libgnunet_plugin_transport_udp_done (void *cls)
1842 {
1843   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1844   struct Plugin *plugin = api->cls;
1845   struct ReceiveContext *rc;
1846
1847   /* FIXME: clean up heap and hashmap */
1848   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &destroy_session,
1849                                          NULL);
1850   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1851   plugin->sessions = NULL;
1852   GNUNET_CONTAINER_multihashmap_iterate (plugin->inbound_sessions, &destroy_inbound_session,
1853                                          NULL);
1854   GNUNET_CONTAINER_multihashmap_destroy (plugin->inbound_sessions);
1855   plugin->inbound_sessions = NULL;
1856   while (NULL != (rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags)))
1857   {
1858     GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
1859     GNUNET_free (rc);
1860   }
1861   GNUNET_CONTAINER_heap_destroy (plugin->defrags);
1862
1863   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1864   {
1865     GNUNET_SCHEDULER_cancel (plugin->select_task);
1866     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1867   }
1868   if (plugin->sockv4 != NULL)
1869   {
1870     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
1871     plugin->sockv4 = NULL;
1872   }
1873   if (plugin->sockv6 != NULL)
1874   {
1875     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
1876     plugin->sockv6 = NULL;
1877   }
1878   GNUNET_SERVER_mst_destroy (plugin->mst);
1879   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1880   GNUNET_NAT_unregister (plugin->nat);
1881   plugin->nat = NULL;
1882   GNUNET_free (plugin);
1883   GNUNET_free (api);
1884   return NULL;
1885 }
1886
1887 /* end of plugin_transport_udp.c */