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