1. if (c->read->ready) {
  2. ngx_http_upstream_process_header(r, u); //读事件触发 准备处理http头部信息
  3. return;
  4. }

向上游服务器发送数据完毕后就会检测是否收到上游服务器的响应:

  1. static void
  2. ngx_http_upstream_process_header(ngx_http_request_t *r, ngx_http_upstream_t *u)
  3. {//读取FCGI头部数据,或者proxy头部数据。ngx_http_upstream_send_request发送完数据后,
  4. //会调用这里,或者有可写事件的时候会调用这里。
  5. //ngx_http_upstream_connect函数连接fastcgi后,会设置这个回调函数为fcgi连接的可读事件回调。
  6. ssize_t n;
  7. ngx_int_t rc;
  8. ngx_connection_t *c;
  9.  
  10. c = u->peer.connection;
  11.  
  12. ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0,
  13. "http upstream process header, fd:%d, buffer_size:%uz", c->fd, u->conf->buffer_size);
  14.  
  15. c->log->action = "reading response header from upstream";
  16.  
  17. if (c->read->timedout) {//读超时了,轮询下一个。 ngx_event_expire_timers超时后走到这里
  18. //该定时器添加地方在ngx_http_upstream_send_request
  19. ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  20. return;
  21. }
  22.  
  23. if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {
  24. ////请求未发送到上游服务器 同时连接测试不通过 转移到下一个server
  25. ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  26. return;
  27. }
  28.  
  29. if (u->buffer.start == NULL) { //分配一块缓存,用来存放接受回来的数据。
  30. u->buffer.start = ngx_palloc(r->pool, u->conf->buffer_size);
  31. //头部行部分(也就是第一个fastcgi data标识信息,里面也会携带一部分网页数据)的fastcgi标识信息开辟的空间用buffer_size配置指定
  32. if (u->buffer.start == NULL) {
  33. ngx_http_upstream_finalize_request(r, u,
  34. NGX_HTTP_INTERNAL_SERVER_ERROR);
  35. return;
  36. }
  37.  
  38. u->buffer.pos = u->buffer.start;
  39. u->buffer.last = u->buffer.start;
  40. u->buffer.end = u->buffer.start + u->conf->buffer_size;
  41. u->buffer.temporary = 1;
  42. u->buffer.tag = u->output.tag;
  43.  
  44. //初始化headers_in存放头部信息,后端FCGI,proxy解析后的HTTP头部将放入这里
  45. if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  46. sizeof(ngx_table_elt_t))
  47. != NGX_OK)
  48. {
  49. ngx_http_upstream_finalize_request(r, u,
  50. NGX_HTTP_INTERNAL_SERVER_ERROR);
  51. return;
  52. }
  53.  
  54. #if (NGX_HTTP_CACHE)
  55. /*
  56. pVpVZ"
  57. KEY: /test.php
  58.  
  59. //下面是后端实际返回的内容,上面的是预留的头部
  60. IX-Powered-By: PHP/5.2.13
  61. Content-type: text/html
  62.  
  63. <Html>
  64. <Head>
  65. <title>Your page Subject and domain name</title>
  66. */
  67. if (r->cache) { //注意这里跳过了预留的头部内存,用于存储cache写入文件时候的头部部分,见
  68. u->buffer.pos += r->cache->header_start;
  69. u->buffer.last = u->buffer.pos;
  70. }
  71. #endif
  72. }
  73.  
  74. for ( ;; ) {
  75. //recv 为 ngx_unix_recv,读取数据放在u->buffer.last的位置,返回读到的大小u->peer.connection->read->ready == 1 (size==n) 时;
    //也就是 u->buffer.end-u->buffer.last == size == n; 也就是size 大小的缓存去读数据时, 返回的n == szie;也就是内核还有数据没有读出来,
    //此时 u->perr.connection->read->ready 不为0 标示还有数据没有读
    n = c->recv(c, u->buffer.last, u->buffer.end - u->buffer.last);
  1. if (n == NGX_AGAIN) { //内核缓冲区已经没数据了
  2. #if 0
  3. ngx_add_timer(rev, u->read_timeout);
  4. #endif
  5. if (ngx_handle_read_event(c->read, 0, NGX_FUNC_LINE) != NGX_OK) {
  6. ngx_http_upstream_finalize_request(r, u,
  7. NGX_HTTP_INTERNAL_SERVER_ERROR);
  8. return;
  9. }
  10. return;
  11. }
  12. if (n == 0) {
  13. ngx_log_error(NGX_LOG_ERR, c->log, 0,
  14. "upstream prematurely closed connection");
  15. }
  16. if (n == NGX_ERROR || n == 0) {
  17. ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  18. return;
  19. }
  20. u->buffer.last += n;
  21. //ngx_http_xxx_process_header ngx_http_proxy_process_header ngx_http_proxy_process_status_line
  22. rc = u->process_header(r);//ngx_http_fastcgi_process_header等,进行数据处理,比如后端返回的数据头部解析,body读取等。
  23. if (rc == NGX_AGAIN) {
  24. ngx_log_debugall(c->log, 0, " ngx_http_upstream_process_header u->process_header() return NGX_AGAIN");
  25. if (u->buffer.last == u->buffer.end) { //分配的用来存储fastcgi STDOUT头部行包体的buf已经用完了头部行都还没有解析完成,
  26. ngx_log_error(NGX_LOG_ERR, c->log, 0,
  27. "upstream sent too big header");
  28. ngx_http_upstream_next(r, u,
  29. NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  30. return;
  31. }
  32. continue;
  33. }
  34. break;
  35. }
  36. if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  37. ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  38. return;
  39. }
  40. if (rc == NGX_ERROR) {
  41. ngx_http_upstream_finalize_request(r, u, NGX_HTTP_INTERNAL_SERVER_ERROR);
  42. return;
  43. }
  44. /* rc == NGX_OK */
  45. u->state->header_time = ngx_current_msec - u->state->response_time;
  46. if (u->headers_in.status_n >= NGX_HTTP_SPECIAL_RESPONSE) {
  47. if (ngx_http_upstream_test_next(r, u) == NGX_OK) {
  48. return;
  49. }
  50. if (ngx_http_upstream_intercept_errors(r, u) == NGX_OK) {
  51. return;
  52. }
  53. }
  54. //到这里,FCGI等格式的数据已经解析为标准HTTP的表示形式了(除了BODY),所以可以进行upstream的process_headers。
  55. //上面的 u->process_header(r)已经进行FCGI等格式的解析了。下面将头部数据拷贝到headers_out.headers数组中。
  56. if (ngx_http_upstream_process_headers(r, u) != NGX_OK) {
  57. return;
  58. }
  59. if (!r->subrequest_in_memory) {//如果没有子请求了,那就直接发送响应给客户端吧。
          
    当请求的ngx_http_request_t结构体中subrequest_in_memory标志位为1时,将采用第1种方式,即upstream不转发响应包体到下游,
          HTTP模块实现的input_filter方法处理包体;当subrequest_in_memory0时,upstream会转发响应包体。
          ngx_http_upstream_conf_t配置结构体中的buffering标志位为1时,将开启更多的内存和磁盘文件用于缓存上游的响应包体,这意味上游网速更快;
          buffering0时,将使用固定大小的缓冲区(就是上面介绍的buffer缓冲区)来转发响应包体
          //buffering方式和非buffering方式在函数ngx_http_upstream_send_response分惜
         ngx_http_upstream_send_response(r, u);//给客户端发送响应,里面会处理header,body分开发送的情况
        return
        }
  1. /* subrequest content in memory */
  2. //子请求,并且后端数据需要保存到内存在
  3. //注意下面只是把后端数据存到buf中,但是没有发送到客户端,实际发送一般是由ngx_http_finalize_request->ngx_http_set_write_handler实现
  4. if (u->input_filter == NULL) {
  5. u->input_filter_init = ngx_http_upstream_non_buffered_filter_init;
  6. u->input_filter = ngx_http_upstream_non_buffered_filter;
  7. u->input_filter_ctx = r;
  8. }
  9. if (u->input_filter_init(u->input_filter_ctx) == NGX_ERROR) {
  10. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  11. return;
  12. }
  13. n = u->buffer.last - u->buffer.pos;
  14. if (n) {
  15. u->buffer.last = u->buffer.pos;
  16. u->state->response_length += n;
  17. if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  18. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  19. return;
  20. }
  21. }
  22. if (u->length == 0) {
  23. ngx_http_upstream_finalize_request(r, u, 0);
  24. return;
  25. }
  26. u->read_event_handler = ngx_http_upstream_process_body_in_memory;//设置body部分的读事件回调。
  27. ngx_http_upstream_process_body_in_memory(r, u);
  28. }

http request 结构体

  1. /*
  2. 对于每个ngx_http_request_t请求来说,只能访问一个上游服务器,但对于一个客户端请求来说,可以派生出许多子请求,任何一个子请求都
  3. 可以访问一个上游服务器,这些子请求的结果组合起来就可以使来自客户端的请求处理复杂的业务。
  4. */
  5. //ngx_http_parse_request_line解析请求行, ngx_http_process_request_headers解析头部行(请求头部)
  6. //请求的所有信息都可以都可以在ngx_http_request_s结构获取到
  7. struct ngx_http_request_s { //当接收到客户端请求数据后,调用ngx_http_create_request中创建并赋值
  8. uint32_t signature; /* "HTTP" */
  9.  
  10. /*
  11. 在接收到客户端数据后,会创建一个ngx_http_request_s,其connection成员指向对应的accept成功后获取到的连接信息
  12. ngx_connection_t,见ngx_http_create_request
  13. 这个请求对应的客户端连接 如果该r是子请求,其connection成员指向顶层root父请求的ngx_connection_t,因为它们都是对应的同一个客户端连接,见ngx_http_subrequest
  14. */
  15. ngx_connection_t *connection;
  16.  
  17. /*
  18. ctx与ngx_http_conf_ctxt结构的3个数组成员非常相似,它们都
  19. 表示指向void指针的数组。HTTP框架就是在ctx数组中保存所有HTTP模块上下文结构体的指针的,所有模块的请求上下文空间在
  20. ngx_http_create_request中创建。获取和设置分别在ngx_http_get_module_ctx和ngx_http_set_ctx,为每个请求创建ngx_http_request_s的时候
  21. 都会为该请求的ctx[]为所有的模块创建一个指针,也就是每个模块在ngx_http_request_s中有一个ctx
  22. */ //在应答完后,在ngx_http_filter_finalize_request会把ctx指向的空间全部清0 参考4.5节
  23. void **ctx; //指向存放所有HTTP模块的上下文结构体的指针数组,实际上发送给客户端的应答完成后,会把ctx全部置0
  24. /*
  25. 当客户端建立连接后,并发送请求数据过来后,在ngx_http_create_request中从ngx_http_connection_t->conf_ctx获取这三个值,也就是根据客户端连接
  26. 本端所处IP:port所对应的默认server{}块上下文,如果是以下情况:ip:port相同,单在不同的server{}块中,那么有可能客户端请求过来的时候携带的host
  27. 头部项的server_name不在默认的server{}中,而在另外的server{}中,所以需要通过ngx_http_set_virtual_server重新获取server{}和location{}上下文配置
  28. 例如:
  29. server { #1
  30. listen 1.1.1.1:80;
  31. server_name aaa
  32. }
  33.  
  34. server { #2
  35. listen 1.1.1.1:80;
  36. server_name bbb
  37. }
  38. 这个配置在ngx_http_init_connection中把ngx_http_connection_t->conf_ctx指向ngx_http_addr_conf_s->default_server,也就是指向#1,然后
  39. ngx_http_create_request中把main_conf srv_conf loc_conf 指向#1,
  40. 但如果请求行的头部的host:bbb,那么需要重新获取对应的server{} #2,见ngx_http_set_virtual_server
  41. */ //ngx_http_create_request和ngx_http_set_virtual_server 已经rewrite过程中(例如ngx_http_core_find_location
  42. //ngx_http_core_post_rewrite_phase ngx_http_internal_redirect ngx_http_internal_redirect 子请求ngx_http_subrequest)都可能对他们赋值
  43. void **main_conf; //指向请求对应的存放main级别配置结构体的指针数组
  44. void **srv_conf; //指向请求对应的存放srv级别配置结构体的指针数组 赋值见ngx_http_set_virtual_server
  45. void **loc_conf; //指向请求对应的存放loc级别配置结构体的指针数组 赋值见ngx_http_set_virtual_server
  46.  
  47. /*
  48. 在接收完HTTP头部,第一次在业务上处理HTTP请求时,HTTP框架提供的处理方法是ngx_http_process_request。但如果该方法无法一次处
  49. 理完该请求的全部业务,在归还控制权到epoll事件模块后,该请求再次被回调时,将通过ngx_http_request_handler方法来处理,而这个
  50. 方法中对于可读事件的处理就是调用read_event_handler处理请求。也就是说,HTTP模块希望在底层处理请求的读事件时,重新实现read_event_handler方法
  51.  
  52. //在读取客户端来的包体时,赋值为ngx_http_read_client_request_body_handler
  53. 丢弃客户端的包体时,赋值为ngx_http_discarded_request_body_handler
  54. */ //注意ngx_http_upstream_t和ngx_http_request_t都有该成员 分别在ngx_http_request_handler和ngx_http_upstream_handler中执行
  55. ngx_http_event_handler_pt read_event_handler;
  56.  
  57. /* 与read_event_handler回调方法类似,如果ngx_http_request_handler方法判断当前事件是可写事件,则调用write_event_handler处理请求 */
  58. /*请求行和请求头部解析完成后,会在ngx_http_handler中赋值为ngx_http_core_run_phases 子请求的的handler为ngx_http_handler
  59. 当发送响应的时候,如果一次没有发送完,则设在为ngx_http_writer
  60. */ //注意ngx_http_upstream_t和ngx_http_request_t都有该成员 分别在ngx_http_request_handler和ngx_http_upstream_handler中执行
  61. //如果采用buffer方式缓存后端包体,则在发送包体给客户端浏览器的时候,会把客户端连接的write_e_hand置为ngx_http_upstream_process_downstream
  62. //在触发epoll_in的同时也会触发epoll_out,从而会执行该函数
  63. ngx_http_event_handler_pt write_event_handler;//父请求重新激活后的回调方法
  64.  
  65. #if (NGX_HTTP_CACHE)
  66. //通过ngx_http_upstream_cache_get获取
  67. ngx_http_cache_t *cache;//在客户端请求过来后,在ngx_http_upstream_cache->ngx_http_file_cache_new中赋值r->caceh = ngx_http_cache_t
  68. #endif
  69.  
  70. /*
  71. 如果没有使用upstream机制,那么ngx_http_request_t中的upstream成员是NULL空指针,在ngx_http_upstream_create中创建空间
  72. */
  73. ngx_http_upstream_t *upstream; //upstream机制用到的结构体
  74. ngx_array_t *upstream_states; //创建空间和赋值见ngx_http_upstream_init_request
  75. /* of ngx_http_upstream_state_t */
  76.  
  77. /*
  78. 表示这个请求的内存池,在ngx_http_free_request方法中销毁。它与ngx_connection-t中的内存池意义不同,当请求释放时,TCP连接可能并
  79. 没有关闭,这时请求的内存池会销毁,但ngx_connection_t的内存池并不会销毁
  80. */
  81. ngx_pool_t *pool;
  82. //其中,header_in指向Nginx收到的未经解析的HTTP头部,这里暂不关注它(header_in就是接收HTTP头部的缓冲区)。 header_in存放请求行,headers_in存放头部行
  83. //请求行和请求头部内容都在该buffer中
  84. ngx_buf_t *header_in;//用于接收HTTP请求内容的缓冲区,主要用于接收HTTP头部,该指针指向ngx_connection_t->buffer
  85.  
  86. //类型的headers_in则存储已经解析过的HTTP头部。
  87. /*常用的HTTP头部信息可以通过r->headers_in获取,不常用的HTTP头部则需要遍历r->headers_in.headers来遍历获取*/
  88. /*
  89. ngx_http_process_request_headers方法在接收、解析完HTTP请求的头部后,会把解析完的每一个HTTP头部加入到headers_in的headers链表中,同时会构造headers_in中的其他成员
  90. */ //参考ngx_http_headers_in,通过该数组中的回调hander来存储解析到的请求行name:value中的value到headers_in的响应成员中,见ngx_http_process_request_headers
  91. //注意:在需要把客户端请求头发送到后端的话,在请求头后面可能添加有HTTP_相关变量,例如fastcgi,见ngx_http_fastcgi_create_request
  92. ngx_http_headers_in_t headers_in; //http头部行解析后的内容都由该成员存储 header_in存放请求行,headers_in存放头部行
  93. //只要指定headers_out中的成员,就可以在调用ngx_http_send_header时正确地把HTTP头部发出
  94. //HTTP模块会把想要发送的HTTP响应信息放到headers_out中,期望HTTP框架将headers_out中的成员序列化为HTTP响应包发送给用户
  95. ngx_http_headers_out_t headers_out;
  96. //如果是upstream赋值的来源是后端服务器会有的头部行中拷贝,参考ngx_http_upstream_headers_in中的copy_handler
  97.  
  98. /*
  99. 接收完请求的包体后,可以在r->request_body->temp_file->file中获取临时文件(假定将r->request_body_in_file_only标志位设为1,那就一定可以
  100. 在这个变量获取到包体。)。file是一个ngx_file_t类型。这里,我们可以从
  101. r->request_body->temp_file->file.name中获取Nginx接收到的请求包体所在文件的名称(包括路径)。
  102. */ //在ngx_http_read_client_request_body中分配存储空间 读取的客户端包体存储在r->request_body->bufs链表和临时文件r->request_body->temp_file中 ngx_http_read_client_request_body
  103. //读取客户包体即使是存入临时文件中,当所有包体读取完毕后(见ngx_http_do_read_client_request_body),还是会让r->request_body->bufs指向文件中的相关偏移内存地址
  104. //向上游发送包体u->request_bufs(ngx_http_fastcgi_create_request),接收客户端的包体在r->request_body
  105. ngx_http_request_body_t *request_body; //接收HTTP请求中包体的数据结构,为NULL表示还没有分配空间
  106. //min(lingering_time,lingering_timeout)这段时间内可以继续读取数据,如果客户端有发送数据过来,见ngx_http_set_lingering_close
  107. time_t lingering_time; //延迟关闭连接的时间
  108. //ngx_http_request_t结构体中有两个成员表示这个请求的开始处理时间:start sec成员和start msec成员
  109. /*
  110. 当前请求初始化时的时间。start sec是格林威治时间1970年1月1日凌晨0点0分0秒到当前时间的秒数。如果这个请求是子请求,则该时间
  111. 是子请求的生成时间;如果这个请求是用户发来的请求,则是在建立起TCP连接后,第一次接收到可读事件时的时间
  112. */
  113. time_t start_sec;
  114. ngx_msec_t start_msec;//与start_sec配合使用,表示相对于start_set秒的毫秒偏移量
  115.  
  116. //以下9个成员都是ngx_http_proces s_request_line方法在接收、解析HTTP请求行时解析出的信息
  117. /*
  118. 注意 Nginx中对内存的控制相当严格,为了避免不必要的内存开销,许多需要用到的成员都不是重新分配内存后存储的,而是直接指向用户请求中的相应地址。
  119. 例如,method_name.data、request_start这两个指针实际指向的都是同一个地址。而且,因为它们是简单的内存指针,不是指向字符串的指针,所以,在大部分情况下,都不能将这些u_char*指针当做字符串使用。
  120. */ //NGX_HTTP_GET | NGX_HTTP_HEAD等,为NGX_HTTP_HEAD表示只需要发送HTTP头部字段
  121. /* HTTP2的method赋值见ngx_http_v2_parse_method */
  122. ngx_uint_t method; //对应客户端请求中请求行的请求方法GET、POS等,取值见NGX_HTTP_GET,也可以用下面的method_name进行字符串比较
  123. /*
  124. http_protocol指向用户请求中HTTP的起始地址。
  125. http_version是Nginx解析过的协议版本,它的取值范围如下:
  126. #define NGX_HTTP_VERSION_9 9
  127. #define NGX_HTTP_VERSION_10 1000
  128. #define NGX_HTTP_VERSION_11 1001
  129. 建议使用http_version分析HTTP的协议版本。
  130. 最后,使用request_start和request_end可以获取原始的用户请求行。
  131. */
  132. ngx_uint_t http_version;//http_version是Nginx解析过的协议版本,它的取值范围如下:
  133. /* 如果是HTTP2,则赋值见ngx_http_v2_construct_request_line */
  134. ngx_str_t request_line; //请求行内容
  135.  
  136. //ngx_str_t类型的uri成员指向用户请求中的URI。同理,u_char*类型的uri_start和uri_end也与request_start、method_end的用法相似,唯一不
  137. //同的是,method_end指向方法名的最后一个字符,而uri_end指向URI结束后的下一个地址,也就是最后一个字符的下一个字符地址(HTTP框架的行为),
  138. //这是大部分u_char*类型指针对“xxx_start”和“xxx_end”变量的用法。
  139. //http://10.135.10.167/mytest中的/mytest http://10.135.10.167/mytest?abc?ttt中的/mytest
  140. //同时"GET /mytest?abc?ttt HTTP/1.1"中的mytest和uri中的一样
  141. ngx_str_t uri;
  142. //arg指向用户请求中的URL参数。 http://10.135.10.167/mytest?abc?ttt中的abc?ttt
  143. //同时"GET /mytest?abc?ttt HTTP/1.1"中的mytest?abc?ttt和uri中的一样
  144.  
  145. /*把请求中GET /download/nginx-1.9.2.rar?st=xhWL03HbtjrojpEAfiD6Mw&e=1452139931 HTTP/1.1的st和e形成变量$arg_st #arg_e,value分别
  146. 为xhWL03HbtjrojpEAfiD6Mw 1452139931即$arg_st=xhWL03HbtjrojpEAfiD6Mw,#arg_e=1452139931,见ngx_http_arg */
  147. ngx_str_t args;
  148. /*
  149. ngx_str_t类型的extern成员指向用户请求的文件扩展名。例如,在访问“GET /a.txt HTTP/1.1”时,extern的值是{len = 3, data = "txt"},
  150. 而在访问“GET /a HTTP/1.1”时,extern的值为空,也就是{len = 0, data = 0x0}。
  151. uri_ext指针指向的地址与extern.data相同。
  152. */
  153. ngx_str_t exten; //http://10.135.10.167/mytest/ac.txt中的txt
  154. /*
  155. url参数中出现+、空格、=、%、&、#等字符的解决办法
  156. url出现了有+,空格,/,?,%,#,&,=等特殊符号的时候,可能在服务器端无法获得正确的参数值,如何是好?
  157. 解决办法
  158. 将这些字符转化成服务器可以识别的字符,对应关系如下:
  159. URL字符转义
  160.  
  161. 用其它字符替代吧,或用全角的。
  162.  
  163. + URL 中+号表示空格 %2B
  164. 空格 URL中的空格可以用+号或者编码 %20
  165. / 分隔目录和子目录 %2F
  166. ? 分隔实际的URL和参数 %3F
  167. % 指定特殊字符 %25
  168. # 表示书签 %23
  169. & URL 中指定的参数间的分隔符 %26
  170. = URL 中指定参数的值 %3D
  171. */
  172. //unparsed_uri表示没有进行URL解码的原始请求。例如,当uri为“/a b”时,unparsed_uri是“/a%20b”(空格字符做完编码后是%20)。
  173. ngx_str_t unparsed_uri;//参考:为什么要对URI进行编码:
  174. /* HTTP2的method赋值见ngx_http_v2_parse_method,在组新的HTTP2头部行后,赋值见ngx_http_v2_construct_request_line */
  175. ngx_str_t method_name;//见method GET POST等
  176. ngx_str_t http_protocol;//GET /sample.jsp HTTP/1.1 中的HTTP/1.1
  177.  
  178. /* 当ngx_http_header_filter方法无法一次性发送HTTP头部时,将会有以下两个现象同时发生:请求的out成员中将会保存剩余的响应头部,见ngx_http_header_filter */
  179. /* 表示需要发送给客户端的HTTP响应。out中保存着由headers_out中序列化后的表示HTTP头部的TCP流。在调用ngx_http_output_filter方法后,
  180. out中还会保存待发送的HTTP包体,它是实现异步发送HTTP响应的关键 */
  181. ngx_chain_t *out;//ngx_http_write_filter把in中的数据拼接到out后面,然后调用writev发送,没有发送完
  182.  
  183. /* 当前请求既可能是用户发来的请求,也可能是派生出的子请求,而main则标识一系列相关的派生子请
  184. 求的原始请求,我们一般可通过main和当前请求的地址是否相等来判断当前请求是否为用户发来的原始请求 */
  185.  
  186. //main成员始终指向一系列有亲缘关系的请求中的唯一的那个原始请求,初始赋值见ngx_http_create_request
  187. //客户端的建立连接的时候r->main =r(ngx_http_create_request),如果是创建子请求,sr->main = r->main(ngx_http_subrequest)子请求->main=最上层的r
  188. /* 主请求保存在main字段中,这里其实就是最上层跟请求,例如当前是四层子请求,则main始终指向第一层父请求,
  189. 而不是第三次父请求,parent指向第三层父请求 */
  190. ngx_http_request_t *main; //赋值见ngx_http_subrequest
  191. ngx_http_request_t *parent;//当前请求的父请求。注意,父请求未必是原始请求 赋值见ngx_http_subrequest
  192.  
  193. //ngx_http_subrequest中赋值,表示对应的子请求r,该结构可以表示子请求信息
  194. //postponed删除在ngx_http_finalize_request
  195. //当客户端请求需要通过多个subrequest访问后端的时候,就需要对这多个后端的应答进行合适的顺序整理才能发往客户端
  196. ngx_http_postponed_request_t *postponed; //与subrequest子请求相关的功能 postponed中数据依次发送参考ngx_http_postpone_filter方法
  197. ngx_http_post_subrequest_t *post_subrequest;/* 保存回调handler及数据,在子请求执行完,将会调用 */
  198.  
  199. /* 所有的子请求都是通过posted_requests这个单链表来链接起来的,执行post子请求时调用的
  200. ngx_http_run_posted_requests方法就是通过遍历该单链表来执行子请求的 */
  201. //ngx_http_post_request中创建ngx_http_posted_request_t空间
  202. //ngx_http_post_request将该子请求挂载在主请求的posted_requests链表队尾,在ngx_http_run_posted_requests中执行
  203. ngx_http_posted_request_t *posted_requests; //通过posted_requests就把各个子请求以单向链表的数据结构形式组织起来
  204.  
  205. /*
  206. 全局的ngx_http_phase_engine_t结构体中定义了一个ngx_http_phase_handler_t回调方法组成的数组,而phase_handler成员则与该数组配合使用,
  207. 表示请求下次应当执行以phase_handler作为序号指定的数组中的回调方法。HTTP框架正是以这种方式把各个HTTP摸块集成起来处理请求的
  208. *///phase_handler实际上是该阶段的处理方法函数在ngx_http_phase_engine_t->handlers数组中的位置
  209. ngx_int_t phase_handler;
  210. //表示NGX HTTP CONTENT PHASE阶段提供给HTTP模块处理请求的一种方式,content handler指向HTTP模块实现的请求处理方法,在ngx_http_core_content_phase中执行
  211. //ngx_http_proxy_handler ngx_http_redis2_handler ngx_http_fastcgi_handler等
  212. ngx_http_handler_pt content_handler; ////在ngx_http_update_location_config中赋值给r->content_handler = clcf->handler;
  213. /*
  214. 在NGX_HTTP_ACCESS_PHASE阶段需要判断请求是否具有访问权限时,通过access_code来传递HTTP模块的handler回调方法的返回值,如果access_code为0,
  215. 则表示请求具备访问权限,反之则说明请求不具备访问权限
  216.  
  217. NGXHTTPPREACCESSPHASE、NGX_HTTP_ACCESS_PHASE、NGX HTTPPOST_ACCESS_PHASE,很好理解,做访问权限检查的前期、中期、后期工作,
  218. 其中后期工作是固定的,判断前面访问权限检查的结果(状态码存故在字段r->access_code内),如果当前请求没有访问权限,那么直接返回状
  219. 态403错误,所以这个阶段也无法去挂载额外的回调函数。
  220. */
  221. ngx_uint_t access_code; //赋值见ngx_http_core_access_phase
  222. /*
  223. ngx_http_core_main_conf_t->variables数组成员的结构式ngx_http_variable_s, ngx_http_request_s->variables数组成员结构是ngx_variable_value_t,
  224. 这两个结构的关系很密切,一个所谓变量,一个所谓变量值
  225.  
  226. r->variables这个变量和cmcf->variables是一一对应的,形成var_ name与var_value对,所以两个数组里的同一个下标位置元素刚好就是
  227. 相互对应的变量名和变量值,而我们在使用某个变量时总会先通过函数ngx_http_get_variable_index获得它在变量名数组里的index下标,也就是变
  228. 量名里的index字段值,然后利用这个index下标进而去变量值数组里取对应的值
  229. */ //分配的节点数见ngx_http_create_request,和ngx_http_core_main_conf_t->variables一一对应
  230. //变量ngx_http_script_var_code_t->index表示Nginx变量$file在ngx_http_core_main_conf_t->variables数组内的下标,对应每个请求的变量值存储空间就为r->variables[code->index],参考ngx_http_script_set_var_code
  231. ngx_http_variable_value_t *variables; //注意和ngx_http_core_main_conf_t->variables的区别
  232.  
  233. #if (NGX_PCRE)
  234. /*
  235. 例如正则表达式语句re.name= ^(/download/.*)/media/(.*)/tt/(.*)$, s=/download/aa/media/bdb/tt/ad,则他们会匹配,同时匹配的
  236. 变量数有3个,则返回值为3+1=4,如果不匹配则返回-1
  237.  
  238. 这里*2是因为获取前面例子中的3个变量对应的值需要成对使用r->captures,参考ngx_http_script_copy_capture_code等
  239. */
  240. ngx_uint_t ncaptures; //赋值见ngx_http_regex_exec //最大的$n*2
  241. int *captures; //每个不同的正则解析之后的结果,存放在这里。$1,$2等
  242. u_char *captures_data; //进行正则表达式匹配的原字符串,例如http://10.135.2.1/download/aaa/media/bbb.com中的/download/aaa/media/bbb.com
  243. #endif
  244.  
  245. /* limit_rate成员表示发送响应的最大速率,当它大于0时,表示需要限速。limit rate表示每秒可以发送的字节数,超过这个数字就需要限速;
  246. 然而,限速这个动作必须是在发送了limit_rate_after字节的响应后才能生效(对于小响应包的优化设计) */
  247. //实际最后通过ngx_writev_chain发送数据的时候,还会限制一次
  248. size_t limit_rate; //限速的相关计算方法参考ngx_http_write_filter
  249. size_t limit_rate_after;
  250.  
  251. /* used to learn the Apache compatible response length without a header */
  252. size_t header_size; //所有头部行内容之和,可以参考ngx_http_header_filter
  253.  
  254. off_t request_length; //HTTP请求的全部长度,包括HTTP包体
  255.  
  256. ngx_uint_t err_status; //错误码,取值为NGX_HTTP_BAD_REQUEST等
  257.  
  258. //当连接建立成功后,当收到客户端的第一个请求的时候会通过ngx_http_wait_request_handler->ngx_http_create_request创建ngx_http_request_t
  259. //同时把r->http_connection指向accept客户端连接成功时候创建的ngx_http_connection_t,这里面有存储server{}上下文ctx和server_name等信息
  260. //该ngx_http_request_t会一直有效,除非关闭连接。因此该函数只会调用一次,也就是第一个客户端请求报文过来的时候创建,一直持续到连接关闭
  261. //该结构存储了服务器端接收客户端连接时,服务器端所在的server{]上下文ctx server_name等配置信息
  262. ngx_http_connection_t *http_connection; //存储ngx_connection_t->data指向的ngx_http_connection_t,见ngx_http_create_request
  263.  
  264. #if (NGX_HTTP_SPDY)
  265. ngx_http_spdy_stream_t *spdy_stream;
  266. #endif
  267.  
  268. #if (NGX_HTTP_V2)
  269. /* 赋值见ngx_http_v2_create_stream */
  270. ngx_http_v2_stream_t *stream;
  271. #endif
  272.  
  273. ngx_http_log_handler_pt log_handler;
  274. //在这个请求中如果打开了某些资源,并需要在请求结束时释放,那么都需要在把定义的释放资源方法添加到cleanup成员中
  275. /*
  276. 如果没有需要清理的资源,则cleanup为空指针,否则HTTP模块可以向cleanup中以单链表的形式无限制地添加ngx_http_cleanup_t结构体,
  277. 用以在请求结束时释放资源 */
  278. ngx_http_cleanup_t *cleanup;
  279. //默认值r->subrequests = NGX_HTTP_MAX_SUBREQUESTS + 1;见ngx_http_create_request
  280. unsigned subrequests:8; //该r最多还可以处理多少个子请求
  281.  
  282. /*
  283. 在阅读HTTP反向代理模块(ngx_http_proxy_module)源代码时,会发现它并没有调用r->main->count++,其中proxy模块是这样启动upstream机制的:
  284. ngx_http_read_client_request_body(r,ngx_http_upstream_init);,这表示读取完用户请求的HTTP包体后才会调用ngx_http_upstream_init方法
  285. 启动upstream机制。由于ngx_http_read_client_request_body的第一行有效语句是r->maln->count++,所以HTTP反向代理模块不能
  286. 再次在其代码中执行r->main->count++。
  287.  
  288. 这个过程看起来似乎让人困惑。为什么有时需要把引用计数加1,有时却不需要呢?因为ngx_http_read- client_request_body读取请求包体是
  289. 一个异步操作(需要epoll多次调度方能完成的可称其为异步操作),ngx_http_upstream_init方法启用upstream机制也是一个异步操作,因此,
  290. 从理论上来说,每执行一次异步操作应该把引用计数加1,而异步操作结束时应该调用ngx_http_finalize_request方法把引用计数减1。另外,
  291. ngx_http_read_client_request_body方法内是加过引用计数的,而ngx_http_upstream_init方法内却没有加过引用计数(或许Nginx将来会修改
  292. 这个问题)。在HTTP反向代理模块中,它的ngx_http_proxy_handler方法中用“ngx_http_read- client_request_body(r,ngx_http_upstream_init);”
  293. 语句同时启动了两个异步操作,注意,这行语句中只加了一次引用计数。执行这行语句的ngx_http_proxy_handler方法返回时只调用
  294. ngx_http_finalize_request方法一次,这是正确的。对于mytest模块也一样,务必要保证对引用计数的增加和减少是配对进行的。
  295. */
  296. /*
  297. 表示当前请求的引用次数。例如,在使用subrequest功能时,依附在这个请求上的子请求数目会返回到count上,每增加一个子请求,count数就要加1。
  298. 其中任何一个子请求派生出新的子请求时,对应的原始请求(main指针指向的请求)的count值都要加1。又如,当我们接收HTTP包体时,由于这也是
  299. 一个异步调用,所以count上也需要加1,这样在结束请求时,就不会在count引用计数未清零时销毁请求
  300. */
  301. unsigned count:8; //应用计数 ngx_http_close_request中-1
  302. /* 如果AIO上下文中还在处理这个请求,blocked必然是大于0的,这时ngx_http_close_request方法不能结束请求
  303. ngx_http_copy_aio_handler会自增,当内核把数据发送出去后会在ngx_http_copy_aio_event_handler自剪
  304. */
  305. unsigned blocked:8; //阻塞标志位,目前仅由aio使用 为0,表示没有HTTP模块还需要处理请求
  306. //ngx_http_copy_aio_handler handler ngx_http_copy_aio_event_handler执行后,会置回到0
  307. //ngx_http_copy_thread_handler ngx_http_copy_thread_event_handler置0
  308. //ngx_http_cache_thread_handler置1, ngx_http_cache_thread_event_handler置0
  309. //ngx_http_file_cache_aio_read中置1,
  310. unsigned aio:1; //标志位,为1时表示当前请求正在使用异步文件IO
  311.  
  312. unsigned http_state:4; //赋值见ngx_http_state_e中的成员
  313.  
  314. /* URI with "/." and on Win32 with "//" */
  315. unsigned complex_uri:1;
  316.  
  317. /* URI with "%" */
  318. unsigned quoted_uri:1;
  319.  
  320. /* URI with "+" */
  321. unsigned plus_in_uri:1;
  322.  
  323. /* URI with " " */
  324. unsigned space_in_uri:1; //uri中是否带有空格
  325. //头部帧内容部分header合法性检查,见ngx_http_v2_validate_header
  326. unsigned invalid_header:1; //头部行解析不正确,见ngx_http_parse_header_line
  327.  
  328. unsigned add_uri_to_alias:1;
  329. unsigned valid_location:1; //ngx_http_handler中置1
  330. //如果有rewrite 内部重定向 uri带有args等会直接置0,否则如果uri中有空格会置1
  331. unsigned valid_unparsed_uri:1;//r->valid_unparsed_uri = r->space_in_uri ? 0 : 1;
  332.  
  333. /*
  334. 将uri_changed设置为0后,也就标志说URL没有变化,那么,在ngx_http_core_post_rewrite_phase中就不会执行里面的if语句,也就不会
  335. 再次走到find config的过程了,而是继续处理后面的。不然正常情况,rewrite成功后是会重新来一次的,相当于一个全新的请求。
  336. */ // 例如rewrite ^.*$ www.galaxywind.com last;就会多次执行rewrite ngx_http_script_regex_start_code中置1
  337. unsigned uri_changed:1; //标志位,为1时表示URL发生过rewrite重写 只要不是rewrite xxx bbb sss;aaa不是break结束都会置1
  338. //表示使用rewrite重写URL的次数。因为目前最多可以更改10次,所以uri_changes初始化为11,而每重写URL -次就把uri_changes减1,
  339. //一旦uri_changes等于0,则向用户返回失败
  340. unsigned uri_changes:4; //NGX_HTTP_MAX_URI_CHANGES + 1;
  341.  
  342. unsigned request_body_in_single_buf:1;//client_body_in_single_buffer on | off;设置
  343. //置1包体需要存入临时文件中 如果request_body_no_buffering为1表示不用缓存包体,那么request_body_in_file_only也为0,因为不用缓存包体,那么就不用写到临时文件中
  344. /*注意:如果每次开辟的client_body_buffer_size空间都存储满了还没有读取到完整的包体,则还是会把之前读满了的buf中的内容拷贝到临时文件,参考
  345. ngx_http_do_read_client_request_body -> ngx_http_request_body_filter和ngx_http_read_client_request_body -> ngx_http_request_body_filter
  346. */
  347. unsigned request_body_in_file_only:1; //"client_body_in_file_only on |clean"设置 和request_body_no_buffering是互斥的
  348. unsigned request_body_in_persistent_file:1; //"client_body_in_file_only on"设置
  349. unsigned request_body_in_clean_file:1;//"client_body_in_file_only clean"设置
  350. unsigned request_body_file_group_access:1; //是否有组权限,如果有一般为0600
  351. unsigned request_body_file_log_level:3;
  352. //默认是为0的表示需要缓存客户端包体,决定是否需要转发客户端包体到后端,如果request_body_no_buffering为1表示不用缓存包体,那么request_body_in_file_only也为0,因为不用缓存包体,那么就不用写到临时文件中
  353. unsigned request_body_no_buffering:1; //是否缓存HTTP包体,如果不缓存包体,和request_body_in_file_only是互斥的,见ngx_http_read_client_request_body
  354.  
  355. /*
  356. upstream有3种处理上游响应包体的方式,但HTTP模块如何告诉upstream使用哪一种方式处理上游的响应包体呢?
  357. 当请求的ngx_http_request_t结构体中subrequest_in_memory标志位为1时,将采用第1种方式,即upstream不转发响应包体
  358. 到下游,由HTTP模块实现的input_filter方法处理包体;当subrequest_in_memory为0时,upstream会转发响应包体。当ngx_http_upstream_conf_t
  359. 配置结构体中的buffering标志位为1时,将开启更多的内存和磁盘文件用于缓存上游的响应包体,这意味上游网速更快;当buffering
  360. 为0时,将使用固定大小的缓冲区(就是上面介绍的buffer缓冲区)来转发响应包体。
  361. */
  362. unsigned subrequest_in_memory:1; //ngx_http_subrequest中赋值 NGX_HTTP_SUBREQUEST_IN_MEMORY
  363. unsigned waited:1; //ngx_http_subrequest中赋值 NGX_HTTP_SUBREQUEST_WAITED
  364.  
  365. #if (NGX_HTTP_CACHE)
  366. unsigned cached:1;//如果客户端请求过来有读到缓存文件,则置1,见ngx_http_file_cache_read ngx_http_upstream_cache_send
  367. #endif
  368.  
  369. #if (NGX_HTTP_GZIP)
  370. unsigned gzip_tested:1;
  371. unsigned gzip_ok:1;
  372. unsigned gzip_vary:1;
  373. #endif
  374.  
  375. unsigned proxy:1;
  376. unsigned bypass_cache:1;
  377. unsigned no_cache:1;
  378.  
  379. /*
  380. * instead of using the request context data in
  381. * ngx_http_limit_conn_module and ngx_http_limit_req_module
  382. * we use the single bits in the request structure
  383. */
  384. unsigned limit_conn_set:1;
  385. unsigned limit_req_set:1;
  386.  
  387. #if 0
  388. unsigned cacheable:1;
  389. #endif
  390.  
  391. unsigned pipeline:1;
  392. //如果后端发送过来的头部行中不带有Content-length:xxx 这种情况1.1版本HTTP直接设置chunked为1, 见ngx_http_chunked_header_filter
  393. //如果后端带有Transfer-Encoding: chunked会置1
  394. unsigned chunked:1; //chunk编码方式组包实际组包过程参考ngx_http_chunked_body_filter
  395. //当下游的r->method == NGX_HTTP_HEAD请求方法只请求头部行,则会在ngx_http_header_filter中置1
  396. //HTTP2头部帧发送在ngx_http_v2_header_filter中置1
  397. unsigned header_only:1; //表示是否只有行、头部,没有包体 ngx_http_header_filter中置1
  398. //在1.0以上版本默认是长连接,1.0以上版本默认置1,如果在请求头里面没有设置连接方式,见ngx_http_handler
  399. //标志位,为1时表示当前请求是keepalive请求 1长连接 0短连接 长连接时间通过请求头部的Keep-Alive:设置,参考ngx_http_headers_in_t
  400. unsigned keepalive:1; //赋值见ngx_http_handler
  401. //延迟关闭标志位,为1时表示需要延迟关闭。例如,在接收完HTTP头部时如果发现包体存在,该标志位会设为1,而放弃接收包体时则会设为o
  402. unsigned lingering_close:1;
  403. //如果discard_body为1,则证明曾经执行过丢弃包体的方法,现在包体正在被丢弃中,见ngx_http_read_client_request_body
  404. unsigned discard_body:1;//标志住,为1时表示正在丢弃HTTP请求中的包体
  405. unsigned reading_body:1; //标记包体还没有读完,需要继续读取包体,见 ngx_http_read_client_request_body
  406.  
  407. /* 在这一步骤中,把phase_handler序号设为server_rewrite_index,这意味着无论之前执行到哪一个阶段,马上都要重新从NGX_HTTP_SERVER_REWRITE_PHASE
  408. 阶段开始再次执行,这是Nginx的请求可以反复rewrite重定向的基础。见ngx_http_handler */
  409. //ngx_http_internal_redirect置1 创建子请求的时候,子请求也要置1,见ngx_http_subrequest,所有子请求需要做重定向
  410. //内部重定向是从NGX_HTTP_SERVER_REWRITE_PHASE处继续执行(ngx_http_internal_redirect),而重新rewrite是从NGX_HTTP_FIND_CONFIG_PHASE处执行(ngx_http_core_post_rewrite_phase)
  411. unsigned internal:1;//t标志位,为1时表示请求的当前状态是在做内部跳转,
  412. unsigned error_page:1; //默认0,在ngx_http_special_response_handler中可能置1
  413. unsigned filter_finalize:1;
  414. unsigned post_action:1;//ngx_http_post_action中置1 默认为0,除非post_action XXX配置
  415. unsigned request_complete:1;
  416. unsigned request_output:1;//表示有数据需要往客户端发送,ngx_http_copy_filter中置1
  417. //为I时表示发送给客户端的HTTP响应头部已经发送。在调用ngx_http_send_header方法后,若已经成功地启动响应头部发送流程,
  418. //该标志位就会置为1,用来防止反复地发送头部
  419. unsigned header_sent:1;
  420. unsigned expect_tested:1;
  421. unsigned root_tested:1;
  422. unsigned done:1;
  423. unsigned logged:1;
  424. /* ngx_http_copy_filter中赋值 */
  425. unsigned buffered:4;//表示缓冲中是否有待发送内容的标志位,参考ngx_http_copy_filter
  426.  
  427. unsigned main_filter_need_in_memory:1;
  428. unsigned filter_need_in_memory:1;
  429. unsigned filter_need_temporary:1;
  430. unsigned allow_ranges:1; //支持断点续传 参考3.8.3节
  431. unsigned single_range:1;
  432. //
  433. unsigned disable_not_modified:1; //r->disable_not_modified = !u->cacheable;因此默认为0
  434.  
  435. #if (NGX_STAT_STUB)
  436. unsigned stat_reading:1;
  437. unsigned stat_writing:1;
  438. #endif
  439.  
  440. /* used to parse HTTP headers */ //状态机解析HTTP时使用state来表示当前的解析状态
  441. ngx_uint_t state; //解析状态,见ngx_http_parse_header_line
  442. //header_hash为Accept-Language:zh-cn中Accept-Language所有字符串做hash运算的结果
  443. ngx_uint_t header_hash; //头部行中一行所有内容计算ngx_hash的结构,参考ngx_http_parse_header_line
  444. //lowcase_index为Accept-Language:zh-cn中Accept-Language字符数,也就是15个字节
  445. ngx_uint_t lowcase_index; // 参考ngx_http_parse_header_line
  446. //存储Accept-Language:zh-cn中的Accept-Language字符串到lowcase_header。如果是AAA_BBB:CCC,则该数组存储的是_BBB
  447. u_char lowcase_header[NGX_HTTP_LC_HEADER_LEN]; //http头部内容,不包括应答行或者请求行,参考ngx_http_parse_header_line
  448.  
  449. /*
  450. 例如:Accept:image/gif.image/jpeg,**
  451. Accept对应于key,header_name_start header_name_end分别指向这个Accept字符串的头和尾
  452. image/gif.image/jpeg,** 为value部分,header_start header_end分别对应value的头和尾,可以参考mytest_upstream_process_header
  453. */
  454. //header_name_start指向Accept-Language:zh-cn中的A处
  455. u_char *header_name_start; //解析到的一行http头部行中的一行的name开始处 //赋值见ngx_http_parse_header_line
  456. //header_name_start指向Accept-Language:zh-cn中的:处
  457. u_char *header_name_end; //解析到的一行http头部行中的一行的name的尾部 //赋值见ngx_http_parse_header_line
  458. u_char *header_start;//header_start指向Accept-Language:zh-cn中的z字符处
  459. u_char *header_end;//header_end指向Accept-Language:zh-cn中的末尾换行处
  460.  
  461. /*
  462. * a memory that can be reused after parsing a request line
  463. * via ngx_http_ephemeral_t
  464. */
  465.  
  466. //ngx_str_t类型的uri成员指向用户请求中的URI。同理,u_char*类型的uri_start和uri_end也与request_start、request_end的用法相似,唯一不
  467. //同的是,method_end指向方法名的最后一个字符,而uri_end指向URI结束后的下一个地址,也就是最后一个字符的下一个字符地址(HTTP框架的行为),
  468. //这是大部分u_char*类型指针对“xxx_start”和“xxx_end”变量的用法。
  469. u_char *uri_start;//HTTP2的赋值见ngx_http_v2_parse_path
  470. u_char *uri_end;//HTTP2的赋值见ngx_http_v2_parse_path
  471.  
  472. /*
  473. ngx_str_t类型的extern成员指向用户请求的文件扩展名。例如,在访问“GET /a.txt HTTP/1.1”时,extern的值是{len = 3, data = "txt"},
  474. 而在访问“GET /a HTTP/1.1”时,extern的值为空,也就是{len = 0, data = 0x0}。
  475. uri_ext指针指向的地址与extern.data相同。
  476. */ //GET /sample.jsp HTTP/1.1 后面的文件如果有.字符,则指向该.后面的jsp字符串,表示文件扩展名
  477. u_char *uri_ext;
  478. //"GET /aaaaaaaa?bbbb.txt HTTP/1.1"中的bbb.txt字符串头位置处
  479. u_char *args_start;//args_start指向URL参数的起始地址,配合uri_end使用也可以获得URL参数。
  480.  
  481. /* 通过request_start和request_end可以获得用户完整的请求行 */
  482. u_char *request_start; //请求行开始处
  483. u_char *request_end; //请求行结尾处
  484. u_char *method_end; //GET POST字符串结尾处
  485.  
  486. //HTTP2的赋值见ngx_http_v2_parse_scheme
  487. u_char *schema_start;
  488. u_char *schema_end;
  489. u_char *host_start;
  490. u_char *host_end;
  491. u_char *port_start;
  492. u_char *port_end;
  493.  
  494. // HTTP/1.1前面的1代表major,后面的1代表minor
  495. unsigned http_minor:16;
  496. unsigned http_major:16;
  497. };

http server发送响应到请求端处理

  1. //发送后端返回回来的数据给客户端。里面会处理header,body分开发送的情况的
  2. static void
  3. ngx_http_upstream_send_response(ngx_http_request_t *r, ngx_http_upstream_t *u)
  4. {
  5. int tcp_nodelay;
  6. ssize_t n;
  7. ngx_int_t rc;
  8. ngx_event_pipe_t *p;
  9. ngx_connection_t *c;
  10. ngx_http_core_loc_conf_t *clcf;
  11. int flag;
  12. time_t now, valid;
  13.  
  14. rc = ngx_http_send_header(r);//先发header,再发body //调用每一个filter过滤,处理头部数据。最后将数据发送给客户端。调用ngx_http_top_header_filter
  15.  
  16. if (rc == NGX_ERROR || rc > NGX_OK || r->post_action) {
  17. ngx_http_upstream_finalize_request(r, u, rc);
  18. return;
  19. }
  20.  
  21. u->header_sent = 1;//标记已经发送了头部字段,至少是已经挂载出去,经过了filter了。
  22.  
  23. if (u->upgrade) {
  24. ngx_http_upstream_upgrade(r, u);
  25. return;
  26. }
  27. c = r->connection;
  28. if (r->header_only) {//如果只需要发送头部数据,比如客户端用curl -I 访问的。返回204状态码即可。
  29. if (!u->buffering) { //配置不需要缓存包体,或者后端要求不配置缓存包体,直接结束
  30. ngx_http_upstream_finalize_request(r, u, rc);
  31. return;
  32. }
  33. if (!u->cacheable && !u->store) { //如果定义了#if (NGX_HTTP_CACHE)则可能置1
  34. ngx_http_upstream_finalize_request(r, u, rc);
  35. return;
  36. }
  37. u->pipe->downstream_error = 1; //命名客户端只请求头部行,但是上游雀配置或者要求缓存或者存储包体
  38. }
  39. if (r->request_body && r->request_body->temp_file) { //客户端发送过来的包体存储在临时文件中,则需要把存储临时文件删除
  40. ngx_pool_run_cleanup_file(r->pool, r->request_body->temp_file->file.fd);
  41. //之前临时文件内容已经不需要了,因为在ngx_http_fastcgi_create_request(ngx_http_xxx_create_request)中已经把临时文件中的内容
  42. //赋值给u->request_bufs并通过发送到了后端服务器,现在需要发往客户端的内容为上游应答回来的包体,因此此临时文件内容已经没用了
  43. r->request_body->temp_file->file.fd = NGX_INVALID_FILE;
  44. }
  45. clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
  46. /*
  47. 如果开启缓冲,那么Nginx将尽可能多地读取后端服务器的响应数据,等达到一定量(比如buffer满)再传送给最终客户端。如果关闭,
  48. 那么Nginx对数据的中转就是一个同步的过程,即从后端服务器接收到响应数据就立即将其发送给客户端。
  49. */
  50. flag = u->buffering;
  51. ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0, "ngx_http_upstream_send_response, buffering flag:%d", flag);
  52. if (!u->buffering) {
  53. //buffering为1,表示上游来的包体先缓存上游发送来的包体,然后在发送到下游,如果该值为0,则接收多少上游包体就向下游转发多少包体
  54.  
  55. if (u->input_filter == NULL) { //如果input_filter为空,则设置默认的filter,然后准备发送数据到客户端。然后试着读读FCGI
  56. u->input_filter_init = ngx_http_upstream_non_buffered_filter_init;
  57. //ngx_http_upstream_non_buffered_filter将u->buffer.last - u->buffer.pos之间的数据放到u->out_bufs发送缓冲去链表里面。
  58. //根据具体的到上游转发的方式,选择使用fastcgi memcached等,ngx_http_xxx_filter
  59. u->input_filter = ngx_http_upstream_non_buffered_filter; //一般就设置为这个默认的,memcache为ngx_http_memcached_filter
  60. u->input_filter_ctx = r;
  61. }
  62. //设置upstream的读事件回调,设置客户端连接的写事件回调。
  63. u->read_event_handler = ngx_http_upstream_process_non_buffered_upstream;
  64. r->write_event_handler =
  65. ngx_http_upstream_process_non_buffered_downstream;//调用过滤模块一个个过滤body,最终发送出去。
  66. r->limit_rate = 0;
  67. //ngx_http_XXX_input_filter_init(如ngx_http_fastcgi_input_filter_init ngx_http_proxy_input_filter_init ngx_http_proxy_input_filter_init)
  68. //只有memcached会执行ngx_http_memcached_filter_init,其他方式什么也没做
  69. if (u->input_filter_init(u->input_filter_ctx) == NGX_ERROR) {
  70. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  71. return;
  72. }
  73. if (clcf->tcp_nodelay && c->tcp_nodelay == NGX_TCP_NODELAY_UNSET) {
  74. ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0, "tcp_nodelay");
  75. tcp_nodelay = 1;
  76. if (setsockopt(c->fd, IPPROTO_TCP, TCP_NODELAY,
  77. (const void *) &tcp_nodelay, sizeof(int)) == -1)
  78. {
  79. ngx_connection_error(c, ngx_socket_errno,
  80. "setsockopt(TCP_NODELAY) failed");
  81. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  82. return;
  83. }
  84. c->tcp_nodelay = NGX_TCP_NODELAY_SET;
  85. }
  86. n = u->buffer.last - u->buffer.pos;
  87.  
  88. /*
  89. 不是还没接收包体嘛,为什么就开始发送了呢? 这是因为在前面的ngx_http_upstream_process_header接收fastcgi头部行标识包体处理的时候,有可能会把一部分fastcgi包体标识也收过了,
  90. 因此需要处理
  91. */
  92. if (n) {//得到将要发送的数据的大小,每次有多少就发送多少。不等待upstream了 因为这是不缓存方式发送包体到客户端
  93. u->buffer.last = u->buffer.pos;
  94. u->state->response_length += n;//统计请求的返回包体数据(不包括请求行)长度。
  95. //下面input_filter只是简单的拷贝buffer上面的数据总共n长度的,到u->out_bufs里面去,以待发送。
  96. //ngx_http_xxx_non_buffered_filter(如ngx_http_fastcgi_non_buffered_filter)
  97. if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  98. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  99. return;
  100. }
  101. ngx_http_upstream_process_non_buffered_downstream(r);
  102. } else {
  103. u->buffer.pos = u->buffer.start;
  104. u->buffer.last = u->buffer.start;
  105. if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {
  106. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  107. return;
  108. }
  109.         /------------/u->peer.connection->read->ready == 1 (size==n)
  110. if (u->peer.connection->read->ready || u->length == 0) {
  111. ngx_http_upstream_process_non_buffered_upstream(r, u);
  112. }
  113. }
  114.  
  115. return; //这里会返回回去
  116. }
  117. /* TODO: preallocate event_pipe bufs, look "Content-Length" */
  118.  
  119. ----------------------------
  120. ----------------------------
  121. p->preread_bufs = ngx_alloc_chain_link(r->pool);
  122. if (p->preread_bufs == NULL) {
  123. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  124. return;
  125. }
  126. p->preread_bufs->buf = &u->buffer; //把包体部分的pos和last存储到p->preread_bufs->buf
  127. p->preread_bufs->next = NULL;
  128. u->buffer.recycled = 1;
  129. //之前读取后端头部行信息的时候的buf还有剩余数据,这部分数据就是包体数据,也就是读取头部行fastcgi标识信息的时候把部分包体数据读取了
  130. p->preread_size = u->buffer.last - u->buffer.pos;
  131. if (u->cacheable) { //注意走到这里的时候,前面已经把后端头部行信息解析出来了,u->buffer.pos指向的是实际数据部分
  132. p->buf_to_file = ngx_calloc_buf(r->pool);
  133. if (p->buf_to_file == NULL) {
  134. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  135. return;
  136. }
  137. //指向的是为获取后端头部行的时候分配的第一个缓冲区,buf大小由xxx_buffer_size(fastcgi_buffer_size proxy_buffer_size memcached_buffer_size)指定
  138. /*
  139. 这里面只存储了头部行buffer中头部行的内容部分,因为后面写临时文件的时候,需要把后端头部行也写进来,由于前面读取头部行后指针已经指向了数据部分
  140. 因此需要临时用buf_to_file->start指向头部行部分开始,pos指向数据部分开始,也就是头部行部分结尾
  141. */
  142. p->buf_to_file->start = u->buffer.start;
  143. p->buf_to_file->pos = u->buffer.start;
  144. p->buf_to_file->last = u->buffer.pos;
  145. p->buf_to_file->temporary = 1;
  146. }
  147. -----------------------------------
  148. //buffering方式,后端头部信息已经读取完毕了,如果后端还有包体需要发送,则本端通过该方式读取
  149. u->read_event_handler = ngx_http_upstream_process_upstream;
  150. r->write_event_handler = ngx_http_upstream_process_downstream; //当可写事件促发的时候,通过该函数继续写数据
  151. ngx_http_upstream_process_upstream(r, u);
  152. }

处理响应包体转发

  1. /*
  2. ngx_http_upstream_send_response发送完HERDER后,如果是非缓冲模式,会调用这里将数据发送出去的。
  3. 这个函数实际上判断一下超时后,就调用ngx_http_upstream_process_non_buffered_request了。nginx老方法。
  4. */
  5. static void
  6. //buffring模式通过ngx_http_upstream_process_upstream该函数处理,非buffring模式通过ngx_http_upstream_process_non_buffered_downstream处理
  7. ngx_http_upstream_process_non_buffered_downstream(ngx_http_request_t *r)
  8. {
  9. ngx_event_t *wev;
  10. ngx_connection_t *c;
  11. ngx_http_upstream_t *u;
  12.  
  13. c = r->connection;
  14. u = r->upstream;
  15. wev = c->write;
  16.  
  17. ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  18. "http upstream process non buffered downstream");
  19.  
  20. c->log->action = "sending to client";
  21.  
  22. if (wev->timedout) {
  23. c->timedout = 1;
  24. ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");
  25. ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  26. return;
  27. }
  28.  
  29. //下面开始将out_bufs里面的数据发送出去,然后读取数据,然后发送,如此循环。
  30. ngx_http_upstream_process_non_buffered_request(r, 1);
  31. }
  1. /*
  2. 调用过滤模块,将数据发送出去,do_write为是否要给客户端发送数据。
  3. 1.如果要发送,就调用ngx_http_output_filter将数据发送出去。
  4. 2.然后ngx_unix_recv读取数据,放入out_bufs里面去。如此循环
  5. */
  6. static void
  7. ngx_http_upstream_process_non_buffered_request(ngx_http_request_t *r,
  8. ngx_uint_t do_write)
  9. {
  10. size_t size;
  11. ssize_t n;
  12. ngx_buf_t *b;
  13. ngx_int_t rc;
  14. ngx_connection_t *downstream, *upstream;
  15. ngx_http_upstream_t *u;
  16. ngx_http_core_loc_conf_t *clcf;
  17. u = r->upstream;
  18. downstream = r->connection;//找到这个请求的客户端连接
  19. upstream = u->peer.connection;//找到上游的连接
  20. b = &u->buffer; //找到这坨要发送的数据,不过大部分都被input filter放到out_bufs里面去了。
  21.  
  22. do_write = do_write || u->length == 0; //do_write为1时表示要立即发送给客户端。
  23.  
  24. for ( ;; ) {
  25.  
  26. if (do_write) { //要立即发送。
  27. //out_bufs中的数据是从ngx_http_fastcgi_non_buffered_filter获取
  28. if (u->out_bufs || u->busy_bufs) {
  29. //如果u->out_bufs不为NULL则说明有需要发送的数据,这是u->input_filter_init(u->input_filter_ctx)(ngx_http_upstream_non_buffered_filter)拷贝到这里的。
  30. //u->busy_bufs代表是在读取fastcgi请求头的时候,可能里面会带有包体数据,就是通过这里发送
  31. rc = ngx_http_output_filter(r, u->out_bufs);
  32.  
  33. if (rc == NGX_ERROR) {
  34. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  35. return;
  36. }
  37.  
  38. //就是把ngx_http_output_filter调用后未发送完毕的数据buf添加到busy_bufs中,如果下次再次调用ngx_http_output_filter后把busy_bufs中上一次没有发送完的发送出去了,则把对应的buf移除添加到free中
  39. //下面将out_bufs的元素移动到busy_bufs的后面;将已经发送完毕的busy_bufs链表元素移动到free_bufs里面
  40. ngx_chain_update_chains(r->pool, &u->free_bufs, &u->busy_bufs,
  41. &u->out_bufs, u->output.tag);
  42. }
  43.  
  44. if (u->busy_bufs == NULL) {//busy_bufs没有了,都发完了。想要发送的数据都已经发送完毕
  45.  
  46. if (u->length == 0
  47. || (upstream->read->eof && u->length == -1)) //包体数据已经读完了
  48. {
  49. ngx_http_upstream_finalize_request(r, u, 0);
  50. return;
  51. }
  52. if (upstream->read->eof) {
  53. ngx_log_error(NGX_LOG_ERR, upstream->log, 0,
  54. "upstream prematurely closed connection");
  55.  
  56. ngx_http_upstream_finalize_request(r, u,
  57. NGX_HTTP_BAD_GATEWAY);
  58. return;
  59. }
  60.  
  61. if (upstream->read->error) {
  62. ngx_http_upstream_finalize_request(r, u,
  63. NGX_HTTP_BAD_GATEWAY);
  64. return;
  65. }
  66. b->pos = b->start;//重置u->buffer,以便与下次使用,从开始起。b指向的空间可以继续读数据了
  67. b->last = b->start;
  68. }
  69. }
  70. size = b->end - b->last;//得到当前buf的剩余空间
  71. if (size && upstream->read->ready) {
  72. //为什么可能走到这里?因为在 ngx_http_upstream_process_header 中读取后端数据的时候,buf大小默认为页面大小ngx_pagesize
  73. //单有可能后端发送过来的数据比ngx_pagesize大,因此就没有读完,也就是recv中不会吧ready置0,所以这里可以继续读
  74. ngx_http_upstream_process_header
  75. n = upstream->recv(upstream, b->last, size);
  76. if (n == NGX_AGAIN) { //说明已经内核缓冲区数据已经读完,退出循环,然后根据epoll事件来继续触发读取后端数据
  77. break;
  78. }
  79. if (n > 0) {
  80. u->state->response_length += n;
  81.  
  82. if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  83. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  84. return;
  85. }
  86. }
  87. do_write = 1;//因为刚刚无论如何n大于0,所以读取了数据,那么下一个循环会将out_bufs的数据发送出去的。
  88. continue;
  89. }
  90.  
  91. break;
  92. }
  93.  
  94. clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
  95.  
  96. if (downstream->data == r) {
  97. if (ngx_handle_write_event(downstream->write, clcf->send_lowat, NGX_FUNC_LINE)
  98. != NGX_OK)
  99. {
  100. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  101. return;
  102. }
  103. }
  104.  
  105. if (downstream->write->active && !downstream->write->ready) {
  106. //例如我把数据把数据写到内核协议栈到写满协议栈缓存,但是对端一直不读取的时候,数据一直发不出去了,也不会触发epoll_wait写事件,
  107. //这里加个定时器就是为了避免这种情况发生
  108. ngx_add_timer(downstream->write, clcf->send_timeout, NGX_FUNC_LINE);
  109. } else if (downstream->write->timer_set) {
  110. ngx_del_timer(downstream->write, NGX_FUNC_LINE);
  111. }
  112.  
  113. if (ngx_handle_read_event(upstream->read, 0, NGX_FUNC_LINE) != NGX_OK) { //epoll在accept的时候读写已经加入epoll中,因此对epoll来说没用
  114. ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  115. return;
  116. }
  117.  
  118. if (upstream->read->active && !upstream->read->ready) {
  119. ngx_add_timer(upstream->read, u->conf->read_timeout, NGX_FUNC_LINE);
  120. } else if (upstream->read->timer_set) {
  121. ngx_del_timer(upstream->read, NGX_FUNC_LINE);
  122. }
  123. }
  1.  
  1.  

http代理阅读4 响应缓存处理的更多相关文章

  1. Asp.Net Core 2.1+的视图缓存(响应缓存)

    响应缓存Razor 页与 ASP.NET 核心 2.0 中不支持. 此功能将支持ASP.NET 核心 2.1 版本. 在老的版本的MVC里面,有一种可以缓存视图的特性(OutputCache),可以保 ...

  2. 详解Asp.Net Core 2.1+的视图缓存(响应缓存)

    响应缓存Razor 页与 ASP.NET 核心 2.0 中不支持. 此功能将支持ASP.NET 核心 2.1 版本. 在老的版本的MVC里面,有一种可以缓存视图的特性(OutputCache),可以保 ...

  3. http 代理阅读1

    代理模式数据流处理: //配置proxy_pass后,在 ngx_http_core_content_phase 里面指向该函数 /* 那么,当有请求访问到特定的location的时候(假设这个loc ...

  4. http代理阅读3 发送mem处理

    每次客户端有可读数据触发时,优先检测是否还有数据没有发送,如果有则发送数据,然后在读取client数据 //向后端发送请求的调用过程 //ngx_http_upstream_send_request_ ...

  5. Nginx反向代理 负载均衡 页面缓存 URL重写及读写分离

    大纲 一.前言 二.环境准备 三.安装与配置Nginx 四.Nginx之反向代理 五.Nginx之负载均衡 六.Nginx之页面缓存 七.Nginx之URL重写 八.Nginx之读写分离 注,操作系统 ...

  6. Nginx特性验证-反向代理/负载均衡/页面缓存/URL重定向

    原文发表于cu:2016-08-25 参考文档: Nginx 反向代理.负载均衡.页面缓存.URL重写等:http://freeloda.blog.51cto.com/2033581/1288553 ...

  7. .net core响应缓存

    按照官网资料操作无效,这里使用https://github.com/speige/AspNetCore.ResponseCaching.Extensions的扩展包 安装AspNetCore.Resp ...

  8. http代理阅读2

    向上游服务器发送请求处理 static void ngx_http_upstream_send_request(ngx_http_request_t *r, ngx_http_upstream_t * ...

  9. 巧用Fiddler代理来禁止资源缓存,从而达到每次都是从服务器加载最新的资源

    Fiddler ->  Rules ->  Performance  -> Disable Caching 直接设置禁用缓存,再在没有清除缓存功能的APP 中重新加载最新的页面, 每 ...

随机推荐

  1. element Ui的级联选择器 任意一级选中下拉框自动关闭

    封装成一个子组件 <template> <el-cascader v-model="value" clearable placeholder="请选择& ...

  2. protoc-c 阅读笔记

    以前和山哥做过类似的,最近想起来,抽空又看了下 protoc-c. 山哥做的报文流向: rpc -> lydtree -> motree -> struct 涉及的细节很多 1) l ...

  3. golang API 请求队列

    概要 实现思路 使用方法 启动队列服务 使用队列服务 概要 在调用第三方 API 的时候, 基本都有访问限速的限制条件. 第三方的 API 有多个的时候, 就不太好控制访问速度, 常常会导致 HTTP ...

  4. 扫描仪扫描文件处理-Python批量处理

    多进程处理扫描出来的图片,参见: https://github.com/barrer/scan-helper bug问题反馈github提Issues

  5. 理解Go协程与并发(转)

    理解Go协程与并发   协程 Go语言里创建一个协程很简单,使用go关键字就可以让一个普通方法协程化: Copy package main import ( "fmt" " ...

  6. 第三章 虚拟机的简单使用及其xshell远程工具的使用

    一.虚拟机的快照 1.虚拟机的几种状态: 开机状态 === 运行状态 关机状态 挂起状态 === 虚拟机不关机,但是你使用不了 定身术 快照就是虚拟机的某种状态 === 月光宝盒 2.快照分类: 开机 ...

  7. dubbo配置加载优先级

    优先级从高到低: JVM 启动 -D 参数优先,这样可以使用户在部署和启动时进行参数重写,比如在启动时需改变协议的端口: XML 次之,如果在 XML 中有配置,则 dubbo.properties ...

  8. 1024|推荐一个开源免费的Spring Boot教程

    2020-1024=996! 今天,星期六,你们是否加班了?我反正加了!早上去公司开了一早上会,中午回家写下了这篇文章. 今天,我要推荐一个开源免费的Spring Boot项目,就是我最近日更的Spr ...

  9. 5年Android程序员面试字节跳动两轮后被完虐,请查收给你的面试指南

    大家应该看过很多分享面试成功的经验,但根据幸存者偏差的理论,也许多看看别人面试失败在哪里,对自己才更有帮助. 最近跟一个朋友聊天,他准备了几个月,刚刚参加完字节跳动面试,第二面结束后,嗯,挂了- 所以 ...

  10. 通过express快速搭建一个node服务

    Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台.可以理解为是运行在服务端的 JavaScript.如果你是一个前端程序员,不太擅长像PHP.Python或Ruby等 ...