sapi:server application programming interface 服务器端应用编程端口。研究过php架构的同学应该知道这个东东的重要性,它提供了一个接口,使得php可以和其他应用进行交互数据。 本文不会详细介绍每个php的sapi,只是针对最简单的cgi sapi,来说明sapi的机制。
我们先来看看php的架构图:
sapi指的是php具体应用的编程接口, 就像pc一样,无论安装哪些操作系统,只要满足了pc的接口规范都可以在pc上正常运行, php脚本要执行有很多种方式,通过web服务器,或者直接在命令行下,也可以嵌入在其他程序中。
通常,我们使用apache或者nginx这类web服务器来测试php脚本,或者在命令行下通过php解释器程序来执行。 脚本执行完后,web服务器应答,浏览器显示应答信息,或者在命令行标准输出上显示内容。
我们很少关心php解释器在哪里。虽然通过web服务器和命令行程序执行脚本看起来很不一样, 实际上它们的工作流程是一样的。命令行参数传递给php解释器要执行的脚本, 相当于通过url请求一个php页面。脚本执行完成后返回响应结果,只不过命令行的响应结果是显示在终端上。
脚本执行的开始都是以sapi接口实现开始的。只是不同的sapi接口实现会完成他们特定的工作, 例如apache的mod_php sapi实现需要初始化从apache获取的一些信息,在输出内容是将内容返回给apache, 其他的sapi实现也类似。
sapi提供了一个和外部通信的接口, 对于php5.2,默认提供了很多种sapi, 常见的给apache的mod_php5,cgi,给iis的isapi,还有shell的cli,本文就从cgi sapi入手 ,介绍sapi的机制。 虽然cgi简单,但是不用担心,它包含了绝大部分内容,足以让你深刻理解sapi的工作原理。
要定义个sapi,首先要定义个sapi_module_struct, 查看 php-src/sapi/cgi/cgi_main.c:
*/
static sapi_module_struct cgi_sapi_module = {
#if php_fastcgi
"cgi-fcgi", /* name */
"cgi/fastcgi", /* pretty name */
#else
"cgi", /* name */
"cgi", /* pretty name */
#endif
php_cgi_startup, /* startup */
php_module_shutdown_wrapper, /* shutdown */
null, /* activate */
sapi_cgi_deactivate, /* deactivate */
sapi_cgibin_ub_write, /* unbuffered write */
sapi_cgibin_flush, /* flush */
null, /* get uid */
sapi_cgibin_getenv, /* getenv */
php_error, /* error handler */
null, /* header handler */
sapi_cgi_send_headers, /* send headers handler */
null, /* send header handler */
sapi_cgi_read_post, /* read post data */
sapi_cgi_read_cookies, /* read cookies */
sapi_cgi_register_variables, /* register server variables */
sapi_cgi_log_message, /* log message */
null, /* get request time */
standard_sapi_module_properties
};
这个结构,包含了一些常量,比如name, 这个会在我们调用php_info()的时候被使用。一些初始化,收尾函数,以及一些函数指针,用来告诉zend,如何获取,和输出数据。
1. php_cgi_startup, 当一个应用要调用php的时候,这个函数会被调用,对于cgi来说,它只是简单的调用了php的初始化函数:
static int php_cgi_startup(sapi_module_struct *sapi_module)
{
if (php_module_startup(sapi_module, null, 0) == failure) {
return failure;
}
return success;
}
2. php_module_shutdown_wrapper , 一个对php关闭函数的简单包装。只是简单的调用php_module_shutdown;
3. php会在每个request的时候,处理一些初始化,资源分配的事务。这部分就是activate字段要定义的,从上面的结构我们可以看出,对于cgi来说,它并没有提供初始化处理句柄。对于mod_php5来说,那就不同了,他要在apache的pool中注册资源析构函数, 申请空间, 初始化环境变量,等等。
4. sapi_cgi_deactivate, 这个是对应与activate的函数,顾名思义,它会提供一个handler, 用来处理收尾工作,对于cgi来说,他只是简单的刷新缓冲区,用以保证用户在zend关闭前得到所有的输出数据:
static int sapi_cgi_deactivate(tsrmls_d)
{
/* flush only when sapi was started. the reasons are:
1. sapi deactivate is called from two places: module init and request shutdown
2. when the first call occurs and the request is not set up, flush fails on
fastcgi.
*/
if (sg(sapi_started)) {
sapi_cgibin_flush(sg(server_context));
}
return success;
}
5. sapi_cgibin_ub_write, 这个hanlder告诉了zend,如何输出数据,对于mod_php5来说,这个函数提供了一个向response数据写的接口,而对于cgi来说,只是简单的写到stdout:
static inline size_t sapi_cgibin_single_write(const char *str, uint str_length tsrmls_dc)
{
#ifdef php_write_stdout
long ret;
#else
size_t ret;
#endif
#if php_fastcgi
if (fcgi_is_fastcgi()) {
fcgi_request *request = (fcgi_request*) sg(server_context);
long ret = fcgi_write(request, fcgi_stdout, str, str_length);
if (ret <= 0) {
return 0;
}
return ret;
}
#endif
#ifdef php_write_stdout
ret = write(stdout_fileno, str, str_length);
if (ret <= 0) return 0;
return ret;
#else
ret = fwrite(str, 1, min(str_length, 16384), stdout);
return ret;
#endif
}
static int sapi_cgibin_ub_write(const char *str, uint str_length tsrmls_dc)
{
const char *ptr = str;
uint remaining = str_length;
size_t ret;
while (remaining > 0) {
ret = sapi_cgibin_single_write(ptr, remaining tsrmls_cc);
if (!ret) {
php_handle_aborted_connection();
return str_length - remaining;
}
ptr += ret;
remaining -= ret;
}
return str_length;
}
把真正的写的逻辑剥离出来,就是为了简单实现兼容fastcgi的写方式。
6. sapi_cgibin_flush, 这个是提供给zend的刷新缓存的函数句柄,对于cgi来说,只是简单的调用系统提供的fflush;
7.null, 这部分用来让zend可以验证一个要执行脚本文件的state,从而判断文件是否据有执行权限等等,cgi没有提供。
8. sapi_cgibin_getenv, 为zend提供了一个根据name来查找环境变量的接口,对于mod_php5来说,当我们在脚本中调用getenv的时候,就会间接的调用这个句柄。而对于cgi来说,因为他的运行机制和cli很类似,直接调用父级是shell, 所以,只是简单的调用了系统提供的genenv:
static char *sapi_cgibin_getenv(char *name, size_t name_len tsrmls_dc)
{
#if php_fastcgi
/* when php is started by mod_fastcgi, no regular environment
is provided to php. it is always sent to php at the start
of a request. so we have to do our own lookup to get env
vars. this could probably be faster somehow. */
if (fcgi_is_fastcgi()) {
fcgi_request *request = (fcgi_request*) sg(server_context);
return fcgi_getenv(request, name, name_len);
}
#endif
/* if cgi, or fastcgi and not found in fcgi env
check the regular environment */
return getenv(name);
}
9. php_error, 错误处理函数, 到这里,说几句题外话,上次看到php maillist 提到的使得php的错误处理机制完全oo化, 也就是,改写这个函数句柄,使得每当有错误发生的时候,都throw一个异常。而cgi只是简单的调用了php提供的错误处理函数。
10. 这个函数会在我们调用php的header()函数的时候被调用,对于cgi来说,不提供。
11. sapi_cgi_send_headers, 这个函数会在要真正发送header的时候被调用,一般来说,就是当有任何的输出要发送之前:
static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers tsrmls_dc)
{
char buf[sapi_cgi_max_header_length];
sapi_header_struct *h;
zend_llist_position pos;
if (sg(request_info).no_headers == 1) {
return sapi_header_sent_successfully;
}
if (cgi_nph || sg(sapi_headers).http_response_code != 200)
{
int len;
if (rfc2616_headers && sg(sapi_headers).http_status_line) {
len = snprintf(buf, sapi_cgi_max_header_length,
"%s\r\n", sg(sapi_headers).http_status_line);
if (len > sapi_cgi_max_header_length) {
len = sapi_cgi_max_header_length;
}
} else {
len = sprintf(buf, "status: %d\r\n", sg(sapi_headers).http_response_code);
}
phpwrite_h(buf, len);
}
h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
while (h) {
/* prevent crlfcrlf */
if (h->header_len) {
phpwrite_h(h->header, h->header_len);
phpwrite_h("\r\n", 2);
}
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
}
phpwrite_h("\r\n", 2);
return sapi_header_sent_successfully;
}
12. null, 这个用来单独发送每一个header, cgi没有提供
13. sapi_cgi_read_post, 这个句柄指明了如何获取post的数据,如果做过cgi编程的话,我们就知道cgi是从stdin中读取post data的:
static int sapi_cgi_read_post(char *buffer, uint count_bytes tsrmls_dc)
{
uint read_bytes=0, tmp_read_bytes;
#if php_fastcgi
char *pos = buffer;
#endif
count_bytes = min(count_bytes, (uint) sg(request_info).content_length - sg(read_post_bytes));
while (read_bytes < count_bytes) {
#if php_fastcgi
if (fcgi_is_fastcgi()) {
fcgi_request *request = (fcgi_request*) sg(server_context);
tmp_read_bytes = fcgi_read(request, pos, count_bytes - read_bytes);
pos += tmp_read_bytes;
} else {
tmp_read_bytes = read(0, buffer + read_bytes, count_bytes - read_bytes);
}
#else
tmp_read_bytes = read(0, buffer + read_bytes, count_bytes - read_bytes);
#endif
if (tmp_read_bytes <= 0) {
break;
}
read_bytes += tmp_read_bytes;
}
return read_bytes;
}
14. sapi_cgi_read_cookies, 这个和上面的函数一样,只不过是去获取cookie值:
static char *sapi_cgi_read_cookies(tsrmls_d)
{
return sapi_cgibin_getenv((char *) "http_cookie", sizeof("http_cookie")-1 tsrmls_cc);
}
15. sapi_cgi_register_variables, 这个函数给了一个接口,用以给$_server变量中添加变量,对于cgi来说,注册了一个php_self,这样我们就可以在脚本中访问$_server['php_self']来获取本次的request_uri:
static void sapi_cgi_register_variables(zval *track_vars_array tsrmls_dc)
{
/* in cgi mode, we consider the environment to be a part of the server
* variables
*/
php_import_environment_variables(track_vars_array tsrmls_cc);
/* build the special-case php_self variable for the cgi version */
php_register_variable("php_self", (sg(request_info).request_uri ? sg(request_info).request_uri : ""), track_vars_array tsrmls_cc);
}
16. sapi_cgi_log_message ,用来输出错误信息,对于cgi来说,只是简单的输出到stderr:
static void sapi_cgi_log_message(char *message)
{
#if php_fastcgi
if (fcgi_is_fastcgi() && fcgi_logging) {
fcgi_request *request;
tsrmls_fetch();
request = (fcgi_request*) sg(server_context);
if (request) {
int len = strlen(message);
char *buf = malloc(len+2);
memcpy(buf, message, len);
memcpy(buf + len, "\n", sizeof("\n"));
fcgi_write(request, fcgi_stderr, buf, len+1);
free(buf);
} else {
fprintf(stderr, "%s\n", message);
}
/* ignore return code */
} else
#endif /* php_fastcgi */
fprintf(stderr, "%s\n", message);
}
经过分析,我们已经了解了一个sapi是如何实现的了, 分析过cgi以后,我们也就可以想象mod_php5, embed等sapi的实现机制。