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