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