Some pretty code fixes and memoryleak addressing.
[mistral.git] / mistral.c
blob6645dbb46a0292402765fd2de2c99e9d77a43f69
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);
104 static void write_cb(struct ev_loop *loop, struct ev_io *w, int revents)
106 struct client *cli = (struct client *) w->data;
108 if (EV_ERROR & revents) {
109 ev_timer_start(loop, &cli->ev_goodbye);
110 return;
113 if (revents & EV_WRITE) {
114 if (cli->rbuff) {
115 write(cli->fd, cli->rbuff, cli->rlen);
116 free(cli->rbuff);
118 ev_io_stop(EV_A_ w);
121 if (cli->close == 1 || timeout == 0.0) {
122 ev_timer_start(loop, &cli->ev_goodbye);
123 } else {
124 ev_timer_again(loop, &cli->ev_timeout);
125 ev_io_start(loop, &cli->ev_read);
129 static inline void* execute_php(void *_cli) {
130 int result;
131 struct client *cli = (struct client *) _cli;
132 zval retval;
134 zval *http_headers[1];
136 cli->rbuff[cli->rlen] = '\0';
138 MAKE_STD_ZVAL(http_headers[0]);
139 ZVAL_STRINGL (http_headers[0], cli->rbuff, (cli->rlen + 1), 0);
141 result = call_user_function(EG(function_table), NULL, callback->func, &retval, 1, http_headers TSRMLS_CC);
142 free(cli->rbuff);
143 cli->rbuff = NULL;
144 cli->rlen = 0;
145 FREE_ZVAL(http_headers[0]); /* Free's the object itself */
147 if (result == SUCCESS) {
148 if (Z_TYPE_P(&retval) == IS_STRING) {
149 cli->rlen = 256 + Z_STRLEN_P(&retval);
150 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
151 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",
152 (timeout == 0.0 ? "close" : "keep-alive"), Z_STRLEN_P(&retval), Z_STRVAL_P(&retval));
154 } else if (Z_TYPE_P(&retval) == IS_ARRAY) {
155 HashTable *arr_hash = Z_ARRVAL_P(&retval);
156 HashPosition pointer;
157 zval **data;
158 int header_len = 11; /* HTTP/1.1 \r\n */
159 int body_len = 0;
160 int status_len = 0;
161 char *status_code = NULL;
162 char *body = NULL;
163 char *test;
165 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
166 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
167 zend_hash_move_forward_ex(arr_hash, &pointer)) {
168 char *key;
169 int key_len;
170 long index;
172 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
173 zval temp = **data;
174 zval_copy_ctor(&temp);
175 convert_to_string(&temp);
177 if (Z_STRLEN(temp) > 0) {
178 if (php_strcmp("status_code", key, key_len - 1)) {
179 status_code = strdup(Z_STRVAL(temp));
180 status_len += Z_STRLEN(temp);
181 } else if (php_strcmp("body", key, key_len - 1)) {
182 body_len += Z_STRLEN(temp);
183 } else { /* So it is a header */
184 header_len += key_len - 1;
185 header_len += 4; /* : \r\n */
186 header_len += Z_STRLEN(temp);
188 if (php_strcasecmp("Connection", key, key_len - 1) && php_strcasecmp("close", Z_STRVAL(temp), Z_STRLEN(temp))) {
189 cli->close = 1;
193 zval_dtor(&temp);
197 cli->rlen = (header_len + (status_len == 0 ? 8 : status_len + 2) + body_len);
198 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
199 test = cli->rbuff;
201 if (status_len == 0) {
202 strncpy(test, "HTTP/1.1 200 OK\r\n", 17);
203 test += 17;
204 } else {
205 strncpy(test, "HTTP/1.1 ", 9);
206 test += 9;
207 strncpy(test, status_code, status_len);
208 test += status_len;
209 strncpy(test, "\r\n", 2);
210 test += 2;
211 free(status_code);
214 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
215 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
216 zend_hash_move_forward_ex(arr_hash, &pointer)) {
217 char *key;
218 int key_len;
219 long index;
221 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
222 zval temp = **data;
223 zval_copy_ctor(&temp);
224 convert_to_string(&temp);
226 if (Z_STRLEN(temp) > 0) {
227 if (status_len > 0 && php_strcmp("status_code", key, key_len - 1)) {
228 /* do nothing */
229 } else if (body_len > 0 && php_strcmp("body", key, key_len - 1)) {
230 body = strdup(Z_STRVAL(temp));
231 } else { /* So it is a header */
232 strncpy(test, key, key_len - 1);
233 test += key_len - 1;
234 strncpy(test, ": ", 2);
235 test += 2;
236 strncpy(test, Z_STRVAL(temp), Z_STRLEN(temp));
237 test += Z_STRLEN(temp);
238 strncpy(test, "\r\n", 2);
239 test += 2;
242 zval_dtor(&temp);
246 strncpy(test, "\r\n", 2);
247 test += 2;
249 if (body) {
250 strncpy(test, body, body_len);
251 free(body);
252 test += body_len;
256 ev_io_start(cli->loop,&cli->ev_write);
259 zval_dtor(&retval);
261 if (result != SUCCESS) {
262 ev_timer_start(cli->loop, &cli->ev_goodbye);
266 static void read_cb(struct ev_loop *loop, struct ev_io *w, int revents)
268 if ((revents & EV_READ) && callback) {
269 struct client *cli = (struct client *) w->data;
270 cli->rbuff = malloc(1024);
271 if (cli->rbuff) {
272 cli->rlen = read(cli->fd,cli->rbuff,1023);
273 if (cli->rlen > 0) {
274 ev_io_stop(EV_A_ w);
275 cli->loop = loop;
276 execute_php(cli);
277 return;
278 } else {
279 free(cli->rbuff);
280 cli->rbuff = NULL;
281 cli->rlen = 0;
286 struct client *cli = (struct client *) w->data;
287 ev_io_stop(EV_A_ w);
288 ev_timer_start(loop, &cli->ev_goodbye);
291 static void accept_cb(struct ev_loop *loop, struct ev_io *w, int revents)
293 int client_fd;
294 struct client *cli;
295 struct sockaddr_in client_addr;
296 socklen_t client_len = sizeof(client_addr);
297 client_fd = accept(w->fd, (struct sockaddr *)&client_addr, &client_len);
298 if (client_fd == -1)
299 return;
301 cli = calloc(1,sizeof(struct client));
302 cli->rbuff = NULL;
303 cli->rlen = 0;
304 cli->fd = client_fd;
305 if (setnonblock(cli->fd) < 0)
306 err(1, "failed to set client socket to non-blocking");
308 ev_io_init(&cli->ev_read, read_cb, cli->fd, EV_READ);
309 cli->ev_read.data = cli;
311 ev_io_init(&cli->ev_write, write_cb, cli->fd, EV_WRITE);
312 cli->ev_write.data = cli;
314 ev_timer_init(&cli->ev_goodbye, goodbye_cb, 0., 0.);
315 cli->ev_goodbye.data = cli;
317 ev_timer_init(&cli->ev_timeout, timeout_cb, 0., (timeout == 0.0 ? 30.0 : timeout));
318 cli->ev_timeout.data = cli;
320 ev_io_start(loop,&cli->ev_read);
323 /* {{{ mistral_functions[] */
324 zend_function_entry mistral_functions[] = {
325 PHP_FE(mistral_init, NULL)
326 PHP_FE(mistral_register_callback, NULL)
327 PHP_FE(mistral_start, NULL)
328 { NULL, NULL, NULL }
330 /* }}} */
332 /* {{{ mistral_module_entry
333 * */
334 zend_module_entry mistral_module_entry = {
335 STANDARD_MODULE_HEADER,
336 "mistral",
337 mistral_functions,
338 NULL, /* Replace with NULL if there is nothing to do at php startup */
339 PHP_MSHUTDOWN(mistral),
340 NULL, /* Replace with NULL if there is nothing to do at request start */
341 NULL, /* Replace with NULL if there is nothing to do at request end */
342 PHP_MINFO(mistral),
343 PHP_MISTRAL_VERSION,
344 STANDARD_MODULE_PROPERTIES
346 /* }}} */
348 #ifdef COMPILE_DL_MISTRAL
349 ZEND_GET_MODULE(mistral)
350 #endif
352 /* {{{ PHP_MINFO_FUNCTION */
353 PHP_MINFO_FUNCTION(mistral)
355 php_info_print_table_start();
356 php_info_print_table_header(2, "Mistral support", "enabled");
357 php_info_print_table_row(2, "Version", PHP_MISTRAL_VERSION);
358 php_info_print_table_end();
360 /* }}} */
362 /* {{{ PHP_MSHUTDOWN_FUNCTION */
363 PHP_MSHUTDOWN_FUNCTION (mistral)
365 _php_event_callback_free(callback);
367 /* }}} */
369 PHP_FUNCTION(mistral_init)
371 struct addrinfo *ai = NULL;
372 struct addrinfo hints;
373 struct addrinfo *runp;
374 int listen_sock = -1;
376 char *listen_addr;
377 int listen_addr_len;
378 long listen_port;
380 struct sockaddr_storage sin;
381 struct sockaddr_in * sa4 = (struct sockaddr_in *) &sin;
382 struct sockaddr_in6 * sa6 = (struct sockaddr_in6 *) &sin;
384 int reuseaddr_on = 1;
385 int keepalive_on = 1;
387 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sld", &listen_addr, &listen_addr_len, &listen_port, &timeout) == FAILURE) {
388 RETURN_NULL();
391 if (listen_port < 1 || listen_port > 65535) {
392 RETURN_NULL();
395 bzero(&hints, sizeof (hints));
396 hints.ai_flags = AI_ADDRCONFIG || AI_NUMERICSERV;
397 hints.ai_socktype = SOCK_STREAM;
399 if (getaddrinfo(listen_addr, "", &hints, &ai) != 0) {
400 RETURN_NULL();
403 runp = ai;
405 while (runp != NULL && listen_sock < 0) {
406 listen_sock = socket(runp->ai_family, SOCK_STREAM, 0);
407 if (listen_sock < 0)
408 runp = runp->ai_next;
411 if (listen_sock < 0) {
412 err(1, "listen failed");
415 if (timeout <= 0.0) {
416 timeout = 0.0;
417 } else {
418 if (setsockopt(listen_sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_on, sizeof(keepalive_on)) == -1)
419 err(1, "setsockopt failed");
422 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on, sizeof(reuseaddr_on)) == -1)
423 err(1, "setsockopt failed");
425 if (runp->ai_family == AF_INET6) {
426 int null = 0;
427 setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &null, sizeof(null));
430 memset(&sin, 0, sizeof(sin));
432 sin.ss_family = runp->ai_family;
433 switch (sin.ss_family) {
434 case AF_INET6:
435 inet_pton(sin.ss_family, listen_addr, &(sa6->sin6_addr));
436 sa6->sin6_port = htons(listen_port);
437 break;
438 case AF_INET:
439 if ( strchr(listen_addr, ':') )
440 /* Invalid IPv4-string. Use the wildcard address. */
441 listen_addr = strdup("0.0.0.0");
443 inet_pton(sin.ss_family, listen_addr, &(sa4->sin_addr));
444 sa4->sin_port = htons(listen_port);
447 if (ai)
448 freeaddrinfo(ai);
450 if (bind(listen_sock, (struct sockaddr *) &sin, sizeof(sin)) < 0)
451 err(1, "bind failed");
453 if (listen(listen_sock, 5) < 0)
454 err(1, "listen failed");
456 if (setnonblock(listen_sock) < 0)
457 err(1, "failed to set server socket to non-blocking");
459 ev_io_init(&ev_accept, accept_cb, listen_sock, EV_READ);
462 /* {{{ proto bool event_set(resource event, resource fd, int events, mixed callback[, mixed arg])
463 * Taken from pecl::libevent event_set
465 PHP_FUNCTION(mistral_register_callback)
467 zval *zcallback, *zarg = NULL;
468 php_event_callback_t *new_callback, *old_callback;
469 char *func_name;
471 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zcallback) != SUCCESS) {
472 return;
475 if (!zend_is_callable(zcallback, 0, &func_name TSRMLS_CC)) {
476 php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid callback", func_name);
477 efree(func_name);
478 RETURN_FALSE;
480 efree(func_name);
482 zval_add_ref(&zcallback);
484 new_callback = emalloc(sizeof(php_event_callback_t));
485 new_callback->func = zcallback;
486 new_callback->arg = zarg;
488 old_callback = callback;
489 callback = new_callback;
491 if (old_callback) {
492 _php_event_callback_free(old_callback);
495 RETURN_TRUE;
497 /* }}} */
499 PHP_FUNCTION(mistral_start)
501 struct ev_loop *loop = ev_default_loop(0);
503 ev_io_start(loop, &ev_accept);
504 ev_loop(loop, 0);