alsa_writer pre_select: Only set a small timeout if really neccessary.
[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 #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 extern struct gengetopt_args_info conf;
42
43 /** the possible states of a client from the server's POV */
44 enum http_status {
45         HTTP_CONNECTED,
46         HTTP_GOT_GET_REQUEST,
47         HTTP_SENT_OK_MSG,
48         HTTP_READY_TO_STREAM,
49         HTTP_STREAMING,
50         HTTP_INVALID_GET_REQUEST
51 };
52
53 /** clients will be kicked if there are more than that many bytes pending */
54 #define MAX_BACKLOG 40000
55 /** the list of connected clients **/
56 static struct list_head clients;
57 /** the whitelist/blacklist */
58 static struct list_head access_perm_list;
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 packets for this client */
75         struct list_head packet_queue;
76 /** the number of pending bytes for this client */
77         unsigned long pq_bytes;
78 };
79
80 /**
81  * describes one queued data packet for a client
82  *
83  * The send function of the http sender checks each client fd for writing. If a
84  * client fd is not ready, it tries to queue that packet for this client until
85  * the number of queued bytes exceeds \p MAX_BACKLOG.
86  */
87 struct queued_packet {
88 /** the length of the packet in bytes */
89         unsigned int len;
90 /** pointer to the packet data */
91         char *packet;
92 /** position of the packet in the packet list */
93         struct list_head node;
94 };
95
96 /**
97  * describes one entry in the blacklist/whitelist of the http sender
98  */
99 struct access_info {
100         /** the address to be black/whitelisted */
101         struct in_addr addr;
102         /** the netmask for this entry */
103         int netmask;
104         /** the position of this entry in the access_perm_list */
105         struct list_head node;
106 };
107
108 static int server_fd = -1, numclients;
109 static struct sender *self;
110
111
112 static void http_shutdown_client(struct http_client *hc, const char *msg)
113 {
114         struct queued_packet *qp, *tmp;
115         PARA_INFO_LOG("shutting down %s on fd %d (%s)\n", CLIENT_ADDR(hc),
116                 hc->fd, msg);
117         numclients--;
118         close(hc->fd);
119
120         list_for_each_entry_safe(qp, tmp, &hc->packet_queue, node) {
121                 free(qp->packet);
122                 list_del(&qp->node);
123                 free(qp);
124         }
125         list_del(&hc->node);
126         free(hc);
127 }
128
129 static void http_shutdown_clients(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
136 static int http_send_msg(struct http_client *hc, const char *msg)
137 {
138         int ret = send_buffer(hc->fd, msg);
139
140         if (ret < 0)
141                 http_shutdown_client(hc, "send msg failed");
142         return ret;
143 }
144
145 static void http_send_ok_msg(struct http_client *hc)
146 {
147         PARA_INFO_LOG("sending http ok message to fd %d\n", hc->fd);
148         http_send_msg(hc, HTTP_OK_MSG);
149 }
150
151 static int http_send_err_msg(struct http_client *hc)
152 {
153         PARA_NOTICE_LOG("sending bad request message to fd %d\n", hc->fd);
154         return http_send_msg(hc, HTTP_ERR_MSG);
155 }
156
157 static int queue_packet(struct http_client *hc, const char *buf, size_t len)
158 {
159         struct queued_packet *qp;
160         if (hc->pq_bytes + len > MAX_BACKLOG) {
161                 http_shutdown_client(hc, "packet queue overrun");
162                 return -E_QUEUE;
163         }
164         qp = para_malloc(sizeof(struct queued_packet));
165         hc->pq_bytes += len;
166         qp->packet = para_malloc(len);
167         memcpy(qp->packet, buf, len);
168         qp->len = len;
169         list_add_tail(&qp->node, &hc->packet_queue);
170         PARA_INFO_LOG("%lu bytes queued for fd %d\n", hc->pq_bytes, hc->fd);
171         return 1;
172 }
173
174 static int send_queued_packets(struct http_client *hc)
175 {
176         int ret;
177         struct queued_packet *qp, *tmp;
178
179         if (list_empty(&hc->packet_queue))
180                 return 1;
181         list_for_each_entry_safe(qp, tmp, &hc->packet_queue, node) {
182                 ret = write_ok(hc->fd);
183                 if (ret <= 0)
184                         return ret? -E_WRITE_OK : 0;
185                 ret = write(hc->fd, qp->packet, qp->len);
186                 if (ret < 0)
187                         return ret;
188                 if (ret != qp->len) {
189                         qp->len -= ret;
190                         memmove(qp->packet, qp->packet + ret, qp->len);
191                         return 0;
192                 }
193                 hc->pq_bytes -= qp->len;
194                 free(qp->packet);
195                 list_del(&qp->node);
196                 free(qp);
197         }
198         return 1;
199 }
200
201 static void http_send( long unsigned current_chunk,
202         __a_unused long unsigned chunks_sent, const char *buf, size_t len)
203 {
204         struct http_client *hc, *tmp;
205         int ret;
206
207         list_for_each_entry_safe(hc, tmp, &clients, node) {
208                 if (hc->status != HTTP_STREAMING &&
209                                 hc->status != HTTP_READY_TO_STREAM)
210                         continue;
211                 if (hc->status == HTTP_READY_TO_STREAM) {
212                         int hlen;
213                         char *buf = afs_get_header(&hlen);
214                         if (buf && hlen > 0 && current_chunk) {
215                                 /* need to send header */
216                                 PARA_INFO_LOG("queueing header: %d\n", hlen);
217                                 if (queue_packet(hc, buf, hlen) < 0)
218                                         continue;
219                         } else
220                                 PARA_INFO_LOG("%s", "no need to queue header\n");
221                         hc->status = HTTP_STREAMING;
222                 }
223                 ret = send_queued_packets(hc);
224                 if (ret < 0) {
225                         http_shutdown_client(hc, "send error");
226                         continue;
227                 }
228                 if (!len)
229                         continue;
230                 if (!ret || write_ok(hc->fd) <= 0) {
231                         PARA_INFO_LOG("fd %d not ready (%lu bytes queued),"
232                                 " trying to queue packet\n", hc->fd,
233                                 hc->pq_bytes);
234                         queue_packet(hc, buf, len);
235                         continue;
236                 }
237 //              PARA_DEBUG_LOG("sending %d -> %s\n", len, CLIENT_ADDR(hc));
238                 ret = write(hc->fd, buf, len);
239                 if (ret < 0) {
240                         http_shutdown_client(hc, "send error");
241                         continue;
242                 }
243                 if (ret != len)
244                         queue_packet(hc, buf + ret, len - ret);
245         }
246 }
247
248 static int host_in_access_perm_list(struct http_client *hc)
249 {
250         struct access_info *ai, *tmp;
251         list_for_each_entry_safe(ai, tmp, &access_perm_list, node) {
252                 unsigned mask = ((~0) >> ai->netmask);
253                 if ((hc->addr.sin_addr.s_addr & mask) == (ai->addr.s_addr & mask))
254                         return 1;
255         }
256         return 0;
257 }
258
259 static void http_post_select(fd_set *rfds, fd_set *wfds)
260 {
261         int i = -1, match;
262         struct http_client *hc, *tmp;
263         const char *err_msg;
264
265         list_for_each_entry_safe(hc, tmp, &clients, node) {
266                 i++;
267 //              PARA_DEBUG_LOG("handling client %d: %s\n", i, CLIENT_ADDR(hc));
268                 switch (hc->status) {
269                 case HTTP_STREAMING: /* nothing to do */
270                 case HTTP_READY_TO_STREAM:
271                         break;
272                 case HTTP_CONNECTED: /* need to recv get request */
273                         if (hc->check_r && FD_ISSET(hc->fd, rfds)) {
274                                 if (recv_pattern(hc->fd, HTTP_GET_MSG, MAXLINE)
275                                                 < 0) {
276                                         hc->status = HTTP_INVALID_GET_REQUEST;
277                                 } else {
278                                         hc->status = HTTP_GOT_GET_REQUEST;
279                                         PARA_INFO_LOG("%s",
280                                                 "received get request\n");
281                                 }
282                         }
283                         break;
284                 case HTTP_GOT_GET_REQUEST: /* need to send ok msg */
285                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
286                                 hc->status = HTTP_SENT_OK_MSG;
287                                 http_send_ok_msg(hc);
288                         }
289                         break;
290                 case HTTP_INVALID_GET_REQUEST: /* need to send err msg */
291                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
292                                 if (http_send_err_msg(hc) >= 0)
293                                         http_shutdown_client(hc,
294                                                 "invalid get request");
295                         }
296                         break;
297                 case HTTP_SENT_OK_MSG: /* need to send header? */
298                         if (hc->check_w && FD_ISSET(hc->fd, wfds))
299                                 hc->status = HTTP_READY_TO_STREAM;
300                         break;
301                 }
302         }
303         if (!FD_ISSET(server_fd, rfds))
304                 return;
305         hc = para_calloc(sizeof(struct http_client));
306         err_msg = "accept error";
307         hc->fd = para_accept(server_fd, &hc->addr, sizeof(struct sockaddr_in));
308         if (hc->fd <= 0)
309                 goto err_out;
310         PARA_NOTICE_LOG("connection from %s (fd %d)\n", CLIENT_ADDR(hc), hc->fd);
311         if (conf.http_max_clients_arg > 0 && numclients >=
312                         conf.http_max_clients_arg) {
313                 err_msg = "server full";
314                 goto err_out;
315         }
316         match = host_in_access_perm_list(hc);
317         PARA_DEBUG_LOG("host_in_access_perm_list: %d\n", match);
318         if ((match && !conf.http_default_deny_given) ||
319                         (!match && conf.http_default_deny_given)) {
320                 err_msg = "permission denied";
321                 goto err_out;
322         }
323         hc->status = HTTP_CONNECTED;
324         INIT_LIST_HEAD(&hc->packet_queue);
325         PARA_INFO_LOG("accepted client #%d: %s (fd %d)\n", numclients,
326                 CLIENT_ADDR(hc), hc->fd);
327         numclients++;
328         list_add(&hc->node, &clients);
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 (!afs_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         server_fd = init_tcp_socket(port);
375         if (server_fd < 0) {
376                 http_shutdown_clients();
377                 self->status = SENDER_OFF;
378                 return server_fd;
379         }
380         self->status = SENDER_ON;
381         add_close_on_fork_list(server_fd);
382         return 1;
383 }
384
385 static int http_com_on(__a_unused struct sender_command_data *scd)
386 {
387         if (self->status == SENDER_ON)
388                 return 1;
389         return open_tcp_port(conf.http_port_arg);
390 }
391
392 static int http_com_off(__a_unused struct sender_command_data *scd)
393 {
394         self->status = SENDER_OFF;
395         if (server_fd > 0) {
396                 close(server_fd);
397                 del_close_on_fork_list(server_fd);
398                 server_fd = -1;
399         }
400         http_shutdown_clients();
401         return 1;
402 }
403
404 static void del_perm_list_entry(struct sender_command_data *scd)
405 {
406         struct access_info *ai, *tmp;
407
408         list_for_each_entry_safe(ai, tmp, &access_perm_list, node) {
409                 char *nad = para_strdup(inet_ntoa(ai->addr));
410                 if (!strcmp(nad, inet_ntoa(scd->addr)) &&
411                                 ai->netmask == scd->netmask) {
412                         PARA_NOTICE_LOG("removing %s/%i from access list\n",
413                                 nad, ai->netmask);
414                         list_del(&ai->node);
415                         free(ai);
416                 }
417                 free(nad);
418         }
419 }
420
421 static void add_perm_list_entry(struct sender_command_data *scd)
422 {
423         struct access_info *ai = para_malloc(sizeof(struct access_info));
424         ai->addr = scd->addr;
425         ai->netmask = scd->netmask;
426         PARA_INFO_LOG("adding %s/%i to access list\n", inet_ntoa(ai->addr),
427                 ai->netmask);
428         list_add(&ai->node, &access_perm_list);
429 }
430
431 static int http_com_deny(struct sender_command_data *scd)
432 {
433         if (conf.http_default_deny_given)
434                 del_perm_list_entry(scd);
435         else
436                 add_perm_list_entry(scd);
437         return 1;
438 }
439
440 static int http_com_allow(struct sender_command_data *scd)
441 {
442         if (conf.http_default_deny_given)
443                 add_perm_list_entry(scd);
444         else
445                 del_perm_list_entry(scd);
446         return 1;
447 }
448
449 static char *http_info(void)
450 {
451         char *clnts = NULL, *ap = NULL, *ret;
452         struct access_info *ai, *tmp_ai;
453         struct http_client *hc, *tmp_hc;
454
455         list_for_each_entry_safe(ai, tmp_ai, &access_perm_list, node) {
456                 char *tmp = make_message("%s%s/%d ", ap? ap : "",
457                         inet_ntoa(ai->addr), ai->netmask);
458                 free(ap);
459                 ap = tmp;
460         }
461         list_for_each_entry_safe(hc, tmp_hc, &clients, node) {
462                 char *tmp = make_message("%s%s:%d ", clnts? clnts : "",
463                         CLIENT_ADDR(hc), CLIENT_PORT(hc));
464                 free(clnts);
465                 clnts = tmp;
466         }
467         ret = make_message(
468                 "http status: %s\n"
469                 "http tcp port: %d\n"
470                 "http clients: %d\n"
471                 "http maximal number of clients: %d%s\n"
472                 "http connected clients: %s\n"
473                 "http access %s list: %s\n",
474                 (self->status == SENDER_ON)? "on" : "off",
475                 conf.http_port_arg,
476                 numclients,
477                 conf.http_max_clients_arg,
478                 conf.http_max_clients_arg > 0? "" : " (unlimited)",
479                 clnts? clnts : "(none)",
480                 conf.http_default_deny_given? "allow" : "deny",
481                 ap? ap : "(none)"
482         );
483         free(ap);
484         free(clnts);
485         return ret;
486 }
487
488 static void init_access_control_list(void)
489 {
490         int i;
491         struct sender_command_data scd;
492
493         INIT_LIST_HEAD(&access_perm_list);
494         for (i = 0; i < conf.http_access_given; i++) {
495                 char *arg = para_strdup(conf.http_access_arg[i]);
496                 char *p = strchr(arg, '/');
497                 if (!p)
498                         goto err;
499                 *p = '\0';
500                 if (!inet_aton(arg, &scd.addr))
501                         goto err;
502                 scd.netmask = atoi(++p);
503                 if (scd.netmask < 0 || scd.netmask > 32)
504                         goto err;
505                 add_perm_list_entry(&scd);
506                 goto success;
507 err:
508                 PARA_CRIT_LOG("syntax error for http_access option "
509                         "#%d, ignoring\n", 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, init the client list and the
531  * acess control list as well. If autostart is wanted, open the tcp port.
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_access_control_list();
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 }