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