vss_init(): Use FOR_EACH_AUDIO_FORMAT() instead of open coding the loop.
[paraslash.git] / http_send.c
1 /*
2  * Copyright (C) 2005-2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file http_send.c paraslash's http sender */
8
9
10 #include "para.h"
11 #include "server.cmdline.h"
12 #include "afh.h"
13 #include "server.h"
14 #include "http.h"
15 #include "vss.h"
16 #include "send.h"
17 #include "list.h"
18 #include "close_on_fork.h"
19 #include "error.h"
20 #include "net.h"
21 #include "string.h"
22 #include "fd.h"
23 #include "chunk_queue.h"
24
25 /** \cond convert sock_addr_in to ascii */
26 #define CLIENT_ADDR(hc) inet_ntoa((hc)->addr.sin_addr)
27 /* get the port number of a struct http_client */
28 #define CLIENT_PORT(hc) (hc)->addr.sin_port
29 #define HTTP_ERR_MSG "HTTP/1.0 400 Bad Request\n"
30 /** \endcond */
31
32 /** The possible states of a client from the server's POV. */
33 enum http_status {
34         /** We accepted the connection on the tcp socket. */
35         HTTP_CONNECTED,
36         /** Successfully received the get request. */
37         HTTP_GOT_GET_REQUEST,
38         /** We sent the OK message back to the client. */
39         HTTP_SENT_OK_MSG,
40         /** Connection established, we might need to send the audio file header. */
41         HTTP_READY_TO_STREAM,
42         /** Connection is ready for sending audio data. */
43         HTTP_STREAMING,
44         /** We didn't receive a valid get request. */
45         HTTP_INVALID_GET_REQUEST
46 };
47
48 /** Clients will be kicked if there are more than that many bytes pending. */
49 #define MAX_BACKLOG 400000
50 /** The list of connected clients. */
51 static struct list_head clients;
52 /** The whitelist/blacklist. */
53 static struct list_head access_perm_list;
54
55 /** Describes one client that connected the tcp port of the http sender. */
56 struct http_client {
57         /** The file descriptor of the client. */
58         int fd;
59         /** Address information about the client. */
60         struct sockaddr_in addr;
61         /** The client's current status. */
62         enum http_status status;
63         /** Non-zero if we included \a fd in the read set.*/
64         int check_r;
65         /** Non-zero if we included \a fd in the write set. */
66         int check_w;
67         /** The position of this client in the client list. */
68         struct list_head node;
69         /** The list of pending chunks for this client. */
70         struct chunk_queue *cq;
71 };
72
73 /**
74  * Describes one entry in the blacklist/whitelist of the http sender.
75  */
76 struct access_info {
77         /** The address to be black/whitelisted. */
78         struct in_addr addr;
79         /** The netmask for this entry. */
80         unsigned netmask;
81         /** The position of this entry in the access_perm_list. */
82         struct list_head node;
83 };
84
85 static int server_fd = -1, numclients;
86 static struct sender *self;
87
88
89 static void http_shutdown_client(struct http_client *hc, const char *msg)
90 {
91         PARA_INFO_LOG("shutting down %s on fd %d (%s)\n", CLIENT_ADDR(hc),
92                 hc->fd, msg);
93         numclients--;
94         close(hc->fd);
95         del_close_on_fork_list(hc->fd);
96         cq_destroy(hc->cq);
97         list_del(&hc->node);
98         free(hc);
99 }
100
101 static void http_shutdown_clients(void)
102 {
103         struct http_client *hc, *tmp;
104         list_for_each_entry_safe(hc, tmp, &clients, node)
105                 http_shutdown_client(hc, "vss request");
106 }
107
108 static int http_send_msg(struct http_client *hc, const char *msg)
109 {
110         int ret = send_buffer(hc->fd, msg);
111
112         if (ret < 0)
113                 http_shutdown_client(hc, "send msg failed");
114         return ret;
115 }
116
117 static void http_send_ok_msg(struct http_client *hc)
118 {
119         PARA_INFO_LOG("sending http ok message to fd %d\n", hc->fd);
120         http_send_msg(hc, HTTP_OK_MSG);
121 }
122
123 static int http_send_err_msg(struct http_client *hc)
124 {
125         PARA_NOTICE_LOG("sending bad request message to fd %d\n", hc->fd);
126         return http_send_msg(hc, HTTP_ERR_MSG);
127 }
128
129 static int send_queued_chunks(struct http_client *hc)
130 {
131         struct queued_chunk *qc;
132         while ((qc = cq_peek(hc->cq))) {
133                 char *buf;
134                 size_t len;
135                 int ret = write_ok(hc->fd);
136                 if (ret <= 0)
137                         return ret? -E_WRITE_OK : 0;
138                 cq_get(qc, &buf, &len);
139                 ret = write(hc->fd, buf, len);
140                 if (ret < 0)
141                         return -E_SEND_QUEUED_CHUNK;
142                 cq_update(hc->cq, ret);
143                 if (ret != len)
144                         return 1;
145                 cq_dequeue(hc->cq);
146         }
147         return 1;
148 }
149
150 static int queue_chunk_or_shutdown(struct http_client *hc, long unsigned chunk_num,
151         size_t sent)
152 {
153         int ret = cq_enqueue(hc->cq, chunk_num, sent);
154         if (ret < 0)
155                 http_shutdown_client(hc, "queue error");
156         return ret;
157 }
158
159 static void http_send( long unsigned current_chunk,
160         __a_unused long unsigned chunks_sent, const char *buf, size_t len)
161 {
162         struct http_client *hc, *tmp;
163         int ret;
164
165         list_for_each_entry_safe(hc, tmp, &clients, node) {
166                 if (hc->status != HTTP_STREAMING &&
167                                 hc->status != HTTP_READY_TO_STREAM)
168                         continue;
169                 if (hc->status == HTTP_READY_TO_STREAM) {
170                         size_t hlen;
171                         char *hbuf = vss_get_header(&hlen);
172                         if (hbuf && hlen > 0 && current_chunk) {
173                                 /* need to send header */
174                                 PARA_INFO_LOG("queueing header: %zu\n", hlen);
175                                 if (queue_chunk_or_shutdown(hc, -1U, 0) < 0)
176                                         continue;
177                         } else
178                                 PARA_INFO_LOG("no need to queue header\n");
179                         hc->status = HTTP_STREAMING;
180                 }
181                 ret = send_queued_chunks(hc);
182                 if (ret < 0) {
183                         http_shutdown_client(hc, "queue send error");
184                         continue;
185                 }
186                 if (!len)
187                         continue;
188                 if (!ret || write_ok(hc->fd) <= 0) {
189                         queue_chunk_or_shutdown(hc, current_chunk, 0);
190                         continue;
191                 }
192 //              PARA_DEBUG_LOG("sending %d -> %s\n", len, CLIENT_ADDR(hc));
193                 ret = write(hc->fd, buf, len);
194 //              PARA_DEBUG_LOG("ret: %d\n", ret);
195                 if (ret < 0) {
196                         http_shutdown_client(hc, "send error");
197                         continue;
198                 }
199                 if (ret != len)
200                         queue_chunk_or_shutdown(hc, current_chunk, ret);
201         }
202 }
203
204 static int host_in_access_perm_list(struct http_client *hc)
205 {
206         struct access_info *ai, *tmp;
207         list_for_each_entry_safe(ai, tmp, &access_perm_list, node) {
208                 unsigned mask = ((~0U) >> ai->netmask);
209                 if ((hc->addr.sin_addr.s_addr & mask) == (ai->addr.s_addr & mask))
210                         return 1;
211         }
212         return 0;
213 }
214
215 static void http_post_select(fd_set *rfds, fd_set *wfds)
216 {
217         int i = -1, match;
218         struct http_client *hc, *tmp;
219         const char *err_msg;
220
221         list_for_each_entry_safe(hc, tmp, &clients, node) {
222                 i++;
223 //              PARA_DEBUG_LOG("handling client %d: %s\n", i, CLIENT_ADDR(hc));
224                 switch (hc->status) {
225                 case HTTP_STREAMING: /* nothing to do */
226                 case HTTP_READY_TO_STREAM:
227                         break;
228                 case HTTP_CONNECTED: /* need to recv get request */
229                         if (hc->check_r && FD_ISSET(hc->fd, rfds)) {
230                                 if (recv_pattern(hc->fd, HTTP_GET_MSG, MAXLINE)
231                                                 < 0) {
232                                         hc->status = HTTP_INVALID_GET_REQUEST;
233                                 } else {
234                                         hc->status = HTTP_GOT_GET_REQUEST;
235                                         PARA_INFO_LOG("%s",
236                                                 "received get request\n");
237                                 }
238                         }
239                         break;
240                 case HTTP_GOT_GET_REQUEST: /* need to send ok msg */
241                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
242                                 hc->status = HTTP_SENT_OK_MSG;
243                                 http_send_ok_msg(hc);
244                         }
245                         break;
246                 case HTTP_INVALID_GET_REQUEST: /* need to send err msg */
247                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
248                                 if (http_send_err_msg(hc) >= 0)
249                                         http_shutdown_client(hc,
250                                                 "invalid get request");
251                         }
252                         break;
253                 case HTTP_SENT_OK_MSG: /* need to send header? */
254                         if (hc->check_w && FD_ISSET(hc->fd, wfds))
255                                 hc->status = HTTP_READY_TO_STREAM;
256                         break;
257                 }
258         }
259         if (!FD_ISSET(server_fd, rfds))
260                 return;
261         hc = para_calloc(sizeof(struct http_client));
262         err_msg = "accept error";
263         hc->fd = para_accept(server_fd, &hc->addr, sizeof(struct sockaddr_in));
264         if (hc->fd <= 0)
265                 goto err_out;
266         PARA_NOTICE_LOG("connection from %s (fd %d)\n", CLIENT_ADDR(hc), hc->fd);
267         if (conf.http_max_clients_arg > 0 && numclients >=
268                         conf.http_max_clients_arg) {
269                 err_msg = "server full";
270                 goto err_out;
271         }
272         match = host_in_access_perm_list(hc);
273         PARA_DEBUG_LOG("host_in_access_perm_list: %d\n", match);
274         if ((match && !conf.http_default_deny_given) ||
275                         (!match && conf.http_default_deny_given)) {
276                 err_msg = "permission denied";
277                 goto err_out;
278         }
279         hc->status = HTTP_CONNECTED;
280         hc->cq = cq_new(MAX_BACKLOG);
281         PARA_INFO_LOG("accepted client #%d: %s (fd %d)\n", numclients,
282                 CLIENT_ADDR(hc), hc->fd);
283         numclients++;
284         para_list_add(&hc->node, &clients);
285         add_close_on_fork_list(hc->fd);
286         mark_fd_nonblock(hc->fd);
287         return;
288 err_out:
289         PARA_WARNING_LOG("ignoring connect request from %s (%s)\n",
290                 CLIENT_ADDR(hc), err_msg);
291         if (hc->fd > 0)
292                 close(hc->fd);
293         free(hc);
294 }
295
296 static void http_pre_select(int *max_fileno, fd_set *rfds, fd_set *wfds)
297 {
298         struct http_client *hc, *tmp;
299
300         if (server_fd < 0)
301                 return;
302         para_fd_set(server_fd, rfds, max_fileno);
303         list_for_each_entry_safe(hc, tmp, &clients, node) {
304                 //PARA_DEBUG_LOG("hc %p on fd %d: status %d\n", hc, hc->fd, hc->status);
305                 hc->check_r = 0;
306                 hc->check_w = 0;
307                 switch (hc->status) {
308                 case HTTP_STREAMING:
309                 case HTTP_READY_TO_STREAM:
310                         break;
311                 case HTTP_CONNECTED: /* need to recv get request */
312                         para_fd_set(hc->fd, rfds, max_fileno);
313                         hc->check_r = 1;
314                         break;
315                 case HTTP_GOT_GET_REQUEST: /* need to send ok msg */
316                 case HTTP_INVALID_GET_REQUEST: /* need to send err msg */
317                         para_fd_set(hc->fd, wfds, max_fileno);
318                         hc->check_w = 1;
319                         break;
320                 case HTTP_SENT_OK_MSG:
321                         if (!vss_playing())
322                                 break; /* wait until server starts playing */
323                         para_fd_set(hc->fd, wfds, max_fileno);
324                         hc->check_w = 1;
325                         break;
326                 }
327         }
328 }
329
330 static int open_tcp_port(int port)
331 {
332         int ret;
333
334         server_fd = init_tcp_socket(port);
335         if (server_fd < 0) {
336                 http_shutdown_clients();
337                 self->status = SENDER_OFF;
338                 return server_fd;
339         }
340         ret = mark_fd_nonblock(server_fd);
341         if (ret < 0) {
342                 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
343                 exit(EXIT_FAILURE);
344         }
345         self->status = SENDER_ON;
346         add_close_on_fork_list(server_fd);
347         return 1;
348 }
349
350 static int http_com_on(__a_unused struct sender_command_data *scd)
351 {
352         if (self->status == SENDER_ON)
353                 return 1;
354         return open_tcp_port(conf.http_port_arg);
355 }
356
357 static int http_com_off(__a_unused struct sender_command_data *scd)
358 {
359         self->status = SENDER_OFF;
360         if (server_fd > 0) {
361                 close(server_fd);
362                 del_close_on_fork_list(server_fd);
363                 server_fd = -1;
364         }
365         http_shutdown_clients();
366         return 1;
367 }
368
369 static void del_perm_list_entry(struct sender_command_data *scd)
370 {
371         struct access_info *ai, *tmp;
372
373         list_for_each_entry_safe(ai, tmp, &access_perm_list, node) {
374                 char *nad = para_strdup(inet_ntoa(ai->addr));
375                 if (!strcmp(nad, inet_ntoa(scd->addr)) &&
376                                 ai->netmask == scd->netmask) {
377                         PARA_NOTICE_LOG("removing %s/%i from access list\n",
378                                 nad, ai->netmask);
379                         list_del(&ai->node);
380                         free(ai);
381                 }
382                 free(nad);
383         }
384 }
385
386 static void add_perm_list_entry(struct sender_command_data *scd)
387 {
388         struct access_info *ai = para_malloc(sizeof(struct access_info));
389         ai->addr = scd->addr;
390         ai->netmask = scd->netmask;
391         PARA_INFO_LOG("adding %s/%i to access list\n", inet_ntoa(ai->addr),
392                 ai->netmask);
393         para_list_add(&ai->node, &access_perm_list);
394 }
395
396 static int http_com_deny(struct sender_command_data *scd)
397 {
398         if (conf.http_default_deny_given)
399                 del_perm_list_entry(scd);
400         else
401                 add_perm_list_entry(scd);
402         return 1;
403 }
404
405 static int http_com_allow(struct sender_command_data *scd)
406 {
407         if (conf.http_default_deny_given)
408                 add_perm_list_entry(scd);
409         else
410                 del_perm_list_entry(scd);
411         return 1;
412 }
413
414 static char *http_info(void)
415 {
416         char *clnts = NULL, *ap = NULL, *ret;
417         struct access_info *ai, *tmp_ai;
418         struct http_client *hc, *tmp_hc;
419
420         list_for_each_entry_safe(ai, tmp_ai, &access_perm_list, node) {
421                 char *tmp = make_message("%s%s/%d ", ap? ap : "",
422                         inet_ntoa(ai->addr), ai->netmask);
423                 free(ap);
424                 ap = tmp;
425         }
426         list_for_each_entry_safe(hc, tmp_hc, &clients, node) {
427                 char *tmp = make_message("%s%s:%d ", clnts? clnts : "",
428                         CLIENT_ADDR(hc), CLIENT_PORT(hc));
429                 free(clnts);
430                 clnts = tmp;
431         }
432         ret = make_message(
433                 "http status: %s\n"
434                 "http tcp port: %d\n"
435                 "http clients: %d\n"
436                 "http maximal number of clients: %d%s\n"
437                 "http connected clients: %s\n"
438                 "http access %s list: %s\n",
439                 (self->status == SENDER_ON)? "on" : "off",
440                 conf.http_port_arg,
441                 numclients,
442                 conf.http_max_clients_arg,
443                 conf.http_max_clients_arg > 0? "" : " (unlimited)",
444                 clnts? clnts : "(none)",
445                 conf.http_default_deny_given? "allow" : "deny",
446                 ap? ap : "(none)"
447         );
448         free(ap);
449         free(clnts);
450         return ret;
451 }
452
453 static void init_access_control_list(void)
454 {
455         int i;
456         struct sender_command_data scd;
457
458         INIT_LIST_HEAD(&access_perm_list);
459         for (i = 0; i < conf.http_access_given; i++) {
460                 char *arg = para_strdup(conf.http_access_arg[i]);
461                 char *p = strchr(arg, '/');
462                 if (!p)
463                         goto err;
464                 *p = '\0';
465                 if (!inet_aton(arg, &scd.addr))
466                         goto err;
467                 scd.netmask = atoi(++p);
468                 if (scd.netmask < 0 || scd.netmask > 32)
469                         goto err;
470                 add_perm_list_entry(&scd);
471                 goto success;
472 err:
473                 PARA_CRIT_LOG("syntax error for http_access option "
474                         "#%d, ignoring\n", i);
475 success:
476                 free(arg);
477                 continue;
478         }
479 }
480
481 static char *http_help(void)
482 {
483         return make_message(
484                 "usage: {on|off}\n"
485                 "usage: {allow|deny} IP mask\n"
486                 "example: allow 127.0.0.1 32\n"
487         );
488 }
489
490 /**
491  * The init function of the http sender.
492  *
493  * \param s Pointer to the http sender struct.
494  *
495  * It initializes all function pointers of \a s, the client list and the access
496  * control list. If the autostart option was given, the tcp port is opened.
497  */
498 void http_send_init(struct sender *s)
499 {
500         INIT_LIST_HEAD(&clients);
501         s->info = http_info;
502         s->send = http_send;
503         s->pre_select = http_pre_select;
504         s->post_select = http_post_select;
505         s->shutdown_clients = http_shutdown_clients;
506         s->help = http_help;
507         s->client_cmds[SENDER_ON] = http_com_on;
508         s->client_cmds[SENDER_OFF] = http_com_off;
509         s->client_cmds[SENDER_DENY] = http_com_deny;
510         s->client_cmds[SENDER_ALLOW] = http_com_allow;
511         s->client_cmds[SENDER_ADD] = NULL;
512         s->client_cmds[SENDER_DELETE] = NULL;
513         self = s;
514         init_access_control_list();
515         if (!conf.http_no_autostart_given)
516                 open_tcp_port(conf.http_port_arg); /* ignore errors */
517         PARA_DEBUG_LOG("%s", "http sender init complete\n");
518 }