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