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