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