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