com_cs: Return a syntax error if argc > 2.
[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 send_queued_packets(struct http_client *hc)
182 {
183         int ret;
184         struct queued_packet *qp, *tmp;
185
186         if (list_empty(&hc->packet_queue))
187                 return 1;
188         list_for_each_entry_safe(qp, tmp, &hc->packet_queue, node) {
189                 ret = write_ok(hc->fd);
190                 if (ret <= 0)
191                         return ret? -E_WRITE_OK : 0;
192                 ret = write(hc->fd, qp->packet, qp->len);
193                 if (ret < 0)
194                         return ret;
195                 if (ret != qp->len) {
196                         qp->len -= ret;
197                         memmove(qp->packet, qp->packet + ret, qp->len);
198                         return 0;
199                 }
200                 hc->pq_bytes -= qp->len;
201                 free(qp->packet);
202                 list_del(&qp->node);
203                 free(qp);
204         }
205         return 1;
206 }
207
208 static void http_send(__unused struct audio_format *af,
209                 long unsigned current_chunk,
210                 __unused long unsigned chunks_sent, const char *buf, size_t len)
211 {
212         struct http_client *hc, *tmp;
213         int ret;
214
215         list_for_each_entry_safe(hc, tmp, &clients, node) {
216                 if (hc->status != HTTP_STREAMING &&
217                                 hc->status != HTTP_READY_TO_STREAM)
218                         continue;
219                 if (hc->status == HTTP_READY_TO_STREAM) {
220                         if (af->get_header_info && current_chunk) {
221                                 /* need to send header */
222                                 int hlen;
223                                 char *buf = af->get_header_info(&hlen);
224                                 if (!buf || hlen <= 0)
225                                         continue; /* header not yet available */
226                                 PARA_INFO_LOG("queueing header: %d\n", hlen);
227                                 if (queue_packet(hc, buf, hlen) < 0)
228                                         continue;
229                         } else
230                                 PARA_INFO_LOG("%s", "no need to queue header\n");
231                         hc->status = HTTP_STREAMING;
232                 }
233                 ret = send_queued_packets(hc);
234                 if (ret < 0) {
235                         http_shutdown_client(hc, "send error");
236                         continue;
237                 }
238                 if (!len)
239                         continue;
240                 if (!ret || write_ok(hc->fd) <= 0) {
241                         PARA_INFO_LOG("fd %d not ready (%lu bytes queued),"
242                                 " trying to queue packet\n", hc->fd,
243                                 hc->pq_bytes);
244                         queue_packet(hc, buf, len);
245                         continue;
246                 }
247 //              PARA_DEBUG_LOG("sending %d -> %s\n", len, CLIENT_ADDR(hc));
248                 ret = write(hc->fd, buf, len);
249                 if (ret < 0) {
250                         http_shutdown_client(hc, "send error");
251                         continue;
252                 }
253                 if (ret != len)
254                         queue_packet(hc, buf + ret, len - ret);
255         }
256 }
257
258 static int host_in_access_perm_list(struct http_client *hc)
259 {
260         struct access_info *ai, *tmp;
261         list_for_each_entry_safe(ai, tmp, &access_perm_list, node) {
262                 unsigned mask = ((~0) >> ai->netmask);
263                 if ((hc->addr.sin_addr.s_addr & mask) == (ai->addr.s_addr & mask))
264                         return 1;
265         }
266         return 0;
267 }
268
269 static void http_post_select(__unused struct audio_format *af, fd_set *rfds,
270                 fd_set *wfds)
271 {
272         int i = -1, match;
273         struct http_client *hc, *tmp;
274         const char *err_msg;
275
276         list_for_each_entry_safe(hc, tmp, &clients, node) {
277                 i++;
278 //              PARA_DEBUG_LOG("handling client %d: %s\n", i, CLIENT_ADDR(hc));
279                 switch (hc->status) {
280                 case HTTP_STREAMING: /* nothing to do */
281                 case HTTP_READY_TO_STREAM:
282                         break;
283                 case HTTP_CONNECTED: /* need to recv get request */
284                         if (hc->check_r && FD_ISSET(hc->fd, rfds)) {
285                                 if (recv_pattern(hc->fd, HTTP_GET_MSG, MAXLINE)
286                                                 < 0) {
287                                         hc->status = HTTP_INVALID_GET_REQUEST;
288                                 } else {
289                                         hc->status = HTTP_GOT_GET_REQUEST;
290                                         PARA_INFO_LOG("%s",
291                                                 "received get request\n");
292                                 }
293                         }
294                         break;
295                 case HTTP_GOT_GET_REQUEST: /* need to send ok msg */
296                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
297                                 hc->status = HTTP_SENT_OK_MSG;
298                                 http_send_ok_msg(hc);
299                         }
300                         break;
301                 case HTTP_INVALID_GET_REQUEST: /* need to send err msg */
302                         if (hc->check_w && FD_ISSET(hc->fd, wfds)) {
303                                 if (http_send_err_msg(hc) >= 0)
304                                         http_shutdown_client(hc,
305                                                 "invalid get request");
306                         }
307                         break;
308                 case HTTP_SENT_OK_MSG: /* need to send header? */
309                         if (hc->check_w && FD_ISSET(hc->fd, wfds))
310                                 hc->status = HTTP_READY_TO_STREAM;
311                         break;
312                 }
313         }
314         if (!FD_ISSET(server_fd, rfds))
315                 return;
316         hc = para_calloc(sizeof(struct http_client));
317         err_msg = "accept error";
318         hc->fd = para_accept(server_fd, &hc->addr, sizeof(struct sockaddr_in));
319         if (hc->fd <= 0)
320                 goto err_out;
321         PARA_NOTICE_LOG("connection from %s (fd %d)\n", CLIENT_ADDR(hc), hc->fd);
322         if (conf.http_max_clients_arg > 0 && numclients >=
323                         conf.http_max_clients_arg) {
324                 err_msg = "server full";
325                 goto err_out;
326         }
327         match = host_in_access_perm_list(hc);
328         PARA_DEBUG_LOG("host_in_access_perm_list: %d\n", match);
329         if ((match && !conf.http_default_deny_given) ||
330                         (!match && conf.http_default_deny_given)) {
331                 err_msg = "permission denied";
332                 goto err_out;
333         }
334         hc->status = HTTP_CONNECTED;
335         INIT_LIST_HEAD(&hc->packet_queue);
336         PARA_INFO_LOG("accepted client #%d: %s (fd %d)\n", numclients,
337                 CLIENT_ADDR(hc), hc->fd);
338         numclients++;
339         list_add(&hc->node, &clients);
340         return;
341 err_out:
342         PARA_WARNING_LOG("ignoring connect request from %s (%s)\n",
343                 CLIENT_ADDR(hc), err_msg);
344         if (hc->fd > 0)
345                 close(hc->fd);
346         free(hc);
347 }
348
349 static void http_pre_select(struct audio_format *af, int *max_fileno, fd_set *rfds,
350                 fd_set *wfds)
351 {
352         struct http_client *hc, *tmp;
353
354         if (server_fd < 0)
355                 return;
356         FD_SET(server_fd, rfds);
357         *max_fileno = MAX(*max_fileno, server_fd);
358         list_for_each_entry_safe(hc, tmp, &clients, node) {
359                 //PARA_DEBUG_LOG("hc %p on fd %d: status %d\n", hc, hc->fd, hc->status);
360                 hc->check_r = 0;
361                 hc->check_w = 0;
362                 switch (hc->status) {
363                 case HTTP_STREAMING:
364                 case HTTP_READY_TO_STREAM:
365                         break;
366                 case HTTP_CONNECTED: /* need to recv get request */
367                         FD_SET(hc->fd, rfds);
368                         *max_fileno = MAX(*max_fileno, hc->fd);
369                         hc->check_r = 1;
370                         break;
371                 case HTTP_GOT_GET_REQUEST: /* need to send ok msg */
372                 case HTTP_INVALID_GET_REQUEST: /* need to send err msg */
373                         FD_SET(hc->fd, wfds);
374                         *max_fileno = MAX(*max_fileno, hc->fd);
375                         hc->check_w = 1;
376                         break;
377                 case HTTP_SENT_OK_MSG:
378                         if (!af || !afs_playing())
379                                 break; /* wait until server starts playing */
380                         FD_SET(hc->fd, wfds);
381                         *max_fileno = MAX(*max_fileno, hc->fd);
382                         hc->check_w = 1;
383                         break;
384                 }
385         }
386 }
387
388 static int open_tcp_port(int port)
389 {
390         server_fd = init_tcp_socket(port);
391         if (server_fd < 0) {
392                 http_shutdown_clients_real();
393                 self->status = SENDER_OFF;
394                 return server_fd;
395         }
396         self->status = SENDER_ON;
397         add_close_on_fork_list(server_fd);
398         return 1;
399 }
400
401 static int http_com_on(__unused struct sender_command_data *scd)
402 {
403         if (self->status == SENDER_ON)
404                 return 1;
405         return open_tcp_port(conf.http_port_arg);
406 }
407
408 static int http_com_off(__unused struct sender_command_data *scd)
409 {
410         self->status = SENDER_OFF;
411         if (server_fd > 0) {
412                 close(server_fd);
413                 del_close_on_fork_list(server_fd);
414                 server_fd = -1;
415         }
416         http_shutdown_clients_real();
417         return 1;
418 }
419
420 static void del_perm_list_entry(struct sender_command_data *scd)
421 {
422         struct access_info *ai, *tmp;
423
424         list_for_each_entry_safe(ai, tmp, &access_perm_list, node) {
425                 char *nad = para_strdup(inet_ntoa(ai->addr));
426                 if (!strcmp(nad, inet_ntoa(scd->addr)) &&
427                                 ai->netmask == scd->netmask) {
428                         PARA_NOTICE_LOG("removing %s/%i from access list\n",
429                                 nad, ai->netmask);
430                         list_del(&ai->node);
431                         free(ai);
432                 }
433                 free(nad);
434         }
435 }
436
437 static void add_perm_list_entry(struct sender_command_data *scd)
438 {
439         struct access_info *ai = para_malloc(sizeof(struct access_info));
440         ai->addr = scd->addr;
441         ai->netmask = scd->netmask;
442         PARA_INFO_LOG("adding %s/%i to access list\n", inet_ntoa(ai->addr),
443                 ai->netmask);
444         list_add(&ai->node, &access_perm_list);
445 }
446
447 static int http_com_deny(struct sender_command_data *scd)
448 {
449         if (conf.http_default_deny_given)
450                 del_perm_list_entry(scd);
451         else
452                 add_perm_list_entry(scd);
453         return 1;
454 }
455
456 static int http_com_allow(struct sender_command_data *scd)
457 {
458         if (conf.http_default_deny_given)
459                 add_perm_list_entry(scd);
460         else
461                 del_perm_list_entry(scd);
462         return 1;
463 }
464
465 static char *http_info(void)
466 {
467         char *clnts = NULL, *ap = NULL, *ret;
468         struct access_info *ai, *tmp_ai;
469         struct http_client *hc, *tmp_hc;
470
471         list_for_each_entry_safe(ai, tmp_ai, &access_perm_list, node) {
472                 char *tmp = make_message("%s%s/%d ", ap? ap : "",
473                         inet_ntoa(ai->addr), ai->netmask);
474                 free(ap);
475                 ap = tmp;
476         }
477         list_for_each_entry_safe(hc, tmp_hc, &clients, node) {
478                 char *tmp = make_message("%s%s:%d ", clnts? clnts : "",
479                         CLIENT_ADDR(hc), CLIENT_PORT(hc));
480                 free(clnts);
481                 clnts = tmp;
482         }
483         ret = make_message(
484                 "http status: %s\n"
485                 "http tcp port: %d\n"
486                 "http clients: %d\n"
487                 "http maximal number of clients: %d%s\n"
488                 "http connected clients: %s\n"
489                 "http access %s list: %s\n",
490                 (self->status == SENDER_ON)? "on" : "off",
491                 conf.http_port_arg,
492                 numclients,
493                 conf.http_max_clients_arg,
494                 conf.http_max_clients_arg > 0? "" : " (unlimited)",
495                 clnts? clnts : "(none)",
496                 conf.http_default_deny_given? "allow" : "deny",
497                 ap? ap : "(none)"
498         );
499         free(ap);
500         free(clnts);
501         return ret;
502 }
503
504 static void init_access_control_list(void)
505 {
506         int i;
507         struct sender_command_data scd;
508
509         INIT_LIST_HEAD(&access_perm_list);
510         for (i = 0; i < conf.http_access_given; i++) {
511                 char *arg = para_strdup(conf.http_access_arg[i]);
512                 char *p = strchr(arg, '/');
513                 if (!p)
514                         goto err;
515                 *p = '\0';
516                 if (!inet_aton(arg, &scd.addr))
517                         goto err;
518                 scd.netmask = atoi(++p);
519                 if (scd.netmask < 0 || scd.netmask > 32)
520                         goto err;
521                 add_perm_list_entry(&scd);
522                 goto success;
523 err:
524                 PARA_CRIT_LOG("syntax error for http_access option "
525                         "#%d, ignoring\n", i);
526 success:
527                 free(arg);
528                 continue;
529         }
530 }
531
532 static char *http_help(void)
533 {
534         return make_message(
535                 "usage: {on|off}\n"
536                 "usage: {allow|deny} IP mask\n"
537                 "example: allow 127.0.0.1 32\n"
538         );
539 }
540
541 /**
542  * the init function of the http sender
543  *
544  * \param s pointer to the http sender struct
545  *
546  * It initializes all function pointers of \a s, init the client list and the
547  * acess control list as well. If autostart is wanted, open the tcp port.
548  */
549 void http_send_init(struct sender *s)
550 {
551         INIT_LIST_HEAD(&clients);
552         s->info = http_info;
553         s->send = http_send;
554         s->pre_select = http_pre_select;
555         s->post_select = http_post_select;
556         s->shutdown_clients = http_shutdown_clients;
557         s->help = http_help;
558         s->client_cmds[SENDER_ON] = http_com_on;
559         s->client_cmds[SENDER_OFF] = http_com_off;
560         s->client_cmds[SENDER_DENY] = http_com_deny;
561         s->client_cmds[SENDER_ALLOW] = http_com_allow;
562         s->client_cmds[SENDER_ADD] = NULL;
563         s->client_cmds[SENDER_DELETE] = NULL;
564         self = s;
565         init_access_control_list();
566         if (!conf.http_no_autostart_given)
567                 open_tcp_port(conf.http_port_arg);
568         PARA_DEBUG_LOG("%s", "http sender init complete\n");
569 }