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