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