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