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