static inline int php_url_scanner_add_var_impl(char *name, size_t name_len, char *value, size_t value_len, int encode, int type) { smart_str sname = {0}; smart_str svalue = {0}; smart_str hname = {0}; smart_str hvalue = {0}; zend_string *encoded; url_adapt_state_ex_t *url_state; php_output_handler_func_t handler; if (type) { url_state = &BG(url_adapt_session_ex); handler = php_url_scanner_session_handler; } else { url_state = &BG(url_adapt_output_ex); handler = php_url_scanner_output_handler; } if (!url_state->active) { php_url_scanner_ex_activate(type); php_output_start_internal(ZEND_STRL("URL-Rewriter"), handler, 0, PHP_OUTPUT_HANDLER_STDFLAGS); url_state->active = 1; } if (url_state->url_app.s && ZSTR_LEN(url_state->url_app.s) != 0) { smart_str_appends(&url_state->url_app, PG(arg_separator).output); } if (encode) { encoded = php_raw_url_encode(name, name_len); smart_str_appendl(&sname, ZSTR_VAL(encoded), ZSTR_LEN(encoded)); zend_string_free(encoded); encoded = php_raw_url_encode(value, value_len); smart_str_appendl(&svalue, ZSTR_VAL(encoded), ZSTR_LEN(encoded)); zend_string_free(encoded); encoded = php_escape_html_entities_ex((unsigned char*)name, name_len, 0, ENT_QUOTES|ENT_SUBSTITUTE, SG(default_charset), 0); smart_str_appendl(&hname, ZSTR_VAL(encoded), ZSTR_LEN(encoded)); zend_string_free(encoded); encoded = php_escape_html_entities_ex((unsigned char*)value, value_len, 0, ENT_QUOTES|ENT_SUBSTITUTE, SG(default_charset), 0); smart_str_appendl(&hvalue, ZSTR_VAL(encoded), ZSTR_LEN(encoded)); zend_string_free(encoded); } else { smart_str_appendl(&sname, name, name_len); smart_str_appendl(&svalue, value, value_len); smart_str_appendl(&hname, name, name_len); smart_str_appendl(&hvalue, value, value_len); } smart_str_append_smart_str(&url_state->url_app, &sname); smart_str_appendc(&url_state->url_app, '='); smart_str_append_smart_str(&url_state->url_app, &svalue); smart_str_appends(&url_state->form_app, "<input type=\"hidden\" name=\""); smart_str_append_smart_str(&url_state->form_app, &hname); smart_str_appends(&url_state->form_app, "\" value=\""); smart_str_append_smart_str(&url_state->form_app, &hvalue); smart_str_appends(&url_state->form_app, "\" />"); smart_str_free(&sname); smart_str_free(&svalue); smart_str_free(&hname); smart_str_free(&hvalue); return SUCCESS; }
phpdbg_notice("frame", "id=\"%d\"", "Switched to frame #%d", frame); { const char *file_chr = zend_get_executed_filename(); zend_string *file = zend_string_init(file_chr, strlen(file_chr), 0); phpdbg_list_file(file, 3, zend_get_executed_lineno() - 1, zend_get_executed_lineno()); efree(file); } } /* }}} */ static void phpdbg_dump_prototype(zval *tmp) /* {{{ */ { zval *funcname, *class, class_zv, *type, *args, *argstmp; funcname = zend_hash_str_find(Z_ARRVAL_P(tmp), ZEND_STRL("function")); if ((class = zend_hash_str_find(Z_ARRVAL_P(tmp), ZEND_STRL("object")))) { ZVAL_NEW_STR(&class_zv, Z_OBJCE_P(class)->name); class = &class_zv; } else { class = zend_hash_str_find(Z_ARRVAL_P(tmp), ZEND_STRL("class")); } if (class) { type = zend_hash_str_find(Z_ARRVAL_P(tmp), ZEND_STRL("type")); } args = zend_hash_str_find(Z_ARRVAL_P(tmp), ZEND_STRL("args")); phpdbg_xml(" symbol=\"%s%s%s\"", class ? Z_STRVAL_P(class) : "", class ? Z_STRVAL_P(type) : "", Z_STRVAL_P(funcname));
return instance; } /* }}} */ /** {{{ int yaf_route_map_route(yaf_route_t *route, yaf_request_t *request TSRMLS_DC) */ int yaf_route_map_route(yaf_route_t *route, yaf_request_t *request TSRMLS_DC) { zval *ctl_prefer, *delimer, *zuri, *base_uri, *params; char *req_uri, *tmp, *rest, *ptrptr, *seg; char *query_str = NULL; uint seg_len = 0; smart_str route_result = {0}; zuri = zend_read_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_URI), 1 TSRMLS_CC); base_uri = zend_read_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_BASE), 1 TSRMLS_CC); ctl_prefer = zend_read_property(yaf_route_map_ce, route, ZEND_STRL(YAF_ROUTE_MAP_VAR_NAME_CTL_PREFER), 1 TSRMLS_CC); delimer = zend_read_property(yaf_route_map_ce, route, ZEND_STRL(YAF_ROUTE_MAP_VAR_NAME_DELIMETER), 1 TSRMLS_CC); if (base_uri && IS_STRING == Z_TYPE_P(base_uri) && !strncasecmp(Z_STRVAL_P(zuri), Z_STRVAL_P(base_uri), Z_STRLEN_P(base_uri))) { req_uri = estrdup(Z_STRVAL_P(zuri) + Z_STRLEN_P(base_uri)); } else { req_uri = estrdup(Z_STRVAL_P(zuri)); } if (Z_TYPE_P(delimer) == IS_STRING && Z_STRLEN_P(delimer)) { if ((query_str = strstr(req_uri, Z_STRVAL_P(delimer))) != NULL
static PHP_METHOD(swoole_redis, connect) { char *host; zend_size_t host_len; long port; zval *callback; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "slz", &host, &host_len, &port, &callback) == FAILURE) { RETURN_FALSE; } if (host_len <= 0) { swoole_php_error(E_WARNING, "host is empty."); RETURN_FALSE; } if (port <= 1 || port > 65535) { swoole_php_error(E_WARNING, "port is invalid."); RETURN_FALSE; } swRedisClient *redis = emalloc(sizeof(swRedisClient)); bzero(redis, sizeof(swRedisClient)); #if PHP_MAJOR_VERSION < 7 redis->object = getThis(); #else redis->object = &redis->_object; memcpy(redis->object, getThis(), sizeof(zval)); #endif sw_zval_add_ref(&redis->object); swoole_set_object(getThis(), redis); redisAsyncContext *context = redisAsyncConnect(host, (int) port); if (context->err) { swoole_php_error(E_WARNING, "connect to redis-server[%s:%d] failed, Erorr: %s[%d]", host, (int) port, context->errstr, context->err); RETURN_FALSE; } php_swoole_check_reactor(); if (!isset_event_callback) { SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_READ, swoole_redis_onRead); SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE, swoole_redis_onWrite); isset_event_callback = 1; } redisAsyncSetConnectCallback(context, swoole_redis_onConnect); redisAsyncSetDisconnectCallback(context, swoole_redis_onClose); #if PHP_MAJOR_VERSION < 7 redis->connect_callback = callback; #else redis->connect_callback = &redis->_connect_callback; memcpy(redis->connect_callback, callback, sizeof(zval)); #endif sw_zval_add_ref(&redis->connect_callback); redis->context = context; context->ev.addRead = swoole_redis_event_AddRead; context->ev.delRead = swoole_redis_event_DelRead; context->ev.addWrite = swoole_redis_event_AddWrite; context->ev.delWrite = swoole_redis_event_DelWrite; context->ev.cleanup = swoole_redis_event_Cleanup; context->ev.data = redis; zend_update_property_string(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("host"), host TSRMLS_CC); zend_update_property_long(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("port"), port TSRMLS_CC); if (SwooleG.main_reactor->add(SwooleG.main_reactor, redis->context->c.fd, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE) < 0) { swoole_php_fatal_error(E_WARNING, "swoole_event_add failed. Erorr: %s[%d].", redis->context->errstr, redis->context->err); RETURN_FALSE; } swConnection *conn = swReactor_get(SwooleG.main_reactor, redis->context->c.fd); conn->object = redis; }
zval * yee_exception_to_array(zval *self) { zend_object *object = zend_object_store_get_object(self); zval *ret = NULL; zend_call_method(&self, object->ce, NULL, ZEND_STRL("toarrayrecursive"), &ret, 1, self, NULL); return ret; }
zval_ptr_dtor(¶ms); efree(rest); } return 1; } /* }}} */ /** {{{ int yaf_route_static_route(yaf_route_t *route, yaf_request_t *request TSRMLS_DC) */ int yaf_route_static_route(yaf_route_t *route, yaf_request_t *request TSRMLS_DC) { zval *zuri, *base_uri; char *req_uri; int req_uri_len; zuri = zend_read_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_URI), 1 TSRMLS_CC); base_uri = zend_read_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_BASE), 1 TSRMLS_CC); if (base_uri && IS_STRING == Z_TYPE_P(base_uri) && strstr(Z_STRVAL_P(zuri), Z_STRVAL_P(base_uri)) == Z_STRVAL_P(zuri)) { req_uri = estrdup(Z_STRVAL_P(zuri) + Z_STRLEN_P(base_uri)); req_uri_len = Z_STRLEN_P(zuri) - Z_STRLEN_P(base_uri); } else { req_uri = estrdup(Z_STRVAL_P(zuri)); req_uri_len = Z_STRLEN_P(zuri); } yaf_route_pathinfo_route(request, req_uri, req_uri_len TSRMLS_CC); efree(req_uri); return 1; }
+----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "TSRM.h" #include "php_suhosin.h" #include "ext/standard/base64.h" #include "sha256.h" static void suhosin_get_ipv4(char *buf TSRMLS_DC) { char *raddr = suhosin_getenv(ZEND_STRL("REMOTE_ADDR") TSRMLS_CC); int i; if (raddr == NULL) { memset(buf, 0, 4); return; } for (i=0; i<4; i++) { if (raddr[0] == 0) { buf[i] = 0; } else { buf[i] = strtol(raddr, &raddr, 10); if (raddr[0] == '.') { raddr++;
int fpm_status_handle_request(TSRMLS_D) /* {{{ */ { struct fpm_scoreboard_s scoreboard, *scoreboard_p; struct fpm_scoreboard_proc_s proc; char *buffer, *time_format, time_buffer[64]; time_t now_epoch; int full, encode; char *short_syntax, *short_post; char *full_pre, *full_syntax, *full_post, *full_separator; zend_string *_GET_str; if (!SG(request_info).request_uri) { return 0; } /* PING */ if (fpm_status_ping_uri && fpm_status_ping_response && !strcmp(fpm_status_ping_uri, SG(request_info).request_uri)) { fpm_request_executing(); sapi_add_header_ex(ZEND_STRL("Content-Type: text/plain"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Expires: Thu, 01 Jan 1970 00:00:00 GMT"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Cache-Control: no-cache, no-store, must-revalidate, max-age=0"), 1, 1 TSRMLS_CC); SG(sapi_headers).http_response_code = 200; /* handle HEAD */ if (SG(request_info).headers_only) { return 1; } PUTS(fpm_status_ping_response); return 1; } /* STATUS */ if (fpm_status_uri && !strcmp(fpm_status_uri, SG(request_info).request_uri)) { fpm_request_executing(); scoreboard_p = fpm_scoreboard_get(); if (!scoreboard_p) { zlog(ZLOG_ERROR, "status: unable to find or access status shared memory"); SG(sapi_headers).http_response_code = 500; sapi_add_header_ex(ZEND_STRL("Content-Type: text/plain"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Expires: Thu, 01 Jan 1970 00:00:00 GMT"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Cache-Control: no-cache, no-store, must-revalidate, max-age=0"), 1, 1 TSRMLS_CC); PUTS("Internal error. Please review log file for errors."); return 1; } if (!fpm_spinlock(&scoreboard_p->lock, 1)) { zlog(ZLOG_NOTICE, "[pool %s] status: scoreboard already in used.", scoreboard_p->pool); SG(sapi_headers).http_response_code = 503; sapi_add_header_ex(ZEND_STRL("Content-Type: text/plain"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Expires: Thu, 01 Jan 1970 00:00:00 GMT"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Cache-Control: no-cache, no-store, must-revalidate, max-age=0"), 1, 1 TSRMLS_CC); PUTS("Server busy. Please try again later."); return 1; } /* copy the scoreboard not to bother other processes */ scoreboard = *scoreboard_p; fpm_unlock(scoreboard_p->lock); if (scoreboard.idle < 0 || scoreboard.active < 0) { zlog(ZLOG_ERROR, "[pool %s] invalid status values", scoreboard.pool); SG(sapi_headers).http_response_code = 500; sapi_add_header_ex(ZEND_STRL("Content-Type: text/plain"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Expires: Thu, 01 Jan 1970 00:00:00 GMT"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Cache-Control: no-cache, no-store, must-revalidate, max-age=0"), 1, 1 TSRMLS_CC); PUTS("Internal error. Please review log file for errors."); return 1; } /* send common headers */ sapi_add_header_ex(ZEND_STRL("Expires: Thu, 01 Jan 1970 00:00:00 GMT"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Cache-Control: no-cache, no-store, must-revalidate, max-age=0"), 1, 1 TSRMLS_CC); SG(sapi_headers).http_response_code = 200; /* handle HEAD */ if (SG(request_info).headers_only) { return 1; } /* full status ? */ _GET_str = zend_string_init("_GET", sizeof("_GET")-1, 0); full = (fpm_php_get_string_from_table(_GET_str, "full" TSRMLS_CC) != NULL); short_syntax = short_post = NULL; full_separator = full_pre = full_syntax = full_post = NULL; encode = 0; /* HTML */ if (fpm_php_get_string_from_table(_GET_str, "html" TSRMLS_CC)) { sapi_add_header_ex(ZEND_STRL("Content-Type: text/html"), 1, 1 TSRMLS_CC); time_format = "%d/%b/%Y:%H:%M:%S %z"; encode = 1; short_syntax = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n" "<head><title>PHP-FPM Status Page</title></head>\n" "<body>\n" "<table>\n" "<tr><th>pool</th><td>%s</td></tr>\n" "<tr><th>process manager</th><td>%s</td></tr>\n" "<tr><th>start time</th><td>%s</td></tr>\n" "<tr><th>start since</th><td>%lu</td></tr>\n" "<tr><th>accepted conn</th><td>%lu</td></tr>\n" #ifdef HAVE_FPM_LQ "<tr><th>listen queue</th><td>%u</td></tr>\n" "<tr><th>max listen queue</th><td>%u</td></tr>\n" "<tr><th>listen queue len</th><td>%d</td></tr>\n" #endif "<tr><th>idle processes</th><td>%d</td></tr>\n" "<tr><th>active processes</th><td>%d</td></tr>\n" "<tr><th>total processes</th><td>%d</td></tr>\n" "<tr><th>max active processes</th><td>%d</td></tr>\n" "<tr><th>max children reached</th><td>%u</td></tr>\n" "<tr><th>slow requests</th><td>%lu</td></tr>\n" "</table>\n"; if (!full) { short_post = "</body></html>"; } else { full_pre = "<table border=\"1\">\n" "<tr>" "<th>pid</th>" "<th>state</th>" "<th>start time</th>" "<th>start since</th>" "<th>requests</th>" "<th>request duration</th>" "<th>request method</th>" "<th>request uri</th>" "<th>content length</th>" "<th>user</th>" "<th>script</th>" #ifdef HAVE_FPM_LQ "<th>last request cpu</th>" #endif "<th>last request memory</th>" "</tr>\n"; full_syntax = "<tr>" "<td>%d</td>" "<td>%s</td>" "<td>%s</td>" "<td>%lu</td>" "<td>%lu</td>" "<td>%lu</td>" "<td>%s</td>" "<td>%s%s%s</td>" "<td>%zu</td>" "<td>%s</td>" "<td>%s</td>" #ifdef HAVE_FPM_LQ "<td>%.2f</td>" #endif "<td>%zu</td>" "</tr>\n"; full_post = "</table></body></html>"; } /* XML */ } else if (fpm_php_get_string_from_table(_GET_str, "xml" TSRMLS_CC)) { sapi_add_header_ex(ZEND_STRL("Content-Type: text/xml"), 1, 1 TSRMLS_CC); time_format = "%s"; encode = 1; short_syntax = "<?xml version=\"1.0\" ?>\n" "<status>\n" "<pool>%s</pool>\n" "<process-manager>%s</process-manager>\n" "<start-time>%s</start-time>\n" "<start-since>%lu</start-since>\n" "<accepted-conn>%lu</accepted-conn>\n" #ifdef HAVE_FPM_LQ "<listen-queue>%u</listen-queue>\n" "<max-listen-queue>%u</max-listen-queue>\n" "<listen-queue-len>%d</listen-queue-len>\n" #endif "<idle-processes>%d</idle-processes>\n" "<active-processes>%d</active-processes>\n" "<total-processes>%d</total-processes>\n" "<max-active-processes>%d</max-active-processes>\n" "<max-children-reached>%u</max-children-reached>\n" "<slow-requests>%lu</slow-requests>\n"; if (!full) { short_post = "</status>"; } else { full_pre = "<processes>\n"; full_syntax = "<process>" "<pid>%d</pid>" "<state>%s</state>" "<start-time>%s</start-time>" "<start-since>%lu</start-since>" "<requests>%lu</requests>" "<request-duration>%lu</request-duration>" "<request-method>%s</request-method>" "<request-uri>%s%s%s</request-uri>" "<content-length>%zu</content-length>" "<user>%s</user>" "<script>%s</script>" #ifdef HAVE_FPM_LQ "<last-request-cpu>%.2f</last-request-cpu>" #endif "<last-request-memory>%zu</last-request-memory>" "</process>\n" ; full_post = "</processes>\n</status>"; } /* JSON */ } else if (fpm_php_get_string_from_table(_GET_str, "json" TSRMLS_CC)) { sapi_add_header_ex(ZEND_STRL("Content-Type: application/json"), 1, 1 TSRMLS_CC); time_format = "%s"; short_syntax = "{" "\"pool\":\"%s\"," "\"process manager\":\"%s\"," "\"start time\":%s," "\"start since\":%lu," "\"accepted conn\":%lu," #ifdef HAVE_FPM_LQ "\"listen queue\":%u," "\"max listen queue\":%u," "\"listen queue len\":%d," #endif "\"idle processes\":%d," "\"active processes\":%d," "\"total processes\":%d," "\"max active processes\":%d," "\"max children reached\":%u," "\"slow requests\":%lu"; if (!full) { short_post = "}"; } else { full_separator = ","; full_pre = ", \"processes\":["; full_syntax = "{" "\"pid\":%d," "\"state\":\"%s\"," "\"start time\":%s," "\"start since\":%lu," "\"requests\":%lu," "\"request duration\":%lu," "\"request method\":\"%s\"," "\"request uri\":\"%s%s%s\"," "\"content length\":%zu," "\"user\":\"%s\"," "\"script\":\"%s\"," #ifdef HAVE_FPM_LQ "\"last request cpu\":%.2f," #endif "\"last request memory\":%zu" "}"; full_post = "]}"; } /* TEXT */ } else { sapi_add_header_ex(ZEND_STRL("Content-Type: text/plain"), 1, 1 TSRMLS_CC); time_format = "%d/%b/%Y:%H:%M:%S %z"; short_syntax = "pool: %s\n" "process manager: %s\n" "start time: %s\n" "start since: %lu\n" "accepted conn: %lu\n" #ifdef HAVE_FPM_LQ "listen queue: %u\n" "max listen queue: %u\n" "listen queue len: %d\n" #endif "idle processes: %d\n" "active processes: %d\n" "total processes: %d\n" "max active processes: %d\n" "max children reached: %u\n" "slow requests: %lu\n"; if (full) { full_syntax = "\n" "************************\n" "pid: %d\n" "state: %s\n" "start time: %s\n" "start since: %lu\n" "requests: %lu\n" "request duration: %lu\n" "request method: %s\n" "request URI: %s%s%s\n" "content length: %zu\n" "user: %s\n" "script: %s\n" #ifdef HAVE_FPM_LQ "last request cpu: %.2f\n" #endif "last request memory: %zu\n"; } } strftime(time_buffer, sizeof(time_buffer) - 1, time_format, localtime(&scoreboard.start_epoch)); now_epoch = time(NULL); spprintf(&buffer, 0, short_syntax, scoreboard.pool, PM2STR(scoreboard.pm), time_buffer, now_epoch - scoreboard.start_epoch, scoreboard.requests, #ifdef HAVE_FPM_LQ scoreboard.lq, scoreboard.lq_max, scoreboard.lq_len, #endif scoreboard.idle, scoreboard.active, scoreboard.idle + scoreboard.active, scoreboard.active_max, scoreboard.max_children_reached, scoreboard.slow_rq); PUTS(buffer); efree(buffer); zend_string_release(_GET_str); if (short_post) { PUTS(short_post); } /* no need to test the var 'full' */ if (full_syntax) { int i, first; zend_string *tmp_query_string; char *query_string; struct timeval duration, now; #ifdef HAVE_FPM_LQ float cpu; #endif fpm_clock_get(&now); if (full_pre) { PUTS(full_pre); } first = 1; for (i=0; i<scoreboard_p->nprocs; i++) { if (!scoreboard_p->procs[i] || !scoreboard_p->procs[i]->used) { continue; } proc = *scoreboard_p->procs[i]; if (first) { first = 0; } else { if (full_separator) { PUTS(full_separator); } } query_string = NULL; tmp_query_string = NULL; if (proc.query_string[0] != '\0') { if (!encode) { query_string = proc.query_string; } else { tmp_query_string = php_escape_html_entities_ex((unsigned char *)proc.query_string, strlen(proc.query_string), 1, ENT_HTML_IGNORE_ERRORS & ENT_COMPAT, NULL, 1 TSRMLS_CC); query_string = tmp_query_string->val; } } #ifdef HAVE_FPM_LQ /* prevent NaN */ if (proc.cpu_duration.tv_sec == 0 && proc.cpu_duration.tv_usec == 0) { cpu = 0.; } else { cpu = (proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cutime + proc.last_request_cpu.tms_cstime) / fpm_scoreboard_get_tick() / (proc.cpu_duration.tv_sec + proc.cpu_duration.tv_usec / 1000000.) * 100.; } #endif if (proc.request_stage == FPM_REQUEST_ACCEPTING) { duration = proc.duration; } else { timersub(&now, &proc.accepted, &duration); } strftime(time_buffer, sizeof(time_buffer) - 1, time_format, localtime(&proc.start_epoch)); spprintf(&buffer, 0, full_syntax, proc.pid, fpm_request_get_stage_name(proc.request_stage), time_buffer, now_epoch - proc.start_epoch, proc.requests, duration.tv_sec * 1000000UL + duration.tv_usec, proc.request_method[0] != '\0' ? proc.request_method : "-", proc.request_uri[0] != '\0' ? proc.request_uri : "-", query_string ? "?" : "", query_string ? query_string : "", proc.content_length, proc.auth_user[0] != '\0' ? proc.auth_user : "******", proc.script_filename[0] != '\0' ? proc.script_filename : "-", #ifdef HAVE_FPM_LQ proc.request_stage == FPM_REQUEST_ACCEPTING ? cpu : 0., #endif proc.request_stage == FPM_REQUEST_ACCEPTING ? proc.memory : 0); PUTS(buffer); efree(buffer); if (tmp_query_string) { zend_string_free(tmp_query_string); } } if (full_post) { PUTS(full_post); } } return 1; } return 0; }
PHP_METHOD(swoole_lock, __construct) { long type = SW_MUTEX; char *filelock; int filelock_len = 0; int ret; #ifdef ZTS if(sw_thread_ctx == NULL) { TSRMLS_SET_CTX(sw_thread_ctx); } #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &type, &filelock, &filelock_len) == FAILURE) { RETURN_FALSE; } swLock *lock = SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swLock)); if (lock == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "alloc failed."); RETURN_FALSE; } switch(type) { case SW_RWLOCK: ret = swRWLock_create(lock, 1); break; case SW_FILELOCK: if (filelock_len <= 0) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "filelock require lock file name."); RETURN_FALSE; } int fd; if ((fd = open(filelock, O_RDWR | O_CREAT, 0666)) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "open file[%s] failed. Error: %s [%d]", filelock, strerror(errno), errno); RETURN_FALSE; } ret = swFileLock_create(lock, fd); break; case SW_SEM: ret = swSem_create(lock, IPC_PRIVATE, 1); break; #ifdef HAVE_SPINLOCK case SW_SPINLOCK: ret = swSpinLock_create(lock, 1); break; #endif case SW_MUTEX: default: ret = swMutex_create(lock, 1); break; } if (ret < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "create lock failed"); RETURN_FALSE; } zval *zres; MAKE_STD_ZVAL(zres); ZEND_REGISTER_RESOURCE(zres, lock, le_swoole_lock); zend_update_property(swoole_lock_class_entry_ptr, getThis(), ZEND_STRL("_lock"), zres TSRMLS_CC); zval_ptr_dtor(&zres); RETURN_TRUE; }
return 0; } /* }}} */ /** {{{ int yaf_response_http_send(yaf_response_t *response TSRMLS_DC) */ int yaf_response_http_send(yaf_response_t *response TSRMLS_DC) { zval *zresponse_code, *zheader, *zbody; zval **val, **entry; char *header_name; uint header_name_len; ulong num_key; HashPosition pos; sapi_header_line ctr = {0}; zresponse_code = zend_read_property(yaf_response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_RESPONSECODE), 1 TSRMLS_CC); SG(sapi_headers).http_response_code = Z_LVAL_P(zresponse_code); zheader = zend_read_property(yaf_response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_HEADER), 1 TSRMLS_CC); for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(zheader), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(zheader), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(zheader), &pos)) { if (zend_hash_get_current_key_ex(Z_ARRVAL_P(zheader), &header_name, &header_name_len, &num_key, 0, &pos) == HASH_KEY_IS_STRING) { ctr.line_len = spprintf(&(ctr.line), 0, "%s: %s", header_name, Z_STRVAL_PP(entry)); } else { ctr.line_len = spprintf(&(ctr.line), 0, "%lu: %s", num_key, Z_STRVAL_PP(entry)); } ctr.response_code = 0; if (sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC) != SUCCESS) {
PHP_METHOD(air_mysql_waiter, step_0) { AIR_INIT_THIS; zval *services = zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("_services"), 0 TSRMLS_CC); zval *responses = zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("_responses"), 0 TSRMLS_CC); zval *context = zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("_context"), 0 TSRMLS_CC); zend_class_entry *mysqli_ce = air_get_ce(ZEND_STRL("mysqli") TSRMLS_CC); zval *async; MAKE_STD_ZVAL(async); ZVAL_LONG(async, MYSQLI_ASYNC); zval *wait_pool, *m2s; MAKE_STD_ZVAL(wait_pool); array_init(wait_pool); MAKE_STD_ZVAL(m2s); array_init(m2s); zval *service; ulong idx; uint _idx, key_len; char *key; zval *mysqli = NULL; HashTable *ah = Z_ARRVAL_P(services); for(zend_hash_internal_pointer_reset(ah); zend_hash_has_more_elements(ah) == SUCCESS;){ zval **___tmp; if (zend_hash_get_current_data(ah, (void**)&___tmp) == FAILURE) { continue; } if(zend_hash_get_current_key_ex(ah, &key, &key_len, &idx, 0, NULL) != HASH_KEY_IS_STRING) { key = NULL; key_len = 0; } service = *___tmp; if(Z_TYPE_P(service) == IS_NULL){ zend_hash_index_del(ah, idx); continue; } zval *service_id = zend_read_property(air_async_service_ce, service, ZEND_STRL("_id"), 1 TSRMLS_CC); zval *mysql = zend_read_property(air_async_service_ce, service, ZEND_STRL("_request"), 1 TSRMLS_CC); zval *status = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_status"), 0 TSRMLS_CC); if(Z_LVAL_P(status)){ //ignore if the mysql's been executed zend_hash_index_del(ah, idx); continue; } zval *mysql_config = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_config"), 1 TSRMLS_CC); zval *mode = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_mode"), 1 TSRMLS_CC); if(Z_TYPE_P(mode) == IS_NULL){ air_mysql_auto_mode(mysql TSRMLS_CC); mode = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_mode"), 1 TSRMLS_CC); } zval **acquire_params[2] = {&mysql_config, &mode}; mysqli = NULL; air_call_static_method(air_mysql_keeper_ce, "acquire", &mysqli, 2, acquire_params); if(Z_TYPE_P(mysqli) != IS_NULL){ zval **build_params[1] = {&mysqli}; zval *sql = NULL; air_call_method(&mysql, air_mysql_ce, NULL, ZEND_STRL("build"), &sql, 1, build_params TSRMLS_CC); if(sql){ zval **query_params[2] = {&sql, &async}; air_call_method(&mysqli, mysqli_ce, NULL, ZEND_STRL("query"), NULL, 2, query_params TSRMLS_CC); add_next_index_zval(wait_pool, mysqli); Z_ADDREF_P(service_id); add_index_zval(m2s, air_mysqli_get_id(mysqli TSRMLS_CC), service_id); zval_ptr_dtor(&sql); }else{ //should not happen php_error(E_ERROR, "sql not found"); zval_ptr_dtor(&mysqli); } }else{ zval_ptr_dtor(&mysqli); } zend_hash_move_forward(ah); } zval_ptr_dtor(&async); add_assoc_zval(context, "pool", wait_pool); add_assoc_zval(context, "m2s", m2s); add_assoc_long(context, "waited", zend_hash_num_elements(Z_ARRVAL_P(wait_pool))); add_assoc_long(context, "processed", 0); add_assoc_long(context, "step", 1); }
static int swoole_mysql_onRead(swReactor *reactor, swEvent *event) { #if PHP_MAJOR_VERSION < 7 TSRMLS_FETCH_FROM_CTX(sw_thread_ctx ? sw_thread_ctx : NULL); #endif mysql_client *client = event->socket->object; int sock = event->fd; zval *zobject = client->object; swString *buffer = client->buffer; int ret; zval **args[2]; zval *callback = NULL; zval *retval = NULL; zval *result = NULL; while(1) { ret = recv(sock, buffer->str + buffer->length, buffer->size - buffer->length, 0); if (ret < 0) { if (errno == EINTR) { continue; } else { switch (swConnection_error(errno)) { case SW_ERROR: swSysError("Read from socket[%d] failed.", event->fd); return SW_ERR; case SW_CLOSE: goto close_fd; case SW_WAIT: goto parse_response; default: return SW_ERR; } } } else if (ret == 0) { close_fd: if (client->state == SW_MYSQL_STATE_READ_END) { goto parse_response; } sw_zend_call_method_with_0_params(&zobject, swoole_mysql_class_entry_ptr, NULL, "close", &retval); if (retval) { sw_zval_ptr_dtor(&retval); } if (client->callback) { args[0] = &zobject; args[1] = &result; SW_ALLOC_INIT_ZVAL(result); ZVAL_BOOL(result, 0); callback = client->callback; if (sw_call_user_function_ex(EG(function_table), NULL, callback, &retval, 2, args, 0, NULL TSRMLS_CC) != SUCCESS) { swoole_php_fatal_error(E_WARNING, "swoole_async_mysql callback[2] handler error."); } if (result) { sw_zval_ptr_dtor(&result); } sw_zval_ptr_dtor(&callback); client->callback = NULL; client->state = SW_MYSQL_STATE_QUERY; if (retval) { sw_zval_ptr_dtor(&retval); } } return SW_OK; } else { buffer->length += ret; //recv again if (buffer->length == buffer->size) { if (swString_extend(buffer, buffer->size * 2) < 0) { swoole_php_fatal_error(E_ERROR, "malloc failed."); reactor->del(SwooleG.main_reactor, event->fd); } continue; } parse_response: if (mysql_response(client) < 0) { return SW_OK; } //remove from eventloop reactor->del(reactor, event->fd); zend_update_property_long(swoole_mysql_class_entry_ptr, zobject, ZEND_STRL("affected_rows"), client->response.affected_rows TSRMLS_CC); zend_update_property_long(swoole_mysql_class_entry_ptr, zobject, ZEND_STRL("insert_id"), client->response.insert_id TSRMLS_CC); client->state = SW_MYSQL_STATE_QUERY; args[0] = &zobject; //OK if (client->response.response_type == 0) { SW_ALLOC_INIT_ZVAL(result); ZVAL_BOOL(result, 1); } //ERROR else if (client->response.response_type == 255) { SW_ALLOC_INIT_ZVAL(result); ZVAL_BOOL(result, 0); zend_update_property_string(swoole_mysql_class_entry_ptr, zobject, ZEND_STRL("error"), client->response.server_msg TSRMLS_CC); zend_update_property_long(swoole_mysql_class_entry_ptr, zobject, ZEND_STRL("errno"), client->response.error_code TSRMLS_CC); } //ResultSet else { result = client->response.result_array; } args[1] = &result; callback = client->callback; if (sw_call_user_function_ex(EG(function_table), NULL, callback, &retval, 2, args, 0, NULL TSRMLS_CC) != SUCCESS) { swoole_php_fatal_error(E_WARNING, "swoole_async_mysql callback[2] handler error."); reactor->del(SwooleG.main_reactor, event->fd); } /* free memory */ if (retval) { sw_zval_ptr_dtor(&retval); } if (result) { sw_zval_ptr_dtor(&result); #if PHP_MAJOR_VERSION > 5 efree(result); #endif } //free callback object sw_zval_ptr_dtor(&callback); //clear buffer swString_clear(client->buffer); if (client->response.columns) { efree(client->response.columns); } if (client->object) { sw_zval_ptr_dtor(&client->object); } #if PHP_MAJOR_VERSION > 5 if (client->response.result_array) { efree(client->response.result_array); } #endif bzero(&client->response, sizeof(client->response)); return SW_OK; } } return SW_OK; }
static PHP_METHOD(swoole_mysql, __construct) { if (!mysql_request_buffer) { mysql_request_buffer = swString_new(SW_MYSQL_QUERY_INIT_SIZE); if (!mysql_request_buffer) { swoole_php_fatal_error(E_ERROR, "[1] swString_new(%d) failed.", SW_HTTP_RESPONSE_INIT_SIZE); RETURN_FALSE; } } char *unixsocket = NULL; zend_size_t unixsocket_len = 0; mysql_connector connector; connector.port = SW_MYSQL_DEFAULT_PORT; if (zend_parse_parameters(ZEND_NUM_ARGS()TSRMLS_CC, "ssss|ls", &connector.host, &connector.host_len, &connector.user, &connector.user_len, &connector.password, &connector.password_len, &connector.database, &connector.database_len, &connector.port, &unixsocket, &unixsocket_len) == FAILURE) { RETURN_FALSE; } swClient *cli = emalloc(sizeof(swClient)); int type = SW_SOCK_TCP; if (unixsocket) { type = SW_SOCK_UNIX_STREAM; connector.host = unixsocket; connector.host_len = unixsocket_len; } if (swClient_create(cli, type, 0) < 0) { zend_throw_exception(swoole_mysql_exception_class_entry, "swClient_create failed.", 1 TSRMLS_CC); RETURN_FALSE; } if (cli->connect(cli, connector.host, connector.port, SW_MYSQL_CONNECT_TIMEOUT, 0) < 0) { zend_throw_exception(swoole_mysql_exception_class_entry, "connect to mysql server[%s:%d] failed.", 2 TSRMLS_CC); RETURN_FALSE; } int tcp_nodelay = 1; if (setsockopt(cli->socket->fd, IPPROTO_TCP, TCP_NODELAY, (const void *) &tcp_nodelay, sizeof(int)) == -1) { swoole_php_sys_error(E_WARNING, "setsockopt(%d, IPPROTO_TCP, TCP_NODELAY) failed.", cli->socket->fd); } char buf[2048]; int n = cli->recv(cli, buf, sizeof(buf), 0); if (n < 0) { zend_throw_exception(swoole_mysql_exception_class_entry, "recvfrom mysql server failed.", 3 TSRMLS_CC); RETURN_FALSE; } if (mysql_handshake(&connector, buf, n) == SW_ERR) { zend_throw_exception(swoole_mysql_exception_class_entry, "handshake with mysql server failed.", 4 TSRMLS_CC); RETURN_FALSE; } if (cli->send(cli, connector.buf, connector.packet_length + 4, 0) < 0) { zend_throw_exception(swoole_mysql_exception_class_entry, "sendto mysql server failed.", 5 TSRMLS_CC); RETURN_FALSE; } if (cli->recv(cli, buf, sizeof(buf), 0) < 0) { zend_throw_exception(swoole_mysql_exception_class_entry, "recvfrom mysql server failed.", 6 TSRMLS_CC); RETURN_FALSE; } mysql_client *client = emalloc(sizeof(mysql_client)); bzero(client, sizeof(mysql_client)); client->buffer = swString_new(SW_BUFFER_SIZE_BIG); client->fd = cli->socket->fd; client->object = getThis(); client->cli = cli; sw_copy_to_stack(client->object, client->_object); zend_update_property_bool(swoole_mysql_class_entry_ptr, getThis(), ZEND_STRL("connected"), 1 TSRMLS_CC); swoole_set_object(getThis(), client); php_swoole_check_reactor(); swSetNonBlock(cli->socket->fd); if (!isset_event_callback) { SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_MYSQL | SW_EVENT_READ, swoole_mysql_onRead); SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_MYSQL | SW_EVENT_ERROR, swoole_mysql_onError); } swConnection *socket = swReactor_get(SwooleG.main_reactor, cli->socket->fd); socket->active = 1; socket->object = client; }
static PHP_METHOD(swoole_mysql, query) { zval *callback; swString sql; bzero(&sql, sizeof(sql)); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &sql.str, &sql.length, &callback) == FAILURE) { return; } if (sql.length <= 0) { swoole_php_fatal_error(E_WARNING, "Query is empty."); RETURN_FALSE; } mysql_client *client = swoole_get_object(getThis()); if (!client) { swoole_php_fatal_error(E_WARNING, "object is not instanceof swoole_mysql."); RETURN_FALSE; } if (!client->cli) { swoole_php_fatal_error(E_WARNING, "mysql connection#%d is closed.", client->fd); RETURN_FALSE; } if (client->state != SW_MYSQL_STATE_QUERY) { swoole_php_fatal_error(E_WARNING, "mysql client is waiting response, cannot send new sql query."); RETURN_FALSE; } client->callback = callback; sw_copy_to_stack(client->callback, client->_callback); sw_zval_add_ref(&client->callback); sw_zval_add_ref(&client->object); swString_clear(mysql_request_buffer); if (mysql_request(&sql, mysql_request_buffer) < 0) { RETURN_FALSE; } //add to eventloop if (SwooleG.main_reactor->add(SwooleG.main_reactor, client->fd, PHP_SWOOLE_FD_MYSQL | SW_EVENT_READ) < 0) { swoole_php_fatal_error(E_WARNING, "swoole_event_add failed."); RETURN_FALSE; } //send query if (SwooleG.main_reactor->write(SwooleG.main_reactor, client->fd, mysql_request_buffer->str, mysql_request_buffer->length) < 0) { //connection is closed if (swConnection_error(errno) == SW_CLOSE) { zend_update_property_bool(swoole_mysql_class_entry_ptr, getThis(), ZEND_STRL("connected"), 0 TSRMLS_CC); zend_update_property_bool(swoole_mysql_class_entry_ptr, getThis(), ZEND_STRL("errno"), 2006 TSRMLS_CC); } RETURN_FALSE; } else { client->state = SW_MYSQL_STATE_READ_START; RETURN_TRUE; } }
static int http_request_on_header_value(php_http_parser *parser, const char *at, size_t length) { TSRMLS_FETCH_FROM_CTX(sw_thread_ctx ? sw_thread_ctx : NULL); http_client *client = parser->data; char *header_name = zend_str_tolower_dup(client->current_header_name, client->current_header_name_len); if (memcmp(header_name, ZEND_STRL("cookie")) == 0) { zval *cookie; MAKE_STD_ZVAL(cookie); array_init(cookie); zend_update_property(swoole_http_request_class_entry_ptr, client->zrequest, ZEND_STRL("cookie"), cookie TSRMLS_CC); struct { char *k; int klen; char *v; int vlen; } kv = { 0 }; char keybuf[SW_HTTP_COOKIE_KEYLEN]; char *_c = (char *) at; int n = 1; kv.k = _c; while (_c < at + length) { if (*_c == '=') { kv.v = _c + 1; kv.klen = n; n = 0; } else if (*_c == ';') { kv.vlen = n; if (kv.klen >= SW_HTTP_COOKIE_KEYLEN) { kv.klen = SW_HTTP_COOKIE_KEYLEN - 1; } memcpy(keybuf, kv.k, kv.klen - 1); keybuf[kv.klen - 1] = 0; add_assoc_stringl_ex(cookie, keybuf, kv.klen, kv.v, kv.vlen, 1); kv.k = _c + 2; n = 0; } else { n++; } _c++; } kv.vlen = n; if (kv.klen >= SW_HTTP_COOKIE_KEYLEN) { kv.klen = SW_HTTP_COOKIE_KEYLEN - 1; } memcpy(keybuf, kv.k, kv.klen - 1); keybuf[kv.klen - 1] = 0; add_assoc_stringl_ex(cookie, keybuf, kv.klen , kv.v, kv.vlen, 1); // ZEND_SET_SYMBOL(&EG(symbol_table), "_COOKIE", cookie); mergeGlobal(cookie, client->zrequest, HTTP_GLOBAL_COOKIE); } else if (memcmp(header_name, ZEND_STRL("upgrade")) == 0 && memcmp(at, ZEND_STRL("websocket")) == 0) { SwooleG.lock.lock(&SwooleG.lock); swConnection *conn = swServer_connection_get(SwooleG.serv, client->fd); if(conn->websocket_status == 0) { conn->websocket_status = WEBSOCKET_STATUS_CONNECTION; } SwooleG.lock.unlock(&SwooleG.lock); zval *header = zend_read_property(swoole_http_request_class_entry_ptr, client->zrequest, ZEND_STRL("header"), 1 TSRMLS_CC); add_assoc_stringl_ex(header, header_name, client->current_header_name_len + 1, (char *) at, length, 1); } else if (parser->method == PHP_HTTP_POST && memcmp(header_name, ZEND_STRL("content-type")) == 0 && memcmp(at, ZEND_STRL("application/x-www-form-urlencoded")) == 0) { client->request.post_form_urlencoded = 1; zval *header = zend_read_property(swoole_http_request_class_entry_ptr, client->zrequest, ZEND_STRL("header"), 1 TSRMLS_CC); add_assoc_stringl_ex(header, header_name, client->current_header_name_len + 1, (char *) at, length, 1); } else { zval *header = zend_read_property(swoole_http_request_class_entry_ptr, client->zrequest, ZEND_STRL("header"), 1 TSRMLS_CC); add_assoc_stringl_ex(header, header_name, client->current_header_name_len + 1, (char *) at, length, 1); } if (client->current_header_name_allocated) { efree(client->current_header_name); client->current_header_name_allocated = 0; } efree(header_name); return 0; }
/** {{{ zend_string * yaf_route_map_assemble(zval *info, zval *query) */ zend_string * yaf_route_map_assemble(yaf_route_t *this_ptr, zval *info, zval *query) { char *seg, *ptrptr, *pname; smart_str uri = {0}; size_t seg_len; zend_bool has_delim = 0; zval *delim, *ctl_prefer, *zv; ctl_prefer = zend_read_property(yaf_route_map_ce, this_ptr, ZEND_STRL(YAF_ROUTE_MAP_VAR_NAME_CTL_PREFER), 1, NULL); delim = zend_read_property(yaf_route_map_ce, this_ptr, ZEND_STRL(YAF_ROUTE_MAP_VAR_NAME_DELIMETER), 1, NULL); if (IS_STRING == Z_TYPE_P(delim) && Z_STRLEN_P(delim)) { has_delim = 1; } do { if (Z_TYPE_P(ctl_prefer) == IS_TRUE) { if ((zv = zend_hash_str_find(Z_ARRVAL_P(info), ZEND_STRL(YAF_ROUTE_ASSEMBLE_ACTION_FORMAT))) != NULL && Z_TYPE_P(zv) == IS_STRING) { pname = estrndup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); } else { yaf_trigger_error(YAF_ERR_TYPE_ERROR, "%s", "Undefined the 'action' parameter for the 1st parameter"); break; } } else { if ((zv = zend_hash_str_find(Z_ARRVAL_P(info), ZEND_STRL(YAF_ROUTE_ASSEMBLE_CONTROLLER_FORMAT))) != NULL && Z_TYPE_P(zv) == IS_STRING) { pname = estrndup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); } else { yaf_trigger_error(YAF_ERR_TYPE_ERROR, "%s", "Undefined the 'controller' parameter for the 1st parameter"); break; } } seg = php_strtok_r(pname, "_", &ptrptr); while (seg) { seg_len = strlen(seg); if (seg_len) { smart_str_appendc(&uri, '/'); smart_str_appendl(&uri, seg, seg_len); } seg = php_strtok_r(NULL, "_", &ptrptr); } efree(pname); if (query && IS_ARRAY == Z_TYPE_P(query)) { zend_bool start = 1; zend_string *key, *val; if (has_delim) { smart_str_appendc(&uri, '/'); smart_str_appendl(&uri, Z_STRVAL_P(delim), Z_STRLEN_P(delim)); } ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(query), key, zv) { if (key) { val = zval_get_string(zv); if (has_delim) { smart_str_appendc(&uri, '/'); smart_str_appendl(&uri, ZSTR_VAL(key), ZSTR_LEN(key)); smart_str_appendc(&uri, '/'); smart_str_appendl(&uri, ZSTR_VAL(val), ZSTR_LEN(val)); } else { if (start) { smart_str_appendc(&uri, '?'); smart_str_appendl(&uri, ZSTR_VAL(key), ZSTR_LEN(key)); smart_str_appendc(&uri, '='); smart_str_appendl(&uri, ZSTR_VAL(val), ZSTR_LEN(val)); start = 0; } else { smart_str_appendc(&uri, '&'); smart_str_appendl(&uri, ZSTR_VAL(key), ZSTR_LEN(key)); smart_str_appendc(&uri, '='); smart_str_appendl(&uri, ZSTR_VAL(val), ZSTR_LEN(val)); } } zend_string_release(val); } } ZEND_HASH_FOREACH_END(); } smart_str_0(&uri); return uri.s; } while (0);
static int http_onReceive(swFactory *factory, swEventData *req) { TSRMLS_FETCH_FROM_CTX(sw_thread_ctx ? sw_thread_ctx : NULL); int fd = req->info.fd; // swTrace("on receive:%s pid:%d\n", zdata, getpid()); swConnection *conn = swServer_connection_get(SwooleG.serv, fd); if(conn->websocket_status == WEBSOCKET_STATUS_HANDSHAKE) //websocket callback { zval *zdata = php_swoole_get_data(req TSRMLS_CC); swTrace("on message callback\n"); char *buf = Z_STRVAL_P(zdata); long fin = buf[0] ? 1 : 0; long opcode = buf[1] ? 1 : 0; buf+=2; zval *zresponse; MAKE_STD_ZVAL(zresponse); object_init_ex(zresponse, swoole_http_wsresponse_class_entry_ptr); //socket fd zend_update_property_long(swoole_http_wsresponse_class_entry_ptr, zresponse, ZEND_STRL("fd"), fd TSRMLS_CC); zend_update_property_long(swoole_http_wsresponse_class_entry_ptr, zresponse, ZEND_STRL("fin"), fin TSRMLS_CC); zend_update_property_long(swoole_http_wsresponse_class_entry_ptr, zresponse, ZEND_STRL("opcode"), opcode TSRMLS_CC); zend_update_property_stringl(swoole_http_wsresponse_class_entry_ptr, zresponse, ZEND_STRL("data"), buf, (Z_STRLEN_P(zdata)-2) TSRMLS_CC); zval **args[1]; args[0] = &zresponse; zval *retval; if (call_user_function_ex(EG(function_table), NULL, php_sw_http_server_callbacks[1], &retval, 1, args, 0, NULL TSRMLS_CC) == FAILURE) { zval_ptr_dtor(&zdata); php_error_docref(NULL TSRMLS_CC, E_WARNING, "onMessage handler error"); } swTrace("===== message callback end======"); if (EG(exception)) { zval_ptr_dtor(&zdata); zend_exception_error(EG(exception), E_ERROR TSRMLS_CC); } if (retval) { zval_ptr_dtor(&retval); } zval_ptr_dtor(&zdata); return SW_OK; } http_client *client = swHashMap_find_int(php_sw_http_clients, fd); if (!client) { client = http_client_new(fd TSRMLS_CC); } php_http_parser *parser = &client->parser; /** * create request and response object */ http_request_new(client TSRMLS_CC); parser->data = client; php_http_parser_init(parser, PHP_HTTP_REQUEST); zval *zdata = php_swoole_get_data(req TSRMLS_CC); //server info zval *_request; MAKE_STD_ZVAL(_request); array_init(_request); zend_update_property(swoole_http_request_class_entry_ptr, client->zrequest, ZEND_STRL("request"), _request TSRMLS_CC); size_t n = php_http_parser_execute(parser, &http_parser_settings, Z_STRVAL_P(zdata), Z_STRLEN_P(zdata)); zval_ptr_dtor(&zdata); if (n < 0) { swWarn("php_http_parser_execute failed."); if(conn->websocket_status == WEBSOCKET_STATUS_CONNECTION) { SwooleG.serv->factory.end(&SwooleG.serv->factory, fd); } } else { if(conn->websocket_status == WEBSOCKET_STATUS_CONNECTION) // need handshake { if(php_sw_http_server_callbacks[2] == NULL) { int ret = websocket_handshake(client); http_request_free(client TSRMLS_CC); if (ret == SW_ERR) { swTrace("websocket handshake error\n"); SwooleG.serv->factory.end(&SwooleG.serv->factory, fd); } else { handshake_success(fd); swTrace("websocket handshake_success\n"); return SW_OK; } return ret; } } zval *retval; zval **args[2]; zval *zrequest = client->zrequest; //server info zval *zserver; MAKE_STD_ZVAL(zserver); array_init(zserver); zend_update_property(swoole_http_request_class_entry_ptr, zrequest, ZEND_STRL("server"), zserver TSRMLS_CC); switch (parser->method) { case PHP_HTTP_GET: add_assoc_string(zserver, "REQUEST_METHOD", "GET", 1);break; case PHP_HTTP_POST: add_assoc_string(zserver, "REQUEST_METHOD", "POST", 1);break; case PHP_HTTP_HEAD: add_assoc_string(zserver, "REQUEST_METHOD", "HEAD", 1);break; case PHP_HTTP_PUT: add_assoc_string(zserver, "REQUEST_METHOD", "PUT", 1);break; case PHP_HTTP_DELETE: add_assoc_string(zserver, "REQUEST_METHOD", "DELETE", 1);break; case PHP_HTTP_PATCH: add_assoc_string(zserver, "REQUEST_METHOD", "PATCH", 1);break; /* pathological */ case PHP_HTTP_CONNECT: add_assoc_string(zserver, "REQUEST_METHOD", "CONNECT", 1);break; case PHP_HTTP_OPTIONS: add_assoc_string(zserver, "REQUEST_METHOD", "OPTIONS", 1);break; case PHP_HTTP_TRACE: add_assoc_string(zserver, "REQUEST_METHOD", "TRACE", 1);break; /* webdav */ case PHP_HTTP_COPY: add_assoc_string(zserver, "REQUEST_METHOD", "COPY", 1);break; case PHP_HTTP_LOCK: add_assoc_string(zserver, "REQUEST_METHOD", "LOCK", 1);break; case PHP_HTTP_MKCOL: add_assoc_string(zserver, "REQUEST_METHOD", "MKCOL", 1);break; case PHP_HTTP_MOVE: add_assoc_string(zserver, "REQUEST_METHOD", "MOVE", 1);break; case PHP_HTTP_PROPFIND: add_assoc_string(zserver, "REQUEST_METHOD", "PROPFIND", 1);break; case PHP_HTTP_PROPPATCH: add_assoc_string(zserver, "REQUEST_METHOD", "PROPPATCH", 1);break; case PHP_HTTP_UNLOCK: add_assoc_string(zserver, "REQUEST_METHOD", "UNLOCK", 1);break; /* subversion */ case PHP_HTTP_REPORT: add_assoc_string(zserver, "REQUEST_METHOD", "REPORT", 1);break; case PHP_HTTP_MKACTIVITY: add_assoc_string(zserver, "REQUEST_METHOD", "MKACTIVITY", 1);break; case PHP_HTTP_CHECKOUT: add_assoc_string(zserver, "REQUEST_METHOD", "CHECKOUT", 1);break; case PHP_HTTP_MERGE: add_assoc_string(zserver, "REQUEST_METHOD", "MERGE", 1);break; /* upnp */ case PHP_HTTP_MSEARCH: add_assoc_string(zserver, "REQUEST_METHOD", "MSEARCH", 1);break; case PHP_HTTP_NOTIFY: add_assoc_string(zserver, "REQUEST_METHOD", "NOTIFY", 1);break; case PHP_HTTP_SUBSCRIBE: add_assoc_string(zserver, "REQUEST_METHOD", "SUBSCRIBE", 1);break; case PHP_HTTP_UNSUBSCRIBE: add_assoc_string(zserver, "REQUEST_METHOD", "UNSUBSCRIBE", 1);break; case PHP_HTTP_NOT_IMPLEMENTED: add_assoc_string(zserver, "REQUEST_METHOD", "GET", 1);break; } // if (parser->method == PHP_HTTP_POST) // { // add_assoc_string(zserver, "REQUEST_METHOD", "POST", 1); // } // else // { // add_assoc_string(zserver, "REQUEST_METHOD", "GET", 1); // } add_assoc_stringl(zserver, "REQUEST_URI", client->request.path, client->request.path_len, 1); add_assoc_stringl(zserver, "PATH_INFO", client->request.path, client->request.path_len, 1); add_assoc_long_ex(zserver, ZEND_STRS("REQUEST_TIME"), SwooleGS->now); swConnection *conn = swServer_connection_get(SwooleG.serv, fd); add_assoc_long(zserver, "SERVER_PORT", SwooleG.serv->connection_list[conn->from_fd].addr.sin_port); add_assoc_long(zserver, "REMOTE_PORT", ntohs(conn->addr.sin_port)); add_assoc_string(zserver, "REMOTE_ADDR", inet_ntoa(conn->addr.sin_addr), 1); if (client->request.version == 101) { add_assoc_string(zserver, "SERVER_PROTOCOL", "HTTP/1.1", 1); } else { add_assoc_string(zserver, "SERVER_PROTOCOL", "HTTP/1.0", 1); } add_assoc_string(zserver, "SERVER_SOFTWARE", SW_HTTP_SERVER_SOFTWARE, 1); add_assoc_string(zserver, "GATEWAY_INTERFACE", SW_HTTP_SERVER_SOFTWARE, 1); // ZEND_SET_SYMBOL(&EG(symbol_table), "_SERVER", zserver); zval *zresponse; MAKE_STD_ZVAL(zresponse); object_init_ex(zresponse, swoole_http_response_class_entry_ptr); //socket fd zend_update_property_long(swoole_http_response_class_entry_ptr, zresponse, ZEND_STRL("fd"), client->fd TSRMLS_CC); client->zresponse = zresponse; args[0] = &zrequest; args[1] = &zresponse; int called = 0; if(conn->websocket_status == WEBSOCKET_STATUS_CONNECTION) { called = 2; } if (call_user_function_ex(EG(function_table), NULL, php_sw_http_server_callbacks[called], &retval, 2, args, 0, NULL TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "onRequest handler error"); } if (EG(exception)) { zend_exception_error(EG(exception), E_ERROR TSRMLS_CC); } if (retval) { zval_ptr_dtor(&retval); } swTrace("======call end======\n"); if(called == 2) { handshake_success(fd); } } return SW_OK; }
/** {{{ int yaf_route_map_route(yaf_route_t *route, yaf_request_t *request) */ int yaf_route_map_route(yaf_route_t *route, yaf_request_t *request) { zval *ctl_prefer, *delimer, *zuri, *base_uri, params; char *req_uri, *tmp, *rest, *ptrptr, *seg; char *query_str = NULL; uint seg_len = 0; smart_str route_result = {0}; zuri = zend_read_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_URI), 1, NULL); base_uri = zend_read_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_BASE), 1, NULL); ctl_prefer = zend_read_property(yaf_route_map_ce, route, ZEND_STRL(YAF_ROUTE_MAP_VAR_NAME_CTL_PREFER), 1, NULL); delimer = zend_read_property(yaf_route_map_ce, route, ZEND_STRL(YAF_ROUTE_MAP_VAR_NAME_DELIMETER), 1, NULL); if (base_uri && IS_STRING == Z_TYPE_P(base_uri) && !strncasecmp(Z_STRVAL_P(zuri), Z_STRVAL_P(base_uri), Z_STRLEN_P(base_uri))) { req_uri = estrdup(Z_STRVAL_P(zuri) + Z_STRLEN_P(base_uri)); } else { req_uri = estrdup(Z_STRVAL_P(zuri)); } if (Z_TYPE_P(delimer) == IS_STRING && Z_STRLEN_P(delimer)) { if ((query_str = strstr(req_uri, Z_STRVAL_P(delimer))) != NULL && *(query_str - 1) == '/') { tmp = req_uri; rest = query_str + Z_STRLEN_P(delimer); if (*rest == '\0') { req_uri = estrndup(req_uri, query_str - req_uri); query_str = NULL; efree(tmp); } else if (*rest == '/') { req_uri = estrndup(req_uri, query_str - req_uri); query_str = estrdup(rest); efree(tmp); } else { query_str = NULL; } } else { query_str = NULL; } } seg = php_strtok_r(req_uri, YAF_ROUTER_URL_DELIMIETER, &ptrptr); while (seg) { seg_len = strlen(seg); if (seg_len) { smart_str_appendl(&route_result, seg, seg_len); } smart_str_appendc(&route_result, '_'); seg = php_strtok_r(NULL, YAF_ROUTER_URL_DELIMIETER, &ptrptr); } if (route_result.s) { ZSTR_LEN(route_result.s)--; ZSTR_VAL(route_result.s)[ZSTR_LEN(route_result.s)] = '\0'; if (Z_TYPE_P(ctl_prefer) == IS_TRUE) { zend_update_property_str(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_CONTROLLER), route_result.s); } else { zend_update_property_str(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_ACTION), route_result.s); } smart_str_free(&route_result); } if (query_str) { (void)yaf_router_parse_parameters(query_str, ¶ms); (void)yaf_request_set_params_multi(request, ¶ms); zval_ptr_dtor(¶ms); efree(query_str); } efree(req_uri); return 1; }
static int yaf_route_pathinfo_route(yaf_request_t *request, char *req_uri, int req_uri_len TSRMLS_DC) /* {{{ */ { zval *params; char *module = NULL, *controller = NULL, *action = NULL, *rest = NULL; do { #define strip_slashs(p) while (*p == ' ' || *p == '/') { ++p; } char *s, *p; char *uri; if (req_uri_len == 0 || (req_uri_len == 1 && *req_uri == '/')) { break; } uri = req_uri; s = p = uri; if (req_uri_len) { char *q = req_uri + req_uri_len - 1; while (q > req_uri && (*q == ' ' || *q == '/')) { *q-- = '\0'; } } strip_slashs(p); if ((s = strstr(p, "/")) != NULL) { if (yaf_application_is_module_name(p, s-p TSRMLS_CC)) { module = estrndup(p, s - p); p = s + 1; strip_slashs(p); if ((s = strstr(p, "/")) != NULL) { controller = estrndup(p, s - p); p = s + 1; } } else { controller = estrndup(p, s - p); p = s + 1; } } strip_slashs(p); if ((s = strstr(p, "/")) != NULL) { action = estrndup(p, s - p); p = s + 1; } strip_slashs(p); if (*p != '\0') { do { if (!module && !controller && !action) { if (yaf_application_is_module_name(p, strlen(p) TSRMLS_CC)) { module = estrdup(p); break; } } if (!controller) { controller = estrdup(p); break; } if (!action) { action = estrdup(p); break; } rest = estrdup(p); } while (0); } if (module && controller == NULL) { controller = module; module = NULL; } else if (module && action == NULL) { action = controller; controller = module; module = NULL; } else if (controller && action == NULL ) { /* /controller */ if (YAF_G(action_prefer)) { action = controller; controller = NULL; } } } while (0); if (module != NULL) { zend_update_property_string(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_MODULE), module TSRMLS_CC); efree(module); } if (controller != NULL) { zend_update_property_string(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_CONTROLLER), controller TSRMLS_CC); efree(controller); } if (action != NULL) { zend_update_property_string(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_ACTION), action TSRMLS_CC); efree(action); } if (rest) { params = yaf_router_parse_parameters(rest TSRMLS_CC); (void)yaf_request_set_params_multi(request, params TSRMLS_CC); zval_ptr_dtor(¶ms); efree(rest); } return 1; }
/** {{{ public ZeActiveString::toString($separator) */ PHP_METHOD(ze_activestring, toString) { zval * self = NULL; zval * items = NULL; zval * actives = NULL; char * sep = NULL; int sep_len = 0; smart_str sstr = {NULL, 0, 0}; HashTable * items_table = NULL; HashPosition items_pointer = NULL; HashTable * actives_table = NULL; char * key = NULL; uint key_len = 0; ulong idx = 0; zval ** val = NULL; char * str = NULL; int str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s" , &sep, &sep_len ) == FAILURE) { WRONG_PARAM_COUNT; } self = getThis(); items = zend_read_property(ze_activestring_ce, self, ZEND_STRL(ZE_ITEMS) , 0 TSRMLS_CC); actives = zend_read_property(ze_activestring_ce, self, ZEND_STRL(ZE_ACTIVES), 0 TSRMLS_CC); do { if (!items || Z_TYPE_P(items) != IS_ARRAY) { ZE_PTR_DTOR(items); ze_error(E_ERROR TSRMLS_CC, "recorder.toString.items.not_array"); break; } if (!actives || Z_TYPE_P(actives) != IS_ARRAY) { ZE_PTR_DTOR(actives); ze_error(E_ERROR TSRMLS_CC, "recorder.toString.actives.not_array"); break; } items_table = Z_ARRVAL_P(items); actives_table = Z_ARRVAL_P(actives); for (zend_hash_internal_pointer_reset_ex(items_table, &items_pointer); zend_hash_get_current_key_ex(items_table, &key, &key_len, &idx, 0, &items_pointer) == HASH_KEY_IS_STRING; zend_hash_move_forward_ex(items_table, &items_pointer)) { if (!key || !key_len) { continue; } if (zend_hash_exists(actives_table, key, key_len )) { if (zend_hash_get_current_data_ex(items_table , (void**) &val, &items_pointer) == SUCCESS) { smart_str_appendl(&sstr, Z_STRVAL_PP(val), Z_STRLEN_PP(val)); if (sep_len) { smart_str_appendl(&sstr, sep, sep_len); } } } } smart_str_0(&sstr); } while(0); if (sstr.len) { str_len = sstr.len - sep_len; spprintf(&str, str_len, "%s", sstr.c); smart_str_free(&sstr); RETURN_STRING(str , 0); }else{ smart_str_free(&sstr); RETURN_EMPTY_STRING(); } }
break; default: zval_copy_ctor(value); Z_TYPE_P(value) = Z_TYPE_PP(p); } INIT_PZVAL(value); *p = value; } /* }}} */ /** {{{ zval * yaf_config_ini_format(yaf_config_t *instance, zval **ppzval TSRMLS_DC) */ zval * yaf_config_ini_format(yaf_config_t *instance, zval **ppzval TSRMLS_DC) { zval *readonly, *ret; readonly = zend_read_property(yaf_config_ini_ce, instance, ZEND_STRL(YAF_CONFIG_PROPERT_NAME_READONLY), 1 TSRMLS_CC); ret = yaf_config_ini_instance(NULL, *ppzval, NULL TSRMLS_CC); return ret; } /* }}} */ #if ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION > 2)) /** {{{ static void yaf_config_ini_simple_parser_cb(zval *key, zval *value, zval *index, int callback_type, zval *arr TSRMLS_DC) */ static void yaf_config_ini_simple_parser_cb(zval *key, zval *value, zval *index, int callback_type, zval *arr TSRMLS_DC) { zval *element; switch (callback_type) { case ZEND_INI_PARSER_ENTRY: { char *skey, *seg, *ptr; zval **ppzval, *dst;
ZEND_BEGIN_ARG_INFO_EX(yaf_controller_display_arginfo, 0, 0, 1) ZEND_ARG_INFO(0, tpl) ZEND_ARG_ARRAY_INFO(0, parameters, 1) ZEND_END_ARG_INFO() /* }}} */ /** {{{ zval * yaf_controller_render(yaf_controller_t *instance, char *action_name, int len, zval *var_array TSRMLS_DC) */ zval * yaf_controller_render(yaf_controller_t *instance, char *action_name, int len, zval *var_array TSRMLS_DC) { char *path, *view_ext, *self_name, *tmp; zval *name, *param, *ret = NULL; int path_len; yaf_view_t *view; zend_class_entry *view_ce; view = zend_read_property(yaf_controller_ce, instance, ZEND_STRL(YAF_CONTROLLER_PROPERTY_NAME_VIEW), 0 TSRMLS_CC); name = zend_read_property(yaf_controller_ce, instance, ZEND_STRL(YAF_CONTROLLER_PROPERTY_NAME_NAME), 0 TSRMLS_CC); view_ext = YAF_G(view_ext); self_name = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); tmp = self_name; while (*tmp != '\0') { if (*tmp == '_') { *tmp = DEFAULT_SLASH; } tmp++; } action_name = estrndup(action_name, len);
ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(yaf_dispatcher_setaction_arginfo, 0, 0, 1) ZEND_ARG_INFO(0, action) ZEND_END_ARG_INFO() /* }}} */ /** {{{ yaf_dispatcher_t * yaf_dispatcher_instance(zval *this_ptr TSRMLS_DC) */ yaf_dispatcher_t * yaf_dispatcher_instance(yaf_dispatcher_t *this_ptr TSRMLS_DC) { zval *plugins; yaf_router_t *router; yaf_dispatcher_t *instance; instance = zend_read_static_property(yaf_dispatcher_ce, ZEND_STRL(YAF_DISPATCHER_PROPERTY_NAME_INSTANCE), 1 TSRMLS_CC); if (IS_OBJECT == Z_TYPE_P(instance) && instanceof_function(Z_OBJCE_P(instance), yaf_dispatcher_ce TSRMLS_CC)) { return instance; } if (this_ptr) { instance = this_ptr; return this_ptr; } else { instance = NULL; MAKE_STD_ZVAL(instance); object_init_ex(instance, yaf_dispatcher_ce); }
* limitations under the License. */ #include "molten_status.h" /* {{{ check status */ void mo_request_handle(mo_ctrl_t *mrt TSRMLS_DC) { /* request for status */ if (SG(request_info).request_uri != NULL && SG(request_info).request_method != NULL && strstr(SG(request_info).request_uri, STATUS_URI) != NULL) { /* GET report status */ if (strncmp(SG(request_info).request_method, "GET", sizeof("GET") - 1) == 0) { php_output_start_default(TSRMLS_C); sapi_add_header_ex(ZEND_STRL("Expires: Thu, 01 Jan 1970 00:00:00 GMT"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Cache-Control: no-cache, no-store, must-revalidate, max-age=0"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Content-Type: text/plain"), 1, 1 TSRMLS_CC); SG(sapi_headers).http_response_code = 200; char *buf; mo_ctrl_serialize_msg(mrt, &buf); php_output_write(buf, strlen(buf) TSRMLS_CC); efree(buf); php_output_end_all(TSRMLS_C); /* disable output after */ php_output_set_status(PHP_OUTPUT_DISABLED TSRMLS_C); } /* POST update ctrl info */ if (strncmp(SG(request_info).request_method, "POST", sizeof("POST") - 1) == 0) {
/** {{{ proto public Yaf_Action_Abstract::getController(void) */ PHP_METHOD(yaf_action, getController) { yaf_controller_t *controller = zend_read_property(yaf_action_ce, getThis(), ZEND_STRL(YAF_ACTION_PROPERTY_NAME_CTRL), 1, NULL); RETURN_ZVAL(controller, 1, 0); }
client->fd = fd; swHashMap_add_int(php_sw_http_clients, fd, client, NULL); return client; } static int http_request_new(http_client* client TSRMLS_DC) { zval *zrequest; MAKE_STD_ZVAL(zrequest); object_init_ex(zrequest, swoole_http_request_class_entry_ptr); //http header zval *header; MAKE_STD_ZVAL(header); array_init(header); zend_update_property(swoole_http_request_class_entry_ptr, zrequest, ZEND_STRL("header"), header TSRMLS_CC); client->zrequest = zrequest; client->end = 0; zend_update_property_long(swoole_http_request_class_entry_ptr, zrequest, ZEND_STRL("fd"), client->fd TSRMLS_CC); bzero(&client->request, sizeof(client->request)); bzero(&client->response, sizeof(client->response)); return SW_OK; } static void http_request_free(http_client *client TSRMLS_DC) { http_request *req = &client->request;
PHPDBG_API int phpdbg_consume_bytes(int sock, char *ptr, int len, int tmo) { int got_now, i = len, j; char *p = ptr; #ifndef PHP_WIN32 struct pollfd pfd; if (tmo < 0) goto recv_once; pfd.fd = sock; pfd.events = POLLIN; j = poll(&pfd, 1, tmo); if (j == 0) { #else struct fd_set readfds; struct timeval ttmo; if (tmo < 0) goto recv_once; FD_ZERO(&readfds); FD_SET(sock, &readfds); ttmo.tv_sec = 0; ttmo.tv_usec = tmo*1000; j = select(0, &readfds, NULL, NULL, &ttmo); if (j <= 0) { #endif return -1; } recv_once: while(i > 0) { if (tmo < 0) { /* There's something to read. Read what's available and proceed disregarding whether len could be exhausted or not.*/ int can_read = recv(sock, p, i, MSG_PEEK); #ifndef _WIN32 if (can_read == -1 && errno == EINTR) { continue; } #endif i = can_read; } #ifdef _WIN32 got_now = recv(sock, p, i, 0); #else do { got_now = recv(sock, p, i, 0); } while (got_now == -1 && errno == EINTR); #endif if (got_now == -1) { zend_quiet_write(PHPDBG_G(io)[PHPDBG_STDERR].fd, ZEND_STRL("Read operation timed out!\n")); return -1; } i -= got_now; p += got_now; } return p - ptr; } PHPDBG_API int phpdbg_send_bytes(int sock, const char *ptr, int len) { int sent, i = len; const char *p = ptr; /* XXX poll/select needed here? */ while(i > 0) { sent = send(sock, p, i, 0); if (sent == -1) { return -1; } i -= sent; p += sent; } return len; }
static void mergeGlobal(zval * val, zval *zrequest, int type) { TSRMLS_FETCH_FROM_CTX(sw_thread_ctx ? sw_thread_ctx : NULL); zval *http_server; MAKE_STD_ZVAL(http_server); object_init_ex(http_server, swoole_http_server_class_entry_ptr); zval *http_request_ptr = zend_read_property(swoole_http_server_class_entry_ptr, http_server, ZEND_STRL("request"), 1 TSRMLS_CC); int http_request = Z_LVAL_P(http_request_ptr); switch (type) { case HTTP_GLOBAL_GET: ZEND_SET_SYMBOL(&EG(symbol_table), "_GET", val); break; case HTTP_GLOBAL_POST: ZEND_SET_SYMBOL(&EG(symbol_table), "_POST", val); break; case HTTP_GLOBAL_COOKIE: ZEND_SET_SYMBOL(&EG(symbol_table), "_COOKIE", val); break; } if(http_request & type) { zval *_request = zend_read_property(swoole_http_request_class_entry_ptr, zrequest, ZEND_STRL("request"), 1 TSRMLS_CC); zend_hash_copy(Z_ARRVAL_P(_request), Z_ARRVAL_P(val), NULL, NULL, sizeof(zval)); } }
static int do_cli(int argc, char **argv) /* {{{ */ { int c; zend_file_handle file_handle; int behavior = PHP_MODE_STANDARD; char *reflection_what = NULL; volatile int request_started = 0; volatile int exit_status = 0; char *php_optarg = NULL, *orig_optarg = NULL; int php_optind = 1, orig_optind = 1; char *exec_direct=NULL, *exec_run=NULL, *exec_begin=NULL, *exec_end=NULL; char *arg_free=NULL, **arg_excp=&arg_free; char *script_file=NULL, *translated_path = NULL; int interactive=0; int lineno = 0; const char *param_error=NULL; int hide_argv = 0; zend_try { CG(in_compilation) = 0; /* not initialized but needed for several options */ while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) { switch (c) { case 'i': /* php info & quit */ if (php_request_startup()==FAILURE) { goto err; } request_started = 1; php_print_info(0xFFFFFFFF); php_output_end_all(); exit_status = (c == '?' && argc > 1 && !strchr(argv[1], c)); goto out; case 'v': /* show php version & quit */ php_printf("PHP %s (%s) (built: %s %s) ( %s)\nCopyright (c) 1997-2017 The PHP Group\n%s", PHP_VERSION, cli_sapi_module.name, __DATE__, __TIME__, #if ZTS "ZTS " #else "NTS " #endif #ifdef COMPILER COMPILER " " #endif #ifdef ARCHITECTURE ARCHITECTURE " " #endif #if ZEND_DEBUG "DEBUG " #endif #ifdef HAVE_GCOV "GCOV " #endif , get_zend_version() ); sapi_deactivate(); goto out; case 'm': /* list compiled in modules */ if (php_request_startup()==FAILURE) { goto err; } request_started = 1; php_printf("[PHP Modules]\n"); print_modules(); php_printf("\n[Zend Modules]\n"); print_extensions(); php_printf("\n"); php_output_end_all(); exit_status=0; goto out; default: break; } } /* Set some CLI defaults */ SG(options) |= SAPI_OPTION_NO_CHDIR; php_optind = orig_optind; php_optarg = orig_optarg; while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) { switch (c) { case 'a': /* interactive mode */ if (!interactive) { if (behavior != PHP_MODE_STANDARD) { param_error = param_mode_conflict; break; } interactive=1; } break; case 'C': /* don't chdir to the script directory */ /* This is default so NOP */ break; case 'F': if (behavior == PHP_MODE_PROCESS_STDIN) { if (exec_run || script_file) { param_error = "You can use -R or -F only once.\n"; break; } } else if (behavior != PHP_MODE_STANDARD) { param_error = param_mode_conflict; break; } behavior=PHP_MODE_PROCESS_STDIN; script_file = php_optarg; break; case 'f': /* parse file */ if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) { param_error = param_mode_conflict; break; } else if (script_file) { param_error = "You can use -f only once.\n"; break; } script_file = php_optarg; break; case 'l': /* syntax check mode */ if (behavior != PHP_MODE_STANDARD) { break; } behavior=PHP_MODE_LINT; break; case 'q': /* do not generate HTTP headers */ /* This is default so NOP */ break; case 'r': /* run code from command line */ if (behavior == PHP_MODE_CLI_DIRECT) { if (exec_direct || script_file) { param_error = "You can use -r only once.\n"; break; } } else if (behavior != PHP_MODE_STANDARD || interactive) { param_error = param_mode_conflict; break; } behavior=PHP_MODE_CLI_DIRECT; exec_direct=php_optarg; break; case 'R': if (behavior == PHP_MODE_PROCESS_STDIN) { if (exec_run || script_file) { param_error = "You can use -R or -F only once.\n"; break; } } else if (behavior != PHP_MODE_STANDARD) { param_error = param_mode_conflict; break; } behavior=PHP_MODE_PROCESS_STDIN; exec_run=php_optarg; break; case 'B': if (behavior == PHP_MODE_PROCESS_STDIN) { if (exec_begin) { param_error = "You can use -B only once.\n"; break; } } else if (behavior != PHP_MODE_STANDARD || interactive) { param_error = param_mode_conflict; break; } behavior=PHP_MODE_PROCESS_STDIN; exec_begin=php_optarg; break; case 'E': if (behavior == PHP_MODE_PROCESS_STDIN) { if (exec_end) { param_error = "You can use -E only once.\n"; break; } } else if (behavior != PHP_MODE_STANDARD || interactive) { param_error = param_mode_conflict; break; } behavior=PHP_MODE_PROCESS_STDIN; exec_end=php_optarg; break; case 's': /* generate highlighted HTML from source */ if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) { param_error = "Source highlighting only works for files.\n"; break; } behavior=PHP_MODE_HIGHLIGHT; break; case 'w': if (behavior == PHP_MODE_CLI_DIRECT || behavior == PHP_MODE_PROCESS_STDIN) { param_error = "Source stripping only works for files.\n"; break; } behavior=PHP_MODE_STRIP; break; case 'z': /* load extension file */ zend_load_extension(php_optarg); break; case 'H': hide_argv = 1; break; case 10: behavior=PHP_MODE_REFLECTION_FUNCTION; reflection_what = php_optarg; break; case 11: behavior=PHP_MODE_REFLECTION_CLASS; reflection_what = php_optarg; break; case 12: behavior=PHP_MODE_REFLECTION_EXTENSION; reflection_what = php_optarg; break; case 13: behavior=PHP_MODE_REFLECTION_ZEND_EXTENSION; reflection_what = php_optarg; break; case 14: behavior=PHP_MODE_REFLECTION_EXT_INFO; reflection_what = php_optarg; break; case 15: behavior = PHP_MODE_SHOW_INI_CONFIG; break; default: break; } } if (param_error) { PUTS(param_error); exit_status=1; goto err; } #if defined(PHP_WIN32) && !defined(PHP_CLI_WIN32_NO_CONSOLE) && (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE) if (!interactive) { /* The -a option was not passed. If there is no file, it could still make sense to run interactively. The presense of a file is essential to mitigate buggy console info. */ interactive = php_win32_console_is_own() && !(script_file || argc > php_optind && behavior!=PHP_MODE_CLI_DIRECT && behavior!=PHP_MODE_PROCESS_STDIN && strcmp(argv[php_optind-1],"--") ); } #endif if (interactive) { #if (HAVE_LIBREADLINE || HAVE_LIBEDIT) && !defined(COMPILE_DL_READLINE) printf("Interactive shell\n\n"); #else printf("Interactive mode enabled\n\n"); #endif fflush(stdout); } /* only set script_file if not set already and not in direct mode and not at end of parameter list */ if (argc > php_optind && !script_file && behavior!=PHP_MODE_CLI_DIRECT && behavior!=PHP_MODE_PROCESS_STDIN && strcmp(argv[php_optind-1],"--")) { script_file=argv[php_optind]; php_optind++; } if (script_file) { if (cli_seek_file_begin(&file_handle, script_file, &lineno) != SUCCESS) { goto err; } else { char real_path[MAXPATHLEN]; if (VCWD_REALPATH(script_file, real_path)) { translated_path = strdup(real_path); } script_filename = script_file; } } else { /* We could handle PHP_MODE_PROCESS_STDIN in a different manner */ /* here but this would make things only more complicated. And it */ /* is consitent with the way -R works where the stdin file handle*/ /* is also accessible. */ file_handle.filename = "Standard input code"; file_handle.handle.fp = stdin; } file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; php_self = (char*)file_handle.filename; /* before registering argv to module exchange the *new* argv[0] */ /* we can achieve this without allocating more memory */ SG(request_info).argc=argc-php_optind+1; arg_excp = argv+php_optind-1; arg_free = argv[php_optind-1]; SG(request_info).path_translated = translated_path? translated_path: (char*)file_handle.filename; argv[php_optind-1] = (char*)file_handle.filename; SG(request_info).argv=argv+php_optind-1; if (php_request_startup()==FAILURE) { *arg_excp = arg_free; fclose(file_handle.handle.fp); PUTS("Could not startup.\n"); goto err; } request_started = 1; CG(start_lineno) = lineno; *arg_excp = arg_free; /* reconstuct argv */ if (hide_argv) { int i; for (i = 1; i < argc; i++) { memset(argv[i], 0, strlen(argv[i])); } } zend_is_auto_global_str(ZEND_STRL("_SERVER")); PG(during_request_startup) = 0; switch (behavior) { case PHP_MODE_STANDARD: if (strcmp(file_handle.filename, "Standard input code")) { cli_register_file_handles(); } if (interactive && cli_shell_callbacks.cli_shell_run) { exit_status = cli_shell_callbacks.cli_shell_run(); } else { php_execute_script(&file_handle); exit_status = EG(exit_status); } break; case PHP_MODE_LINT: exit_status = php_lint_script(&file_handle); if (exit_status==SUCCESS) { zend_printf("No syntax errors detected in %s\n", file_handle.filename); } else { zend_printf("Errors parsing %s\n", file_handle.filename); } break; case PHP_MODE_STRIP: if (open_file_for_scanning(&file_handle)==SUCCESS) { zend_strip(); } goto out; break; case PHP_MODE_HIGHLIGHT: { zend_syntax_highlighter_ini syntax_highlighter_ini; if (open_file_for_scanning(&file_handle)==SUCCESS) { php_get_highlight_struct(&syntax_highlighter_ini); zend_highlight(&syntax_highlighter_ini); } goto out; } break; case PHP_MODE_CLI_DIRECT: cli_register_file_handles(); if (zend_eval_string_ex(exec_direct, NULL, "Command line code", 1) == FAILURE) { exit_status=254; } break; case PHP_MODE_PROCESS_STDIN: { char *input; size_t len, index = 0; zval argn, argi; cli_register_file_handles(); if (exec_begin && zend_eval_string_ex(exec_begin, NULL, "Command line begin code", 1) == FAILURE) { exit_status=254; } while (exit_status == SUCCESS && (input=php_stream_gets(s_in_process, NULL, 0)) != NULL) { len = strlen(input); while (len > 0 && len-- && (input[len]=='\n' || input[len]=='\r')) { input[len] = '\0'; } ZVAL_STRINGL(&argn, input, len + 1); zend_hash_str_update(&EG(symbol_table), "argn", sizeof("argn")-1, &argn); ZVAL_LONG(&argi, ++index); zend_hash_str_update(&EG(symbol_table), "argi", sizeof("argi")-1, &argi); if (exec_run) { if (zend_eval_string_ex(exec_run, NULL, "Command line run code", 1) == FAILURE) { exit_status=254; } } else { if (script_file) { if (cli_seek_file_begin(&file_handle, script_file, &lineno) != SUCCESS) { exit_status = 1; } else { CG(start_lineno) = lineno; php_execute_script(&file_handle); exit_status = EG(exit_status); } } } efree(input); } if (exec_end && zend_eval_string_ex(exec_end, NULL, "Command line end code", 1) == FAILURE) { exit_status=254; } break; } case PHP_MODE_REFLECTION_FUNCTION: case PHP_MODE_REFLECTION_CLASS: case PHP_MODE_REFLECTION_EXTENSION: case PHP_MODE_REFLECTION_ZEND_EXTENSION: { zend_class_entry *pce = NULL; zval arg, ref; zend_execute_data execute_data; switch (behavior) { default: break; case PHP_MODE_REFLECTION_FUNCTION: if (strstr(reflection_what, "::")) { pce = reflection_method_ptr; } else { pce = reflection_function_ptr; } break; case PHP_MODE_REFLECTION_CLASS: pce = reflection_class_ptr; break; case PHP_MODE_REFLECTION_EXTENSION: pce = reflection_extension_ptr; break; case PHP_MODE_REFLECTION_ZEND_EXTENSION: pce = reflection_zend_extension_ptr; break; } ZVAL_STRING(&arg, reflection_what); object_init_ex(&ref, pce); memset(&execute_data, 0, sizeof(zend_execute_data)); EG(current_execute_data) = &execute_data; zend_call_method_with_1_params(&ref, pce, &pce->constructor, "__construct", NULL, &arg); if (EG(exception)) { zval tmp, *msg, rv; ZVAL_OBJ(&tmp, EG(exception)); msg = zend_read_property(zend_ce_exception, &tmp, "message", sizeof("message")-1, 0, &rv); zend_printf("Exception: %s\n", Z_STRVAL_P(msg)); zval_ptr_dtor(&tmp); EG(exception) = NULL; } else { zend_call_method_with_1_params(NULL, reflection_ptr, NULL, "export", NULL, &ref); } zval_ptr_dtor(&ref); zval_ptr_dtor(&arg); break; } case PHP_MODE_REFLECTION_EXT_INFO: { size_t len = strlen(reflection_what); char *lcname = zend_str_tolower_dup(reflection_what, len); zend_module_entry *module; if ((module = zend_hash_str_find_ptr(&module_registry, lcname, len)) == NULL) { if (!strcmp(reflection_what, "main")) { display_ini_entries(NULL); } else { zend_printf("Extension '%s' not present.\n", reflection_what); exit_status = 1; } } else { php_info_print_module(module); } efree(lcname); break; } case PHP_MODE_SHOW_INI_CONFIG: { zend_printf("Configuration File (php.ini) Path: %s\n", PHP_CONFIG_FILE_PATH); zend_printf("Loaded Configuration File: %s\n", php_ini_opened_path ? php_ini_opened_path : "(none)"); zend_printf("Scan for additional .ini files in: %s\n", php_ini_scanned_path ? php_ini_scanned_path : "(none)"); zend_printf("Additional .ini files parsed: %s\n", php_ini_scanned_files ? php_ini_scanned_files : "(none)"); break; } } } zend_end_try(); out: if (request_started) { php_request_shutdown((void *) 0); } if (translated_path) { free(translated_path); } if (exit_status == 0) { exit_status = EG(exit_status); } return exit_status; err: sapi_deactivate(); zend_ini_deactivate(); exit_status = 1; goto out; }
static php_stream_filter *http_filter_create(const char *name, zval *params, int p) #endif { zval *tmp = params; php_stream_filter *f = NULL; int flags = p ? PHP_HTTP_ENCODING_STREAM_PERSISTENT : 0; if (params) { switch (Z_TYPE_P(params)) { case IS_ARRAY: case IS_OBJECT: if (!(tmp = zend_hash_str_find_ind(HASH_OF(params), ZEND_STRL("flags")))) { break; } /* no break */ default: flags |= zval_get_long(tmp) & 0x0fffffff; break; } } if (!strcasecmp(name, "http.chunked_decode")) { PHP_HTTP_FILTER_BUFFER(chunked_decode) *b = NULL; if ((b = pecalloc(1, sizeof(PHP_HTTP_FILTER_BUFFER(chunked_decode)), p))) { php_http_buffer_init_ex(PHP_HTTP_BUFFER(b), 4096, p ? PHP_HTTP_BUFFER_INIT_PERSISTENT : 0); if (!(f = php_stream_filter_alloc(&PHP_HTTP_FILTER_OP(chunked_decode), b, p))) { pefree(b, p); } } } else if (!strcasecmp(name, "http.chunked_encode")) { f = php_stream_filter_alloc(&PHP_HTTP_FILTER_OP(chunked_encode), NULL, p); } else if (!strcasecmp(name, "http.inflate")) { PHP_HTTP_FILTER_BUFFER(stream) *b = NULL; if ((b = php_http_encoding_stream_init(NULL, php_http_encoding_stream_get_inflate_ops(), flags))) { if (!(f = php_stream_filter_alloc(&PHP_HTTP_FILTER_OP(inflate), b, p))) { php_http_encoding_stream_free(&b); } } } else if (!strcasecmp(name, "http.deflate")) { PHP_HTTP_FILTER_BUFFER(stream) *b = NULL; if ((b = php_http_encoding_stream_init(NULL, php_http_encoding_stream_get_deflate_ops(), flags))) { if (!(f = php_stream_filter_alloc(&PHP_HTTP_FILTER_OP(deflate), b, p))) { php_http_encoding_stream_free(&b); } } #if PHP_HTTP_HAVE_LIBBROTLI } else if (!strcasecmp(name, "http.brotli_encode")) { PHP_HTTP_FILTER_BUFFER(stream) *b = NULL; if ((b = php_http_encoding_stream_init(NULL, php_http_encoding_stream_get_enbrotli_ops(), flags))) { if (!(f = php_stream_filter_alloc(&PHP_HTTP_FILTER_OP(brotli_encode), b, p))) { php_http_encoding_stream_free(&b); } } } else if (!strcasecmp(name, "http.brotli_decode")) { PHP_HTTP_FILTER_BUFFER(stream) *b = NULL; if ((b = php_http_encoding_stream_init(NULL, php_http_encoding_stream_get_debrotli_ops(), flags))) { if (!(f = php_stream_filter_alloc(&PHP_HTTP_FILTER_OP(brotli_decode), b, p))) { php_http_encoding_stream_free(&b); } } #endif } return f; }