Merge branch 'refs/heads/t/lopsub'
[paraslash.git] / udp_send.c
1 /*
2  * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
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 <netinet/udp.h>
14 #include <net/if.h>
15 #include <arpa/inet.h>
16 #include <sys/un.h>
17 #include <netdb.h>
18 #include <lopsub.h>
19
20 #include "server.lsg.h"
21 #include "para.h"
22 #include "error.h"
23 #include "string.h"
24 #include "afh.h"
25 #include "server.h"
26 #include "list.h"
27 #include "send.h"
28 #include "sched.h"
29 #include "vss.h"
30 #include "portable_io.h"
31 #include "net.h"
32 #include "fd.h"
33 #include "close_on_fork.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         /** The opaque structure returned by vss_add_fec_client(). */
47         struct fec_client *fc;
48         /** The FEC parameters for this target. */
49         struct fec_client_parms fcp;
50         /** Whether we already sent the FEC eof packet to this target. */
51         bool sent_fec_eof;
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;
61         struct udp_target *ut = sc->private_data;
62
63         if (ut->sent_fec_eof)
64                 return;
65         PARA_NOTICE_LOG("sending FEC EOF\n");
66         len = vss_get_fec_eof_packet(&buf);
67         /* Ignore write() errors since we are closing the target anyway. */
68         if (write(sc->fd, buf, len) == len)
69                 ut->sent_fec_eof = true;
70 }
71
72 static void udp_delete_target(struct sender_client *sc, const char *msg)
73 {
74         struct udp_target *ut = sc->private_data;
75
76         PARA_NOTICE_LOG("deleting %s (%s) from list\n", sc->name, msg);
77         udp_close_target(sc);
78         close(sc->fd);
79         del_close_on_fork_list(sc->fd);
80         vss_del_fec_client(ut->fc);
81         list_del(&sc->node);
82         free(sc->name);
83         free(sc);
84         free(ut);
85 }
86
87 /**
88  * Perform AF-independent multicast sender setup.
89  *
90  * \param sc    The connected sender client.
91  *
92  * \return Zero if okay, negative on error.
93  */
94 static int mcast_sender_setup(struct sender_client *sc)
95 {
96         struct sockaddr_storage ss;
97         socklen_t sslen = sizeof(ss);
98         int ttl = OPT_INT32_VAL(UDP_TTL), id = 0;
99         const int on = 1;
100
101         if (OPT_GIVEN(UDP_MCAST_IFACE)) {
102                 const char *iface = OPT_STRING_VAL(UDP_MCAST_IFACE);
103
104                 id = if_nametoindex(iface);
105                 if (id == 0)
106                         PARA_WARNING_LOG("could not resolve interface '%s', "
107                                         "using default", iface);
108         }
109
110         if (getpeername(sc->fd, (struct sockaddr *)&ss, &sslen) < 0)
111                 goto err;
112         assert(ss.ss_family == AF_INET || ss.ss_family == AF_INET6);
113
114         /* RFC 3493, 5.2: -1 means 'use kernel default' */
115         if (ttl < 0 || ttl > 255)
116                 ttl = -1;
117
118         switch (ss.ss_family) {
119         case AF_INET:
120                 if (!IN_MULTICAST(htonl(((struct sockaddr_in *)&ss)->sin_addr.s_addr)))
121                         return 0;
122                 if (id != 0) {
123 #ifdef HAVE_IP_MREQN
124                         struct ip_mreqn mn;
125
126                         memset(&mn, 0, sizeof(mn));
127                         mn.imr_ifindex = id;
128                         if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_IF, &mn, sizeof(mn)) < 0)
129                                 goto err;
130 #else
131                         PARA_ERROR_LOG("No support for setting outgoing IPv4 mcast interface.");
132 #endif
133                 }
134                 /*
135                  * Enable receiving multicast messages generated on the local host
136                  * At least on Linux, this is enabled by default.
137                  */
138                 if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &on, sizeof(on)) < 0)
139                         break;
140
141                 /* Default: use local subnet (do not flood out into the WAN) */
142                 if (ttl == -1)
143                         ttl = 1;
144                 if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0)
145                         break;
146                 return 0;
147         case AF_INET6:
148                 if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)&ss)->sin6_addr))
149                         return 0;
150                 if (id != 0 &&
151                     setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &id, sizeof(id)) < 0)
152                         break;
153                 if (setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &on, sizeof(on)) < 0)
154                         break;
155                 if (setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)) < 0)
156                         break;
157                 return 0;
158         }
159 err:
160         return -ERRNO_TO_PARA_ERROR(errno);
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 : OPT_UINT32_VAL(UDP_DEFAULT_PORT);
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         struct udp_target *ut = sc->private_data;
240         int mps;
241
242         PARA_NOTICE_LOG("sending to udp %s\n", sc->name);
243         ut->sent_fec_eof = false;
244         mps = generic_max_transport_msg_size(sc->fd) - sizeof(struct udphdr);
245         PARA_INFO_LOG("current MPS = %d bytes\n", mps);
246         return mps;
247 }
248
249 /** Check and clear socket error if any. */
250 static int udp_check_socket_state(struct sender_client *sc)
251 {
252         struct udp_target *ut = sc->private_data;
253         int ret;
254         socklen_t errlen = sizeof(ret);
255
256         if (getsockopt(sc->fd, SOL_SOCKET, SO_ERROR, &ret, &errlen) < 0) {
257                 PARA_ERROR_LOG("SO_ERROR failed: %s\n", strerror(ret));
258                 return 0;
259         } else if (ret == 0) {
260                 return 0;
261         } else if (ret == ECONNREFUSED) {
262                 time_t dist = now->tv_sec - ut->last_unreachable;
263
264                 if (dist <= UDP_MAX_UNREACHABLE_TIME) {
265                         return 0;
266                 } else if (dist > 2 * UDP_MAX_UNREACHABLE_TIME) {
267                         ut->last_unreachable = now->tv_sec;
268                         return 0;
269                 } else {
270                         /*
271                          * unreachable_time < dist <= 2 * unreachable_time
272                          * No errors are allowed during this time window.
273                          */
274                         PARA_NOTICE_LOG("Evicting %s after %d seconds "
275                                         "of connection errors.\n",
276                                         sc->name, (int)dist);
277                 }
278         }
279         return -ERRNO_TO_PARA_ERROR(ret);
280 }
281
282 static void udp_send_fec(struct sender_client *sc, char *buf, size_t len)
283 {
284         int ret;
285
286         if (sender_status == SENDER_off)
287                 return;
288         if (len == 0)
289                 return;
290         ret = udp_check_socket_state(sc);
291         if (ret < 0)
292                 goto fail;
293         ret = xwrite(sc->fd, buf, len);
294         if (ret == -ERRNO_TO_PARA_ERROR(ECONNREFUSED)) {
295                 /*
296                  * Happens if meanwhile an ICMP Destination / Port Unreachable
297                  * has arrived. Ignore, persistent errors will be caught above.
298                  */
299                 ret = 0;
300         }
301         if (ret < 0)
302                 goto fail;
303         return;
304 fail:
305         udp_delete_target(sc, para_strerror(-ret));
306 }
307
308 static int udp_com_add(struct sender_command_data *scd)
309 {
310         int ret;
311         struct udp_target *ut;
312         struct sender_client *sc = udp_lookup_target(scd);
313
314         if (sc) {
315                 PARA_NOTICE_LOG("target %s already exists - not adding it\n",
316                                 sc->name);
317                 return -E_TARGET_EXISTS;
318         }
319         ut = para_calloc(sizeof(*ut));
320         sc = para_calloc(sizeof(*sc));
321         ut->fcp.slices_per_group      = scd->slices_per_group;
322         ut->fcp.data_slices_per_group = scd->data_slices_per_group;
323         ut->fcp.init_fec              = udp_init_fec;
324         ut->fcp.send_fec              = udp_send_fec;
325         ut->fcp.need_periodic_header  = true;
326
327         sc->private_data = ut;
328         sc->fd = -1;
329         ret = para_connect_simple(IPPROTO_UDP, scd->host, scd->port);
330         if (ret < 0)
331                 goto err;
332         sc->fd = ret;
333
334         ret = mcast_sender_setup(sc);
335         if (ret < 0)
336                 goto err;
337         ret = mark_fd_nonblocking(sc->fd);
338         if (ret < 0)
339                 goto err;
340         sc->name = para_strdup(remote_name(sc->fd));
341         PARA_INFO_LOG("adding to target list (%s)\n", sc->name);
342         ut->fc = vss_add_fec_client(sc, &ut->fcp);
343         para_list_add(&sc->node, &targets);
344         add_close_on_fork_list(sc->fd);
345         return 1;
346 err:
347         if (sc->fd >= 0)
348                 close(sc->fd);
349         PARA_NOTICE_LOG("failed to set up %s:%d (%s)- not adding it\n",
350                         scd->host, scd->port, para_strerror(-ret));
351         free(sc);
352         free(ut);
353         return ret;
354 }
355
356 static char *udp_status(void)
357 {
358         struct sender_client *sc;
359         char *ret, *tgts = NULL;
360
361         list_for_each_entry(sc, &targets, node) {
362                 struct udp_target *ut = sc->private_data;
363                 char *tmp = make_message("%s%s/%u:%u ",
364                         tgts ? : "", sc->name,
365                         ut->fcp.data_slices_per_group,
366                         ut->fcp.slices_per_group
367                 );
368                 free(tgts);
369                 tgts = tmp;
370         }
371         ret = make_message(
372                 "status: %s\n"
373                 "port: %s\n"
374                 "targets: %s\n",
375                 (sender_status == SENDER_on)? "on" : "off",
376                 stringify_port(OPT_UINT32_VAL(UDP_DEFAULT_PORT), "udp"),
377                 tgts? tgts : "(none)"
378         );
379         free(tgts);
380         return ret;
381 }
382
383 static void udp_init_target_list(void)
384 {
385         struct sender_command_data scd;
386         int i;
387
388         INIT_LIST_HEAD(&targets);
389         for (i = 0; i < OPT_GIVEN(UDP_TARGET); i++) {
390                 const char *arg = lls_string_val(i, OPT_RESULT(UDP_TARGET));
391                 if (udp_resolve_target(arg, &scd) < 0)
392                         PARA_CRIT_LOG("not adding requested target '%s'\n",
393                                         arg);
394                 else
395                         udp_com_add(&scd);
396         }
397 }
398
399 static char *udp_help(void)
400 {
401         return make_message(
402                 "usage: {on|off}\n"
403                 "usage: {add|delete} ip_address[:port][/[packet_size:]k:n]\n"
404                 "       - k is the number of data slices per FEC group\n"
405                 "       - n is the total number of slices in a FEC group\n"
406                 "       - packet_size reduces the slice size below path MTU\n\n"
407                 "examples: add 224.0.1.38:1500  (IPv4 multicast)\n"
408                 "          add 224.0.1.38:8080/14:16 (explicit FEC)\n"
409                 "          add 10.10.1.42       (using default port)\n"
410                 "          add [FF05::42]:1500  (IPv6 multicast)\n"
411                 "          add [::1]            (IPv6 localhost/default port)\n"
412                 "          delete myhost.net    (host with port wildcard)\n"
413                 "          delete 10.1.2.3:456  (IPv4 with explicit port)\n"
414                 "          delete [badc0de::1]  (IPv6 with port wildcard)\n"
415         );
416 }
417
418 /**
419  * The init function of para_server's udp sender.
420  *
421  * \param s Pointer to the udp sender struct.
422  *
423  * It initializes all function pointers of \a s and the list of udp targets.
424  */
425 void udp_send_init(struct sender *s)
426 {
427         INIT_LIST_HEAD(&targets);
428         s->status = udp_status;
429         s->help = udp_help;
430         s->send = NULL;
431         s->pre_select = NULL;
432         s->post_select = NULL;
433         s->shutdown_clients = udp_shutdown_targets;
434         s->resolve_target = udp_resolve_target;
435         s->client_cmds[SENDER_on] = udp_com_on;
436         s->client_cmds[SENDER_off] = udp_com_off;
437         s->client_cmds[SENDER_deny] = NULL;
438         s->client_cmds[SENDER_allow] = NULL;
439         s->client_cmds[SENDER_add] = udp_com_add;
440         s->client_cmds[SENDER_delete] = udp_com_delete;
441         sender_status = SENDER_off;
442         udp_init_target_list();
443         if (!OPT_GIVEN(UDP_NO_AUTOSTART))
444                 sender_status = SENDER_on;
445         PARA_DEBUG_LOG("udp sender init complete\n");
446 }