f081c5e65cc74eb4c10f8ac7ad2818a50cffc73f
[deb_shairplay.git] / src / lib / httpd.c
1 /**
2 * Copyright (C) 2011-2012 Juho Vähä-Herttua
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library 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 GNU
12 * Lesser General Public License for more details.
13 */
14
15 #include <stdlib.h>
16 #include <string.h>
17 #include <stdio.h>
18 #include <assert.h>
19
20 #include "httpd.h"
21 #include "netutils.h"
22 #include "http_request.h"
23 #include "compat.h"
24 #include "logger.h"
25
26 struct http_connection_s {
27 int connected;
28
29 int socket_fd;
30 void *user_data;
31 http_request_t *request;
32 };
33 typedef struct http_connection_s http_connection_t;
34
35 struct httpd_s {
36 logger_t *logger;
37 httpd_callbacks_t callbacks;
38
39 int max_connections;
40 int open_connections;
41 http_connection_t *connections;
42
43 /* These variables only edited mutex locked */
44 int running;
45 int joined;
46 thread_handle_t thread;
47 mutex_handle_t run_mutex;
48
49 /* Server fds for accepting connections */
50 int server_fd4;
51 int server_fd6;
52 };
53
54 httpd_t *
55 httpd_init(logger_t *logger, httpd_callbacks_t *callbacks, int max_connections)
56 {
57 httpd_t *httpd;
58
59 assert(logger);
60 assert(callbacks);
61 assert(max_connections > 0);
62
63 /* Allocate the httpd_t structure */
64 httpd = calloc(1, sizeof(httpd_t));
65 if (!httpd) {
66 return NULL;
67 }
68
69 httpd->max_connections = max_connections;
70 httpd->connections = calloc(max_connections, sizeof(http_connection_t));
71 if (!httpd->connections) {
72 free(httpd);
73 return NULL;
74 }
75
76 /* Use the logger provided */
77 httpd->logger = logger;
78
79 /* Save callback pointers */
80 memcpy(&httpd->callbacks, callbacks, sizeof(httpd_callbacks_t));
81
82 /* Initial status joined */
83 httpd->running = 0;
84 httpd->joined = 1;
85
86 return httpd;
87 }
88
89 void
90 httpd_destroy(httpd_t *httpd)
91 {
92 if (httpd) {
93 httpd_stop(httpd);
94
95 free(httpd->connections);
96 free(httpd);
97 }
98 }
99
100 static void
101 httpd_add_connection(httpd_t *httpd, int fd, unsigned char *local, int local_len, unsigned char *remote, int remote_len)
102 {
103 int i;
104
105 for (i=0; i<httpd->max_connections; i++) {
106 if (!httpd->connections[i].connected) {
107 break;
108 }
109 }
110 if (i == httpd->max_connections) {
111 /* This code should never be reached, we do not select server_fds when full */
112 logger_log(httpd->logger, LOGGER_INFO, "Max connections reached");
113 shutdown(fd, SHUT_RDWR);
114 closesocket(fd);
115 return;
116 }
117
118 httpd->open_connections++;
119 httpd->connections[i].socket_fd = fd;
120 httpd->connections[i].connected = 1;
121 httpd->connections[i].user_data = httpd->callbacks.conn_init(httpd->callbacks.opaque, local, local_len, remote, remote_len);
122 }
123
124 static int
125 httpd_accept_connection(httpd_t *httpd, int server_fd, int is_ipv6)
126 {
127 struct sockaddr_storage remote_saddr;
128 socklen_t remote_saddrlen;
129 struct sockaddr_storage local_saddr;
130 socklen_t local_saddrlen;
131 unsigned char *local, *remote;
132 int local_len, remote_len;
133 int ret, fd;
134
135 remote_saddrlen = sizeof(remote_saddr);
136 fd = accept(server_fd, (struct sockaddr *)&remote_saddr, &remote_saddrlen);
137 if (fd == -1) {
138 /* FIXME: Error happened */
139 return -1;
140 }
141
142 local_saddrlen = sizeof(local_saddr);
143 ret = getsockname(fd, (struct sockaddr *)&local_saddr, &local_saddrlen);
144 if (ret == -1) {
145 closesocket(fd);
146 return 0;
147 }
148
149 logger_log(httpd->logger, LOGGER_INFO, "Accepted %s client on socket %d",
150 (is_ipv6 ? "IPv6" : "IPv4"), fd);
151 local = netutils_get_address(&local_saddr, &local_len);
152 remote = netutils_get_address(&remote_saddr, &remote_len);
153
154 httpd_add_connection(httpd, fd, local, local_len, remote, remote_len);
155 return 1;
156 }
157
158 static void
159 httpd_remove_connection(httpd_t *httpd, http_connection_t *connection)
160 {
161 if (connection->request) {
162 http_request_destroy(connection->request);
163 connection->request = NULL;
164 }
165 httpd->callbacks.conn_destroy(connection->user_data);
166 shutdown(connection->socket_fd, SHUT_WR);
167 closesocket(connection->socket_fd);
168 connection->connected = 0;
169 httpd->open_connections--;
170 }
171
172 static THREAD_RETVAL
173 httpd_thread(void *arg)
174 {
175 httpd_t *httpd = arg;
176 char buffer[1024];
177 int i;
178
179 assert(httpd);
180
181 while (1) {
182 fd_set rfds;
183 struct timeval tv;
184 int nfds=0;
185 int ret;
186
187 MUTEX_LOCK(httpd->run_mutex);
188 if (!httpd->running) {
189 MUTEX_UNLOCK(httpd->run_mutex);
190 break;
191 }
192 MUTEX_UNLOCK(httpd->run_mutex);
193
194 /* Set timeout value to 5ms */
195 tv.tv_sec = 1;
196 tv.tv_usec = 5000;
197
198 /* Get the correct nfds value and set rfds */
199 FD_ZERO(&rfds);
200 if (httpd->open_connections < httpd->max_connections) {
201 FD_SET(httpd->server_fd4, &rfds);
202 nfds = httpd->server_fd4+1;
203 if (httpd->server_fd6 != -1) {
204 FD_SET(httpd->server_fd6, &rfds);
205 if (nfds <= httpd->server_fd6) {
206 nfds = httpd->server_fd6+1;
207 }
208 }
209 }
210 for (i=0; i<httpd->max_connections; i++) {
211 int socket_fd;
212 if (!httpd->connections[i].connected) {
213 continue;
214 }
215 socket_fd = httpd->connections[i].socket_fd;
216 FD_SET(socket_fd, &rfds);
217 if (nfds <= socket_fd) {
218 nfds = socket_fd+1;
219 }
220 }
221
222 ret = select(nfds, &rfds, NULL, NULL, &tv);
223 if (ret == 0) {
224 /* Timeout happened */
225 continue;
226 } else if (ret == -1) {
227 /* FIXME: Error happened */
228 logger_log(httpd->logger, LOGGER_INFO, "Error in select");
229 break;
230 }
231
232 if (FD_ISSET(httpd->server_fd4, &rfds)) {
233 ret = httpd_accept_connection(httpd, httpd->server_fd4, 0);
234 if (ret == -1) {
235 break;
236 } else if (ret == 0) {
237 continue;
238 }
239 }
240 if (httpd->open_connections < httpd->max_connections &&
241 httpd->server_fd6 != -1 && FD_ISSET(httpd->server_fd6, &rfds)) {
242 ret = httpd_accept_connection(httpd, httpd->server_fd6, 1);
243 if (ret == -1) {
244 break;
245 } else if (ret == 0) {
246 continue;
247 }
248 }
249 for (i=0; i<httpd->max_connections; i++) {
250 http_connection_t *connection = &httpd->connections[i];
251
252 if (!connection->connected) {
253 continue;
254 }
255 if (!FD_ISSET(connection->socket_fd, &rfds)) {
256 continue;
257 }
258
259 /* If not in the middle of request, allocate one */
260 if (!connection->request) {
261 connection->request = http_request_init();
262 assert(connection->request);
263 }
264
265 logger_log(httpd->logger, LOGGER_DEBUG, "Receiving on socket %d", connection->socket_fd);
266 ret = recv(connection->socket_fd, buffer, sizeof(buffer), 0);
267 if (ret == 0) {
268 logger_log(httpd->logger, LOGGER_INFO, "Connection closed for socket %d", connection->socket_fd);
269 httpd_remove_connection(httpd, connection);
270 continue;
271 }
272
273 /* Parse HTTP request from data read from connection */
274 http_request_add_data(connection->request, buffer, ret);
275 if (http_request_has_error(connection->request)) {
276 logger_log(httpd->logger, LOGGER_INFO, "Error in parsing: %s", http_request_get_error_name(connection->request));
277 httpd_remove_connection(httpd, connection);
278 continue;
279 }
280
281 /* If request is finished, process and deallocate */
282 if (http_request_is_complete(connection->request)) {
283 http_response_t *response = NULL;
284
285 httpd->callbacks.conn_request(connection->user_data, connection->request, &response);
286 http_request_destroy(connection->request);
287 connection->request = NULL;
288
289 if (response) {
290 const char *data;
291 int datalen;
292 int written;
293 int ret;
294
295 /* Get response data and datalen */
296 data = http_response_get_data(response, &datalen);
297
298 written = 0;
299 while (written < datalen) {
300 ret = send(connection->socket_fd, data+written, datalen-written, 0);
301 if (ret == -1) {
302 /* FIXME: Error happened */
303 logger_log(httpd->logger, LOGGER_INFO, "Error in sending data");
304 break;
305 }
306 written += ret;
307 }
308
309 if (http_response_get_disconnect(response)) {
310 logger_log(httpd->logger, LOGGER_INFO, "Disconnecting on software request");
311 httpd_remove_connection(httpd, connection);
312 }
313 } else {
314 logger_log(httpd->logger, LOGGER_INFO, "Didn't get response");
315 }
316 http_response_destroy(response);
317 } else {
318 logger_log(httpd->logger, LOGGER_DEBUG, "Request not complete, waiting for more data...");
319 }
320 }
321 }
322
323 /* Remove all connections that are still connected */
324 for (i=0; i<httpd->max_connections; i++) {
325 http_connection_t *connection = &httpd->connections[i];
326
327 if (!connection->connected) {
328 continue;
329 }
330 logger_log(httpd->logger, LOGGER_INFO, "Removing connection for socket %d", connection->socket_fd);
331 httpd_remove_connection(httpd, connection);
332 }
333
334 /* Close server sockets since they are not used any more */
335 if (httpd->server_fd4 != -1) {
336 closesocket(httpd->server_fd4);
337 httpd->server_fd4 = -1;
338 }
339 if (httpd->server_fd6 != -1) {
340 closesocket(httpd->server_fd6);
341 httpd->server_fd6 = -1;
342 }
343
344 logger_log(httpd->logger, LOGGER_INFO, "Exiting HTTP thread");
345
346 return 0;
347 }
348
349 int
350 httpd_start(httpd_t *httpd, unsigned short *port)
351 {
352 assert(httpd);
353 assert(port);
354
355 MUTEX_LOCK(httpd->run_mutex);
356 if (httpd->running || !httpd->joined) {
357 MUTEX_UNLOCK(httpd->run_mutex);
358 return 0;
359 }
360
361 httpd->server_fd4 = netutils_init_socket(port, 0, 0);
362 if (httpd->server_fd4 == -1) {
363 logger_log(httpd->logger, LOGGER_ERR, "Error initialising socket %d", SOCKET_GET_ERROR());
364 MUTEX_UNLOCK(httpd->run_mutex);
365 return -1;
366 }
367 httpd->server_fd6 = netutils_init_socket(port, 1, 0);
368 if (httpd->server_fd6 == -1) {
369 logger_log(httpd->logger, LOGGER_WARNING, "Error initialising IPv6 socket %d", SOCKET_GET_ERROR());
370 logger_log(httpd->logger, LOGGER_WARNING, "Continuing without IPv6 support");
371 }
372
373 if (listen(httpd->server_fd4, 5) == -1) {
374 logger_log(httpd->logger, LOGGER_ERR, "Error listening to IPv4 socket");
375 closesocket(httpd->server_fd4);
376 closesocket(httpd->server_fd6);
377 MUTEX_UNLOCK(httpd->run_mutex);
378 return -2;
379 }
380 if (httpd->server_fd6 != -1 && listen(httpd->server_fd6, 5) == -1) {
381 logger_log(httpd->logger, LOGGER_ERR, "Error listening to IPv6 socket");
382 closesocket(httpd->server_fd4);
383 closesocket(httpd->server_fd6);
384 MUTEX_UNLOCK(httpd->run_mutex);
385 return -2;
386 }
387 logger_log(httpd->logger, LOGGER_INFO, "Initialized server socket(s)");
388
389 /* Set values correctly and create new thread */
390 httpd->running = 1;
391 httpd->joined = 0;
392 THREAD_CREATE(httpd->thread, httpd_thread, httpd);
393 MUTEX_UNLOCK(httpd->run_mutex);
394
395 return 1;
396 }
397
398 int
399 httpd_is_running(httpd_t *httpd)
400 {
401 int running;
402
403 assert(httpd);
404
405 MUTEX_LOCK(httpd->run_mutex);
406 running = httpd->running || !httpd->joined;
407 MUTEX_UNLOCK(httpd->run_mutex);
408
409 return running;
410 }
411
412 void
413 httpd_stop(httpd_t *httpd)
414 {
415 assert(httpd);
416
417 MUTEX_LOCK(httpd->run_mutex);
418 if (!httpd->running || httpd->joined) {
419 MUTEX_UNLOCK(httpd->run_mutex);
420 return;
421 }
422 httpd->running = 0;
423 MUTEX_UNLOCK(httpd->run_mutex);
424
425 THREAD_JOIN(httpd->thread);
426
427 MUTEX_LOCK(httpd->run_mutex);
428 httpd->joined = 1;
429 MUTEX_UNLOCK(httpd->run_mutex);
430 }
431