Change copyright year to 2019.
[paraslash.git] / udp_send.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file udp_send.c Para_server's udp sender. */
4
5 #include <netinet/in.h>
6 #include <sys/socket.h>
7 #include <regex.h>
8 #include <sys/types.h>
9 #include <netinet/udp.h>
10 #include <net/if.h>
11 #include <arpa/inet.h>
12 #include <sys/un.h>
13 #include <netdb.h>
14 #include <lopsub.h>
15
16 #include "server.lsg.h"
17 #include "para.h"
18 #include "error.h"
19 #include "string.h"
20 #include "afh.h"
21 #include "net.h"
22 #include "server.h"
23 #include "list.h"
24 #include "send.h"
25 #include "sched.h"
26 #include "vss.h"
27 #include "portable_io.h"
28 #include "fd.h"
29 #include "close_on_fork.h"
30
31 /**
32  * Time window during which ICMP Destination/Port Unreachable messages are
33  * ignored, covering transient receiver problems such as restarting the
34  * client, rebooting, reconfiguration, or handover.
35  */
36 #define UDP_MAX_UNREACHABLE_TIME 30
37
38 /** Describes one entry in the list of targets for the udp sender. */
39 struct udp_target {
40         /** Track time (seconds) of last ICMP Port Unreachable error */
41         time_t last_unreachable;
42         /** The opaque structure returned by vss_add_fec_client(). */
43         struct fec_client *fc;
44         /** The FEC parameters for this target. */
45         struct fec_client_parms fcp;
46         /** Whether we already sent the FEC eof packet to this target. */
47         bool sent_fec_eof;
48 };
49
50 static struct list_head targets;
51 static int sender_status;
52
53 static void udp_close_target(struct sender_client *sc)
54 {
55         const char *buf;
56         size_t len;
57         struct udp_target *ut = sc->private_data;
58
59         if (ut->sent_fec_eof)
60                 return;
61         PARA_NOTICE_LOG("sending FEC EOF\n");
62         len = vss_get_fec_eof_packet(&buf);
63         /* Ignore write() errors since we are closing the target anyway. */
64         if (write(sc->fd, buf, len))
65                 do_nothing; /* avoid "ignoring return value" warning */
66         ut->sent_fec_eof = true;
67 }
68
69 static void udp_delete_target(struct sender_client *sc, const char *msg)
70 {
71         struct udp_target *ut = sc->private_data;
72
73         PARA_NOTICE_LOG("deleting %s (%s) from list\n", sc->name, msg);
74         udp_close_target(sc);
75         /* command handlers already called close_listed_fds() */
76         if (!process_is_command_handler()) {
77                 close(sc->fd);
78                 del_close_on_fork_list(sc->fd);
79         }
80         vss_del_fec_client(ut->fc);
81         list_del(&sc->node);
82         free(sc->name);
83         free(sc);
84         free(ut);
85 }
86
87 /**
88  * Perform AF-independent multicast sender setup.
89  *
90  * \param sc    The connected sender client.
91  *
92  * \return Zero if okay, negative on error.
93  */
94 static int mcast_sender_setup(struct sender_client *sc)
95 {
96         struct sockaddr_storage ss;
97         socklen_t sslen = sizeof(ss);
98         int ttl = OPT_INT32_VAL(UDP_TTL), id = 0;
99         const int on = 1;
100
101         if (OPT_GIVEN(UDP_MCAST_IFACE)) {
102                 const char *iface = OPT_STRING_VAL(UDP_MCAST_IFACE);
103
104                 id = if_nametoindex(iface);
105                 if (id == 0)
106                         PARA_WARNING_LOG("could not resolve interface '%s', "
107                                         "using default", iface);
108         }
109
110         if (getpeername(sc->fd, (struct sockaddr *)&ss, &sslen) < 0)
111                 goto err;
112         assert(ss.ss_family == AF_INET || ss.ss_family == AF_INET6);
113
114         /* RFC 3493, 5.2: -1 means 'use kernel default' */
115         if (ttl < 0 || ttl > 255)
116                 ttl = -1;
117
118         switch (ss.ss_family) {
119         case AF_INET:
120                 if (!IN_MULTICAST(htonl(((struct sockaddr_in *)&ss)->sin_addr.s_addr)))
121                         return 0;
122                 if (id != 0) {
123 #ifdef HAVE_IP_MREQN
124                         struct ip_mreqn mn;
125
126                         memset(&mn, 0, sizeof(mn));
127                         mn.imr_ifindex = id;
128                         if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_IF, &mn, sizeof(mn)) < 0)
129                                 goto err;
130 #else
131                         PARA_ERROR_LOG("No support for setting outgoing IPv4 mcast interface.");
132 #endif
133                 }
134                 /*
135                  * Enable receiving multicast messages generated on the local host
136                  * At least on Linux, this is enabled by default.
137                  */
138                 if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &on, sizeof(on)) < 0)
139                         break;
140
141                 /* Default: use local subnet (do not flood out into the WAN) */
142                 if (ttl == -1)
143                         ttl = 1;
144                 if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0)
145                         break;
146                 return 0;
147         case AF_INET6:
148                 if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)&ss)->sin6_addr))
149                         return 0;
150                 if (id != 0 &&
151                     setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &id, sizeof(id)) < 0)
152                         break;
153                 if (setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &on, sizeof(on)) < 0)
154                         break;
155                 if (setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)) < 0)
156                         break;
157                 return 0;
158         }
159 err:
160         return -ERRNO_TO_PARA_ERROR(errno);
161 }
162
163 static void udp_shutdown_targets(void)
164 {
165         struct sender_client *sc, *tmp;
166         list_for_each_entry_safe(sc, tmp, &targets, node)
167                 udp_close_target(sc);
168 }
169
170 static void udp_shutdown(void)
171 {
172         struct sender_client *sc, *tmp;
173         list_for_each_entry_safe(sc, tmp, &targets, node)
174                 udp_delete_target(sc, "shutdown");
175 }
176
177 static int udp_resolve_target(const char *url, struct sender_command_data *scd)
178 {
179         const char *result;
180         int ret, port;
181
182         ret = parse_fec_url(url, scd);
183         if (ret)
184                 return ret;
185         port = scd->port > 0 ? scd->port : OPT_UINT32_VAL(UDP_DEFAULT_PORT);
186
187         ret = para_connect_simple(IPPROTO_UDP, scd->host, port);
188         if (ret < 0)
189                 return ret;
190
191         result = remote_name(ret);
192         close(ret);
193
194         if (!parse_url(result, scd->host, sizeof(scd->host), &scd->port))
195                 return -E_ADDRESS_LOOKUP;
196         return 1;
197 }
198
199 static int udp_com_on(__a_unused struct sender_command_data *scd)
200 {
201         sender_status = SENDER_on;
202         return 1;
203 }
204
205 static int udp_com_off(__a_unused struct sender_command_data *scd)
206 {
207         udp_shutdown_targets();
208         sender_status = SENDER_off;
209         return 1;
210 }
211
212 static struct sender_client *udp_lookup_target(struct sender_command_data *scd)
213 {
214         struct sender_client *sc, *tmp;
215         char host[MAX_HOSTLEN];
216         int32_t port;
217
218         list_for_each_entry_safe(sc, tmp, &targets, node) {
219                 parse_url(sc->name, host, sizeof(host), &port);
220
221                 /* Unspecified port means wildcard port match */
222                 if (scd->port > 0 && scd->port != port)
223                         continue;
224                 if (strcmp(host, scd->host))
225                         continue;
226                 return sc;
227         }
228         return NULL;
229 }
230
231 static int udp_com_delete(struct sender_command_data *scd)
232 {
233         struct sender_client *sc = udp_lookup_target(scd);
234
235         if (sc) {
236                 udp_delete_target(sc, "com_delete");
237                 return 1;
238         }
239         PARA_NOTICE_LOG("not deleting non-existing target '%s'\n", scd->host);
240         return -E_TARGET_NOT_FOUND;
241 }
242
243 /** Initialize UDP session and set maximum payload size. */
244 static int udp_init_fec(struct sender_client *sc)
245 {
246         struct udp_target *ut = sc->private_data;
247         int mps;
248
249         PARA_NOTICE_LOG("sending to udp %s\n", sc->name);
250         ut->sent_fec_eof = false;
251         mps = generic_max_transport_msg_size(sc->fd) - sizeof(struct udphdr);
252         PARA_INFO_LOG("current MPS = %d bytes\n", mps);
253         return mps;
254 }
255
256 /** Check and clear socket error if any. */
257 static int udp_check_socket_state(struct sender_client *sc)
258 {
259         struct udp_target *ut = sc->private_data;
260         int ret;
261         socklen_t errlen = sizeof(ret);
262
263         if (getsockopt(sc->fd, SOL_SOCKET, SO_ERROR, &ret, &errlen) < 0) {
264                 PARA_ERROR_LOG("SO_ERROR failed: %s\n", strerror(ret));
265                 return 0;
266         } else if (ret == 0) {
267                 return 0;
268         } else if (ret == ECONNREFUSED) {
269                 time_t dist = now->tv_sec - ut->last_unreachable;
270
271                 if (dist <= UDP_MAX_UNREACHABLE_TIME) {
272                         return 0;
273                 } else if (dist > 2 * UDP_MAX_UNREACHABLE_TIME) {
274                         ut->last_unreachable = now->tv_sec;
275                         return 0;
276                 } else {
277                         /*
278                          * unreachable_time < dist <= 2 * unreachable_time
279                          * No errors are allowed during this time window.
280                          */
281                         PARA_NOTICE_LOG("Evicting %s after %d seconds "
282                                         "of connection errors.\n",
283                                         sc->name, (int)dist);
284                 }
285         }
286         return -ERRNO_TO_PARA_ERROR(ret);
287 }
288
289 static void udp_send_fec(struct sender_client *sc, char *buf, size_t len)
290 {
291         int ret;
292
293         if (sender_status == SENDER_off)
294                 return;
295         if (len == 0)
296                 return;
297         ret = udp_check_socket_state(sc);
298         if (ret < 0)
299                 goto fail;
300         ret = xwrite(sc->fd, buf, len);
301         if (ret == -ERRNO_TO_PARA_ERROR(ECONNREFUSED)) {
302                 /*
303                  * Happens if meanwhile an ICMP Destination / Port Unreachable
304                  * has arrived. Ignore, persistent errors will be caught above.
305                  */
306                 ret = 0;
307         }
308         if (ret < 0)
309                 goto fail;
310         return;
311 fail:
312         udp_delete_target(sc, para_strerror(-ret));
313 }
314
315 static int udp_com_add(struct sender_command_data *scd)
316 {
317         int ret;
318         struct udp_target *ut;
319         struct sender_client *sc = udp_lookup_target(scd);
320
321         if (sc) {
322                 PARA_NOTICE_LOG("target %s already exists - not adding it\n",
323                                 sc->name);
324                 return -E_TARGET_EXISTS;
325         }
326         ut = para_calloc(sizeof(*ut));
327         sc = para_calloc(sizeof(*sc));
328         ut->fcp.slices_per_group      = scd->slices_per_group;
329         ut->fcp.data_slices_per_group = scd->data_slices_per_group;
330         ut->fcp.init_fec              = udp_init_fec;
331         ut->fcp.send_fec              = udp_send_fec;
332         ut->fcp.need_periodic_header  = true;
333
334         sc->private_data = ut;
335         sc->fd = -1;
336         ret = para_connect_simple(IPPROTO_UDP, scd->host, scd->port);
337         if (ret < 0)
338                 goto err;
339         sc->fd = ret;
340
341         ret = mcast_sender_setup(sc);
342         if (ret < 0)
343                 goto err;
344         ret = mark_fd_nonblocking(sc->fd);
345         if (ret < 0)
346                 goto err;
347         sc->name = para_strdup(remote_name(sc->fd));
348         PARA_INFO_LOG("adding to target list (%s)\n", sc->name);
349         ut->fc = vss_add_fec_client(sc, &ut->fcp);
350         para_list_add(&sc->node, &targets);
351         add_close_on_fork_list(sc->fd);
352         return 1;
353 err:
354         if (sc->fd >= 0)
355                 close(sc->fd);
356         PARA_NOTICE_LOG("failed to set up %s:%d (%s)- not adding it\n",
357                         scd->host, scd->port, para_strerror(-ret));
358         free(sc);
359         free(ut);
360         return ret;
361 }
362
363 static char *udp_status(void)
364 {
365         struct sender_client *sc;
366         char *ret, *tgts = NULL;
367
368         list_for_each_entry(sc, &targets, node) {
369                 struct udp_target *ut = sc->private_data;
370                 char *tmp = make_message("%s%s/%u:%u ",
371                         tgts ? : "", sc->name,
372                         ut->fcp.data_slices_per_group,
373                         ut->fcp.slices_per_group
374                 );
375                 free(tgts);
376                 tgts = tmp;
377         }
378         ret = make_message(
379                 "status: %s\n"
380                 "port: %s\n"
381                 "targets: %s\n",
382                 (sender_status == SENDER_on)? "on" : "off",
383                 stringify_port(OPT_UINT32_VAL(UDP_DEFAULT_PORT), "udp"),
384                 tgts? tgts : "(none)"
385         );
386         free(tgts);
387         return ret;
388 }
389
390 static void udp_init_target_list(void)
391 {
392         struct sender_command_data scd;
393         int i;
394
395         INIT_LIST_HEAD(&targets);
396         for (i = 0; i < OPT_GIVEN(UDP_TARGET); i++) {
397                 const char *arg = lls_string_val(i, OPT_RESULT(UDP_TARGET));
398                 if (udp_resolve_target(arg, &scd) < 0)
399                         PARA_CRIT_LOG("not adding requested target '%s'\n",
400                                         arg);
401                 else
402                         udp_com_add(&scd);
403         }
404 }
405
406 static char *udp_help(void)
407 {
408         return make_message(
409                 "usage: {on|off}\n"
410                 "usage: {add|delete} ip_address[:port][/[packet_size:]k:n]\n"
411                 "       - k is the number of data slices per FEC group\n"
412                 "       - n is the total number of slices in a FEC group\n"
413                 "       - packet_size reduces the slice size below path MTU\n\n"
414                 "examples: add 224.0.1.38:1500  (IPv4 multicast)\n"
415                 "          add 224.0.1.38:8080/14:16 (explicit FEC)\n"
416                 "          add 10.10.1.42       (using default port)\n"
417                 "          add [FF05::42]:1500  (IPv6 multicast)\n"
418                 "          add [::1]            (IPv6 localhost/default port)\n"
419                 "          delete myhost.net    (host with port wildcard)\n"
420                 "          delete 10.1.2.3:456  (IPv4 with explicit port)\n"
421                 "          delete [badc0de::1]  (IPv6 with port wildcard)\n"
422         );
423 }
424
425 /* Initialize the list of udp targets. */
426 static void udp_send_init(void)
427 {
428         INIT_LIST_HEAD(&targets);
429         sender_status = SENDER_off;
430         udp_init_target_list();
431         if (!OPT_GIVEN(UDP_NO_AUTOSTART))
432                 sender_status = SENDER_on;
433         PARA_DEBUG_LOG("udp sender init complete\n");
434 }
435
436 /**
437  * The UDP sender.
438  *
439  * In contrast to the other senders the UDP sender is active in the sense that
440  * it initiates the network connection according to its list of targets rather
441  * than passively waiting for clients to connect. Like DCCP streams, UDP
442  * streams are always sent FEC-encoded. The UDP sender is the only sender which
443  * supports IP multicasting.
444  */
445 const struct sender udp_sender = {
446         .name = "udp",
447         .init = udp_send_init,
448         .shutdown = udp_shutdown,
449         .shutdown_clients = udp_shutdown_targets,
450         .resolve_target = udp_resolve_target,
451         .client_cmds = {
452                 [SENDER_on] = udp_com_on,
453                 [SENDER_off] = udp_com_off,
454                 [SENDER_add] = udp_com_add,
455                 [SENDER_delete] = udp_com_delete,
456         },
457         .help = udp_help,
458         .status = udp_status,
459 };