gcrypt: Use GCRYMPI_FMT_USG for gcry_sexp_nth_mpi().
[paraslash.git] / send_common.c
1 /*
2  * Copyright (C) 2005-2011 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 <osl.h>
11
12 #include "para.h"
13 #include "error.h"
14 #include "string.h"
15 #include "fd.h"
16 #include "net.h"
17 #include "list.h"
18 #include "afh.h"
19 #include "afs.h"
20 #include "server.h"
21 #include "acl.h"
22 #include "send.h"
23 #include "close_on_fork.h"
24 #include "chunk_queue.h"
25 #include "vss.h"
26
27 /** Clients will be kicked if there are more than that many bytes pending. */
28 #define MAX_CQ_BYTES 40000
29
30 /**
31  * Open a passive socket of given layer4 type.
32  *
33  * Set the resulting file descriptor to nonblocking mode and add it to the list
34  * of fds that are being closed in the child process when the server calls
35  * fork().
36  *
37  * \param l4type The transport-layer protocol.
38  * \param port The port number.
39  *
40  * \return The listening fd on success, negative on errors.
41  */
42 static int open_sender(unsigned l4type, int port)
43 {
44         int fd, ret = para_listen_simple(l4type, port);
45
46         if (ret < 0)
47                 return ret;
48         fd = ret;
49         ret = mark_fd_nonblocking(fd);
50         if (ret < 0) {
51                 close(fd);
52                 return ret;
53         }
54         add_close_on_fork_list(fd);
55         return fd;
56 }
57
58 /**
59  * Shut down a client connected to a paraslash sender.
60  *
61  * \param sc The client to shut down.
62  * \param ss The sender whose clients are to be shut down.
63  *
64  * Close the file descriptor given by \a sc, remove it from the close-on-fork
65  * list, destroy the chunk queue of this client, delete the client from the
66  * list of connected clients and free the sender_client struct.
67  *
68  * \sa shutdown_clients().
69  */
70 void shutdown_client(struct sender_client *sc, struct sender_status *ss)
71 {
72         PARA_INFO_LOG("shutting down %s on fd %d\n", sc->name, sc->fd);
73         free(sc->name);
74         close(sc->fd);
75         del_close_on_fork_list(sc->fd);
76         cq_destroy(sc->cq);
77         list_del(&sc->node);
78         free(sc->private_data);
79         free(sc);
80         ss->num_clients--;
81 }
82
83 /**
84  * Shut down all clients connected to a paraslash sender.
85  *
86  * \param ss The sender whose clients are to be shut down.
87  *
88  * This just loops over all connected clients and calls shutdown_client()
89  * for each client.
90  */
91 void shutdown_clients(struct sender_status *ss)
92 {
93         struct sender_client *sc, *tmp;
94         list_for_each_entry_safe(sc, tmp, &ss->client_list, node)
95                 shutdown_client(sc, ss);
96 }
97
98 /**
99  * Try to empty the chunk queue for this fd.
100  *
101  * \param fd The file descriptor.
102  * \param cq The list of queued chunks.
103  *
104  * \return Negative on errors, zero if not everything was sent, one otherwise.
105  */
106 int send_queued_chunks(int fd, struct chunk_queue *cq)
107 {
108         struct queued_chunk *qc;
109         while ((qc = cq_peek(cq))) {
110                 const char *buf;
111                 size_t len;
112                 int ret;
113
114                 cq_get(qc, &buf, &len);
115                 ret = write_nonblock(fd, buf, len);
116                 if (ret < 0)
117                         return ret;
118                 cq_update(cq, ret);
119                 if (ret != len)
120                         return 0;
121                 cq_dequeue(cq);
122         }
123         return 1;
124 }
125
126 /**
127  * Initialize a struct sender status.
128  *
129  * \param ss The struct to initialize.
130  * \param access_arg The array of access arguments given at the command line.
131  * \param num_access_args The number of elements in \a access_arg.
132  * \param port The tcp or dccp port to listen on.
133  * \param max_clients The maximal number of simultaneous connections.
134  * \param default_deny Whether a blacklist should be used for access control.
135  */
136 void init_sender_status(struct sender_status *ss, char **access_arg,
137         int num_access_args, int port, int max_clients, int default_deny)
138 {
139         ss->listen_fd = -1;
140         INIT_LIST_HEAD(&ss->client_list);
141         ss->port = port;
142         acl_init(&ss->acl, access_arg, num_access_args);
143         ss->num_clients = 0;
144         ss->max_clients = max_clients;
145         ss->default_deny = default_deny;
146 }
147
148 /**
149  * Return a string containing the current status of a sender.
150  *
151  * \param ss The sender.
152  * \param name Used for printing the header line.
153  *
154  * \return The string printed in the "si" command.
155  */
156 char *get_sender_info(struct sender_status *ss, const char *name)
157 {
158         char *clnts = NULL, *ret;
159         struct sender_client *sc, *tmp_sc;
160
161         char *acl_contents = acl_get_contents(&ss->acl);
162         list_for_each_entry_safe(sc, tmp_sc, &ss->client_list, node) {
163                 char *tmp = make_message("%s%s ", clnts? clnts : "", sc->name);
164                 free(clnts);
165                 clnts = tmp;
166         }
167         ret = make_message(
168                 "%s sender:\n"
169                 "\tstatus: %s\n"
170                 "\tport: %s\n"
171                 "\tnumber of connected clients: %d\n"
172                 "\tmaximal number of clients: %d%s\n"
173                 "\tconnected clients: %s\n"
174                 "\taccess %s list: %s\n",
175                 name,
176                 (ss->listen_fd >= 0)? "on" : "off",
177                 stringify_port(ss->port, strcmp(name, "http") ? "dccp" : "tcp"),
178                 ss->num_clients,
179                 ss->max_clients,
180                 ss->max_clients > 0? "" : " (unlimited)",
181                 clnts? clnts : "(none)",
182                 ss->default_deny? "allow" : "deny",
183                 acl_contents? acl_contents : "(empty)"
184         );
185         free(acl_contents);
186         free(clnts);
187         return ret;
188 }
189
190 /**
191  * Allow connections from the given range of IP addresses.
192  *
193  * \param scd Contains the IP and the netmask.
194  * \param ss The sender.
195  *
196  * \sa generic_com_deny().
197  */
198 void generic_com_allow(struct sender_command_data *scd,
199                 struct sender_status *ss)
200 {
201         acl_allow(scd->host, scd->netmask, &ss->acl, ss->default_deny);
202 }
203
204 /**
205  * Deny connections from the given range of IP addresses.
206  *
207  * \param scd see \ref generic_com_allow().
208  * \param ss see \ref generic_com_allow().
209  *
210  * \sa generic_com_allow().
211  */
212 void generic_com_deny(struct sender_command_data *scd,
213                 struct sender_status *ss)
214 {
215         acl_deny(scd->host, scd->netmask, &ss->acl, ss->default_deny);
216 }
217
218 /**
219  * Activate a paraslash sender.
220  *
221  * \param ss The sender to activate.
222  * \param protocol The symbolic name of the transport-layer protocol.
223  *
224  * \return Standard.
225  */
226 int generic_com_on(struct sender_status *ss, unsigned protocol)
227 {
228         int ret;
229
230         if (ss->listen_fd >= 0)
231                 return 1;
232         ret = open_sender(protocol, ss->port);
233         if (ret < 0)
234                 return ret;
235         ss->listen_fd = ret;
236         return 1;
237 }
238
239 /**
240  * Deactivate a paraslash sender.
241  *
242  * Shutdown all connected clients and stop listening on the TCP/DCCP socket.
243  *
244  * \param ss The sender to deactivate.
245  *
246  * \sa \ref del_close_on_fork_list(), shutdown_clients().
247  */
248 void generic_com_off(struct sender_status *ss)
249 {
250         if (ss->listen_fd < 0)
251                 return;
252         PARA_NOTICE_LOG("closing port %d\n", ss->port);
253         close(ss->listen_fd);
254         del_close_on_fork_list(ss->listen_fd);
255         shutdown_clients(ss);
256         ss->listen_fd = -1;
257 }
258
259 /**
260  * Accept a connection on the socket this server is listening on.
261  *
262  * \param ss The sender whose listening fd is ready for reading.
263  * \param rfds Passed to para_accept(),
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 = para_strdup(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),
345              *b = strchr(a, ':'),
346              *c = strrchr(a, ':');
347         int ret = -E_COMMAND_SYNTAX;
348
349         if (!b || !c)
350                 goto out;
351         *b = *c = '\0';
352
353         ret = para_atoi32(a, &val);
354         if (ret < 0)
355                 goto out;
356
357         /* optional max_slice_bytes (0 means "use MTU") */
358         if (b == c) {
359                 scd->max_slice_bytes = 0;
360         } else {
361                 if (val < 0 || val > 65535)
362                         goto fec_einval;
363                 scd->max_slice_bytes = val;
364
365                 ret = para_atoi32(b + 1, &val);
366                 if (ret < 0)
367                         goto out;
368         }
369
370         /* k = data_slices_per_group */
371         if (val < 0 || val > 255)
372                 goto fec_einval;
373         scd->data_slices_per_group = val;
374
375         /* n = slices_per_group */
376         ret = para_atoi32(c + 1, &val);
377         if (ret < 0)
378                 goto out;
379         if (val < 0 || val < scd->data_slices_per_group)
380                 goto fec_einval;
381         scd->slices_per_group = val;
382         ret = 0;
383 out:
384         free(a);
385         return ret;
386 fec_einval:
387         ret = -ERRNO_TO_PARA_ERROR(EINVAL);
388         goto out;
389 }
390
391 /**
392  * Parse a FEC URL string.
393  *
394  * \param arg the URL string to parse.
395  * \param scd The structure containing host, port and the FEC parameters.
396  *
397  * \return Standard.
398  *
399  * A FEC URL consists of an ordinary URL string according to RFC 3986,
400  * optionally followed by a slash and the three FEC parameters slice_size,
401  * data_slices_per_group and slices_per_group. The three FEC parameters are
402  * separated by colons.
403  *
404  * \sa \ref parse_url().
405  */
406 int parse_fec_url(const char *arg, struct sender_command_data *scd)
407 {
408         char *a = para_strdup(arg), *p = strchr(a, '/');
409         int ret = 0;
410
411         /* default fec parameters */
412         scd->max_slice_bytes       = 0;
413         scd->data_slices_per_group = 14;
414         scd->slices_per_group      = 16;
415
416         if (p) {
417                 *p = '\0';
418                 ret = parse_fec_parms(p + 1, scd);
419                 if (ret < 0)
420                         goto out;
421         }
422         if (!parse_url(a, scd->host, sizeof(scd->host), &scd->port))
423                 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
424 out:
425         free(a);
426         return ret;
427 }