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