486f72364f5993005b77f4023169fc69aa5436d7
[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 GNUNET_NETWORK_STRUCT_BEGIN
74
75 /**
76  * UDP Message-Packet header (after defragmentation).
77  */
78 struct UDPMessage
79 {
80   /**
81    * Message header.
82    */
83   struct GNUNET_MessageHeader header;
84
85   /**
86    * Always zero for now.
87    */
88   uint32_t reserved;
89
90   /**
91    * What is the identity of the sender
92    */
93   struct GNUNET_PeerIdentity sender;
94
95 };
96
97 /**
98  * UDP ACK Message-Packet header (after defragmentation).
99  */
100 struct UDP_ACK_Message
101 {
102   /**
103    * Message header.
104    */
105   struct GNUNET_MessageHeader header;
106
107   /**
108    * Desired delay for flow control
109    */
110   uint32_t delay;
111
112   /**
113    * What is the identity of the sender
114    */
115   struct GNUNET_PeerIdentity sender;
116 };
117
118
119 struct UDP_Beacon_Message
120 {
121  /**
122   * Message header.
123   */
124   struct GNUNET_MessageHeader header;
125
126  /**
127   * What is the identity of the sender
128   */
129   struct GNUNET_PeerIdentity sender;
130 };
131
132
133 /**
134  * Network format for IPv4 addresses.
135  */
136 struct IPv4UdpAddress
137 {
138   /**
139    * IPv4 address, in network byte order.
140    */
141   uint32_t ipv4_addr GNUNET_PACKED;
142
143   /**
144    * Port number, in network byte order.
145    */
146   uint16_t u4_port GNUNET_PACKED;
147 };
148
149
150 /**
151  * Network format for IPv6 addresses.
152  */
153 struct IPv6UdpAddress
154 {
155
156   /**
157    * IPv6 address.
158    */
159   struct in6_addr ipv6_addr GNUNET_PACKED;
160
161   /**
162    * Port number, in network byte order.
163    */
164   uint16_t u6_port GNUNET_PACKED;
165 };
166 GNUNET_NETWORK_STRUCT_END
167
168 /* Forward definition */
169 struct Plugin;
170
171
172 /**
173  * Session with another peer.  FIXME: why not make this into
174  * a regular 'struct Session' and pass it around!?
175  */
176 struct Session
177 {
178
179   /**
180    * Which peer is this session for?
181    */
182   struct GNUNET_PeerIdentity target;
183
184   /**
185    * Pointer to the global plugin struct.
186    */
187   struct Plugin *plugin;
188
189   /**
190    * Address of the other peer
191    */
192   const struct sockaddr *sock_addr;
193
194   size_t addrlen;
195
196   /**
197    * ATS network type in NBO
198    */
199   uint32_t ats_address_network_type;
200
201   /**
202    * Function to call upon completion of the transmission.
203    */
204   GNUNET_TRANSPORT_TransmitContinuation cont;
205
206   /**
207    * Closure for 'cont'.
208    */
209   void *cont_cls;
210
211   /**
212    * Current outgoing message to this peer.
213    */
214   struct GNUNET_FRAGMENT_Context *frag;
215
216   struct GNUNET_TIME_Absolute valid_until;
217
218   GNUNET_SCHEDULER_TaskIdentifier invalidation_task;
219
220   GNUNET_SCHEDULER_TaskIdentifier delayed_cont_task;
221
222   /**
223    * Desired delay for next sending we send to other peer
224    */
225   struct GNUNET_TIME_Relative flow_delay_for_other_peer;
226
227   /**
228    * Desired delay for next sending we received from other peer
229    */
230   struct GNUNET_TIME_Absolute flow_delay_from_other_peer;
231 };
232
233
234 /**
235  * Data structure to track defragmentation contexts based
236  * on the source of the UDP traffic.
237  */
238 struct ReceiveContext
239 {
240
241   /**
242    * Defragmentation context.
243    */
244   struct GNUNET_DEFRAGMENT_Context *defrag;
245
246   /**
247    * Source address this receive context is for (allocated at the
248    * end of the struct).
249    */
250   const struct sockaddr *src_addr;
251
252   /**
253    * Reference to master plugin struct.
254    */
255   struct Plugin *plugin;
256
257   /**
258    * Node in the defrag heap.
259    */
260   struct GNUNET_CONTAINER_HeapNode *hnode;
261
262   /**
263    * Length of 'src_addr'
264    */
265   size_t addr_len;
266
267   struct GNUNET_PeerIdentity id;
268
269 };
270
271 struct BroadcastAddress
272 {
273   struct BroadcastAddress *next;
274   struct BroadcastAddress *prev;
275
276   void *addr;
277   socklen_t addrlen;
278 };
279
280
281 /**
282  * Encapsulation of all of the state of the plugin.
283  */
284 struct Plugin
285 {
286
287   /**
288    * Our environment.
289    */
290   struct GNUNET_TRANSPORT_PluginEnvironment *env;
291
292   /**
293    * Session of peers with whom we are currently connected,
294    * map of peer identity to 'struct PeerSession'.
295    */
296   struct GNUNET_CONTAINER_MultiHashMap *sessions;
297
298   /**
299    * Session of peers with whom we are currently connected,
300    * map of peer identity to 'struct PeerSession'.
301    */
302   struct GNUNET_CONTAINER_MultiHashMap *inbound_sessions;
303
304   /**
305    * Heap with all of our defragmentation activities.
306    */
307   struct GNUNET_CONTAINER_Heap *defrags;
308
309   /**
310    * ID of select task
311    */
312   GNUNET_SCHEDULER_TaskIdentifier select_task;
313
314   /**
315    * Tokenizer for inbound messages.
316    */
317   struct GNUNET_SERVER_MessageStreamTokenizer *mst;
318
319   /**
320    * Bandwidth tracker to limit global UDP traffic.
321    */
322   struct GNUNET_BANDWIDTH_Tracker tracker;
323
324   /**
325    * Address we were told to bind to exclusively (IPv4).
326    */
327   char *bind4_address;
328
329   /**
330    * Address we were told to bind to exclusively (IPv6).
331    */
332   char *bind6_address;
333
334   /**
335    * Handle to NAT traversal support.
336    */
337   struct GNUNET_NAT_Handle *nat;
338
339   /**
340    * FD Read set
341    */
342   struct GNUNET_NETWORK_FDSet *rs;
343
344   /**
345    * The read socket for IPv4
346    */
347   struct GNUNET_NETWORK_Handle *sockv4;
348
349   /**
350    * The read socket for IPv6
351    */
352   struct GNUNET_NETWORK_Handle *sockv6;
353
354   /**
355    * Beacon broadcasting
356    * -------------------
357    */
358
359   /**
360    * Broadcast interval
361    */
362   struct GNUNET_TIME_Relative broadcast_interval;
363
364   /**
365    * Broadcast with IPv4
366    */
367   int broadcast_ipv4;
368
369   /**
370    * Broadcast with IPv6
371    */
372   int broadcast_ipv6;
373
374
375   /**
376    * Tokenizer for inbound messages.
377    */
378   struct GNUNET_SERVER_MessageStreamTokenizer *broadcast_ipv6_mst;
379   struct GNUNET_SERVER_MessageStreamTokenizer *broadcast_ipv4_mst;
380
381   /**
382    * ID of select broadcast task
383    */
384   GNUNET_SCHEDULER_TaskIdentifier send_ipv4_broadcast_task;
385
386   /**
387    * ID of select broadcast task
388    */
389   GNUNET_SCHEDULER_TaskIdentifier send_ipv6_broadcast_task;
390
391   /**
392    * IPv6 multicast address
393    */
394   struct sockaddr_in6 ipv6_multicast_address;
395
396   /**
397    * DLL of IPv4 broadcast addresses
398    */
399   struct BroadcastAddress *ipv4_broadcast_tail;
400   struct BroadcastAddress *ipv4_broadcast_head;
401
402
403   /**
404    * expected delay for ACKs
405    */
406   struct GNUNET_TIME_Relative last_expected_delay;
407
408   /**
409    * Port we broadcasting on.
410    */
411   uint16_t broadcast_port;
412
413   /**
414    * Port we listen on.
415    */
416   uint16_t port;
417
418   /**
419    * Port we advertise on.
420    */
421   uint16_t aport;
422
423 };
424
425 struct PeerSessionIteratorContext
426 {
427   struct Session *result;
428   const void *addr;
429   size_t addrlen;
430 };
431
432
433 /**
434  * Lookup the session for the given peer.
435  *
436  * @param plugin the plugin
437  * @param peer peer's identity
438  * @return NULL if we have no session
439  */
440 static struct Session *
441 find_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *peer)
442 {
443   return GNUNET_CONTAINER_multihashmap_get (plugin->sessions,
444                                             &peer->hashPubKey);
445 }
446
447
448 static int
449 inbound_session_iterator (void *cls, const GNUNET_HashCode * key, void *value)
450 {
451   struct PeerSessionIteratorContext *psc = cls;
452   struct Session *s = value;
453
454   if (s->addrlen == psc->addrlen)
455   {
456     if (0 == memcmp (&s[1], psc->addr, s->addrlen))
457       psc->result = s;
458   }
459   if (psc->result != NULL)
460     return GNUNET_NO;
461   return GNUNET_YES;
462 }
463
464
465 /**
466  * Lookup the session for the given peer.
467  *
468  * @param plugin the plugin
469  * @param peer peer's identity
470  * @param addr address
471  * @param addrlen address length
472  * @return NULL if we have no session
473  */
474 static struct Session *
475 find_inbound_session (struct Plugin *plugin,
476                       const struct GNUNET_PeerIdentity *peer, const void *addr,
477                       size_t addrlen)
478 {
479   struct PeerSessionIteratorContext psc;
480
481   psc.result = NULL;
482   psc.addrlen = addrlen;
483   psc.addr = addr;
484
485   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->inbound_sessions,
486                                               &peer->hashPubKey,
487                                               &inbound_session_iterator, &psc);
488   return psc.result;
489 }
490
491
492 static int
493 inbound_session_by_addr_iterator (void *cls, const GNUNET_HashCode * key,
494                                   void *value)
495 {
496   struct PeerSessionIteratorContext *psc = cls;
497   struct Session *s = value;
498
499   if (s->addrlen == psc->addrlen)
500   {
501     if (0 == memcmp (&s[1], psc->addr, s->addrlen))
502       psc->result = s;
503   }
504   if (psc->result != NULL)
505     return GNUNET_NO;
506   else
507     return GNUNET_YES;
508 };
509
510 /**
511  * Lookup the session for the given peer just by address.
512  *
513  * @param plugin the plugin
514  * @param addr address
515  * @param addrlen address length
516  * @return NULL if we have no session
517  */
518 static struct Session *
519 find_inbound_session_by_addr (struct Plugin *plugin, const void *addr,
520                               size_t addrlen)
521 {
522   struct PeerSessionIteratorContext psc;
523
524   psc.result = NULL;
525   psc.addrlen = addrlen;
526   psc.addr = addr;
527
528   GNUNET_CONTAINER_multihashmap_iterate (plugin->inbound_sessions,
529                                          &inbound_session_by_addr_iterator,
530                                          &psc);
531   return psc.result;
532 }
533
534
535 /**
536  * Destroy a session, plugin is being unloaded.
537  *
538  * @param cls unused
539  * @param key hash of public key of target peer
540  * @param value a 'struct PeerSession*' to clean up
541  * @return GNUNET_OK (continue to iterate)
542  */
543 static int
544 destroy_session (void *cls, const GNUNET_HashCode * key, void *value)
545 {
546   struct Session *peer_session = value;
547
548   GNUNET_assert (GNUNET_YES ==
549                  GNUNET_CONTAINER_multihashmap_remove (peer_session->
550                                                        plugin->sessions,
551                                                        &peer_session->
552                                                        target.hashPubKey,
553                                                        peer_session));
554   if (peer_session->frag != NULL)
555     GNUNET_FRAGMENT_context_destroy (peer_session->frag);
556   if (GNUNET_SCHEDULER_NO_TASK != peer_session->delayed_cont_task)
557     GNUNET_SCHEDULER_cancel (peer_session->delayed_cont_task);
558   GNUNET_free (peer_session);
559   return GNUNET_OK;
560 }
561
562
563 /**
564  * Destroy a session, plugin is being unloaded.
565  *
566  * @param cls unused
567  * @param key hash of public key of target peer
568  * @param value a 'struct PeerSession*' to clean up
569  * @return GNUNET_OK (continue to iterate)
570  */
571 static int
572 destroy_inbound_session (void *cls, const GNUNET_HashCode * key, void *value)
573 {
574   struct Session *s = value;
575
576   if (s->invalidation_task != GNUNET_SCHEDULER_NO_TASK)
577     GNUNET_SCHEDULER_cancel (s->invalidation_task);
578   if (GNUNET_SCHEDULER_NO_TASK != s->delayed_cont_task)
579     GNUNET_SCHEDULER_cancel (s->delayed_cont_task);
580   GNUNET_CONTAINER_multihashmap_remove (s->plugin->inbound_sessions,
581                                         &s->target.hashPubKey, s);
582   GNUNET_free (s);
583   return GNUNET_OK;
584 }
585
586
587 /**
588  * Disconnect from a remote node.  Clean up session if we have one for this peer
589  *
590  * @param cls closure for this call (should be handle to Plugin)
591  * @param target the peeridentity of the peer to disconnect
592  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
593  */
594 static void
595 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
596 {
597   struct Plugin *plugin = cls;
598   struct Session *session;
599
600   session = find_session (plugin, target);
601   if (NULL == session)
602     return;
603   GNUNET_assert (GNUNET_OK ==
604                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
605                                                        &target->hashPubKey,
606                                                        session));
607
608   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->inbound_sessions,
609                                               &target->hashPubKey,
610                                               &destroy_inbound_session, NULL);
611   plugin->last_expected_delay = GNUNET_FRAGMENT_context_destroy (session->frag);
612   if (GNUNET_SCHEDULER_NO_TASK != session->delayed_cont_task)
613     GNUNET_SCHEDULER_cancel (session->delayed_cont_task);
614   if (session->cont != NULL)
615     session->cont (session->cont_cls, target, GNUNET_SYSERR);
616   GNUNET_free (session);
617 }
618
619
620 /**
621  * Creates a new outbound session the transport service will use to send data to the
622  * peer
623  *
624  * @param cls the plugin
625  * @param address the address
626  * @return the session or NULL of max connections exceeded
627  */
628
629 static struct Session *
630 udp_plugin_get_session (void *cls,
631                   const struct GNUNET_HELLO_Address *address)
632 {
633   struct Session * s = NULL;
634   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "To be implemented\n");
635   GNUNET_break (0);
636   return s;
637 }
638
639 /**
640  * Function that can be used by the transport service to transmit
641  * a message using the plugin.   Note that in the case of a
642  * peer disconnecting, the continuation MUST be called
643  * prior to the disconnect notification itself.  This function
644  * will be called with this peer's HELLO message to initiate
645  * a fresh connection to another peer.
646  *
647  * @param cls closure
648  * @param session which session must be used
649  * @param msgbuf the message to transmit
650  * @param msgbuf_size number of bytes in 'msgbuf'
651  * @param priority how important is the message (most plugins will
652  *                 ignore message priority and just FIFO)
653  * @param to how long to wait at most for the transmission (does not
654  *                require plugins to discard the message after the timeout,
655  *                just advisory for the desired delay; most plugins will ignore
656  *                this as well)
657  * @param cont continuation to call once the message has
658  *        been transmitted (or if the transport is ready
659  *        for the next transmission call; or if the
660  *        peer disconnected...); can be NULL
661  * @param cont_cls closure for cont
662  * @return number of bytes used (on the physical network, with overheads);
663  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
664  *         and does NOT mean that the message was not transmitted (DV)
665  */
666 static ssize_t
667 udp_plugin_send (void *cls,
668                   struct Session *session,
669                   const char *msgbuf, size_t msgbuf_size,
670                   unsigned int priority,
671                   struct GNUNET_TIME_Relative to,
672                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
673 {
674   ssize_t sent = -1;
675   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "To be implemented\n");
676   GNUNET_break (0);
677   return sent;
678 }
679
680
681 /**
682  * Actually send out the message.
683  *
684  * @param plugin the plugin
685  * @param sa the address to send the message to
686  * @param msg message to transmit
687  * @return the number of bytes written
688  */
689 static ssize_t
690 udp_send (struct Plugin *plugin, const struct sockaddr *sa,
691           const struct GNUNET_MessageHeader *msg)
692 {
693   ssize_t sent;
694   size_t slen;
695
696   switch (sa->sa_family)
697   {
698   case AF_INET:
699     if (NULL == plugin->sockv4)
700       return 0;
701     sent =
702         GNUNET_NETWORK_socket_sendto (plugin->sockv4, msg, ntohs (msg->size),
703                                       sa, slen = sizeof (struct sockaddr_in));
704     break;
705   case AF_INET6:
706     if (NULL == plugin->sockv6)
707       return 0;
708     sent =
709         GNUNET_NETWORK_socket_sendto (plugin->sockv6, msg, ntohs (msg->size),
710                                       sa, slen = sizeof (struct sockaddr_in6));
711     break;
712   default:
713     GNUNET_break (0);
714     return 0;
715   }
716   if (GNUNET_SYSERR == sent)
717   {
718     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
719     LOG (GNUNET_ERROR_TYPE_ERROR,
720          "UDP transmited %u-byte message to %s (%d: %s)\n",
721          (unsigned int) ntohs (msg->size), GNUNET_a2s (sa, slen), (int) sent,
722          (sent < 0) ? STRERROR (errno) : "ok");
723
724   }
725   LOG (GNUNET_ERROR_TYPE_DEBUG,
726        "UDP transmited %u-byte message to %s (%d: %s)\n",
727        (unsigned int) ntohs (msg->size), GNUNET_a2s (sa, slen), (int) sent,
728        (sent < 0) ? STRERROR (errno) : "ok");
729   return sent;
730 }
731
732
733 /**
734  * Function that is called with messages created by the fragmentation
735  * module.  In the case of the 'proc' callback of the
736  * GNUNET_FRAGMENT_context_create function, this function must
737  * eventually call 'GNUNET_FRAGMENT_context_transmission_done'.
738  *
739  * @param cls closure, the 'struct PeerSession'
740  * @param msg the message that was created
741  */
742 static void
743 send_fragment (void *cls, const struct GNUNET_MessageHeader *msg)
744 {
745   struct Session *session = cls;
746
747   udp_send (session->plugin, session->sock_addr, msg);
748   GNUNET_FRAGMENT_context_transmission_done (session->frag);
749 }
750
751
752 static struct Session *
753 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
754                 const void *addr, size_t addrlen,
755                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
756 {
757   struct Session *peer_session;
758   const struct IPv4UdpAddress *t4;
759   const struct IPv6UdpAddress *t6;
760   struct sockaddr_in *v4;
761   struct sockaddr_in6 *v6;
762   size_t len;
763   struct GNUNET_ATS_Information ats;
764
765   switch (addrlen)
766   {
767   case sizeof (struct IPv4UdpAddress):
768     if (NULL == plugin->sockv4)
769     {
770       return NULL;
771     }
772     t4 = addr;
773     peer_session =
774         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
775     len = sizeof (struct sockaddr_in);
776     v4 = (struct sockaddr_in *) &peer_session[1];
777     v4->sin_family = AF_INET;
778 #if HAVE_SOCKADDR_IN_SIN_LEN
779     v4->sin_len = sizeof (struct sockaddr_in);
780 #endif
781     v4->sin_port = t4->u4_port;
782     v4->sin_addr.s_addr = t4->ipv4_addr;
783     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
784     break;
785   case sizeof (struct IPv6UdpAddress):
786     if (NULL == plugin->sockv6)
787     {
788       return NULL;
789     }
790     t6 = addr;
791     peer_session =
792         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
793     len = sizeof (struct sockaddr_in6);
794     v6 = (struct sockaddr_in6 *) &peer_session[1];
795     v6->sin6_family = AF_INET6;
796 #if HAVE_SOCKADDR_IN_SIN_LEN
797     v6->sin6_len = sizeof (struct sockaddr_in6);
798 #endif
799     v6->sin6_port = t6->u6_port;
800     v6->sin6_addr = t6->ipv6_addr;
801     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
802     break;
803   default:
804     /* Must have a valid address to send to */
805     GNUNET_break_op (0);
806     return NULL;
807   }
808
809   peer_session->ats_address_network_type = ats.value;
810   peer_session->valid_until = GNUNET_TIME_absolute_get_zero ();
811   peer_session->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
812   peer_session->addrlen = len;
813   peer_session->target = *target;
814   peer_session->plugin = plugin;
815   peer_session->sock_addr = (const struct sockaddr *) &peer_session[1];
816   peer_session->cont = cont;
817   peer_session->cont_cls = cont_cls;
818
819   return peer_session;
820 }
821
822 static const char *
823 udp_address_to_string (void *cls, const void *addr, size_t addrlen);
824
825
826 static void
827 udp_call_continuation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
828 {
829   struct Session *s = cls;
830   GNUNET_TRANSPORT_TransmitContinuation cont = s->cont;
831
832   s->delayed_cont_task = GNUNET_SCHEDULER_NO_TASK;
833   s->cont = NULL;
834   cont (s->cont_cls, &s->target, GNUNET_OK);
835 }
836
837
838 /**
839  * Function that can be used by the transport service to transmit
840  * a message using the plugin.
841  *
842  * @param cls closure
843  * @param target who should receive this message (ignored by UDP)
844  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
845  * @param msgbuf_size the size of the msgbuf to send
846  * @param priority how important is the message (ignored by UDP)
847  * @param timeout when should we time out (give up) if we can not transmit?
848  * @param session identifier used for this session (NULL for UDP)
849  * @param addr the addr to send the message to
850  * @param addrlen the len of addr
851  * @param force_address not used, we had better have an address to send to
852  *        because we are stateless!!
853  * @param cont continuation to call once the message has
854  *        been transmitted (or if the transport is ready
855  *        for the next transmission call; or if the
856  *        peer disconnected...)
857  * @param cont_cls closure for cont
858  *
859  * @return the number of bytes written (may return 0 and the message can
860  *         still be transmitted later!)
861  */
862 static ssize_t
863 udp_plugin_send_old (void *cls, const struct GNUNET_PeerIdentity *target,
864                  const char *msgbuf, size_t msgbuf_size, unsigned int priority,
865                  struct GNUNET_TIME_Relative timeout, struct Session *session,
866                  const void *addr, size_t addrlen, int force_address,
867                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
868 {
869   struct Plugin *plugin = cls;
870   struct Session *peer_session;
871   struct Session *s;
872   const struct IPv4UdpAddress *t4;
873   const struct IPv6UdpAddress *t6;
874   size_t mlen = msgbuf_size + sizeof (struct UDPMessage);
875   char mbuf[mlen];
876   struct UDPMessage *udp;
877   struct GNUNET_TIME_Relative delta;
878
879   if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
880   {
881     GNUNET_break (0);
882     return GNUNET_SYSERR;
883   }
884
885   LOG (GNUNET_ERROR_TYPE_DEBUG,
886        "UDP transmits %u-byte message to `%s' using address `%s' session 0x%X mode %i\n",
887        msgbuf_size, GNUNET_i2s (target), udp_address_to_string (NULL, addr,
888                                                                 addrlen),
889        session, force_address);
890
891   if ((force_address == GNUNET_SYSERR) && (session == NULL))
892     return GNUNET_SYSERR;
893
894   s = NULL;
895   /* safety check: comparing address to address stored in session */
896   if ((session != NULL) && (addr != NULL) && (addrlen != 0))
897   {
898     s = session;
899     GNUNET_assert (GNUNET_YES ==
900                    GNUNET_CONTAINER_multihashmap_contains_value
901                    (plugin->inbound_sessions, &target->hashPubKey, s));
902
903     if (0 != memcmp (&s->target, target, sizeof (struct GNUNET_PeerIdentity)))
904       return GNUNET_SYSERR;
905     switch (addrlen)
906     {
907     case sizeof (struct IPv4UdpAddress):
908       if (NULL == plugin->sockv4)
909       {
910         if (cont != NULL)
911           cont (cont_cls, target, GNUNET_SYSERR);
912         return GNUNET_SYSERR;
913       }
914       t4 = addr;
915       if (s->addrlen != (sizeof (struct sockaddr_in)))
916         return GNUNET_SYSERR;
917       struct sockaddr_in *a4 = (struct sockaddr_in *) s->sock_addr;
918
919       GNUNET_assert (a4->sin_port == t4->u4_port);
920       GNUNET_assert (0 ==
921                      memcmp (&a4->sin_addr, &t4->ipv4_addr,
922                              sizeof (struct in_addr)));
923       LOG (GNUNET_ERROR_TYPE_DEBUG, "Session 0x%X successfully checked!\n",
924            session);
925       break;
926     case sizeof (struct IPv6UdpAddress):
927       if (NULL == plugin->sockv6)
928       {
929         if (cont != NULL)
930           cont (cont_cls, target, GNUNET_SYSERR);
931         return GNUNET_SYSERR;
932       }
933       t6 = addr;
934       GNUNET_assert (s->addrlen == sizeof (struct sockaddr_in6));
935       struct sockaddr_in6 *a6 = (struct sockaddr_in6 *) s->sock_addr;
936
937       GNUNET_assert (a6->sin6_port == t6->u6_port);
938       GNUNET_assert (0 ==
939                      memcmp (&a6->sin6_addr, &t6->ipv6_addr,
940                              sizeof (struct in6_addr)));
941       LOG (GNUNET_ERROR_TYPE_DEBUG, "Session 0x%X successfully checked!\n",
942            session);
943       break;
944     default:
945       /* Must have a valid address to send to */
946       GNUNET_break_op (0);
947     }
948   }
949 //session_invalid:
950   if ((addr == NULL) || (addrlen == 0))
951     return GNUNET_SYSERR;
952   peer_session = create_session (plugin, target, addr, addrlen, cont, cont_cls);
953   if (peer_session == NULL)
954   {
955     if (cont != NULL)
956       cont (cont_cls, target, GNUNET_SYSERR);
957     return GNUNET_SYSERR;;
958   }
959
960   /* Message */
961   udp = (struct UDPMessage *) mbuf;
962   udp->header.size = htons (mlen);
963   udp->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE);
964   udp->reserved = htonl (0);
965   udp->sender = *plugin->env->my_identity;
966   memcpy (&udp[1], msgbuf, msgbuf_size);
967
968   if (s != NULL)
969     delta = GNUNET_TIME_absolute_get_remaining (s->flow_delay_from_other_peer);
970   else
971     delta = GNUNET_TIME_UNIT_ZERO;
972   if (mlen <= UDP_MTU)
973   {
974     mlen = udp_send (plugin, peer_session->sock_addr, &udp->header);
975     if (cont != NULL)
976     {
977       if ((delta.rel_value > 0) && (mlen > 0))
978       {
979         s->cont = cont;
980         s->cont_cls = cont_cls;
981         s->delayed_cont_task =
982             GNUNET_SCHEDULER_add_delayed (delta, &udp_call_continuation, s);
983       }
984       else
985         cont (cont_cls, target, (mlen > 0) ? GNUNET_OK : GNUNET_SYSERR);
986     }
987     GNUNET_free_non_null (peer_session);
988   }
989   else
990   {
991     GNUNET_assert (GNUNET_OK ==
992                    GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
993                                                       &target->hashPubKey,
994                                                       peer_session,
995                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
996     peer_session->frag =
997         GNUNET_FRAGMENT_context_create (plugin->env->stats, UDP_MTU,
998                                         &plugin->tracker,
999                                         plugin->last_expected_delay,
1000                                         &udp->header, &send_fragment,
1001                                         peer_session);
1002   }
1003   return mlen;
1004 }
1005
1006
1007 /**
1008  * Closure for 'process_inbound_tokenized_messages'
1009  */
1010 struct SourceInformation
1011 {
1012   /**
1013    * Sender identity.
1014    */
1015   struct GNUNET_PeerIdentity sender;
1016
1017   /**
1018    * Source address.
1019    */
1020   const void *arg;
1021
1022   /**
1023    * Number of bytes in source address.
1024    */
1025   size_t args;
1026
1027   struct Session *session;
1028 };
1029
1030
1031 /**
1032  * Message tokenizer has broken up an incomming message. Pass it on
1033  * to the service.
1034  *
1035  * @param cls the 'struct Plugin'
1036  * @param client the 'struct SourceInformation'
1037  * @param hdr the actual message
1038  */
1039 static void
1040 process_inbound_tokenized_messages (void *cls, void *client,
1041                                     const struct GNUNET_MessageHeader *hdr)
1042 {
1043   struct Plugin *plugin = cls;
1044   struct SourceInformation *si = client;
1045   struct GNUNET_ATS_Information atsi[2];
1046   struct GNUNET_TIME_Relative delay;
1047
1048   /* setup ATS */
1049   atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1050   atsi[0].value = htonl (1);
1051   atsi[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1052   atsi[1].value = si->session->ats_address_network_type;
1053   GNUNET_break (ntohl(si->session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1054
1055
1056   LOG (GNUNET_ERROR_TYPE_DEBUG, "Giving Session %X %s  to transport\n",
1057        si->session, GNUNET_i2s (&si->session->target));
1058   delay =
1059       plugin->env->receive (plugin->env->cls, &si->sender, hdr,
1060                             (const struct GNUNET_ATS_Information *) &atsi, 2,
1061                             si->session, si->arg, si->args);
1062   si->session->flow_delay_for_other_peer = delay;
1063 }
1064
1065 static void
1066 invalidation_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1067 {
1068   struct Session *s = cls;
1069
1070   s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
1071   LOG (GNUNET_ERROR_TYPE_DEBUG, "Session %X (`%s') is now invalid\n", s,
1072        GNUNET_a2s (s->sock_addr, s->addrlen));
1073
1074   s->plugin->env->session_end (s->plugin->env->cls, &s->target, s);
1075   GNUNET_assert (GNUNET_YES ==
1076                  GNUNET_CONTAINER_multihashmap_remove (s->
1077                                                        plugin->inbound_sessions,
1078                                                        &s->target.hashPubKey,
1079                                                        s));
1080   GNUNET_free (s);
1081 }
1082
1083
1084 /**
1085  * We've received a UDP Message.  Process it (pass contents to main service).
1086  *
1087  * @param plugin plugin context
1088  * @param msg the message
1089  * @param sender_addr sender address
1090  * @param sender_addr_len number of bytes in sender_addr
1091  */
1092 static void
1093 process_udp_message (struct Plugin *plugin, const struct UDPMessage *msg,
1094                      const struct sockaddr *sender_addr,
1095                      socklen_t sender_addr_len)
1096 {
1097   struct SourceInformation si;
1098   struct IPv4UdpAddress u4;
1099   struct IPv6UdpAddress u6;
1100   struct GNUNET_ATS_Information ats;
1101   const void *arg;
1102   size_t args;
1103
1104   if (0 != ntohl (msg->reserved))
1105   {
1106     GNUNET_break_op (0);
1107     return;
1108   }
1109   if (ntohs (msg->header.size) <
1110       sizeof (struct GNUNET_MessageHeader) + sizeof (struct UDPMessage))
1111   {
1112     GNUNET_break_op (0);
1113     return;
1114   }
1115
1116   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1117   ats.value = htonl (GNUNET_ATS_NET_UNSPECIFIED);
1118   /* convert address */
1119   switch (sender_addr->sa_family)
1120   {
1121   case AF_INET:
1122     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in));
1123     u4.ipv4_addr = ((struct sockaddr_in *) sender_addr)->sin_addr.s_addr;
1124     u4.u4_port = ((struct sockaddr_in *) sender_addr)->sin_port;
1125     arg = &u4;
1126     args = sizeof (u4);
1127     break;
1128   case AF_INET6:
1129     GNUNET_assert (sender_addr_len == sizeof (struct sockaddr_in6));
1130     u6.ipv6_addr = ((struct sockaddr_in6 *) sender_addr)->sin6_addr;
1131     u6.u6_port = ((struct sockaddr_in6 *) sender_addr)->sin6_port;
1132     arg = &u6;
1133     args = sizeof (u6);
1134     break;
1135   default:
1136     GNUNET_break (0);
1137     return;
1138   }
1139 #if DEBUG_UDP
1140   LOG (GNUNET_ERROR_TYPE_DEBUG,
1141        "Received message with %u bytes from peer `%s' at `%s'\n",
1142        (unsigned int) ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1143        GNUNET_a2s (sender_addr, sender_addr_len));
1144 #endif
1145
1146   /* create a session for inbound connections */
1147   const struct UDPMessage *udp_msg = (const struct UDPMessage *) msg;
1148
1149   LOG (GNUNET_ERROR_TYPE_DEBUG,
1150        "Lookup inbound UDP sessions for peer `%s' address `%s'\n",
1151        GNUNET_i2s (&udp_msg->sender), udp_address_to_string (NULL, arg, args));
1152
1153   struct Session *s = NULL;
1154
1155   s = find_inbound_session (plugin, &udp_msg->sender, sender_addr,
1156                             sender_addr_len);
1157
1158   if (s != NULL)
1159   {
1160     LOG (GNUNET_ERROR_TYPE_DEBUG,
1161          "Found existing inbound UDP sessions 0x%X for peer `%s' address `%s'\n",
1162          s, GNUNET_i2s (&s->target), udp_address_to_string (NULL, arg, args));
1163   }
1164   else
1165   {
1166     s = create_session (plugin, &udp_msg->sender, arg, args, NULL, NULL);
1167     ats = plugin->env->get_address_type (plugin->env->cls, sender_addr, sender_addr_len);
1168     s->ats_address_network_type = ats.value;
1169     LOG (GNUNET_ERROR_TYPE_DEBUG,
1170          "Creating inbound UDP sessions 0x%X for peer `%s' address `%s'\n", s,
1171          GNUNET_i2s (&s->target), udp_address_to_string (NULL, arg, args));
1172
1173     GNUNET_assert (GNUNET_OK ==
1174                    GNUNET_CONTAINER_multihashmap_put (plugin->inbound_sessions,
1175                                                       &s->target.hashPubKey, s,
1176                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1177   }
1178   s->valid_until =
1179       GNUNET_TIME_relative_to_absolute
1180       (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1181   if (s->invalidation_task != GNUNET_SCHEDULER_NO_TASK)
1182   {
1183     GNUNET_SCHEDULER_cancel (s->invalidation_task);
1184     s->invalidation_task = GNUNET_SCHEDULER_NO_TASK;
1185     LOG (GNUNET_ERROR_TYPE_DEBUG, "Rescheduling %X' `%s'\n", s,
1186          udp_address_to_string (NULL, arg, args));
1187   }
1188   s->invalidation_task =
1189       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1190                                     &invalidation_task, s);
1191   /* iterate over all embedded messages */
1192   si.sender = msg->sender;
1193   si.arg = arg;
1194   si.args = args;
1195   si.session = s;
1196   GNUNET_SERVER_mst_receive (plugin->mst, &si, (const char *) &msg[1],
1197                              ntohs (msg->header.size) -
1198                              sizeof (struct UDPMessage), GNUNET_YES, GNUNET_NO);
1199 }
1200
1201
1202 /**
1203  * Process a defragmented message.
1204  *
1205  * @param cls the 'struct ReceiveContext'
1206  * @param msg the message
1207  */
1208 static void
1209 fragment_msg_proc (void *cls, const struct GNUNET_MessageHeader *msg)
1210 {
1211   struct ReceiveContext *rc = cls;
1212
1213   if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE)
1214   {
1215     GNUNET_break (0);
1216     return;
1217   }
1218   if (ntohs (msg->size) < sizeof (struct UDPMessage))
1219   {
1220     GNUNET_break (0);
1221     return;
1222   }
1223   process_udp_message (rc->plugin, (const struct UDPMessage *) msg,
1224                        rc->src_addr, rc->addr_len);
1225 }
1226
1227
1228 /**
1229  * Transmit an acknowledgement.
1230  *
1231  * @param cls the 'struct ReceiveContext'
1232  * @param id message ID (unused)
1233  * @param msg ack to transmit
1234  */
1235 static void
1236 ack_proc (void *cls, uint32_t id, const struct GNUNET_MessageHeader *msg)
1237 {
1238   struct ReceiveContext *rc = cls;
1239
1240   size_t msize = sizeof (struct UDP_ACK_Message) + ntohs (msg->size);
1241   char buf[msize];
1242   struct UDP_ACK_Message *udp_ack;
1243   uint32_t delay = 0;
1244
1245   struct Session *s;
1246
1247   s = find_inbound_session_by_addr (rc->plugin, rc->src_addr, rc->addr_len);
1248   if (s != NULL)
1249   {
1250     if (s->flow_delay_for_other_peer.rel_value <= UINT32_MAX)
1251       delay = s->flow_delay_for_other_peer.rel_value;
1252     else
1253       delay = UINT32_MAX;
1254   }
1255
1256
1257 #if DEBUG_UDP
1258   LOG (GNUNET_ERROR_TYPE_DEBUG,
1259        "Sending ACK to `%s' including delay of %u ms\n",
1260        GNUNET_a2s (rc->src_addr,
1261                    (rc->src_addr->sa_family ==
1262                     AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct
1263                                                                      sockaddr_in6)),
1264        delay);
1265 #endif
1266   udp_ack = (struct UDP_ACK_Message *) buf;
1267   udp_ack->header.size = htons ((uint16_t) msize);
1268   udp_ack->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK);
1269   udp_ack->delay = htonl (delay);
1270   udp_ack->sender = *rc->plugin->env->my_identity;
1271   memcpy (&udp_ack[1], msg, ntohs (msg->size));
1272   (void) udp_send (rc->plugin, rc->src_addr, &udp_ack->header);
1273 }
1274
1275
1276 /**
1277  * Closure for 'find_receive_context'.
1278  */
1279 struct FindReceiveContext
1280 {
1281   /**
1282    * Where to store the result.
1283    */
1284   struct ReceiveContext *rc;
1285
1286   /**
1287    * Address to find.
1288    */
1289   const struct sockaddr *addr;
1290
1291   /**
1292    * Number of bytes in 'addr'.
1293    */
1294   socklen_t addr_len;
1295
1296   struct Session *session;
1297 };
1298
1299
1300 /**
1301  * Scan the heap for a receive context with the given address.
1302  *
1303  * @param cls the 'struct FindReceiveContext'
1304  * @param node internal node of the heap
1305  * @param element value stored at the node (a 'struct ReceiveContext')
1306  * @param cost cost associated with the node
1307  * @return GNUNET_YES if we should continue to iterate,
1308  *         GNUNET_NO if not.
1309  */
1310 static int
1311 find_receive_context (void *cls, struct GNUNET_CONTAINER_HeapNode *node,
1312                       void *element, GNUNET_CONTAINER_HeapCostType cost)
1313 {
1314   struct FindReceiveContext *frc = cls;
1315   struct ReceiveContext *e = element;
1316
1317   if ((frc->addr_len == e->addr_len) &&
1318       (0 == memcmp (frc->addr, e->src_addr, frc->addr_len)))
1319   {
1320     frc->rc = e;
1321     return GNUNET_NO;
1322   }
1323   return GNUNET_YES;
1324 }
1325
1326 struct Mstv4Context
1327 {
1328   struct Plugin *plugin;
1329
1330   struct IPv4UdpAddress addr;
1331   /**
1332    * ATS network type in NBO
1333    */
1334   uint32_t ats_address_network_type;
1335 };
1336
1337 struct Mstv6Context
1338 {
1339   struct Plugin *plugin;
1340
1341   struct IPv6UdpAddress addr;
1342   /**
1343    * ATS network type in NBO
1344    */
1345   uint32_t ats_address_network_type;
1346 };
1347
1348
1349 /**
1350  * Read and process a message from the given socket.
1351  *
1352  * @param plugin the overall plugin
1353  * @param rsock socket to read from
1354  */
1355 static void
1356 udp_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
1357 {
1358   socklen_t fromlen;
1359   char addr[32];
1360   char buf[65536];
1361   ssize_t ret;
1362   const struct GNUNET_MessageHeader *msg;
1363   const struct GNUNET_MessageHeader *ack;
1364   struct Session *peer_session;
1365   const struct UDP_ACK_Message *udp_ack;
1366   struct ReceiveContext *rc;
1367   struct GNUNET_TIME_Absolute now;
1368   struct FindReceiveContext frc;
1369   struct Session *s = NULL;
1370   struct GNUNET_TIME_Relative flow_delay;
1371   struct GNUNET_ATS_Information ats;
1372
1373   fromlen = sizeof (addr);
1374   memset (&addr, 0, sizeof (addr));
1375   ret =
1376       GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
1377                                       (struct sockaddr *) &addr, &fromlen);
1378   if (ret < sizeof (struct GNUNET_MessageHeader))
1379   {
1380     GNUNET_break_op (0);
1381     return;
1382   }
1383   msg = (const struct GNUNET_MessageHeader *) buf;
1384
1385   LOG (GNUNET_ERROR_TYPE_DEBUG,
1386        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) ret,
1387        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
1388
1389   if (ret != ntohs (msg->size))
1390   {
1391     GNUNET_break_op (0);
1392     return;
1393   }
1394   switch (ntohs (msg->type))
1395   {
1396   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
1397   {
1398     if (fromlen == sizeof (struct sockaddr_in))
1399     {
1400       LOG (GNUNET_ERROR_TYPE_DEBUG,
1401            "Received IPv4 HELLO beacon broadcast with %i bytes from address %s\n",
1402            ret, GNUNET_a2s ((const struct sockaddr *) &addr, fromlen));
1403
1404       struct Mstv4Context *mc;
1405
1406       mc = GNUNET_malloc (sizeof (struct Mstv4Context));
1407       struct sockaddr_in *av4 = (struct sockaddr_in *) &addr;
1408
1409       mc->addr.ipv4_addr = av4->sin_addr.s_addr;
1410       mc->addr.u4_port = av4->sin_port;
1411       ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) &addr, fromlen);
1412       mc->ats_address_network_type = ats.value;
1413       if (GNUNET_OK !=
1414           GNUNET_SERVER_mst_receive (plugin->broadcast_ipv4_mst, mc, buf, ret,
1415                                      GNUNET_NO, GNUNET_NO))
1416         GNUNET_free (mc);
1417     }
1418     else if (fromlen == sizeof (struct sockaddr_in6))
1419     {
1420       LOG (GNUNET_ERROR_TYPE_DEBUG,
1421            "Received IPv6 HELLO beacon broadcast with %i bytes from address %s\n",
1422            ret, GNUNET_a2s ((const struct sockaddr *) &addr, fromlen));
1423
1424       struct Mstv6Context *mc;
1425
1426       mc = GNUNET_malloc (sizeof (struct Mstv6Context));
1427       struct sockaddr_in6 *av6 = (struct sockaddr_in6 *) &addr;
1428
1429       mc->addr.ipv6_addr = av6->sin6_addr;
1430       mc->addr.u6_port = av6->sin6_port;
1431       ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) &addr, fromlen);
1432       mc->ats_address_network_type = ats.value;
1433
1434       if (GNUNET_OK !=
1435           GNUNET_SERVER_mst_receive (plugin->broadcast_ipv6_mst, mc, buf, ret,
1436                                      GNUNET_NO, GNUNET_NO))
1437         GNUNET_free (mc);
1438     }
1439     return;
1440   }
1441   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
1442     if (ntohs (msg->size) < sizeof (struct UDPMessage))
1443     {
1444       GNUNET_break_op (0);
1445       return;
1446     }
1447     process_udp_message (plugin, (const struct UDPMessage *) msg,
1448                          (const struct sockaddr *) addr, fromlen);
1449     return;
1450   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_ACK:
1451
1452     if (ntohs (msg->size) <
1453         sizeof (struct UDP_ACK_Message) + sizeof (struct GNUNET_MessageHeader))
1454     {
1455       GNUNET_break_op (0);
1456       return;
1457     }
1458     udp_ack = (const struct UDP_ACK_Message *) msg;
1459     s = find_inbound_session (plugin, &udp_ack->sender, addr, fromlen);
1460     if (s != NULL)
1461     {
1462       flow_delay.rel_value = (uint64_t) ntohl (udp_ack->delay);
1463
1464       LOG (GNUNET_ERROR_TYPE_DEBUG, "We received a sending delay of %llu\n",
1465            flow_delay.rel_value);
1466
1467       s->flow_delay_from_other_peer =
1468           GNUNET_TIME_relative_to_absolute (flow_delay);
1469     }
1470     ack = (const struct GNUNET_MessageHeader *) &udp_ack[1];
1471     if (ntohs (ack->size) !=
1472         ntohs (msg->size) - sizeof (struct UDP_ACK_Message))
1473     {
1474       GNUNET_break_op (0);
1475       return;
1476     }
1477 #if DEBUG_UDP
1478     LOG (GNUNET_ERROR_TYPE_DEBUG,
1479          "UDP processes %u-byte acknowledgement from `%s' at `%s'\n",
1480          (unsigned int) ntohs (msg->size), GNUNET_i2s (&udp_ack->sender),
1481          GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1482 #endif
1483
1484     peer_session = find_session (plugin, &udp_ack->sender);
1485     if (NULL == peer_session)
1486     {
1487 #if DEBUG_UDP
1488       LOG (GNUNET_ERROR_TYPE_DEBUG,
1489            "Session for ACK not found, dropping ACK!\n");
1490 #endif
1491       return;
1492     }
1493     if (GNUNET_OK != GNUNET_FRAGMENT_process_ack (peer_session->frag, ack))
1494       return;
1495     GNUNET_assert (GNUNET_OK ==
1496                    GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
1497                                                          &udp_ack->
1498                                                          sender.hashPubKey,
1499                                                          peer_session));
1500     plugin->last_expected_delay =
1501         GNUNET_FRAGMENT_context_destroy (peer_session->frag);
1502     if (peer_session->cont != NULL)
1503       peer_session->cont (peer_session->cont_cls, &udp_ack->sender, GNUNET_OK);
1504     GNUNET_free (peer_session);
1505     return;
1506   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1507     frc.rc = NULL;
1508     frc.addr = (const struct sockaddr *) addr;
1509     frc.addr_len = fromlen;
1510     GNUNET_CONTAINER_heap_iterate (plugin->defrags, &find_receive_context,
1511                                    &frc);
1512     now = GNUNET_TIME_absolute_get ();
1513     rc = frc.rc;
1514     if (rc == NULL)
1515     {
1516       /* need to create a new RC */
1517       rc = GNUNET_malloc (sizeof (struct ReceiveContext) + fromlen);
1518       memcpy (&rc[1], addr, fromlen);
1519       rc->src_addr = (const struct sockaddr *) &rc[1];
1520       rc->addr_len = fromlen;
1521       rc->plugin = plugin;
1522       rc->defrag =
1523           GNUNET_DEFRAGMENT_context_create (plugin->env->stats, UDP_MTU,
1524                                             UDP_MAX_MESSAGES_IN_DEFRAG, rc,
1525                                             &fragment_msg_proc, &ack_proc);
1526       rc->hnode =
1527           GNUNET_CONTAINER_heap_insert (plugin->defrags, rc,
1528                                         (GNUNET_CONTAINER_HeapCostType)
1529                                         now.abs_value);
1530     }
1531 #if DEBUG_UDP
1532     LOG (GNUNET_ERROR_TYPE_DEBUG, "UDP processes %u-byte fragment from `%s'\n",
1533          (unsigned int) ntohs (msg->size),
1534          GNUNET_a2s ((const struct sockaddr *) addr, fromlen));
1535 #endif
1536
1537     if (GNUNET_OK == GNUNET_DEFRAGMENT_process_fragment (rc->defrag, msg))
1538     {
1539       /* keep this 'rc' from expiring */
1540       GNUNET_CONTAINER_heap_update_cost (plugin->defrags, rc->hnode,
1541                                          (GNUNET_CONTAINER_HeapCostType)
1542                                          now.abs_value);
1543     }
1544     if (GNUNET_CONTAINER_heap_get_size (plugin->defrags) >
1545         UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG)
1546     {
1547       /* remove 'rc' that was inactive the longest */
1548       rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags);
1549       GNUNET_assert (NULL != rc);
1550       GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
1551       GNUNET_free (rc);
1552     }
1553     return;
1554   default:
1555     GNUNET_break_op (0);
1556     return;
1557   }
1558 }
1559
1560
1561 /**
1562  * We have been notified that our writeset has something to read.  We don't
1563  * know which socket needs to be read, so we have to check each one
1564  * Then reschedule this function to be called again once more is available.
1565  *
1566  * @param cls the plugin handle
1567  * @param tc the scheduling context (for rescheduling this function again)
1568  */
1569 static void
1570 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1571 {
1572   struct Plugin *plugin = cls;
1573
1574   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1575   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1576     return;
1577   if ((NULL != plugin->sockv4) &&
1578       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
1579     udp_read (plugin, plugin->sockv4);
1580   if ((NULL != plugin->sockv6) &&
1581       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
1582     udp_read (plugin, plugin->sockv6);
1583   plugin->select_task =
1584       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1585                                    GNUNET_SCHEDULER_NO_TASK,
1586                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
1587                                    NULL, &udp_plugin_select, plugin);
1588
1589 }
1590
1591
1592 void
1593 broadcast_ipv4_mst_cb (void *cls, void *client,
1594                        const struct GNUNET_MessageHeader *message)
1595 {
1596   struct Plugin *plugin = cls;
1597   struct Mstv4Context *mc = client;
1598   const struct GNUNET_MessageHeader *hello;
1599   struct UDP_Beacon_Message *msg;
1600
1601   msg = (struct UDP_Beacon_Message *) message;
1602
1603   if (GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON !=
1604       ntohs (msg->header.type))
1605     return;
1606
1607   LOG (GNUNET_ERROR_TYPE_DEBUG,
1608        "Received beacon with %u bytes from peer `%s' via address `%s'\n",
1609        ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1610        udp_address_to_string (NULL, &mc->addr, sizeof (mc->addr)));
1611
1612   struct GNUNET_ATS_Information atsi[2];
1613
1614   /* setup ATS */
1615   atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1616   atsi[0].value = htonl (1);
1617   atsi[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1618   atsi[1].value = mc->ats_address_network_type;
1619   GNUNET_break (ntohl(mc->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1620
1621   hello = (struct GNUNET_MessageHeader *) &msg[1];
1622   plugin->env->receive (plugin->env->cls, &msg->sender, hello,
1623                         (const struct GNUNET_ATS_Information *) &atsi, 2, NULL,
1624                         (const char *) &mc->addr, sizeof (mc->addr));
1625
1626   GNUNET_STATISTICS_update (plugin->env->stats,
1627                             _
1628                             ("# IPv4 broadcast HELLO beacons received via udp"),
1629                             1, GNUNET_NO);
1630   GNUNET_free (mc);
1631 }
1632
1633
1634 void
1635 broadcast_ipv6_mst_cb (void *cls, void *client,
1636                        const struct GNUNET_MessageHeader *message)
1637 {
1638
1639   struct Plugin *plugin = cls;
1640   struct Mstv6Context *mc = client;
1641   const struct GNUNET_MessageHeader *hello;
1642   struct UDP_Beacon_Message *msg;
1643
1644   msg = (struct UDP_Beacon_Message *) message;
1645
1646   if (GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON !=
1647       ntohs (msg->header.type))
1648     return;
1649
1650   LOG (GNUNET_ERROR_TYPE_DEBUG,
1651        "Received beacon with %u bytes from peer `%s' via address `%s'\n",
1652        ntohs (msg->header.size), GNUNET_i2s (&msg->sender),
1653        udp_address_to_string (NULL, &mc->addr, sizeof (mc->addr)));
1654
1655   struct GNUNET_ATS_Information atsi[2];
1656
1657   /* setup ATS */
1658   atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1659   atsi[0].value = htonl (1);
1660   atsi[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1661   atsi[1].value = mc->ats_address_network_type;
1662   GNUNET_break (ntohl(mc->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1663
1664   hello = (struct GNUNET_MessageHeader *) &msg[1];
1665   plugin->env->receive (plugin->env->cls, &msg->sender, hello,
1666                         (const struct GNUNET_ATS_Information *) &atsi, 2, NULL,
1667                         (const char *) &mc->addr, sizeof (mc->addr));
1668
1669   GNUNET_STATISTICS_update (plugin->env->stats,
1670                             _
1671                             ("# IPv6 multicast HELLO beacons received via udp"),
1672                             1, GNUNET_NO);
1673   GNUNET_free (mc);
1674 }
1675
1676
1677 static void
1678 udp_ipv4_broadcast_send (void *cls,
1679                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1680 {
1681   struct Plugin *plugin = cls;
1682   int sent;
1683   uint16_t msg_size;
1684   uint16_t hello_size;
1685   char buf[65536];
1686
1687   const struct GNUNET_MessageHeader *hello;
1688   struct UDP_Beacon_Message *msg;
1689   struct BroadcastAddress *baddr;
1690
1691   plugin->send_ipv4_broadcast_task = GNUNET_SCHEDULER_NO_TASK;
1692
1693   hello = plugin->env->get_our_hello ();
1694   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1695   msg_size = hello_size + sizeof (struct UDP_Beacon_Message);
1696
1697   if (hello_size < (sizeof (struct GNUNET_MessageHeader)) ||
1698       (msg_size > (UDP_MTU)))
1699     return;
1700
1701   msg = (struct UDP_Beacon_Message *) buf;
1702   msg->sender = *(plugin->env->my_identity);
1703   msg->header.size = ntohs (msg_size);
1704   msg->header.type = ntohs (GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON);
1705   memcpy (&msg[1], hello, hello_size);
1706   sent = 0;
1707
1708   baddr = plugin->ipv4_broadcast_head;
1709   /* just IPv4 */
1710   while ((baddr != NULL) && (baddr->addrlen == sizeof (struct sockaddr_in)))
1711   {
1712     struct sockaddr_in *addr = (struct sockaddr_in *) baddr->addr;
1713
1714     addr->sin_port = htons (plugin->port);
1715
1716     sent =
1717         GNUNET_NETWORK_socket_sendto (plugin->sockv4, msg, msg_size,
1718                                       (const struct sockaddr *) addr,
1719                                       baddr->addrlen);
1720     if (sent == GNUNET_SYSERR)
1721       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
1722     else
1723       LOG (GNUNET_ERROR_TYPE_DEBUG,
1724            "Sent HELLO beacon broadcast with  %i bytes to address %s\n", sent,
1725            GNUNET_a2s (baddr->addr, baddr->addrlen));
1726     baddr = baddr->next;
1727   }
1728
1729   plugin->send_ipv4_broadcast_task =
1730       GNUNET_SCHEDULER_add_delayed (plugin->broadcast_interval,
1731                                     &udp_ipv4_broadcast_send, plugin);
1732 }
1733
1734 static void
1735 udp_ipv6_broadcast_send (void *cls,
1736                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1737 {
1738   struct Plugin *plugin = cls;
1739   int sent;
1740   uint16_t msg_size;
1741   uint16_t hello_size;
1742   char buf[65536];
1743
1744   const struct GNUNET_MessageHeader *hello;
1745   struct UDP_Beacon_Message *msg;
1746
1747   plugin->send_ipv6_broadcast_task = GNUNET_SCHEDULER_NO_TASK;
1748
1749   hello = plugin->env->get_our_hello ();
1750   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1751   msg_size = hello_size + sizeof (struct UDP_Beacon_Message);
1752
1753   if (hello_size < (sizeof (struct GNUNET_MessageHeader)) ||
1754       (msg_size > (UDP_MTU)))
1755     return;
1756
1757   msg = (struct UDP_Beacon_Message *) buf;
1758   msg->sender = *(plugin->env->my_identity);
1759   msg->header.size = ntohs (msg_size);
1760   msg->header.type = ntohs (GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON);
1761   memcpy (&msg[1], hello, hello_size);
1762   sent = 0;
1763
1764   sent =
1765       GNUNET_NETWORK_socket_sendto (plugin->sockv6, msg, msg_size,
1766                                     (const struct sockaddr *)
1767                                     &plugin->ipv6_multicast_address,
1768                                     sizeof (struct sockaddr_in6));
1769   if (sent == GNUNET_SYSERR)
1770     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
1771   else
1772     LOG (GNUNET_ERROR_TYPE_DEBUG,
1773          "Sending IPv6 HELLO beacon broadcast with  %i bytes to address %s\n",
1774          sent,
1775          GNUNET_a2s ((const struct sockaddr *) &plugin->ipv6_multicast_address,
1776                      sizeof (struct sockaddr_in6)));
1777
1778
1779
1780   plugin->send_ipv6_broadcast_task =
1781       GNUNET_SCHEDULER_add_delayed (plugin->broadcast_interval,
1782                                     &udp_ipv6_broadcast_send, plugin);
1783 }
1784
1785 /**
1786  * Check if the given port is plausible (must be either our listen
1787  * port or our advertised port).  If it is neither, we return
1788  * GNUNET_SYSERR.
1789  *
1790  * @param plugin global variables
1791  * @param in_port port number to check
1792  * @return GNUNET_OK if port is either open_port or adv_port
1793  */
1794 static int
1795 check_port (struct Plugin *plugin, uint16_t in_port)
1796 {
1797   if ((in_port == plugin->port) || (in_port == plugin->aport))
1798     return GNUNET_OK;
1799   return GNUNET_SYSERR;
1800 }
1801
1802
1803 /**
1804  * Function that will be called to check if a binary address for this
1805  * plugin is well-formed and corresponds to an address for THIS peer
1806  * (as per our configuration).  Naturally, if absolutely necessary,
1807  * plugins can be a bit conservative in their answer, but in general
1808  * plugins should make sure that the address does not redirect
1809  * traffic to a 3rd party that might try to man-in-the-middle our
1810  * traffic.
1811  *
1812  * @param cls closure, should be our handle to the Plugin
1813  * @param addr pointer to the address
1814  * @param addrlen length of addr
1815  * @return GNUNET_OK if this is a plausible address for this peer
1816  *         and transport, GNUNET_SYSERR if not
1817  *
1818  */
1819 static int
1820 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1821 {
1822   struct Plugin *plugin = cls;
1823   struct IPv4UdpAddress *v4;
1824   struct IPv6UdpAddress *v6;
1825
1826   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
1827       (addrlen != sizeof (struct IPv6UdpAddress)))
1828   {
1829     GNUNET_break_op (0);
1830     return GNUNET_SYSERR;
1831   }
1832   if (addrlen == sizeof (struct IPv4UdpAddress))
1833   {
1834     v4 = (struct IPv4UdpAddress *) addr;
1835     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
1836       return GNUNET_SYSERR;
1837     if (GNUNET_OK !=
1838         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1839                                  sizeof (struct in_addr)))
1840       return GNUNET_SYSERR;
1841   }
1842   else
1843   {
1844     v6 = (struct IPv6UdpAddress *) addr;
1845     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1846     {
1847       GNUNET_break_op (0);
1848       return GNUNET_SYSERR;
1849     }
1850     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
1851       return GNUNET_SYSERR;
1852     if (GNUNET_OK !=
1853         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1854                                  sizeof (struct in6_addr)))
1855       return GNUNET_SYSERR;
1856   }
1857   return GNUNET_OK;
1858 }
1859
1860
1861 /**
1862  * Function called for a quick conversion of the binary address to
1863  * a numeric address.  Note that the caller must not free the
1864  * address and that the next call to this function is allowed
1865  * to override the address again.
1866  *
1867  * @param cls closure
1868  * @param addr binary address
1869  * @param addrlen length of the address
1870  * @return string representing the same address
1871  */
1872 static const char *
1873 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
1874 {
1875   static char rbuf[INET6_ADDRSTRLEN + 10];
1876   char buf[INET6_ADDRSTRLEN];
1877   const void *sb;
1878   struct in_addr a4;
1879   struct in6_addr a6;
1880   const struct IPv4UdpAddress *t4;
1881   const struct IPv6UdpAddress *t6;
1882   int af;
1883   uint16_t port;
1884
1885   if (addrlen == sizeof (struct IPv6UdpAddress))
1886   {
1887     t6 = addr;
1888     af = AF_INET6;
1889     port = ntohs (t6->u6_port);
1890     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
1891     sb = &a6;
1892   }
1893   else if (addrlen == sizeof (struct IPv4UdpAddress))
1894   {
1895     t4 = addr;
1896     af = AF_INET;
1897     port = ntohs (t4->u4_port);
1898     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
1899     sb = &a4;
1900   }
1901   else
1902   {
1903     GNUNET_break_op (0);
1904     return NULL;
1905   }
1906   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
1907   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
1908                    buf, port);
1909   return rbuf;
1910 }
1911
1912
1913 /**
1914  * Closure for 'append_port'.
1915  */
1916 struct PrettyPrinterContext
1917 {
1918   /**
1919    * Function to call with the result.
1920    */
1921   GNUNET_TRANSPORT_AddressStringCallback asc;
1922
1923   /**
1924    * Clsoure for 'asc'.
1925    */
1926   void *asc_cls;
1927
1928   /**
1929    * Port to add after the IP address.
1930    */
1931   uint16_t port;
1932 };
1933
1934
1935 /**
1936  * Append our port and forward the result.
1937  *
1938  * @param cls a 'struct PrettyPrinterContext'
1939  * @param hostname result from DNS resolver
1940  */
1941 static void
1942 append_port (void *cls, const char *hostname)
1943 {
1944   struct PrettyPrinterContext *ppc = cls;
1945   char *ret;
1946
1947   if (hostname == NULL)
1948   {
1949     ppc->asc (ppc->asc_cls, NULL);
1950     GNUNET_free (ppc);
1951     return;
1952   }
1953   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1954   ppc->asc (ppc->asc_cls, ret);
1955   GNUNET_free (ret);
1956 }
1957
1958
1959 /**
1960  * Convert the transports address to a nice, human-readable
1961  * format.
1962  *
1963  * @param cls closure
1964  * @param type name of the transport that generated the address
1965  * @param addr one of the addresses of the host, NULL for the last address
1966  *        the specific address format depends on the transport
1967  * @param addrlen length of the address
1968  * @param numeric should (IP) addresses be displayed in numeric form?
1969  * @param timeout after how long should we give up?
1970  * @param asc function to call on each string
1971  * @param asc_cls closure for asc
1972  */
1973 static void
1974 udp_plugin_address_pretty_printer (void *cls, const char *type,
1975                                    const void *addr, size_t addrlen,
1976                                    int numeric,
1977                                    struct GNUNET_TIME_Relative timeout,
1978                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1979                                    void *asc_cls)
1980 {
1981   struct PrettyPrinterContext *ppc;
1982   const void *sb;
1983   size_t sbs;
1984   struct sockaddr_in a4;
1985   struct sockaddr_in6 a6;
1986   const struct IPv4UdpAddress *u4;
1987   const struct IPv6UdpAddress *u6;
1988   uint16_t port;
1989
1990   if (addrlen == sizeof (struct IPv6UdpAddress))
1991   {
1992     u6 = addr;
1993     memset (&a6, 0, sizeof (a6));
1994     a6.sin6_family = AF_INET6;
1995 #if HAVE_SOCKADDR_IN_SIN_LEN
1996     a6.sin6_len = sizeof (a6);
1997 #endif
1998     a6.sin6_port = u6->u6_port;
1999     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
2000     port = ntohs (u6->u6_port);
2001     sb = &a6;
2002     sbs = sizeof (a6);
2003   }
2004   else if (addrlen == sizeof (struct IPv4UdpAddress))
2005   {
2006     u4 = addr;
2007     memset (&a4, 0, sizeof (a4));
2008     a4.sin_family = AF_INET;
2009 #if HAVE_SOCKADDR_IN_SIN_LEN
2010     a4.sin_len = sizeof (a4);
2011 #endif
2012     a4.sin_port = u4->u4_port;
2013     a4.sin_addr.s_addr = u4->ipv4_addr;
2014     port = ntohs (u4->u4_port);
2015     sb = &a4;
2016     sbs = sizeof (a4);
2017   }
2018   else
2019   {
2020     /* invalid address */
2021     GNUNET_break_op (0);
2022     asc (asc_cls, NULL);
2023     return;
2024   }
2025   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
2026   ppc->asc = asc;
2027   ppc->asc_cls = asc_cls;
2028   ppc->port = port;
2029   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
2030 }
2031
2032
2033 /**
2034  * Our external IP address/port mapping has changed.
2035  *
2036  * @param cls closure, the 'struct LocalAddrList'
2037  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
2038  *     the previous (now invalid) one
2039  * @param addr either the previous or the new public IP address
2040  * @param addrlen actual lenght of the address
2041  */
2042 static void
2043 udp_nat_port_map_callback (void *cls, int add_remove,
2044                            const struct sockaddr *addr, socklen_t addrlen)
2045 {
2046   struct Plugin *plugin = cls;
2047   struct IPv4UdpAddress u4;
2048   struct IPv6UdpAddress u6;
2049   void *arg;
2050   size_t args;
2051
2052   /* convert 'addr' to our internal format */
2053   switch (addr->sa_family)
2054   {
2055   case AF_INET:
2056     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2057     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
2058     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
2059     arg = &u4;
2060     args = sizeof (u4);
2061     break;
2062   case AF_INET6:
2063     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
2064     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
2065             sizeof (struct in6_addr));
2066     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
2067     arg = &u6;
2068     args = sizeof (u6);
2069     break;
2070   default:
2071     GNUNET_break (0);
2072     return;
2073   }
2074   /* modify our published address list */
2075   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
2076 }
2077
2078
2079 static int
2080 iface_proc (void *cls, const char *name, int isDefault,
2081             const struct sockaddr *addr, const struct sockaddr *broadcast_addr,
2082             const struct sockaddr *netmask, socklen_t addrlen)
2083 {
2084   struct Plugin *plugin = cls;
2085
2086   if (addr != NULL)
2087   {
2088     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "address %s for interface %s %p\n ",
2089                 GNUNET_a2s (addr, addrlen), name, addr);
2090     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091                 "broadcast address %s for interface %s %p\n ",
2092                 GNUNET_a2s (broadcast_addr, addrlen), name, broadcast_addr);
2093     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "netmask %s for interface %s %p\n ",
2094                 GNUNET_a2s (netmask, addrlen), name, netmask);
2095
2096
2097     /* Collecting broadcast addresses */
2098     if (broadcast_addr != NULL)
2099     {
2100       struct BroadcastAddress *ba =
2101           GNUNET_malloc (sizeof (struct BroadcastAddress));
2102       ba->addr = GNUNET_malloc (addrlen);
2103       memcpy (ba->addr, broadcast_addr, addrlen);
2104       ba->addrlen = addrlen;
2105       GNUNET_CONTAINER_DLL_insert (plugin->ipv4_broadcast_head,
2106                                    plugin->ipv4_broadcast_tail, ba);
2107     }
2108   }
2109   return GNUNET_OK;
2110 }
2111
2112
2113 /**
2114  * The exported method. Makes the core api available via a global and
2115  * returns the udp transport API.
2116  *
2117  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
2118  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
2119  */
2120 void *
2121 libgnunet_plugin_transport_udp_init (void *cls)
2122 {
2123   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2124   unsigned long long port;
2125   unsigned long long aport;
2126   struct GNUNET_TRANSPORT_PluginFunctions *api;
2127   struct Plugin *plugin;
2128   int sockets_created;
2129   int broadcast;
2130   struct GNUNET_TIME_Relative interval;
2131   struct sockaddr_in serverAddrv4;
2132   struct sockaddr_in6 serverAddrv6;
2133   struct sockaddr *serverAddr;
2134   struct sockaddr *addrs[2];
2135   socklen_t addrlens[2];
2136   socklen_t addrlen;
2137   unsigned int tries;
2138   unsigned long long udp_max_bps;
2139
2140   if (GNUNET_OK !=
2141       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
2142                                              &port))
2143     port = 2086;
2144
2145   broadcast =
2146       GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
2147                                             "BROADCAST");
2148   if (broadcast == GNUNET_SYSERR)
2149     broadcast = GNUNET_NO;
2150
2151   if (GNUNET_SYSERR ==
2152       GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-udp",
2153                                            "BROADCAST_INTERVAL", &interval))
2154     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
2155
2156   if (GNUNET_OK !=
2157       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2158                                              "MAX_BPS", &udp_max_bps))
2159     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
2160   if (GNUNET_OK !=
2161       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
2162                                              "ADVERTISED_PORT", &aport))
2163     aport = port;
2164   if (port > 65535)
2165   {
2166     LOG (GNUNET_ERROR_TYPE_WARNING,
2167          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
2168          65535);
2169     return NULL;
2170   }
2171   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
2172   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
2173
2174   plugin = GNUNET_malloc (sizeof (struct Plugin));
2175   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
2176                                  GNUNET_BANDWIDTH_value_init ((uint32_t)
2177                                                               udp_max_bps), 30);
2178   plugin->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
2179   plugin->port = port;
2180   plugin->aport = aport;
2181   plugin->env = env;
2182   plugin->broadcast_interval = interval;
2183   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2184   api->cls = plugin;
2185
2186   api->send = &udp_plugin_send_old;
2187   api->disconnect = &udp_disconnect;
2188   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
2189   api->address_to_string = &udp_address_to_string;
2190   api->check_address = &udp_plugin_check_address;
2191
2192   api->get_session = &udp_plugin_get_session;
2193   api->send_with_session = &udp_plugin_send;
2194
2195   if (GNUNET_YES ==
2196       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2197                                              "BINDTO", &plugin->bind4_address))
2198   {
2199     LOG (GNUNET_ERROR_TYPE_DEBUG,
2200          "Binding udp plugin to specific address: `%s'\n",
2201          plugin->bind4_address);
2202     if (1 != inet_pton (AF_INET, plugin->bind4_address, &serverAddrv4.sin_addr))
2203     {
2204       GNUNET_free (plugin->bind4_address);
2205       GNUNET_free (plugin);
2206       GNUNET_free (api);
2207       return NULL;
2208     }
2209   }
2210
2211   if (GNUNET_YES ==
2212       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
2213                                              "BINDTO6", &plugin->bind6_address))
2214   {
2215     LOG (GNUNET_ERROR_TYPE_DEBUG,
2216          "Binding udp plugin to specific address: `%s'\n",
2217          plugin->bind6_address);
2218     if (1 !=
2219         inet_pton (AF_INET6, plugin->bind6_address, &serverAddrv6.sin6_addr))
2220     {
2221       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
2222            plugin->bind6_address);
2223       GNUNET_free_non_null (plugin->bind4_address);
2224       GNUNET_free (plugin->bind6_address);
2225       GNUNET_free (plugin);
2226       GNUNET_free (api);
2227       return NULL;
2228     }
2229   }
2230
2231   plugin->defrags =
2232       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2233   plugin->sessions =
2234       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
2235                                             * 2);
2236   plugin->inbound_sessions =
2237       GNUNET_CONTAINER_multihashmap_create (UDP_MAX_SENDER_ADDRESSES_WITH_DEFRAG
2238                                             * 2);
2239   sockets_created = 0;
2240   if ((GNUNET_YES !=
2241        GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, "nat",
2242                                              "DISABLEV6")))
2243   {
2244     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
2245     if (NULL == plugin->sockv6)
2246     {
2247       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
2248     }
2249     else
2250     {
2251 #if HAVE_SOCKADDR_IN_SIN_LEN
2252       serverAddrv6.sin6_len = sizeof (serverAddrv6);
2253 #endif
2254       serverAddrv6.sin6_family = AF_INET6;
2255       serverAddrv6.sin6_addr = in6addr_any;
2256       serverAddrv6.sin6_port = htons (plugin->port);
2257       addrlen = sizeof (serverAddrv6);
2258       serverAddr = (struct sockaddr *) &serverAddrv6;
2259 #if DEBUG_UDP
2260       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
2261            ntohs (serverAddrv6.sin6_port));
2262 #endif
2263       tries = 0;
2264       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
2265              GNUNET_OK)
2266       {
2267         serverAddrv6.sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
2268 #if DEBUG_UDP
2269         LOG (GNUNET_ERROR_TYPE_DEBUG,
2270              "IPv6 Binding failed, trying new port %d\n",
2271              ntohs (serverAddrv6.sin6_port));
2272 #endif
2273         tries++;
2274         if (tries > 10)
2275         {
2276           GNUNET_NETWORK_socket_close (plugin->sockv6);
2277           plugin->sockv6 = NULL;
2278           break;
2279         }
2280       }
2281       if (plugin->sockv6 != NULL)
2282       {
2283         addrs[sockets_created] = (struct sockaddr *) &serverAddrv6;
2284         addrlens[sockets_created] = sizeof (serverAddrv6);
2285         sockets_created++;
2286       }
2287     }
2288   }
2289
2290   plugin->mst =
2291       GNUNET_SERVER_mst_create (&process_inbound_tokenized_messages, plugin);
2292   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
2293   if (NULL == plugin->sockv4)
2294   {
2295     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
2296   }
2297   else
2298   {
2299 #if HAVE_SOCKADDR_IN_SIN_LEN
2300     serverAddrv4.sin_len = sizeof (serverAddrv4);
2301 #endif
2302     serverAddrv4.sin_family = AF_INET;
2303     serverAddrv4.sin_addr.s_addr = INADDR_ANY;
2304     serverAddrv4.sin_port = htons (plugin->port);
2305     addrlen = sizeof (serverAddrv4);
2306     serverAddr = (struct sockaddr *) &serverAddrv4;
2307 #if DEBUG_UDP
2308     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
2309          ntohs (serverAddrv4.sin_port));
2310 #endif
2311     tries = 0;
2312     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
2313            GNUNET_OK)
2314     {
2315       serverAddrv4.sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
2316 #if DEBUG_UDP
2317       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
2318            ntohs (serverAddrv4.sin_port));
2319 #endif
2320       tries++;
2321       if (tries > 10)
2322       {
2323         GNUNET_NETWORK_socket_close (plugin->sockv4);
2324         plugin->sockv4 = NULL;
2325         break;
2326       }
2327     }
2328     if (plugin->sockv4 != NULL)
2329     {
2330       addrs[sockets_created] = (struct sockaddr *) &serverAddrv4;
2331       addrlens[sockets_created] = sizeof (serverAddrv4);
2332       sockets_created++;
2333     }
2334   }
2335
2336   plugin->rs = GNUNET_NETWORK_fdset_create ();
2337   GNUNET_NETWORK_fdset_zero (plugin->rs);
2338   if (NULL != plugin->sockv4)
2339     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
2340   if (NULL != plugin->sockv6)
2341     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
2342
2343   plugin->select_task =
2344       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2345                                    GNUNET_SCHEDULER_NO_TASK,
2346                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
2347                                    NULL, &udp_plugin_select, plugin);
2348
2349
2350
2351   if (broadcast)
2352   {
2353     /* create IPv4 broadcast socket */
2354     plugin->broadcast_ipv4 = GNUNET_NO;
2355     if (plugin->sockv4 != NULL)
2356     {
2357       int yes = 1;
2358
2359       if (GNUNET_NETWORK_socket_setsockopt
2360           (plugin->sockv4, SOL_SOCKET, SO_BROADCAST, &yes,
2361            sizeof (int)) != GNUNET_OK)
2362       {
2363         LOG (GNUNET_ERROR_TYPE_WARNING,
2364              _
2365              ("Failed to set IPv4 broadcast option for broadcast socket on port %d\n"),
2366              ntohs (serverAddrv4.sin_port));
2367       }
2368       else
2369       {
2370         GNUNET_OS_network_interfaces_list (iface_proc, plugin);
2371         plugin->send_ipv4_broadcast_task =
2372             GNUNET_SCHEDULER_add_now (&udp_ipv4_broadcast_send, plugin);
2373
2374         plugin->broadcast_ipv4_mst =
2375             GNUNET_SERVER_mst_create (broadcast_ipv4_mst_cb, plugin);
2376
2377         LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Broadcasting running\n");
2378         plugin->broadcast_ipv4 = GNUNET_YES;
2379       }
2380     }
2381
2382     plugin->broadcast_ipv6 = GNUNET_NO;
2383     if (plugin->sockv6 != NULL)
2384     {
2385       memset (&plugin->ipv6_multicast_address, 0, sizeof (struct sockaddr_in6));
2386       GNUNET_assert (1 ==
2387                      inet_pton (AF_INET6, "FF05::13B",
2388                                 &plugin->ipv6_multicast_address.sin6_addr));
2389
2390       plugin->ipv6_multicast_address.sin6_family = AF_INET6;
2391       plugin->ipv6_multicast_address.sin6_port = htons (plugin->port);
2392
2393       plugin->broadcast_ipv6_mst =
2394           GNUNET_SERVER_mst_create (broadcast_ipv6_mst_cb, plugin);
2395
2396       /* Create IPv6 multicast request */
2397       struct ipv6_mreq multicastRequest;
2398
2399       multicastRequest.ipv6mr_multiaddr =
2400           plugin->ipv6_multicast_address.sin6_addr;
2401       /* TODO: 0 selects the "best" interface, tweak to use all interfaces
2402        *
2403        * http://tools.ietf.org/html/rfc2553#section-5.2:
2404        *
2405        * IPV6_JOIN_GROUP
2406        *
2407        * Join a multicast group on a specified local interface.  If the
2408        * interface index is specified as 0, the kernel chooses the local
2409        * interface.  For example, some kernels look up the multicast
2410        * group in the normal IPv6 routing table and using the resulting
2411        * interface.
2412        * */
2413       multicastRequest.ipv6mr_interface = 0;
2414
2415       /* Join the multicast group */
2416       if (GNUNET_NETWORK_socket_setsockopt
2417           (plugin->sockv6, IPPROTO_IPV6, IPV6_JOIN_GROUP,
2418            (char *) &multicastRequest, sizeof (multicastRequest)) != GNUNET_OK)
2419       {
2420         LOG (GNUNET_ERROR_TYPE_WARNING,
2421         "Failed to join IPv6 multicast group: IPv6 broadcasting not running\n");
2422       }
2423       else
2424       {
2425 #if DEBUG_UDP
2426         LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv6 broadcasting running\n");
2427 #endif
2428         plugin->send_ipv6_broadcast_task =
2429             GNUNET_SCHEDULER_add_now (&udp_ipv6_broadcast_send, plugin);
2430         plugin->broadcast_ipv6 = GNUNET_YES;
2431       }
2432     }
2433   }
2434
2435   if (sockets_created == 0)
2436     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
2437   plugin->nat =
2438       GNUNET_NAT_register (env->cfg, GNUNET_NO, port, sockets_created,
2439                            (const struct sockaddr **) addrs, addrlens,
2440                            &udp_nat_port_map_callback, NULL, plugin);
2441   return api;
2442 }
2443
2444 /**
2445  * Shutdown the plugin.
2446  *
2447  * @param cls our 'struct GNUNET_TRANSPORT_PluginFunctions'
2448  * @return NULL
2449  */
2450 void *
2451 libgnunet_plugin_transport_udp_done (void *cls)
2452 {
2453   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2454   struct Plugin *plugin = api->cls;
2455   struct ReceiveContext *rc;
2456
2457   /* FIXME: clean up heap and hashmap */
2458   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &destroy_session,
2459                                          NULL);
2460   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
2461   plugin->sessions = NULL;
2462   GNUNET_CONTAINER_multihashmap_iterate (plugin->inbound_sessions,
2463                                          &destroy_inbound_session, NULL);
2464   GNUNET_CONTAINER_multihashmap_destroy (plugin->inbound_sessions);
2465   plugin->inbound_sessions = NULL;
2466   while (NULL != (rc = GNUNET_CONTAINER_heap_remove_root (plugin->defrags)))
2467   {
2468     GNUNET_DEFRAGMENT_context_destroy (rc->defrag);
2469     GNUNET_free (rc);
2470   }
2471   GNUNET_CONTAINER_heap_destroy (plugin->defrags);
2472
2473   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
2474   {
2475     GNUNET_SCHEDULER_cancel (plugin->select_task);
2476     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
2477   }
2478
2479   if (plugin->broadcast_ipv4)
2480   {
2481     if (plugin->send_ipv4_broadcast_task != GNUNET_SCHEDULER_NO_TASK)
2482     {
2483       GNUNET_SCHEDULER_cancel (plugin->send_ipv4_broadcast_task);
2484       plugin->send_ipv4_broadcast_task = GNUNET_SCHEDULER_NO_TASK;
2485     }
2486
2487     if (plugin->broadcast_ipv4_mst != NULL)
2488       GNUNET_SERVER_mst_destroy (plugin->broadcast_ipv4_mst);
2489
2490     while (plugin->ipv4_broadcast_head != NULL)
2491     {
2492       struct BroadcastAddress *p = plugin->ipv4_broadcast_head;
2493
2494       GNUNET_CONTAINER_DLL_remove (plugin->ipv4_broadcast_head,
2495                                    plugin->ipv4_broadcast_tail, p);
2496       GNUNET_free (p->addr);
2497       GNUNET_free (p);
2498     }
2499   }
2500
2501   if (plugin->broadcast_ipv6)
2502   {
2503     /* Create IPv6 multicast request */
2504     struct ipv6_mreq multicastRequest;
2505
2506     multicastRequest.ipv6mr_multiaddr =
2507         plugin->ipv6_multicast_address.sin6_addr;
2508     multicastRequest.ipv6mr_interface = 0;
2509
2510     /* Join the multicast address */
2511     if (GNUNET_NETWORK_socket_setsockopt
2512         (plugin->sockv6, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
2513         (char *) &multicastRequest, sizeof (multicastRequest)) != GNUNET_OK)
2514     {
2515        GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, setsockopt);
2516     }
2517     else
2518     {
2519 #if DEBUG_UDP
2520       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv6 Broadcasting stopped\n");
2521 #endif
2522     }
2523
2524     if (plugin->send_ipv6_broadcast_task != GNUNET_SCHEDULER_NO_TASK)
2525     {
2526       GNUNET_SCHEDULER_cancel (plugin->send_ipv6_broadcast_task);
2527       plugin->send_ipv6_broadcast_task = GNUNET_SCHEDULER_NO_TASK;
2528     }
2529     if (plugin->broadcast_ipv6_mst != NULL)
2530       GNUNET_SERVER_mst_destroy (plugin->broadcast_ipv6_mst);
2531   }
2532
2533
2534   if (plugin->sockv4 != NULL)
2535   {
2536     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
2537     plugin->sockv4 = NULL;
2538   }
2539   if (plugin->sockv6 != NULL)
2540   {
2541     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
2542     plugin->sockv6 = NULL;
2543   }
2544
2545   GNUNET_SERVER_mst_destroy (plugin->mst);
2546   GNUNET_NETWORK_fdset_destroy (plugin->rs);
2547
2548   GNUNET_NAT_unregister (plugin->nat);
2549   plugin->nat = NULL;
2550   GNUNET_free (plugin);
2551   GNUNET_free (api);
2552   return NULL;
2553 }
2554
2555 /* end of plugin_transport_udp.c */