037d4f248d99a296a9c94da06ec27a34fd1aff39
[paraslash.git] / http_send.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 http_send.c paraslash's http sender */
8
9 #include <sys/types.h>
10 #include <dirent.h>
11
12 #include "para.h"
13 #include "error.h"
14 #include "string.h"
15 #include "server.cmdline.h"
16 #include "afh.h"
17 #include "afs.h"
18 #include "server.h"
19 #include "http.h"
20 #include "vss.h"
21 #include "send.h"
22 #include "list.h"
23 #include "close_on_fork.h"
24 #include "net.h"
25 #include "fd.h"
26 #include "chunk_queue.h"
27
28 /** Message sent to clients that do not send a valid get request. */
29 #define HTTP_ERR_MSG "HTTP/1.0 400 Bad Request\n"
30
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 http_acl;
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         /** The socket `name' of the client. */
60         char *name;
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 acl. */
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", hc->name, hc->fd,
92                 msg);
93         numclients--;
94         free(hc->name);
95         close(hc->fd);
96         del_close_on_fork_list(hc->fd);
97         cq_destroy(hc->cq);
98         list_del(&hc->node);
99         free(hc);
100 }
101
102 static void http_shutdown_clients(void)
103 {
104         struct http_client *hc, *tmp;
105         list_for_each_entry_safe(hc, tmp, &clients, node)
106                 http_shutdown_client(hc, "vss request");
107 }
108
109 static int http_send_msg(struct http_client *hc, const char *msg)
110 {
111         int ret = send_buffer(hc->fd, msg);
112
113         if (ret < 0)
114                 http_shutdown_client(hc, "send msg failed");
115         return ret;
116 }
117
118 static void http_send_ok_msg(struct http_client *hc)
119 {
120         PARA_INFO_LOG("sending http ok message to fd %d\n", hc->fd);
121         http_send_msg(hc, HTTP_OK_MSG);
122 }
123
124 static int http_send_err_msg(struct http_client *hc)
125 {
126         PARA_NOTICE_LOG("sending bad request message to fd %d\n", hc->fd);
127         return http_send_msg(hc, HTTP_ERR_MSG);
128 }
129
130 static int send_queued_chunks(struct http_client *hc)
131 {
132         struct queued_chunk *qc;
133         while ((qc = cq_peek(hc->cq))) {
134                 char *buf;
135                 size_t len;
136                 int ret = write_ok(hc->fd);
137                 if (ret <= 0)
138                         return ret? -E_WRITE_OK : 0;
139                 cq_get(qc, &buf, &len);
140                 ret = write(hc->fd, buf, len);
141                 if (ret < 0)
142                         return -E_SEND_QUEUED_CHUNK;
143                 cq_update(hc->cq, ret);
144                 if (ret != len)
145                         return 1;
146                 cq_dequeue(hc->cq);
147         }
148         return 1;
149 }
150
151 static int queue_chunk_or_shutdown(struct http_client *hc, long unsigned chunk_num,
152         size_t sent)
153 {
154         int ret = cq_enqueue(hc->cq, chunk_num, sent);
155         if (ret < 0)
156                 http_shutdown_client(hc, "queue error");
157         return ret;
158 }
159
160 static void http_send( long unsigned current_chunk,
161         __a_unused long unsigned chunks_sent, const char *buf, size_t len)
162 {
163         struct http_client *hc, *tmp;
164         int ret;
165
166         list_for_each_entry_safe(hc, tmp, &clients, node) {
167                 if (hc->status != HTTP_STREAMING &&
168                                 hc->status != HTTP_READY_TO_STREAM)
169                         continue;
170                 if (hc->status == HTTP_READY_TO_STREAM) {
171                         size_t hlen;
172                         char *hbuf = vss_get_header(&hlen);
173                         if (hbuf && hlen > 0 && current_chunk) {
174                                 /* need to send header */
175                                 PARA_INFO_LOG("queueing header: %zu\n", hlen);
176                                 if (queue_chunk_or_shutdown(hc, -1U, 0) < 0)
177                                         continue;
178                         } else
179                                 PARA_INFO_LOG("no need to queue header\n");
180                         hc->status = HTTP_STREAMING;
181                 }
182                 ret = send_queued_chunks(hc);
183                 if (ret < 0) {
184                         http_shutdown_client(hc, "queue send error");
185                         continue;
186                 }
187                 if (!len)
188                         continue;
189                 if (!ret || write_ok(hc->fd) <= 0) {
190                         queue_chunk_or_shutdown(hc, current_chunk, 0);
191                         continue;
192                 }
193 //              PARA_DEBUG_LOG("sending %d -> %s\n", len, remote_name(hc->fd));
194                 ret = write(hc->fd, buf, len);
195 //              PARA_DEBUG_LOG("ret: %d\n", ret);
196                 if (ret < 0) {
197                         http_shutdown_client(hc, "send error");
198                         continue;
199                 }
200                 if (ret != len)
201                         queue_chunk_or_shutdown(hc, current_chunk, ret);
202         }
203 }
204
205 /**
206  * Return true if addr_1 matches addr_2 in the first `netmask' bits.
207  */
208 static int v4_addr_match(uint32_t addr_1, uint32_t addr_2, uint8_t netmask)
209 {
210         uint32_t mask = ~0U;
211
212         if (netmask < 32)
213                 mask <<= (32 - netmask);
214         return (htonl(addr_1) & mask) == (htonl(addr_2) & mask);
215 }
216
217 static int host_in_acl(int fd, struct list_head *acl)
218 {
219         struct access_info *ai, *tmp;
220         struct sockaddr_storage ss;
221         socklen_t sslen = sizeof(ss);
222         struct in_addr v4_addr;
223
224         if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {
225                 PARA_ERROR_LOG("Can not determine peer address: %s\n", strerror(errno));
226                 goto no_match;
227         }
228         v4_addr = extract_v4_addr(&ss);
229         if (!v4_addr.s_addr)
230                 goto no_match;
231
232         list_for_each_entry_safe(ai, tmp, acl, node)
233                 if (v4_addr_match(v4_addr.s_addr, ai->addr.s_addr, ai->netmask))
234                         return 1;
235 no_match:
236         return 0;
237 }
238
239 static void http_post_select(fd_set *rfds, fd_set *wfds)
240 {
241         int i = -1, match;
242         struct http_client *hc, *tmp;
243         const char *err_msg;
244
245         list_for_each_entry_safe(hc, tmp, &clients, node) {
246                 i++;
247 //              PARA_DEBUG_LOG("handling client %d: %s\n", i, remote_name(hc->fd));
248                 switch (hc->status) {
249                 case HTTP_STREAMING: /* nothing to do */
250                 case HTTP_READY_TO_STREAM:
251                         break;
252                 case HTTP_CONNECTED: /* need to recv get request */
253                         if (hc->check_r && FD_ISSET(hc->fd, rfds)) {
254                                 if (recv_pattern(hc->fd, HTTP_GET_MSG, MAXLINE)
255                                                 < 0) {
256                                         hc->status = HTTP_INVALID_GET_REQUEST;
257                                 } else {
258                                         hc->status = HTTP_GOT_GET_REQUEST;
259                                         PARA_INFO_LOG("%s",
260                                                 "received get request\n");
261                                 }
262                         }
263                         break;
264                 case HTTP_GOT_GET_REQUEST: /* need to send ok msg */
265                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
266                                 hc->status = HTTP_SENT_OK_MSG;
267                                 http_send_ok_msg(hc);
268                         }
269                         break;
270                 case HTTP_INVALID_GET_REQUEST: /* need to send err msg */
271                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
272                                 if (http_send_err_msg(hc) >= 0)
273                                         http_shutdown_client(hc,
274                                                 "invalid get request");
275                         }
276                         break;
277                 case HTTP_SENT_OK_MSG: /* need to send header? */
278                         if (hc->check_w && FD_ISSET(hc->fd, wfds))
279                                 hc->status = HTTP_READY_TO_STREAM;
280                         break;
281                 }
282         }
283         if (!FD_ISSET(server_fd, rfds))
284                 return;
285         hc = para_calloc(sizeof(struct http_client));
286         err_msg = "accept error";
287         hc->fd = para_accept(server_fd, NULL, 0);
288         if (hc->fd <= 0)
289                 goto err_out;
290         hc->name = make_message("%s", remote_name(hc->fd));
291         PARA_NOTICE_LOG("connection from %s (fd %d)\n", hc->name, hc->fd);
292         if (conf.http_max_clients_arg > 0 && numclients >=
293                         conf.http_max_clients_arg) {
294                 err_msg = "server full";
295                 goto err_out;
296         }
297         match = host_in_acl(hc->fd, &http_acl);
298         PARA_DEBUG_LOG("host_in_acl: %d\n", match);
299         if ((match && !conf.http_default_deny_given) ||
300                         (!match && conf.http_default_deny_given)) {
301                 err_msg = "permission denied";
302                 goto err_out;
303         }
304         hc->status = HTTP_CONNECTED;
305         hc->cq = cq_new(MAX_BACKLOG);
306         numclients++;
307         PARA_INFO_LOG("accepted client #%d: %s (fd %d)\n", numclients,
308                 hc->name, hc->fd);
309         para_list_add(&hc->node, &clients);
310         add_close_on_fork_list(hc->fd);
311         mark_fd_nonblocking(hc->fd);
312         return;
313 err_out:
314         PARA_WARNING_LOG("ignoring connect request from %s (%s)\n",
315                 hc->name, err_msg);
316         if (hc->fd > 0)
317                 close(hc->fd);
318         free(hc);
319 }
320
321 static void http_pre_select(int *max_fileno, fd_set *rfds, fd_set *wfds)
322 {
323         struct http_client *hc, *tmp;
324
325         if (server_fd < 0)
326                 return;
327         para_fd_set(server_fd, rfds, max_fileno);
328         list_for_each_entry_safe(hc, tmp, &clients, node) {
329                 //PARA_DEBUG_LOG("hc %p on fd %d: status %d\n", hc, hc->fd, hc->status);
330                 hc->check_r = 0;
331                 hc->check_w = 0;
332                 switch (hc->status) {
333                 case HTTP_STREAMING:
334                 case HTTP_READY_TO_STREAM:
335                         break;
336                 case HTTP_CONNECTED: /* need to recv get request */
337                         para_fd_set(hc->fd, rfds, max_fileno);
338                         hc->check_r = 1;
339                         break;
340                 case HTTP_GOT_GET_REQUEST: /* need to send ok msg */
341                 case HTTP_INVALID_GET_REQUEST: /* need to send err msg */
342                         para_fd_set(hc->fd, wfds, max_fileno);
343                         hc->check_w = 1;
344                         break;
345                 case HTTP_SENT_OK_MSG:
346                         if (!vss_playing())
347                                 break; /* wait until server starts playing */
348                         para_fd_set(hc->fd, wfds, max_fileno);
349                         hc->check_w = 1;
350                         break;
351                 }
352         }
353 }
354
355 static int open_tcp_port(int port)
356 {
357         int ret;
358
359         server_fd = para_listen(AF_UNSPEC, IPPROTO_TCP, port);
360         if (server_fd < 0) {
361                 http_shutdown_clients();
362                 self->status = SENDER_OFF;
363                 return server_fd;
364         }
365         ret = mark_fd_nonblocking(server_fd);
366         if (ret < 0) {
367                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
368                 exit(EXIT_FAILURE);
369         }
370         self->status = SENDER_ON;
371         add_close_on_fork_list(server_fd);
372         return 1;
373 }
374
375 static int http_com_on(__a_unused struct sender_command_data *scd)
376 {
377         if (self->status == SENDER_ON)
378                 return 1;
379         return open_tcp_port(conf.http_port_arg);
380 }
381
382 static int http_com_off(__a_unused struct sender_command_data *scd)
383 {
384         self->status = SENDER_OFF;
385         if (server_fd > 0) {
386                 close(server_fd);
387                 del_close_on_fork_list(server_fd);
388                 server_fd = -1;
389         }
390         http_shutdown_clients();
391         return 1;
392 }
393
394 static void del_acl_entry(struct list_head *acl, struct in_addr addr,
395                 int netmask)
396 {
397         struct access_info *ai, *tmp;
398
399         list_for_each_entry_safe(ai, tmp, acl, node) {
400                 char *nad = para_strdup(inet_ntoa(ai->addr));
401                 if (!strcmp(nad, inet_ntoa(addr)) &&
402                                 ai->netmask == netmask) {
403                         PARA_NOTICE_LOG("removing %s/%i from access list\n",
404                                 nad, ai->netmask);
405                         list_del(&ai->node);
406                         free(ai);
407                 }
408                 free(nad);
409         }
410 }
411
412 static void add_acl_entry(struct list_head *acl, struct in_addr addr,
413                 int netmask)
414 {
415         struct access_info *ai = para_malloc(sizeof(struct access_info));
416         ai->addr = addr;
417         ai->netmask = netmask;
418         PARA_INFO_LOG("adding %s/%i to access list\n", inet_ntoa(ai->addr),
419                 ai->netmask);
420         para_list_add(&ai->node, acl);
421 }
422
423 static int http_com_deny(struct sender_command_data *scd)
424 {
425         if (conf.http_default_deny_given)
426                 del_acl_entry(&http_acl, scd->addr, scd->netmask);
427         else
428                 add_acl_entry(&http_acl, scd->addr, scd->netmask);
429         return 1;
430 }
431
432 static int http_com_allow(struct sender_command_data *scd)
433 {
434         if (conf.http_default_deny_given)
435                 add_acl_entry(&http_acl, scd->addr, scd->netmask);
436         else
437                 del_acl_entry(&http_acl, scd->addr, scd->netmask);
438         return 1;
439 }
440
441 static char *get_acl_contents(struct list_head *acl)
442 {
443         struct access_info *ai, *tmp_ai;
444         char *ret = NULL;
445
446         list_for_each_entry_safe(ai, tmp_ai, acl, node) {
447                 char *tmp = make_message("%s%s/%d ", ret? ret : "",
448                         inet_ntoa(ai->addr), ai->netmask);
449                 free(ret);
450                 ret = tmp;
451         }
452         return ret;
453 }
454
455 static char *http_info(void)
456 {
457         char *clnts = NULL, *ret;
458         struct http_client *hc, *tmp_hc;
459
460         char *acl_contents = get_acl_contents(&http_acl);
461         list_for_each_entry_safe(hc, tmp_hc, &clients, node) {
462                 char *tmp = make_message("%s%s ", clnts? clnts : "", hc->name);
463                 free(clnts);
464                 clnts = tmp;
465         }
466         ret = make_message(
467                 "http status: %s\n"
468                 "http tcp port: %d\n"
469                 "http clients: %d\n"
470                 "http maximal number of clients: %d%s\n"
471                 "http connected clients: %s\n"
472                 "http access %s list: %s\n",
473                 (self->status == SENDER_ON)? "on" : "off",
474                 conf.http_port_arg,
475                 numclients,
476                 conf.http_max_clients_arg,
477                 conf.http_max_clients_arg > 0? "" : " (unlimited)",
478                 clnts? clnts : "(none)",
479                 conf.http_default_deny_given? "allow" : "deny",
480                 acl_contents? acl_contents : "(none)"
481         );
482         free(acl_contents);
483         free(clnts);
484         return ret;
485 }
486
487 static void init_acl(struct list_head *acl, char * const *acl_info, int num)
488 {
489         int i;
490
491         INIT_LIST_HEAD(acl);
492         for (i = 0; i < num; i++) {
493                 char *arg = para_strdup(acl_info[i]);
494                 char *p = strchr(arg, '/');
495                 struct in_addr addr;
496                 int netmask;
497
498                 if (!p)
499                         goto err;
500                 *p = '\0';
501                 if (!inet_pton(AF_INET, arg, &addr))
502                         goto err;
503                 netmask = atoi(++p);
504                 if (netmask < 0 || netmask > 32)
505                         goto err;
506                 add_acl_entry(acl, addr, netmask);
507                 goto success;
508 err:
509                 PARA_CRIT_LOG("syntax error: %s\n", acl_info[i]);
510 success:
511                 free(arg);
512                 continue;
513         }
514 }
515
516 static char *http_help(void)
517 {
518         return make_message(
519                 "usage: {on|off}\n"
520                 "usage: {allow|deny} IP mask\n"
521                 "example: allow 127.0.0.1 32\n"
522         );
523 }
524
525 /**
526  * The init function of the http sender.
527  *
528  * \param s Pointer to the http sender struct.
529  *
530  * It initializes all function pointers of \a s, the client list and the access
531  * control list. If the autostart option was given, the tcp port is opened.
532  */
533 void http_send_init(struct sender *s)
534 {
535         INIT_LIST_HEAD(&clients);
536         s->info = http_info;
537         s->send = http_send;
538         s->pre_select = http_pre_select;
539         s->post_select = http_post_select;
540         s->shutdown_clients = http_shutdown_clients;
541         s->help = http_help;
542         s->client_cmds[SENDER_ON] = http_com_on;
543         s->client_cmds[SENDER_OFF] = http_com_off;
544         s->client_cmds[SENDER_DENY] = http_com_deny;
545         s->client_cmds[SENDER_ALLOW] = http_com_allow;
546         s->client_cmds[SENDER_ADD] = NULL;
547         s->client_cmds[SENDER_DELETE] = NULL;
548         self = s;
549         init_acl(&http_acl, conf.http_access_arg, conf.http_access_given);
550         if (!conf.http_no_autostart_given)
551                 open_tcp_port(conf.http_port_arg); /* ignore errors */
552         PARA_DEBUG_LOG("%s", "http sender init complete\n");
553 }