The fix to have everything binary related working.
[mistral.git] / mistral.c
blobcaabff0d7be74482fe0a906b98b59d4265f7ad9b
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;
45 int done;
47 int close;
50 ev_io ev_accept;
51 double timeout = 300;
53 typedef struct _php_event_callback_t { /* {{{ */
54 zval *func;
55 zval *arg;
56 } php_event_callback_t;
57 /* }}} */
59 php_event_callback_t *callback = NULL;
61 http_parser parser;
63 void http_field_cb(void *data, const char *field, size_t flen, const char *value, size_t vlen) {
64 zval *server_vars = (zval *)data;
65 char *fld = malloc(5 + flen + 1);
66 char *val = strndup(value, vlen);
67 size_t i;
69 memcpy(fld, "HTTP_", 5);
70 for (i = 0; i < flen; i++) {
71 if (field[i] == '-')
72 fld[5+i] = '_';
73 else
74 fld[5+i] = toupper(field[i]);
76 fld[5+flen] = '\0';
78 add_assoc_string(server_vars, (char *)fld, (char *)val, 1);
79 free(fld);
80 free(val);
83 void http_on_element(void *data, int type, const char *at, size_t length) {
84 char *line, *val;
85 zval *server_vars = (zval *)data;
87 switch( type ) {
88 case MONGREL_CONTENT_LENGTH:
89 line = "CONTENT_LENGTH";
90 break;
92 case MONGREL_CONTENT_TYPE:
93 line = "CONTENT_TYPE";
94 break;
96 case MONGREL_FRAGMENT:
97 line = "FRAGMENT";
98 break;
100 case MONGREL_HTTP_VERSION:
101 line = "HTTP_VERSION";
102 break;
104 case MONGREL_QUERY_STRING:
105 line = "QUERY_STRING";
106 break;
108 case MONGREL_REQUEST_PATH:
109 line = "REQUEST_PATH";
110 break;
112 case MONGREL_REQUEST_METHOD:
113 line = "REQUEST_METHOD";
114 break;
116 case MONGREL_REQUEST_URI:
117 line = "REQUEST_URI";
118 break;
120 default:
121 line = "UNKNOWN";
124 val = strndup(at, length);
125 add_assoc_string(server_vars, (char *) line, (char *) val, 1);
126 free(val);
129 static int setnonblock(int fd)
131 int flags;
133 flags = fcntl(fd, F_GETFL);
134 if (flags < 0)
135 return flags;
136 flags |= O_NONBLOCK;
137 if (fcntl(fd, F_SETFL, flags) < 0)
138 return -1;
140 return 0;
143 static inline void _php_event_callback_free(php_event_callback_t *this_callback) /* {{{ */
145 if (!this_callback)
146 return;
148 zval_ptr_dtor(&this_callback->func);
149 if (this_callback->arg)
150 zval_ptr_dtor(&this_callback->arg);
152 efree(this_callback);
155 static void timeout_cb(struct ev_loop *loop, struct ev_timer *w, int revents) {
156 struct client *cli = (struct client *) w->data;
157 assert(w == &cli->ev_timeout);
159 ev_timer_start(loop, &cli->ev_goodbye);
162 static void goodbye_cb(struct ev_loop *loop, struct ev_timer *w, int revents) {
163 struct client *cli = (struct client *) w->data;
164 assert(w == &cli->ev_goodbye);
166 ev_io_stop(loop, &cli->ev_read);
167 ev_io_stop(loop, &cli->ev_write);
168 ev_timer_stop(loop, &cli->ev_timeout);
170 shutdown(cli->fd, SHUT_WR);
172 close(cli->fd);
173 free(cli);
176 static void write_cb(struct ev_loop *loop, struct ev_io *w, int revents)
178 struct client *cli = (struct client *) w->data;
180 if (EV_ERROR & revents) {
181 ev_timer_start(loop, &cli->ev_goodbye);
182 return;
185 if (revents & EV_WRITE) {
186 if (cli->rbuff) {
187 cli->done += write(cli->fd, cli->rbuff + cli->done, cli->rlen - cli->done);
188 if (cli->done == cli->rlen) {
189 free(cli->rbuff);
190 cli->rbuff = NULL;
191 cli->rlen = 0;
194 ev_io_stop(EV_A_ w);
197 if ((cli->rlen == 0 && cli->close == 1) || timeout == 0.0) {
198 ev_timer_start(loop, &cli->ev_goodbye);
199 } else {
200 ev_timer_again(loop, &cli->ev_timeout);
201 ev_io_start(loop, &cli->ev_read);
202 if (cli->done < cli->rlen)
203 ev_io_start(loop, &cli->ev_write);
207 static inline void* execute_php(void *_cli) {
208 int result;
209 struct client *cli = (struct client *) _cli;
210 zval retval;
211 zval *headers[1];
212 MAKE_STD_ZVAL(headers[0]);
213 array_init(headers[0]);
215 cli->done = 0;
216 cli->rbuff[cli->rlen] = '\0';
218 http_parser_init(&parser);
219 parser.http_field = &http_field_cb;
220 parser.on_element = &http_on_element;
221 parser.data = headers[0];
222 http_parser_execute(&parser, cli->rbuff, cli->rlen, 0);
224 result = call_user_function(EG(function_table), NULL, callback->func, &retval, 1, headers TSRMLS_CC);
225 free(cli->rbuff);
226 cli->rbuff = NULL;
227 cli->rlen = 0;
229 zval_dtor(headers[0]); /* Free's the object contents */
230 FREE_ZVAL(headers[0]); /* Free's the object itself */
232 if (result == SUCCESS) {
233 if (Z_TYPE_P(&retval) == IS_STRING) {
234 cli->rlen = 256 + Z_STRLEN_P(&retval);
235 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
236 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",
237 (timeout == 0.0 ? "close" : "keep-alive"), Z_STRLEN_P(&retval), Z_STRVAL_P(&retval));
239 } else if (Z_TYPE_P(&retval) == IS_ARRAY) {
240 HashTable *arr_hash = Z_ARRVAL_P(&retval);
241 HashPosition pointer;
242 zval **data;
243 int header_len = 11; /* HTTP/1.1 \r\n */
244 int body_len = 0;
245 int status_len = 0;
246 char *status_code = NULL;
247 char *body = NULL;
248 char *test;
250 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
251 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
252 zend_hash_move_forward_ex(arr_hash, &pointer)) {
253 char *key;
254 int key_len;
255 long index;
257 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
258 zval temp = **data;
259 zval_copy_ctor(&temp);
260 convert_to_string(&temp);
262 if (Z_STRLEN(temp) > 0) {
263 if (php_strcmp("status_code", key, key_len - 1)) {
264 status_code = strndup(Z_STRVAL(temp), Z_STRLEN(temp));
265 status_len += Z_STRLEN(temp);
266 } else if (php_strcmp("body", key, key_len - 1)) {
267 body_len += Z_STRLEN(temp);
268 } else { /* So it is a header */
269 header_len += key_len - 1;
270 header_len += 4; /* : \r\n */
271 header_len += Z_STRLEN(temp);
273 if (php_strcasecmp("Connection", key, key_len - 1) && php_strcasecmp("close", Z_STRVAL(temp), Z_STRLEN(temp))) {
274 cli->close = 1;
278 zval_dtor(&temp);
282 cli->rlen = (header_len + (status_len == 0 ? 8 : status_len + 2) + body_len);
283 cli->rbuff = (char *) malloc(cli->rlen * sizeof(char));
284 test = cli->rbuff;
286 if (status_len == 0) {
287 memcpy(test, "HTTP/1.1 200 OK\r\n", 17);
288 test += 17;
289 } else {
290 memcpy(test, "HTTP/1.1 ", 9);
291 test += 9;
293 memcpy(test, status_code, status_len);
294 test += status_len;
296 memcpy(test, "\r\n", 2);
297 test += 2;
298 free(status_code);
301 for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
302 zend_hash_get_current_data_ex(arr_hash, (void**) &data, &pointer) == SUCCESS;
303 zend_hash_move_forward_ex(arr_hash, &pointer)) {
304 char *key;
305 int key_len;
306 long index;
308 if (zend_hash_get_current_key_ex(arr_hash, &key, &key_len, &index, 0, &pointer) == HASH_KEY_IS_STRING) {
309 zval temp = **data;
310 zval_copy_ctor(&temp);
311 convert_to_string(&temp);
313 if (Z_STRLEN(temp) > 0) {
314 if (status_len > 0 && php_strcmp("status_code", key, key_len - 1)) {
315 /* do nothing */
316 } else if (body_len > 0 && php_strcmp("body", key, key_len - 1)) {
317 body = malloc(Z_STRLEN(temp) * sizeof(char));
318 memcpy(body, Z_STRVAL(temp), Z_STRLEN(temp));
319 } else { /* So it is a header */
320 memcpy(test, key, key_len - 1);
321 test += (key_len - 1);
323 memcpy(test, ": ", 2);
324 test += 2;
326 memcpy(test, Z_STRVAL(temp), Z_STRLEN(temp));
327 test += Z_STRLEN(temp);
329 memcpy(test, "\r\n", 2);
330 test += 2;
333 zval_dtor(&temp);
337 memcpy(test, "\r\n", 2);
338 test += 2;
340 if (body) {
341 memcpy(test, body, body_len);
342 free(body);
343 test += body_len;
347 ev_io_start(cli->loop,&cli->ev_write);
350 zval_dtor(&retval);
352 if (result != SUCCESS) {
353 ev_timer_start(cli->loop, &cli->ev_goodbye);
357 static void read_cb(struct ev_loop *loop, struct ev_io *w, int revents)
359 if ((revents & EV_READ) && callback) {
360 struct client *cli = (struct client *) w->data;
361 cli->rbuff = malloc(1024);
362 if (cli->rbuff) {
363 cli->rlen = read(cli->fd,cli->rbuff,1023);
364 if (cli->rlen > 0) {
365 ev_io_stop(EV_A_ w);
366 cli->loop = loop;
367 execute_php(cli);
368 return;
369 } else {
370 free(cli->rbuff);
371 cli->rbuff = NULL;
372 cli->rlen = 0;
377 struct client *cli = (struct client *) w->data;
378 ev_io_stop(EV_A_ w);
379 ev_timer_start(loop, &cli->ev_goodbye);
382 static void accept_cb(struct ev_loop *loop, struct ev_io *w, int revents)
384 int client_fd;
385 struct client *cli;
386 struct sockaddr_in client_addr;
387 socklen_t client_len = sizeof(client_addr);
388 client_fd = accept(w->fd, (struct sockaddr *)&client_addr, &client_len);
389 if (client_fd == -1)
390 return;
392 cli = calloc(1,sizeof(struct client));
393 cli->rbuff = NULL;
394 cli->rlen = 0;
395 cli->fd = client_fd;
396 if (setnonblock(cli->fd) < 0)
397 err(1, "failed to set client socket to non-blocking");
399 ev_io_init(&cli->ev_read, read_cb, cli->fd, EV_READ);
400 cli->ev_read.data = cli;
402 ev_io_init(&cli->ev_write, write_cb, cli->fd, EV_WRITE);
403 cli->ev_write.data = cli;
405 ev_timer_init(&cli->ev_goodbye, goodbye_cb, 0., 0.);
406 cli->ev_goodbye.data = cli;
408 ev_timer_init(&cli->ev_timeout, timeout_cb, 0., (timeout == 0.0 ? 30.0 : timeout));
409 cli->ev_timeout.data = cli;
411 ev_io_start(loop,&cli->ev_read);
414 /* {{{ mistral_functions[] */
415 zend_function_entry mistral_functions[] = {
416 PHP_FE(mistral_init, NULL)
417 PHP_FE(mistral_register_callback, NULL)
418 PHP_FE(mistral_start, NULL)
419 { NULL, NULL, NULL }
421 /* }}} */
423 /* {{{ mistral_module_entry
424 * */
425 zend_module_entry mistral_module_entry = {
426 STANDARD_MODULE_HEADER,
427 "mistral",
428 mistral_functions,
429 NULL, /* Replace with NULL if there is nothing to do at php startup */
430 PHP_MSHUTDOWN(mistral),
431 NULL, /* Replace with NULL if there is nothing to do at request start */
432 NULL, /* Replace with NULL if there is nothing to do at request end */
433 PHP_MINFO(mistral),
434 PHP_MISTRAL_VERSION,
435 STANDARD_MODULE_PROPERTIES
437 /* }}} */
439 #ifdef COMPILE_DL_MISTRAL
440 ZEND_GET_MODULE(mistral)
441 #endif
443 /* {{{ PHP_MINFO_FUNCTION */
444 PHP_MINFO_FUNCTION(mistral)
446 php_info_print_table_start();
447 php_info_print_table_header(2, "Mistral support", "enabled");
448 php_info_print_table_row(2, "Version", PHP_MISTRAL_VERSION);
449 php_info_print_table_end();
451 /* }}} */
453 /* {{{ PHP_MSHUTDOWN_FUNCTION */
454 PHP_MSHUTDOWN_FUNCTION (mistral)
456 _php_event_callback_free(callback);
458 /* }}} */
460 PHP_FUNCTION(mistral_init)
462 struct addrinfo *ai = NULL;
463 struct addrinfo hints;
464 struct addrinfo *runp;
465 int listen_sock = -1;
467 char *listen_addr;
468 int listen_addr_len;
469 long listen_port;
471 struct sockaddr_storage sin;
472 struct sockaddr_in * sa4 = (struct sockaddr_in *) &sin;
473 struct sockaddr_in6 * sa6 = (struct sockaddr_in6 *) &sin;
475 int reuseaddr_on = 1;
476 int keepalive_on = 1;
478 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sld", &listen_addr, &listen_addr_len, &listen_port, &timeout) == FAILURE) {
479 RETURN_NULL();
482 if (listen_port < 1 || listen_port > 65535) {
483 RETURN_NULL();
486 bzero(&hints, sizeof (hints));
487 hints.ai_flags = AI_ADDRCONFIG || AI_NUMERICSERV;
488 hints.ai_socktype = SOCK_STREAM;
490 if (getaddrinfo(listen_addr, "", &hints, &ai) != 0) {
491 RETURN_NULL();
494 runp = ai;
496 while (runp != NULL && listen_sock < 0) {
497 listen_sock = socket(runp->ai_family, SOCK_STREAM, 0);
498 if (listen_sock < 0)
499 runp = runp->ai_next;
502 if (listen_sock < 0) {
503 err(1, "listen failed");
506 if (timeout <= 0.0) {
507 timeout = 0.0;
508 } else {
509 if (setsockopt(listen_sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_on, sizeof(keepalive_on)) == -1)
510 err(1, "setsockopt failed");
513 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on, sizeof(reuseaddr_on)) == -1)
514 err(1, "setsockopt failed");
516 if (runp->ai_family == AF_INET6) {
517 int null = 0;
518 setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &null, sizeof(null));
521 memset(&sin, 0, sizeof(sin));
523 sin.ss_family = runp->ai_family;
524 switch (sin.ss_family) {
525 case AF_INET6:
526 inet_pton(sin.ss_family, listen_addr, &(sa6->sin6_addr));
527 sa6->sin6_port = htons(listen_port);
528 break;
529 case AF_INET:
530 if ( strchr(listen_addr, ':') )
531 /* Invalid IPv4-string. Use the wildcard address. */
532 listen_addr = strndup("0.0.0.0", 7);
534 inet_pton(sin.ss_family, listen_addr, &(sa4->sin_addr));
535 sa4->sin_port = htons(listen_port);
538 if (ai)
539 freeaddrinfo(ai);
541 if (bind(listen_sock, (struct sockaddr *) &sin, sizeof(sin)) < 0)
542 err(1, "bind failed");
544 if (listen(listen_sock, 5) < 0)
545 err(1, "listen failed");
547 if (setnonblock(listen_sock) < 0)
548 err(1, "failed to set server socket to non-blocking");
550 ev_io_init(&ev_accept, accept_cb, listen_sock, EV_READ);
553 /* {{{ proto bool event_set(resource event, resource fd, int events, mixed callback[, mixed arg])
554 * Taken from pecl::libevent event_set
556 PHP_FUNCTION(mistral_register_callback)
558 zval *zcallback, *zarg = NULL;
559 php_event_callback_t *new_callback, *old_callback;
560 char *func_name;
562 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zcallback) != SUCCESS) {
563 return;
566 if (!zend_is_callable(zcallback, 0, &func_name TSRMLS_CC)) {
567 php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid callback", func_name);
568 efree(func_name);
569 RETURN_FALSE;
571 efree(func_name);
573 zval_add_ref(&zcallback);
575 new_callback = emalloc(sizeof(php_event_callback_t));
576 new_callback->func = zcallback;
577 new_callback->arg = zarg;
579 old_callback = callback;
580 callback = new_callback;
582 if (old_callback) {
583 _php_event_callback_free(old_callback);
586 RETURN_TRUE;
588 /* }}} */
590 PHP_FUNCTION(mistral_start)
592 struct ev_loop *loop = ev_default_loop(0);
594 ev_io_start(loop, &ev_accept);
595 ev_loop(loop, 0);