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