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