server: Exit cleanly on SIGINT/SIGTERM.
[paraslash.git] / send_common.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file send_common.c Functions used by more than one paraslash sender. */
4
5 #include <netinet/in.h>
6 #include <sys/socket.h>
7 #include <regex.h>
8 #include <osl.h>
9 #include <arpa/inet.h>
10 #include <sys/un.h>
11 #include <netdb.h>
12 #include <lopsub.h>
13
14 #include "para.h"
15 #include "error.h"
16 #include "string.h"
17 #include "fd.h"
18 #include "net.h"
19 #include "list.h"
20 #include "afh.h"
21 #include "afs.h"
22 #include "server.h"
23 #include "acl.h"
24 #include "send.h"
25 #include "close_on_fork.h"
26 #include "chunk_queue.h"
27 #include "sched.h"
28 #include "vss.h"
29
30 /** Clients will be kicked if there are more than that many bytes pending. */
31 #define MAX_CQ_BYTES 40000
32
33 /**
34  * Open a passive socket of given layer4 type.
35  *
36  * Set the resulting file descriptor to nonblocking mode and add it to the list
37  * of fds that are being closed in the child process when the server calls
38  * fork().
39  *
40  * \param l4type The transport-layer protocol.
41  * \param port The port number.
42  *
43  * \return The listening fd on success, negative on errors.
44  */
45 static int open_sender(unsigned l4type, int port)
46 {
47         int fd, ret = para_listen_simple(l4type, port);
48
49         if (ret < 0)
50                 return ret;
51         fd = ret;
52         ret = mark_fd_nonblocking(fd);
53         if (ret < 0) {
54                 close(fd);
55                 return ret;
56         }
57         add_close_on_fork_list(fd);
58         return fd;
59 }
60
61 /**
62  * Shut down a client connected to a paraslash sender.
63  *
64  * \param sc The client to shut down.
65  * \param ss The sender whose clients are to be shut down.
66  *
67  * Close the file descriptor given by \a sc, remove it from the close-on-fork
68  * list, destroy the chunk queue of this client, delete the client from the
69  * list of connected clients and free the sender_client struct.
70  *
71  * \sa \ref shutdown_clients().
72  */
73 void shutdown_client(struct sender_client *sc, struct sender_status *ss)
74 {
75         PARA_INFO_LOG("shutting down %s on fd %d\n", sc->name, sc->fd);
76         free(sc->name);
77         if (!process_is_command_handler()) {
78                 close(sc->fd);
79                 del_close_on_fork_list(sc->fd);
80         }
81         cq_destroy(sc->cq);
82         list_del(&sc->node);
83         free(sc->private_data);
84         free(sc);
85         ss->num_clients--;
86 }
87
88 /**
89  * Shut down all clients connected to a paraslash sender.
90  *
91  * \param ss The sender whose clients are to be shut down.
92  *
93  * This just loops over all connected clients and calls shutdown_client()
94  * for each client.
95  */
96 void shutdown_clients(struct sender_status *ss)
97 {
98         struct sender_client *sc, *tmp;
99         list_for_each_entry_safe(sc, tmp, &ss->client_list, node)
100                 shutdown_client(sc, ss);
101 }
102
103 /**
104  * Try to empty the chunk queue for this fd.
105  *
106  * \param fd The file descriptor.
107  * \param cq The list of queued chunks.
108  *
109  * \return Negative on errors, zero if not everything was sent, one otherwise.
110  */
111 int send_queued_chunks(int fd, struct chunk_queue *cq)
112 {
113         struct queued_chunk *qc;
114         while ((qc = cq_peek(cq))) {
115                 const char *buf;
116                 size_t len;
117                 int ret;
118
119                 cq_get(qc, &buf, &len);
120                 ret = xwrite(fd, buf, len);
121                 if (ret < 0)
122                         return ret;
123                 cq_update(cq, ret);
124                 if (ret != len)
125                         return 0;
126                 cq_dequeue(cq);
127         }
128         return 1;
129 }
130
131 /**
132  * Initialize a struct sender status.
133  *
134  * \param ss The struct to initialize.
135  * \param acl_opt_result Contains array of --{http|dccp}-access arguments.
136  * \param port The tcp or dccp port to listen on.
137  * \param max_clients The maximal number of simultaneous connections.
138  * \param default_deny Whether a blacklist should be used for access control.
139  */
140 void init_sender_status(struct sender_status *ss,
141                 const struct lls_opt_result *acl_opt_result, int port,
142                 int max_clients, int default_deny)
143 {
144         int i;
145
146         ss->listen_fd = -1;
147         INIT_LIST_HEAD(&ss->client_list);
148         ss->port = port;
149
150         /* Initialize an access control list */
151         INIT_LIST_HEAD(&ss->acl);
152         for (i = 0; i < lls_opt_given(acl_opt_result); i++) {
153                 const char *arg = lls_string_val(i, acl_opt_result);
154                 char addr[16];
155                 int mask;
156                 if (!parse_cidr(arg, addr, sizeof(addr), &mask))
157                         PARA_WARNING_LOG("ACL syntax error: %s, ignoring\n",
158                                 arg);
159                 else
160                         acl_add_entry(&ss->acl, addr, mask);
161         }
162         ss->num_clients = 0;
163         ss->max_clients = max_clients;
164         ss->default_deny = default_deny;
165 }
166
167 /**
168  * Return a string containing the current status of a sender.
169  *
170  * \param ss The sender.
171  * \param name Used for printing the header line.
172  *
173  * \return The string printed in the "si" command.
174  */
175 char *generic_sender_status(struct sender_status *ss, const char *name)
176 {
177         char *clnts = NULL, *ret;
178         struct sender_client *sc, *tmp_sc;
179
180         char *acl_contents = acl_get_contents(&ss->acl);
181         list_for_each_entry_safe(sc, tmp_sc, &ss->client_list, node) {
182                 char *tmp = make_message("%s%s ", clnts? clnts : "", sc->name);
183                 free(clnts);
184                 clnts = tmp;
185         }
186         ret = make_message(
187                 "status: %s\n"
188                 "port: %s\n"
189                 "number of connected clients: %d\n"
190                 "maximal number of clients: %d%s\n"
191                 "connected clients: %s\n"
192                 "access %s list: %s\n",
193                 (ss->listen_fd >= 0)? "on" : "off",
194                 stringify_port(ss->port, strcmp(name, "http") ? "dccp" : "tcp"),
195                 ss->num_clients,
196                 ss->max_clients,
197                 ss->max_clients > 0? "" : " (unlimited)",
198                 clnts? clnts : "(none)",
199                 ss->default_deny? "allow" : "deny",
200                 acl_contents? acl_contents : "(empty)"
201         );
202         free(acl_contents);
203         free(clnts);
204         return ret;
205 }
206
207 /**
208  * Allow connections from the given range of IP addresses.
209  *
210  * \param scd Contains the IP and the netmask.
211  * \param ss The sender.
212  *
213  * \sa \ref generic_com_deny().
214  */
215 void generic_com_allow(struct sender_command_data *scd,
216                 struct sender_status *ss)
217 {
218         acl_allow(scd->host, scd->netmask, &ss->acl, ss->default_deny);
219 }
220
221 /**
222  * Deny connections from the given range of IP addresses.
223  *
224  * \param scd see \ref generic_com_allow().
225  * \param ss see \ref generic_com_allow().
226  *
227  * \sa \ref generic_com_allow().
228  */
229 void generic_com_deny(struct sender_command_data *scd,
230                 struct sender_status *ss)
231 {
232         acl_deny(scd->host, scd->netmask, &ss->acl, ss->default_deny);
233 }
234
235 /**
236  * Activate a paraslash sender.
237  *
238  * \param ss The sender to activate.
239  * \param protocol The symbolic name of the transport-layer protocol.
240  *
241  * \return Standard.
242  */
243 int generic_com_on(struct sender_status *ss, unsigned protocol)
244 {
245         int ret;
246
247         if (ss->listen_fd >= 0)
248                 return 1;
249         ret = open_sender(protocol, ss->port);
250         if (ret < 0)
251                 return ret;
252         ss->listen_fd = ret;
253         return 1;
254 }
255
256 /**
257  * Deactivate a paraslash sender.
258  *
259  * Shutdown all connected clients and stop listening on the TCP/DCCP socket.
260  *
261  * \param ss The sender to deactivate.
262  *
263  * \sa \ref del_close_on_fork_list(), \ref shutdown_clients().
264  */
265 void generic_com_off(struct sender_status *ss)
266 {
267         if (ss->listen_fd < 0)
268                 return;
269         PARA_NOTICE_LOG("closing port %d\n", ss->port);
270         close(ss->listen_fd);
271         del_close_on_fork_list(ss->listen_fd);
272         shutdown_clients(ss);
273         ss->listen_fd = -1;
274 }
275
276 /**
277  * Accept a connection on the socket this server is listening on.
278  *
279  * \param ss The sender whose listening fd is ready for reading.
280  * \param rfds Passed to para_accept(),
281  *
282  * This must be called only if the socket fd of \a ss is ready for reading.  It
283  * calls para_accept() to accept the connection and performs the following
284  * actions on the resulting file descriptor \a fd:
285  *
286  *      - Checks whether the maximal number of connections are exceeded.
287  *      - Sets \a fd to nonblocking mode.
288  *      - Checks the acl of the sender to find out whether connections
289  *        are allowed from the IP of the connecting peer.
290  *      - Increases the number of connections for this sender.
291  *      - Creates and initializes a new chunk queue for queuing network
292  *        packets that can not be sent immediately.
293  *      - Allocates a new struct sender_client and fills in its \a fd, \a cq
294  *        and \a name members.
295  *      - Adds \a fd to the list of connected clients for this sender.
296  *      - Adds \a fd to the list of file descriptors that should be closed
297  *        in the child process when the server calls fork().
298  *
299  * \return A pointer to the allocated sender_client structure on success, \p
300  * NULL on errors.
301  *
302  * \sa \ref para_accept(), \ref mark_fd_nonblocking(), \ref acl_check_access(),
303  * \ref cq_new(), \ref add_close_on_fork_list().
304  */
305 struct sender_client *accept_sender_client(struct sender_status *ss, fd_set *rfds)
306 {
307         struct sender_client *sc;
308         int fd, ret;
309
310         if (ss->listen_fd < 0)
311                 return NULL;
312         ret = para_accept(ss->listen_fd, rfds, NULL, 0, &fd);
313         if (ret < 0)
314                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
315         if (ret <= 0)
316                 return NULL;
317         ret = -E_MAX_CLIENTS;
318         if (ss->max_clients > 0 && ss->num_clients >= ss->max_clients)
319                 goto err_out;
320         ret = mark_fd_nonblocking(fd);
321         if (ret < 0)
322                 goto err_out;
323         ret = acl_check_access(fd, &ss->acl, ss->default_deny);
324         if (ret < 0)
325                 goto err_out;
326         ss->num_clients++;
327         sc = para_calloc(sizeof(*sc));
328         sc->fd = fd;
329         sc->name = para_strdup(remote_name(fd));
330         sc->cq = cq_new(MAX_CQ_BYTES);
331         para_list_add(&sc->node, &ss->client_list);
332         add_close_on_fork_list(fd);
333         PARA_INFO_LOG("accepted client #%d: %s (fd %d)\n", ss->num_clients,
334                 sc->name, fd);
335         return sc;
336 err_out:
337         PARA_WARNING_LOG("%s\n", para_strerror(-ret));
338         close(fd);
339         return NULL;
340 }
341
342 /**
343  * Get the generic help text.
344  *
345  * \return A dynamically allocated string containing the help text for
346  * a paraslash sender.
347  */
348 char *generic_sender_help(void)
349 {
350         return make_message(
351                 "usage: {on|off}\n"
352                 "usage: {allow|deny} IP[/netmask]\n"
353                 "       where mask defaults to 32\n"
354                 "example: allow 192.168.0.1/24\n"
355         );
356 }
357
358 static int parse_fec_parms(const char *arg, struct sender_command_data *scd)
359 {
360         int32_t val;
361         char *a = para_strdup(arg),
362              *b = strchr(a, ':'),
363              *c = strrchr(a, ':');
364         int ret = -E_COMMAND_SYNTAX;
365
366         if (!b || !c)
367                 goto out;
368         *b = *c = '\0';
369
370         ret = para_atoi32(a, &val);
371         if (ret < 0)
372                 goto out;
373
374         /* optional max_slice_bytes (0 means "use MTU") */
375         if (b == c) {
376                 scd->max_slice_bytes = 0;
377         } else {
378                 if (val < 0 || val > 65535)
379                         goto fec_einval;
380                 scd->max_slice_bytes = val;
381
382                 ret = para_atoi32(b + 1, &val);
383                 if (ret < 0)
384                         goto out;
385         }
386
387         /* k = data_slices_per_group */
388         if (val < 0 || val > 255)
389                 goto fec_einval;
390         scd->data_slices_per_group = val;
391
392         /* n = slices_per_group */
393         ret = para_atoi32(c + 1, &val);
394         if (ret < 0)
395                 goto out;
396         if (val < 0 || val < scd->data_slices_per_group)
397                 goto fec_einval;
398         scd->slices_per_group = val;
399         ret = 0;
400 out:
401         free(a);
402         return ret;
403 fec_einval:
404         ret = -ERRNO_TO_PARA_ERROR(EINVAL);
405         goto out;
406 }
407
408 /**
409  * Parse a FEC URL string.
410  *
411  * \param arg the URL string to parse.
412  * \param scd The structure containing host, port and the FEC parameters.
413  *
414  * \return Standard.
415  *
416  * A FEC URL consists of an ordinary URL string according to RFC 3986,
417  * optionally followed by a slash and the three FEC parameters slice_size,
418  * data_slices_per_group and slices_per_group. The three FEC parameters are
419  * separated by colons.
420  *
421  * \sa \ref parse_url().
422  */
423 int parse_fec_url(const char *arg, struct sender_command_data *scd)
424 {
425         char *a = para_strdup(arg), *p = strchr(a, '/');
426         int ret = 0;
427
428         /* default fec parameters */
429         scd->max_slice_bytes       = 0;
430         scd->data_slices_per_group = 14;
431         scd->slices_per_group      = 16;
432
433         if (p) {
434                 *p = '\0';
435                 ret = parse_fec_parms(p + 1, scd);
436                 if (ret < 0)
437                         goto out;
438         }
439         if (!parse_url(a, scd->host, sizeof(scd->host), &scd->port))
440                 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
441 out:
442         free(a);
443         return ret;
444 }