Introduce LIST_HEAD macro and use it in audiod_command.
[paraslash.git] / udp_send.c
index 7704b0a1a8f01b1580bae58c59a2817ca324371e..f8cce2b943d0f204a089cc9c06a6911f879a0541 100644 (file)
@@ -7,8 +7,12 @@
 /** \file udp_send.c Para_server's udp sender. */
 
 
+#include <regex.h>
 #include <sys/time.h>
 #include <dirent.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <osl.h>
 
 #include "server.cmdline.h"
 #include "para.h"
 #include "list.h"
 #include "send.h"
 #include "portable_io.h"
-#include "udp_header.h"
 #include "net.h"
 #include "fd.h"
 #include "sched.h"
 #include "close_on_fork.h"
 #include "chunk_queue.h"
 
-/** Convert in_addr to ascii. */
-#define TARGET_ADDR(oc) inet_ntoa((oc)->addr)
-
 /** Describes one entry in the list of targets for the udp sender. */
 struct udp_target {
-       /** Address info. */
-       struct in_addr addr;
        /** The position of this target in the list of targets. */
        struct list_head node;
+       /** The hostname (DNS name or IPv4/v6 address string). */
+       char host[MAX_HOSTLEN];
        /** The UDP port. */
        int port;
        /** The socket fd. */
        int fd;
        /** The list of queued chunks for this fd. */
        struct chunk_queue *cq;
+       /** The opaque structure returned by vss_add_fec_client(). */
+       struct fec_client *fc;
+       /** The FEC parameters for this target. */
+       struct fec_client_parms fcp;
 };
 
 static struct list_head targets;
@@ -61,45 +65,115 @@ static void udp_close_target(struct udp_target *ut)
 
 static void udp_delete_target(struct udp_target *ut, const char *msg)
 {
-       PARA_NOTICE_LOG("deleting %s:%d (%s) from list\n", TARGET_ADDR(ut),
+       PARA_NOTICE_LOG("deleting %s#%d (%s) from list\n", ut->host,
                ut->port, msg);
        udp_close_target(ut);
+       vss_del_fec_client(ut->fc);
        list_del(&ut->node);
        free(ut);
 }
 
-static void udp_send_buf(char *buf, size_t len)
+/**
+ * Perform AF-independent multicast sender setup.
+ *
+ * \param fd   The connected socket descriptor.
+ * \param ttl  UDPv4 multicast TTL or UDPv6 multicast number of hops.
+ *             Use -1 to mean default, 0..255 otherwise.
+ * \param iface        The outgoing multicast interface, or NULL for the default.
+ *
+ * \return Zero if okay, negative on error.
+ */
+static int mcast_sender_setup(struct udp_target *ut, int ttl, char *iface)
 {
-       struct udp_target *ut, *tmp;
-       int ret;
-
-       list_for_each_entry_safe(ut, tmp, &targets, node) {
-               if (ut->fd < 0)
-                       continue;
-               ret = write_nonblock(ut->fd, buf, len, len);
-               if (ret < 0) {
-                       udp_delete_target(ut, para_strerror(-ret));
-                       continue;
+       struct sockaddr_storage ss;
+       socklen_t sslen = sizeof(ss);
+
+       const int on = 1;
+       int id = iface == NULL ? 0 : if_nametoindex(iface);
+
+       if (getpeername(ut->fd, (struct sockaddr *)&ss, &sslen) < 0)
+               goto err;
+
+       if (iface != NULL && id == 0)
+               PARA_WARNING_LOG("could not resolve interface %s, using default", iface);
+
+       /* RFC 3493, 5.2: -1 means 'use kernel default' */
+       if (ttl < 0 || ttl > 255)
+               ttl = -1;
+
+       switch (ss.ss_family) {
+       case AF_INET:
+               if (!IN_MULTICAST(htonl(((struct sockaddr_in *)&ss)->sin_addr.s_addr)))
+                       return 0;
+               if (id != 0) {
+#ifdef HAVE_IP_MREQN
+                       struct ip_mreqn mn;
+
+                       memset(&mn, 0, sizeof(mn));
+                       mn.imr_ifindex = id;
+                       if (setsockopt(ut->fd, IPPROTO_IP, IP_MULTICAST_IF, &mn, sizeof(mn)) < 0)
+                               goto err;
+#else
+                       PARA_ERROR_LOG("No support for setting outgoing IPv4 mcast interface.");
+#endif
                }
-               if (ret != len)
-                       PARA_WARNING_LOG("short write %zu/%zu\n", ret, len);
+               /*
+                * Enable receiving multicast messages generated on the local host
+                * At least on Linux, this is enabled by default.
+                */
+               if (setsockopt(ut->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &on, sizeof(on)) < 0)
+                       break;
+
+               /* Default: use local subnet (do not flood out into the WAN) */
+               if (ttl == -1)
+                       ttl = 1;
+               if (setsockopt(ut->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0)
+                       break;
+               return 0;
+       case AF_INET6:
+               if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)&ss)->sin6_addr))
+                       return 0;
+               if (id != 0 &&
+                   setsockopt(ut->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &id, sizeof(id)) < 0)
+                       break;
+               if (setsockopt(ut->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &on, sizeof(on)) < 0)
+                       break;
+               if (setsockopt(ut->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)) < 0)
+                       break;
+               return 0;
+       default:
+               PARA_ERROR_LOG("address family %d not supported", ss.ss_family);
+               return -E_ADDRESS_LOOKUP;
        }
+err:
+       return -ERRNO_TO_PARA_ERROR(errno);
 }
 
+/** The maximal size of the per-target chunk queue. */
 #define UDP_CQ_BYTES 40000
 
 static int udp_init_session(struct udp_target *ut)
 {
        int ret;
+       char *iface = NULL;
 
        if (ut->fd >= 0) /* nothing to do */
                return 0;
-       PARA_NOTICE_LOG("sending to udp %s:%d\n", TARGET_ADDR(ut), ut->port);
-       ret = create_udp_send_socket(TARGET_ADDR(ut), ut->port,
-               conf.udp_ttl_arg);
+
+       ret = makesock(AF_UNSPEC, IPPROTO_UDP, 0, ut->host, ut->port);
        if (ret < 0)
                return ret;
        ut->fd = ret;
+
+       if (conf.udp_mcast_iface_given)
+               iface = conf.udp_mcast_iface_arg;
+
+       ret = mcast_sender_setup(ut, conf.udp_ttl_arg, iface);
+       if (ret < 0) {
+               close(ut->fd);
+               return ret;
+       }
+
        ret = mark_fd_nonblocking(ut->fd);
        if (ret < 0) {
                close(ut->fd);
@@ -107,86 +181,28 @@ static int udp_init_session(struct udp_target *ut)
        }
        add_close_on_fork_list(ut->fd);
        ut->cq = cq_new(UDP_CQ_BYTES);
+       PARA_NOTICE_LOG("sending to udp %s#%d using fec parms %d:%d:%d\n",
+               ut->host, ut->port , ut->fcp.max_slice_bytes,
+               ut->fcp.data_slices_per_group, ut->fcp.slices_per_group);
        return 1;
 }
 
 static void udp_shutdown_targets(void)
 {
-       char buf[UDP_AUDIO_HEADER_LEN];
        struct udp_target *ut, *tmp;
+       const char *buf = NULL;
+       size_t len = 0; /* STFU, gcc */
 
-       udp_write_packet_type(buf, UDP_EOF_PACKET);
-       udp_write_magic(buf);
        list_for_each_entry_safe(ut, tmp, &targets, node) {
                if (ut->fd < 0)
                        continue;
-               write(ut->fd, buf, UDP_AUDIO_HEADER_LEN);
+               if (!buf)
+                       len = vss_get_fec_eof_packet(&buf);
+               write(ut->fd, buf, len);
                udp_close_target(ut);
        }
 }
 
-static int need_extra_header(long unsigned current_chunk)
-{
-       static struct timeval last_header;
-       struct timeval diff;
-
-       if (!current_chunk)
-               return 0;
-       tv_diff(now, &last_header, &diff);
-       if (tv2ms(&diff) < conf.udp_header_interval_arg)
-               return 0;
-       last_header = *now;
-       return 1;
-}
-
-static void udp_send(long unsigned current_chunk, __a_unused long unsigned chunks_sent,
-               const char *buf, size_t len, const char *header_buf,
-               size_t header_len)
-{
-       struct udp_target *ut, *tmp;
-       size_t sendbuf_len;
-       uint8_t packet_type = UDP_DATA_PACKET;
-       int ret;
-       char *sendbuf;
-       struct timeval *chunk_tv;
-       uint8_t stream_type = header_len? UDP_HEADER_STREAM : UDP_PLAIN_STREAM;
-
-//     PARA_NOTICE_LOG("header_len: %zd, header_buf: %p\n", header_len,
-//             header_buf);
-       if (sender_status != SENDER_ON)
-               return;
-
-       /* we might not yet know the chunk time */
-       chunk_tv = vss_chunk_time();
-       if (!chunk_tv)
-               return;
-       if (list_empty(&targets))
-               return;
-       list_for_each_entry_safe(ut, tmp, &targets, node) {
-               ret = udp_init_session(ut);
-               if (ret < 0)
-                       udp_delete_target(ut, para_strerror(-ret));
-       }
-       if (!need_extra_header(current_chunk))
-               header_len = 0;
-       if (!current_chunk)
-               packet_type = UDP_BOF_PACKET;
-       else if (header_len)
-               packet_type = UDP_HEADER_PACKET;
-       sendbuf_len = UDP_AUDIO_HEADER_LEN + header_len + len;
-       sendbuf = para_malloc(sendbuf_len);
-       udp_write_magic(sendbuf);
-       udp_write_stream_type(sendbuf, stream_type);
-       udp_write_packet_type(sendbuf, packet_type);
-       udp_write_header_len(sendbuf, header_len);
-       if (header_len)
-               memcpy(sendbuf + UDP_AUDIO_HEADER_LEN, header_buf,
-                       header_len);
-       memcpy(sendbuf + UDP_AUDIO_HEADER_LEN + header_len, buf, len);
-       udp_send_buf(sendbuf, sendbuf_len);
-       free(sendbuf);
-}
-
 static int udp_com_on(__a_unused struct sender_command_data *scd)
 {
        sender_status = SENDER_ON;
@@ -202,33 +218,70 @@ static int udp_com_off(__a_unused struct sender_command_data *scd)
 
 static int udp_com_delete(struct sender_command_data *scd)
 {
-       char *a = para_strdup(inet_ntoa(scd->addr));
        struct udp_target *ut, *tmp;
+
        list_for_each_entry_safe(ut, tmp, &targets, node) {
-               if (scd->port != ut->port)
+               /* Unspecified port means wildcard port match */
+               if (scd->port > 0 && scd->port != ut->port)
                        continue;
-               if (strcmp(TARGET_ADDR(ut), a))
+               if (strcmp(ut->host, scd->host))
                        continue;
                udp_delete_target(ut, "com_delete");
        }
        return 1;
 }
 
-static void udp_add_target(int port, struct in_addr *addr)
+static int udp_send_fec(char *buf, size_t len, void *private_data)
+{
+       struct udp_target *ut = private_data;
+       int ret = udp_init_session(ut);
+
+       if (ret < 0)
+               goto fail;
+       ret = send_queued_chunks(ut->fd, ut->cq, 0);
+       if (ret < 0)
+               goto fail;
+       if (!len)
+               return 0;
+       if (!ret) { /* still data left in the queue */
+               ret = cq_enqueue(ut->cq, buf, len);
+               if (ret < 0)
+                       goto fail;
+       }
+       ret = write_nonblock(ut->fd, buf, len, 0);
+       if (ret < 0)
+               goto fail;
+       if (ret != len) {
+               ret = cq_enqueue(ut->cq, buf + ret, len - ret);
+               if (ret < 0)
+                       goto fail;
+       }
+       return 1;
+fail:
+       udp_delete_target(ut, para_strerror(-ret));
+       return ret;
+}
+
+static void udp_add_target(struct sender_command_data *scd)
 {
        struct udp_target *ut = para_calloc(sizeof(struct udp_target));
-       ut->port = port;
-       ut->addr = *addr;
+
+       strncpy(ut->host, scd->host, sizeof(ut->host));
+       ut->port = scd->port > 0 ? scd->port : conf.udp_default_port_arg;
        ut->fd = -1; /* not yet connected */
-       PARA_INFO_LOG("adding to target list (%s:%d)\n",
-               TARGET_ADDR(ut), ut->port);
+       PARA_INFO_LOG("adding to target list (%s#%d)\n", ut->host, ut->port);
        para_list_add(&ut->node, &targets);
+       ut->fcp.slices_per_group = scd->slices_per_group;
+       ut->fcp.data_slices_per_group = scd->data_slices_per_group;
+       ut->fcp.max_slice_bytes = scd->max_slice_bytes;
+       ut->fcp.send = udp_send_fec;
+       ut->fcp.private_data = ut;
+       vss_add_fec_client(&ut->fcp, &ut->fc);
 }
 
 static int udp_com_add(struct sender_command_data *scd)
 {
-       int port = (scd->port > 0)? scd->port : conf.udp_default_port_arg;
-       udp_add_target(port, &scd->addr);
+       udp_add_target(scd);
        return 1;
 }
 
@@ -238,8 +291,14 @@ static char *udp_info(void)
        char *ret, *tgts = NULL;
 
        list_for_each_entry(ut, &targets, node) {
-               char *tmp = make_message("%s%s:%d ", tgts? tgts : "",
-                       TARGET_ADDR(ut), ut->port);
+               bool is_v6 = strchr(ut->host, ':') != NULL;
+               char *tmp = make_message("%s%s%s%s:%d/%u:%u:%u ", tgts ? : "",
+                       is_v6 ? "[" : "", ut->host,
+                       is_v6 ? "]" : "", ut->port,
+                       ut->fcp.max_slice_bytes,
+                       ut->fcp.data_slices_per_group,
+                       ut->fcp.slices_per_group
+               );
                free(tgts);
                tgts = tmp;
        }
@@ -258,31 +317,17 @@ static char *udp_info(void)
 
 static void udp_init_target_list(void)
 {
+       struct sender_command_data scd;
        int i;
 
        INIT_LIST_HEAD(&targets);
        for (i = 0; i < conf.udp_target_given; i++) {
-               char *arg = para_strdup(conf.udp_target_arg[i]);
-               char *p = strchr(arg, ':');
-               int port;
-               struct in_addr addr;
-
-               if (!p)
-                       goto err;
-               *p = '\0';
-               if (!inet_pton(AF_INET, arg, &addr))
-                       goto err;
-               port = atoi(++p);
-               if (port < 0 || port > 65535)
-                       port = conf.udp_default_port_arg;
-               udp_add_target(port, &addr);
-               goto success;
-err:
-               PARA_CRIT_LOG("syntax error for udp target option "
-                       "#%d, ignoring\n", i);
-success:
-               free(arg);
-               continue;
+               if (parse_fec_url(conf.udp_target_arg[i], &scd) < 0) {
+                       PARA_CRIT_LOG("syntax error for udp target option "
+                               "#%d, ignoring\n", i);
+                       continue;
+               }
+               udp_add_target(&scd);
        }
 }
 
@@ -290,15 +335,23 @@ static char *udp_help(void)
 {
        return make_message(
                "usage: {on|off}\n"
-               "usage: {add|delete} IP port\n"
-               "example: add 224.0.1.38 8000 (multicast streaming)\n"
+               "usage: {add|delete} host[:port][/packet_size:k:n]\n"
+               "examples: add 224.0.1.38:1500  (IPv4 multicast)\n"
+               "          add 224.0.1.38:1500/1400:14:16\n"
+               "              (likewise, using 1400 byte packets, with 14\n"
+               "               data slices per 16 slice FEC group)\n"
+               "          add 10.10.1.42       (using default port)\n"
+               "          add [FF05::42]:1500  (IPv6 multicast)\n"
+               "          add [::1]            (IPv6 localhost/default port)\n"
+               "          delete myhost.net    (host with port wildcard)\n"
+               "          delete [badc0de::1]  (IPv6 with port wildcard)\n"
        );
 }
 
 /**
  * The init function of para_server's udp sender.
  *
- * \param s Pointer to the http sender struct.
+ * \param s Pointer to the udp sender struct.
  *
  * It initializes all function pointers of \a s and the list of udp targets.
  */
@@ -307,7 +360,7 @@ void udp_send_init(struct sender *s)
        INIT_LIST_HEAD(&targets);
        s->info = udp_info;
        s->help = udp_help;
-       s->send = udp_send;
+       s->send = NULL;
        s->pre_select = NULL;
        s->post_select = NULL;
        s->shutdown_clients = udp_shutdown_targets;