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