src/http/ngx_http_upstream.c - nginx-1.31.9 nginx/ @ 2a3a19c6f

Global variables defined

Functions defined

Source code


  1. /*
  2. * Copyright (C) Igor Sysoev
  3. * Copyright (C) Nginx, Inc.
  4. */


  5. #include <ngx_config.h>
  6. #include <ngx_core.h>
  7. #include <ngx_http.h>


  8. #if (NGX_HTTP_CACHE)
  9. static ngx_int_t ngx_http_upstream_cache(ngx_http_request_t *r,
  10.     ngx_http_upstream_t *u);
  11. static ngx_int_t ngx_http_upstream_cache_get(ngx_http_request_t *r,
  12.     ngx_http_upstream_t *u, ngx_http_file_cache_t **cache);
  13. static ngx_int_t ngx_http_upstream_cache_send(ngx_http_request_t *r,
  14.     ngx_http_upstream_t *u);
  15. static ngx_int_t ngx_http_upstream_cache_background_update(
  16.     ngx_http_request_t *r, ngx_http_upstream_t *u);
  17. static ngx_int_t ngx_http_upstream_cache_check_range(ngx_http_request_t *r,
  18.     ngx_http_upstream_t *u);
  19. static ngx_int_t ngx_http_upstream_cache_status(ngx_http_request_t *r,
  20.     ngx_http_variable_value_t *v, uintptr_t data);
  21. static ngx_int_t ngx_http_upstream_cache_last_modified(ngx_http_request_t *r,
  22.     ngx_http_variable_value_t *v, uintptr_t data);
  23. static ngx_int_t ngx_http_upstream_cache_etag(ngx_http_request_t *r,
  24.     ngx_http_variable_value_t *v, uintptr_t data);
  25. #endif

  26. static void ngx_http_upstream_init_request(ngx_http_request_t *r);
  27. static void ngx_http_upstream_resolve_handler(ngx_resolver_ctx_t *ctx);
  28. static void ngx_http_upstream_rd_check_broken_connection(ngx_http_request_t *r);
  29. static void ngx_http_upstream_wr_check_broken_connection(ngx_http_request_t *r);
  30. static void ngx_http_upstream_check_broken_connection(ngx_http_request_t *r,
  31.     ngx_event_t *ev);
  32. static void ngx_http_upstream_connect(ngx_http_request_t *r,
  33.     ngx_http_upstream_t *u);
  34. static ngx_int_t ngx_http_upstream_reinit(ngx_http_request_t *r,
  35.     ngx_http_upstream_t *u);
  36. static void ngx_http_upstream_send_request(ngx_http_request_t *r,
  37.     ngx_http_upstream_t *u, ngx_uint_t do_write);
  38. static ngx_int_t ngx_http_upstream_send_request_body(ngx_http_request_t *r,
  39.     ngx_http_upstream_t *u, ngx_uint_t do_write);
  40. static void ngx_http_upstream_send_request_handler(ngx_http_request_t *r,
  41.     ngx_http_upstream_t *u);
  42. static void ngx_http_upstream_read_request_handler(ngx_http_request_t *r);
  43. static void ngx_http_upstream_process_header(ngx_http_request_t *r,
  44.     ngx_http_upstream_t *u);
  45. static ngx_int_t ngx_http_upstream_process_early_hints(ngx_http_request_t *r,
  46.     ngx_http_upstream_t *u);
  47. static void ngx_http_upstream_early_hints_writer(ngx_http_request_t *r);
  48. static ngx_int_t ngx_http_upstream_test_next(ngx_http_request_t *r,
  49.     ngx_http_upstream_t *u);
  50. static ngx_int_t ngx_http_upstream_intercept_errors(ngx_http_request_t *r,
  51.     ngx_http_upstream_t *u);
  52. static ngx_int_t ngx_http_upstream_test_connect(ngx_connection_t *c);
  53. static ngx_int_t ngx_http_upstream_process_headers(ngx_http_request_t *r,
  54.     ngx_http_upstream_t *u);
  55. static ngx_int_t ngx_http_upstream_process_trailers(ngx_http_request_t *r,
  56.     ngx_http_upstream_t *u);
  57. static void ngx_http_upstream_send_response(ngx_http_request_t *r,
  58.     ngx_http_upstream_t *u);
  59. static void ngx_http_upstream_upgrade(ngx_http_request_t *r,
  60.     ngx_http_upstream_t *u);
  61. static void ngx_http_upstream_upgraded_read_downstream(ngx_http_request_t *r);
  62. static void ngx_http_upstream_upgraded_write_downstream(ngx_http_request_t *r);
  63. static void ngx_http_upstream_upgraded_read_upstream(ngx_http_request_t *r,
  64.     ngx_http_upstream_t *u);
  65. static void ngx_http_upstream_upgraded_write_upstream(ngx_http_request_t *r,
  66.     ngx_http_upstream_t *u);
  67. static void ngx_http_upstream_process_upgraded(ngx_http_request_t *r,
  68.     ngx_uint_t from_upstream, ngx_uint_t do_write);
  69. static void
  70.     ngx_http_upstream_process_non_buffered_downstream(ngx_http_request_t *r);
  71. static void
  72.     ngx_http_upstream_process_non_buffered_upstream(ngx_http_request_t *r,
  73.     ngx_http_upstream_t *u);
  74. static void
  75.     ngx_http_upstream_process_non_buffered_request(ngx_http_request_t *r,
  76.     ngx_uint_t do_write);
  77. #if (NGX_THREADS)
  78. static ngx_int_t ngx_http_upstream_thread_handler(ngx_thread_task_t *task,
  79.     ngx_file_t *file);
  80. static void ngx_http_upstream_thread_event_handler(ngx_event_t *ev);
  81. #endif
  82. static ngx_int_t ngx_http_upstream_output_filter(void *data,
  83.     ngx_chain_t *chain);
  84. static void ngx_http_upstream_process_downstream(ngx_http_request_t *r);
  85. static void ngx_http_upstream_process_upstream(ngx_http_request_t *r,
  86.     ngx_http_upstream_t *u);
  87. static void ngx_http_upstream_process_request(ngx_http_request_t *r,
  88.     ngx_http_upstream_t *u);
  89. static void ngx_http_upstream_store(ngx_http_request_t *r,
  90.     ngx_http_upstream_t *u);
  91. static void ngx_http_upstream_dummy_handler(ngx_http_request_t *r,
  92.     ngx_http_upstream_t *u);
  93. static void ngx_http_upstream_next(ngx_http_request_t *r,
  94.     ngx_http_upstream_t *u, ngx_uint_t ft_type);
  95. static void ngx_http_upstream_cleanup(void *data);
  96. static void ngx_http_upstream_finalize_request(ngx_http_request_t *r,
  97.     ngx_http_upstream_t *u, ngx_int_t rc);

  98. static ngx_int_t ngx_http_upstream_process_header_line(ngx_http_request_t *r,
  99.     ngx_table_elt_t *h, ngx_uint_t offset);
  100. static ngx_int_t
  101.     ngx_http_upstream_process_multi_header_lines(ngx_http_request_t *r,
  102.     ngx_table_elt_t *h, ngx_uint_t offset);
  103. static ngx_int_t ngx_http_upstream_process_content_length(ngx_http_request_t *r,
  104.     ngx_table_elt_t *h, ngx_uint_t offset);
  105. static ngx_int_t ngx_http_upstream_process_last_modified(ngx_http_request_t *r,
  106.     ngx_table_elt_t *h, ngx_uint_t offset);
  107. static ngx_int_t ngx_http_upstream_process_set_cookie(ngx_http_request_t *r,
  108.     ngx_table_elt_t *h, ngx_uint_t offset);
  109. static ngx_int_t
  110.     ngx_http_upstream_process_cache_control(ngx_http_request_t *r,
  111.     ngx_table_elt_t *h, ngx_uint_t offset);
  112. #if (NGX_HTTP_CACHE)
  113. static ngx_int_t ngx_http_upstream_process_delta_seconds(u_char *p,
  114.     u_char *last);
  115. #endif
  116. static ngx_int_t ngx_http_upstream_ignore_header_line(ngx_http_request_t *r,
  117.     ngx_table_elt_t *h, ngx_uint_t offset);
  118. static ngx_int_t ngx_http_upstream_process_expires(ngx_http_request_t *r,
  119.     ngx_table_elt_t *h, ngx_uint_t offset);
  120. static ngx_int_t ngx_http_upstream_process_accel_expires(ngx_http_request_t *r,
  121.     ngx_table_elt_t *h, ngx_uint_t offset);
  122. static ngx_int_t ngx_http_upstream_process_limit_rate(ngx_http_request_t *r,
  123.     ngx_table_elt_t *h, ngx_uint_t offset);
  124. static ngx_int_t ngx_http_upstream_process_buffering(ngx_http_request_t *r,
  125.     ngx_table_elt_t *h, ngx_uint_t offset);
  126. static ngx_int_t ngx_http_upstream_process_charset(ngx_http_request_t *r,
  127.     ngx_table_elt_t *h, ngx_uint_t offset);
  128. static ngx_int_t ngx_http_upstream_process_connection(ngx_http_request_t *r,
  129.     ngx_table_elt_t *h, ngx_uint_t offset);
  130. static ngx_int_t
  131.     ngx_http_upstream_process_transfer_encoding(ngx_http_request_t *r,
  132.     ngx_table_elt_t *h, ngx_uint_t offset);
  133. static ngx_int_t ngx_http_upstream_process_vary(ngx_http_request_t *r,
  134.     ngx_table_elt_t *h, ngx_uint_t offset);
  135. static ngx_int_t ngx_http_upstream_process_priority(ngx_http_request_t *r,
  136.     ngx_table_elt_t *h, ngx_uint_t offset);
  137. static ngx_int_t ngx_http_upstream_copy_header_line(ngx_http_request_t *r,
  138.     ngx_table_elt_t *h, ngx_uint_t offset);
  139. static ngx_int_t
  140.     ngx_http_upstream_copy_multi_header_lines(ngx_http_request_t *r,
  141.     ngx_table_elt_t *h, ngx_uint_t offset);
  142. static ngx_int_t ngx_http_upstream_copy_content_type(ngx_http_request_t *r,
  143.     ngx_table_elt_t *h, ngx_uint_t offset);
  144. static ngx_int_t ngx_http_upstream_copy_last_modified(ngx_http_request_t *r,
  145.     ngx_table_elt_t *h, ngx_uint_t offset);
  146. static ngx_int_t ngx_http_upstream_rewrite_location(ngx_http_request_t *r,
  147.     ngx_table_elt_t *h, ngx_uint_t offset);
  148. static ngx_int_t ngx_http_upstream_rewrite_refresh(ngx_http_request_t *r,
  149.     ngx_table_elt_t *h, ngx_uint_t offset);
  150. static ngx_int_t ngx_http_upstream_rewrite_set_cookie(ngx_http_request_t *r,
  151.     ngx_table_elt_t *h, ngx_uint_t offset);
  152. static ngx_int_t ngx_http_upstream_copy_allow_ranges(ngx_http_request_t *r,
  153.     ngx_table_elt_t *h, ngx_uint_t offset);
  154. static ngx_int_t ngx_http_upstream_copy_upgrade(ngx_http_request_t *r,
  155.     ngx_table_elt_t *h, ngx_uint_t offset);

  156. static ngx_int_t ngx_http_upstream_add_variables(ngx_conf_t *cf);
  157. static ngx_int_t ngx_http_upstream_addr_variable(ngx_http_request_t *r,
  158.     ngx_http_variable_value_t *v, uintptr_t data);
  159. static ngx_int_t ngx_http_upstream_status_variable(ngx_http_request_t *r,
  160.     ngx_http_variable_value_t *v, uintptr_t data);
  161. static ngx_int_t ngx_http_upstream_response_time_variable(ngx_http_request_t *r,
  162.     ngx_http_variable_value_t *v, uintptr_t data);
  163. static ngx_int_t ngx_http_upstream_response_length_variable(
  164.     ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data);
  165. static ngx_int_t ngx_http_upstream_header_variable(ngx_http_request_t *r,
  166.     ngx_http_variable_value_t *v, uintptr_t data);
  167. static ngx_int_t ngx_http_upstream_trailer_variable(ngx_http_request_t *r,
  168.     ngx_http_variable_value_t *v, uintptr_t data);
  169. static ngx_int_t ngx_http_upstream_cookie_variable(ngx_http_request_t *r,
  170.     ngx_http_variable_value_t *v, uintptr_t data);

  171. static char *ngx_http_upstream(ngx_conf_t *cf, ngx_command_t *cmd, void *dummy);
  172. static char *ngx_http_upstream_server(ngx_conf_t *cf, ngx_command_t *cmd,
  173.     void *conf);
  174. #if (NGX_HTTP_UPSTREAM_ZONE)
  175. static char *ngx_http_upstream_resolver(ngx_conf_t *cf, ngx_command_t *cmd,
  176.     void *conf);
  177. #endif

  178. static ngx_int_t ngx_http_upstream_set_local(ngx_http_request_t *r,
  179.   ngx_http_upstream_t *u, ngx_http_upstream_local_t *local);

  180. static void *ngx_http_upstream_create_main_conf(ngx_conf_t *cf);
  181. static char *ngx_http_upstream_init_main_conf(ngx_conf_t *cf, void *conf);

  182. #if (NGX_HTTP_SSL)
  183. static void ngx_http_upstream_ssl_init_connection(ngx_http_request_t *,
  184.     ngx_http_upstream_t *u, ngx_connection_t *c);
  185. static void ngx_http_upstream_ssl_handshake_handler(ngx_connection_t *c);
  186. static void ngx_http_upstream_ssl_handshake(ngx_http_request_t *,
  187.     ngx_http_upstream_t *u, ngx_connection_t *c);
  188. static void ngx_http_upstream_ssl_save_session(ngx_connection_t *c);
  189. static ngx_int_t ngx_http_upstream_ssl_name(ngx_http_request_t *r,
  190.     ngx_http_upstream_t *u, ngx_connection_t *c);
  191. static ngx_int_t ngx_http_upstream_ssl_certificate(ngx_http_request_t *r,
  192.     ngx_http_upstream_t *u, ngx_connection_t *c);
  193. #endif


  194. ‌static ngx_http_upstream_header_t  ngx_http_upstream_headers_in[] = {

  195.     { ngx_string("Status"),
  196.                  ngx_http_upstream_process_header_line,
  197.                  offsetof(ngx_http_upstream_headers_in_t, status),
  198.                  ngx_http_upstream_copy_header_line, 0, 0 },

  199.     { ngx_string("Content-Type"),
  200.                  ngx_http_upstream_process_header_line,
  201.                  offsetof(ngx_http_upstream_headers_in_t, content_type),
  202.                  ngx_http_upstream_copy_content_type, 0, 1 },

  203.     { ngx_string("Content-Length"),
  204.                  ngx_http_upstream_process_content_length, 0,
  205.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  206.     { ngx_string("Date"),
  207.                  ngx_http_upstream_process_header_line,
  208.                  offsetof(ngx_http_upstream_headers_in_t, date),
  209.                  ngx_http_upstream_copy_header_line,
  210.                  offsetof(ngx_http_headers_out_t, date), 0 },

  211.     { ngx_string("Last-Modified"),
  212.                  ngx_http_upstream_process_last_modified, 0,
  213.                  ngx_http_upstream_copy_last_modified, 0, 0 },

  214.     { ngx_string("ETag"),
  215.                  ngx_http_upstream_process_header_line,
  216.                  offsetof(ngx_http_upstream_headers_in_t, etag),
  217.                  ngx_http_upstream_copy_header_line,
  218.                  offsetof(ngx_http_headers_out_t, etag), 0 },

  219.     { ngx_string("Server"),
  220.                  ngx_http_upstream_process_header_line,
  221.                  offsetof(ngx_http_upstream_headers_in_t, server),
  222.                  ngx_http_upstream_copy_header_line,
  223.                  offsetof(ngx_http_headers_out_t, server), 0 },

  224.     { ngx_string("WWW-Authenticate"),
  225.                  ngx_http_upstream_process_multi_header_lines,
  226.                  offsetof(ngx_http_upstream_headers_in_t, www_authenticate),
  227.                  ngx_http_upstream_copy_header_line, 0, 0 },

  228.     { ngx_string("Location"),
  229.                  ngx_http_upstream_process_header_line,
  230.                  offsetof(ngx_http_upstream_headers_in_t, location),
  231.                  ngx_http_upstream_rewrite_location, 0, 0 },

  232.     { ngx_string("Refresh"),
  233.                  ngx_http_upstream_process_header_line,
  234.                  offsetof(ngx_http_upstream_headers_in_t, refresh),
  235.                  ngx_http_upstream_rewrite_refresh, 0, 0 },

  236.     { ngx_string("Set-Cookie"),
  237.                  ngx_http_upstream_process_set_cookie,
  238.                  offsetof(ngx_http_upstream_headers_in_t, set_cookie),
  239.                  ngx_http_upstream_rewrite_set_cookie, 0, 1 },

  240.     { ngx_string("Content-Disposition"),
  241.                  ngx_http_upstream_ignore_header_line, 0,
  242.                  ngx_http_upstream_copy_header_line, 0, 1 },

  243.     { ngx_string("Cache-Control"),
  244.                  ngx_http_upstream_process_cache_control, 0,
  245.                  ngx_http_upstream_copy_multi_header_lines,
  246.                  offsetof(ngx_http_headers_out_t, cache_control), 1 },

  247.     { ngx_string("Expires"),
  248.                  ngx_http_upstream_process_expires, 0,
  249.                  ngx_http_upstream_copy_header_line,
  250.                  offsetof(ngx_http_headers_out_t, expires), 1 },

  251.     { ngx_string("Accept-Ranges"),
  252.                  ngx_http_upstream_ignore_header_line, 0,
  253.                  ngx_http_upstream_copy_allow_ranges,
  254.                  offsetof(ngx_http_headers_out_t, accept_ranges), 1 },

  255.     { ngx_string("Upgrade"),
  256.                  ngx_http_upstream_ignore_header_line, 0,
  257.                  ngx_http_upstream_copy_upgrade, 0, 0 },

  258.     { ngx_string("Content-Range"),
  259.                  ngx_http_upstream_ignore_header_line, 0,
  260.                  ngx_http_upstream_copy_header_line,
  261.                  offsetof(ngx_http_headers_out_t, content_range), 0 },

  262.     { ngx_string("Connection"),
  263.                  ngx_http_upstream_process_connection, 0,
  264.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  265.     { ngx_string("Keep-Alive"),
  266.                  ngx_http_upstream_ignore_header_line, 0,
  267.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  268.     { ngx_string("Vary"),
  269.                  ngx_http_upstream_process_vary, 0,
  270.                  ngx_http_upstream_copy_header_line, 0, 0 },

  271.     { ngx_string("Link"),
  272.                  ngx_http_upstream_ignore_header_line, 0,
  273.                  ngx_http_upstream_copy_multi_header_lines,
  274.                  offsetof(ngx_http_headers_out_t, link), 0 },

  275.     { ngx_string("X-Accel-Expires"),
  276.                  ngx_http_upstream_process_accel_expires, 0,
  277.                  ngx_http_upstream_copy_header_line, 0, 0 },

  278.     { ngx_string("X-Accel-Redirect"),
  279.                  ngx_http_upstream_process_header_line,
  280.                  offsetof(ngx_http_upstream_headers_in_t, x_accel_redirect),
  281.                  ngx_http_upstream_copy_header_line, 0, 0 },

  282.     { ngx_string("X-Accel-Limit-Rate"),
  283.                  ngx_http_upstream_process_limit_rate, 0,
  284.                  ngx_http_upstream_copy_header_line, 0, 0 },

  285.     { ngx_string("X-Accel-Buffering"),
  286.                  ngx_http_upstream_process_buffering, 0,
  287.                  ngx_http_upstream_copy_header_line, 0, 0 },

  288.     { ngx_string("X-Accel-Charset"),
  289.                  ngx_http_upstream_process_charset, 0,
  290.                  ngx_http_upstream_copy_header_line, 0, 0 },

  291.     { ngx_string("Transfer-Encoding"),
  292.                  ngx_http_upstream_process_transfer_encoding, 0,
  293.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  294.     { ngx_string("Content-Encoding"),
  295.                  ngx_http_upstream_ignore_header_line, 0,
  296.                  ngx_http_upstream_copy_header_line,
  297.                  offsetof(ngx_http_headers_out_t, content_encoding), 0 },

  298.     { ngx_string("Priority"),
  299.                  ngx_http_upstream_process_priority, 0,
  300.                  ngx_http_upstream_copy_header_line, 0, 0 },

  301.     { ngx_null_string, NULL, 0, NULL, 0, 0 }
  302. };


  303. ‌static ngx_command_t  ngx_http_upstream_commands[] = {

  304.     { ngx_string("upstream"),
  305.       NGX_HTTP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE1,
  306.       ngx_http_upstream,
  307.       0,
  308.       0,
  309.       NULL },

  310.     { ngx_string("server"),
  311.       NGX_HTTP_UPS_CONF|NGX_CONF_1MORE,
  312.       ngx_http_upstream_server,
  313.       NGX_HTTP_SRV_CONF_OFFSET,
  314.       0,
  315.       NULL },

  316. #if (NGX_HTTP_UPSTREAM_ZONE)

  317.     { ngx_string("resolver"),
  318.       NGX_HTTP_UPS_CONF|NGX_CONF_1MORE,
  319.       ngx_http_upstream_resolver,
  320.       NGX_HTTP_SRV_CONF_OFFSET,
  321.       0,
  322.       NULL },

  323.     { ngx_string("resolver_timeout"),
  324.       NGX_HTTP_UPS_CONF|NGX_CONF_TAKE1,
  325.       ngx_conf_set_msec_slot,
  326.       NGX_HTTP_SRV_CONF_OFFSET,
  327.       offsetof(ngx_http_upstream_srv_conf_t, resolver_timeout),
  328.       NULL },

  329. #endif

  330.       ngx_null_command
  331. };


  332. ‌static ngx_http_module_t  ngx_http_upstream_module_ctx = {
  333.     ngx_http_upstream_add_variables,       /* preconfiguration */
  334.     NULL,                                  /* postconfiguration */

  335.     ngx_http_upstream_create_main_conf,    /* create main configuration */
  336.     ngx_http_upstream_init_main_conf,      /* init main configuration */

  337.     NULL,                                  /* create server configuration */
  338.     NULL,                                  /* merge server configuration */

  339.     NULL,                                  /* create location configuration */
  340.     NULL                                   /* merge location configuration */
  341. };


  342. ‌ngx_module_t  ngx_http_upstream_module = {
  343.     NGX_MODULE_V1,
  344.     &ngx_http_upstream_module_ctx,         /* module context */
  345.     ngx_http_upstream_commands,            /* module directives */
  346.     NGX_HTTP_MODULE,                       /* module type */
  347.     NULL,                                  /* init master */
  348.     NULL,                                  /* init module */
  349.     NULL,                                  /* init process */
  350.     NULL,                                  /* init thread */
  351.     NULL,                                  /* exit thread */
  352.     NULL,                                  /* exit process */
  353.     NULL,                                  /* exit master */
  354.     NGX_MODULE_V1_PADDING
  355. };


  356. ‌static ngx_http_variable_t  ngx_http_upstream_vars[] = {

  357.     { ngx_string("upstream_addr"), NULL,
  358.       ngx_http_upstream_addr_variable, 0,
  359.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  360.     { ngx_string("upstream_status"), NULL,
  361.       ngx_http_upstream_status_variable, 0,
  362.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  363.     { ngx_string("upstream_connect_time"), NULL,
  364.       ngx_http_upstream_response_time_variable, 2,
  365.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  366.     { ngx_string("upstream_header_time"), NULL,
  367.       ngx_http_upstream_response_time_variable, 1,
  368.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  369.     { ngx_string("upstream_response_time"), NULL,
  370.       ngx_http_upstream_response_time_variable, 0,
  371.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  372.     { ngx_string("upstream_response_length"), NULL,
  373.       ngx_http_upstream_response_length_variable, 0,
  374.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  375.     { ngx_string("upstream_bytes_received"), NULL,
  376.       ngx_http_upstream_response_length_variable, 1,
  377.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  378.     { ngx_string("upstream_bytes_sent"), NULL,
  379.       ngx_http_upstream_response_length_variable, 2,
  380.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  381. #if (NGX_HTTP_CACHE)

  382.     { ngx_string("upstream_cache_status"), NULL,
  383.       ngx_http_upstream_cache_status, 0,
  384.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  385.     { ngx_string("upstream_cache_last_modified"), NULL,
  386.       ngx_http_upstream_cache_last_modified, 0,
  387.       NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_NOHASH, 0 },

  388.     { ngx_string("upstream_cache_etag"), NULL,
  389.       ngx_http_upstream_cache_etag, 0,
  390.       NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_NOHASH, 0 },

  391. #endif

  392.     { ngx_string("upstream_http_"), NULL, ngx_http_upstream_header_variable,
  393.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  394.     { ngx_string("upstream_trailer_"), NULL, ngx_http_upstream_trailer_variable,
  395.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  396.     { ngx_string("upstream_cookie_"), NULL, ngx_http_upstream_cookie_variable,
  397.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  398.       ngx_http_null_variable
  399. };


  400. ‌static ngx_http_upstream_next_t  ngx_http_upstream_next_errors[] = {
  401.     { 500, NGX_HTTP_UPSTREAM_FT_HTTP_500 },
  402.     { 502, NGX_HTTP_UPSTREAM_FT_HTTP_502 },
  403.     { 503, NGX_HTTP_UPSTREAM_FT_HTTP_503 },
  404.     { 504, NGX_HTTP_UPSTREAM_FT_HTTP_504 },
  405.     { 403, NGX_HTTP_UPSTREAM_FT_HTTP_403 },
  406.     { 404, NGX_HTTP_UPSTREAM_FT_HTTP_404 },
  407.     { 429, NGX_HTTP_UPSTREAM_FT_HTTP_429 },
  408.     { 0, 0 }
  409. };


  410. ‌ngx_conf_bitmask_t  ngx_http_upstream_cache_method_mask[] = {
  411.     { ngx_string("GET"), NGX_HTTP_GET },
  412.     { ngx_string("HEAD"), NGX_HTTP_HEAD },
  413.     { ngx_string("POST"), NGX_HTTP_POST },
  414.     { ngx_null_string, 0 }
  415. };


  416. ‌ngx_conf_bitmask_t  ngx_http_upstream_ignore_headers_masks[] = {
  417.     { ngx_string("X-Accel-Redirect"), NGX_HTTP_UPSTREAM_IGN_XA_REDIRECT },
  418.     { ngx_string("X-Accel-Expires"), NGX_HTTP_UPSTREAM_IGN_XA_EXPIRES },
  419.     { ngx_string("X-Accel-Limit-Rate"), NGX_HTTP_UPSTREAM_IGN_XA_LIMIT_RATE },
  420.     { ngx_string("X-Accel-Buffering"), NGX_HTTP_UPSTREAM_IGN_XA_BUFFERING },
  421.     { ngx_string("X-Accel-Charset"), NGX_HTTP_UPSTREAM_IGN_XA_CHARSET },
  422.     { ngx_string("Expires"), NGX_HTTP_UPSTREAM_IGN_EXPIRES },
  423.     { ngx_string("Cache-Control"), NGX_HTTP_UPSTREAM_IGN_CACHE_CONTROL },
  424.     { ngx_string("Set-Cookie"), NGX_HTTP_UPSTREAM_IGN_SET_COOKIE },
  425.     { ngx_string("Vary"), NGX_HTTP_UPSTREAM_IGN_VARY },
  426.     { ngx_null_string, 0 }
  427. };


  428. ngx_int_t
  429. ‌ngx_http_upstream_create(ngx_http_request_t *r)
  430. {
  431.     ngx_http_upstream_t  *u;

  432.     u = r->upstream;

  433.     if (u && u->cleanup) {
  434.         r->main->count++;
  435.         ngx_http_upstream_cleanup(r);
  436.     }

  437.     u = ngx_pcalloc(r->pool, sizeof(ngx_http_upstream_t));
  438.     if (u == NULL) {
  439.         return NGX_ERROR;
  440.     }

  441.     r->upstream = u;

  442.     u->peer.log = r->connection->log;
  443.     u->peer.log_error = NGX_ERROR_ERR;

  444. #if (NGX_HTTP_CACHE)
  445.     r->cache = NULL;
  446. #endif

  447.     u->headers_in.content_length_n = -1;
  448.     u->headers_in.last_modified_time = -1;

  449.     return NGX_OK;
  450. }


  451. void
  452. ‌ngx_http_upstream_init(ngx_http_request_t *r)
  453. {
  454.     ngx_connection_t     *c;

  455.     c = r->connection;

  456.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0,
  457.                    "http init upstream, client timer: %d", c->read->timer_set);

  458. #if (NGX_HTTP_V2)
  459.     if (r->stream) {
  460.         ngx_http_upstream_init_request(r);
  461.         return;
  462.     }
  463. #endif

  464. #if (NGX_HTTP_V3)
  465.     if (c->quic) {
  466.         ngx_http_upstream_init_request(r);
  467.         return;
  468.     }
  469. #endif

  470.     if (c->read->timer_set) {
  471.         ngx_del_timer(c->read);
  472.     }

  473.     if (ngx_event_flags & NGX_USE_CLEAR_EVENT) {

  474.         if (!c->write->active) {
  475.             if (ngx_add_event(c->write, NGX_WRITE_EVENT, NGX_CLEAR_EVENT)
  476.                 == NGX_ERROR)
  477.             {
  478.                 ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  479.                 return;
  480.             }
  481.         }
  482.     }

  483.     ngx_http_upstream_init_request(r);
  484. }


  485. static void
  486. ‌ngx_http_upstream_init_request(ngx_http_request_t *r)
  487. {
  488.     ngx_str_t                      *host;
  489.     ngx_uint_t                      i;
  490.     ngx_resolver_ctx_t             *ctx, temp;
  491.     ngx_http_cleanup_t             *cln;
  492.     ngx_http_upstream_t            *u;
  493.     ngx_http_core_loc_conf_t       *clcf;
  494.     ngx_http_upstream_srv_conf_t   *uscf, **uscfp;
  495.     ngx_http_upstream_main_conf_t  *umcf;

  496.     if (r->aio) {
  497.         return;
  498.     }

  499.     u = r->upstream;

  500. #if (NGX_HTTP_CACHE)

  501.     if (u->conf->cache) {
  502.         ngx_int_t  rc;

  503.         rc = ngx_http_upstream_cache(r, u);

  504.         if (rc == NGX_BUSY) {
  505.             r->write_event_handler = ngx_http_upstream_init_request;
  506.             return;
  507.         }

  508.         r->write_event_handler = ngx_http_request_empty_handler;

  509.         if (rc == NGX_ERROR) {
  510.             ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  511.             return;
  512.         }

  513.         if (rc == NGX_OK) {
  514.             rc = ngx_http_upstream_cache_send(r, u);

  515.             if (rc == NGX_DONE) {
  516.                 return;
  517.             }

  518.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  519.                 rc = NGX_DECLINED;
  520.                 r->cached = 0;
  521.                 u->buffer.start = NULL;
  522.                 u->cache_status = NGX_HTTP_CACHE_MISS;
  523.                 u->request_sent = 1;
  524.             }
  525.         }

  526.         if (rc != NGX_DECLINED) {
  527.             ngx_http_finalize_request(r, rc);
  528.             return;
  529.         }
  530.     }

  531. #endif

  532.     u->store = u->conf->store;

  533.     if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {

  534.         if (r->connection->read->ready) {
  535.             ngx_post_event(r->connection->read, &ngx_posted_events);

  536.         } else {
  537.             if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {
  538.                 ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  539.                 return;
  540.             }
  541.         }

  542.         r->read_event_handler = ngx_http_upstream_rd_check_broken_connection;
  543.         r->write_event_handler = ngx_http_upstream_wr_check_broken_connection;
  544.     }

  545.     if (r->request_body) {
  546.         u->request_bufs = r->request_body->bufs;
  547.     }

  548.     if (u->create_request(r) != NGX_OK) {
  549.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  550.         return;
  551.     }

  552.     if (ngx_http_upstream_set_local(r, u, u->conf->local) != NGX_OK) {
  553.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  554.         return;
  555.     }

  556.     if (u->conf->socket_keepalive) {
  557.         u->peer.so_keepalive = 1;
  558.     }

  559.     if (u->conf->socket_rcvbuf) {
  560.         u->peer.rcvbuf = (int) u->conf->socket_rcvbuf;
  561.     }

  562.     if (u->conf->socket_sndbuf) {
  563.         u->peer.sndbuf = (int) u->conf->socket_sndbuf;
  564.     }

  565.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  566.     u->output.alignment = clcf->directio_alignment;
  567.     u->output.pool = r->pool;
  568.     u->output.bufs.num = 1;
  569.     u->output.bufs.size = clcf->client_body_buffer_size;

  570.     if (u->output.output_filter == NULL) {
  571.         u->output.output_filter = ngx_chain_writer;
  572.         u->output.filter_ctx = &u->writer;
  573.     }

  574.     u->writer.pool = r->pool;

  575.     if (r->upstream_states == NULL) {

  576.         r->upstream_states = ngx_array_create(r->pool, 1,
  577.                                             sizeof(ngx_http_upstream_state_t));
  578.         if (r->upstream_states == NULL) {
  579.             ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  580.             return;
  581.         }

  582.     } else {

  583.         u->state = ngx_array_push(r->upstream_states);
  584.         if (u->state == NULL) {
  585.             ngx_http_upstream_finalize_request(r, u,
  586.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  587.             return;
  588.         }

  589.         ngx_memzero(u->state, sizeof(ngx_http_upstream_state_t));
  590.     }

  591.     cln = ngx_http_cleanup_add(r, 0);
  592.     if (cln == NULL) {
  593.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  594.         return;
  595.     }

  596.     cln->handler = ngx_http_upstream_cleanup;
  597.     cln->data = r;
  598.     u->cleanup = &cln->handler;

  599.     if (u->resolved == NULL) {

  600.         uscf = u->conf->upstream;

  601.     } else {

  602. #if (NGX_HTTP_SSL)
  603.         u->ssl_name = u->resolved->host;
  604. #endif

  605.         host = &u->resolved->host;

  606.         umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);

  607.         uscfp = umcf->upstreams.elts;

  608.         for (i = 0; i < umcf->upstreams.nelts; i++) {

  609.             uscf = uscfp[i];

  610.             if (uscf->host.len == host->len
  611.                 && ((uscf->port == 0 && u->resolved->no_port)
  612.                      || uscf->port == u->resolved->port)
  613.                 && ngx_strncasecmp(uscf->host.data, host->data, host->len) == 0)
  614.             {
  615.                 goto found;
  616.             }
  617.         }

  618.         if (u->resolved->sockaddr) {

  619.             if (u->resolved->port == 0
  620.                 && u->resolved->sockaddr->sa_family != AF_UNIX)
  621.             {
  622.                 ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  623.                               "no port in upstream \"%V\"", host);
  624.                 ngx_http_upstream_finalize_request(r, u,
  625.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  626.                 return;
  627.             }

  628.             if (ngx_http_upstream_create_round_robin_peer(r, u->resolved)
  629.                 != NGX_OK)
  630.             {
  631.                 ngx_http_upstream_finalize_request(r, u,
  632.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  633.                 return;
  634.             }

  635.             ngx_http_upstream_connect(r, u);

  636.             return;
  637.         }

  638.         if (u->resolved->port == 0) {
  639.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  640.                           "no port in upstream \"%V\"", host);
  641.             ngx_http_upstream_finalize_request(r, u,
  642.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  643.             return;
  644.         }

  645.         temp.name = *host;

  646.         ctx = ngx_resolve_start(clcf->resolver, &temp);
  647.         if (ctx == NULL) {
  648.             ngx_http_upstream_finalize_request(r, u,
  649.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  650.             return;
  651.         }

  652.         if (ctx == NGX_NO_RESOLVER) {
  653.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  654.                           "no resolver defined to resolve %V", host);

  655.             ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  656.             return;
  657.         }

  658.         ctx->name = *host;
  659.         ctx->handler = ngx_http_upstream_resolve_handler;
  660.         ctx->data = r;
  661.         ctx->timeout = clcf->resolver_timeout;

  662.         u->resolved->ctx = ctx;

  663.         if (ngx_resolve_name(ctx) != NGX_OK) {
  664.             u->resolved->ctx = NULL;
  665.             ngx_http_upstream_finalize_request(r, u,
  666.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  667.             return;
  668.         }

  669.         return;
  670.     }

  671. found:

  672.     if (uscf == NULL) {
  673.         ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0,
  674.                       "no upstream configuration");
  675.         ngx_http_upstream_finalize_request(r, u,
  676.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  677.         return;
  678.     }

  679.     u->upstream = uscf;

  680. #if (NGX_HTTP_SSL)
  681.     u->ssl_name = uscf->host;
  682. #endif

  683.     if (uscf->peer.init(r, uscf) != NGX_OK) {
  684.         ngx_http_upstream_finalize_request(r, u,
  685.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  686.         return;
  687.     }

  688.     u->peer.start_time = ngx_current_msec;

  689.     if (u->conf->next_upstream_tries
  690.         && u->peer.tries > u->conf->next_upstream_tries)
  691.     {
  692.         u->peer.tries = u->conf->next_upstream_tries;
  693.     }

  694.     ngx_http_upstream_connect(r, u);
  695. }


  696. #if (NGX_HTTP_CACHE)

  697. static ngx_int_t
  698. ‌ngx_http_upstream_cache(ngx_http_request_t *r, ngx_http_upstream_t *u)
  699. {
  700.     ngx_int_t               rc;
  701.     ngx_http_cache_t       *c;
  702.     ngx_http_file_cache_t  *cache;

  703.     c = r->cache;

  704.     if (c == NULL) {

  705.         if (!(r->method & u->conf->cache_methods)) {
  706.             return NGX_DECLINED;
  707.         }

  708.         rc = ngx_http_upstream_cache_get(r, u, &cache);

  709.         if (rc != NGX_OK) {
  710.             return rc;
  711.         }

  712.         if (r->method == NGX_HTTP_HEAD && u->conf->cache_convert_head) {
  713.             u->method = ngx_http_core_get_method;
  714.         }

  715.         if (ngx_http_file_cache_new(r) != NGX_OK) {
  716.             return NGX_ERROR;
  717.         }

  718.         if (u->create_key(r) != NGX_OK) {
  719.             return NGX_ERROR;
  720.         }

  721.         /* TODO: add keys */

  722.         ngx_http_file_cache_create_key(r);

  723.         if (r->cache->header_start + 256 > u->conf->buffer_size) {
  724.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  725.                           "%V_buffer_size %uz is not enough for cache key, "
  726.                           "it should be increased to at least %uz",
  727.                           &u->conf->module, u->conf->buffer_size,
  728.                           ngx_align(r->cache->header_start + 256, 1024));

  729.             r->cache = NULL;
  730.             return NGX_DECLINED;
  731.         }

  732.         u->cacheable = 1;

  733.         c = r->cache;

  734.         c->body_start = u->conf->buffer_size;
  735.         c->min_uses = u->conf->cache_min_uses;
  736.         c->file_cache = cache;

  737.         switch (ngx_http_test_predicates(r, u->conf->cache_bypass)) {

  738.         case NGX_ERROR:
  739.             return NGX_ERROR;

  740.         case NGX_DECLINED:
  741.             u->cache_status = NGX_HTTP_CACHE_BYPASS;
  742.             return NGX_DECLINED;

  743.         default: /* NGX_OK */
  744.             break;
  745.         }

  746.         c->lock = u->conf->cache_lock;
  747.         c->lock_timeout = u->conf->cache_lock_timeout;
  748.         c->lock_age = u->conf->cache_lock_age;

  749.         u->cache_status = NGX_HTTP_CACHE_MISS;
  750.     }

  751.     rc = ngx_http_file_cache_open(r);

  752.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  753.                    "http upstream cache: %i", rc);

  754.     switch (rc) {

  755.     case NGX_HTTP_CACHE_STALE:

  756.         if (((u->conf->cache_use_stale & NGX_HTTP_UPSTREAM_FT_UPDATING)
  757.              || c->stale_updating) && !r->background
  758.             && u->conf->cache_background_update)
  759.         {
  760.             if (ngx_http_upstream_cache_background_update(r, u) == NGX_OK) {
  761.                 r->cache->background = 1;
  762.                 u->cache_status = rc;
  763.                 rc = NGX_OK;

  764.             } else {
  765.                 rc = NGX_ERROR;
  766.             }
  767.         }

  768.         break;

  769.     case NGX_HTTP_CACHE_UPDATING:

  770.         if (((u->conf->cache_use_stale & NGX_HTTP_UPSTREAM_FT_UPDATING)
  771.              || c->stale_updating) && !r->background)
  772.         {
  773.             u->cache_status = rc;
  774.             rc = NGX_OK;

  775.         } else {
  776.             rc = NGX_HTTP_CACHE_STALE;
  777.         }

  778.         break;

  779.     case NGX_OK:
  780.         u->cache_status = NGX_HTTP_CACHE_HIT;
  781.     }

  782.     switch (rc) {

  783.     case NGX_OK:

  784.         return NGX_OK;

  785.     case NGX_HTTP_CACHE_STALE:

  786.         c->valid_sec = 0;
  787.         c->updating_sec = 0;
  788.         c->error_sec = 0;

  789.         u->buffer.start = NULL;
  790.         u->cache_status = NGX_HTTP_CACHE_EXPIRED;

  791.         break;

  792.     case NGX_DECLINED:

  793.         if ((size_t) (u->buffer.end - u->buffer.start) < u->conf->buffer_size) {
  794.             u->buffer.start = NULL;

  795.         } else {
  796.             u->buffer.pos = u->buffer.start + c->header_start;
  797.             u->buffer.last = u->buffer.pos;
  798.         }

  799.         break;

  800.     case NGX_HTTP_CACHE_SCARCE:

  801.         u->cacheable = 0;

  802.         break;

  803.     case NGX_AGAIN:

  804.         return NGX_BUSY;

  805.     case NGX_ERROR:

  806.         return NGX_ERROR;

  807.     default:

  808.         /* cached NGX_HTTP_BAD_GATEWAY, NGX_HTTP_GATEWAY_TIME_OUT, etc. */

  809.         u->cache_status = NGX_HTTP_CACHE_HIT;

  810.         return rc;
  811.     }

  812.     if (ngx_http_upstream_cache_check_range(r, u) == NGX_DECLINED) {
  813.         u->cacheable = 0;
  814.     }

  815.     r->cached = 0;

  816.     return NGX_DECLINED;
  817. }


  818. static ngx_int_t
  819. ‌ngx_http_upstream_cache_get(ngx_http_request_t *r, ngx_http_upstream_t *u,
  820.     ngx_http_file_cache_t **cache)
  821. {
  822.     ngx_str_t               *name, val;
  823.     ngx_uint_t               i;
  824.     ngx_http_file_cache_t  **caches;

  825.     if (u->conf->cache_zone) {
  826.         *cache = u->conf->cache_zone->data;
  827.         return NGX_OK;
  828.     }

  829.     if (ngx_http_complex_value(r, u->conf->cache_value, &val) != NGX_OK) {
  830.         return NGX_ERROR;
  831.     }

  832.     if (val.len == 0
  833.         || (val.len == 3 && ngx_strncmp(val.data, "off", 3) == 0))
  834.     {
  835.         return NGX_DECLINED;
  836.     }

  837.     caches = u->caches->elts;

  838.     for (i = 0; i < u->caches->nelts; i++) {
  839.         name = &caches[i]->shm_zone->shm.name;

  840.         if (name->len == val.len
  841.             && ngx_strncmp(name->data, val.data, val.len) == 0)
  842.         {
  843.             *cache = caches[i];
  844.             return NGX_OK;
  845.         }
  846.     }

  847.     ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  848.                   "cache \"%V\" not found", &val);

  849.     return NGX_ERROR;
  850. }


  851. static ngx_int_t
  852. ‌ngx_http_upstream_cache_send(ngx_http_request_t *r, ngx_http_upstream_t *u)
  853. {
  854.     ngx_int_t          rc;
  855.     ngx_http_cache_t  *c;

  856.     r->cached = 1;
  857.     c = r->cache;

  858.     if (c->header_start == c->body_start) {
  859.         r->http_version = NGX_HTTP_VERSION_9;
  860.         return ngx_http_cache_send(r);
  861.     }

  862.     /* TODO: cache stack */

  863.     u->buffer = *c->buf;
  864.     u->buffer.pos += c->header_start;

  865.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  866.     u->headers_in.content_length_n = -1;
  867.     u->headers_in.last_modified_time = -1;

  868.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  869.                       sizeof(ngx_table_elt_t))
  870.         != NGX_OK)
  871.     {
  872.         return NGX_ERROR;
  873.     }

  874.     if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  875.                       sizeof(ngx_table_elt_t))
  876.         != NGX_OK)
  877.     {
  878.         return NGX_ERROR;
  879.     }

  880.     rc = u->process_header(r);

  881.     if (rc == NGX_OK) {

  882.         rc = ngx_http_upstream_process_headers(r, u);

  883.         if (rc != NGX_OK) {
  884.             return rc;
  885.         }

  886.         return ngx_http_cache_send(r);
  887.     }

  888.     if (rc == NGX_ERROR) {
  889.         return NGX_ERROR;
  890.     }

  891.     if (rc == NGX_AGAIN || rc == NGX_HTTP_UPSTREAM_EARLY_HINTS) {
  892.         rc = NGX_HTTP_UPSTREAM_INVALID_HEADER;
  893.     }

  894.     /* rc == NGX_HTTP_UPSTREAM_INVALID_HEADER */

  895.     ngx_log_error(NGX_LOG_CRIT, r->connection->log, 0,
  896.                   "cache file \"%s\" contains invalid header",
  897.                   c->file.name.data);

  898.     /* TODO: delete file */

  899.     return rc;
  900. }


  901. static ngx_int_t
  902. ‌ngx_http_upstream_cache_background_update(ngx_http_request_t *r,
  903.     ngx_http_upstream_t *u)
  904. {
  905.     ngx_http_request_t  *sr;

  906.     if (r == r->main) {
  907.         r->preserve_body = 1;
  908.     }

  909.     if (ngx_http_subrequest(r, &r->uri, &r->args, &sr, NULL,
  910.                             NGX_HTTP_SUBREQUEST_CLONE
  911.                             |NGX_HTTP_SUBREQUEST_BACKGROUND)
  912.         != NGX_OK)
  913.     {
  914.         return NGX_ERROR;
  915.     }

  916.     sr->header_only = 1;

  917.     return NGX_OK;
  918. }


  919. static ngx_int_t
  920. ‌ngx_http_upstream_cache_check_range(ngx_http_request_t *r,
  921.     ngx_http_upstream_t *u)
  922. {
  923.     off_t             offset;
  924.     u_char           *p, *start;
  925.     ngx_table_elt_t  *h;

  926.     h = r->headers_in.range;

  927.     if (h == NULL
  928.         || !u->cacheable
  929.         || u->conf->cache_max_range_offset == NGX_MAX_OFF_T_VALUE)
  930.     {
  931.         return NGX_OK;
  932.     }

  933.     if (u->conf->cache_max_range_offset == 0) {
  934.         return NGX_DECLINED;
  935.     }

  936.     if (h->value.len < 7
  937.         || ngx_strncasecmp(h->value.data, (u_char *) "bytes=", 6) != 0)
  938.     {
  939.         return NGX_OK;
  940.     }

  941.     p = h->value.data + 6;

  942.     while (*p == ' ') { p++; }

  943.     if (*p == '-') {
  944.         return NGX_DECLINED;
  945.     }

  946.     start = p;

  947.     while (*p >= '0' && *p <= '9') { p++; }

  948.     offset = ngx_atoof(start, p - start);

  949.     if (offset >= u->conf->cache_max_range_offset) {
  950.         return NGX_DECLINED;
  951.     }

  952.     return NGX_OK;
  953. }

  954. #endif


  955. static void
  956. ‌ngx_http_upstream_resolve_handler(ngx_resolver_ctx_t *ctx)
  957. {
  958.     ngx_uint_t                     run_posted;
  959.     ngx_connection_t              *c;
  960.     ngx_http_request_t            *r;
  961.     ngx_http_upstream_t           *u;
  962.     ngx_http_upstream_resolved_t  *ur;

  963.     run_posted = ctx->async;

  964.     r = ctx->data;
  965.     c = r->connection;

  966.     u = r->upstream;
  967.     ur = u->resolved;

  968.     ngx_http_set_log_request(c->log, r);

  969.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0,
  970.                    "http upstream resolve: \"%V?%V\"", &r->uri, &r->args);

  971.     if (ctx->state) {
  972.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  973.                       "%V could not be resolved (%i: %s)",
  974.                       &ctx->name, ctx->state,
  975.                       ngx_resolver_strerror(ctx->state));

  976.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  977.         goto failed;
  978.     }

  979.     ur->naddrs = ctx->naddrs;
  980.     ur->addrs = ctx->addrs;

  981. #if (NGX_DEBUG)
  982.     {
  983.     u_char      text[NGX_SOCKADDR_STRLEN];
  984.     ngx_str_t   addr;
  985.     ngx_uint_t  i;

  986.     addr.data = text;

  987.     for (i = 0; i < ctx->naddrs; i++) {
  988.         addr.len = ngx_sock_ntop(ur->addrs[i].sockaddr, ur->addrs[i].socklen,
  989.                                  text, NGX_SOCKADDR_STRLEN, 0);

  990.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  991.                        "name was resolved to %V", &addr);
  992.     }
  993.     }
  994. #endif

  995.     if (ngx_http_upstream_create_round_robin_peer(r, ur) != NGX_OK) {
  996.         ngx_http_upstream_finalize_request(r, u,
  997.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  998.         goto failed;
  999.     }

  1000.     ngx_resolve_name_done(ctx);
  1001.     ur->ctx = NULL;

  1002.     u->peer.start_time = ngx_current_msec;

  1003.     if (u->conf->next_upstream_tries
  1004.         && u->peer.tries > u->conf->next_upstream_tries)
  1005.     {
  1006.         u->peer.tries = u->conf->next_upstream_tries;
  1007.     }

  1008.     ngx_http_upstream_connect(r, u);

  1009. failed:

  1010.     if (run_posted) {
  1011.         ngx_http_run_posted_requests(c);
  1012.     }
  1013. }


  1014. static void
  1015. ‌ngx_http_upstream_handler(ngx_event_t *ev)
  1016. {
  1017.     ngx_connection_t     *c;
  1018.     ngx_http_request_t   *r;
  1019.     ngx_http_upstream_t  *u;

  1020.     c = ev->data;
  1021.     r = c->data;

  1022.     u = r->upstream;
  1023.     c = r->connection;

  1024.     ngx_http_set_log_request(c->log, r);

  1025.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0,
  1026.                    "http upstream request: \"%V?%V\"", &r->uri, &r->args);

  1027.     if (ev->delayed && ev->timedout) {
  1028.         ev->delayed = 0;
  1029.         ev->timedout = 0;
  1030.     }

  1031.     if (ev->write) {
  1032.         u->write_event_handler(r, u);

  1033.     } else {
  1034.         u->read_event_handler(r, u);
  1035.     }

  1036.     ngx_http_run_posted_requests(c);
  1037. }


  1038. static void
  1039. ‌ngx_http_upstream_rd_check_broken_connection(ngx_http_request_t *r)
  1040. {
  1041.     ngx_http_upstream_check_broken_connection(r, r->connection->read);
  1042. }


  1043. static void
  1044. ‌ngx_http_upstream_wr_check_broken_connection(ngx_http_request_t *r)
  1045. {
  1046.     ngx_http_upstream_check_broken_connection(r, r->connection->write);
  1047. }


  1048. static void
  1049. ‌ngx_http_upstream_check_broken_connection(ngx_http_request_t *r,
  1050.     ngx_event_t *ev)
  1051. {
  1052.     int                  n;
  1053.     char                 buf[1];
  1054.     ngx_err_t            err;
  1055.     ngx_int_t            event;
  1056.     ngx_connection_t     *c;
  1057.     ngx_http_upstream_t  *u;

  1058.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, ev->log, 0,
  1059.                    "http upstream check client, write event:%d, \"%V\"",
  1060.                    ev->write, &r->uri);

  1061.     c = r->connection;
  1062.     u = r->upstream;

  1063.     if (c->error) {
  1064.         if ((ngx_event_flags & NGX_USE_LEVEL_EVENT) && ev->active) {

  1065.             event = ev->write ? NGX_WRITE_EVENT : NGX_READ_EVENT;

  1066.             if (ngx_del_event(ev, event, 0) != NGX_OK) {
  1067.                 ngx_http_upstream_finalize_request(r, u,
  1068.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1069.                 return;
  1070.             }
  1071.         }

  1072.         if (!u->cacheable) {
  1073.             ngx_http_upstream_finalize_request(r, u,
  1074.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1075.         }

  1076.         return;
  1077.     }

  1078. #if (NGX_HTTP_V2)
  1079.     if (r->stream) {
  1080.         return;
  1081.     }
  1082. #endif

  1083. #if (NGX_HTTP_V3)

  1084.     if (c->quic) {
  1085.         if (c->write->error) {
  1086.             ngx_http_upstream_finalize_request(r, u,
  1087.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1088.         }

  1089.         return;
  1090.     }

  1091. #endif

  1092. #if (NGX_HAVE_KQUEUE)

  1093.     if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) {

  1094.         if (!ev->pending_eof) {
  1095.             return;
  1096.         }

  1097.         ev->eof = 1;
  1098.         c->error = 1;

  1099.         if (ev->kq_errno) {
  1100.             ev->error = 1;
  1101.         }

  1102.         if (!u->cacheable && u->peer.connection) {
  1103.             ngx_log_error(NGX_LOG_INFO, ev->log, ev->kq_errno,
  1104.                           "kevent() reported that client prematurely closed "
  1105.                           "connection, so upstream connection is closed too");
  1106.             ngx_http_upstream_finalize_request(r, u,
  1107.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1108.             return;
  1109.         }

  1110.         ngx_log_error(NGX_LOG_INFO, ev->log, ev->kq_errno,
  1111.                       "kevent() reported that client prematurely closed "
  1112.                       "connection");

  1113.         if (u->peer.connection == NULL) {
  1114.             ngx_http_upstream_finalize_request(r, u,
  1115.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1116.         }

  1117.         return;
  1118.     }

  1119. #endif

  1120. #if (NGX_HAVE_EPOLLRDHUP)

  1121.     if ((ngx_event_flags & NGX_USE_EPOLL_EVENT) && ngx_use_epoll_rdhup) {
  1122.         socklen_t  len;

  1123.         if (!ev->pending_eof) {
  1124.             return;
  1125.         }

  1126.         ev->eof = 1;
  1127.         c->error = 1;

  1128.         err = 0;
  1129.         len = sizeof(ngx_err_t);

  1130.         /*
  1131.          * BSDs and Linux return 0 and set a pending error in err
  1132.          * Solaris returns -1 and sets errno
  1133.          */

  1134.         if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, (void *) &err, &len)
  1135.             == -1)
  1136.         {
  1137.             err = ngx_socket_errno;
  1138.         }

  1139.         if (err) {
  1140.             ev->error = 1;
  1141.         }

  1142.         if (!u->cacheable && u->peer.connection) {
  1143.             ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1144.                         "epoll_wait() reported that client prematurely closed "
  1145.                         "connection, so upstream connection is closed too");
  1146.             ngx_http_upstream_finalize_request(r, u,
  1147.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1148.             return;
  1149.         }

  1150.         ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1151.                       "epoll_wait() reported that client prematurely closed "
  1152.                       "connection");

  1153.         if (u->peer.connection == NULL) {
  1154.             ngx_http_upstream_finalize_request(r, u,
  1155.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1156.         }

  1157.         return;
  1158.     }

  1159. #endif

  1160.     n = recv(c->fd, buf, 1, MSG_PEEK);

  1161.     err = ngx_socket_errno;

  1162.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, ev->log, err,
  1163.                    "http upstream recv(): %d", n);

  1164.     if (ev->write && (n >= 0 || err == NGX_EAGAIN)) {
  1165.         return;
  1166.     }

  1167.     if ((ngx_event_flags & NGX_USE_LEVEL_EVENT) && ev->active) {

  1168.         event = ev->write ? NGX_WRITE_EVENT : NGX_READ_EVENT;

  1169.         if (ngx_del_event(ev, event, 0) != NGX_OK) {
  1170.             ngx_http_upstream_finalize_request(r, u,
  1171.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1172.             return;
  1173.         }
  1174.     }

  1175.     if (n > 0) {
  1176.         return;
  1177.     }

  1178.     if (n == -1) {
  1179.         if (err == NGX_EAGAIN) {
  1180.             return;
  1181.         }

  1182.         ev->error = 1;

  1183.     } else { /* n == 0 */
  1184.         err = 0;
  1185.     }

  1186.     ev->eof = 1;
  1187.     c->error = 1;

  1188.     if (!u->cacheable && u->peer.connection) {
  1189.         ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1190.                       "client prematurely closed connection, "
  1191.                       "so upstream connection is closed too");
  1192.         ngx_http_upstream_finalize_request(r, u,
  1193.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1194.         return;
  1195.     }

  1196.     ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1197.                   "client prematurely closed connection");

  1198.     if (u->peer.connection == NULL) {
  1199.         ngx_http_upstream_finalize_request(r, u,
  1200.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1201.     }
  1202. }


  1203. static void
  1204. ‌ngx_http_upstream_connect(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1205. {
  1206.     ngx_int_t                  rc;
  1207.     ngx_connection_t          *c;
  1208.     ngx_http_core_loc_conf_t  *clcf;

  1209.     r->connection->log->action = "connecting to upstream";

  1210.     if (u->state && u->state->response_time == (ngx_msec_t) -1) {
  1211.         u->state->response_time = ngx_current_msec - u->start_time;
  1212.     }

  1213.     u->state = ngx_array_push(r->upstream_states);
  1214.     if (u->state == NULL) {
  1215.         ngx_http_upstream_finalize_request(r, u,
  1216.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1217.         return;
  1218.     }

  1219.     ngx_memzero(u->state, sizeof(ngx_http_upstream_state_t));

  1220.     u->start_time = ngx_current_msec;

  1221.     u->state->response_time = (ngx_msec_t) -1;
  1222.     u->state->connect_time = (ngx_msec_t) -1;
  1223.     u->state->header_time = (ngx_msec_t) -1;

  1224.     rc = ngx_event_connect_peer(&u->peer);

  1225.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  1226.                    "http upstream connect: %i", rc);

  1227.     if (rc == NGX_ERROR) {
  1228.         ngx_http_upstream_finalize_request(r, u,
  1229.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1230.         return;
  1231.     }

  1232.     u->state->peer = u->peer.name;

  1233. #if (NGX_HTTP_UPSTREAM_ZONE)
  1234.     if (u->upstream && u->upstream->shm_zone
  1235.         && (u->upstream->flags & NGX_HTTP_UPSTREAM_MODIFY))
  1236.     {
  1237.         u->state->peer = ngx_palloc(r->pool,
  1238.                                     sizeof(ngx_str_t) + u->peer.name->len);
  1239.         if (u->state->peer == NULL) {
  1240.             ngx_http_upstream_finalize_request(r, u,
  1241.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1242.             return;
  1243.         }

  1244.         u->state->peer->len = u->peer.name->len;
  1245.         u->state->peer->data = (u_char *) (u->state->peer + 1);
  1246.         ngx_memcpy(u->state->peer->data, u->peer.name->data, u->peer.name->len);

  1247.         u->peer.name = u->state->peer;
  1248.     }
  1249. #endif

  1250.     if (rc == NGX_BUSY) {
  1251.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "no live upstreams");
  1252.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_NOLIVE);
  1253.         return;
  1254.     }

  1255.     if (rc == NGX_DECLINED) {
  1256.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1257.         return;
  1258.     }

  1259.     /* rc == NGX_OK || rc == NGX_AGAIN || rc == NGX_DONE */

  1260.     c = u->peer.connection;

  1261.     c->requests++;

  1262.     c->data = r;

  1263.     c->write->handler = ngx_http_upstream_handler;
  1264.     c->read->handler = ngx_http_upstream_handler;

  1265.     u->write_event_handler = ngx_http_upstream_send_request_handler;
  1266.     u->read_event_handler = ngx_http_upstream_process_header;

  1267.     c->sendfile &= r->connection->sendfile;
  1268.     u->output.sendfile = c->sendfile;

  1269.     if (r->connection->tcp_nopush == NGX_TCP_NOPUSH_DISABLED) {
  1270.         c->tcp_nopush = NGX_TCP_NOPUSH_DISABLED;
  1271.     }

  1272.     if (c->pool == NULL) {

  1273.         /* we need separate pool here to be able to cache SSL connections */

  1274.         c->pool = ngx_create_pool(128, r->connection->log);
  1275.         if (c->pool == NULL) {
  1276.             ngx_http_upstream_finalize_request(r, u,
  1277.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1278.             return;
  1279.         }
  1280.     }

  1281.     c->log = r->connection->log;
  1282.     c->pool->log = c->log;
  1283.     c->read->log = c->log;
  1284.     c->write->log = c->log;

  1285.     /* init or reinit the ngx_output_chain() and ngx_chain_writer() contexts */

  1286.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  1287.     u->writer.out = NULL;
  1288.     u->writer.last = &u->writer.out;
  1289.     u->writer.connection = c;
  1290.     u->writer.limit = clcf->sendfile_max_chunk;

  1291.     if (u->request_sent || u->response_received) {
  1292.         if (ngx_http_upstream_reinit(r, u) != NGX_OK) {
  1293.             ngx_http_upstream_finalize_request(r, u,
  1294.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1295.             return;
  1296.         }
  1297.     }

  1298.     if (r->request_body
  1299.         && r->request_body->buf
  1300.         && r->request_body->temp_file
  1301.         && r == r->main)
  1302.     {
  1303.         /*
  1304.          * the r->request_body->buf can be reused for one request only,
  1305.          * the subrequests should allocate their own temporary bufs
  1306.          */

  1307.         u->output.free = ngx_alloc_chain_link(r->pool);
  1308.         if (u->output.free == NULL) {
  1309.             ngx_http_upstream_finalize_request(r, u,
  1310.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1311.             return;
  1312.         }

  1313.         u->output.free->buf = r->request_body->buf;
  1314.         u->output.free->next = NULL;
  1315.         u->output.allocated = 1;

  1316.         r->request_body->buf->pos = r->request_body->buf->start;
  1317.         r->request_body->buf->last = r->request_body->buf->start;
  1318.         r->request_body->buf->tag = u->output.tag;
  1319.     }

  1320.     u->request_sent = 0;
  1321.     u->request_body_sent = 0;
  1322.     u->request_body_blocked = 0;
  1323.     u->response_received = 0;

  1324.     if (rc == NGX_AGAIN) {
  1325.         ngx_add_timer(c->write, u->conf->connect_timeout);
  1326.         return;
  1327.     }

  1328. #if (NGX_HTTP_SSL)

  1329.     if (u->ssl && c->ssl == NULL) {
  1330.         ngx_http_upstream_ssl_init_connection(r, u, c);
  1331.         return;
  1332.     }

  1333. #endif

  1334.     ngx_http_upstream_send_request(r, u, 1);
  1335. }


  1336. #if (NGX_HTTP_SSL)

  1337. static void
  1338. ‌ngx_http_upstream_ssl_init_connection(ngx_http_request_t *r,
  1339.     ngx_http_upstream_t *u, ngx_connection_t *c)
  1340. {
  1341.     ngx_int_t                  rc;
  1342.     ngx_http_core_loc_conf_t  *clcf;

  1343.     if (ngx_http_upstream_test_connect(c) != NGX_OK) {
  1344.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1345.         return;
  1346.     }

  1347.     if (ngx_ssl_create_connection(u->conf->ssl, c,
  1348.                                   NGX_SSL_BUFFER|NGX_SSL_CLIENT)
  1349.         != NGX_OK)
  1350.     {
  1351.         ngx_http_upstream_finalize_request(r, u,
  1352.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1353.         return;
  1354.     }

  1355.     if (u->conf->ssl_server_name || u->conf->ssl_verify) {
  1356.         if (ngx_http_upstream_ssl_name(r, u, c) != NGX_OK) {
  1357.             ngx_http_upstream_finalize_request(r, u,
  1358.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1359.             return;
  1360.         }
  1361.     }

  1362.     if (u->conf->ssl_certificate
  1363.         && u->conf->ssl_certificate->value.len
  1364.         && (u->conf->ssl_certificate->lengths
  1365.             || u->conf->ssl_certificate_key->lengths))
  1366.     {
  1367.         if (ngx_http_upstream_ssl_certificate(r, u, c) != NGX_OK) {
  1368.             ngx_http_upstream_finalize_request(r, u,
  1369.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1370.             return;
  1371.         }
  1372.     }

  1373. #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation

  1374.     if (u->ssl_alpn_protocol.len) {
  1375.         if (SSL_set_alpn_protos(c->ssl->connection, u->ssl_alpn_protocol.data,
  1376.                                 u->ssl_alpn_protocol.len)
  1377.             != 0)
  1378.         {
  1379.             ngx_ssl_error(NGX_LOG_ERR, c->log, 0,
  1380.                           "SSL_set_alpn_protos() failed");
  1381.             ngx_http_upstream_finalize_request(r, u,
  1382.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1383.             return;
  1384.         }
  1385.     }

  1386. #endif

  1387.     if (u->conf->ssl_session_reuse) {
  1388.         c->ssl->save_session = ngx_http_upstream_ssl_save_session;

  1389.         if (u->peer.set_session(&u->peer, u->peer.data) != NGX_OK) {
  1390.             ngx_http_upstream_finalize_request(r, u,
  1391.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1392.             return;
  1393.         }

  1394.         /* abbreviated SSL handshake may interact badly with Nagle */

  1395.         clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  1396.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  1397.             ngx_http_upstream_finalize_request(r, u,
  1398.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1399.             return;
  1400.         }
  1401.     }

  1402.     r->connection->log->action = "SSL handshaking to upstream";

  1403.     rc = ngx_ssl_handshake(c);

  1404.     if (rc == NGX_AGAIN) {

  1405.         if (!c->write->timer_set) {
  1406.             ngx_add_timer(c->write, u->conf->connect_timeout);
  1407.         }

  1408.         c->ssl->handler = ngx_http_upstream_ssl_handshake_handler;
  1409.         return;
  1410.     }

  1411.     ngx_http_upstream_ssl_handshake(r, u, c);
  1412. }


  1413. static void
  1414. ‌ngx_http_upstream_ssl_handshake_handler(ngx_connection_t *c)
  1415. {
  1416.     ngx_http_request_t   *r;
  1417.     ngx_http_upstream_t  *u;

  1418.     r = c->data;

  1419.     u = r->upstream;
  1420.     c = r->connection;

  1421.     ngx_http_set_log_request(c->log, r);

  1422.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0,
  1423.                    "http upstream ssl handshake: \"%V?%V\"",
  1424.                    &r->uri, &r->args);

  1425.     ngx_http_upstream_ssl_handshake(r, u, u->peer.connection);

  1426.     ngx_http_run_posted_requests(c);
  1427. }


  1428. static void
  1429. ‌ngx_http_upstream_ssl_handshake(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1430.     ngx_connection_t *c)
  1431. {
  1432.     long  rc;

  1433.     if (c->ssl->handshaked) {

  1434.         if (u->conf->ssl_verify) {
  1435.             rc = SSL_get_verify_result(c->ssl->connection);

  1436.             if (rc != X509_V_OK) {
  1437.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1438.                               "upstream SSL certificate verify error: (%l:%s)",
  1439.                               rc, X509_verify_cert_error_string(rc));
  1440.                 goto failed;
  1441.             }

  1442.             if (ngx_ssl_check_host(c, &u->ssl_name) != NGX_OK) {
  1443.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1444.                               "upstream SSL certificate does not match \"%V\"",
  1445.                               &u->ssl_name);
  1446.                 goto failed;
  1447.             }
  1448.         }

  1449.         if (!c->ssl->sendfile) {
  1450.             c->sendfile = 0;
  1451.             u->output.sendfile = 0;
  1452.         }

  1453.         c->write->handler = ngx_http_upstream_handler;
  1454.         c->read->handler = ngx_http_upstream_handler;

  1455.         ngx_http_upstream_send_request(r, u, 1);

  1456.         return;
  1457.     }

  1458.     if (c->write->timedout) {
  1459.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1460.         return;
  1461.     }

  1462. failed:

  1463.     ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1464. }


  1465. static void
  1466. ‌ngx_http_upstream_ssl_save_session(ngx_connection_t *c)
  1467. {
  1468.     ngx_http_request_t   *r;
  1469.     ngx_http_upstream_t  *u;

  1470.     if (c->idle) {
  1471.         return;
  1472.     }

  1473.     r = c->data;

  1474.     u = r->upstream;
  1475.     c = r->connection;

  1476.     ngx_http_set_log_request(c->log, r);

  1477.     u->peer.save_session(&u->peer, u->peer.data);
  1478. }


  1479. static ngx_int_t
  1480. ‌ngx_http_upstream_ssl_name(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1481.     ngx_connection_t *c)
  1482. {
  1483.     u_char     *p, *last;
  1484.     ngx_str_t   name;

  1485.     if (u->conf->ssl_name) {
  1486.         if (ngx_http_complex_value(r, u->conf->ssl_name, &name) != NGX_OK) {
  1487.             return NGX_ERROR;
  1488.         }

  1489.     } else {
  1490.         name = u->ssl_name;
  1491.     }

  1492.     if (name.len == 0) {
  1493.         goto done;
  1494.     }

  1495.     /*
  1496.      * ssl name here may contain port, notably if derived from $proxy_host
  1497.      * or $http_host; we have to strip it
  1498.      */

  1499.     p = name.data;
  1500.     last = name.data + name.len;

  1501.     if (*p == '[') {
  1502.         p = ngx_strlchr(p, last, ']');

  1503.         if (p == NULL) {
  1504.             p = name.data;
  1505.         }
  1506.     }

  1507.     p = ngx_strlchr(p, last, ':');

  1508.     if (p != NULL) {
  1509.         name.len = p - name.data;
  1510.     }

  1511.     if (!u->conf->ssl_server_name) {
  1512.         goto done;
  1513.     }

  1514. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME

  1515.     /* as per RFC 6066, literal IPv4 and IPv6 addresses are not permitted */

  1516.     if (name.len == 0 || *name.data == '[') {
  1517.         goto done;
  1518.     }

  1519.     if (ngx_inet_addr(name.data, name.len) != INADDR_NONE) {
  1520.         goto done;
  1521.     }

  1522.     /*
  1523.      * SSL_set_tlsext_host_name() needs a null-terminated string,
  1524.      * hence we explicitly null-terminate name here
  1525.      */

  1526.     p = ngx_pnalloc(r->pool, name.len + 1);
  1527.     if (p == NULL) {
  1528.         return NGX_ERROR;
  1529.     }

  1530.     (void) ngx_cpystrn(p, name.data, name.len + 1);

  1531.     name.data = p;

  1532.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  1533.                    "upstream SSL server name: \"%s\"", name.data);

  1534.     if (SSL_set_tlsext_host_name(c->ssl->connection,
  1535.                                  (char *) name.data)
  1536.         == 0)
  1537.     {
  1538.         ngx_ssl_error(NGX_LOG_ERR, r->connection->log, 0,
  1539.                       "SSL_set_tlsext_host_name(\"%s\") failed", name.data);
  1540.         return NGX_ERROR;
  1541.     }

  1542. #endif

  1543. done:

  1544.     u->ssl_name = name;

  1545.     return NGX_OK;
  1546. }


  1547. static ngx_int_t
  1548. ‌ngx_http_upstream_ssl_certificate(ngx_http_request_t *r,
  1549.     ngx_http_upstream_t *u, ngx_connection_t *c)
  1550. {
  1551.     ngx_str_t  cert, key;

  1552.     if (ngx_http_complex_value(r, u->conf->ssl_certificate, &cert)
  1553.         != NGX_OK)
  1554.     {
  1555.         return NGX_ERROR;
  1556.     }

  1557.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0,
  1558.                    "http upstream ssl cert: \"%s\"", cert.data);

  1559.     if (*cert.data == '\0') {
  1560.         return NGX_OK;
  1561.     }

  1562.     if (ngx_http_complex_value(r, u->conf->ssl_certificate_key, &key)
  1563.         != NGX_OK)
  1564.     {
  1565.         return NGX_ERROR;
  1566.     }

  1567.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0,
  1568.                    "http upstream ssl key: \"%s\"", key.data);

  1569.     if (ngx_ssl_connection_certificate(c, r->pool, &cert, &key,
  1570.                                        u->conf->ssl_certificate_cache,
  1571.                                        u->conf->ssl_passwords)
  1572.         != NGX_OK)
  1573.     {
  1574.         return NGX_ERROR;
  1575.     }

  1576.     return NGX_OK;
  1577. }

  1578. #endif


  1579. static ngx_int_t
  1580. ‌ngx_http_upstream_reinit(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1581. {
  1582.     off_t         file_pos;
  1583.     ngx_chain_t  *cl;

  1584.     if (u->reinit_request(r) != NGX_OK) {
  1585.         return NGX_ERROR;
  1586.     }

  1587.     u->early_hints_length = 0;
  1588.     u->keepalive = 0;
  1589.     u->upgrade = 0;
  1590.     u->error = 0;

  1591.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  1592.     u->headers_in.content_length_n = -1;
  1593.     u->headers_in.last_modified_time = -1;

  1594.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  1595.                       sizeof(ngx_table_elt_t))
  1596.         != NGX_OK)
  1597.     {
  1598.         return NGX_ERROR;
  1599.     }

  1600.     if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  1601.                       sizeof(ngx_table_elt_t))
  1602.         != NGX_OK)
  1603.     {
  1604.         return NGX_ERROR;
  1605.     }

  1606.     /* reinit the request chain */

  1607.     file_pos = 0;

  1608.     for (cl = u->request_bufs; cl; cl = cl->next) {
  1609.         cl->buf->pos = cl->buf->start;

  1610.         /* there is at most one file */

  1611.         if (cl->buf->in_file) {
  1612.             cl->buf->file_pos = file_pos;
  1613.             file_pos = cl->buf->file_last;
  1614.         }
  1615.     }

  1616.     /* reinit the subrequest's ngx_output_chain() context */

  1617.     if (r->request_body && r->request_body->temp_file
  1618.         && r != r->main && u->output.buf)
  1619.     {
  1620.         u->output.free = ngx_alloc_chain_link(r->pool);
  1621.         if (u->output.free == NULL) {
  1622.             return NGX_ERROR;
  1623.         }

  1624.         u->output.free->buf = u->output.buf;
  1625.         u->output.free->next = NULL;

  1626.         u->output.buf->pos = u->output.buf->start;
  1627.         u->output.buf->last = u->output.buf->start;
  1628.     }

  1629.     u->output.buf = NULL;
  1630.     u->output.in = NULL;
  1631.     u->output.busy = NULL;

  1632.     /* reinit u->buffer */

  1633.     u->buffer.pos = u->buffer.start;

  1634. #if (NGX_HTTP_CACHE)

  1635.     if (r->cache) {
  1636.         u->buffer.pos += r->cache->header_start;
  1637.     }

  1638. #endif

  1639.     u->buffer.last = u->buffer.pos;

  1640.     return NGX_OK;
  1641. }


  1642. static void
  1643. ‌ngx_http_upstream_send_request(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1644.     ngx_uint_t do_write)
  1645. {
  1646.     ngx_int_t          rc;
  1647.     ngx_connection_t  *c;

  1648.     c = u->peer.connection;

  1649.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  1650.                    "http upstream send request");

  1651.     if (u->state->connect_time == (ngx_msec_t) -1) {
  1652.         u->state->connect_time = ngx_current_msec - u->start_time;
  1653.     }

  1654.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {
  1655.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1656.         return;
  1657.     }

  1658.     c->log->action = "sending request to upstream";

  1659.     rc = ngx_http_upstream_send_request_body(r, u, do_write);

  1660.     if (rc == NGX_ERROR) {
  1661.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1662.         return;
  1663.     }

  1664.     if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  1665.         ngx_http_upstream_finalize_request(r, u, rc);
  1666.         return;
  1667.     }

  1668.     if (rc == NGX_AGAIN) {
  1669.         if (!c->write->ready || u->request_body_blocked) {
  1670.             ngx_add_timer(c->write, u->conf->send_timeout);

  1671.         } else if (c->write->timer_set) {
  1672.             ngx_del_timer(c->write);
  1673.         }

  1674.         if (ngx_handle_write_event(c->write, u->conf->send_lowat) != NGX_OK) {
  1675.             ngx_http_upstream_finalize_request(r, u,
  1676.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1677.             return;
  1678.         }

  1679.         if (c->write->ready && c->tcp_nopush == NGX_TCP_NOPUSH_SET) {
  1680.             if (ngx_tcp_push(c->fd) == -1) {
  1681.                 ngx_log_error(NGX_LOG_CRIT, c->log, ngx_socket_errno,
  1682.                               ngx_tcp_push_n " failed");
  1683.                 ngx_http_upstream_finalize_request(r, u,
  1684.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1685.                 return;
  1686.             }

  1687.             c->tcp_nopush = NGX_TCP_NOPUSH_UNSET;
  1688.         }

  1689.         if (c->read->ready) {
  1690.             ngx_post_event(c->read, &ngx_posted_events);
  1691.         }

  1692.         return;
  1693.     }

  1694.     /* rc == NGX_OK */

  1695.     if (c->write->timer_set) {
  1696.         ngx_del_timer(c->write);
  1697.     }

  1698.     if (c->tcp_nopush == NGX_TCP_NOPUSH_SET) {
  1699.         if (ngx_tcp_push(c->fd) == -1) {
  1700.             ngx_log_error(NGX_LOG_CRIT, c->log, ngx_socket_errno,
  1701.                           ngx_tcp_push_n " failed");
  1702.             ngx_http_upstream_finalize_request(r, u,
  1703.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1704.             return;
  1705.         }

  1706.         c->tcp_nopush = NGX_TCP_NOPUSH_UNSET;
  1707.     }

  1708.     if (!u->conf->preserve_output) {
  1709.         u->write_event_handler = ngx_http_upstream_dummy_handler;
  1710.     }

  1711.     if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  1712.         ngx_http_upstream_finalize_request(r, u,
  1713.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1714.         return;
  1715.     }

  1716.     if (!u->request_body_sent) {
  1717.         u->request_body_sent = 1;

  1718.         if (u->header_sent) {
  1719.             return;
  1720.         }

  1721.         if (u->conf->ignore_input) {
  1722.             ngx_http_upstream_process_header(r, u);
  1723.             return;
  1724.         }

  1725.         ngx_add_timer(c->read, u->conf->read_timeout);

  1726.         if (c->read->ready) {
  1727.             ngx_http_upstream_process_header(r, u);
  1728.             return;
  1729.         }
  1730.     }
  1731. }


  1732. static ngx_int_t
  1733. ‌ngx_http_upstream_send_request_body(ngx_http_request_t *r,
  1734.     ngx_http_upstream_t *u, ngx_uint_t do_write)
  1735. {
  1736.     ngx_int_t                  rc;
  1737.     ngx_chain_t               *out, *cl, *ln;
  1738.     ngx_connection_t          *c;
  1739.     ngx_http_core_loc_conf_t  *clcf;

  1740.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  1741.                    "http upstream send request body");

  1742.     if (!r->request_body_no_buffering) {

  1743.         /* buffered request body */

  1744.         if (!u->request_sent) {
  1745.             u->request_sent = 1;
  1746.             out = u->request_bufs;

  1747.         } else {
  1748.             out = NULL;
  1749.         }

  1750.         rc = ngx_output_chain(&u->output, out);

  1751.         if (rc == NGX_AGAIN) {
  1752.             u->request_body_blocked = 1;

  1753.         } else {
  1754.             u->request_body_blocked = 0;
  1755.         }

  1756.         return rc;
  1757.     }

  1758.     if (!u->request_sent) {
  1759.         u->request_sent = 1;
  1760.         out = u->request_bufs;

  1761.         if (r->request_body->bufs) {
  1762.             for (cl = out; cl->next; cl = cl->next) { /* void */ }
  1763.             cl->next = r->request_body->bufs;
  1764.             r->request_body->bufs = NULL;
  1765.         }

  1766.         c = u->peer.connection;
  1767.         clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  1768.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  1769.             return NGX_ERROR;
  1770.         }

  1771.         r->read_event_handler = ngx_http_upstream_read_request_handler;

  1772.     } else {
  1773.         out = NULL;
  1774.     }

  1775.     for ( ;; ) {

  1776.         if (do_write) {
  1777.             rc = ngx_output_chain(&u->output, out);

  1778.             if (rc == NGX_ERROR) {
  1779.                 return NGX_ERROR;
  1780.             }

  1781.             while (out) {
  1782.                 ln = out;
  1783.                 out = out->next;
  1784.                 ngx_free_chain(r->pool, ln);
  1785.             }

  1786.             if (rc == NGX_AGAIN) {
  1787.                 u->request_body_blocked = 1;

  1788.             } else {
  1789.                 u->request_body_blocked = 0;
  1790.             }

  1791.             if (rc == NGX_OK && !r->reading_body) {
  1792.                 break;
  1793.             }
  1794.         }

  1795.         if (r->reading_body) {
  1796.             /* read client request body */

  1797.             rc = ngx_http_read_unbuffered_request_body(r);

  1798.             if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  1799.                 return rc;
  1800.             }

  1801.             out = r->request_body->bufs;
  1802.             r->request_body->bufs = NULL;
  1803.         }

  1804.         /* stop if there is nothing to send */

  1805.         if (out == NULL) {
  1806.             rc = NGX_AGAIN;
  1807.             break;
  1808.         }

  1809.         do_write = 1;
  1810.     }

  1811.     if (!r->reading_body) {
  1812.         if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {
  1813.             r->read_event_handler =
  1814.                                   ngx_http_upstream_rd_check_broken_connection;
  1815.         }
  1816.     }

  1817.     return rc;
  1818. }


  1819. static void
  1820. ‌ngx_http_upstream_send_request_handler(ngx_http_request_t *r,
  1821.     ngx_http_upstream_t *u)
  1822. {
  1823.     ngx_connection_t  *c;

  1824.     c = u->peer.connection;

  1825.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  1826.                    "http upstream send request handler");

  1827.     if (c->write->timedout) {
  1828.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1829.         return;
  1830.     }

  1831. #if (NGX_HTTP_SSL)

  1832.     if (u->ssl && c->ssl == NULL) {
  1833.         ngx_http_upstream_ssl_init_connection(r, u, c);
  1834.         return;
  1835.     }

  1836. #endif

  1837.     if (u->header_sent && !u->conf->preserve_output) {
  1838.         u->write_event_handler = ngx_http_upstream_dummy_handler;

  1839.         (void) ngx_handle_write_event(c->write, 0);

  1840.         return;
  1841.     }

  1842.     ngx_http_upstream_send_request(r, u, 1);
  1843. }


  1844. static void
  1845. ‌ngx_http_upstream_read_request_handler(ngx_http_request_t *r)
  1846. {
  1847.     ngx_connection_t     *c;
  1848.     ngx_http_upstream_t  *u;

  1849.     c = r->connection;
  1850.     u = r->upstream;

  1851.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  1852.                    "http upstream read request handler");

  1853.     if (c->read->timedout) {
  1854.         c->timedout = 1;
  1855.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  1856.         return;
  1857.     }

  1858.     ngx_http_upstream_send_request(r, u, 0);
  1859. }


  1860. static void
  1861. ‌ngx_http_upstream_process_header(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1862. {
  1863.     ssize_t            n;
  1864.     ngx_int_t          rc;
  1865.     ngx_connection_t  *c;

  1866.     c = u->peer.connection;

  1867.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  1868.                    "http upstream process header");

  1869.     c->log->action = "reading response header from upstream";

  1870.     if (c->read->timedout) {
  1871.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1872.         return;
  1873.     }

  1874.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {
  1875.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1876.         return;
  1877.     }

  1878.     if (u->buffer.start == NULL) {
  1879.         u->buffer.start = ngx_palloc(r->pool, u->conf->buffer_size);
  1880.         if (u->buffer.start == NULL) {
  1881.             ngx_http_upstream_finalize_request(r, u,
  1882.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1883.             return;
  1884.         }

  1885.         u->buffer.pos = u->buffer.start;
  1886.         u->buffer.last = u->buffer.start;
  1887.         u->buffer.end = u->buffer.start + u->conf->buffer_size;
  1888.         u->buffer.temporary = 1;

  1889.         u->buffer.tag = u->output.tag;

  1890.         if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  1891.                           sizeof(ngx_table_elt_t))
  1892.             != NGX_OK)
  1893.         {
  1894.             ngx_http_upstream_finalize_request(r, u,
  1895.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1896.             return;
  1897.         }

  1898.         if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  1899.                           sizeof(ngx_table_elt_t))
  1900.             != NGX_OK)
  1901.         {
  1902.             ngx_http_upstream_finalize_request(r, u,
  1903.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1904.             return;
  1905.         }

  1906. #if (NGX_HTTP_CACHE)

  1907.         if (r->cache) {
  1908.             u->buffer.pos += r->cache->header_start;
  1909.             u->buffer.last = u->buffer.pos;
  1910.         }
  1911. #endif
  1912.     }

  1913.     if (u->conf->ignore_input) {
  1914.         rc = u->process_header(r);
  1915.         goto done;
  1916.     }

  1917.     for ( ;; ) {

  1918.         n = c->recv(c, u->buffer.last, u->buffer.end - u->buffer.last);

  1919.         if (n == NGX_AGAIN) {
  1920. #if 0
  1921.             ngx_add_timer(rev, u->read_timeout);
  1922. #endif

  1923.             if (ngx_handle_read_event(c->read, 0) != NGX_OK) {
  1924.                 ngx_http_upstream_finalize_request(r, u,
  1925.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1926.                 return;
  1927.             }

  1928.             return;
  1929.         }

  1930.         if (n == 0) {
  1931.             ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1932.                           "upstream prematurely closed connection");
  1933.         }

  1934.         if (n == NGX_ERROR || n == 0) {
  1935.             ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1936.             return;
  1937.         }

  1938. #if (NGX_HTTP_SSL)
  1939.         if (u->ssl && c->ssl == NULL) {
  1940.             ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1941.                           "upstream prematurely sent response");
  1942.             ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1943.             return;
  1944.         }
  1945. #endif

  1946.         u->state->bytes_received += n;

  1947.         u->buffer.last += n;

  1948. #if 0
  1949.         u->valid_header_in = 0;

  1950.         u->peer.cached = 0;
  1951. #endif

  1952.         u->response_received = 1;

  1953. again:

  1954.         rc = u->process_header(r);

  1955.         if (rc == NGX_AGAIN) {

  1956.             if (u->buffer.last == u->buffer.end) {
  1957.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1958.                               "upstream sent too big header");

  1959.                 ngx_http_upstream_next(r, u,
  1960.                                        NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  1961.                 return;
  1962.             }

  1963.             continue;
  1964.         }

  1965.         if (rc == NGX_HTTP_UPSTREAM_EARLY_HINTS) {
  1966.             rc = ngx_http_upstream_process_early_hints(r, u);

  1967.             if (rc == NGX_OK) {
  1968.                 goto again;
  1969.             }
  1970.         }

  1971.         break;
  1972.     }

  1973. done:

  1974.     if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  1975.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  1976.         return;
  1977.     }

  1978.     if (rc == NGX_ERROR) {
  1979.         ngx_http_upstream_finalize_request(r, u,
  1980.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1981.         return;
  1982.     }

  1983.     /* rc == NGX_OK */

  1984.     u->state->header_time = ngx_current_msec - u->start_time;

  1985.     if (u->headers_in.status_n >= NGX_HTTP_SPECIAL_RESPONSE) {

  1986.         if (ngx_http_upstream_test_next(r, u) == NGX_OK) {
  1987.             return;
  1988.         }

  1989.         if (ngx_http_upstream_intercept_errors(r, u) == NGX_OK) {
  1990.             return;
  1991.         }
  1992.     }

  1993.     if (u->peer.notify) {
  1994.         u->peer.notify(&u->peer, u->peer.data, NGX_HTTP_UPSTREAM_NOTIFY_HEADER);
  1995.     }

  1996.     rc = ngx_http_upstream_process_headers(r, u);

  1997.     if (rc == NGX_DONE) {
  1998.         return;
  1999.     }

  2000.     if (rc == NGX_ERROR) {
  2001.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2002.         return;
  2003.     }

  2004.     ngx_http_upstream_send_response(r, u);
  2005. }


  2006. static ngx_int_t
  2007. ‌ngx_http_upstream_process_early_hints(ngx_http_request_t *r,
  2008.     ngx_http_upstream_t *u)
  2009. {
  2010.     u_char            *p;
  2011.     ngx_uint_t         i;
  2012.     ngx_list_part_t   *part;
  2013.     ngx_table_elt_t   *h, *ho;
  2014.     ngx_connection_t  *c;

  2015.     c = r->connection;

  2016.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0, "http upstream early hints");

  2017.     if (u->conf->pass_early_hints) {

  2018.         u->early_hints_length += u->buffer.pos - u->buffer.start;

  2019.         if (u->early_hints_length <= (off_t) u->conf->buffer_size) {

  2020.             part = &u->headers_in.headers.part;
  2021.             h = part->elts;

  2022.             for (i = 0; /* void */; i++) {

  2023.                 if (i >= part->nelts) {
  2024.                     if (part->next == NULL) {
  2025.                         break;
  2026.                     }

  2027.                     part = part->next;
  2028.                     h = part->elts;
  2029.                     i = 0;
  2030.                 }

  2031.                 if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2032.                                   h[i].lowcase_key, h[i].key.len))
  2033.                 {
  2034.                     continue;
  2035.                 }

  2036.                 ho = ngx_list_push(&r->headers_out.headers);
  2037.                 if (ho == NULL) {
  2038.                     return NGX_ERROR;
  2039.                 }

  2040.                 *ho = h[i];
  2041.             }

  2042.             if (ngx_http_send_early_hints(r) == NGX_ERROR) {
  2043.                 return NGX_ERROR;
  2044.             }

  2045.             if (c->buffered) {
  2046.                 if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  2047.                     return NGX_ERROR;
  2048.                 }

  2049.                 r->write_event_handler = ngx_http_upstream_early_hints_writer;
  2050.             }

  2051.         } else {
  2052.             ngx_log_error(NGX_LOG_INFO, c->log, 0,
  2053.                           "upstream sent too big early hints");
  2054.         }
  2055.     }

  2056.     ngx_http_clean_header(r);

  2057.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  2058.     u->headers_in.content_length_n = -1;
  2059.     u->headers_in.last_modified_time = -1;

  2060.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  2061.                       sizeof(ngx_table_elt_t))
  2062.         != NGX_OK)
  2063.     {
  2064.         return NGX_ERROR;
  2065.     }

  2066.     if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  2067.                       sizeof(ngx_table_elt_t))
  2068.         != NGX_OK)
  2069.     {
  2070.         return NGX_ERROR;
  2071.     }

  2072.     p = u->buffer.pos;

  2073.     u->buffer.pos = u->buffer.start;

  2074. #if (NGX_HTTP_CACHE)

  2075.     if (r->cache) {
  2076.         u->buffer.pos += r->cache->header_start;
  2077.     }

  2078. #endif

  2079.     u->buffer.last = ngx_movemem(u->buffer.pos, p, u->buffer.last - p);

  2080.     return NGX_OK;
  2081. }


  2082. static void
  2083. ‌ngx_http_upstream_early_hints_writer(ngx_http_request_t *r)
  2084. {
  2085.     ngx_connection_t     *c;
  2086.     ngx_http_upstream_t  *u;

  2087.     c = r->connection;
  2088.     u = r->upstream;

  2089.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2090.                    "http upstream early hints writer");

  2091.     c->log->action = "sending early hints to client";

  2092.     if (ngx_http_write_filter(r, NULL) == NGX_ERROR) {
  2093.         ngx_http_upstream_finalize_request(r, u,
  2094.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  2095.         return;
  2096.     }

  2097.     if (!c->buffered) {
  2098.         if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {
  2099.             r->write_event_handler =
  2100.                                   ngx_http_upstream_wr_check_broken_connection;

  2101.         } else {
  2102.             r->write_event_handler = ngx_http_request_empty_handler;
  2103.         }
  2104.     }

  2105.     if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  2106.         ngx_http_upstream_finalize_request(r, u,
  2107.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  2108.     }
  2109. }


  2110. static ngx_int_t
  2111. ‌ngx_http_upstream_test_next(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2112. {
  2113.     ngx_msec_t                 timeout;
  2114.     ngx_uint_t                 status, mask;
  2115.     ngx_http_upstream_next_t  *un;

  2116.     status = u->headers_in.status_n;

  2117.     for (un = ngx_http_upstream_next_errors; un->status; un++) {

  2118.         if (status != un->status) {
  2119.             continue;
  2120.         }

  2121.         timeout = u->conf->next_upstream_timeout;

  2122.         if (u->request_sent
  2123.             && (r->method & (NGX_HTTP_POST|NGX_HTTP_LOCK|NGX_HTTP_PATCH)))
  2124.         {
  2125.             mask = un->mask | NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT;

  2126.         } else {
  2127.             mask = un->mask;
  2128.         }

  2129.         if (u->peer.tries > 1
  2130.             && ((u->conf->next_upstream & mask) == mask)
  2131.             && !(u->request_sent && r->request_body_no_buffering)
  2132.             && !(timeout && ngx_current_msec - u->peer.start_time >= timeout))
  2133.         {
  2134.             ngx_http_upstream_next(r, u, un->mask);
  2135.             return NGX_OK;
  2136.         }

  2137. #if (NGX_HTTP_CACHE)

  2138.         if (u->cache_status == NGX_HTTP_CACHE_EXPIRED
  2139.             && (u->conf->cache_use_stale & un->mask))
  2140.         {
  2141.             ngx_int_t  rc;

  2142.             rc = u->reinit_request(r);

  2143.             if (rc != NGX_OK) {
  2144.                 ngx_http_upstream_finalize_request(r, u, rc);
  2145.                 return NGX_OK;
  2146.             }

  2147.             u->cache_status = NGX_HTTP_CACHE_STALE;
  2148.             rc = ngx_http_upstream_cache_send(r, u);

  2149.             if (rc == NGX_DONE) {
  2150.                 return NGX_OK;
  2151.             }

  2152.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  2153.                 rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  2154.             }

  2155.             ngx_http_upstream_finalize_request(r, u, rc);
  2156.             return NGX_OK;
  2157.         }

  2158. #endif

  2159.         break;
  2160.     }

  2161. #if (NGX_HTTP_CACHE)

  2162.     if (status == NGX_HTTP_NOT_MODIFIED
  2163.         && u->cache_status == NGX_HTTP_CACHE_EXPIRED
  2164.         && u->conf->cache_revalidate)
  2165.     {
  2166.         time_t     now, valid, updating, error;
  2167.         ngx_int_t  rc;

  2168.         ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  2169.                        "http upstream not modified");

  2170.         now = ngx_time();

  2171.         valid = r->cache->valid_sec;
  2172.         updating = r->cache->updating_sec;
  2173.         error = r->cache->error_sec;

  2174.         rc = u->reinit_request(r);

  2175.         if (rc != NGX_OK) {
  2176.             ngx_http_upstream_finalize_request(r, u, rc);
  2177.             return NGX_OK;
  2178.         }

  2179.         u->cache_status = NGX_HTTP_CACHE_REVALIDATED;
  2180.         rc = ngx_http_upstream_cache_send(r, u);

  2181.         if (rc == NGX_DONE) {
  2182.             return NGX_OK;
  2183.         }

  2184.         if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  2185.             rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  2186.         }

  2187.         if (valid == 0) {
  2188.             valid = r->cache->valid_sec;
  2189.             updating = r->cache->updating_sec;
  2190.             error = r->cache->error_sec;
  2191.         }

  2192.         if (valid == 0) {
  2193.             valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2194.                                               u->headers_in.status_n);
  2195.             if (valid) {
  2196.                 valid = now + valid;
  2197.             }
  2198.         }

  2199.         if (valid) {
  2200.             r->cache->valid_sec = valid;
  2201.             r->cache->updating_sec = updating;
  2202.             r->cache->error_sec = error;

  2203.             r->cache->date = now;

  2204.             ngx_http_file_cache_update_header(r);
  2205.         }

  2206.         ngx_http_upstream_finalize_request(r, u, rc);
  2207.         return NGX_OK;
  2208.     }

  2209. #endif

  2210.     return NGX_DECLINED;
  2211. }


  2212. static ngx_int_t
  2213. ‌ngx_http_upstream_intercept_errors(ngx_http_request_t *r,
  2214.     ngx_http_upstream_t *u)
  2215. {
  2216.     ngx_int_t                  status;
  2217.     ngx_uint_t                 i;
  2218.     ngx_table_elt_t           *h, *ho, **ph;
  2219.     ngx_http_err_page_t       *err_page;
  2220.     ngx_http_core_loc_conf_t  *clcf;

  2221.     status = u->headers_in.status_n;

  2222.     if (status == NGX_HTTP_NOT_FOUND && u->conf->intercept_404) {
  2223.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_NOT_FOUND);
  2224.         return NGX_OK;
  2225.     }

  2226.     if (!u->conf->intercept_errors) {
  2227.         return NGX_DECLINED;
  2228.     }

  2229.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2230.     if (clcf->error_pages == NULL) {
  2231.         return NGX_DECLINED;
  2232.     }

  2233.     err_page = clcf->error_pages->elts;
  2234.     for (i = 0; i < clcf->error_pages->nelts; i++) {

  2235.         if (err_page[i].status == status) {

  2236.             if (status == NGX_HTTP_UNAUTHORIZED
  2237.                 && u->headers_in.www_authenticate)
  2238.             {
  2239.                 h = u->headers_in.www_authenticate;
  2240.                 ph = &r->headers_out.www_authenticate;

  2241.                 while (h) {
  2242.                     ho = ngx_list_push(&r->headers_out.headers);

  2243.                     if (ho == NULL) {
  2244.                         ngx_http_upstream_finalize_request(r, u,
  2245.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  2246.                         return NGX_OK;
  2247.                     }

  2248.                     *ho = *h;
  2249.                     ho->next = NULL;

  2250.                     *ph = ho;
  2251.                     ph = &ho->next;

  2252.                     h = h->next;
  2253.                 }
  2254.             }

  2255. #if (NGX_HTTP_CACHE)

  2256.             if (r->cache) {

  2257.                 if (u->headers_in.no_cache || u->headers_in.expired) {
  2258.                     u->cacheable = 0;
  2259.                 }

  2260.                 if (u->cacheable) {
  2261.                     time_t  valid;

  2262.                     valid = r->cache->valid_sec;

  2263.                     if (valid == 0) {
  2264.                         valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2265.                                                           status);
  2266.                         if (valid) {
  2267.                             r->cache->valid_sec = ngx_time() + valid;
  2268.                         }
  2269.                     }

  2270.                     if (valid) {
  2271.                         r->cache->error = status;
  2272.                     }
  2273.                 }

  2274.                 ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2275.             }
  2276. #endif
  2277.             ngx_http_upstream_finalize_request(r, u, status);

  2278.             return NGX_OK;
  2279.         }
  2280.     }

  2281.     return NGX_DECLINED;
  2282. }


  2283. static ngx_int_t
  2284. ‌ngx_http_upstream_test_connect(ngx_connection_t *c)
  2285. {
  2286.     int        err;
  2287.     socklen_t  len;

  2288. #if (NGX_HAVE_KQUEUE)

  2289.     if (ngx_event_flags & NGX_USE_KQUEUE_EVENT)  {
  2290.         if (c->write->pending_eof || c->read->pending_eof) {
  2291.             if (c->write->pending_eof) {
  2292.                 err = c->write->kq_errno;

  2293.             } else {
  2294.                 err = c->read->kq_errno;
  2295.             }

  2296.             c->log->action = "connecting to upstream";
  2297.             (void) ngx_connection_error(c, err,
  2298.                                     "kevent() reported that connect() failed");
  2299.             return NGX_ERROR;
  2300.         }

  2301.     } else
  2302. #endif
  2303.     {
  2304.         err = 0;
  2305.         len = sizeof(int);

  2306.         /*
  2307.          * BSDs and Linux return 0 and set a pending error in err
  2308.          * Solaris returns -1 and sets errno
  2309.          */

  2310.         if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, (void *) &err, &len)
  2311.             == -1)
  2312.         {
  2313.             err = ngx_socket_errno;
  2314.         }

  2315.         if (err) {
  2316.             c->log->action = "connecting to upstream";
  2317.             (void) ngx_connection_error(c, err, "connect() failed");
  2318.             return NGX_ERROR;
  2319.         }
  2320.     }

  2321.     return NGX_OK;
  2322. }


  2323. static ngx_int_t
  2324. ‌ngx_http_upstream_process_headers(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2325. {
  2326.     ngx_str_t                       uri, args;
  2327.     ngx_uint_t                      i, flags;
  2328.     ngx_list_part_t                *part;
  2329.     ngx_table_elt_t                *h;
  2330.     ngx_http_upstream_header_t     *hh;
  2331.     ngx_http_upstream_main_conf_t  *umcf;

  2332.     umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);

  2333.     if (u->headers_in.no_cache || u->headers_in.expired) {
  2334.         u->cacheable = 0;
  2335.     }

  2336.     if (u->headers_in.x_accel_redirect
  2337.         && !(u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_REDIRECT))
  2338.     {
  2339.         if (u->cleanup) {
  2340.             ngx_http_upstream_finalize_request(r, u, NGX_DECLINED);
  2341.         }

  2342.         part = &u->headers_in.headers.part;
  2343.         h = part->elts;

  2344.         for (i = 0; /* void */; i++) {

  2345.             if (i >= part->nelts) {
  2346.                 if (part->next == NULL) {
  2347.                     break;
  2348.                 }

  2349.                 part = part->next;
  2350.                 h = part->elts;
  2351.                 i = 0;
  2352.             }

  2353.             if (h[i].hash == 0) {
  2354.                 continue;
  2355.             }

  2356.             hh = ngx_hash_find(&umcf->headers_in_hash, h[i].hash,
  2357.                                h[i].lowcase_key, h[i].key.len);

  2358.             if (hh && hh->redirect) {
  2359.                 if (hh->copy_handler(r, &h[i], hh->conf) != NGX_OK) {
  2360.                     ngx_http_finalize_request(r,
  2361.                                               NGX_HTTP_INTERNAL_SERVER_ERROR);
  2362.                     return NGX_DONE;
  2363.                 }
  2364.             }
  2365.         }

  2366.         uri = u->headers_in.x_accel_redirect->value;

  2367.         if (uri.data[0] == '@') {
  2368.             ngx_http_named_location(r, &uri);

  2369.         } else {
  2370.             ngx_str_null(&args);
  2371.             flags = NGX_HTTP_LOG_UNSAFE;

  2372.             if (ngx_http_parse_unsafe_uri(r, &uri, &args, &flags) != NGX_OK) {
  2373.                 ngx_http_finalize_request(r, NGX_HTTP_NOT_FOUND);
  2374.                 return NGX_DONE;
  2375.             }

  2376.             if (r->method != NGX_HTTP_HEAD) {
  2377.                 r->method = NGX_HTTP_GET;
  2378.                 r->method_name = ngx_http_core_get_method;
  2379.             }

  2380.             ngx_http_internal_redirect(r, &uri, &args);
  2381.         }

  2382.         ngx_http_finalize_request(r, NGX_DONE);
  2383.         return NGX_DONE;
  2384.     }

  2385.     part = &u->headers_in.headers.part;
  2386.     h = part->elts;

  2387.     for (i = 0; /* void */; i++) {

  2388.         if (i >= part->nelts) {
  2389.             if (part->next == NULL) {
  2390.                 break;
  2391.             }

  2392.             part = part->next;
  2393.             h = part->elts;
  2394.             i = 0;
  2395.         }

  2396.         if (h[i].hash == 0) {
  2397.             continue;
  2398.         }

  2399.         if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2400.                           h[i].lowcase_key, h[i].key.len))
  2401.         {
  2402.             continue;
  2403.         }

  2404.         hh = ngx_hash_find(&umcf->headers_in_hash, h[i].hash,
  2405.                            h[i].lowcase_key, h[i].key.len);

  2406.         if (hh) {
  2407.             if (hh->copy_handler(r, &h[i], hh->conf) != NGX_OK) {
  2408.                 return NGX_ERROR;
  2409.             }

  2410.             continue;
  2411.         }

  2412.         if (ngx_http_upstream_copy_header_line(r, &h[i], 0) != NGX_OK) {
  2413.             return NGX_ERROR;
  2414.         }
  2415.     }

  2416.     if (r->headers_out.server && r->headers_out.server->value.data == NULL) {
  2417.         r->headers_out.server->hash = 0;
  2418.     }

  2419.     if (r->headers_out.date && r->headers_out.date->value.data == NULL) {
  2420.         r->headers_out.date->hash = 0;
  2421.     }

  2422.     r->headers_out.status = u->headers_in.status_n;
  2423.     r->headers_out.status_line = u->headers_in.status_line;

  2424.     r->headers_out.content_length_n = u->headers_in.content_length_n;

  2425.     r->disable_not_modified = !u->cacheable;

  2426.     if (u->conf->force_ranges) {
  2427.         r->allow_ranges = 1;
  2428.         r->single_range = 1;

  2429. #if (NGX_HTTP_CACHE)
  2430.         if (r->cached) {
  2431.             r->single_range = 0;
  2432.         }
  2433. #endif
  2434.     }

  2435.     u->length = -1;

  2436.     return NGX_OK;
  2437. }


  2438. static ngx_int_t
  2439. ‌ngx_http_upstream_process_trailers(ngx_http_request_t *r,
  2440.     ngx_http_upstream_t *u)
  2441. {
  2442.     ngx_uint_t        i;
  2443.     ngx_list_part_t  *part;
  2444.     ngx_table_elt_t  *h, *ho;

  2445.     if (!u->conf->pass_trailers) {
  2446.         return NGX_OK;
  2447.     }

  2448.     part = &u->headers_in.trailers.part;
  2449.     h = part->elts;

  2450.     for (i = 0; /* void */; i++) {

  2451.         if (i >= part->nelts) {
  2452.             if (part->next == NULL) {
  2453.                 break;
  2454.             }

  2455.             part = part->next;
  2456.             h = part->elts;
  2457.             i = 0;
  2458.         }

  2459.         if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2460.                           h[i].lowcase_key, h[i].key.len))
  2461.         {
  2462.             continue;
  2463.         }

  2464.         ho = ngx_list_push(&r->headers_out.trailers);
  2465.         if (ho == NULL) {
  2466.             return NGX_ERROR;
  2467.         }

  2468.         *ho = h[i];
  2469.     }

  2470.     return NGX_OK;
  2471. }


  2472. static void
  2473. ‌ngx_http_upstream_send_response(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2474. {
  2475.     ssize_t                    n;
  2476.     ngx_int_t                  rc;
  2477.     ngx_event_pipe_t          *p;
  2478.     ngx_connection_t          *c;
  2479.     ngx_http_core_loc_conf_t  *clcf;

  2480.     rc = ngx_http_send_header(r);

  2481.     if (rc == NGX_ERROR || rc > NGX_OK || r->post_action) {
  2482.         ngx_http_upstream_finalize_request(r, u, rc);
  2483.         return;
  2484.     }

  2485.     u->header_sent = 1;

  2486.     if (u->upgrade) {

  2487. #if (NGX_HTTP_CACHE)

  2488.         if (r->cache) {
  2489.             ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2490.         }

  2491. #endif

  2492.         ngx_http_upstream_upgrade(r, u);
  2493.         return;
  2494.     }

  2495.     c = r->connection;

  2496.     if (r->header_only) {

  2497.         if (!u->buffering) {
  2498.             ngx_http_upstream_finalize_request(r, u, rc);
  2499.             return;
  2500.         }

  2501.         if (!u->cacheable && !u->store) {
  2502.             ngx_http_upstream_finalize_request(r, u, rc);
  2503.             return;
  2504.         }

  2505.         u->pipe->downstream_error = 1;
  2506.     }

  2507.     if (r->request_body && r->request_body->temp_file
  2508.         && r == r->main && !r->preserve_body
  2509.         && !u->conf->preserve_output)
  2510.     {
  2511.         ngx_pool_run_cleanup_file(r->pool, r->request_body->temp_file->file.fd);
  2512.         r->request_body->temp_file->file.fd = NGX_INVALID_FILE;
  2513.     }

  2514.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2515.     if (!u->buffering) {

  2516. #if (NGX_HTTP_CACHE)

  2517.         if (r->cache) {
  2518.             ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2519.         }

  2520. #endif

  2521.         if (u->input_filter == NULL) {
  2522.             u->input_filter_init = ngx_http_upstream_non_buffered_filter_init;
  2523.             u->input_filter = ngx_http_upstream_non_buffered_filter;
  2524.             u->input_filter_ctx = r;
  2525.         }

  2526.         u->read_event_handler = ngx_http_upstream_process_non_buffered_upstream;
  2527.         r->write_event_handler =
  2528.                              ngx_http_upstream_process_non_buffered_downstream;

  2529.         r->limit_rate = 0;
  2530.         r->limit_rate_set = 1;

  2531.         if (u->input_filter_init(u->input_filter_ctx) == NGX_ERROR) {
  2532.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2533.             return;
  2534.         }

  2535.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  2536.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2537.             return;
  2538.         }

  2539.         n = u->buffer.last - u->buffer.pos;

  2540.         if (n) {
  2541.             u->buffer.last = u->buffer.pos;

  2542.             u->state->response_length += n;

  2543.             if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  2544.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2545.                 return;
  2546.             }

  2547.             ngx_http_upstream_process_non_buffered_downstream(r);

  2548.         } else {
  2549.             u->buffer.pos = u->buffer.start;
  2550.             u->buffer.last = u->buffer.start;

  2551.             if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {
  2552.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2553.                 return;
  2554.             }

  2555.             ngx_http_upstream_process_non_buffered_upstream(r, u);
  2556.         }

  2557.         return;
  2558.     }

  2559.     /* TODO: preallocate event_pipe bufs, look "Content-Length" */

  2560. #if (NGX_HTTP_CACHE)

  2561.     if (r->cache && r->cache->file.fd != NGX_INVALID_FILE) {
  2562.         ngx_pool_run_cleanup_file(r->pool, r->cache->file.fd);
  2563.         r->cache->file.fd = NGX_INVALID_FILE;
  2564.     }

  2565.     switch (ngx_http_test_predicates(r, u->conf->no_cache)) {

  2566.     case NGX_ERROR:
  2567.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2568.         return;

  2569.     case NGX_DECLINED:
  2570.         u->cacheable = 0;
  2571.         break;

  2572.     default: /* NGX_OK */

  2573.         if (u->cache_status == NGX_HTTP_CACHE_BYPASS) {

  2574.             /* create cache if previously bypassed */

  2575.             if (ngx_http_file_cache_create(r) != NGX_OK) {
  2576.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2577.                 return;
  2578.             }
  2579.         }

  2580.         break;
  2581.     }

  2582.     if (u->cacheable) {
  2583.         time_t  now, valid;

  2584.         now = ngx_time();

  2585.         valid = r->cache->valid_sec;

  2586.         if (valid == 0) {
  2587.             valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2588.                                               u->headers_in.status_n);
  2589.             if (valid) {
  2590.                 r->cache->valid_sec = now + valid;
  2591.             }
  2592.         }

  2593.         if (valid) {
  2594.             r->cache->date = now;
  2595.             r->cache->body_start = (u_short) (u->buffer.pos - u->buffer.start);

  2596.             if (u->headers_in.status_n == NGX_HTTP_OK
  2597.                 || u->headers_in.status_n == NGX_HTTP_PARTIAL_CONTENT)
  2598.             {
  2599.                 r->cache->last_modified = u->headers_in.last_modified_time;

  2600.                 if (u->headers_in.etag) {
  2601.                     r->cache->etag = u->headers_in.etag->value;

  2602.                 } else {
  2603.                     ngx_str_null(&r->cache->etag);
  2604.                 }

  2605.             } else {
  2606.                 r->cache->last_modified = -1;
  2607.                 ngx_str_null(&r->cache->etag);
  2608.             }

  2609.             if (ngx_http_file_cache_set_header(r, u->buffer.start) != NGX_OK) {
  2610.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2611.                 return;
  2612.             }

  2613.         } else {
  2614.             u->cacheable = 0;
  2615.         }
  2616.     }

  2617.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2618.                    "http cacheable: %d", u->cacheable);

  2619.     if (u->cacheable == 0 && r->cache) {
  2620.         ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2621.     }

  2622.     if (r->header_only && !u->cacheable && !u->store) {
  2623.         ngx_http_upstream_finalize_request(r, u, 0);
  2624.         return;
  2625.     }

  2626. #endif

  2627.     p = u->pipe;

  2628.     p->output_filter = ngx_http_upstream_output_filter;
  2629.     p->output_ctx = r;
  2630.     p->tag = u->output.tag;
  2631.     p->bufs = u->conf->bufs;
  2632.     p->busy_size = u->conf->busy_buffers_size;
  2633.     p->upstream = u->peer.connection;
  2634.     p->downstream = c;
  2635.     p->pool = r->pool;
  2636.     p->log = c->log;
  2637.     p->limit_rate = ngx_http_complex_value_size(r, u->conf->limit_rate, 0);
  2638.     p->start_sec = ngx_time();

  2639.     p->cacheable = u->cacheable || u->store;

  2640.     p->temp_file = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t));
  2641.     if (p->temp_file == NULL) {
  2642.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2643.         return;
  2644.     }

  2645.     p->temp_file->file.fd = NGX_INVALID_FILE;
  2646.     p->temp_file->file.log = c->log;
  2647.     p->temp_file->path = u->conf->temp_path;
  2648.     p->temp_file->pool = r->pool;

  2649.     if (p->cacheable) {
  2650.         p->temp_file->persistent = 1;

  2651. #if (NGX_HTTP_CACHE)
  2652.         if (r->cache && !r->cache->file_cache->use_temp_path) {
  2653.             p->temp_file->path = r->cache->file_cache->path;
  2654.             p->temp_file->file.name = r->cache->file.name;
  2655.         }
  2656. #endif

  2657.     } else {
  2658.         p->temp_file->log_level = NGX_LOG_WARN;
  2659.         p->temp_file->warn = "an upstream response is buffered "
  2660.                              "to a temporary file";
  2661.     }

  2662.     p->max_temp_file_size = u->conf->max_temp_file_size;
  2663.     p->temp_file_write_size = u->conf->temp_file_write_size;

  2664. #if (NGX_THREADS)
  2665.     if (clcf->aio == NGX_HTTP_AIO_THREADS && clcf->aio_write) {
  2666.         p->thread_handler = ngx_http_upstream_thread_handler;
  2667.         p->thread_ctx = r;
  2668.     }
  2669. #endif

  2670.     p->preread_bufs = ngx_alloc_chain_link(r->pool);
  2671.     if (p->preread_bufs == NULL) {
  2672.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2673.         return;
  2674.     }

  2675.     p->preread_bufs->buf = &u->buffer;
  2676.     p->preread_bufs->next = NULL;
  2677.     u->buffer.recycled = 1;

  2678.     p->preread_size = u->buffer.last - u->buffer.pos;

  2679.     if (u->cacheable) {

  2680.         p->buf_to_file = ngx_calloc_buf(r->pool);
  2681.         if (p->buf_to_file == NULL) {
  2682.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2683.             return;
  2684.         }

  2685.         p->buf_to_file->start = u->buffer.start;
  2686.         p->buf_to_file->pos = u->buffer.start;
  2687.         p->buf_to_file->last = u->buffer.pos;
  2688.         p->buf_to_file->temporary = 1;
  2689.     }

  2690.     /* TODO: p->free_bufs = 0 if use ngx_create_chain_of_bufs() */
  2691.     p->free_bufs = 1;

  2692.     /*
  2693.      * event_pipe would do u->buffer.last += p->preread_size
  2694.      * as though these bytes were read
  2695.      */
  2696.     u->buffer.last = u->buffer.pos;

  2697.     if (u->conf->cyclic_temp_file) {

  2698.         /*
  2699.          * we need to disable the use of sendfile() if we use cyclic temp file
  2700.          * because the writing a new data may interfere with sendfile()
  2701.          * that uses the same kernel file pages (at least on FreeBSD)
  2702.          */

  2703.         p->cyclic_temp_file = 1;
  2704.         c->sendfile = 0;

  2705.     } else {
  2706.         p->cyclic_temp_file = 0;
  2707.     }

  2708.     p->read_timeout = u->conf->read_timeout;
  2709.     p->send_timeout = clcf->send_timeout;
  2710.     p->send_lowat = clcf->send_lowat;

  2711.     p->length = -1;

  2712.     if (u->input_filter_init
  2713.         && u->input_filter_init(p->input_ctx) != NGX_OK)
  2714.     {
  2715.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2716.         return;
  2717.     }

  2718.     u->read_event_handler = ngx_http_upstream_process_upstream;
  2719.     r->write_event_handler = ngx_http_upstream_process_downstream;

  2720.     ngx_http_upstream_process_upstream(r, u);
  2721. }


  2722. static void
  2723. ‌ngx_http_upstream_upgrade(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2724. {
  2725.     ngx_connection_t          *c;
  2726.     ngx_http_core_loc_conf_t  *clcf;

  2727.     c = r->connection;
  2728.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2729.     /* TODO: prevent upgrade if not requested or not possible */

  2730.     if (r != r->main) {
  2731.         ngx_log_error(NGX_LOG_ERR, c->log, 0,
  2732.                       "connection upgrade in subrequest");
  2733.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2734.         return;
  2735.     }

  2736.     r->keepalive = 0;
  2737.     c->log->action = "proxying upgraded connection";

  2738.     u->read_event_handler = ngx_http_upstream_upgraded_read_upstream;
  2739.     u->write_event_handler = ngx_http_upstream_upgraded_write_upstream;
  2740.     r->read_event_handler = ngx_http_upstream_upgraded_read_downstream;
  2741.     r->write_event_handler = ngx_http_upstream_upgraded_write_downstream;

  2742.     if (clcf->tcp_nodelay) {

  2743.         if (ngx_tcp_nodelay(c) != NGX_OK) {
  2744.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2745.             return;
  2746.         }

  2747.         if (ngx_tcp_nodelay(u->peer.connection) != NGX_OK) {
  2748.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2749.             return;
  2750.         }
  2751.     }

  2752.     if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {
  2753.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2754.         return;
  2755.     }

  2756.     if (u->peer.connection->read->ready
  2757.         || u->buffer.pos != u->buffer.last)
  2758.     {
  2759.         ngx_post_event(c->read, &ngx_posted_events);
  2760.         ngx_http_upstream_process_upgraded(r, 1, 1);
  2761.         return;
  2762.     }

  2763.     ngx_http_upstream_process_upgraded(r, 0, 1);
  2764. }


  2765. static void
  2766. ‌ngx_http_upstream_upgraded_read_downstream(ngx_http_request_t *r)
  2767. {
  2768.     ngx_http_upstream_process_upgraded(r, 0, 0);
  2769. }


  2770. static void
  2771. ‌ngx_http_upstream_upgraded_write_downstream(ngx_http_request_t *r)
  2772. {
  2773.     ngx_http_upstream_process_upgraded(r, 1, 1);
  2774. }


  2775. static void
  2776. ‌ngx_http_upstream_upgraded_read_upstream(ngx_http_request_t *r,
  2777.     ngx_http_upstream_t *u)
  2778. {
  2779.     ngx_http_upstream_process_upgraded(r, 1, 0);
  2780. }


  2781. static void
  2782. ‌ngx_http_upstream_upgraded_write_upstream(ngx_http_request_t *r,
  2783.     ngx_http_upstream_t *u)
  2784. {
  2785.     ngx_http_upstream_process_upgraded(r, 0, 1);
  2786. }


  2787. static void
  2788. ‌ngx_http_upstream_process_upgraded(ngx_http_request_t *r,
  2789.     ngx_uint_t from_upstream, ngx_uint_t do_write)
  2790. {
  2791.     size_t                     size;
  2792.     ssize_t                    n;
  2793.     ngx_buf_t                 *b;
  2794.     ngx_uint_t                 flags;
  2795.     ngx_connection_t          *c, *downstream, *upstream, *dst, *src;
  2796.     ngx_http_upstream_t       *u;
  2797.     ngx_http_core_loc_conf_t  *clcf;

  2798.     c = r->connection;
  2799.     u = r->upstream;

  2800.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2801.                    "http upstream process upgraded, fu:%ui", from_upstream);

  2802.     downstream = c;
  2803.     upstream = u->peer.connection;

  2804.     if (downstream->write->timedout) {
  2805.         c->timedout = 1;
  2806.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");
  2807.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  2808.         return;
  2809.     }

  2810.     if (upstream->read->timedout || upstream->write->timedout) {
  2811.         ngx_connection_error(c, NGX_ETIMEDOUT, "upstream timed out");
  2812.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_GATEWAY_TIME_OUT);
  2813.         return;
  2814.     }

  2815.     if (from_upstream) {
  2816.         src = upstream;
  2817.         dst = downstream;
  2818.         b = &u->buffer;

  2819.     } else {
  2820.         src = downstream;
  2821.         dst = upstream;
  2822.         b = &u->from_client;

  2823.         if (r->header_in->last > r->header_in->pos) {
  2824.             b = r->header_in;
  2825.             b->end = b->last;
  2826.             do_write = 1;
  2827.         }

  2828.         if (b->start == NULL) {
  2829.             b->start = ngx_palloc(r->pool, u->conf->buffer_size);
  2830.             if (b->start == NULL) {
  2831.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2832.                 return;
  2833.             }

  2834.             b->pos = b->start;
  2835.             b->last = b->start;
  2836.             b->end = b->start + u->conf->buffer_size;
  2837.             b->temporary = 1;
  2838.             b->tag = u->output.tag;
  2839.         }
  2840.     }

  2841.     for ( ;; ) {

  2842.         if (do_write) {

  2843.             size = b->last - b->pos;

  2844.             if (size && dst->write->ready) {

  2845.                 n = dst->send(dst, b->pos, size);

  2846.                 if (n == NGX_ERROR) {
  2847.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2848.                     return;
  2849.                 }

  2850.                 if (n > 0) {
  2851.                     b->pos += n;

  2852.                     if (b->pos == b->last) {
  2853.                         b->pos = b->start;
  2854.                         b->last = b->start;
  2855.                     }
  2856.                 }
  2857.             }
  2858.         }

  2859.         size = b->end - b->last;

  2860.         if (size && src->read->ready) {

  2861.             n = src->recv(src, b->last, size);

  2862.             if (n == NGX_AGAIN || n == 0) {
  2863.                 break;
  2864.             }

  2865.             if (n > 0) {
  2866.                 do_write = 1;
  2867.                 b->last += n;

  2868.                 if (from_upstream) {
  2869.                     u->state->bytes_received += n;
  2870.                 }

  2871.                 continue;
  2872.             }

  2873.             if (n == NGX_ERROR) {
  2874.                 src->read->eof = 1;
  2875.             }
  2876.         }

  2877.         break;
  2878.     }

  2879.     if ((upstream->read->eof && u->buffer.pos == u->buffer.last)
  2880.         || (downstream->read->eof && u->from_client.pos == u->from_client.last)
  2881.         || (downstream->read->eof && upstream->read->eof))
  2882.     {
  2883.         ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2884.                        "http upstream upgraded done");
  2885.         ngx_http_upstream_finalize_request(r, u, 0);
  2886.         return;
  2887.     }

  2888.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2889.     if (ngx_handle_write_event(upstream->write, u->conf->send_lowat)
  2890.         != NGX_OK)
  2891.     {
  2892.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2893.         return;
  2894.     }

  2895.     if (upstream->write->active && !upstream->write->ready) {
  2896.         ngx_add_timer(upstream->write, u->conf->send_timeout);

  2897.     } else if (upstream->write->timer_set) {
  2898.         ngx_del_timer(upstream->write);
  2899.     }

  2900.     if (upstream->read->eof || upstream->read->error) {
  2901.         flags = NGX_CLOSE_EVENT;

  2902.     } else {
  2903.         flags = 0;
  2904.     }

  2905.     if (ngx_handle_read_event(upstream->read, flags) != NGX_OK) {
  2906.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2907.         return;
  2908.     }

  2909.     if (upstream->read->active && !upstream->read->ready) {
  2910.         ngx_add_timer(upstream->read, u->conf->read_timeout);

  2911.     } else if (upstream->read->timer_set) {
  2912.         ngx_del_timer(upstream->read);
  2913.     }

  2914.     if (ngx_handle_write_event(downstream->write, clcf->send_lowat)
  2915.         != NGX_OK)
  2916.     {
  2917.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2918.         return;
  2919.     }

  2920.     if (downstream->read->eof || downstream->read->error) {
  2921.         flags = NGX_CLOSE_EVENT;

  2922.     } else {
  2923.         flags = 0;
  2924.     }

  2925.     if (ngx_handle_read_event(downstream->read, flags) != NGX_OK) {
  2926.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2927.         return;
  2928.     }

  2929.     if (downstream->write->active && !downstream->write->ready) {
  2930.         ngx_add_timer(downstream->write, clcf->send_timeout);

  2931.     } else if (downstream->write->timer_set) {
  2932.         ngx_del_timer(downstream->write);
  2933.     }
  2934. }


  2935. static void
  2936. ‌ngx_http_upstream_process_non_buffered_downstream(ngx_http_request_t *r)
  2937. {
  2938.     ngx_event_t          *wev;
  2939.     ngx_connection_t     *c;
  2940.     ngx_http_upstream_t  *u;

  2941.     c = r->connection;
  2942.     u = r->upstream;
  2943.     wev = c->write;

  2944.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2945.                    "http upstream process non buffered downstream");

  2946.     c->log->action = "sending to client";

  2947.     if (wev->timedout) {
  2948.         c->timedout = 1;
  2949.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");
  2950.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  2951.         return;
  2952.     }

  2953.     ngx_http_upstream_process_non_buffered_request(r, 1);
  2954. }


  2955. static void
  2956. ‌ngx_http_upstream_process_non_buffered_upstream(ngx_http_request_t *r,
  2957.     ngx_http_upstream_t *u)
  2958. {
  2959.     ngx_connection_t  *c;

  2960.     c = u->peer.connection;

  2961.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2962.                    "http upstream process non buffered upstream");

  2963.     c->log->action = "reading upstream";

  2964.     if (c->read->timedout) {
  2965.         ngx_connection_error(c, NGX_ETIMEDOUT, "upstream timed out");
  2966.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_GATEWAY_TIME_OUT);
  2967.         return;
  2968.     }

  2969.     ngx_http_upstream_process_non_buffered_request(r, 0);
  2970. }


  2971. static void
  2972. ‌ngx_http_upstream_process_non_buffered_request(ngx_http_request_t *r,
  2973.     ngx_uint_t do_write)
  2974. {
  2975.     size_t                     size;
  2976.     ssize_t                    n;
  2977.     ngx_buf_t                 *b;
  2978.     ngx_int_t                  rc;
  2979.     ngx_uint_t                 flags;
  2980.     ngx_connection_t          *downstream, *upstream;
  2981.     ngx_http_upstream_t       *u;
  2982.     ngx_http_core_loc_conf_t  *clcf;

  2983.     u = r->upstream;
  2984.     downstream = r->connection;
  2985.     upstream = u->peer.connection;

  2986.     b = &u->buffer;

  2987.     do_write = do_write || u->length == 0;

  2988.     for ( ;; ) {

  2989.         if (do_write) {

  2990.             if (u->out_bufs || u->busy_bufs || downstream->buffered) {
  2991.                 rc = ngx_http_output_filter(r, u->out_bufs);

  2992.                 if (rc == NGX_ERROR) {
  2993.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2994.                     return;
  2995.                 }

  2996.                 ngx_chain_update_chains(r->pool, &u->free_bufs, &u->busy_bufs,
  2997.                                         &u->out_bufs, u->output.tag);
  2998.             }

  2999.             if (u->busy_bufs == NULL) {

  3000.                 if (u->length == 0
  3001.                     || (upstream->read->eof && u->length == -1))
  3002.                 {
  3003.                     ngx_http_upstream_finalize_request(r, u, 0);
  3004.                     return;
  3005.                 }

  3006.                 if (upstream->read->eof) {
  3007.                     ngx_log_error(NGX_LOG_ERR, upstream->log, 0,
  3008.                                   "upstream prematurely closed connection");

  3009.                     ngx_http_upstream_finalize_request(r, u,
  3010.                                                        NGX_HTTP_BAD_GATEWAY);
  3011.                     return;
  3012.                 }

  3013.                 if (upstream->read->error || u->error) {
  3014.                     ngx_http_upstream_finalize_request(r, u,
  3015.                                                        NGX_HTTP_BAD_GATEWAY);
  3016.                     return;
  3017.                 }

  3018.                 b->pos = b->start;
  3019.                 b->last = b->start;
  3020.             }
  3021.         }

  3022.         size = b->end - b->last;

  3023.         if (size && upstream->read->ready) {

  3024.             n = upstream->recv(upstream, b->last, size);

  3025.             if (n == NGX_AGAIN) {
  3026.                 break;
  3027.             }

  3028.             if (n > 0) {
  3029.                 u->state->bytes_received += n;
  3030.                 u->state->response_length += n;

  3031.                 if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  3032.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3033.                     return;
  3034.                 }
  3035.             }

  3036.             do_write = 1;

  3037.             continue;
  3038.         }

  3039.         break;
  3040.     }

  3041.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  3042.     if (downstream->data == r) {
  3043.         if (ngx_handle_write_event(downstream->write, clcf->send_lowat)
  3044.             != NGX_OK)
  3045.         {
  3046.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3047.             return;
  3048.         }
  3049.     }

  3050.     if (downstream->write->active && !downstream->write->ready) {
  3051.         ngx_add_timer(downstream->write, clcf->send_timeout);

  3052.     } else if (downstream->write->timer_set) {
  3053.         ngx_del_timer(downstream->write);
  3054.     }

  3055.     if (upstream->read->eof || upstream->read->error) {
  3056.         flags = NGX_CLOSE_EVENT;

  3057.     } else {
  3058.         flags = 0;
  3059.     }

  3060.     if (ngx_handle_read_event(upstream->read, flags) != NGX_OK) {
  3061.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3062.         return;
  3063.     }

  3064.     if (upstream->read->active && !upstream->read->ready) {
  3065.         ngx_add_timer(upstream->read, u->conf->read_timeout);

  3066.     } else if (upstream->read->timer_set) {
  3067.         ngx_del_timer(upstream->read);
  3068.     }
  3069. }


  3070. ngx_int_t
  3071. ‌ngx_http_upstream_non_buffered_filter_init(void *data)
  3072. {
  3073.     return NGX_OK;
  3074. }


  3075. ngx_int_t
  3076. ‌ngx_http_upstream_non_buffered_filter(void *data, ssize_t bytes)
  3077. {
  3078.     ngx_http_request_t  *r = data;

  3079.     ngx_buf_t            *b;
  3080.     ngx_chain_t          *cl, **ll;
  3081.     ngx_http_upstream_t  *u;

  3082.     u = r->upstream;

  3083.     if (u->length == 0) {
  3084.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3085.                       "upstream sent more data than specified in "
  3086.                       "\"Content-Length\" header");
  3087.         return NGX_OK;
  3088.     }

  3089.     for (cl = u->out_bufs, ll = &u->out_bufs; cl; cl = cl->next) {
  3090.         ll = &cl->next;
  3091.     }

  3092.     cl = ngx_chain_get_free_buf(r->pool, &u->free_bufs);
  3093.     if (cl == NULL) {
  3094.         return NGX_ERROR;
  3095.     }

  3096.     *ll = cl;

  3097.     cl->buf->flush = 1;
  3098.     cl->buf->memory = 1;

  3099.     b = &u->buffer;

  3100.     cl->buf->pos = b->last;
  3101.     b->last += bytes;
  3102.     cl->buf->last = b->last;
  3103.     cl->buf->tag = u->output.tag;

  3104.     if (u->length == -1) {
  3105.         return NGX_OK;
  3106.     }

  3107.     if (bytes > u->length) {

  3108.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3109.                       "upstream sent more data than specified in "
  3110.                       "\"Content-Length\" header");

  3111.         cl->buf->last = cl->buf->pos + u->length;
  3112.         u->length = 0;

  3113.         return NGX_OK;
  3114.     }

  3115.     u->length -= bytes;

  3116.     return NGX_OK;
  3117. }


  3118. #if (NGX_THREADS)

  3119. static ngx_int_t
  3120. ‌ngx_http_upstream_thread_handler(ngx_thread_task_t *task, ngx_file_t *file)
  3121. {
  3122.     ngx_str_t                  name;
  3123.     ngx_event_pipe_t          *p;
  3124.     ngx_connection_t          *c;
  3125.     ngx_thread_pool_t         *tp;
  3126.     ngx_http_request_t        *r;
  3127.     ngx_http_core_loc_conf_t  *clcf;

  3128.     r = file->thread_ctx;
  3129.     p = r->upstream->pipe;

  3130.     if (r->aio) {
  3131.         /*
  3132.          * tolerate sendfile() calls if another operation is already
  3133.          * running; this can happen due to subrequests, multiple calls
  3134.          * of the next body filter from a filter, or in HTTP/2 due to
  3135.          * a write event on the main connection
  3136.          */

  3137.         c = r->connection;

  3138. #if (NGX_HTTP_V2)
  3139.         if (r->stream) {
  3140.             c = r->stream->connection->connection;
  3141.         }
  3142. #endif

  3143.         if (task == c->sendfile_task) {
  3144.             return NGX_OK;
  3145.         }
  3146.     }

  3147.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
  3148.     tp = clcf->thread_pool;

  3149.     if (tp == NULL) {
  3150.         if (ngx_http_complex_value(r, clcf->thread_pool_value, &name)
  3151.             != NGX_OK)
  3152.         {
  3153.             return NGX_ERROR;
  3154.         }

  3155.         tp = ngx_thread_pool_get((ngx_cycle_t *) ngx_cycle, &name);

  3156.         if (tp == NULL) {
  3157.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3158.                           "thread pool \"%V\" not found", &name);
  3159.             return NGX_ERROR;
  3160.         }
  3161.     }

  3162.     task->event.data = r;
  3163.     task->event.handler = ngx_http_upstream_thread_event_handler;

  3164.     if (r->main->blocked >= NGX_HTTP_MAX_BLOCKED) {
  3165.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3166.                       "too many operations pending");
  3167.         return NGX_ERROR;
  3168.     }

  3169.     if (ngx_thread_task_post(tp, task) != NGX_OK) {
  3170.         return NGX_ERROR;
  3171.     }

  3172.     r->main->blocked++;
  3173.     r->aio = 1;
  3174.     p->aio = 1;

  3175.     ngx_add_timer(&task->event, 60000);

  3176.     return NGX_OK;
  3177. }


  3178. static void
  3179. ‌ngx_http_upstream_thread_event_handler(ngx_event_t *ev)
  3180. {
  3181.     ngx_connection_t    *c;
  3182.     ngx_http_request_t  *r;

  3183.     r = ev->data;
  3184.     c = r->connection;

  3185.     ngx_http_set_log_request(c->log, r);

  3186.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, c->log, 0,
  3187.                    "http upstream thread: \"%V?%V\"", &r->uri, &r->args);

  3188.     if (ev->timedout) {
  3189.         ngx_log_error(NGX_LOG_ALERT, c->log, 0,
  3190.                       "thread operation took too long");
  3191.         ev->timedout = 0;
  3192.         return;
  3193.     }

  3194.     if (ev->timer_set) {
  3195.         ngx_del_timer(ev);
  3196.     }

  3197.     r->main->blocked--;
  3198.     r->aio = 0;

  3199. #if (NGX_HTTP_V2)

  3200.     if (r->stream) {
  3201.         /*
  3202.          * for HTTP/2, update write event to make sure processing will
  3203.          * reach the main connection to handle sendfile() in threads
  3204.          */

  3205.         c->write->ready = 1;
  3206.         c->write->active = 0;
  3207.     }

  3208. #endif

  3209.     if (r->done || r->main->terminated) {
  3210.         /*
  3211.          * trigger connection event handler if the subrequest was
  3212.          * already finalized (this can happen if the handler is used
  3213.          * for sendfile() in threads), or if the request was terminated
  3214.          */

  3215.         c->write->handler(c->write);

  3216.     } else {
  3217.         r->write_event_handler(r);
  3218.         ngx_http_run_posted_requests(c);
  3219.     }
  3220. }

  3221. #endif


  3222. static ngx_int_t
  3223. ‌ngx_http_upstream_output_filter(void *data, ngx_chain_t *chain)
  3224. {
  3225.     ngx_int_t            rc;
  3226.     ngx_event_pipe_t    *p;
  3227.     ngx_http_request_t  *r;

  3228.     r = data;
  3229.     p = r->upstream->pipe;

  3230.     rc = ngx_http_output_filter(r, chain);

  3231.     p->aio = r->aio;

  3232.     return rc;
  3233. }


  3234. static void
  3235. ‌ngx_http_upstream_process_downstream(ngx_http_request_t *r)
  3236. {
  3237.     ngx_event_t          *wev;
  3238.     ngx_connection_t     *c;
  3239.     ngx_event_pipe_t     *p;
  3240.     ngx_http_upstream_t  *u;

  3241.     c = r->connection;
  3242.     u = r->upstream;
  3243.     p = u->pipe;
  3244.     wev = c->write;

  3245.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  3246.                    "http upstream process downstream");

  3247.     c->log->action = "sending to client";

  3248. #if (NGX_THREADS)
  3249.     p->aio = r->aio;
  3250. #endif

  3251.     if (wev->timedout) {

  3252.         p->downstream_error = 1;
  3253.         c->timedout = 1;
  3254.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");

  3255.     } else {

  3256.         if (wev->delayed) {

  3257.             ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  3258.                            "http downstream delayed");

  3259.             if (ngx_handle_write_event(wev, p->send_lowat) != NGX_OK) {
  3260.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3261.             }

  3262.             return;
  3263.         }

  3264.         if (ngx_event_pipe(p, 1) == NGX_ABORT) {
  3265.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3266.             return;
  3267.         }
  3268.     }

  3269.     ngx_http_upstream_process_request(r, u);
  3270. }


  3271. static void
  3272. ‌ngx_http_upstream_process_upstream(ngx_http_request_t *r,
  3273.     ngx_http_upstream_t *u)
  3274. {
  3275.     ngx_event_t       *rev;
  3276.     ngx_event_pipe_t  *p;
  3277.     ngx_connection_t  *c;

  3278.     c = u->peer.connection;
  3279.     p = u->pipe;
  3280.     rev = c->read;

  3281.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  3282.                    "http upstream process upstream");

  3283.     c->log->action = "reading upstream";

  3284.     if (rev->timedout) {

  3285.         p->upstream_error = 1;
  3286.         ngx_connection_error(c, NGX_ETIMEDOUT, "upstream timed out");

  3287.     } else {

  3288.         if (rev->delayed) {

  3289.             ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  3290.                            "http upstream delayed");

  3291.             if (ngx_handle_read_event(rev, 0) != NGX_OK) {
  3292.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3293.             }

  3294.             return;
  3295.         }

  3296.         if (ngx_event_pipe(p, 0) == NGX_ABORT) {
  3297.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3298.             return;
  3299.         }
  3300.     }

  3301.     ngx_http_upstream_process_request(r, u);
  3302. }


  3303. static void
  3304. ‌ngx_http_upstream_process_request(ngx_http_request_t *r,
  3305.     ngx_http_upstream_t *u)
  3306. {
  3307.     ngx_temp_file_t   *tf;
  3308.     ngx_event_pipe_t  *p;

  3309.     p = u->pipe;

  3310. #if (NGX_THREADS)

  3311.     if (p->writing && !p->aio) {

  3312.         /*
  3313.          * make sure to call ngx_event_pipe()
  3314.          * if there is an incomplete aio write
  3315.          */

  3316.         if (ngx_event_pipe(p, 1) == NGX_ABORT) {
  3317.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3318.             return;
  3319.         }
  3320.     }

  3321.     if (p->writing) {
  3322.         return;
  3323.     }

  3324. #endif

  3325.     if (u->peer.connection) {

  3326.         if (u->store) {

  3327.             if (p->upstream_eof || p->upstream_done) {

  3328.                 tf = p->temp_file;

  3329.                 if (u->headers_in.status_n == NGX_HTTP_OK
  3330.                     && (p->upstream_done || p->length == -1)
  3331.                     && (u->headers_in.content_length_n == -1
  3332.                         || u->headers_in.content_length_n == tf->offset))
  3333.                 {
  3334.                     ngx_http_upstream_store(r, u);
  3335.                 }
  3336.             }
  3337.         }

  3338. #if (NGX_HTTP_CACHE)

  3339.         if (u->cacheable) {

  3340.             if (p->upstream_done) {
  3341.                 ngx_http_file_cache_update(r, p->temp_file);

  3342.             } else if (p->upstream_eof) {

  3343.                 tf = p->temp_file;

  3344.                 if (p->length == -1
  3345.                     && (u->headers_in.content_length_n == -1
  3346.                         || u->headers_in.content_length_n
  3347.                            == tf->offset - (off_t) r->cache->body_start))
  3348.                 {
  3349.                     ngx_http_file_cache_update(r, tf);

  3350.                 } else {
  3351.                     ngx_http_file_cache_free(r->cache, tf);
  3352.                 }

  3353.             } else if (p->upstream_error) {
  3354.                 ngx_http_file_cache_free(r->cache, p->temp_file);
  3355.             }
  3356.         }

  3357. #endif

  3358.         if (p->upstream_done || p->upstream_eof || p->upstream_error) {
  3359.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3360.                            "http upstream exit: %p", p->out);

  3361.             if (p->upstream_done
  3362.                 || (p->upstream_eof && p->length == -1))
  3363.             {
  3364.                 ngx_http_upstream_finalize_request(r, u, 0);
  3365.                 return;
  3366.             }

  3367.             if (p->upstream_eof) {
  3368.                 ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3369.                               "upstream prematurely closed connection");
  3370.             }

  3371.             ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  3372.             return;
  3373.         }
  3374.     }

  3375.     if (p->downstream_error) {
  3376.         ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3377.                        "http upstream downstream error");

  3378.         if (!u->cacheable && !u->store && u->peer.connection) {
  3379.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3380.         }
  3381.     }
  3382. }


  3383. static void
  3384. ‌ngx_http_upstream_store(ngx_http_request_t *r, ngx_http_upstream_t *u)
  3385. {
  3386.     size_t                  root;
  3387.     time_t                  lm;
  3388.     ngx_str_t               path;
  3389.     ngx_temp_file_t        *tf;
  3390.     ngx_ext_rename_file_t   ext;

  3391.     tf = u->pipe->temp_file;

  3392.     if (tf->file.fd == NGX_INVALID_FILE) {

  3393.         /* create file for empty 200 response */

  3394.         tf = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t));
  3395.         if (tf == NULL) {
  3396.             return;
  3397.         }

  3398.         tf->file.fd = NGX_INVALID_FILE;
  3399.         tf->file.log = r->connection->log;
  3400.         tf->path = u->conf->temp_path;
  3401.         tf->pool = r->pool;
  3402.         tf->persistent = 1;

  3403.         if (ngx_create_temp_file(&tf->file, tf->path, tf->pool,
  3404.                                  tf->persistent, tf->clean, tf->access)
  3405.             != NGX_OK)
  3406.         {
  3407.             return;
  3408.         }

  3409.         u->pipe->temp_file = tf;
  3410.     }

  3411.     ext.access = u->conf->store_access;
  3412.     ext.path_access = u->conf->store_access;
  3413.     ext.time = -1;
  3414.     ext.create_path = 1;
  3415.     ext.delete_file = 1;
  3416.     ext.log = r->connection->log;

  3417.     if (u->headers_in.last_modified) {

  3418.         lm = ngx_parse_http_time(u->headers_in.last_modified->value.data,
  3419.                                  u->headers_in.last_modified->value.len);

  3420.         if (lm != NGX_ERROR) {
  3421.             ext.time = lm;
  3422.             ext.fd = tf->file.fd;
  3423.         }
  3424.     }

  3425.     if (u->conf->store_lengths == NULL) {

  3426.         if (ngx_http_map_uri_to_path(r, &path, &root, 0) == NULL) {
  3427.             return;
  3428.         }

  3429.     } else {
  3430.         if (ngx_http_script_run(r, &path, u->conf->store_lengths->elts, 0,
  3431.                                 u->conf->store_values->elts)
  3432.             == NULL)
  3433.         {
  3434.             return;
  3435.         }
  3436.     }

  3437.     path.len--;

  3438.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3439.                    "upstream stores \"%s\" to \"%s\"",
  3440.                    tf->file.name.data, path.data);

  3441.     if (path.len == 0) {
  3442.         return;
  3443.     }

  3444.     (void) ngx_ext_rename_file(&tf->file.name, &path, &ext);

  3445.     u->store = 0;
  3446. }


  3447. static void
  3448. ‌ngx_http_upstream_dummy_handler(ngx_http_request_t *r, ngx_http_upstream_t *u)
  3449. {
  3450.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3451.                    "http upstream dummy handler");
  3452. }


  3453. static void
  3454. ‌ngx_http_upstream_next(ngx_http_request_t *r, ngx_http_upstream_t *u,
  3455.     ngx_uint_t ft_type)
  3456. {
  3457.     ngx_msec_t  timeout;
  3458.     ngx_uint_t  status, state;

  3459.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3460.                    "http next upstream, %xi", ft_type);

  3461.     if (u->peer.sockaddr) {

  3462.         if (u->peer.connection) {
  3463.             u->state->bytes_sent = u->peer.connection->sent;
  3464.         }

  3465.         if (ft_type == NGX_HTTP_UPSTREAM_FT_HTTP_403
  3466.             || ft_type == NGX_HTTP_UPSTREAM_FT_HTTP_404)
  3467.         {
  3468.             state = NGX_PEER_NEXT;

  3469.         } else {
  3470.             state = NGX_PEER_FAILED;
  3471.         }

  3472.         u->peer.free(&u->peer, u->peer.data, state);
  3473.         u->peer.sockaddr = NULL;

  3474. #if (NGX_HTTP_UPSTREAM_SID)
  3475.         u->peer.sid = NULL;
  3476. #endif
  3477.     }

  3478.     if (ft_type == NGX_HTTP_UPSTREAM_FT_TIMEOUT) {
  3479.         ngx_log_error(NGX_LOG_ERR, r->connection->log, NGX_ETIMEDOUT,
  3480.                       "upstream timed out");
  3481.     }

  3482.     if (u->peer.cached && ft_type == NGX_HTTP_UPSTREAM_FT_ERROR) {
  3483.         /* TODO: inform balancer instead */
  3484.         u->peer.tries++;
  3485.     }

  3486.     switch (ft_type) {

  3487.     case NGX_HTTP_UPSTREAM_FT_TIMEOUT:
  3488.     case NGX_HTTP_UPSTREAM_FT_HTTP_504:
  3489.         status = NGX_HTTP_GATEWAY_TIME_OUT;
  3490.         break;

  3491.     case NGX_HTTP_UPSTREAM_FT_HTTP_500:
  3492.         status = NGX_HTTP_INTERNAL_SERVER_ERROR;
  3493.         break;

  3494.     case NGX_HTTP_UPSTREAM_FT_HTTP_503:
  3495.         status = NGX_HTTP_SERVICE_UNAVAILABLE;
  3496.         break;

  3497.     case NGX_HTTP_UPSTREAM_FT_HTTP_403:
  3498.         status = NGX_HTTP_FORBIDDEN;
  3499.         break;

  3500.     case NGX_HTTP_UPSTREAM_FT_HTTP_404:
  3501.         status = NGX_HTTP_NOT_FOUND;
  3502.         break;

  3503.     case NGX_HTTP_UPSTREAM_FT_HTTP_429:
  3504.         status = NGX_HTTP_TOO_MANY_REQUESTS;
  3505.         break;

  3506.     /*
  3507.      * NGX_HTTP_UPSTREAM_FT_BUSY_LOCK and NGX_HTTP_UPSTREAM_FT_MAX_WAITING
  3508.      * never reach here
  3509.      */

  3510.     default:
  3511.         status = NGX_HTTP_BAD_GATEWAY;
  3512.     }

  3513.     if (r->connection->error) {
  3514.         ngx_http_upstream_finalize_request(r, u,
  3515.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  3516.         return;
  3517.     }

  3518.     u->state->status = status;

  3519.     timeout = u->conf->next_upstream_timeout;

  3520.     if (u->request_sent
  3521.         && (r->method & (NGX_HTTP_POST|NGX_HTTP_LOCK|NGX_HTTP_PATCH)))
  3522.     {
  3523.         ft_type |= NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT;
  3524.     }

  3525.     if (u->peer.tries == 0
  3526.         || ((u->conf->next_upstream & ft_type) != ft_type)
  3527.         || (u->request_sent && r->request_body_no_buffering)
  3528.         || (timeout && ngx_current_msec - u->peer.start_time >= timeout))
  3529.     {
  3530. #if (NGX_HTTP_CACHE)

  3531.         if (u->cache_status == NGX_HTTP_CACHE_EXPIRED
  3532.             && ((u->conf->cache_use_stale & ft_type) || r->cache->stale_error))
  3533.         {
  3534.             ngx_int_t  rc;

  3535.             rc = u->reinit_request(r);

  3536.             if (rc != NGX_OK) {
  3537.                 ngx_http_upstream_finalize_request(r, u, rc);
  3538.                 return;
  3539.             }

  3540.             u->cache_status = NGX_HTTP_CACHE_STALE;
  3541.             rc = ngx_http_upstream_cache_send(r, u);

  3542.             if (rc == NGX_DONE) {
  3543.                 return;
  3544.             }

  3545.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  3546.                 rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  3547.             }

  3548.             ngx_http_upstream_finalize_request(r, u, rc);
  3549.             return;
  3550.         }
  3551. #endif

  3552.         ngx_http_upstream_finalize_request(r, u, status);
  3553.         return;
  3554.     }

  3555.     if (u->peer.connection) {
  3556.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3557.                        "close http upstream connection: %d",
  3558.                        u->peer.connection->fd);
  3559. #if (NGX_HTTP_SSL)

  3560.         if (u->peer.connection->ssl) {
  3561.             u->peer.connection->ssl->no_wait_shutdown = 1;
  3562.             u->peer.connection->ssl->no_send_shutdown = 1;

  3563.             (void) ngx_ssl_shutdown(u->peer.connection);
  3564.         }
  3565. #endif

  3566.         if (u->peer.connection->pool) {
  3567.             ngx_destroy_pool(u->peer.connection->pool);
  3568.         }

  3569.         ngx_close_connection(u->peer.connection);
  3570.         u->peer.connection = NULL;
  3571.     }

  3572.     ngx_http_upstream_connect(r, u);
  3573. }


  3574. static void
  3575. ‌ngx_http_upstream_cleanup(void *data)
  3576. {
  3577.     ngx_http_request_t *r = data;

  3578.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3579.                    "cleanup http upstream request: \"%V\"", &r->uri);

  3580.     ngx_http_upstream_finalize_request(r, r->upstream, NGX_DONE);
  3581. }


  3582. static void
  3583. ‌ngx_http_upstream_finalize_request(ngx_http_request_t *r,
  3584.     ngx_http_upstream_t *u, ngx_int_t rc)
  3585. {
  3586.     ngx_uint_t  flush;

  3587.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3588.                    "finalize http upstream request: %i", rc);

  3589.     if (u->cleanup == NULL) {
  3590.         /* the request was already finalized */
  3591.         ngx_http_finalize_request(r, NGX_DONE);
  3592.         return;
  3593.     }

  3594.     *u->cleanup = NULL;
  3595.     u->cleanup = NULL;

  3596.     if (u->resolved && u->resolved->ctx) {
  3597.         ngx_resolve_name_done(u->resolved->ctx);
  3598.         u->resolved->ctx = NULL;
  3599.     }

  3600.     if (u->state && u->state->response_time == (ngx_msec_t) -1) {
  3601.         u->state->response_time = ngx_current_msec - u->start_time;

  3602.         if (u->pipe && u->pipe->read_length) {
  3603.             u->state->bytes_received += u->pipe->read_length
  3604.                                         - u->pipe->preread_size;
  3605.             u->state->response_length = u->pipe->read_length;
  3606.         }

  3607.         if (u->peer.connection) {
  3608.             u->state->bytes_sent = u->peer.connection->sent;
  3609.         }
  3610.     }

  3611.     u->finalize_request(r, rc);

  3612.     if (u->peer.free && u->peer.sockaddr) {
  3613.         u->peer.free(&u->peer, u->peer.data, 0);
  3614.         u->peer.sockaddr = NULL;

  3615. #if (NGX_HTTP_UPSTREAM_SID)
  3616.         u->peer.sid = NULL;
  3617. #endif
  3618.     }

  3619.     if (u->peer.connection) {

  3620. #if (NGX_HTTP_SSL)

  3621.         /* TODO: do not shutdown persistent connection */

  3622.         if (u->peer.connection->ssl) {

  3623.             /*
  3624.              * We send the "close notify" shutdown alert to the upstream only
  3625.              * and do not wait its "close notify" shutdown alert.
  3626.              * It is acceptable according to the TLS standard.
  3627.              */

  3628.             u->peer.connection->ssl->no_wait_shutdown = 1;

  3629.             (void) ngx_ssl_shutdown(u->peer.connection);
  3630.         }
  3631. #endif

  3632.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3633.                        "close http upstream connection: %d",
  3634.                        u->peer.connection->fd);

  3635.         if (u->peer.connection->pool) {
  3636.             ngx_destroy_pool(u->peer.connection->pool);
  3637.         }

  3638.         ngx_close_connection(u->peer.connection);
  3639.     }

  3640.     u->peer.connection = NULL;

  3641.     if (u->pipe) {
  3642.         u->pipe->upstream = NULL;
  3643.     }

  3644.     if (u->pipe && u->pipe->temp_file) {
  3645.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3646.                        "http upstream temp fd: %d",
  3647.                        u->pipe->temp_file->file.fd);
  3648.     }

  3649.     if (u->store && u->pipe && u->pipe->temp_file
  3650.         && u->pipe->temp_file->file.fd != NGX_INVALID_FILE)
  3651.     {
  3652.         if (ngx_delete_file(u->pipe->temp_file->file.name.data)
  3653.             == NGX_FILE_ERROR)
  3654.         {
  3655.             ngx_log_error(NGX_LOG_CRIT, r->connection->log, ngx_errno,
  3656.                           ngx_delete_file_n " \"%s\" failed",
  3657.                           u->pipe->temp_file->file.name.data);
  3658.         }
  3659.     }

  3660. #if (NGX_HTTP_CACHE)

  3661.     if (r->cache) {

  3662.         if (u->cacheable) {

  3663.             if (rc == NGX_HTTP_BAD_GATEWAY || rc == NGX_HTTP_GATEWAY_TIME_OUT) {
  3664.                 time_t  valid;

  3665.                 valid = ngx_http_file_cache_valid(u->conf->cache_valid, rc);

  3666.                 if (valid) {
  3667.                     r->cache->valid_sec = ngx_time() + valid;
  3668.                     r->cache->error = rc;
  3669.                 }
  3670.             }
  3671.         }

  3672.         ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  3673.     }

  3674. #endif

  3675.     r->read_event_handler = ngx_http_block_reading;

  3676.     if (rc == NGX_DECLINED) {
  3677.         return;
  3678.     }

  3679.     r->connection->log->action = "sending to client";

  3680.     if (!u->header_sent
  3681.         || rc == NGX_HTTP_REQUEST_TIME_OUT
  3682.         || rc == NGX_HTTP_CLIENT_CLOSED_REQUEST)
  3683.     {
  3684.         ngx_http_finalize_request(r, rc);
  3685.         return;
  3686.     }

  3687.     flush = 0;

  3688.     if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  3689.         rc = NGX_ERROR;
  3690.         flush = 1;
  3691.     }

  3692.     if (r->header_only
  3693.         || (u->pipe && u->pipe->downstream_error))
  3694.     {
  3695.         ngx_http_finalize_request(r, rc);
  3696.         return;
  3697.     }

  3698.     if (rc == 0) {

  3699.         if (ngx_http_upstream_process_trailers(r, u) != NGX_OK) {
  3700.             ngx_http_finalize_request(r, NGX_ERROR);
  3701.             return;
  3702.         }

  3703.         rc = ngx_http_send_special(r, NGX_HTTP_LAST);

  3704.     } else if (flush) {
  3705.         r->keepalive = 0;
  3706.         rc = ngx_http_send_special(r, NGX_HTTP_FLUSH);
  3707.     }

  3708.     ngx_http_finalize_request(r, rc);
  3709. }


  3710. static ngx_int_t
  3711. ‌ngx_http_upstream_process_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  3712.     ngx_uint_t offset)
  3713. {
  3714.     ngx_table_elt_t  **ph;

  3715.     ph = (ngx_table_elt_t **) ((char *) &r->upstream->headers_in + offset);

  3716.     if (*ph) {
  3717.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3718.                       "upstream sent duplicate header line: \"%V: %V\", "
  3719.                       "previous value: \"%V: %V\", ignored",
  3720.                       &h->key, &h->value,
  3721.                       &(*ph)->key, &(*ph)->value);
  3722.         h->hash = 0;
  3723.         return NGX_OK;
  3724.     }

  3725.     *ph = h;
  3726.     h->next = NULL;

  3727.     return NGX_OK;
  3728. }


  3729. static ngx_int_t
  3730. ‌ngx_http_upstream_process_multi_header_lines(ngx_http_request_t *r,
  3731.     ngx_table_elt_t *h, ngx_uint_t offset)
  3732. {
  3733.     ngx_table_elt_t  **ph;

  3734.     ph = (ngx_table_elt_t **) ((char *) &r->upstream->headers_in + offset);

  3735.     while (*ph) { ph = &(*ph)->next; }

  3736.     *ph = h;
  3737.     h->next = NULL;

  3738.     return NGX_OK;
  3739. }


  3740. static ngx_int_t
  3741. ‌ngx_http_upstream_ignore_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  3742.     ngx_uint_t offset)
  3743. {
  3744.     return NGX_OK;
  3745. }


  3746. static ngx_int_t
  3747. ‌ngx_http_upstream_process_content_length(ngx_http_request_t *r,
  3748.     ngx_table_elt_t *h, ngx_uint_t offset)
  3749. {
  3750.     ngx_http_upstream_t  *u;

  3751.     u = r->upstream;

  3752.     if (u->headers_in.content_length) {
  3753.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3754.                       "upstream sent duplicate header line: \"%V: %V\", "
  3755.                       "previous value: \"%V: %V\"",
  3756.                       &h->key, &h->value,
  3757.                       &u->headers_in.content_length->key,
  3758.                       &u->headers_in.content_length->value);
  3759.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3760.     }

  3761.     if (u->headers_in.transfer_encoding) {
  3762.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3763.                       "upstream sent \"Content-Length\" and "
  3764.                       "\"Transfer-Encoding\" headers at the same time");
  3765.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3766.     }

  3767.     h->next = NULL;
  3768.     u->headers_in.content_length = h;
  3769.     u->headers_in.content_length_n = ngx_atoof(h->value.data, h->value.len);

  3770.     if (u->headers_in.content_length_n == NGX_ERROR) {
  3771.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3772.                       "upstream sent invalid \"Content-Length\" header: "
  3773.                       "\"%V: %V\"", &h->key, &h->value);
  3774.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3775.     }

  3776.     return NGX_OK;
  3777. }


  3778. static ngx_int_t
  3779. ‌ngx_http_upstream_process_last_modified(ngx_http_request_t *r,
  3780.     ngx_table_elt_t *h, ngx_uint_t offset)
  3781. {
  3782.     ngx_http_upstream_t  *u;

  3783.     u = r->upstream;

  3784.     if (u->headers_in.last_modified) {
  3785.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3786.                       "upstream sent duplicate header line: \"%V: %V\", "
  3787.                       "previous value: \"%V: %V\", ignored",
  3788.                       &h->key, &h->value,
  3789.                       &u->headers_in.last_modified->key,
  3790.                       &u->headers_in.last_modified->value);
  3791.         h->hash = 0;
  3792.         return NGX_OK;
  3793.     }

  3794.     h->next = NULL;
  3795.     u->headers_in.last_modified = h;
  3796.     u->headers_in.last_modified_time = ngx_parse_http_time(h->value.data,
  3797.                                                            h->value.len);

  3798.     return NGX_OK;
  3799. }


  3800. static ngx_int_t
  3801. ‌ngx_http_upstream_process_set_cookie(ngx_http_request_t *r, ngx_table_elt_t *h,
  3802.     ngx_uint_t offset)
  3803. {
  3804.     ngx_table_elt_t      **ph;
  3805.     ngx_http_upstream_t   *u;

  3806.     u = r->upstream;
  3807.     ph = &u->headers_in.set_cookie;

  3808.     while (*ph) { ph = &(*ph)->next; }

  3809.     *ph = h;
  3810.     h->next = NULL;

  3811. #if (NGX_HTTP_CACHE)
  3812.     if (!(u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_SET_COOKIE)) {
  3813.         u->cacheable = 0;
  3814.     }
  3815. #endif

  3816.     return NGX_OK;
  3817. }


  3818. static ngx_int_t
  3819. ‌ngx_http_upstream_process_cache_control(ngx_http_request_t *r,
  3820.     ngx_table_elt_t *h, ngx_uint_t offset)
  3821. {
  3822.     ngx_table_elt_t      **ph;
  3823.     ngx_http_upstream_t   *u;

  3824.     u = r->upstream;
  3825.     ph = &u->headers_in.cache_control;

  3826.     while (*ph) { ph = &(*ph)->next; }

  3827.     *ph = h;
  3828.     h->next = NULL;

  3829. #if (NGX_HTTP_CACHE)
  3830.     {
  3831.     u_char     *p, *start, *last;
  3832.     ngx_int_t   n;

  3833.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_CACHE_CONTROL) {
  3834.         return NGX_OK;
  3835.     }

  3836.     if (r->cache == NULL) {
  3837.         return NGX_OK;
  3838.     }

  3839.     start = h->value.data;
  3840.     last = start + h->value.len;

  3841.     if (r->cache->valid_sec != 0 && u->headers_in.x_accel_expires != NULL) {
  3842.         goto extensions;
  3843.     }

  3844.     if (ngx_strlcasestrn(start, last, (u_char *) "no-cache", 8 - 1) != NULL
  3845.         || ngx_strlcasestrn(start, last, (u_char *) "no-store", 8 - 1) != NULL
  3846.         || ngx_strlcasestrn(start, last, (u_char *) "private", 7 - 1) != NULL)
  3847.     {
  3848.         u->headers_in.no_cache = 1;
  3849.         return NGX_OK;
  3850.     }

  3851.     p = ngx_strlcasestrn(start, last, (u_char *) "s-maxage=", 9 - 1);
  3852.     offset = 9;

  3853.     if (p == NULL) {
  3854.         p = ngx_strlcasestrn(start, last, (u_char *) "max-age=", 8 - 1);
  3855.         offset = 8;
  3856.     }

  3857.     if (p) {
  3858.         n = ngx_http_upstream_process_delta_seconds(p + offset, last);

  3859.         if (n == NGX_ERROR) {
  3860.             u->cacheable = 0;
  3861.             return NGX_OK;
  3862.         }

  3863.         if (n == 0) {
  3864.             u->headers_in.no_cache = 1;
  3865.             return NGX_OK;
  3866.         }

  3867.         r->cache->valid_sec = ngx_min((ngx_uint_t) ngx_time() + n,
  3868.                                       NGX_MAX_INT_T_VALUE);
  3869.         u->headers_in.expired = 0;
  3870.     }

  3871. extensions:

  3872.     p = ngx_strlcasestrn(start, last, (u_char *) "stale-while-revalidate=",
  3873.                          23 - 1);

  3874.     if (p) {
  3875.         n = ngx_http_upstream_process_delta_seconds(p + 23, last);

  3876.         if (n == NGX_ERROR) {
  3877.             u->cacheable = 0;
  3878.             return NGX_OK;
  3879.         }

  3880.         r->cache->updating_sec = n;
  3881.         r->cache->error_sec = n;
  3882.     }

  3883.     p = ngx_strlcasestrn(start, last, (u_char *) "stale-if-error=", 15 - 1);

  3884.     if (p) {
  3885.         n = ngx_http_upstream_process_delta_seconds(p + 15, last);

  3886.         if (n == NGX_ERROR) {
  3887.             u->cacheable = 0;
  3888.             return NGX_OK;
  3889.         }

  3890.         r->cache->error_sec = n;
  3891.     }
  3892.     }
  3893. #endif

  3894.     return NGX_OK;
  3895. }


  3896. #if (NGX_HTTP_CACHE)

  3897. static ngx_int_t
  3898. ‌ngx_http_upstream_process_delta_seconds(u_char *p, u_char *last)
  3899. {
  3900.     ngx_int_t  n, cutoff, cutlim;

  3901.     cutoff = NGX_MAX_INT_T_VALUE / 10;
  3902.     cutlim = NGX_MAX_INT_T_VALUE % 10;

  3903.     n = 0;

  3904.     for ( /* void */ ; p < last; p++) {
  3905.         if (*p == ',' || *p == ';' || *p == ' ') {
  3906.             break;
  3907.         }

  3908.         if (*p < '0' || *p > '9') {
  3909.             return NGX_ERROR;
  3910.         }

  3911.         if (n >= cutoff && (n > cutoff || *p - '0' > cutlim)) {
  3912.             n = NGX_MAX_INT_T_VALUE;
  3913.             break;
  3914.         }

  3915.         n = n * 10 + (*p - '0');
  3916.     }

  3917.     return n;
  3918. }

  3919. #endif


  3920. static ngx_int_t
  3921. ‌ngx_http_upstream_process_expires(ngx_http_request_t *r, ngx_table_elt_t *h,
  3922.     ngx_uint_t offset)
  3923. {
  3924.     ngx_http_upstream_t  *u;

  3925.     u = r->upstream;

  3926.     if (u->headers_in.expires) {
  3927.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3928.                       "upstream sent duplicate header line: \"%V: %V\", "
  3929.                       "previous value: \"%V: %V\", ignored",
  3930.                       &h->key, &h->value,
  3931.                       &u->headers_in.expires->key,
  3932.                       &u->headers_in.expires->value);
  3933.         h->hash = 0;
  3934.         return NGX_OK;
  3935.     }

  3936.     u->headers_in.expires = h;
  3937.     h->next = NULL;

  3938. #if (NGX_HTTP_CACHE)
  3939.     {
  3940.     time_t  expires;

  3941.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_EXPIRES) {
  3942.         return NGX_OK;
  3943.     }

  3944.     if (r->cache == NULL) {
  3945.         return NGX_OK;
  3946.     }

  3947.     if (r->cache->valid_sec != 0) {
  3948.         return NGX_OK;
  3949.     }

  3950.     expires = ngx_parse_http_time(h->value.data, h->value.len);

  3951.     if (expires == NGX_ERROR || expires < ngx_time()) {
  3952.         u->headers_in.expired = 1;
  3953.         return NGX_OK;
  3954.     }

  3955.     r->cache->valid_sec = expires;
  3956.     }
  3957. #endif

  3958.     return NGX_OK;
  3959. }


  3960. static ngx_int_t
  3961. ‌ngx_http_upstream_process_accel_expires(ngx_http_request_t *r,
  3962.     ngx_table_elt_t *h, ngx_uint_t offset)
  3963. {
  3964.     ngx_http_upstream_t  *u;

  3965.     u = r->upstream;

  3966.     if (u->headers_in.x_accel_expires) {
  3967.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3968.                       "upstream sent duplicate header line: \"%V: %V\", "
  3969.                       "previous value: \"%V: %V\", ignored",
  3970.                       &h->key, &h->value,
  3971.                       &u->headers_in.x_accel_expires->key,
  3972.                       &u->headers_in.x_accel_expires->value);
  3973.         h->hash = 0;
  3974.         return NGX_OK;
  3975.     }

  3976.     u->headers_in.x_accel_expires = h;
  3977.     h->next = NULL;

  3978. #if (NGX_HTTP_CACHE)
  3979.     {
  3980.     u_char     *p;
  3981.     size_t      len;
  3982.     ngx_int_t   n;

  3983.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_EXPIRES) {
  3984.         return NGX_OK;
  3985.     }

  3986.     if (r->cache == NULL) {
  3987.         return NGX_OK;
  3988.     }

  3989.     len = h->value.len;
  3990.     p = h->value.data;

  3991.     if (p[0] != '@') {
  3992.         n = ngx_atoi(p, len);

  3993.         switch (n) {
  3994.         case 0:
  3995.             u->cacheable = 0;
  3996.             /* fall through */

  3997.         case NGX_ERROR:
  3998.             return NGX_OK;

  3999.         default:
  4000.             r->cache->valid_sec = ngx_time() + n;
  4001.             u->headers_in.no_cache = 0;
  4002.             u->headers_in.expired = 0;
  4003.             return NGX_OK;
  4004.         }
  4005.     }

  4006.     p++;
  4007.     len--;

  4008.     n = ngx_atoi(p, len);

  4009.     if (n != NGX_ERROR) {
  4010.         r->cache->valid_sec = n;
  4011.         u->headers_in.no_cache = 0;
  4012.         u->headers_in.expired = 0;
  4013.     }
  4014.     }
  4015. #endif

  4016.     return NGX_OK;
  4017. }


  4018. static ngx_int_t
  4019. ‌ngx_http_upstream_process_limit_rate(ngx_http_request_t *r, ngx_table_elt_t *h,
  4020.     ngx_uint_t offset)
  4021. {
  4022.     ngx_int_t             n;
  4023.     ngx_http_upstream_t  *u;

  4024.     u = r->upstream;

  4025.     if (u->headers_in.x_accel_limit_rate) {
  4026.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  4027.                       "upstream sent duplicate header line: \"%V: %V\", "
  4028.                       "previous value: \"%V: %V\", ignored",
  4029.                       &h->key, &h->value,
  4030.                       &u->headers_in.x_accel_limit_rate->key,
  4031.                       &u->headers_in.x_accel_limit_rate->value);
  4032.         h->hash = 0;
  4033.         return NGX_OK;
  4034.     }

  4035.     u->headers_in.x_accel_limit_rate = h;
  4036.     h->next = NULL;

  4037.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_LIMIT_RATE) {
  4038.         return NGX_OK;
  4039.     }

  4040.     n = ngx_atoi(h->value.data, h->value.len);

  4041.     if (n != NGX_ERROR) {
  4042.         r->limit_rate = (size_t) n;
  4043.         r->limit_rate_set = 1;
  4044.     }

  4045.     return NGX_OK;
  4046. }


  4047. static ngx_int_t
  4048. ‌ngx_http_upstream_process_buffering(ngx_http_request_t *r, ngx_table_elt_t *h,
  4049.     ngx_uint_t offset)
  4050. {
  4051.     u_char                c0, c1, c2;
  4052.     ngx_http_upstream_t  *u;

  4053.     u = r->upstream;

  4054.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_BUFFERING) {
  4055.         return NGX_OK;
  4056.     }

  4057.     if (u->conf->change_buffering) {

  4058.         if (h->value.len == 2) {
  4059.             c0 = ngx_tolower(h->value.data[0]);
  4060.             c1 = ngx_tolower(h->value.data[1]);

  4061.             if (c0 == 'n' && c1 == 'o') {
  4062.                 u->buffering = 0;
  4063.             }

  4064.         } else if (h->value.len == 3) {
  4065.             c0 = ngx_tolower(h->value.data[0]);
  4066.             c1 = ngx_tolower(h->value.data[1]);
  4067.             c2 = ngx_tolower(h->value.data[2]);

  4068.             if (c0 == 'y' && c1 == 'e' && c2 == 's') {
  4069.                 u->buffering = 1;
  4070.             }
  4071.         }
  4072.     }

  4073.     return NGX_OK;
  4074. }


  4075. static ngx_int_t
  4076. ‌ngx_http_upstream_process_charset(ngx_http_request_t *r, ngx_table_elt_t *h,
  4077.     ngx_uint_t offset)
  4078. {
  4079.     ngx_http_upstream_t  *u;

  4080.     u = r->upstream;

  4081.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_CHARSET) {
  4082.         return NGX_OK;
  4083.     }

  4084.     r->headers_out.override_charset = &h->value;

  4085.     return NGX_OK;
  4086. }


  4087. static ngx_int_t
  4088. ‌ngx_http_upstream_process_connection(ngx_http_request_t *r, ngx_table_elt_t *h,
  4089.     ngx_uint_t offset)
  4090. {
  4091.     ngx_table_elt_t      **ph;
  4092.     ngx_http_upstream_t   *u;

  4093.     u = r->upstream;
  4094.     ph = &u->headers_in.connection;

  4095.     while (*ph) { ph = &(*ph)->next; }

  4096.     *ph = h;
  4097.     h->next = NULL;

  4098.     if (ngx_strlcasestrn(h->value.data, h->value.data + h->value.len,
  4099.                          (u_char *) "close", 5 - 1)
  4100.         != NULL)
  4101.     {
  4102.         u->headers_in.connection_close = 1;
  4103.     }

  4104.     return NGX_OK;
  4105. }


  4106. static ngx_int_t
  4107. ‌ngx_http_upstream_process_transfer_encoding(ngx_http_request_t *r,
  4108.     ngx_table_elt_t *h, ngx_uint_t offset)
  4109. {
  4110.     ngx_http_upstream_t  *u;

  4111.     u = r->upstream;

  4112.     if (u->headers_in.transfer_encoding) {
  4113.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4114.                       "upstream sent duplicate header line: \"%V: %V\", "
  4115.                       "previous value: \"%V: %V\"",
  4116.                       &h->key, &h->value,
  4117.                       &u->headers_in.transfer_encoding->key,
  4118.                       &u->headers_in.transfer_encoding->value);
  4119.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4120.     }

  4121.     if (u->headers_in.content_length) {
  4122.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4123.                       "upstream sent \"Content-Length\" and "
  4124.                       "\"Transfer-Encoding\" headers at the same time");
  4125.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4126.     }

  4127.     u->headers_in.transfer_encoding = h;
  4128.     h->next = NULL;

  4129.     if (h->value.len == 7
  4130.         && ngx_strncasecmp(h->value.data, (u_char *) "chunked", 7) == 0)
  4131.     {
  4132.         u->headers_in.chunked = 1;

  4133.     } else {
  4134.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4135.                       "upstream sent unknown \"Transfer-Encoding\": \"%V\"",
  4136.                       &h->value);
  4137.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4138.     }

  4139.     return NGX_OK;
  4140. }


  4141. static ngx_int_t
  4142. ‌ngx_http_upstream_process_vary(ngx_http_request_t *r,
  4143.     ngx_table_elt_t *h, ngx_uint_t offset)
  4144. {
  4145.     ngx_table_elt_t      **ph;
  4146.     ngx_http_upstream_t   *u;

  4147.     u = r->upstream;
  4148.     ph = &u->headers_in.vary;

  4149.     while (*ph) { ph = &(*ph)->next; }

  4150.     *ph = h;
  4151.     h->next = NULL;

  4152. #if (NGX_HTTP_CACHE)
  4153.     {
  4154.     u_char     *p;
  4155.     size_t      len;
  4156.     ngx_str_t   vary;

  4157.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_VARY) {
  4158.         return NGX_OK;
  4159.     }

  4160.     if (r->cache == NULL || !u->cacheable) {
  4161.         return NGX_OK;
  4162.     }

  4163.     if (h->value.len == 1 && h->value.data[0] == '*') {
  4164.         u->cacheable = 0;
  4165.         return NGX_OK;
  4166.     }

  4167.     if (u->headers_in.vary->next) {

  4168.         len = 0;

  4169.         for (h = u->headers_in.vary; h; h = h->next) {
  4170.             len += h->value.len + 2;
  4171.         }

  4172.         len -= 2;

  4173.         p = ngx_pnalloc(r->pool, len);
  4174.         if (p == NULL) {
  4175.             return NGX_ERROR;
  4176.         }

  4177.         vary.len = len;
  4178.         vary.data = p;

  4179.         for (h = u->headers_in.vary; h; h = h->next) {
  4180.             p = ngx_copy(p, h->value.data, h->value.len);

  4181.             if (h->next == NULL) {
  4182.                 break;
  4183.             }

  4184.             *p++ = ','; *p++ = ' ';
  4185.         }

  4186.     } else {
  4187.         vary = h->value;
  4188.     }

  4189.     if (vary.len > NGX_HTTP_CACHE_VARY_LEN) {
  4190.         u->cacheable = 0;
  4191.     }

  4192.     r->cache->vary = vary;
  4193.     }
  4194. #endif

  4195.     return NGX_OK;
  4196. }


  4197. static ngx_int_t
  4198. ‌ngx_http_upstream_process_priority(ngx_http_request_t *r,
  4199.     ngx_table_elt_t *h, ngx_uint_t offset)
  4200. {
  4201. #if (NGX_HTTP_V2)
  4202.     ngx_http_priority_t    priority;
  4203.     ngx_http_v2_stream_t  *stream;

  4204.     if (r != r->main) {
  4205.         return NGX_OK;
  4206.     }

  4207.     /* RFC 9218, Section 8: server hints override the client's values */

  4208.     stream = r->stream;

  4209.     if (stream == NULL) {
  4210.         return NGX_OK;
  4211.     }

  4212.     if (ngx_http_priority_parse(&h->value, &priority) != NGX_OK
  4213.         || !(priority.urgency_set || priority.incremental_set))
  4214.     {
  4215.         return NGX_OK;
  4216.     }

  4217.     stream->priority.server = priority;
  4218.     ngx_http_priority_state_update(&stream->priority);

  4219.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4220.                    "http upstream priority: u=%ud i=%ud",
  4221.                    stream->priority.effective.urgency,
  4222.                    stream->priority.effective.incremental);
  4223. #endif

  4224.     return NGX_OK;
  4225. }


  4226. static ngx_int_t
  4227. ‌ngx_http_upstream_copy_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  4228.     ngx_uint_t offset)
  4229. {
  4230.     ngx_table_elt_t  *ho, **ph;

  4231.     ho = ngx_list_push(&r->headers_out.headers);
  4232.     if (ho == NULL) {
  4233.         return NGX_ERROR;
  4234.     }

  4235.     *ho = *h;

  4236.     if (offset) {
  4237.         ph = (ngx_table_elt_t **) ((char *) &r->headers_out + offset);
  4238.         *ph = ho;
  4239.         ho->next = NULL;
  4240.     }

  4241.     return NGX_OK;
  4242. }


  4243. static ngx_int_t
  4244. ‌ngx_http_upstream_copy_multi_header_lines(ngx_http_request_t *r,
  4245.     ngx_table_elt_t *h, ngx_uint_t offset)
  4246. {
  4247.     ngx_table_elt_t  *ho, **ph;

  4248.     ho = ngx_list_push(&r->headers_out.headers);
  4249.     if (ho == NULL) {
  4250.         return NGX_ERROR;
  4251.     }

  4252.     *ho = *h;

  4253.     ph = (ngx_table_elt_t **) ((char *) &r->headers_out + offset);

  4254.     while (*ph) { ph = &(*ph)->next; }

  4255.     *ph = ho;
  4256.     ho->next = NULL;

  4257.     return NGX_OK;
  4258. }


  4259. static ngx_int_t
  4260. ‌ngx_http_upstream_copy_content_type(ngx_http_request_t *r, ngx_table_elt_t *h,
  4261.     ngx_uint_t offset)
  4262. {
  4263.     u_char  *p, *last;

  4264.     r->headers_out.content_type_len = h->value.len;
  4265.     r->headers_out.content_type = h->value;
  4266.     r->headers_out.content_type_lowcase = NULL;

  4267.     for (p = h->value.data; *p; p++) {

  4268.         if (*p != ';') {
  4269.             continue;
  4270.         }

  4271.         last = p;

  4272.         while (*++p == ' ') { /* void */ }

  4273.         if (*p == '\0') {
  4274.             return NGX_OK;
  4275.         }

  4276.         if (ngx_strncasecmp(p, (u_char *) "charset=", 8) != 0) {
  4277.             continue;
  4278.         }

  4279.         p += 8;

  4280.         r->headers_out.content_type_len = last - h->value.data;

  4281.         if (*p == '"') {
  4282.             p++;
  4283.         }

  4284.         last = h->value.data + h->value.len;

  4285.         if (last > p && *(last - 1) == '"') {
  4286.             last--;
  4287.         }

  4288.         r->headers_out.charset.len = last - p;
  4289.         r->headers_out.charset.data = p;

  4290.         return NGX_OK;
  4291.     }

  4292.     return NGX_OK;
  4293. }


  4294. static ngx_int_t
  4295. ‌ngx_http_upstream_copy_last_modified(ngx_http_request_t *r, ngx_table_elt_t *h,
  4296.     ngx_uint_t offset)
  4297. {
  4298.     ngx_table_elt_t  *ho;

  4299.     ho = ngx_list_push(&r->headers_out.headers);
  4300.     if (ho == NULL) {
  4301.         return NGX_ERROR;
  4302.     }

  4303.     *ho = *h;
  4304.     ho->next = NULL;

  4305.     r->headers_out.last_modified = ho;
  4306.     r->headers_out.last_modified_time =
  4307.                                     r->upstream->headers_in.last_modified_time;

  4308.     return NGX_OK;
  4309. }


  4310. static ngx_int_t
  4311. ‌ngx_http_upstream_rewrite_location(ngx_http_request_t *r, ngx_table_elt_t *h,
  4312.     ngx_uint_t offset)
  4313. {
  4314.     ngx_int_t         rc;
  4315.     ngx_table_elt_t  *ho;

  4316.     ho = ngx_list_push(&r->headers_out.headers);
  4317.     if (ho == NULL) {
  4318.         return NGX_ERROR;
  4319.     }

  4320.     *ho = *h;
  4321.     ho->next = NULL;

  4322.     if (r->upstream->rewrite_redirect) {
  4323.         rc = r->upstream->rewrite_redirect(r, ho, 0);

  4324.         if (rc == NGX_DECLINED) {
  4325.             return NGX_OK;
  4326.         }

  4327.         if (rc == NGX_OK) {
  4328.             r->headers_out.location = ho;

  4329.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4330.                            "rewritten location: \"%V\"", &ho->value);
  4331.         }

  4332.         return rc;
  4333.     }

  4334.     if (ho->value.data[0] != '/') {
  4335.         r->headers_out.location = ho;
  4336.     }

  4337.     /*
  4338.      * we do not set r->headers_out.location here to avoid handling
  4339.      * relative redirects in ngx_http_header_filter()
  4340.      */

  4341.     return NGX_OK;
  4342. }


  4343. static ngx_int_t
  4344. ‌ngx_http_upstream_rewrite_refresh(ngx_http_request_t *r, ngx_table_elt_t *h,
  4345.     ngx_uint_t offset)
  4346. {
  4347.     u_char           *p;
  4348.     ngx_int_t         rc;
  4349.     ngx_table_elt_t  *ho;

  4350.     ho = ngx_list_push(&r->headers_out.headers);
  4351.     if (ho == NULL) {
  4352.         return NGX_ERROR;
  4353.     }

  4354.     *ho = *h;
  4355.     ho->next = NULL;

  4356.     if (r->upstream->rewrite_redirect) {

  4357.         p = ngx_strcasestrn(ho->value.data, "url=", 4 - 1);

  4358.         if (p) {
  4359.             rc = r->upstream->rewrite_redirect(r, ho, p + 4 - ho->value.data);

  4360.         } else {
  4361.             return NGX_OK;
  4362.         }

  4363.         if (rc == NGX_DECLINED) {
  4364.             return NGX_OK;
  4365.         }

  4366.         if (rc == NGX_OK) {
  4367.             r->headers_out.refresh = ho;

  4368.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4369.                            "rewritten refresh: \"%V\"", &ho->value);
  4370.         }

  4371.         return rc;
  4372.     }

  4373.     r->headers_out.refresh = ho;

  4374.     return NGX_OK;
  4375. }


  4376. static ngx_int_t
  4377. ‌ngx_http_upstream_rewrite_set_cookie(ngx_http_request_t *r, ngx_table_elt_t *h,
  4378.     ngx_uint_t offset)
  4379. {
  4380.     ngx_int_t         rc;
  4381.     ngx_table_elt_t  *ho;

  4382.     ho = ngx_list_push(&r->headers_out.headers);
  4383.     if (ho == NULL) {
  4384.         return NGX_ERROR;
  4385.     }

  4386.     *ho = *h;
  4387.     ho->next = NULL;

  4388.     if (r->upstream->rewrite_cookie) {
  4389.         rc = r->upstream->rewrite_cookie(r, ho);

  4390.         if (rc == NGX_DECLINED) {
  4391.             return NGX_OK;
  4392.         }

  4393. #if (NGX_DEBUG)
  4394.         if (rc == NGX_OK) {
  4395.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4396.                            "rewritten cookie: \"%V\"", &ho->value);
  4397.         }
  4398. #endif

  4399.         return rc;
  4400.     }

  4401.     return NGX_OK;
  4402. }


  4403. static ngx_int_t
  4404. ‌ngx_http_upstream_copy_allow_ranges(ngx_http_request_t *r,
  4405.     ngx_table_elt_t *h, ngx_uint_t offset)
  4406. {
  4407.     ngx_table_elt_t  *ho;

  4408.     if (r->upstream->conf->force_ranges) {
  4409.         return NGX_OK;
  4410.     }

  4411. #if (NGX_HTTP_CACHE)

  4412.     if (r->cached) {
  4413.         r->allow_ranges = 1;
  4414.         return NGX_OK;
  4415.     }

  4416.     if (r->upstream->cacheable) {
  4417.         r->allow_ranges = 1;
  4418.         r->single_range = 1;
  4419.         return NGX_OK;
  4420.     }

  4421. #endif

  4422.     ho = ngx_list_push(&r->headers_out.headers);
  4423.     if (ho == NULL) {
  4424.         return NGX_ERROR;
  4425.     }

  4426.     *ho = *h;
  4427.     ho->next = NULL;

  4428.     r->headers_out.accept_ranges = ho;

  4429.     return NGX_OK;
  4430. }


  4431. static ngx_int_t
  4432. ‌ngx_http_upstream_copy_upgrade(ngx_http_request_t *r, ngx_table_elt_t *h,
  4433.     ngx_uint_t offset)
  4434. {
  4435.     ngx_table_elt_t  *ho;

  4436.     if (r->http_version >= NGX_HTTP_VERSION_20) {
  4437.         return NGX_OK;
  4438.     }

  4439.     ho = ngx_list_push(&r->headers_out.headers);
  4440.     if (ho == NULL) {
  4441.         return NGX_ERROR;
  4442.     }

  4443.     *ho = *h;

  4444.     return NGX_OK;
  4445. }


  4446. static ngx_int_t
  4447. ‌ngx_http_upstream_add_variables(ngx_conf_t *cf)
  4448. {
  4449.     ngx_http_variable_t  *var, *v;

  4450.     for (v = ngx_http_upstream_vars; v->name.len; v++) {
  4451.         var = ngx_http_add_variable(cf, &v->name, v->flags);
  4452.         if (var == NULL) {
  4453.             return NGX_ERROR;
  4454.         }

  4455.         var->get_handler = v->get_handler;
  4456.         var->data = v->data;
  4457.     }

  4458.     return NGX_OK;
  4459. }


  4460. static ngx_int_t
  4461. ‌ngx_http_upstream_addr_variable(ngx_http_request_t *r,
  4462.     ngx_http_variable_value_t *v, uintptr_t data)
  4463. {
  4464.     u_char                     *p;
  4465.     size_t                      len;
  4466.     ngx_uint_t                  i;
  4467.     ngx_http_upstream_state_t  *state;

  4468.     v->valid = 1;
  4469.     v->no_cacheable = 0;
  4470.     v->not_found = 0;

  4471.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4472.         v->not_found = 1;
  4473.         return NGX_OK;
  4474.     }

  4475.     len = 0;
  4476.     state = r->upstream_states->elts;

  4477.     for (i = 0; i < r->upstream_states->nelts; i++) {
  4478.         if (state[i].peer) {
  4479.             len += state[i].peer->len + 2;

  4480.         } else {
  4481.             len += 3;
  4482.         }
  4483.     }

  4484.     p = ngx_pnalloc(r->pool, len);
  4485.     if (p == NULL) {
  4486.         return NGX_ERROR;
  4487.     }

  4488.     v->data = p;

  4489.     i = 0;

  4490.     for ( ;; ) {
  4491.         if (state[i].peer) {
  4492.             p = ngx_cpymem(p, state[i].peer->data, state[i].peer->len);
  4493.         }

  4494.         if (++i == r->upstream_states->nelts) {
  4495.             break;
  4496.         }

  4497.         if (state[i].peer) {
  4498.             *p++ = ',';
  4499.             *p++ = ' ';

  4500.         } else {
  4501.             *p++ = ' ';
  4502.             *p++ = ':';
  4503.             *p++ = ' ';

  4504.             if (++i == r->upstream_states->nelts) {
  4505.                 break;
  4506.             }

  4507.             continue;
  4508.         }
  4509.     }

  4510.     v->len = p - v->data;

  4511.     return NGX_OK;
  4512. }


  4513. static ngx_int_t
  4514. ‌ngx_http_upstream_status_variable(ngx_http_request_t *r,
  4515.     ngx_http_variable_value_t *v, uintptr_t data)
  4516. {
  4517.     u_char                     *p;
  4518.     size_t                      len;
  4519.     ngx_uint_t                  i;
  4520.     ngx_http_upstream_state_t  *state;

  4521.     v->valid = 1;
  4522.     v->no_cacheable = 0;
  4523.     v->not_found = 0;

  4524.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4525.         v->not_found = 1;
  4526.         return NGX_OK;
  4527.     }

  4528.     len = r->upstream_states->nelts * (3 + 2);

  4529.     p = ngx_pnalloc(r->pool, len);
  4530.     if (p == NULL) {
  4531.         return NGX_ERROR;
  4532.     }

  4533.     v->data = p;

  4534.     i = 0;
  4535.     state = r->upstream_states->elts;

  4536.     for ( ;; ) {
  4537.         if (state[i].status) {
  4538.             p = ngx_sprintf(p, "%ui", state[i].status);

  4539.         } else {
  4540.             *p++ = '-';
  4541.         }

  4542.         if (++i == r->upstream_states->nelts) {
  4543.             break;
  4544.         }

  4545.         if (state[i].peer) {
  4546.             *p++ = ',';
  4547.             *p++ = ' ';

  4548.         } else {
  4549.             *p++ = ' ';
  4550.             *p++ = ':';
  4551.             *p++ = ' ';

  4552.             if (++i == r->upstream_states->nelts) {
  4553.                 break;
  4554.             }

  4555.             continue;
  4556.         }
  4557.     }

  4558.     v->len = p - v->data;

  4559.     return NGX_OK;
  4560. }


  4561. static ngx_int_t
  4562. ‌ngx_http_upstream_response_time_variable(ngx_http_request_t *r,
  4563.     ngx_http_variable_value_t *v, uintptr_t data)
  4564. {
  4565.     u_char                     *p;
  4566.     size_t                      len;
  4567.     ngx_uint_t                  i;
  4568.     ngx_msec_int_t              ms;
  4569.     ngx_http_upstream_state_t  *state;

  4570.     v->valid = 1;
  4571.     v->no_cacheable = 0;
  4572.     v->not_found = 0;

  4573.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4574.         v->not_found = 1;
  4575.         return NGX_OK;
  4576.     }

  4577.     len = r->upstream_states->nelts * (NGX_TIME_T_LEN + 4 + 2);

  4578.     p = ngx_pnalloc(r->pool, len);
  4579.     if (p == NULL) {
  4580.         return NGX_ERROR;
  4581.     }

  4582.     v->data = p;

  4583.     i = 0;
  4584.     state = r->upstream_states->elts;

  4585.     for ( ;; ) {

  4586.         if (data == 1) {
  4587.             ms = state[i].header_time;

  4588.         } else if (data == 2) {
  4589.             ms = state[i].connect_time;

  4590.         } else {
  4591.             ms = state[i].response_time;
  4592.         }

  4593.         if (ms != -1) {
  4594.             ms = ngx_max(ms, 0);
  4595.             p = ngx_sprintf(p, "%T.%03M", (time_t) ms / 1000, ms % 1000);

  4596.         } else {
  4597.             *p++ = '-';
  4598.         }

  4599.         if (++i == r->upstream_states->nelts) {
  4600.             break;
  4601.         }

  4602.         if (state[i].peer) {
  4603.             *p++ = ',';
  4604.             *p++ = ' ';

  4605.         } else {
  4606.             *p++ = ' ';
  4607.             *p++ = ':';
  4608.             *p++ = ' ';

  4609.             if (++i == r->upstream_states->nelts) {
  4610.                 break;
  4611.             }

  4612.             continue;
  4613.         }
  4614.     }

  4615.     v->len = p - v->data;

  4616.     return NGX_OK;
  4617. }


  4618. static ngx_int_t
  4619. ‌ngx_http_upstream_response_length_variable(ngx_http_request_t *r,
  4620.     ngx_http_variable_value_t *v, uintptr_t data)
  4621. {
  4622.     u_char                     *p;
  4623.     size_t                      len;
  4624.     ngx_uint_t                  i;
  4625.     ngx_http_upstream_state_t  *state;

  4626.     v->valid = 1;
  4627.     v->no_cacheable = 0;
  4628.     v->not_found = 0;

  4629.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4630.         v->not_found = 1;
  4631.         return NGX_OK;
  4632.     }

  4633.     len = r->upstream_states->nelts * (NGX_OFF_T_LEN + 2);

  4634.     p = ngx_pnalloc(r->pool, len);
  4635.     if (p == NULL) {
  4636.         return NGX_ERROR;
  4637.     }

  4638.     v->data = p;

  4639.     i = 0;
  4640.     state = r->upstream_states->elts;

  4641.     for ( ;; ) {

  4642.         if (data == 1) {
  4643.             p = ngx_sprintf(p, "%O", state[i].bytes_received);

  4644.         } else if (data == 2) {
  4645.             p = ngx_sprintf(p, "%O", state[i].bytes_sent);

  4646.         } else {
  4647.             p = ngx_sprintf(p, "%O", state[i].response_length);
  4648.         }

  4649.         if (++i == r->upstream_states->nelts) {
  4650.             break;
  4651.         }

  4652.         if (state[i].peer) {
  4653.             *p++ = ',';
  4654.             *p++ = ' ';

  4655.         } else {
  4656.             *p++ = ' ';
  4657.             *p++ = ':';
  4658.             *p++ = ' ';

  4659.             if (++i == r->upstream_states->nelts) {
  4660.                 break;
  4661.             }

  4662.             continue;
  4663.         }
  4664.     }

  4665.     v->len = p - v->data;

  4666.     return NGX_OK;
  4667. }


  4668. static ngx_int_t
  4669. ‌ngx_http_upstream_header_variable(ngx_http_request_t *r,
  4670.     ngx_http_variable_value_t *v, uintptr_t data)
  4671. {
  4672.     if (r->upstream == NULL) {
  4673.         v->not_found = 1;
  4674.         return NGX_OK;
  4675.     }

  4676.     return ngx_http_variable_unknown_header(r, v, (ngx_str_t *) data,
  4677.                                          &r->upstream->headers_in.headers.part,
  4678.                                          sizeof("upstream_http_") - 1);
  4679. }


  4680. static ngx_int_t
  4681. ‌ngx_http_upstream_trailer_variable(ngx_http_request_t *r,
  4682.     ngx_http_variable_value_t *v, uintptr_t data)
  4683. {
  4684.     if (r->upstream == NULL) {
  4685.         v->not_found = 1;
  4686.         return NGX_OK;
  4687.     }

  4688.     return ngx_http_variable_unknown_header(r, v, (ngx_str_t *) data,
  4689.                                         &r->upstream->headers_in.trailers.part,
  4690.                                         sizeof("upstream_trailer_") - 1);
  4691. }


  4692. static ngx_int_t
  4693. ‌ngx_http_upstream_cookie_variable(ngx_http_request_t *r,
  4694.     ngx_http_variable_value_t *v, uintptr_t data)
  4695. {
  4696.     ngx_str_t  *name = (ngx_str_t *) data;

  4697.     ngx_str_t   cookie, s;

  4698.     if (r->upstream == NULL) {
  4699.         v->not_found = 1;
  4700.         return NGX_OK;
  4701.     }

  4702.     s.len = name->len - (sizeof("upstream_cookie_") - 1);
  4703.     s.data = name->data + sizeof("upstream_cookie_") - 1;

  4704.     if (ngx_http_parse_set_cookie_lines(r, r->upstream->headers_in.set_cookie,
  4705.                                         &s, &cookie)
  4706.         == NULL)
  4707.     {
  4708.         v->not_found = 1;
  4709.         return NGX_OK;
  4710.     }

  4711.     v->len = cookie.len;
  4712.     v->valid = 1;
  4713.     v->no_cacheable = 0;
  4714.     v->not_found = 0;
  4715.     v->data = cookie.data;

  4716.     return NGX_OK;
  4717. }


  4718. #if (NGX_HTTP_CACHE)

  4719. static ngx_int_t
  4720. ‌ngx_http_upstream_cache_status(ngx_http_request_t *r,
  4721.     ngx_http_variable_value_t *v, uintptr_t data)
  4722. {
  4723.     ngx_uint_t  n;

  4724.     if (r->upstream == NULL || r->upstream->cache_status == 0) {
  4725.         v->not_found = 1;
  4726.         return NGX_OK;
  4727.     }

  4728.     n = r->upstream->cache_status - 1;

  4729.     v->valid = 1;
  4730.     v->no_cacheable = 0;
  4731.     v->not_found = 0;
  4732.     v->len = ngx_http_cache_status[n].len;
  4733.     v->data = ngx_http_cache_status[n].data;

  4734.     return NGX_OK;
  4735. }


  4736. static ngx_int_t
  4737. ‌ngx_http_upstream_cache_last_modified(ngx_http_request_t *r,
  4738.     ngx_http_variable_value_t *v, uintptr_t data)
  4739. {
  4740.     u_char  *p;

  4741.     if (r->upstream == NULL
  4742.         || !r->upstream->conf->cache_revalidate
  4743.         || r->upstream->cache_status != NGX_HTTP_CACHE_EXPIRED
  4744.         || r->cache->last_modified == -1)
  4745.     {
  4746.         v->not_found = 1;
  4747.         return NGX_OK;
  4748.     }

  4749.     p = ngx_pnalloc(r->pool, sizeof("Mon, 28 Sep 1970 06:00:00 GMT") - 1);
  4750.     if (p == NULL) {
  4751.         return NGX_ERROR;
  4752.     }

  4753.     v->len = ngx_http_time(p, r->cache->last_modified) - p;
  4754.     v->valid = 1;
  4755.     v->no_cacheable = 0;
  4756.     v->not_found = 0;
  4757.     v->data = p;

  4758.     return NGX_OK;
  4759. }


  4760. static ngx_int_t
  4761. ‌ngx_http_upstream_cache_etag(ngx_http_request_t *r,
  4762.     ngx_http_variable_value_t *v, uintptr_t data)
  4763. {
  4764.     if (r->upstream == NULL
  4765.         || !r->upstream->conf->cache_revalidate
  4766.         || r->upstream->cache_status != NGX_HTTP_CACHE_EXPIRED
  4767.         || r->cache->etag.len == 0)
  4768.     {
  4769.         v->not_found = 1;
  4770.         return NGX_OK;
  4771.     }

  4772.     v->valid = 1;
  4773.     v->no_cacheable = 0;
  4774.     v->not_found = 0;
  4775.     v->len = r->cache->etag.len;
  4776.     v->data = r->cache->etag.data;

  4777.     return NGX_OK;
  4778. }

  4779. #endif


  4780. static char *
  4781. ‌ngx_http_upstream(ngx_conf_t *cf, ngx_command_t *cmd, void *dummy)
  4782. {
  4783.     char                          *rv;
  4784.     void                          *mconf;
  4785.     ngx_str_t                     *value;
  4786.     ngx_url_t                      u;
  4787.     ngx_uint_t                     m;
  4788.     ngx_conf_t                     pcf;
  4789.     ngx_http_module_t             *module;
  4790.     ngx_http_conf_ctx_t           *ctx, *http_ctx;
  4791.     ngx_http_upstream_srv_conf_t  *uscf;

  4792.     ngx_memzero(&u, sizeof(ngx_url_t));

  4793.     value = cf->args->elts;
  4794.     u.host = value[1];
  4795.     u.no_resolve = 1;
  4796.     u.no_port = 1;

  4797.     uscf = ngx_http_upstream_add(cf, &u, NGX_HTTP_UPSTREAM_CREATE
  4798.                                          |NGX_HTTP_UPSTREAM_MODIFY
  4799.                                          |NGX_HTTP_UPSTREAM_WEIGHT
  4800.                                          |NGX_HTTP_UPSTREAM_MAX_CONNS
  4801.                                          |NGX_HTTP_UPSTREAM_MAX_FAILS
  4802.                                          |NGX_HTTP_UPSTREAM_FAIL_TIMEOUT
  4803.                                          |NGX_HTTP_UPSTREAM_DOWN
  4804.                                          |NGX_HTTP_UPSTREAM_BACKUP);
  4805.     if (uscf == NULL) {
  4806.         return NGX_CONF_ERROR;
  4807.     }


  4808.     ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_conf_ctx_t));
  4809.     if (ctx == NULL) {
  4810.         return NGX_CONF_ERROR;
  4811.     }

  4812.     http_ctx = cf->ctx;
  4813.     ctx->main_conf = http_ctx->main_conf;

  4814.     /* the upstream{}'s srv_conf */

  4815.     ctx->srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  4816.     if (ctx->srv_conf == NULL) {
  4817.         return NGX_CONF_ERROR;
  4818.     }

  4819.     ctx->srv_conf[ngx_http_upstream_module.ctx_index] = uscf;

  4820.     uscf->srv_conf = ctx->srv_conf;


  4821.     /* the upstream{}'s loc_conf */

  4822.     ctx->loc_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  4823.     if (ctx->loc_conf == NULL) {
  4824.         return NGX_CONF_ERROR;
  4825.     }

  4826.     for (m = 0; cf->cycle->modules[m]; m++) {
  4827.         if (cf->cycle->modules[m]->type != NGX_HTTP_MODULE) {
  4828.             continue;
  4829.         }

  4830.         module = cf->cycle->modules[m]->ctx;

  4831.         if (module->create_srv_conf) {
  4832.             mconf = module->create_srv_conf(cf);
  4833.             if (mconf == NULL) {
  4834.                 return NGX_CONF_ERROR;
  4835.             }

  4836.             ctx->srv_conf[cf->cycle->modules[m]->ctx_index] = mconf;
  4837.         }

  4838.         if (module->create_loc_conf) {
  4839.             mconf = module->create_loc_conf(cf);
  4840.             if (mconf == NULL) {
  4841.                 return NGX_CONF_ERROR;
  4842.             }

  4843.             ctx->loc_conf[cf->cycle->modules[m]->ctx_index] = mconf;
  4844.         }
  4845.     }

  4846.     uscf->servers = ngx_array_create(cf->pool, 4,
  4847.                                      sizeof(ngx_http_upstream_server_t));
  4848.     if (uscf->servers == NULL) {
  4849.         return NGX_CONF_ERROR;
  4850.     }


  4851.     /* parse inside upstream{} */

  4852.     pcf = *cf;
  4853.     cf->ctx = ctx;
  4854.     cf->cmd_type = NGX_HTTP_UPS_CONF;

  4855.     rv = ngx_conf_parse(cf, NULL);

  4856.     *cf = pcf;

  4857.     if (rv != NGX_CONF_OK) {
  4858.         return rv;
  4859.     }

  4860.     if (uscf->servers->nelts == 0) {
  4861.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4862.                            "no servers are inside upstream");
  4863.         return NGX_CONF_ERROR;
  4864.     }

  4865.     return rv;
  4866. }


  4867. static char *
  4868. ‌ngx_http_upstream_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  4869. {
  4870.     ngx_http_upstream_srv_conf_t  *uscf = conf;

  4871.     time_t                       fail_timeout;
  4872.     ngx_str_t                   *value, s;
  4873.     ngx_url_t                    u;
  4874.     ngx_int_t                    weight, max_conns, max_fails;
  4875.     ngx_uint_t                   i;
  4876. #if (NGX_HTTP_UPSTREAM_ZONE)
  4877.     ngx_uint_t                   resolve;
  4878. #endif
  4879.     ngx_http_upstream_server_t  *us;

  4880.     us = ngx_array_push(uscf->servers);
  4881.     if (us == NULL) {
  4882.         return NGX_CONF_ERROR;
  4883.     }

  4884.     ngx_memzero(us, sizeof(ngx_http_upstream_server_t));

  4885.     value = cf->args->elts;

  4886.     weight = 1;
  4887.     max_conns = 0;
  4888.     max_fails = 1;
  4889.     fail_timeout = 10;
  4890. #if (NGX_HTTP_UPSTREAM_ZONE)
  4891.     resolve = 0;
  4892. #endif

  4893.     for (i = 2; i < cf->args->nelts; i++) {

  4894.         if (ngx_strncmp(value[i].data, "weight=", 7) == 0) {

  4895.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_WEIGHT)) {
  4896.                 goto not_supported;
  4897.             }

  4898.             weight = ngx_atoi(&value[i].data[7], value[i].len - 7);

  4899.             if (weight == NGX_ERROR || weight == 0) {
  4900.                 goto invalid;
  4901.             }

  4902.             continue;
  4903.         }

  4904.         if (ngx_strncmp(value[i].data, "max_conns=", 10) == 0) {

  4905.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_MAX_CONNS)) {
  4906.                 goto not_supported;
  4907.             }

  4908.             max_conns = ngx_atoi(&value[i].data[10], value[i].len - 10);

  4909.             if (max_conns == NGX_ERROR) {
  4910.                 goto invalid;
  4911.             }

  4912.             continue;
  4913.         }

  4914.         if (ngx_strncmp(value[i].data, "max_fails=", 10) == 0) {

  4915.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_MAX_FAILS)) {
  4916.                 goto not_supported;
  4917.             }

  4918.             max_fails = ngx_atoi(&value[i].data[10], value[i].len - 10);

  4919.             if (max_fails == NGX_ERROR) {
  4920.                 goto invalid;
  4921.             }

  4922.             continue;
  4923.         }

  4924.         if (ngx_strncmp(value[i].data, "fail_timeout=", 13) == 0) {

  4925.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_FAIL_TIMEOUT)) {
  4926.                 goto not_supported;
  4927.             }

  4928.             s.len = value[i].len - 13;
  4929.             s.data = &value[i].data[13];

  4930.             fail_timeout = ngx_parse_time(&s, 1);

  4931.             if (fail_timeout == (time_t) NGX_ERROR) {
  4932.                 goto invalid;
  4933.             }

  4934.             continue;
  4935.         }

  4936.         if (ngx_strcmp(value[i].data, "backup") == 0) {

  4937.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_BACKUP)) {
  4938.                 goto not_supported;
  4939.             }

  4940.             us->backup = 1;

  4941.             continue;
  4942.         }

  4943.         if (ngx_strcmp(value[i].data, "down") == 0) {

  4944.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_DOWN)) {
  4945.                 goto not_supported;
  4946.             }

  4947.             us->down = NGX_HTTP_UPSTREAM_FAILED;

  4948.             continue;
  4949.         }

  4950. #if (NGX_HTTP_UPSTREAM_STICKY)
  4951.         if (ngx_strcmp(value[i].data, "drain") == 0) {

  4952.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_DOWN)) {
  4953.                 goto not_supported;
  4954.             }

  4955.             us->down = NGX_HTTP_UPSTREAM_DRAINING;

  4956.             continue;
  4957.         }
  4958. #endif

  4959. #if (NGX_HTTP_UPSTREAM_SID)
  4960.         if (ngx_strncmp(value[i].data, "route=", 6) == 0) {

  4961.             us->sid.data = &value[i].data[6];
  4962.             us->sid.len = value[i].len - 6;

  4963.             if (us->sid.len == 0) {
  4964.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "route is empty");
  4965.                 return NGX_CONF_ERROR;
  4966.             }

  4967.             if (us->sid.len > NGX_HTTP_UPSTREAM_SID_LEN) {
  4968.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4969.                                    "route is longer than %d",
  4970.                                    NGX_HTTP_UPSTREAM_SID_LEN);
  4971.                 return NGX_CONF_ERROR;
  4972.             }

  4973.             continue;
  4974.         }
  4975. #endif

  4976. #if (NGX_HTTP_UPSTREAM_ZONE)
  4977.         if (ngx_strcmp(value[i].data, "resolve") == 0) {
  4978.             resolve = 1;
  4979.             continue;
  4980.         }

  4981.         if (ngx_strncmp(value[i].data, "service=", 8) == 0) {

  4982.             us->service.len = value[i].len - 8;
  4983.             us->service.data = &value[i].data[8];

  4984.             if (us->service.len == 0) {
  4985.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "service is empty");
  4986.                 return NGX_CONF_ERROR;
  4987.             }

  4988.             continue;
  4989.         }
  4990. #endif

  4991.         goto invalid;
  4992.     }

  4993.     ngx_memzero(&u, sizeof(ngx_url_t));

  4994.     u.url = value[1];
  4995.     u.default_port = 80;

  4996. #if (NGX_HTTP_UPSTREAM_ZONE)
  4997.     if (resolve) {
  4998.         /* resolve at run time */
  4999.         u.no_resolve = 1;
  5000.     }

  5001.     if (us->service.len && !resolve) {
  5002.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5003.                            "service upstream \"%V\" requires "
  5004.                            "\"resolve\" parameter",
  5005.                            &u.url);
  5006.         return NGX_CONF_ERROR;
  5007.     }

  5008. #endif

  5009.     if (ngx_parse_url(cf->pool, &u) != NGX_OK) {
  5010.         if (u.err) {
  5011.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5012.                                "%s in upstream \"%V\"", u.err, &u.url);
  5013.         }

  5014.         return NGX_CONF_ERROR;
  5015.     }

  5016.     us->name = u.url;

  5017. #if (NGX_HTTP_UPSTREAM_ZONE)

  5018.     if (us->service.len && !u.no_port) {
  5019.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5020.                            "service upstream \"%V\" may not have port",
  5021.                            &us->name);

  5022.         return NGX_CONF_ERROR;
  5023.     }

  5024.     if (us->service.len && u.naddrs) {
  5025.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5026.                            "service upstream \"%V\" requires domain name",
  5027.                            &us->name);

  5028.         return NGX_CONF_ERROR;
  5029.     }

  5030.     if (resolve && u.naddrs == 0) {
  5031.         ngx_addr_t  *addr;

  5032.         /* save port */

  5033.         addr = ngx_pcalloc(cf->pool, sizeof(ngx_addr_t));
  5034.         if (addr == NULL) {
  5035.             return NGX_CONF_ERROR;
  5036.         }

  5037.         addr->sockaddr = ngx_palloc(cf->pool, u.socklen);
  5038.         if (addr->sockaddr == NULL) {
  5039.             return NGX_CONF_ERROR;
  5040.         }

  5041.         ngx_memcpy(addr->sockaddr, &u.sockaddr, u.socklen);

  5042.         addr->socklen = u.socklen;

  5043.         us->addrs = addr;
  5044.         us->naddrs = 1;

  5045.         us->host = u.host;

  5046.     } else {
  5047.         us->addrs = u.addrs;
  5048.         us->naddrs = u.naddrs;
  5049.     }

  5050. #else

  5051.     us->addrs = u.addrs;
  5052.     us->naddrs = u.naddrs;

  5053. #endif

  5054.     us->weight = weight;
  5055.     us->max_conns = max_conns;
  5056.     us->max_fails = max_fails;
  5057.     us->fail_timeout = fail_timeout;

  5058.     return NGX_CONF_OK;

  5059. invalid:

  5060.     ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5061.                        "invalid parameter \"%V\"", &value[i]);

  5062.     return NGX_CONF_ERROR;

  5063. not_supported:

  5064.     ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5065.                        "balancing method does not support parameter \"%V\"",
  5066.                        &value[i]);

  5067.     return NGX_CONF_ERROR;
  5068. }


  5069. #if (NGX_HTTP_UPSTREAM_ZONE)

  5070. static char *
  5071. ‌ngx_http_upstream_resolver(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  5072. {
  5073.     ngx_http_upstream_srv_conf_t  *uscf = conf;

  5074.     ngx_str_t  *value;

  5075.     if (uscf->resolver) {
  5076.         return "is duplicate";
  5077.     }

  5078.     value = cf->args->elts;

  5079.     uscf->resolver = ngx_resolver_create(cf, &value[1], cf->args->nelts - 1);
  5080.     if (uscf->resolver == NULL) {
  5081.         return NGX_CONF_ERROR;
  5082.     }

  5083.     return NGX_CONF_OK;
  5084. }

  5085. #endif


  5086. ngx_http_upstream_srv_conf_t *
  5087. ‌ngx_http_upstream_add(ngx_conf_t *cf, ngx_url_t *u, ngx_uint_t flags)
  5088. {
  5089.     ngx_uint_t                      i;
  5090.     ngx_http_upstream_server_t     *us;
  5091.     ngx_http_upstream_srv_conf_t   *uscf, **uscfp;
  5092.     ngx_http_upstream_main_conf_t  *umcf;

  5093.     if (!(flags & NGX_HTTP_UPSTREAM_CREATE)) {

  5094.         if (ngx_parse_url(cf->pool, u) != NGX_OK) {
  5095.             if (u->err) {
  5096.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5097.                                    "%s in upstream \"%V\"", u->err, &u->url);
  5098.             }

  5099.             return NULL;
  5100.         }
  5101.     }

  5102.     umcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_upstream_module);

  5103.     uscfp = umcf->upstreams.elts;

  5104.     for (i = 0; i < umcf->upstreams.nelts; i++) {

  5105.         if (uscfp[i]->host.len != u->host.len
  5106.             || ngx_strncasecmp(uscfp[i]->host.data, u->host.data, u->host.len)
  5107.                != 0)
  5108.         {
  5109.             continue;
  5110.         }

  5111.         if ((flags & NGX_HTTP_UPSTREAM_CREATE)
  5112.              && (uscfp[i]->flags & NGX_HTTP_UPSTREAM_CREATE))
  5113.         {
  5114.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5115.                                "duplicate upstream \"%V\"", &u->host);
  5116.             return NULL;
  5117.         }

  5118.         if ((uscfp[i]->flags & NGX_HTTP_UPSTREAM_CREATE) && !u->no_port) {
  5119.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5120.                                "upstream \"%V\" may not have port %d",
  5121.                                &u->host, u->port);
  5122.             return NULL;
  5123.         }

  5124.         if ((flags & NGX_HTTP_UPSTREAM_CREATE) && !uscfp[i]->no_port) {
  5125.             ngx_log_error(NGX_LOG_EMERG, cf->log, 0,
  5126.                           "upstream \"%V\" may not have port %d in %s:%ui",
  5127.                           &u->host, uscfp[i]->port,
  5128.                           uscfp[i]->file_name, uscfp[i]->line);
  5129.             return NULL;
  5130.         }

  5131.         if (uscfp[i]->port && u->port
  5132.             && uscfp[i]->port != u->port)
  5133.         {
  5134.             continue;
  5135.         }

  5136.         if (flags & NGX_HTTP_UPSTREAM_CREATE) {
  5137.             uscfp[i]->flags = flags;
  5138.             uscfp[i]->port = 0;
  5139.         }

  5140.         return uscfp[i];
  5141.     }

  5142.     uscf = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_srv_conf_t));
  5143.     if (uscf == NULL) {
  5144.         return NULL;
  5145.     }

  5146.     uscf->flags = flags;
  5147.     uscf->host = u->host;
  5148.     uscf->file_name = cf->conf_file->file.name.data;
  5149.     uscf->line = cf->conf_file->line;
  5150.     uscf->port = u->port;
  5151.     uscf->no_port = u->no_port;
  5152. #if (NGX_HTTP_UPSTREAM_ZONE)
  5153.     uscf->resolver_timeout = NGX_CONF_UNSET_MSEC;
  5154. #endif

  5155.     if (u->naddrs == 1 && (u->port || u->family == AF_UNIX)) {
  5156.         uscf->servers = ngx_array_create(cf->pool, 1,
  5157.                                          sizeof(ngx_http_upstream_server_t));
  5158.         if (uscf->servers == NULL) {
  5159.             return NULL;
  5160.         }

  5161.         us = ngx_array_push(uscf->servers);
  5162.         if (us == NULL) {
  5163.             return NULL;
  5164.         }

  5165.         ngx_memzero(us, sizeof(ngx_http_upstream_server_t));

  5166.         us->addrs = u->addrs;
  5167.         us->naddrs = 1;
  5168.     }

  5169.     uscfp = ngx_array_push(&umcf->upstreams);
  5170.     if (uscfp == NULL) {
  5171.         return NULL;
  5172.     }

  5173.     *uscfp = uscf;

  5174.     return uscf;
  5175. }


  5176. char *
  5177. ‌ngx_http_upstream_bind_set_slot(ngx_conf_t *cf, ngx_command_t *cmd,
  5178.     void *conf)
  5179. {
  5180.     char  *p = conf;

  5181.     ngx_int_t                           rc;
  5182.     ngx_str_t                          *value;
  5183.     ngx_http_complex_value_t            cv;
  5184.     ngx_http_upstream_local_t         **plocal, *local;
  5185.     ngx_http_compile_complex_value_t    ccv;

  5186.     plocal = (ngx_http_upstream_local_t **) (p + cmd->offset);

  5187.     if (*plocal != NGX_CONF_UNSET_PTR) {
  5188.         return "is duplicate";
  5189.     }

  5190.     value = cf->args->elts;

  5191.     if (cf->args->nelts == 2 && ngx_strcmp(value[1].data, "off") == 0) {
  5192.         *plocal = NULL;
  5193.         return NGX_CONF_OK;
  5194.     }

  5195.     ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));

  5196.     ccv.cf = cf;
  5197.     ccv.value = &value[1];
  5198.     ccv.complex_value = &cv;

  5199.     if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
  5200.         return NGX_CONF_ERROR;
  5201.     }

  5202.     local = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_local_t));
  5203.     if (local == NULL) {
  5204.         return NGX_CONF_ERROR;
  5205.     }

  5206.     *plocal = local;

  5207.     if (cv.lengths) {
  5208.         local->value = ngx_palloc(cf->pool, sizeof(ngx_http_complex_value_t));
  5209.         if (local->value == NULL) {
  5210.             return NGX_CONF_ERROR;
  5211.         }

  5212.         *local->value = cv;

  5213.     } else {
  5214.         local->addr = ngx_palloc(cf->pool, sizeof(ngx_addr_t));
  5215.         if (local->addr == NULL) {
  5216.             return NGX_CONF_ERROR;
  5217.         }

  5218.         rc = ngx_parse_addr_port(cf->pool, local->addr, value[1].data,
  5219.                                  value[1].len);

  5220.         switch (rc) {
  5221.         case NGX_OK:
  5222.             local->addr->name = value[1];
  5223.             break;

  5224.         case NGX_DECLINED:
  5225.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5226.                                "invalid address \"%V\"", &value[1]);
  5227.             /* fall through */

  5228.         default:
  5229.             return NGX_CONF_ERROR;
  5230.         }
  5231.     }

  5232.     if (cf->args->nelts > 2) {
  5233.         if (ngx_strcmp(value[2].data, "transparent") == 0) {
  5234. #if (NGX_HAVE_TRANSPARENT_PROXY)
  5235.             ngx_core_conf_t  *ccf;

  5236.             ccf = (ngx_core_conf_t *) ngx_get_conf(cf->cycle->conf_ctx,
  5237.                                                    ngx_core_module);

  5238.             ccf->transparent = 1;
  5239.             local->transparent = 1;
  5240. #else
  5241.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5242.                                "transparent proxying is not supported "
  5243.                                "on this platform, ignored");
  5244. #endif
  5245.         } else {
  5246.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5247.                                "invalid parameter \"%V\"", &value[2]);
  5248.             return NGX_CONF_ERROR;
  5249.         }
  5250.     }

  5251.     return NGX_CONF_OK;
  5252. }


  5253. static ngx_int_t
  5254. ‌ngx_http_upstream_set_local(ngx_http_request_t *r, ngx_http_upstream_t *u,
  5255.     ngx_http_upstream_local_t *local)
  5256. {
  5257.     ngx_int_t    rc;
  5258.     ngx_str_t    val;
  5259.     ngx_addr_t  *addr;

  5260.     if (local == NULL) {
  5261.         u->peer.local = NULL;
  5262.         return NGX_OK;
  5263.     }

  5264. #if (NGX_HAVE_TRANSPARENT_PROXY)
  5265.     u->peer.transparent = local->transparent;
  5266. #endif

  5267.     if (local->value == NULL) {
  5268.         u->peer.local = local->addr;
  5269.         return NGX_OK;
  5270.     }

  5271.     if (ngx_http_complex_value(r, local->value, &val) != NGX_OK) {
  5272.         return NGX_ERROR;
  5273.     }

  5274.     if (val.len == 0) {
  5275.         u->peer.local = NULL;
  5276.         return NGX_OK;
  5277.     }

  5278.     addr = ngx_palloc(r->pool, sizeof(ngx_addr_t));
  5279.     if (addr == NULL) {
  5280.         return NGX_ERROR;
  5281.     }

  5282.     rc = ngx_parse_addr_port(r->pool, addr, val.data, val.len);
  5283.     if (rc == NGX_ERROR) {
  5284.         return NGX_ERROR;
  5285.     }

  5286.     if (rc != NGX_OK) {
  5287.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  5288.                       "invalid local address \"%V\"", &val);
  5289.         u->peer.local = NULL;
  5290.         return NGX_OK;
  5291.     }

  5292.     addr->name = val;
  5293.     u->peer.local = addr;

  5294.     return NGX_OK;
  5295. }


  5296. char *
  5297. ‌ngx_http_upstream_param_set_slot(ngx_conf_t *cf, ngx_command_t *cmd,
  5298.     void *conf)
  5299. {
  5300.     char  *p = conf;

  5301.     ngx_str_t                   *value;
  5302.     ngx_array_t                **a;
  5303.     ngx_http_upstream_param_t   *param;

  5304.     a = (ngx_array_t **) (p + cmd->offset);

  5305.     if (*a == NULL) {
  5306.         *a = ngx_array_create(cf->pool, 4, sizeof(ngx_http_upstream_param_t));
  5307.         if (*a == NULL) {
  5308.             return NGX_CONF_ERROR;
  5309.         }
  5310.     }

  5311.     param = ngx_array_push(*a);
  5312.     if (param == NULL) {
  5313.         return NGX_CONF_ERROR;
  5314.     }

  5315.     value = cf->args->elts;

  5316.     param->key = value[1];
  5317.     param->value = value[2];
  5318.     param->skip_empty = 0;

  5319.     if (cf->args->nelts == 4) {
  5320.         if (ngx_strcmp(value[3].data, "if_not_empty") != 0) {
  5321.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5322.                                "invalid parameter \"%V\"", &value[3]);
  5323.             return NGX_CONF_ERROR;
  5324.         }

  5325.         param->skip_empty = 1;
  5326.     }

  5327.     return NGX_CONF_OK;
  5328. }


  5329. ngx_int_t
  5330. ‌ngx_http_upstream_hide_headers_hash(ngx_conf_t *cf,
  5331.     ngx_http_upstream_conf_t *conf, ngx_http_upstream_conf_t *prev,
  5332.     ngx_str_t *default_hide_headers, ngx_hash_init_t *hash)
  5333. {
  5334.     ngx_str_t       *h;
  5335.     ngx_uint_t       i, j;
  5336.     ngx_array_t      hide_headers;
  5337.     ngx_hash_key_t  *hk;

  5338.     if (conf->hide_headers == NGX_CONF_UNSET_PTR
  5339.         && conf->pass_headers == NGX_CONF_UNSET_PTR)
  5340.     {
  5341.         conf->hide_headers = prev->hide_headers;
  5342.         conf->pass_headers = prev->pass_headers;

  5343.         conf->hide_headers_hash = prev->hide_headers_hash;

  5344.         if (conf->hide_headers_hash.buckets) {
  5345.             return NGX_OK;
  5346.         }

  5347.     } else {
  5348.         if (conf->hide_headers == NGX_CONF_UNSET_PTR) {
  5349.             conf->hide_headers = prev->hide_headers;
  5350.         }

  5351.         if (conf->pass_headers == NGX_CONF_UNSET_PTR) {
  5352.             conf->pass_headers = prev->pass_headers;
  5353.         }
  5354.     }

  5355.     if (ngx_array_init(&hide_headers, cf->temp_pool, 4, sizeof(ngx_hash_key_t))
  5356.         != NGX_OK)
  5357.     {
  5358.         return NGX_ERROR;
  5359.     }

  5360.     for (h = default_hide_headers; h->len; h++) {
  5361.         hk = ngx_array_push(&hide_headers);
  5362.         if (hk == NULL) {
  5363.             return NGX_ERROR;
  5364.         }

  5365.         hk->key = *h;
  5366.         hk->key_hash = ngx_hash_key_lc(h->data, h->len);
  5367.         hk->value = (void *) 1;
  5368.     }

  5369.     if (conf->hide_headers != NGX_CONF_UNSET_PTR) {

  5370.         h = conf->hide_headers->elts;

  5371.         for (i = 0; i < conf->hide_headers->nelts; i++) {

  5372.             hk = hide_headers.elts;

  5373.             for (j = 0; j < hide_headers.nelts; j++) {
  5374.                 if (ngx_strcasecmp(h[i].data, hk[j].key.data) == 0) {
  5375.                     goto exist;
  5376.                 }
  5377.             }

  5378.             hk = ngx_array_push(&hide_headers);
  5379.             if (hk == NULL) {
  5380.                 return NGX_ERROR;
  5381.             }

  5382.             hk->key = h[i];
  5383.             hk->key_hash = ngx_hash_key_lc(h[i].data, h[i].len);
  5384.             hk->value = (void *) 1;

  5385.         exist:

  5386.             continue;
  5387.         }
  5388.     }

  5389.     if (conf->pass_headers != NGX_CONF_UNSET_PTR) {

  5390.         h = conf->pass_headers->elts;
  5391.         hk = hide_headers.elts;

  5392.         for (i = 0; i < conf->pass_headers->nelts; i++) {
  5393.             for (j = 0; j < hide_headers.nelts; j++) {

  5394.                 if (hk[j].key.data == NULL) {
  5395.                     continue;
  5396.                 }

  5397.                 if (ngx_strcasecmp(h[i].data, hk[j].key.data) == 0) {
  5398.                     hk[j].key.data = NULL;
  5399.                     break;
  5400.                 }
  5401.             }
  5402.         }
  5403.     }

  5404.     hash->hash = &conf->hide_headers_hash;
  5405.     hash->key = ngx_hash_key_lc;
  5406.     hash->pool = cf->pool;
  5407.     hash->temp_pool = NULL;

  5408.     if (ngx_hash_init(hash, hide_headers.elts, hide_headers.nelts) != NGX_OK) {
  5409.         return NGX_ERROR;
  5410.     }

  5411.     /*
  5412.      * special handling to preserve conf->hide_headers_hash
  5413.      * in the "http" section to inherit it to all servers
  5414.      */

  5415.     if (prev->hide_headers_hash.buckets == NULL
  5416.         && conf->hide_headers == prev->hide_headers
  5417.         && conf->pass_headers == prev->pass_headers)
  5418.     {
  5419.         prev->hide_headers_hash = conf->hide_headers_hash;
  5420.     }

  5421.     return NGX_OK;
  5422. }


  5423. #if (NGX_HTTP_SSL)

  5424. ngx_int_t
  5425. ‌ngx_http_upstream_merge_ssl_passwords(ngx_conf_t *cf,
  5426.     ngx_http_upstream_conf_t *conf, ngx_http_upstream_conf_t *prev)
  5427. {
  5428.     ngx_uint_t  preserve;

  5429.     ngx_conf_merge_ptr_value(conf->ssl_passwords, prev->ssl_passwords, NULL);

  5430.     if (conf->ssl_certificate == NULL
  5431.         || conf->ssl_certificate->value.len == 0
  5432.         || conf->ssl_certificate_key == NULL)
  5433.     {
  5434.         return NGX_OK;
  5435.     }

  5436.     if (conf->ssl_certificate->lengths == NULL
  5437.         && conf->ssl_certificate_key->lengths == NULL)
  5438.     {
  5439.         if (conf->ssl_passwords && conf->ssl_passwords->pool == NULL) {
  5440.             /* un-preserve empty password list */
  5441.             conf->ssl_passwords = NULL;
  5442.         }

  5443.         return NGX_OK;
  5444.     }

  5445.     if (conf->ssl_passwords && conf->ssl_passwords->pool != cf->temp_pool) {
  5446.         /* already preserved */
  5447.         return NGX_OK;
  5448.     }

  5449.     preserve = (conf->ssl_passwords == prev->ssl_passwords) ? 1 : 0;

  5450.     conf->ssl_passwords = ngx_ssl_preserve_passwords(cf, conf->ssl_passwords);
  5451.     if (conf->ssl_passwords == NULL) {
  5452.         return NGX_ERROR;
  5453.     }

  5454.     /*
  5455.      * special handling to keep a preserved ssl_passwords copy
  5456.      * in the previous configuration to inherit it to all children
  5457.      */

  5458.     if (preserve) {
  5459.         prev->ssl_passwords = conf->ssl_passwords;
  5460.     }

  5461.     return NGX_OK;
  5462. }

  5463. #endif


  5464. static void *
  5465. ‌ngx_http_upstream_create_main_conf(ngx_conf_t *cf)
  5466. {
  5467.     ngx_http_upstream_main_conf_t  *umcf;

  5468.     umcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_main_conf_t));
  5469.     if (umcf == NULL) {
  5470.         return NULL;
  5471.     }

  5472.     if (ngx_array_init(&umcf->upstreams, cf->pool, 4,
  5473.                        sizeof(ngx_http_upstream_srv_conf_t *))
  5474.         != NGX_OK)
  5475.     {
  5476.         return NULL;
  5477.     }

  5478.     return umcf;
  5479. }


  5480. static char *
  5481. ‌ngx_http_upstream_init_main_conf(ngx_conf_t *cf, void *conf)
  5482. {
  5483.     ngx_http_upstream_main_conf_t  *umcf = conf;

  5484.     ngx_uint_t                      i;
  5485.     ngx_array_t                     headers_in;
  5486.     ngx_hash_key_t                 *hk;
  5487.     ngx_hash_init_t                 hash;
  5488.     ngx_http_upstream_init_pt       init;
  5489.     ngx_http_upstream_header_t     *header;
  5490.     ngx_http_upstream_srv_conf_t  **uscfp;

  5491.     uscfp = umcf->upstreams.elts;

  5492.     for (i = 0; i < umcf->upstreams.nelts; i++) {

  5493.         init = uscfp[i]->peer.init_upstream ? uscfp[i]->peer.init_upstream:
  5494.                                             ngx_http_upstream_init_round_robin;

  5495.         if (init(cf, uscfp[i]) != NGX_OK) {
  5496.             return NGX_CONF_ERROR;
  5497.         }
  5498.     }


  5499.     /* upstream_headers_in_hash */

  5500.     if (ngx_array_init(&headers_in, cf->temp_pool, 32, sizeof(ngx_hash_key_t))
  5501.         != NGX_OK)
  5502.     {
  5503.         return NGX_CONF_ERROR;
  5504.     }

  5505.     for (header = ngx_http_upstream_headers_in; header->name.len; header++) {
  5506.         hk = ngx_array_push(&headers_in);
  5507.         if (hk == NULL) {
  5508.             return NGX_CONF_ERROR;
  5509.         }

  5510.         hk->key = header->name;
  5511.         hk->key_hash = ngx_hash_key_lc(header->name.data, header->name.len);
  5512.         hk->value = header;
  5513.     }

  5514.     hash.hash = &umcf->headers_in_hash;
  5515.     hash.key = ngx_hash_key_lc;
  5516.     hash.max_size = 512;
  5517.     hash.bucket_size = ngx_align(64, ngx_cacheline_size);
  5518.     hash.name = "upstream_headers_in_hash";
  5519.     hash.pool = cf->pool;
  5520.     hash.temp_pool = NULL;

  5521.     if (ngx_hash_init(&hash, headers_in.elts, headers_in.nelts) != NGX_OK) {
  5522.         return NGX_CONF_ERROR;
  5523.     }

  5524.     return NGX_CONF_OK;
  5525. }