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