last step to new cadet api
[oweals/gnunet.git] / src / transport / plugin_transport_udp_broadcasting.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2010, 2011 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_udp_broadcasting.c
23  * @brief Neighbour discovery with UDP
24  * @author Christian Grothoff
25  * @author Matthias Wachs
26  */
27 #include "platform.h"
28 #include "plugin_transport_udp.h"
29 #include "gnunet_hello_lib.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_fragmentation_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_transport_plugin.h"
39 #include "transport.h"
40
41 #define LOG(kind,...) GNUNET_log_from (kind, "transport-udp", __VA_ARGS__)
42
43 /* *********** Cryogenic ********** */
44 #if LINUX
45 #include <sys/stat.h>
46 #include <fcntl.h>
47
48 #include <sys/ioctl.h>
49 #include <sys/select.h>
50 #include <sys/time.h>
51
52 #define PM_MAGIC 'k'
53 #define PM_SET_DELAY_AND_TIMEOUT _IOW(PM_MAGIC, 1, struct pm_times)
54
55 struct pm_times {
56         unsigned long delay_msecs;
57         unsigned long timeout_msecs;
58 };
59 #endif
60 /************************************/
61
62
63 struct UDP_Beacon_Message
64 {
65  /**
66   * Message header.
67   */
68   struct GNUNET_MessageHeader header;
69
70  /**
71   * What is the identity of the sender
72   */
73   struct GNUNET_PeerIdentity sender;
74 };
75
76
77 struct BroadcastAddress
78 {
79   struct BroadcastAddress *next;
80
81   struct BroadcastAddress *prev;
82
83   /**
84    * ID of select broadcast task
85    */
86   struct GNUNET_SCHEDULER_Task * broadcast_task;
87
88   struct Plugin *plugin;
89
90   struct sockaddr *addr;
91
92   socklen_t addrlen;
93
94 #if LINUX
95   /**
96    * Cryogenic handle.
97    */
98   struct GNUNET_DISK_FileHandle *cryogenic_fd;
99
100   /**
101    * Time out for cryogenic.
102    */
103   struct pm_times cryogenic_times;
104 #endif
105 };
106
107
108 /**
109  * Client-specific context for #broadcast_mst_cb().
110  */
111 struct MstContext
112 {
113   struct Plugin *plugin;
114
115   const union UdpAddress *udp_addr;
116
117   size_t udp_addr_len;
118
119   /**
120    * ATS network type.
121    */
122   enum GNUNET_ATS_Network_Type ats_address_network_type;
123 };
124
125
126 /**
127  * Parse broadcast message received.
128  *
129  * @param cls the `struct Plugin`
130  * @param client the `struct MstContext` with sender address
131  * @param message the message we received
132  * @return #GNUNET_OK (always)
133  */
134 static int
135 broadcast_mst_cb (void *cls,
136                   void *client,
137                   const struct GNUNET_MessageHeader *message)
138 {
139   struct Plugin *plugin = cls;
140   struct MstContext *mc = client;
141   struct GNUNET_HELLO_Address *address;
142   const struct GNUNET_MessageHeader *hello;
143   const struct UDP_Beacon_Message *msg;
144
145   msg = (const struct UDP_Beacon_Message *) message;
146
147   if (GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON !=
148       ntohs (msg->header.type))
149     return GNUNET_OK;
150   LOG (GNUNET_ERROR_TYPE_DEBUG,
151        "Received beacon with %u bytes from peer `%s' via address `%s'\n",
152        ntohs (msg->header.size),
153        GNUNET_i2s (&msg->sender),
154        udp_address_to_string (NULL,
155                               mc->udp_addr,
156                               mc->udp_addr_len));
157   hello = (struct GNUNET_MessageHeader *) &msg[1];
158   address = GNUNET_HELLO_address_allocate (&msg->sender,
159                                            PLUGIN_NAME,
160                                            mc->udp_addr,
161                                            mc->udp_addr_len,
162                                            GNUNET_HELLO_ADDRESS_INFO_NONE);
163   plugin->env->receive (plugin->env->cls,
164                         address,
165                         NULL,
166                         hello);
167   GNUNET_HELLO_address_free (address);
168   GNUNET_STATISTICS_update (plugin->env->stats,
169                             _("# Multicast HELLO beacons received via UDP"),
170                             1, GNUNET_NO);
171   return GNUNET_OK;
172 }
173
174
175 /**
176  * We received a broadcast message.  Process it and all subsequent
177  * messages in the same packet.
178  *
179  * @param plugin the UDP plugin
180  * @param buf the buffer with the message(s)
181  * @param size number of bytes in @a buf
182  * @param udp_addr address of the sender
183  * @param udp_addr_len number of bytes in @a udp_addr
184  * @param network_type network type of the sender's address
185  */
186 void
187 udp_broadcast_receive (struct Plugin *plugin,
188                        const char *buf,
189                        ssize_t size,
190                        const union UdpAddress *udp_addr,
191                        size_t udp_addr_len,
192                        enum GNUNET_ATS_Network_Type network_type)
193 {
194   struct MstContext mc;
195
196   mc.udp_addr = udp_addr;
197   mc.udp_addr_len = udp_addr_len;
198   mc.ats_address_network_type = network_type;
199   GNUNET_SERVER_mst_receive (plugin->broadcast_mst,
200                              &mc,
201                              buf, size,
202                              GNUNET_NO,
203                              GNUNET_NO);
204 }
205
206
207 static unsigned int
208 prepare_beacon (struct Plugin *plugin,
209                 struct UDP_Beacon_Message *msg)
210 {
211   uint16_t hello_size;
212   uint16_t msg_size;
213
214   const struct GNUNET_MessageHeader *hello;
215   hello = plugin->env->get_our_hello ();
216   if (NULL == hello)
217     return 0;
218   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
219   msg_size = hello_size + sizeof (struct UDP_Beacon_Message);
220
221   if (hello_size < (sizeof (struct GNUNET_MessageHeader)) ||
222       (msg_size > (UDP_MTU)))
223     return 0;
224
225   msg->sender = *(plugin->env->my_identity);
226   msg->header.size = htons (msg_size);
227   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BROADCAST_BEACON);
228   GNUNET_memcpy (&msg[1], hello, hello_size);
229   return msg_size;
230 }
231
232
233 static void
234 udp_ipv4_broadcast_send (void *cls)
235 {
236   struct BroadcastAddress *baddr = cls;
237   struct Plugin *plugin = baddr->plugin;
238   int sent;
239   uint16_t msg_size;
240   char buf[65536] GNUNET_ALIGN;
241
242   baddr->broadcast_task = NULL;
243
244   msg_size = prepare_beacon(plugin, (struct UDP_Beacon_Message *) &buf);
245   if (0 != msg_size)
246   {
247     struct sockaddr_in *addr = (struct sockaddr_in *) baddr->addr;
248
249     addr->sin_port = htons (plugin->port);
250     sent = GNUNET_NETWORK_socket_sendto (plugin->sockv4, &buf, msg_size,
251                                       (const struct sockaddr *) addr,
252                                       baddr->addrlen);
253     if (sent == GNUNET_SYSERR)
254     {
255       if ((ENETUNREACH == errno) || (ENETDOWN == errno))
256       {
257         /* "Network unreachable" or "Network down"
258          *
259          * This indicates that we just do not have network connectivity
260          */
261         GNUNET_log (GNUNET_ERROR_TYPE_BULK | GNUNET_ERROR_TYPE_WARNING,
262             "Network connectivity is down, cannot send beacon!\n");
263       }
264       else
265         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
266     }
267     else
268     {
269       LOG (GNUNET_ERROR_TYPE_DEBUG,
270            "Sent HELLO beacon broadcast with %i bytes to address %s\n", sent,
271            GNUNET_a2s (baddr->addr, baddr->addrlen));
272     }
273   }
274
275 #if LINUX
276   /*
277    * Cryogenic
278    */
279   if (NULL != baddr->cryogenic_fd)
280   {
281     baddr->cryogenic_times.delay_msecs = (plugin->broadcast_interval.rel_value_us/1000.0)*0.5;
282     baddr->cryogenic_times.timeout_msecs = (plugin->broadcast_interval.rel_value_us/1000.0)*1.5;
283
284     if (ioctl(baddr->cryogenic_fd->fd,
285                   PM_SET_DELAY_AND_TIMEOUT,
286                   &baddr->cryogenic_times) < 0)
287     {
288       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctl");
289       baddr->broadcast_task =
290           GNUNET_SCHEDULER_add_delayed (plugin->broadcast_interval,
291                                         &udp_ipv4_broadcast_send, baddr);
292     }
293     else
294       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
295                                            baddr->cryogenic_fd,
296                                                &udp_ipv4_broadcast_send,
297                                                baddr);
298
299   }
300   else
301 #endif
302     baddr->broadcast_task =
303         GNUNET_SCHEDULER_add_delayed (plugin->broadcast_interval,
304                                           &udp_ipv4_broadcast_send, baddr);
305 }
306
307
308 static void
309 udp_ipv6_broadcast_send (void *cls)
310 {
311   struct BroadcastAddress *baddr = cls;
312   struct Plugin *plugin = baddr->plugin;
313   ssize_t sent;
314   uint16_t msg_size;
315   char buf[65536] GNUNET_ALIGN;
316   const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) baddr->addr;
317
318   baddr->broadcast_task = NULL;
319
320   msg_size = prepare_beacon(plugin, (struct UDP_Beacon_Message *) &buf);
321   /* Note: unclear if this actually works to limit the multicast to
322      the specified interface as we're not (necessarily) using a
323      link-local multicast group and the kernel suggests that the
324      scope ID is only respected for link-local addresses; however,
325      if the scope ID is ignored, the kernel should just multicast
326      on ALL interfaces, which is merely slightly less efficient;
327      in that case, we might want to revert to only doing this
328      once, and not per interface (hard to test...) */
329   plugin->ipv6_multicast_address.sin6_scope_id = s6->sin6_scope_id;
330   sent = GNUNET_NETWORK_socket_sendto (plugin->sockv6, &buf, msg_size,
331                                     (const struct sockaddr *)
332                                     &plugin->ipv6_multicast_address,
333                                     sizeof (struct sockaddr_in6));
334   plugin->ipv6_multicast_address.sin6_scope_id = 0;
335   if (sent == GNUNET_SYSERR)
336   {
337     if ((ENETUNREACH == errno) || (ENETDOWN == errno))
338     {
339       /* "Network unreachable" or "Network down"
340        *
341        * This indicates that this system is IPv6 enabled, but does not
342        * have a valid global IPv6 address assigned
343        */
344       GNUNET_log (GNUNET_ERROR_TYPE_BULK | GNUNET_ERROR_TYPE_WARNING,
345           "Network connectivity is down, cannot send beacon!\n");
346     }
347     else
348       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "sendto");
349   }
350   else
351   {
352     LOG (GNUNET_ERROR_TYPE_DEBUG,
353          "Sending IPv6 HELLO beacon broadcast with %d bytes to address %s\n",
354          (int) sent,
355          GNUNET_a2s ((const struct sockaddr *) &plugin->ipv6_multicast_address,
356                      sizeof (struct sockaddr_in6)));
357   }
358 #if LINUX
359   /*
360    * Cryogenic
361    */
362   if (NULL != baddr->cryogenic_fd)
363   {
364     baddr->cryogenic_times.delay_msecs = (plugin->broadcast_interval.rel_value_us/1000.0)*0.5;
365     baddr->cryogenic_times.timeout_msecs = (plugin->broadcast_interval.rel_value_us/1000.0)*1.5;
366
367     if (ioctl(baddr->cryogenic_fd->fd,
368                   PM_SET_DELAY_AND_TIMEOUT,
369                   &baddr->cryogenic_times) < 0)
370     {
371       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctl");
372       baddr->broadcast_task =
373           GNUNET_SCHEDULER_add_delayed (plugin->broadcast_interval,
374                                         &udp_ipv6_broadcast_send, baddr);
375     }
376     else
377       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
378                                        baddr->cryogenic_fd,
379                                        &udp_ipv6_broadcast_send,
380                                        baddr);
381   }
382   else
383 #endif
384     baddr->broadcast_task =
385         GNUNET_SCHEDULER_add_delayed (plugin->broadcast_interval,
386                                       &udp_ipv6_broadcast_send, baddr);
387 }
388
389
390 /**
391  * Callback function invoked for each interface found.
392  *
393  * @param cls closure with the `struct Plugin`
394  * @param name name of the interface (can be NULL for unknown)
395  * @param isDefault is this presumably the default interface
396  * @param addr address of this interface (can be NULL for unknown or unassigned)
397  * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
398  * @param netmask the network mask (can be NULL for unknown or unassigned)
399  * @param addrlen length of the address
400  * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
401  */
402 static int
403 iface_proc (void *cls,
404             const char *name,
405             int isDefault,
406             const struct sockaddr *addr,
407             const struct sockaddr *broadcast_addr,
408             const struct sockaddr *netmask, socklen_t addrlen)
409 {
410   struct Plugin *plugin = cls;
411   struct BroadcastAddress *ba;
412   enum GNUNET_ATS_Network_Type network;
413
414   if (NULL == addr)
415     return GNUNET_OK;
416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
417               "address %s for interface %s %p\n ",
418               GNUNET_a2s (addr, addrlen), name, addr);
419   if (NULL == broadcast_addr)
420     return GNUNET_OK;
421   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
422               "broadcast address %s for interface %s %p\n ",
423               GNUNET_a2s (broadcast_addr, addrlen), name, broadcast_addr);
424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "netmask %s for interface %s %p\n ",
425               GNUNET_a2s (netmask, addrlen), name, netmask);
426
427   network = plugin->env->get_address_type (plugin->env->cls, broadcast_addr, addrlen);
428   if (GNUNET_ATS_NET_LOOPBACK == network)
429   {
430     /* Broadcasting on loopback does not make sense */
431     return GNUNET_YES;
432   }
433
434   ba = GNUNET_new (struct BroadcastAddress);
435   ba->plugin = plugin;
436   ba->addr = GNUNET_malloc (addrlen);
437   GNUNET_memcpy (ba->addr, broadcast_addr, addrlen);
438   ba->addrlen = addrlen;
439
440   if ( (GNUNET_YES == plugin->enable_ipv4) &&
441        (NULL != plugin->sockv4) &&
442        (addrlen == sizeof (struct sockaddr_in)) )
443   {
444 #if LINUX
445     /*
446      * setup Cryogenic FD for ipv4 broadcasting
447      */
448     char *filename;
449
450     GNUNET_asprintf (&filename,
451                      "/dev/cryogenic/%s",
452                      name);
453     if (0 == ACCESS (name, R_OK))
454     {
455       ba->cryogenic_fd =
456         GNUNET_DISK_file_open (filename,
457                                GNUNET_DISK_OPEN_WRITE,
458                                GNUNET_DISK_PERM_NONE);
459     }
460     GNUNET_free (filename);
461 #endif
462     ba->broadcast_task =
463         GNUNET_SCHEDULER_add_now (&udp_ipv4_broadcast_send, ba);
464   }
465   if ((GNUNET_YES == plugin->enable_ipv6) &&
466       (NULL != plugin->sockv6) &&
467       (addrlen == sizeof (struct sockaddr_in6)))
468   {
469     /* Create IPv6 multicast request */
470     struct ipv6_mreq multicastRequest;
471     const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) broadcast_addr;
472
473     multicastRequest.ipv6mr_multiaddr =
474         plugin->ipv6_multicast_address.sin6_addr;
475     /* http://tools.ietf.org/html/rfc2553#section-5.2:
476      *
477      * IPV6_JOIN_GROUP
478      *
479      * Join a multicast group on a specified local interface.  If the
480      * interface index is specified as 0, the kernel chooses the local
481      * interface.  For example, some kernels look up the multicast
482      * group in the normal IPv6 routing table and using the resulting
483      * interface; we do this for each interface, so no need to use
484      * zero (anymore...).
485      */
486     multicastRequest.ipv6mr_interface = s6->sin6_scope_id;
487
488     /* Join the multicast group */
489     if (GNUNET_OK !=
490         GNUNET_NETWORK_socket_setsockopt
491         (plugin->sockv6, IPPROTO_IPV6, IPV6_JOIN_GROUP,
492          &multicastRequest, sizeof (multicastRequest)))
493     {
494       LOG (GNUNET_ERROR_TYPE_WARNING,
495       "Failed to join IPv6 multicast group: IPv6 broadcasting not running\n");
496     }
497     else
498     {
499 #if LINUX
500       /*
501        * setup Cryogenic FD for ipv6 broadcasting
502        */
503       char *filename;
504
505       GNUNET_asprintf (&filename,
506                        "/dev/cryogenic/%s",
507                        name);
508       if (0 == ACCESS (name, R_OK))
509       {
510         ba->cryogenic_fd =
511           GNUNET_DISK_file_open (filename,
512                                  GNUNET_DISK_OPEN_WRITE,
513                                  GNUNET_DISK_PERM_NONE);
514       }
515       GNUNET_free (filename);
516 #endif
517       ba->broadcast_task =
518           GNUNET_SCHEDULER_add_now (&udp_ipv6_broadcast_send, ba);
519     }
520   }
521   GNUNET_CONTAINER_DLL_insert (plugin->broadcast_head,
522                                plugin->broadcast_tail, ba);
523   return GNUNET_OK;
524 }
525
526
527 /**
528  * Setup broadcasting subsystem.
529  *
530  * @param plugin
531  * @param server_addrv6
532  * @param server_addrv4
533  */
534 void
535 setup_broadcast (struct Plugin *plugin,
536                  struct sockaddr_in6 *server_addrv6,
537                  struct sockaddr_in *server_addrv4)
538 {
539   if (GNUNET_YES ==
540       GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
541                                             "topology",
542                                             "FRIENDS-ONLY"))
543   {
544     LOG (GNUNET_ERROR_TYPE_WARNING,
545          _("Disabling HELLO broadcasting due to friend-to-friend only configuration!\n"));
546     return;
547   }
548
549   /* always create tokenizers */
550   plugin->broadcast_mst =
551     GNUNET_SERVER_mst_create (&broadcast_mst_cb, plugin);
552
553   if (GNUNET_YES != plugin->enable_broadcasting)
554     return; /* We do not send, just receive */
555
556   /* create IPv4 broadcast socket */
557   if ((GNUNET_YES == plugin->enable_ipv4) && (NULL != plugin->sockv4))
558   {
559     static int yes = 1;
560
561     if (GNUNET_NETWORK_socket_setsockopt
562         (plugin->sockv4, SOL_SOCKET, SO_BROADCAST, &yes,
563          sizeof (int)) != GNUNET_OK)
564     {
565       LOG (GNUNET_ERROR_TYPE_WARNING,
566            _("Failed to set IPv4 broadcast option for broadcast socket on port %d\n"),
567            ntohs (server_addrv4->sin_port));
568     }
569   }
570   /* create IPv6 multicast socket */
571   if ((GNUNET_YES == plugin->enable_ipv6) && (plugin->sockv6 != NULL))
572   {
573     memset (&plugin->ipv6_multicast_address, 0, sizeof (struct sockaddr_in6));
574     GNUNET_assert (1 ==
575                    inet_pton (AF_INET6, "FF05::13B",
576                               &plugin->ipv6_multicast_address.sin6_addr));
577     plugin->ipv6_multicast_address.sin6_family = AF_INET6;
578     plugin->ipv6_multicast_address.sin6_port = htons (plugin->port);
579   }
580   GNUNET_OS_network_interfaces_list (&iface_proc, plugin);
581 }
582
583
584 /**
585  * Stop broadcasting subsystem.
586  *
587  * @param plugin
588  */
589 void
590 stop_broadcast (struct Plugin *plugin)
591 {
592   if (GNUNET_YES == plugin->enable_broadcasting)
593   {
594     /* Disable broadcasting */
595     while (plugin->broadcast_head != NULL)
596     {
597       struct BroadcastAddress *p = plugin->broadcast_head;
598
599       if (p->broadcast_task != NULL)
600       {
601         GNUNET_SCHEDULER_cancel (p->broadcast_task);
602         p->broadcast_task = NULL;
603       }
604       if ((GNUNET_YES == plugin->enable_ipv6) &&
605           (NULL != plugin->sockv6) &&
606           (p->addrlen == sizeof (struct sockaddr_in6)))
607       {
608         /* Create IPv6 multicast request */
609         struct ipv6_mreq multicastRequest;
610         const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) p->addr;
611
612         multicastRequest.ipv6mr_multiaddr =
613           plugin->ipv6_multicast_address.sin6_addr;
614         multicastRequest.ipv6mr_interface = s6->sin6_scope_id;
615
616         /* Leave the multicast group */
617         if (GNUNET_OK ==
618             GNUNET_NETWORK_socket_setsockopt
619             (plugin->sockv6, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
620              &multicastRequest, sizeof (multicastRequest)))
621         {
622           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
623         }
624         else
625         {
626           LOG (GNUNET_ERROR_TYPE_DEBUG, "IPv6 multicasting stopped\n");
627         }
628       }
629
630 #if LINUX
631     GNUNET_DISK_file_close(p->cryogenic_fd);
632 #endif
633       GNUNET_CONTAINER_DLL_remove (plugin->broadcast_head,
634                                    plugin->broadcast_tail, p);
635       GNUNET_free (p->addr);
636       GNUNET_free (p);
637     }
638   }
639
640   /* Destroy MSTs */
641   if (NULL != plugin->broadcast_mst)
642   {
643     GNUNET_SERVER_mst_destroy (plugin->broadcast_mst);
644     plugin->broadcast_mst = NULL;
645   }
646 }
647
648 /* end of plugin_transport_udp_broadcasting.c */