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