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