a7d696efd93c88e3ef3aabd257943b5db6380945
[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 /** Describes one entry in the list of targets for the udp sender. */
36 struct udp_target {
37         /** The hostname (DNS name or IPv4/v6 address string). */
38         char host[MAX_HOSTLEN];
39         /** The UDP port. */
40         int port;
41         /** Common sender client data */
42         struct sender_client *sc;
43         /** The opaque structure returned by vss_add_fec_client(). */
44         struct fec_client *fc;
45         /** The FEC parameters for this target. */
46         struct fec_client_parms fcp;
47 };
48
49 static struct list_head targets;
50 static int sender_status;
51
52 static void udp_close_target(struct sender_client *sc)
53 {
54         if (sc->fd < 0)
55                 return;
56         close(sc->fd);
57         del_close_on_fork_list(sc->fd);
58         cq_destroy(sc->cq);
59         sc->cq   = NULL;
60         sc->fd   = -1;
61 }
62
63 static void udp_delete_target(struct udp_target *ut, const char *msg)
64 {
65
66         PARA_NOTICE_LOG("deleting %s#%d (%s) from list\n", ut->host,
67                 ut->port, msg);
68         udp_close_target(ut->sc);
69         vss_del_fec_client(ut->fc);
70         list_del(&ut->sc->node);
71         free(ut->sc);
72         free(ut);
73 }
74
75 /**
76  * Perform AF-independent multicast sender setup.
77  *
78  * \param sc    The connected sender client.
79  * \param ttl   UDPv4 multicast TTL or UDPv6 multicast number of hops.
80  *              Use -1 to mean default, 0..255 otherwise.
81  * \param iface The outgoing multicast interface, or NULL for the default.
82  *
83  * \return Zero if okay, negative on error.
84  */
85 static int mcast_sender_setup(struct sender_client *sc, int ttl, char *iface)
86 {
87         struct sockaddr_storage ss;
88         socklen_t sslen = sizeof(ss);
89
90         const int on = 1;
91         int id = iface == NULL ? 0 : if_nametoindex(iface);
92
93         if (getpeername(sc->fd, (struct sockaddr *)&ss, &sslen) < 0)
94                 goto err;
95
96         if (iface != NULL && id == 0)
97                 PARA_WARNING_LOG("could not resolve interface %s, using default", iface);
98
99         /* RFC 3493, 5.2: -1 means 'use kernel default' */
100         if (ttl < 0 || ttl > 255)
101                 ttl = -1;
102
103         switch (ss.ss_family) {
104         case AF_INET:
105                 if (!IN_MULTICAST(htonl(((struct sockaddr_in *)&ss)->sin_addr.s_addr)))
106                         return 0;
107                 if (id != 0) {
108 #ifdef HAVE_IP_MREQN
109                         struct ip_mreqn mn;
110
111                         memset(&mn, 0, sizeof(mn));
112                         mn.imr_ifindex = id;
113                         if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_IF, &mn, sizeof(mn)) < 0)
114                                 goto err;
115 #else
116                         PARA_ERROR_LOG("No support for setting outgoing IPv4 mcast interface.");
117 #endif
118                 }
119                 /*
120                  * Enable receiving multicast messages generated on the local host
121                  * At least on Linux, this is enabled by default.
122                  */
123                 if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &on, sizeof(on)) < 0)
124                         break;
125
126                 /* Default: use local subnet (do not flood out into the WAN) */
127                 if (ttl == -1)
128                         ttl = 1;
129                 if (setsockopt(sc->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0)
130                         break;
131                 return 0;
132         case AF_INET6:
133                 if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)&ss)->sin6_addr))
134                         return 0;
135                 if (id != 0 &&
136                     setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &id, sizeof(id)) < 0)
137                         break;
138                 if (setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &on, sizeof(on)) < 0)
139                         break;
140                 if (setsockopt(sc->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)) < 0)
141                         break;
142                 return 0;
143         default:
144                 PARA_ERROR_LOG("address family %d not supported", ss.ss_family);
145                 return -E_ADDRESS_LOOKUP;
146         }
147 err:
148         return -ERRNO_TO_PARA_ERROR(errno);
149 }
150
151 /** The maximal size of the per-target chunk queue. */
152 #define UDP_CQ_BYTES 40000
153
154 static int udp_init_session(struct sender_client *sc)
155 {
156         struct udp_target *ut = sc->private_data;
157         int ret;
158         char *iface = NULL;
159
160         if (sc->fd >= 0) /* nothing to do */
161                 return 0;
162
163         ret = para_connect_simple(IPPROTO_UDP, ut->host, ut->port);
164         if (ret < 0)
165                 return ret;
166         sc->fd = ret;
167
168         if (conf.udp_mcast_iface_given)
169                 iface = conf.udp_mcast_iface_arg;
170
171         ret = mcast_sender_setup(sc, conf.udp_ttl_arg, iface);
172         if (ret < 0) {
173                 close(sc->fd);
174                 return ret;
175         }
176
177         ret = mark_fd_nonblocking(sc->fd);
178         if (ret < 0) {
179                 close(sc->fd);
180                 return ret;
181         }
182         add_close_on_fork_list(sc->fd);
183         sc->cq   = cq_new(UDP_CQ_BYTES);
184         PARA_NOTICE_LOG("sending to udp %s#%d\n", ut->host, ut->port);
185         return 1;
186 }
187
188 static void udp_shutdown_targets(void)
189 {
190         struct sender_client *sc, *tmp;
191         const char *buf = NULL;
192         size_t len = 0; /* STFU, gcc */
193
194         list_for_each_entry_safe(sc, tmp, &targets, node) {
195                 int ubuntu_glibc_headers_suck;
196                 if (sc->fd < 0)
197                         continue;
198                 if (!buf)
199                         len = vss_get_fec_eof_packet(&buf);
200                 /* ignore return value, we're closing the target anyway. */
201                 ubuntu_glibc_headers_suck = write(sc->fd, buf, len); /* STFU */
202                 udp_close_target(sc);
203         }
204 }
205
206 static int udp_com_on(__a_unused struct sender_command_data *scd)
207 {
208         sender_status = SENDER_ON;
209         return 1;
210 }
211
212 static int udp_com_off(__a_unused struct sender_command_data *scd)
213 {
214         udp_shutdown_targets();
215         sender_status = SENDER_OFF;
216         return 1;
217 }
218
219 static int udp_com_delete(struct sender_command_data *scd)
220 {
221         struct sender_client *sc, *tmp;
222
223         list_for_each_entry_safe(sc, tmp, &targets, node) {
224                 struct udp_target *ut = sc->private_data;
225
226                 /* Unspecified port means wildcard port match */
227                 if (scd->port > 0 && scd->port != ut->port)
228                         continue;
229                 if (strcmp(ut->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, ret = udp_init_session(sc);
240
241         if (ret < 0)
242                 return ret;
243
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 static int udp_send_fec(struct sender_client *sc, char *buf, size_t len)
250 {
251         struct udp_target *ut = sc->private_data;
252         int ret;
253
254         if (sender_status == SENDER_OFF)
255                 return 0;
256         ret = udp_init_session(sc);
257         if (ret < 0)
258                 goto fail;
259         ret = send_queued_chunks(sc->fd, sc->cq, 0);
260         if (ret == -ERRNO_TO_PARA_ERROR(ECONNREFUSED))
261                 ret = 0;
262         if (ret < 0)
263                 goto fail;
264         if (!len)
265                 return 0;
266         if (!ret) { /* still data left in the queue */
267                 ret = cq_force_enqueue(sc->cq, buf, len);
268                 assert(ret >= 0);
269         }
270         ret = write_nonblock(sc->fd, buf, len, 0);
271         if (ret == -ERRNO_TO_PARA_ERROR(ECONNREFUSED))
272                 ret = 0;
273         if (ret < 0)
274                 goto fail;
275         if (ret != len) {
276                 ret = cq_force_enqueue(sc->cq, buf + ret, len - ret);
277                 assert(ret >= 0);
278         }
279         return 1;
280 fail:
281         udp_delete_target(ut, para_strerror(-ret));
282         return ret;
283 }
284
285 static void udp_add_target(struct sender_command_data *scd)
286 {
287         struct udp_target *ut = para_calloc(sizeof(*ut));
288
289         strncpy(ut->host, scd->host, sizeof(ut->host));
290         ut->port = scd->port > 0 ? scd->port : conf.udp_default_port_arg;
291
292         ut->fcp.slices_per_group      = scd->slices_per_group;
293         ut->fcp.data_slices_per_group = scd->data_slices_per_group;
294         ut->fcp.max_slice_bytes       = scd->max_slice_bytes;
295         ut->fcp.init_fec              = udp_init_fec;
296         ut->fcp.send_fec              = udp_send_fec;
297
298         ut->sc = para_calloc(sizeof(*ut->sc));
299         ut->sc->fd = -1; /* not yet connected */
300         ut->sc->private_data = ut;
301         ut->fc = vss_add_fec_client(ut->sc, &ut->fcp);
302
303         PARA_INFO_LOG("adding to target list (%s#%d)\n", ut->host, ut->port);
304         para_list_add(&ut->sc->node, &targets);
305 }
306
307 static int udp_com_add(struct sender_command_data *scd)
308 {
309         udp_add_target(scd);
310         return 1;
311 }
312
313 static char *udp_info(void)
314 {
315         struct sender_client *sc;
316         char *ret, *tgts = NULL;
317
318         list_for_each_entry(sc, &targets, node) {
319                 struct udp_target *ut = sc->private_data;
320                 bool is_v6 = strchr(ut->host, ':') != NULL;
321                 char *tmp = make_message("%s%s%s%s:%d/%u:%u:%u ", tgts ? : "",
322                         is_v6 ? "[" : "", ut->host,
323                         is_v6 ? "]" : "", ut->port,
324                         ut->fcp.max_slice_bytes,
325                         ut->fcp.data_slices_per_group,
326                         ut->fcp.slices_per_group
327                 );
328                 free(tgts);
329                 tgts = tmp;
330         }
331         ret = make_message(
332                 "udp sender:\n"
333                 "\tstatus: %s\n"
334                 "\tport: %s\n"
335                 "\ttargets: %s\n",
336                 (sender_status == SENDER_ON)? "on" : "off",
337                 stringify_port(conf.udp_default_port_arg, "udp"),
338                 tgts? tgts : "(none)"
339         );
340         free(tgts);
341         return ret;
342 }
343
344 static void udp_init_target_list(void)
345 {
346         struct sender_command_data scd;
347         int i;
348
349         INIT_LIST_HEAD(&targets);
350         for (i = 0; i < conf.udp_target_given; i++) {
351                 if (parse_fec_url(conf.udp_target_arg[i], &scd) < 0) {
352                         PARA_CRIT_LOG("syntax error for udp target option "
353                                 "#%d, ignoring\n", i);
354                         continue;
355                 }
356                 udp_add_target(&scd);
357         }
358 }
359
360 static char *udp_help(void)
361 {
362         return make_message(
363                 "usage: {on|off}\n"
364                 "usage: {add|delete} host[:port][/packet_size:k:n]\n"
365                 "examples: add 224.0.1.38:1500  (IPv4 multicast)\n"
366                 "          add 224.0.1.38:1500/1400:14:16\n"
367                 "              (likewise, using 1400 byte packets, with 14\n"
368                 "               data slices per 16 slice FEC group)\n"
369                 "          add 10.10.1.42       (using default port)\n"
370                 "          add [FF05::42]:1500  (IPv6 multicast)\n"
371                 "          add [::1]            (IPv6 localhost/default port)\n"
372                 "          delete myhost.net    (host with port wildcard)\n"
373                 "          delete [badc0de::1]  (IPv6 with port wildcard)\n"
374         );
375 }
376
377 /**
378  * The init function of para_server's udp sender.
379  *
380  * \param s Pointer to the udp sender struct.
381  *
382  * It initializes all function pointers of \a s and the list of udp targets.
383  */
384 void udp_send_init(struct sender *s)
385 {
386         INIT_LIST_HEAD(&targets);
387         s->info = udp_info;
388         s->help = udp_help;
389         s->send = NULL;
390         s->pre_select = NULL;
391         s->post_select = NULL;
392         s->shutdown_clients = udp_shutdown_targets;
393         s->client_cmds[SENDER_ON] = udp_com_on;
394         s->client_cmds[SENDER_OFF] = udp_com_off;
395         s->client_cmds[SENDER_DENY] = NULL;
396         s->client_cmds[SENDER_ALLOW] = NULL;
397         s->client_cmds[SENDER_ADD] = udp_com_add;
398         s->client_cmds[SENDER_DELETE] = udp_com_delete;
399         sender_status = SENDER_OFF;
400         udp_init_target_list();
401         if (!conf.udp_no_autostart_given)
402                 sender_status = SENDER_ON;
403         PARA_DEBUG_LOG("udp sender init complete\n");
404 }