Table of Contents
1. 消息类型
2. 消息头
3. FCGI_BEGIN_REQUEST
4. 名-值对
5. 请求协议
6. 响应协议
Home Backend Development PHP Tutorial Analysis of FastCGI protocol in php source code

Analysis of FastCGI protocol in php source code

Jul 20, 2018 am 10:07 AM
php

这篇文章给大家介绍的内容是关于php源码中FastCGI协议的解析,有着一定的参考价值,有需要的朋友可以参考一下。

FastCGI 是一种协议,它是建立在CGI/1.1基础之上的,把CGI/1.1里面的要传递的数据通过FastCGI协议定义的顺序和格式进行传递。为了更好理解PHP-FPM的工作,下面具体阐述一下FastCGI协议的内容。

1. 消息类型

FastCGI协议分为了10种类型,具体定义如下:

typedef enum _fcgi_request_type {

      FCGI_BEGIN_REQUEST  =  1, /* [in] */

      FCGI_ABORT_REQUEST  =  2, /* [in]  (not supported) */

      FCGI_END_REQUEST     =  3, /* [out] */

      FCGI_PARAMS          =  4, /* [in]  environment variables  */

      FCGI_STDIN           =  5, /* [in]  post data   */

      FCGI_STDOUT          =  6, /* [out] response   */

      FCGI_STDERR          =  7, /* [out] errors     */

      FCGI_DATA    =  8, /* [in]  filter data (not supported) */

      FCGI_GET_VALUES      =  9, /* [in]  */

      FCGI_GET_VALUES_RESULT = 10  /* [out] */

} fcgi_request_type;
Copy after login

整个FastCGI是二进制连续传递的,定义了一个统一结构的消息头,用来读取每个消息的消息体,方便消息包的切割。一般情况下,最先发送的是FCGI_BEGIN_REQUEST类型的消息,然后是FCGI_PARAMS和FCGI_STDIN类型的消息,当FastCGI响应处理完后,将发送FCGI_STDOUT和FCGI_STDERR类型的消息,最后以FCGI_END_REQUEST表示请求的结束。FCGI_BEGIN_REQUEST和FCGI_END_REQUEST分别表示请求的开始和结束,与整个协议相关。

2. 消息头

对于10种类型的消息,都是以一个消息头开始的,其结构体定义如下:

typedef struct _fcgi_header {

      unsigned char version;

      unsigned char type;

      unsigned char requestIdB1;

      unsigned char requestIdB0;

      unsigned char contentLengthB1;

      unsigned char contentLengthB0;

      unsigned char paddingLength;

      unsigned char reserved;

} fcgi_header;
Copy after login

其中,

  • version标识FastCGI协议版本

  • type 标识FastCGI记录类型

  • requestId标识消息所属的FastCGI请求

requestId计算方式如下:

(requestIdB1 <p>所以requestId的范围为0~2的16次方-1,也就是0~65535;</p><p>contentLength标识消息的contentData组件的字节数,计算方式跟requestId类似,范围同样是0~65535:</p><pre class="brush:php;toolbar:false">(contentLengthB1 <p>paddingLength标识消息的paddingData组件的字节数,范围是0~255;协议通过paddingData提供给发送者填充发送的记录的功能,并且方便接受者通过paddingLength快速的跳过paddingData。填充的目的是允许发送者为更有效地处理保持对齐的数据。如果内容的长度超过65535怎么办呢?答案是可以分成多个消息发送。</p><h2 id="strong-FCGI-BEGIN-REQUEST-strong"><strong>3. FCGI_BEGIN_REQUEST</strong></h2><p>FCGI_BEGIN_REQUEST 的结构体定义如下:</p><pre class="brush:php;toolbar:false">typedef struct _fcgi_begin_request {

      unsigned char roleB1;

      unsigned char roleB0;

      unsigned char flags;

      unsigned char reserved[5];

} fcgi_begin_request;
Copy after login

其中role代表的是Web服务器期望应用扮演的角色,计算方式是:

(roleB1 <p>对于PHP7中,处理了三种角色,分别是FCGI_RESPONDER,FCGI_AUTHORIZER       和FCGI_FILTER。</p><p>flags & FCGI_KEEP_CONN:如果为0,则在对本次请求响应后关闭链接。如果非0,在对本次请求响应后不会关闭链接。</p><h2 id="strong-名-值对-strong"><strong>4. 名-值对</strong></h2><p>对于,type为FCGI_PARAMS类型,FastCGI协议中提供了名-值对来很好的满足读写可变长度的name和value,格式如下:</p><pre class="brush:php;toolbar:false">nameLength+valueLength+name+value
Copy after login

为了节省空间,对于0~127长度的值,Length使用了一个char来表示,第一位为0,对于大于127的长度的值,Length使用了4个char来表示,第一位为1;如图所示Analysis of FastCGI protocol in php source code

长度计算代码如下:

if (UNEXPECTED(name_len >= 128)) {

      if (UNEXPECTED(p + 3 >= end)) return 0;

      name_len = ((name_len & 0x7f) <p>这样最长可以表达0~2的31次方的长度。</p><h2 id="strong-请求协议-strong"><strong>5. 请求协议</strong></h2><p>FastCGI协议的定义结构体如下:</p><pre class="brush:php;toolbar:false">    typedef struct _fcgi_begin_request_rec {

      fcgi_header hdr;

      fcgi_begin_request body;

} fcgi_begin_request_rec;
Copy after login

分析完FastCGI的协议,我们整体掌握了请求的FastCGI消息的内容,我们通过访问对应的接口,采用gdb抓取其中的内容:

首先我们修改php-fpm.conf的参数,保证只启动一个worker:

pm.max_children = 1
Copy after login

然后重新启动php-fpm:

./sbin/php-fpm -y etc/php-fpm.conf
Copy after login

然后对worker进行gdb:

ps aux | grep php-fpm

root     30014  0.0  0.0 142308  4724 ?        Ss   Nov26   0:03 php-fpm: master process (etc/php-fpm.conf)

chenlei   30015  0.0  0.0 142508  5500 ?        S    Nov26   0:00 php-fpm: pool www

gdb –p 30015

(gdb) b fcgi_read_request
Copy after login

然后通过浏览器访问nginx,nginx转发到php-fpm的worker上,根据gdb可以打印出FastCGI消息的内容:

(gdb) b fcgi_read_request
Copy after login

对于第一个消息,内容如图:

Analysis of FastCGI protocol in php source code

其中type对应的是FCGI_BEGIN_REQUEST,requestid为1,长度为8, 恰好是fcgi_begin_request结构体的大小,内容如图:

Analysis of FastCGI protocol in php source code

role对应的是FCGI_RESPONDER。继续往下读,得到的消息内容如图:

Analysis of FastCGI protocol in php source code

其中type对应的是FCGI_PARAMS,requestid为1,长度为:

(contentLengthB1 <p>paddingLength=5,而987+5=992,恰好是8的倍数。根据contentLength+ paddingLength向后读取992长度的字节流,我们打印一下:</p><pre class="brush:php;toolbar:false">(gdb) p *p@987

$1 = "\017TSCRIPT_FILENAME/home/xiaoju/webroot/beatles/application/mis/mis/src/index.php/admin/operation/index\f\016QUERY_STRINGactivity_id=89\016\003REQUEST_METHODGET\f\000CONTENT_TYPE\016\000CONTENT_LENGTH\v SCRIPT_NAME/index.php/admin/operation/index\v%REQUEST_URI/admin/operation/index?activity_id=89\f DOCUMENT_URI/index.php/admin/operation/index\r4DOCUMENT_ROOT/home/xiaoju/webroot/beatles/application/mis/mis/src\017\bSERVER_PROTOCOLHTTP/1.1\021\aGATEWAY_INTERFACECGI/1.1\017\vSERVER_SOFTWAREnginx/1.2.5\v\rREMOTE_ADDR172.22.32.131\v\005REMOTE_PORT50973\v\fSERVER_ADDR10.94.98.116\v\004SERVER_PORT8085\v\000SERVER_NAME\017\003REDIRECT_STATUS200\t\021HTTP_HOST10.94.98.116:8085\017\nHTTP_CONNECTIONkeep-alive\017xHTTP_USER_AGENTMozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36\036\001HTTP_UPGRADE_INSECURE_REQUESTS1\vUHTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\024\rHTTP_ACCEPT_ENCODINGgzip, deflate\024\027HTTP_ACCEPT_LANGUAGEzh-CN,zh;q=0.9,en;q=0.8"
Copy after login

根据上一节我们讲到的名-值对的长度规则,我们可以看出,Fastcgi协议中封装了类似于http协议里面的键值对。读取完毕后,继续跟踪消息,打印可以得出,得到的消息如图所示。

Analysis of FastCGI protocol in php source code

其中type对应的是FCGI_PARAMS,requestid为1,长度为0,此时完成了FastCGI协议消息的读取过程。下面说一下处理完请求后返回给nginx的FastCGI协议的消息。

6. 响应协议

在fcgi_finish_request中调用fcgi_flush,fcgi_flush中封装一个FCGI_END_REQUEST消息体,再通过safe_write写入 socket 连接的客户端描述符。

int fcgi_flush(fcgi_request *req, int close)

{

      int len;

 

      close_packet(req);

      len = (int)(req->out_pos - req->out_buf);

 

      if (close) {

               fcgi_end_request_rec *rec = (fcgi_end_request_rec*)(req->out_pos);

                 //创建FCGI_END_REQUEST的头

               fcgi_make_header(&rec->hdr, FCGI_END_REQUEST, req->id, sizeof(fcgi_end_request));

                 //写入appStatus

               rec->body.appStatusB3 = 0;

               rec->body.appStatusB2 = 0;

               rec->body.appStatusB1 = 0;

               rec->body.appStatusB0 = 0;

                 //修改protocolStatus为FCGI_REQUEST_COMPLETE;

               rec->body.protocolStatus = FCGI_REQUEST_COMPLETE;

               len += sizeof(fcgi_end_request_rec);

      }

 

      if (safe_write(req, req->out_buf, len) != len) {

               req->keep = 0;

               req->out_pos = req->out_buf;

               return 0;

      }

 

      req->out_pos = req->out_buf;

      return 1;

}
Copy after login

到此我们就完全掌握了FastCGI的协议。

相关推荐:

PHP开发中redis的主从模式以及加密方法

The above is the detailed content of Analysis of FastCGI protocol in php source code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles