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