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