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