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