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