-simplify
[oweals/gnunet.git] / src / transport / plugin_transport_udp_new.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 transport protocol
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  * @author Matthias Wachs
27  */
28 #include "platform.h"
29 #include "plugin_transport_udp_new.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_fragmentation_lib.h"
33 #include "gnunet_nat_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_resolver_service.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_constants.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_transport_service.h"
40 #include "gnunet_transport_plugin.h"
41 #include "transport.h"
42
43 #define LOG(kind,...) GNUNET_log_from (kind, "transport-udp", __VA_ARGS__)
44
45
46 /**
47  * Closure for 'append_port'.
48  */
49 struct PrettyPrinterContext
50 {
51   /**
52    * Function to call with the result.
53    */
54   GNUNET_TRANSPORT_AddressStringCallback asc;
55
56   /**
57    * Clsoure for 'asc'.
58    */
59   void *asc_cls;
60
61   /**
62    * Port to add after the IP address.
63    */
64   uint16_t port;
65 };
66
67 struct Session
68 {
69   /**
70    * Which peer is this session for?
71    */
72   struct GNUNET_PeerIdentity target;
73
74   /**
75    * Address of the other peer
76    */
77   const struct sockaddr *sock_addr;
78
79   size_t addrlen;
80 };
81
82
83 struct SessionCompareContext
84 {
85   struct Session *res;
86   const struct GNUNET_HELLO_Address *addr;
87 };
88
89
90
91 /**
92  * Function called for a quick conversion of the binary address to
93  * a numeric address.  Note that the caller must not free the
94  * address and that the next call to this function is allowed
95  * to override the address again.
96  *
97  * @param cls closure
98  * @param addr binary address
99  * @param addrlen length of the address
100  * @return string representing the same address
101  */
102 const char *
103 udp_address_to_string (void *cls, const void *addr, size_t addrlen)
104 {
105   static char rbuf[INET6_ADDRSTRLEN + 10];
106   char buf[INET6_ADDRSTRLEN];
107   const void *sb;
108   struct in_addr a4;
109   struct in6_addr a6;
110   const struct IPv4UdpAddress *t4;
111   const struct IPv6UdpAddress *t6;
112   int af;
113   uint16_t port;
114
115   if (addrlen == sizeof (struct IPv6UdpAddress))
116   {
117     t6 = addr;
118     af = AF_INET6;
119     port = ntohs (t6->u6_port);
120     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
121     sb = &a6;
122   }
123   else if (addrlen == sizeof (struct IPv4UdpAddress))
124   {
125     t4 = addr;
126     af = AF_INET;
127     port = ntohs (t4->u4_port);
128     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
129     sb = &a4;
130   }
131   else
132   {
133     GNUNET_break_op (0);
134     return NULL;
135   }
136   inet_ntop (af, sb, buf, INET6_ADDRSTRLEN);
137   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
138                    buf, port);
139   return rbuf;
140 }
141
142
143 /**
144  * Append our port and forward the result.
145  *
146  * @param cls a 'struct PrettyPrinterContext'
147  * @param hostname result from DNS resolver
148  */
149 static void
150 append_port (void *cls, const char *hostname)
151 {
152   struct PrettyPrinterContext *ppc = cls;
153   char *ret;
154
155   if (hostname == NULL)
156   {
157     ppc->asc (ppc->asc_cls, NULL);
158     GNUNET_free (ppc);
159     return;
160   }
161   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
162   ppc->asc (ppc->asc_cls, ret);
163   GNUNET_free (ret);
164 }
165
166
167 /**
168  * Convert the transports address to a nice, human-readable
169  * format.
170  *
171  * @param cls closure
172  * @param type name of the transport that generated the address
173  * @param addr one of the addresses of the host, NULL for the last address
174  *        the specific address format depends on the transport
175  * @param addrlen length of the address
176  * @param numeric should (IP) addresses be displayed in numeric form?
177  * @param timeout after how long should we give up?
178  * @param asc function to call on each string
179  * @param asc_cls closure for asc
180  */
181 static void
182 udp_plugin_address_pretty_printer (void *cls, const char *type,
183                                    const void *addr, size_t addrlen,
184                                    int numeric,
185                                    struct GNUNET_TIME_Relative timeout,
186                                    GNUNET_TRANSPORT_AddressStringCallback asc,
187                                    void *asc_cls)
188 {
189   struct PrettyPrinterContext *ppc;
190   const void *sb;
191   size_t sbs;
192   struct sockaddr_in a4;
193   struct sockaddr_in6 a6;
194   const struct IPv4UdpAddress *u4;
195   const struct IPv6UdpAddress *u6;
196   uint16_t port;
197
198   if (addrlen == sizeof (struct IPv6UdpAddress))
199   {
200     u6 = addr;
201     memset (&a6, 0, sizeof (a6));
202     a6.sin6_family = AF_INET6;
203 #if HAVE_SOCKADDR_IN_SIN_LEN
204     a6.sin6_len = sizeof (a6);
205 #endif
206     a6.sin6_port = u6->u6_port;
207     memcpy (&a6.sin6_addr, &u6->ipv6_addr, sizeof (struct in6_addr));
208     port = ntohs (u6->u6_port);
209     sb = &a6;
210     sbs = sizeof (a6);
211   }
212   else if (addrlen == sizeof (struct IPv4UdpAddress))
213   {
214     u4 = addr;
215     memset (&a4, 0, sizeof (a4));
216     a4.sin_family = AF_INET;
217 #if HAVE_SOCKADDR_IN_SIN_LEN
218     a4.sin_len = sizeof (a4);
219 #endif
220     a4.sin_port = u4->u4_port;
221     a4.sin_addr.s_addr = u4->ipv4_addr;
222     port = ntohs (u4->u4_port);
223     sb = &a4;
224     sbs = sizeof (a4);
225   }
226   else
227   {
228     /* invalid address */
229     GNUNET_break_op (0);
230     asc (asc_cls, NULL);
231     return;
232   }
233   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
234   ppc->asc = asc;
235   ppc->asc_cls = asc_cls;
236   ppc->port = port;
237   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
238 }
239
240
241 /**
242  * Check if the given port is plausible (must be either our listen
243  * port or our advertised port).  If it is neither, we return
244  * GNUNET_SYSERR.
245  *
246  * @param plugin global variables
247  * @param in_port port number to check
248  * @return GNUNET_OK if port is either open_port or adv_port
249  */
250 static int
251 check_port (struct Plugin *plugin, uint16_t in_port)
252 {
253   if ((in_port == plugin->port) || (in_port == plugin->aport))
254     return GNUNET_OK;
255   return GNUNET_SYSERR;
256 }
257
258
259
260 /**
261  * Function that will be called to check if a binary address for this
262  * plugin is well-formed and corresponds to an address for THIS peer
263  * (as per our configuration).  Naturally, if absolutely necessary,
264  * plugins can be a bit conservative in their answer, but in general
265  * plugins should make sure that the address does not redirect
266  * traffic to a 3rd party that might try to man-in-the-middle our
267  * traffic.
268  *
269  * @param cls closure, should be our handle to the Plugin
270  * @param addr pointer to the address
271  * @param addrlen length of addr
272  * @return GNUNET_OK if this is a plausible address for this peer
273  *         and transport, GNUNET_SYSERR if not
274  *
275  */
276 static int
277 udp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
278 {
279   struct Plugin *plugin = cls;
280   struct IPv4UdpAddress *v4;
281   struct IPv6UdpAddress *v6;
282
283   if ((addrlen != sizeof (struct IPv4UdpAddress)) &&
284       (addrlen != sizeof (struct IPv6UdpAddress)))
285   {
286     GNUNET_break_op (0);
287     return GNUNET_SYSERR;
288   }
289   if (addrlen == sizeof (struct IPv4UdpAddress))
290   {
291     v4 = (struct IPv4UdpAddress *) addr;
292     if (GNUNET_OK != check_port (plugin, ntohs (v4->u4_port)))
293       return GNUNET_SYSERR;
294     if (GNUNET_OK !=
295         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
296                                  sizeof (struct in_addr)))
297       return GNUNET_SYSERR;
298   }
299   else
300   {
301     v6 = (struct IPv6UdpAddress *) addr;
302     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
303     {
304       GNUNET_break_op (0);
305       return GNUNET_SYSERR;
306     }
307     if (GNUNET_OK != check_port (plugin, ntohs (v6->u6_port)))
308       return GNUNET_SYSERR;
309     if (GNUNET_OK !=
310         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
311                                  sizeof (struct in6_addr)))
312       return GNUNET_SYSERR;
313   }
314   return GNUNET_OK;
315 }
316
317
318 /**
319  * Destroy a session, plugin is being unloaded.
320  *
321  * @param cls unused
322  * @param key hash of public key of target peer
323  * @param value a 'struct PeerSession*' to clean up
324  * @return GNUNET_OK (continue to iterate)
325  */
326 static int
327 disconnect_and_free_it (void *cls, const GNUNET_HashCode * key, void *value)
328 {
329   struct Plugin *plugin = cls;
330   struct Session *s = value;
331
332 #if DEBUG_UDP
333   LOG (GNUNET_ERROR_TYPE_DEBUG,
334        "Session %p to peer `%s' address ended \n",
335          s,
336          GNUNET_i2s (&s->target),
337          GNUNET_a2s (s->sock_addr, s->addrlen));
338 #endif
339
340   plugin->env->session_end (plugin->env->cls, &s->target, s);
341
342   GNUNET_assert (GNUNET_YES ==
343                  GNUNET_CONTAINER_multihashmap_remove (plugin->sessions,
344                                                        &s->target.hashPubKey,
345                                                        s));
346
347   GNUNET_free (s);
348   return GNUNET_OK;
349 }
350
351
352 /**
353  * Disconnect from a remote node.  Clean up session if we have one for this peer
354  *
355  * @param cls closure for this call (should be handle to Plugin)
356  * @param target the peeridentity of the peer to disconnect
357  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
358  */
359 static void
360 udp_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
361 {
362   struct Plugin *plugin = cls;
363   GNUNET_assert (plugin != NULL);
364
365   GNUNET_assert (target != NULL);
366 #if DEBUG_UDP
367   LOG (GNUNET_ERROR_TYPE_DEBUG,
368        "Disconnecting from peer `%s'\n", GNUNET_i2s (target));
369 #endif
370   /* Clean up sessions */
371   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessions, &target->hashPubKey, &disconnect_and_free_it, plugin);
372
373 }
374
375 static struct Session *
376 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
377                 const void *addr, size_t addrlen,
378                 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
379 {
380   struct Session *s;
381   const struct IPv4UdpAddress *t4;
382   const struct IPv6UdpAddress *t6;
383   struct sockaddr_in *v4;
384   struct sockaddr_in6 *v6;
385   size_t len;
386   struct GNUNET_ATS_Information ats;
387
388   switch (addrlen)
389   {
390   case sizeof (struct IPv4UdpAddress):
391     if (NULL == plugin->sockv4)
392     {
393       return NULL;
394     }
395     t4 = addr;
396     s = GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in));
397     len = sizeof (struct sockaddr_in);
398     v4 = (struct sockaddr_in *) &s[1];
399     v4->sin_family = AF_INET;
400 #if HAVE_SOCKADDR_IN_SIN_LEN
401     v4->sin_len = sizeof (struct sockaddr_in);
402 #endif
403     v4->sin_port = t4->u4_port;
404     v4->sin_addr.s_addr = t4->ipv4_addr;
405     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v4, sizeof (struct sockaddr_in));
406     break;
407   case sizeof (struct IPv6UdpAddress):
408     if (NULL == plugin->sockv6)
409     {
410       return NULL;
411     }
412     t6 = addr;
413     s =
414         GNUNET_malloc (sizeof (struct Session) + sizeof (struct sockaddr_in6));
415     len = sizeof (struct sockaddr_in6);
416     v6 = (struct sockaddr_in6 *) &s[1];
417     v6->sin6_family = AF_INET6;
418 #if HAVE_SOCKADDR_IN_SIN_LEN
419     v6->sin6_len = sizeof (struct sockaddr_in6);
420 #endif
421     v6->sin6_port = t6->u6_port;
422     v6->sin6_addr = t6->ipv6_addr;
423     ats = plugin->env->get_address_type (plugin->env->cls, (const struct sockaddr *) v6, sizeof (struct sockaddr_in6));
424     break;
425   default:
426     /* Must have a valid address to send to */
427     GNUNET_break_op (0);
428     return NULL;
429   }
430
431   s->addrlen = len;
432   s->target = *target;
433   s->sock_addr = (const struct sockaddr *) &s[1];
434
435   return s;
436 }
437
438 static int session_cmp_it (void *cls,
439                            const GNUNET_HashCode * key,
440                            void *value)
441 {
442   struct SessionCompareContext * cctx = cls;
443   const struct GNUNET_HELLO_Address *address = cctx->addr;
444   struct Session *s = value;
445   struct Session *r = cctx->res;
446   struct IPv4UdpAddress * u4 = NULL;
447   struct IPv6UdpAddress * u6 = NULL;
448   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "AAAAAAAAAAAAAAAAAAa\n");
449   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Looking for existing session for address %s\n", udp_address_to_string (NULL, (void *) address->address, address->address_length));
450
451   if (s->addrlen == address->address_length)
452   {
453     if (address->address_length == sizeof (struct IPv4UdpAddress))
454     {
455       u4 = (struct IPv4UdpAddress * ) address->address;
456       struct sockaddr_in *sai = (struct sockaddr_in *) s->sock_addr;
457       if ((u4->ipv4_addr == sai->sin_addr.s_addr) &&
458           (u4->u4_port == sai->sin_port))
459       {
460         r = s;
461         return GNUNET_NO;
462       }
463     }
464     else if (address->address_length == sizeof (struct IPv6UdpAddress))
465     {
466       u6 = (struct IPv6UdpAddress * ) address->address;
467       struct sockaddr_in6 *sai = (struct sockaddr_in6 *) s->sock_addr;
468
469       if ((0 == memcmp (&u6->ipv6_addr, &sai->sin6_addr, sizeof (struct in6_addr))) &&
470          (u6->u6_port == sai->sin6_port))
471       {
472         r = s;
473         return GNUNET_NO;
474       }
475     }
476     else
477     {
478       GNUNET_break (0);
479       return GNUNET_YES;
480     }
481   }
482   return GNUNET_YES;
483 }
484
485
486 /**
487  * Creates a new outbound session the transport service will use to send data to the
488  * peer
489  *
490  * @param cls the plugin
491  * @param address the address
492  * @return the session or NULL of max connections exceeded
493  */
494 static struct Session *
495 udp_plugin_get_session (void *cls,
496                   const struct GNUNET_HELLO_Address *address)
497 {
498   struct Session * s = NULL;
499   struct Plugin * plugin = cls;
500
501   GNUNET_assert (plugin != NULL);
502   GNUNET_assert (address != NULL);
503
504   if ((address->address == NULL) ||
505       ((address->address_length != sizeof (struct IPv4UdpAddress)) &&
506       (address->address_length != sizeof (struct IPv6UdpAddress))))
507   {
508     GNUNET_break (0);
509     return NULL;
510   }
511
512   /* check if session already exists */
513   if (NULL != NULL)
514  {
515   struct SessionCompareContext cctx;
516   cctx.addr = address;
517   cctx.res = NULL;
518 #if DEBUG_UDP
519   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Looking for existing session for peer `%s' `%s' \n", GNUNET_i2s (&address->peer), udp_address_to_string(NULL, address->address, address->address_length));
520 #endif
521   GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessions, &address->peer.hashPubKey, session_cmp_it, &cctx);
522   if (cctx.res != NULL)
523   {
524     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found existing session\n");
525     return cctx.res;
526   }
527  }
528   /* otherwise create new */
529   s = create_session (plugin,
530       &address->peer,
531       address->address,
532       address->address_length,
533       NULL, NULL);
534   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Creating new session %p\n", s);
535   GNUNET_assert (GNUNET_OK ==
536                  GNUNET_CONTAINER_multihashmap_put (plugin->sessions,
537                                                     &s->target.hashPubKey,
538                                                     s,
539                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
540
541   return s;
542 }
543
544
545 /**
546  * Function that can be used by the transport service to transmit
547  * a message using the plugin.   Note that in the case of a
548  * peer disconnecting, the continuation MUST be called
549  * prior to the disconnect notification itself.  This function
550  * will be called with this peer's HELLO message to initiate
551  * a fresh connection to another peer.
552  *
553  * @param cls closure
554  * @param session which session must be used
555  * @param msgbuf the message to transmit
556  * @param msgbuf_size number of bytes in 'msgbuf'
557  * @param priority how important is the message (most plugins will
558  *                 ignore message priority and just FIFO)
559  * @param to how long to wait at most for the transmission (does not
560  *                require plugins to discard the message after the timeout,
561  *                just advisory for the desired delay; most plugins will ignore
562  *                this as well)
563  * @param cont continuation to call once the message has
564  *        been transmitted (or if the transport is ready
565  *        for the next transmission call; or if the
566  *        peer disconnected...); can be NULL
567  * @param cont_cls closure for cont
568  * @return number of bytes used (on the physical network, with overheads);
569  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
570  *         and does NOT mean that the message was not transmitted (DV)
571  */
572 static ssize_t
573 udp_plugin_send (void *cls,
574                   struct Session *session,
575                   const char *msgbuf, size_t msgbuf_size,
576                   unsigned int priority,
577                   struct GNUNET_TIME_Relative to,
578                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
579 {
580
581   return 0;
582
583 }
584
585 static ssize_t udp_plugin_send_wrapper (void *cls,
586                                         const struct
587                                         GNUNET_PeerIdentity *
588                                         target,
589                                         const char *msgbuf,
590                                         size_t msgbuf_size,
591                                         uint32_t priority,
592                                         struct
593                                         GNUNET_TIME_Relative
594                                         timeout,
595                                         struct Session * session,
596                                         const void *addr,
597                                         size_t addrlen,
598                                         int force_address,
599                                         GNUNET_TRANSPORT_TransmitContinuation
600                                         cont, void *cont_cls)
601 {
602   int ret;
603   struct Session * s = NULL;
604   struct GNUNET_HELLO_Address * ha = NULL;
605
606   ha = GNUNET_HELLO_address_allocate(target, "", addr,addrlen);
607   GNUNET_assert (ha != NULL);
608   s = udp_plugin_get_session(cls, ha);
609   GNUNET_assert (s != NULL);
610   GNUNET_free (ha);
611   ret = udp_plugin_send (cls, s, msgbuf, msgbuf_size, priority, timeout, cont, cont_cls);
612
613   return ret;
614 }
615
616
617 /**
618  * Our external IP address/port mapping has changed.
619  *
620  * @param cls closure, the 'struct LocalAddrList'
621  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
622  *     the previous (now invalid) one
623  * @param addr either the previous or the new public IP address
624  * @param addrlen actual lenght of the address
625  */
626 static void
627 udp_nat_port_map_callback (void *cls, int add_remove,
628                            const struct sockaddr *addr, socklen_t addrlen)
629 {
630   struct Plugin *plugin = cls;
631   struct IPv4UdpAddress u4;
632   struct IPv6UdpAddress u6;
633   void *arg;
634   size_t args;
635
636   /* convert 'addr' to our internal format */
637   switch (addr->sa_family)
638   {
639   case AF_INET:
640     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
641     u4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
642     u4.u4_port = ((struct sockaddr_in *) addr)->sin_port;
643     arg = &u4;
644     args = sizeof (u4);
645     break;
646   case AF_INET6:
647     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
648     memcpy (&u6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
649             sizeof (struct in6_addr));
650     u6.u6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
651     arg = &u6;
652     args = sizeof (u6);
653     break;
654   default:
655     GNUNET_break (0);
656     return;
657   }
658   /* modify our published address list */
659   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
660 }
661
662
663 /**
664  * Read and process a message from the given socket.
665  *
666  * @param plugin the overall plugin
667  * @param rsock socket to read from
668  */
669 static void
670 udp_read (struct Plugin *plugin, struct GNUNET_NETWORK_Handle *rsock)
671 {
672   socklen_t fromlen;
673   char addr[32];
674   char buf[65536];
675   ssize_t size;
676   const struct GNUNET_MessageHeader *msg;
677   //const struct GNUNET_MessageHeader *ack;
678   //struct Session *peer_session;
679   //const struct UDP_ACK_Message *udp_ack;
680   //struct ReceiveContext *rc;
681   //struct GNUNET_TIME_Absolute now;
682   //struct FindReceiveContext frc;
683   //struct Session *s = NULL;
684   //struct GNUNET_TIME_Relative flow_delay;
685   //struct GNUNET_ATS_Information ats;
686
687   fromlen = sizeof (addr);
688   memset (&addr, 0, sizeof (addr));
689   size = GNUNET_NETWORK_socket_recvfrom (rsock, buf, sizeof (buf),
690                                       (struct sockaddr *) &addr, &fromlen);
691   if (size < sizeof (struct GNUNET_MessageHeader))
692   {
693     GNUNET_break_op (0);
694     return;
695   }
696   msg = (const struct GNUNET_MessageHeader *) buf;
697
698   LOG (GNUNET_ERROR_TYPE_DEBUG,
699        "UDP received %u-byte message from `%s' type %i\n", (unsigned int) size,
700        GNUNET_a2s ((const struct sockaddr *) addr, fromlen), ntohs (msg->type));
701
702   if (size != ntohs (msg->size))
703   {
704     GNUNET_break_op (0);
705     return;
706   }
707   switch (ntohs (msg->type))
708   {
709   case GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON:
710   {
711     udp_broadcast_receive(plugin, &buf, size, addr, fromlen);
712     return;
713   }
714   case GNUNET_MESSAGE_TYPE_TRANSPORT_UDP_MESSAGE:
715     if (ntohs (msg->size) < sizeof (struct UDPMessage))
716     {
717       GNUNET_break_op (0);
718       return;
719     }
720     /*
721     process_udp_message (plugin, (const struct UDPMessage *) msg,
722                          (const struct sockaddr *) addr, fromlen);
723      */
724     return;
725   default:
726     GNUNET_break_op (0);
727     return;
728   }
729 }
730
731 /**
732  * We have been notified that our readset has something to read.  We don't
733  * know which socket needs to be read, so we have to check each one
734  * Then reschedule this function to be called again once more is available.
735  *
736  * @param cls the plugin handle
737  * @param tc the scheduling context (for rescheduling this function again)
738  */
739 static void
740 udp_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
741 {
742   struct Plugin *plugin = cls;
743
744   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
745   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
746     return;
747
748   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
749   {
750     if ((NULL != plugin->sockv4) &&
751       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv4)))
752         udp_read (plugin, plugin->sockv4);
753     if ((NULL != plugin->sockv6) &&
754       (GNUNET_NETWORK_fdset_isset (tc->read_ready, plugin->sockv6)))
755         udp_read (plugin, plugin->sockv6);
756   }
757
758   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
759   {
760     /* TODO */
761   }
762
763   plugin->select_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
764                                    GNUNET_SCHEDULER_NO_TASK,
765                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
766                                    plugin->ws, &udp_plugin_select, plugin);
767
768 }
769
770
771 static int
772 setup_sockets (struct Plugin *plugin, struct sockaddr_in6 *serverAddrv6, struct sockaddr_in *serverAddrv4)
773 {
774   int tries;
775   int sockets_created = 0;
776   struct sockaddr *serverAddr;
777   struct sockaddr *addrs[2];
778   socklen_t addrlens[2];
779   socklen_t addrlen;
780
781   /* Create IPv6 socket */
782   if (plugin->enable_ipv6 == GNUNET_YES)
783   {
784     plugin->sockv6 = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_DGRAM, 0);
785     if (NULL == plugin->sockv6)
786     {
787       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
788     }
789     else
790     {
791 #if HAVE_SOCKADDR_IN_SIN_LEN
792       serverAddrv6.sin6_len = sizeof (serverAddrv6);
793 #endif
794       serverAddrv6->sin6_family = AF_INET6;
795       serverAddrv6->sin6_addr = in6addr_any;
796       serverAddrv6->sin6_port = htons (plugin->port);
797       addrlen = sizeof (struct sockaddr_in6);
798       serverAddr = (struct sockaddr *) serverAddrv6;
799 #if DEBUG_UDP
800       LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv6 port %d\n",
801            ntohs (serverAddrv6->sin6_port));
802 #endif
803       tries = 0;
804       while (GNUNET_NETWORK_socket_bind (plugin->sockv6, serverAddr, addrlen) !=
805              GNUNET_OK)
806       {
807         serverAddrv6->sin6_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);        /* Find a good, non-root port */
808 #if DEBUG_UDP
809         LOG (GNUNET_ERROR_TYPE_DEBUG,
810              "IPv6 Binding failed, trying new port %d\n",
811              ntohs (serverAddrv6->sin6_port));
812 #endif
813         tries++;
814         if (tries > 10)
815         {
816           GNUNET_NETWORK_socket_close (plugin->sockv6);
817           plugin->sockv6 = NULL;
818           break;
819         }
820       }
821       if (plugin->sockv6 != NULL)
822       {
823 #if DEBUG_UDP
824         LOG (GNUNET_ERROR_TYPE_DEBUG,
825              "IPv6 socket created on port %d\n",
826              ntohs (serverAddrv6->sin6_port));
827 #endif
828         addrs[sockets_created] = (struct sockaddr *) serverAddrv6;
829         addrlens[sockets_created] = sizeof (struct sockaddr_in6);
830         sockets_created++;
831       }
832     }
833   }
834
835   /* Create IPv4 socket */
836   plugin->sockv4 = GNUNET_NETWORK_socket_create (PF_INET, SOCK_DGRAM, 0);
837   if (NULL == plugin->sockv4)
838   {
839     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "socket");
840   }
841   else
842   {
843 #if HAVE_SOCKADDR_IN_SIN_LEN
844     serverAddrv4.sin_len = sizeof (serverAddrv4);
845 #endif
846     serverAddrv4->sin_family = AF_INET;
847     serverAddrv4->sin_addr.s_addr = INADDR_ANY;
848     serverAddrv4->sin_port = htons (plugin->port);
849     addrlen = sizeof (struct sockaddr_in);
850     serverAddr = (struct sockaddr *) serverAddrv4;
851
852 #if DEBUG_UDP
853     LOG (GNUNET_ERROR_TYPE_DEBUG, "Binding to IPv4 port %d\n",
854          ntohs (serverAddrv4->sin_port));
855 #endif
856     tries = 0;
857     while (GNUNET_NETWORK_socket_bind (plugin->sockv4, serverAddr, addrlen) !=
858            GNUNET_OK)
859     {
860       serverAddrv4->sin_port = htons (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, 33537) + 32000);   /* Find a good, non-root port */
861 #if DEBUG_UDP
862       LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv4 Binding failed, trying new port %d\n",
863            ntohs (serverAddrv4->sin_port));
864 #endif
865       tries++;
866       if (tries > 10)
867       {
868         GNUNET_NETWORK_socket_close (plugin->sockv4);
869         plugin->sockv4 = NULL;
870         break;
871       }
872     }
873     if (plugin->sockv4 != NULL)
874     {
875       addrs[sockets_created] = (struct sockaddr *) serverAddrv4;
876       addrlens[sockets_created] = sizeof (struct sockaddr_in);
877       sockets_created++;
878     }
879   }
880
881   /* Create file descriptors */
882   plugin->rs = GNUNET_NETWORK_fdset_create ();
883   plugin->ws = GNUNET_NETWORK_fdset_create ();
884   GNUNET_NETWORK_fdset_zero (plugin->rs);
885   GNUNET_NETWORK_fdset_zero (plugin->ws);
886   if (NULL != plugin->sockv4)
887   {
888     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv4);
889     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv4);
890   }
891   if (NULL != plugin->sockv6)
892   {
893     GNUNET_NETWORK_fdset_set (plugin->rs, plugin->sockv6);
894     GNUNET_NETWORK_fdset_set (plugin->ws, plugin->sockv6);
895   }
896
897   if (sockets_created == 0)
898     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Failed to open UDP sockets\n"));
899
900   plugin->select_task =
901       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
902                                    GNUNET_SCHEDULER_NO_TASK,
903                                    GNUNET_TIME_UNIT_FOREVER_REL, plugin->rs,
904                                    plugin->ws, &udp_plugin_select, plugin);
905
906   plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
907                            GNUNET_NO, plugin->port,
908                            sockets_created,
909                            (const struct sockaddr **) addrs, addrlens,
910                            &udp_nat_port_map_callback, NULL, plugin);
911
912   return sockets_created;
913 }
914
915
916 /**
917  * The exported method. Makes the core api available via a global and
918  * returns the udp transport API.
919  *
920  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
921  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
922  */
923 void *
924 libgnunet_plugin_transport_udp_init (void *cls)
925 {
926   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
927   struct GNUNET_TRANSPORT_PluginFunctions *api;
928   struct Plugin *plugin;
929
930   unsigned long long port;
931   unsigned long long aport;
932   unsigned long long broadcast;
933   unsigned long long udp_max_bps;
934   unsigned long long enable_v6;
935   char * bind4_address;
936   char * bind6_address;
937   struct GNUNET_TIME_Relative interval;
938
939   struct sockaddr_in serverAddrv4;
940   struct sockaddr_in6 serverAddrv6;
941
942   int res;
943
944   /* Get port number */
945   if (GNUNET_OK !=
946       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp", "PORT",
947                                              &port))
948     port = 2086;
949   if (GNUNET_OK !=
950       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
951                                              "ADVERTISED_PORT", &aport))
952     aport = port;
953   if (port > 65535)
954   {
955     LOG (GNUNET_ERROR_TYPE_WARNING,
956          _("Given `%s' option is out of range: %llu > %u\n"), "PORT", port,
957          65535);
958     return NULL;
959   }
960
961   /* Protocols */
962   if ((GNUNET_YES ==
963        GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "nat",
964                                              "DISABLEV6")))
965   {
966     enable_v6 = GNUNET_NO;
967   }
968   else
969     enable_v6 = GNUNET_YES;
970
971
972   /* Addresses */
973   memset (&serverAddrv6, 0, sizeof (serverAddrv6));
974   memset (&serverAddrv4, 0, sizeof (serverAddrv4));
975
976   if (GNUNET_YES ==
977       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
978                                              "BINDTO", &bind4_address))
979   {
980     LOG (GNUNET_ERROR_TYPE_DEBUG,
981          "Binding udp plugin to specific address: `%s'\n",
982          bind4_address);
983     if (1 != inet_pton (AF_INET, bind4_address, &serverAddrv4.sin_addr))
984     {
985       GNUNET_free (bind4_address);
986       return NULL;
987     }
988   }
989
990   if (GNUNET_YES ==
991       GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-udp",
992                                              "BINDTO6", &bind6_address))
993   {
994     LOG (GNUNET_ERROR_TYPE_DEBUG,
995          "Binding udp plugin to specific address: `%s'\n",
996          bind6_address);
997     if (1 !=
998         inet_pton (AF_INET6, bind6_address, &serverAddrv6.sin6_addr))
999     {
1000       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid IPv6 address: `%s'\n"),
1001            bind6_address);
1002       GNUNET_free_non_null (bind4_address);
1003       GNUNET_free (bind6_address);
1004       return NULL;
1005     }
1006   }
1007
1008
1009   /* Enable neighbour discovery */
1010   broadcast = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, "transport-udp",
1011                                             "BROADCAST");
1012   if (broadcast == GNUNET_SYSERR)
1013     broadcast = GNUNET_NO;
1014
1015   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-udp",
1016                                            "BROADCAST_INTERVAL", &interval))
1017   {
1018     interval = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
1019   }
1020
1021   /* Maximum datarate */
1022   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-udp",
1023                                              "MAX_BPS", &udp_max_bps))
1024   {
1025     udp_max_bps = 1024 * 1024 * 50;     /* 50 MB/s == infinity for practical purposes */
1026   }
1027
1028   plugin = GNUNET_malloc (sizeof (struct Plugin));
1029   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1030
1031   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1032                                  GNUNET_BANDWIDTH_value_init ((uint32_t)udp_max_bps), 30);
1033
1034
1035   plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
1036   plugin->port = port;
1037   plugin->aport = aport;
1038   plugin->last_expected_delay = GNUNET_TIME_UNIT_SECONDS;
1039   plugin->broadcast_interval = interval;
1040   plugin->enable_ipv6 = enable_v6;
1041   plugin->env = env;
1042
1043   api->cls = plugin;
1044   api->send = NULL;
1045   api->disconnect = &udp_disconnect;
1046   api->address_pretty_printer = &udp_plugin_address_pretty_printer;
1047   api->address_to_string = &udp_address_to_string;
1048   api->check_address = &udp_plugin_check_address;
1049   api->get_session = &udp_plugin_get_session;
1050   api->send = &udp_plugin_send_wrapper;
1051   api->send_with_session = &udp_plugin_send;
1052
1053   LOG (GNUNET_ERROR_TYPE_ERROR, "Setting up sockets\n");
1054   res = setup_sockets (plugin, &serverAddrv6, &serverAddrv4);
1055   if ((res == 0) || ((plugin->sockv4 == NULL) && (plugin->sockv6 == NULL)))
1056   {
1057     LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to create network sockets, plugin failed\n");
1058     GNUNET_free (plugin);
1059     GNUNET_free (api);
1060     return NULL;
1061   }
1062
1063   LOG (GNUNET_ERROR_TYPE_ERROR, "Starting broadcasting\n");
1064   setup_broadcast (plugin, &serverAddrv6, &serverAddrv4);
1065
1066
1067   GNUNET_free_non_null (bind4_address);
1068   GNUNET_free_non_null (bind6_address);
1069   return api;
1070 }
1071
1072 /**
1073  * The exported method. Makes the core api available via a global and
1074  * returns the udp transport API.
1075  *
1076  * @param cls our 'struct GNUNET_TRANSPORT_PluginEnvironment'
1077  * @return our 'struct GNUNET_TRANSPORT_PluginFunctions'
1078  */
1079 void *
1080 libgnunet_plugin_transport_udp_done (void *cls)
1081 {
1082   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1083   struct Plugin *plugin = api->cls;
1084
1085   stop_broadcast (plugin);
1086
1087   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
1088   {
1089     GNUNET_SCHEDULER_cancel (plugin->select_task);
1090     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1091   }
1092
1093   /* Closing sockets */
1094   if (plugin->sockv4 != NULL)
1095   {
1096     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv4));
1097     plugin->sockv4 = NULL;
1098   }
1099   if (plugin->sockv6 != NULL)
1100   {
1101     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (plugin->sockv6));
1102     plugin->sockv6 = NULL;
1103   }
1104   GNUNET_NETWORK_fdset_destroy (plugin->rs);
1105   GNUNET_NETWORK_fdset_destroy (plugin->ws);
1106   GNUNET_NAT_unregister (plugin->nat);
1107
1108   /* Clean up sessions */
1109 #if DEBUG_UDP
1110   LOG (GNUNET_ERROR_TYPE_DEBUG,
1111        "Cleaning up sessions\n");
1112 #endif
1113   GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions, &disconnect_and_free_it, plugin);
1114   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);
1115
1116   plugin->nat = NULL;
1117   GNUNET_free (plugin);
1118   GNUNET_free (api);
1119   return NULL;
1120 }
1121
1122
1123 /* end of plugin_transport_udp.c */