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