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