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