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