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