To use it.
[mistral.git] / mistral.c
blob5c5fe772f773b4fb28dd0f706433ad7e27acdd7f
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 "parser.h"
26 #include "mistral.h"
29 * We did use some ideas from:
30 * https://sie.isc.org/svn/nmsg-httpk/trunk/nmsg-httpk.c
31 * http://github.com/ry/libebb/blob/master/ebb.c
34 struct client {
35 int fd;
37 ev_io ev_read;
38 ev_io ev_write;
39 ev_timer ev_timeout;
40 ev_timer ev_goodbye;
42 struct ev_loop *loop;
43 char *rbuff;
44 int rlen;
46 int close;
49 ev_io ev_accept;
50 double timeout = 300;
52 typedef struct _php_event_callback_t { /* {{{ */
53 zval *func;
54 zval *arg;
55 } php_event_callback_t;
56 /* }}} */
58 php_event_callback_t *callback = NULL;
60 http_parser parser;
62 void http_field_cb(void *data, const char *field, size_t flen, const char *value, size_t vlen) {
63 zval *server_vars = (zval *)data;
64 char *fld = malloc(5 + flen + 1);
65 char *val = strndup(value, vlen);
66 size_t i;
68 strncpy(fld, "HTTP_", 5);
69 for (i = 0; i < flen; i++) {
70 if (field[i] == '-')
71 fld[5+i] = '_';
72 else
73 fld[5+i] = toupper(field[i]);
75 fld[5+flen] = '\0';
77 add_assoc_string(server_vars, (char *)fld, (char *)val, 1);
78 free(fld);
79 free(val);
82 void http_on_element(void *data, int type, const char *at, size_t length) {
83 char *line, *val;
84 zval *server_vars = (zval *)data;
86 switch( type ) {
87 case MONGREL_CONTENT_LENGTH:
88 line = "CONTENT_LENGTH";
89 break;
91 case MONGREL_CONTENT_TYPE:
92 line = "CONTENT_TYPE";
93 break;
95 case MONGREL_FRAGMENT:
96 line = "FRAGMENT";
97 break;
99 case MONGREL_HTTP_VERSION:
100 line = "HTTP_VERSION";
101 break;
103 case MONGREL_QUERY_STRING:
104 line = "QUERY_STRING";
105 break;
107 case MONGREL_REQUEST_PATH:
108 line = "REQUEST_PATH";
109 break;
111 case MONGREL_REQUEST_METHOD:
112 line = "REQUEST_METHOD";
113 break;
115 case MONGREL_REQUEST_URI:
116 line = "REQUEST_URI";
117 break;
119 default:
120 line = "UNKNOWN";
123 val = strndup(at, length);
124 add_assoc_string(server_vars, (char *) line, (char *) val, 1);
125 free(val);
128 static int setnonblock(int fd)
130 int flags;
132 flags = fcntl(fd, F_GETFL);
133 if (flags < 0)
134 return flags;
135 flags |= O_NONBLOCK;
136 if (fcntl(fd, F_SETFL, flags) < 0)
137 return -1;
139 return 0;
142 static inline void _php_event_callback_free(php_event_callback_t *this_callback) /* {{{ */
144 if (!this_callback)
145 return;
147 zval_ptr_dtor(&this_callback->func);
148 if (this_callback->arg)
149 zval_ptr_dtor(&this_callback->arg);
151 efree(this_callback);
154 static void timeout_cb(struct ev_loop *loop, struct ev_timer *w, int revents) {
155 struct client *cli = (struct client *) w->data;
156 assert(w == &cli->ev_timeout);
158 ev_timer_start(loop, &cli->ev_goodbye);
161 static void goodbye_cb(struct ev_loop *loop, struct ev_timer *w, int revents) {
162 struct client *cli = (struct client *) w->data;
163 assert(w == &cli->ev_goodbye);
165 ev_io_stop(loop, &cli->ev_read);
166 ev_io_stop(loop, &cli->ev_write);
167 ev_timer_stop(loop, &cli->ev_timeout);
169 close(cli->fd);
172 static void write_cb(struct ev_loop *loop, struct ev_io *w, int revents)
174 struct client *cli = (struct client *) w->data;
176 if (EV_ERROR & revents) {
177 ev_timer_start(loop, &cli->ev_goodbye);
178 return;
181 if (revents & EV_WRITE) {
182 if (cli->rbuff) {
183 write(cli->fd, cli->rbuff, cli->rlen);
184 free(cli->rbuff);
186 ev_io_stop(EV_A_ w);
189 if (cli->close == 1 || timeout == 0.0) {
190 ev_timer_start(loop, &cli->ev_goodbye);
191 } else {
192 ev_timer_again(loop, &cli->ev_timeout);
193 ev_io_start(loop, &cli->ev_read);
197 static inline void* execute_php(void *_cli) {
198 int result;
199 struct client *cli = (struct client *) _cli;
200 zval retval;
201 zval *headers[1];
202 MAKE_STD_ZVAL(headers[0]);
203 array_init(headers[0]);
205 cli->rbuff[cli->rlen] = '\0';
207 http_parser_init(&parser);
208 parser.http_field = &http_field_cb;
209 parser.on_element = &http_on_element;
210 parser.data = headers[0];
211 http_parser_execute(&parser, cli->rbuff, cli->rlen, 0);
213 result = call_user_function(EG(function_table), NULL, callback->func, &retval, 1, headers TSRMLS_CC);
214 free(cli->rbuff);
215 cli->rbuff = NULL;
216 cli->rlen = 0;
218 zval_dtor(headers[0]); /* Free's the object contents */
219 FREE_ZVAL(headers[0]); /* Free's the object itself */
221 if (result == SUCCESS) {
222 if (Z_TYPE_P(&retval) == IS_STRING) {
223 cli->rlen = 256 + Z_STRLEN_P(&retval);
224 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
225 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",
226 (timeout == 0.0 ? "close" : "keep-alive"), Z_STRLEN_P(&retval), Z_STRVAL_P(&retval));
228 } else if (Z_TYPE_P(&retval) == IS_ARRAY) {
229 HashTable *arr_hash = Z_ARRVAL_P(&retval);
230 HashPosition pointer;
231 zval **data;
232 int header_len = 11; /* HTTP/1.1 \r\n */
233 int body_len = 0;
234 int status_len = 0;
235 char *status_code = NULL;
236 char *body = NULL;
237 char *test;
239 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
240 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
241 zend_hash_move_forward_ex(arr_hash, &pointer)) {
242 char *key;
243 int key_len;
244 long index;
246 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
247 zval temp = **data;
248 zval_copy_ctor(&temp);
249 convert_to_string(&temp);
251 if (Z_STRLEN(temp) > 0) {
252 if (php_strcmp("status_code", key, key_len - 1)) {
253 status_code = strdup(Z_STRVAL(temp));
254 status_len += Z_STRLEN(temp);
255 } else if (php_strcmp("body", key, key_len - 1)) {
256 body_len += Z_STRLEN(temp);
257 } else { /* So it is a header */
258 header_len += key_len - 1;
259 header_len += 4; /* : \r\n */
260 header_len += Z_STRLEN(temp);
262 if (php_strcasecmp("Connection", key, key_len - 1) && php_strcasecmp("close", Z_STRVAL(temp), Z_STRLEN(temp))) {
263 cli->close = 1;
267 zval_dtor(&temp);
271 cli->rlen = (header_len + (status_len == 0 ? 8 : status_len + 2) + body_len);
272 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
273 test = cli->rbuff;
275 if (status_len == 0) {
276 strncpy(test, "HTTP/1.1 200 OK\r\n", 17);
277 test += 17;
278 } else {
279 strncpy(test, "HTTP/1.1 ", 9);
280 test += 9;
281 strncpy(test, status_code, status_len);
282 test += status_len;
283 strncpy(test, "\r\n", 2);
284 test += 2;
285 free(status_code);
288 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
289 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
290 zend_hash_move_forward_ex(arr_hash, &pointer)) {
291 char *key;
292 int key_len;
293 long index;
295 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
296 zval temp = **data;
297 zval_copy_ctor(&temp);
298 convert_to_string(&temp);
300 if (Z_STRLEN(temp) > 0) {
301 if (status_len > 0 && php_strcmp("status_code", key, key_len - 1)) {
302 /* do nothing */
303 } else if (body_len > 0 && php_strcmp("body", key, key_len - 1)) {
304 body = strdup(Z_STRVAL(temp));
305 } else { /* So it is a header */
306 strncpy(test, key, key_len - 1);
307 test += key_len - 1;
308 strncpy(test, ": ", 2);
309 test += 2;
310 strncpy(test, Z_STRVAL(temp), Z_STRLEN(temp));
311 test += Z_STRLEN(temp);
312 strncpy(test, "\r\n", 2);
313 test += 2;
316 zval_dtor(&temp);
320 strncpy(test, "\r\n", 2);
321 test += 2;
323 if (body) {
324 strncpy(test, body, body_len);
325 free(body);
326 test += body_len;
330 ev_io_start(cli->loop,&cli->ev_write);
333 zval_dtor(&retval);
335 if (result != SUCCESS) {
336 ev_timer_start(cli->loop, &cli->ev_goodbye);
340 static void read_cb(struct ev_loop *loop, struct ev_io *w, int revents)
342 if ((revents & EV_READ) && callback) {
343 struct client *cli = (struct client *) w->data;
344 cli->rbuff = malloc(1024);
345 if (cli->rbuff) {
346 cli->rlen = read(cli->fd,cli->rbuff,1023);
347 if (cli->rlen > 0) {
348 ev_io_stop(EV_A_ w);
349 cli->loop = loop;
350 execute_php(cli);
351 return;
352 } else {
353 free(cli->rbuff);
354 cli->rbuff = NULL;
355 cli->rlen = 0;
360 struct client *cli = (struct client *) w->data;
361 ev_io_stop(EV_A_ w);
362 ev_timer_start(loop, &cli->ev_goodbye);
365 static void accept_cb(struct ev_loop *loop, struct ev_io *w, int revents)
367 int client_fd;
368 struct client *cli;
369 struct sockaddr_in client_addr;
370 socklen_t client_len = sizeof(client_addr);
371 client_fd = accept(w->fd, (struct sockaddr *)&client_addr, &client_len);
372 if (client_fd == -1)
373 return;
375 cli = calloc(1,sizeof(struct client));
376 cli->rbuff = NULL;
377 cli->rlen = 0;
378 cli->fd = client_fd;
379 if (setnonblock(cli->fd) < 0)
380 err(1, "failed to set client socket to non-blocking");
382 ev_io_init(&cli->ev_read, read_cb, cli->fd, EV_READ);
383 cli->ev_read.data = cli;
385 ev_io_init(&cli->ev_write, write_cb, cli->fd, EV_WRITE);
386 cli->ev_write.data = cli;
388 ev_timer_init(&cli->ev_goodbye, goodbye_cb, 0., 0.);
389 cli->ev_goodbye.data = cli;
391 ev_timer_init(&cli->ev_timeout, timeout_cb, 0., (timeout == 0.0 ? 30.0 : timeout));
392 cli->ev_timeout.data = cli;
394 ev_io_start(loop,&cli->ev_read);
397 /* {{{ mistral_functions[] */
398 zend_function_entry mistral_functions[] = {
399 PHP_FE(mistral_init, NULL)
400 PHP_FE(mistral_register_callback, NULL)
401 PHP_FE(mistral_start, NULL)
402 { NULL, NULL, NULL }
404 /* }}} */
406 /* {{{ mistral_module_entry
407 * */
408 zend_module_entry mistral_module_entry = {
409 STANDARD_MODULE_HEADER,
410 "mistral",
411 mistral_functions,
412 NULL, /* Replace with NULL if there is nothing to do at php startup */
413 PHP_MSHUTDOWN(mistral),
414 NULL, /* Replace with NULL if there is nothing to do at request start */
415 NULL, /* Replace with NULL if there is nothing to do at request end */
416 PHP_MINFO(mistral),
417 PHP_MISTRAL_VERSION,
418 STANDARD_MODULE_PROPERTIES
420 /* }}} */
422 #ifdef COMPILE_DL_MISTRAL
423 ZEND_GET_MODULE(mistral)
424 #endif
426 /* {{{ PHP_MINFO_FUNCTION */
427 PHP_MINFO_FUNCTION(mistral)
429 php_info_print_table_start();
430 php_info_print_table_header(2, "Mistral support", "enabled");
431 php_info_print_table_row(2, "Version", PHP_MISTRAL_VERSION);
432 php_info_print_table_end();
434 /* }}} */
436 /* {{{ PHP_MSHUTDOWN_FUNCTION */
437 PHP_MSHUTDOWN_FUNCTION (mistral)
439 _php_event_callback_free(callback);
441 /* }}} */
443 PHP_FUNCTION(mistral_init)
445 struct addrinfo *ai = NULL;
446 struct addrinfo hints;
447 struct addrinfo *runp;
448 int listen_sock = -1;
450 char *listen_addr;
451 int listen_addr_len;
452 long listen_port;
454 struct sockaddr_storage sin;
455 struct sockaddr_in * sa4 = (struct sockaddr_in *) &sin;
456 struct sockaddr_in6 * sa6 = (struct sockaddr_in6 *) &sin;
458 int reuseaddr_on = 1;
459 int keepalive_on = 1;
461 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sld", &listen_addr, &listen_addr_len, &listen_port, &timeout) == FAILURE) {
462 RETURN_NULL();
465 if (listen_port < 1 || listen_port > 65535) {
466 RETURN_NULL();
469 bzero(&hints, sizeof (hints));
470 hints.ai_flags = AI_ADDRCONFIG || AI_NUMERICSERV;
471 hints.ai_socktype = SOCK_STREAM;
473 if (getaddrinfo(listen_addr, "", &hints, &ai) != 0) {
474 RETURN_NULL();
477 runp = ai;
479 while (runp != NULL && listen_sock < 0) {
480 listen_sock = socket(runp->ai_family, SOCK_STREAM, 0);
481 if (listen_sock < 0)
482 runp = runp->ai_next;
485 if (listen_sock < 0) {
486 err(1, "listen failed");
489 if (timeout <= 0.0) {
490 timeout = 0.0;
491 } else {
492 if (setsockopt(listen_sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_on, sizeof(keepalive_on)) == -1)
493 err(1, "setsockopt failed");
496 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on, sizeof(reuseaddr_on)) == -1)
497 err(1, "setsockopt failed");
499 if (runp->ai_family == AF_INET6) {
500 int null = 0;
501 setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &null, sizeof(null));
504 memset(&sin, 0, sizeof(sin));
506 sin.ss_family = runp->ai_family;
507 switch (sin.ss_family) {
508 case AF_INET6:
509 inet_pton(sin.ss_family, listen_addr, &(sa6->sin6_addr));
510 sa6->sin6_port = htons(listen_port);
511 break;
512 case AF_INET:
513 if ( strchr(listen_addr, ':') )
514 /* Invalid IPv4-string. Use the wildcard address. */
515 listen_addr = strdup("0.0.0.0");
517 inet_pton(sin.ss_family, listen_addr, &(sa4->sin_addr));
518 sa4->sin_port = htons(listen_port);
521 if (ai)
522 freeaddrinfo(ai);
524 if (bind(listen_sock, (struct sockaddr *) &sin, sizeof(sin)) < 0)
525 err(1, "bind failed");
527 if (listen(listen_sock, 5) < 0)
528 err(1, "listen failed");
530 if (setnonblock(listen_sock) < 0)
531 err(1, "failed to set server socket to non-blocking");
533 ev_io_init(&ev_accept, accept_cb, listen_sock, EV_READ);
536 /* {{{ proto bool event_set(resource event, resource fd, int events, mixed callback[, mixed arg])
537 * Taken from pecl::libevent event_set
539 PHP_FUNCTION(mistral_register_callback)
541 zval *zcallback, *zarg = NULL;
542 php_event_callback_t *new_callback, *old_callback;
543 char *func_name;
545 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zcallback) != SUCCESS) {
546 return;
549 if (!zend_is_callable(zcallback, 0, &func_name TSRMLS_CC)) {
550 php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid callback", func_name);
551 efree(func_name);
552 RETURN_FALSE;
554 efree(func_name);
556 zval_add_ref(&zcallback);
558 new_callback = emalloc(sizeof(php_event_callback_t));
559 new_callback->func = zcallback;
560 new_callback->arg = zarg;
562 old_callback = callback;
563 callback = new_callback;
565 if (old_callback) {
566 _php_event_callback_free(old_callback);
569 RETURN_TRUE;
571 /* }}} */
573 PHP_FUNCTION(mistral_start)
575 struct ev_loop *loop = ev_default_loop(0);
577 ev_io_start(loop, &ev_accept);
578 ev_loop(loop, 0);