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