Memoryleak
[mistral.git] / mistral.c
blobb00701d8444755504ea51e442a674b14cea3ee1c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
5 #include "php.h"
6 #include "ext/standard/info.h"
8 #include <sys/types.h>
9 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <arpa/inet.h>
12 #include <netdb.h>
13 #include <sys/time.h>
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include <fcntl.h>
19 #include <errno.h>
20 #include <err.h>
21 #include <stddef.h>
23 #include <ev.h>
25 #include "mistral.h"
28 * We did use some ideas from:
29 * https://sie.isc.org/svn/nmsg-httpk/trunk/nmsg-httpk.c
30 * http://github.com/ry/libebb/blob/master/ebb.c
33 struct client {
34 int fd;
36 ev_io ev_read;
37 ev_io ev_write;
38 ev_timer ev_timeout;
39 ev_timer ev_goodbye;
41 struct ev_loop *loop;
42 char *rbuff;
43 int rlen;
45 int close;
48 ev_io ev_accept;
49 double timeout = 300;
51 typedef struct _php_event_callback_t { /* {{{ */
52 zval *func;
53 zval *arg;
54 } php_event_callback_t;
55 /* }}} */
57 php_event_callback_t *callback = NULL;
59 static int setnonblock(int fd)
61 int flags;
63 flags = fcntl(fd, F_GETFL);
64 if (flags < 0)
65 return flags;
66 flags |= O_NONBLOCK;
67 if (fcntl(fd, F_SETFL, flags) < 0)
68 return -1;
70 return 0;
73 static inline void _php_event_callback_free(php_event_callback_t *this_callback) /* {{{ */
75 if (!this_callback) {
76 return;
79 zval_ptr_dtor(&this_callback->func);
80 if (this_callback->arg) {
81 zval_ptr_dtor(&this_callback->arg);
83 efree(this_callback);
86 static void timeout_cb(struct ev_loop *loop, struct ev_timer *w, int revents) {
87 struct client *cli = (struct client *) w->data;
88 assert(w == &cli->ev_timeout);
90 ev_timer_start(loop, &cli->ev_goodbye);
93 static void goodbye_cb(struct ev_loop *loop, struct ev_timer *w, int revents) {
94 struct client *cli = (struct client *) w->data;
95 assert(w == &cli->ev_goodbye);
97 ev_io_stop(loop, &cli->ev_read);
98 ev_io_stop(loop, &cli->ev_write);
99 ev_timer_stop(loop, &cli->ev_timeout);
101 close(cli->fd);
102 free(cli);
105 static void write_cb(struct ev_loop *loop, struct ev_io *w, int revents)
107 struct client *cli = (struct client *) w->data;
109 if (EV_ERROR & revents) {
110 ev_timer_start(loop, &cli->ev_goodbye);
111 return;
114 if (revents & EV_WRITE) {
115 if (cli->rbuff) {
116 write(cli->fd, cli->rbuff, cli->rlen);
117 free(cli->rbuff);
119 ev_io_stop(EV_A_ w);
122 if (cli->close == 1 || timeout == 0.0) {
123 ev_timer_start(loop, &cli->ev_goodbye);
124 } else {
125 ev_timer_again(loop, &cli->ev_timeout);
126 ev_io_start(loop, &cli->ev_read);
130 static inline void* execute_php(void *_cli) {
131 int result;
132 struct client *cli = (struct client *) _cli;
133 zval retval;
135 zval *http_headers[1];
137 cli->rbuff[cli->rlen] = '\0';
139 MAKE_STD_ZVAL(http_headers[0]);
140 ZVAL_STRINGL (http_headers[0], cli->rbuff, (cli->rlen + 1), 0);
142 result = call_user_function(EG(function_table), NULL, callback->func, &retval, 1, http_headers TSRMLS_CC);
143 free(cli->rbuff);
144 cli->rbuff = NULL;
145 cli->rlen = 0;
146 FREE_ZVAL(http_headers[0]); /* Free's the object itself */
148 if (result == SUCCESS) {
149 if (Z_TYPE_P(&retval) == IS_STRING) {
150 cli->rlen = 256 + Z_STRLEN_P(&retval);
151 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
152 cli->rlen = snprintf(cli->rbuff, (cli->rlen - 1), "HTTP/1.1 200 OK\r\nConnection: %s\r\nContent-Type: text/plain\r\nServer: mistral/0.1\r\nContent-Length: %u\r\n\r\n%s",
153 (timeout == 0.0 ? "close" : "keep-alive"), Z_STRLEN_P(&retval), Z_STRVAL_P(&retval));
155 } else if (Z_TYPE_P(&retval) == IS_ARRAY) {
156 HashTable *arr_hash = Z_ARRVAL_P(&retval);
157 HashPosition pointer;
158 zval **data;
159 int header_len = 11; /* HTTP/1.1 \r\n */
160 int body_len = 0;
161 int status_len = 0;
162 char *status_code = NULL;
163 char *body = NULL;
164 char *test;
166 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
167 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
168 zend_hash_move_forward_ex(arr_hash, &pointer)) {
169 char *key;
170 int key_len;
171 long index;
173 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
174 zval temp = **data;
175 zval_copy_ctor(&temp);
176 convert_to_string(&temp);
178 if (Z_STRLEN(temp) > 0) {
179 if (php_strcmp("status_code", key, key_len - 1)) {
180 status_code = strdup(Z_STRVAL(temp));
181 status_len += Z_STRLEN(temp);
182 } else if (php_strcmp("body", key, key_len - 1)) {
183 body_len += Z_STRLEN(temp);
184 } else { /* So it is a header */
185 header_len += key_len - 1;
186 header_len += 4; /* : \r\n */
187 header_len += Z_STRLEN(temp);
189 if (php_strcasecmp("Connection", key, key_len - 1) && php_strcasecmp("close", Z_STRVAL(temp), Z_STRLEN(temp))) {
190 cli->close = 1;
194 zval_dtor(&temp);
198 cli->rlen = (header_len + (status_len == 0 ? 8 : status_len + 2) + body_len);
199 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
200 test = cli->rbuff;
202 if (status_len == 0) {
203 strncpy(test, "HTTP/1.1 200 OK\r\n", 17);
204 test += 17;
205 } else {
206 strncpy(test, "HTTP/1.1 ", 9);
207 test += 9;
208 strncpy(test, status_code, status_len);
209 test += status_len;
210 strncpy(test, "\r\n", 2);
211 test += 2;
212 free(status_code);
215 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
216 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
217 zend_hash_move_forward_ex(arr_hash, &pointer)) {
218 char *key;
219 int key_len;
220 long index;
222 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
223 zval temp = **data;
224 zval_copy_ctor(&temp);
225 convert_to_string(&temp);
227 if (Z_STRLEN(temp) > 0) {
228 if (status_len > 0 && php_strcmp("status_code", key, key_len - 1)) {
229 /* do nothing */
230 } else if (body_len > 0 && php_strcmp("body", key, key_len - 1)) {
231 body = strdup(Z_STRVAL(temp));
232 } else { /* So it is a header */
233 strncpy(test, key, key_len - 1);
234 test += key_len - 1;
235 strncpy(test, ": ", 2);
236 test += 2;
237 strncpy(test, Z_STRVAL(temp), Z_STRLEN(temp));
238 test += Z_STRLEN(temp);
239 strncpy(test, "\r\n", 2);
240 test += 2;
243 zval_dtor(&temp);
247 strncpy(test, "\r\n", 2);
248 test += 2;
250 if (body) {
251 strncpy(test, body, body_len);
252 free(body);
253 test += body_len;
257 ev_io_start(cli->loop,&cli->ev_write);
260 zval_dtor(&retval);
262 if (result != SUCCESS) {
263 ev_timer_start(cli->loop, &cli->ev_goodbye);
267 static void read_cb(struct ev_loop *loop, struct ev_io *w, int revents)
269 if ((revents & EV_READ) && callback) {
270 struct client *cli = (struct client *) w->data;
271 cli->rbuff = malloc(1024);
272 if (cli->rbuff) {
273 cli->rlen = read(cli->fd,cli->rbuff,1023);
274 if (cli->rlen > 0) {
275 ev_io_stop(EV_A_ w);
276 cli->loop = loop;
277 execute_php(cli);
278 return;
279 } else {
280 free(cli->rbuff);
281 cli->rbuff = NULL;
282 cli->rlen = 0;
287 struct client *cli = (struct client *) w->data;
288 ev_io_stop(EV_A_ w);
289 ev_timer_start(loop, &cli->ev_goodbye);
292 static void accept_cb(struct ev_loop *loop, struct ev_io *w, int revents)
294 int client_fd;
295 struct client *cli;
296 struct sockaddr_in client_addr;
297 socklen_t client_len = sizeof(client_addr);
298 client_fd = accept(w->fd, (struct sockaddr *)&client_addr, &client_len);
299 if (client_fd == -1)
300 return;
302 cli = calloc(1,sizeof(struct client));
303 cli->rbuff = NULL;
304 cli->rlen = 0;
305 cli->fd = client_fd;
306 if (setnonblock(cli->fd) < 0)
307 err(1, "failed to set client socket to non-blocking");
309 ev_io_init(&cli->ev_read, read_cb, cli->fd, EV_READ);
310 cli->ev_read.data = cli;
312 ev_io_init(&cli->ev_write, write_cb, cli->fd, EV_WRITE);
313 cli->ev_write.data = cli;
315 ev_timer_init(&cli->ev_goodbye, goodbye_cb, 0., 0.);
316 cli->ev_goodbye.data = cli;
318 ev_timer_init(&cli->ev_timeout, timeout_cb, 0., (timeout == 0.0 ? 30.0 : timeout));
319 cli->ev_timeout.data = cli;
321 ev_io_start(loop,&cli->ev_read);
324 /* {{{ mistral_functions[] */
325 zend_function_entry mistral_functions[] = {
326 PHP_FE(mistral_init, NULL)
327 PHP_FE(mistral_register_callback, NULL)
328 PHP_FE(mistral_start, NULL)
329 { NULL, NULL, NULL }
331 /* }}} */
333 /* {{{ mistral_module_entry
334 * */
335 zend_module_entry mistral_module_entry = {
336 STANDARD_MODULE_HEADER,
337 "mistral",
338 mistral_functions,
339 NULL, /* Replace with NULL if there is nothing to do at php startup */
340 PHP_MSHUTDOWN(mistral),
341 NULL, /* Replace with NULL if there is nothing to do at request start */
342 NULL, /* Replace with NULL if there is nothing to do at request end */
343 PHP_MINFO(mistral),
344 PHP_MISTRAL_VERSION,
345 STANDARD_MODULE_PROPERTIES
347 /* }}} */
349 #ifdef COMPILE_DL_MISTRAL
350 ZEND_GET_MODULE(mistral)
351 #endif
353 /* {{{ PHP_MINFO_FUNCTION */
354 PHP_MINFO_FUNCTION(mistral)
356 php_info_print_table_start();
357 php_info_print_table_header(2, "Mistral support", "enabled");
358 php_info_print_table_row(2, "Version", PHP_MISTRAL_VERSION);
359 php_info_print_table_end();
361 /* }}} */
363 /* {{{ PHP_MSHUTDOWN_FUNCTION */
364 PHP_MSHUTDOWN_FUNCTION (mistral)
366 _php_event_callback_free(callback);
368 /* }}} */
370 PHP_FUNCTION(mistral_init)
372 struct addrinfo *ai = NULL;
373 struct addrinfo hints;
374 struct addrinfo *runp;
375 int listen_sock = -1;
377 char *listen_addr;
378 int listen_addr_len;
379 long listen_port;
381 struct sockaddr_storage sin;
382 struct sockaddr_in * sa4 = (struct sockaddr_in *) &sin;
383 struct sockaddr_in6 * sa6 = (struct sockaddr_in6 *) &sin;
385 int reuseaddr_on = 1;
386 int keepalive_on = 1;
388 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sld", &listen_addr, &listen_addr_len, &listen_port, &timeout) == FAILURE) {
389 RETURN_NULL();
392 if (listen_port < 1 || listen_port > 65535) {
393 RETURN_NULL();
396 bzero(&hints, sizeof (hints));
397 hints.ai_flags = AI_ADDRCONFIG || AI_NUMERICSERV;
398 hints.ai_socktype = SOCK_STREAM;
400 if (getaddrinfo(listen_addr, "", &hints, &ai) != 0) {
401 RETURN_NULL();
404 runp = ai;
406 while (runp != NULL && listen_sock < 0) {
407 listen_sock = socket(runp->ai_family, SOCK_STREAM, 0);
408 if (listen_sock < 0)
409 runp = runp->ai_next;
412 if (listen_sock < 0) {
413 err(1, "listen failed");
416 if (timeout <= 0.0) {
417 timeout = 0.0;
418 } else {
419 if (setsockopt(listen_sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_on, sizeof(keepalive_on)) == -1)
420 err(1, "setsockopt failed");
423 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on, sizeof(reuseaddr_on)) == -1)
424 err(1, "setsockopt failed");
426 if (runp->ai_family == AF_INET6) {
427 int null = 0;
428 setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &null, sizeof(null));
431 memset(&sin, 0, sizeof(sin));
433 sin.ss_family = runp->ai_family;
434 switch (sin.ss_family) {
435 case AF_INET6:
436 inet_pton(sin.ss_family, listen_addr, &(sa6->sin6_addr));
437 sa6->sin6_port = htons(listen_port);
438 break;
439 case AF_INET:
440 if ( strchr(listen_addr, ':') )
441 /* Invalid IPv4-string. Use the wildcard address. */
442 listen_addr = strdup("0.0.0.0");
444 inet_pton(sin.ss_family, listen_addr, &(sa4->sin_addr));
445 sa4->sin_port = htons(listen_port);
448 if (ai)
449 freeaddrinfo(ai);
451 if (bind(listen_sock, (struct sockaddr *) &sin, sizeof(sin)) < 0)
452 err(1, "bind failed");
454 if (listen(listen_sock, 5) < 0)
455 err(1, "listen failed");
457 if (setnonblock(listen_sock) < 0)
458 err(1, "failed to set server socket to non-blocking");
460 ev_io_init(&ev_accept, accept_cb, listen_sock, EV_READ);
463 /* {{{ proto bool event_set(resource event, resource fd, int events, mixed callback[, mixed arg])
464 * Taken from pecl::libevent event_set
466 PHP_FUNCTION(mistral_register_callback)
468 zval *zcallback, *zarg = NULL;
469 php_event_callback_t *new_callback, *old_callback;
470 char *func_name;
472 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zcallback) != SUCCESS) {
473 return;
476 if (!zend_is_callable(zcallback, 0, &func_name TSRMLS_CC)) {
477 php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid callback", func_name);
478 efree(func_name);
479 RETURN_FALSE;
481 efree(func_name);
483 zval_add_ref(&zcallback);
485 new_callback = emalloc(sizeof(php_event_callback_t));
486 new_callback->func = zcallback;
487 new_callback->arg = zarg;
489 old_callback = callback;
490 callback = new_callback;
492 if (old_callback) {
493 _php_event_callback_free(old_callback);
496 RETURN_TRUE;
498 /* }}} */
500 PHP_FUNCTION(mistral_start)
502 struct ev_loop *loop = ev_default_loop(0);
504 ev_io_start(loop, &ev_accept);
505 ev_loop(loop, 0);