src/http/ngx_http_upstream.c - nginx-1.31.4 nginx/ @ 8d9666701

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_copy_header_line(ngx_http_request_t *r,
  136.     ngx_table_elt_t *h, ngx_uint_t offset);
  137. static ngx_int_t
  138.     ngx_http_upstream_copy_multi_header_lines(ngx_http_request_t *r,
  139.     ngx_table_elt_t *h, ngx_uint_t offset);
  140. static ngx_int_t ngx_http_upstream_copy_content_type(ngx_http_request_t *r,
  141.     ngx_table_elt_t *h, ngx_uint_t offset);
  142. static ngx_int_t ngx_http_upstream_copy_last_modified(ngx_http_request_t *r,
  143.     ngx_table_elt_t *h, ngx_uint_t offset);
  144. static ngx_int_t ngx_http_upstream_rewrite_location(ngx_http_request_t *r,
  145.     ngx_table_elt_t *h, ngx_uint_t offset);
  146. static ngx_int_t ngx_http_upstream_rewrite_refresh(ngx_http_request_t *r,
  147.     ngx_table_elt_t *h, ngx_uint_t offset);
  148. static ngx_int_t ngx_http_upstream_rewrite_set_cookie(ngx_http_request_t *r,
  149.     ngx_table_elt_t *h, ngx_uint_t offset);
  150. static ngx_int_t ngx_http_upstream_copy_allow_ranges(ngx_http_request_t *r,
  151.     ngx_table_elt_t *h, ngx_uint_t offset);
  152. static ngx_int_t ngx_http_upstream_copy_upgrade(ngx_http_request_t *r,
  153.     ngx_table_elt_t *h, ngx_uint_t offset);

  154. static ngx_int_t ngx_http_upstream_add_variables(ngx_conf_t *cf);
  155. static ngx_int_t ngx_http_upstream_addr_variable(ngx_http_request_t *r,
  156.     ngx_http_variable_value_t *v, uintptr_t data);
  157. static ngx_int_t ngx_http_upstream_status_variable(ngx_http_request_t *r,
  158.     ngx_http_variable_value_t *v, uintptr_t data);
  159. static ngx_int_t ngx_http_upstream_response_time_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_length_variable(
  162.     ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data);
  163. static ngx_int_t ngx_http_upstream_header_variable(ngx_http_request_t *r,
  164.     ngx_http_variable_value_t *v, uintptr_t data);
  165. static ngx_int_t ngx_http_upstream_trailer_variable(ngx_http_request_t *r,
  166.     ngx_http_variable_value_t *v, uintptr_t data);
  167. static ngx_int_t ngx_http_upstream_cookie_variable(ngx_http_request_t *r,
  168.     ngx_http_variable_value_t *v, uintptr_t data);

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

  176. static ngx_int_t ngx_http_upstream_set_local(ngx_http_request_t *r,
  177.   ngx_http_upstream_t *u, ngx_http_upstream_local_t *local);

  178. static void *ngx_http_upstream_create_main_conf(ngx_conf_t *cf);
  179. static char *ngx_http_upstream_init_main_conf(ngx_conf_t *cf, void *conf);

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


  192. static ngx_http_upstream_header_t  ngx_http_upstream_headers_in[] = {

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

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

  201.     { ngx_string("Content-Length"),
  202.                  ngx_http_upstream_process_content_length, 0,
  203.                  ngx_http_upstream_ignore_header_line, 0, 0 },

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

  209.     { ngx_string("Last-Modified"),
  210.                  ngx_http_upstream_process_last_modified, 0,
  211.                  ngx_http_upstream_copy_last_modified, 0, 0 },

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

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

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

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

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

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

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

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

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

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

  253.     { ngx_string("Upgrade"),
  254.                  ngx_http_upstream_ignore_header_line, 0,
  255.                  ngx_http_upstream_copy_upgrade, 0, 0 },

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

  260.     { ngx_string("Connection"),
  261.                  ngx_http_upstream_process_connection, 0,
  262.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  263.     { ngx_string("Keep-Alive"),
  264.                  ngx_http_upstream_ignore_header_line, 0,
  265.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  266.     { ngx_string("Vary"),
  267.                  ngx_http_upstream_process_vary, 0,
  268.                  ngx_http_upstream_copy_header_line, 0, 0 },

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

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

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

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

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

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

  289.     { ngx_string("Transfer-Encoding"),
  290.                  ngx_http_upstream_process_transfer_encoding, 0,
  291.                  ngx_http_upstream_ignore_header_line, 0, 0 },

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

  296.     { ngx_null_string, NULL, 0, NULL, 0, 0 }
  297. };


  298. static ngx_command_t  ngx_http_upstream_commands[] = {

  299.     { ngx_string("upstream"),
  300.       NGX_HTTP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE1,
  301.       ngx_http_upstream,
  302.       0,
  303.       0,
  304.       NULL },

  305.     { ngx_string("server"),
  306.       NGX_HTTP_UPS_CONF|NGX_CONF_1MORE,
  307.       ngx_http_upstream_server,
  308.       NGX_HTTP_SRV_CONF_OFFSET,
  309.       0,
  310.       NULL },

  311. #if (NGX_HTTP_UPSTREAM_ZONE)

  312.     { ngx_string("resolver"),
  313.       NGX_HTTP_UPS_CONF|NGX_CONF_1MORE,
  314.       ngx_http_upstream_resolver,
  315.       NGX_HTTP_SRV_CONF_OFFSET,
  316.       0,
  317.       NULL },

  318.     { ngx_string("resolver_timeout"),
  319.       NGX_HTTP_UPS_CONF|NGX_CONF_TAKE1,
  320.       ngx_conf_set_msec_slot,
  321.       NGX_HTTP_SRV_CONF_OFFSET,
  322.       offsetof(ngx_http_upstream_srv_conf_t, resolver_timeout),
  323.       NULL },

  324. #endif

  325.       ngx_null_command
  326. };


  327. static ngx_http_module_t  ngx_http_upstream_module_ctx = {
  328.     ngx_http_upstream_add_variables,       /* preconfiguration */
  329.     NULL,                                  /* postconfiguration */

  330.     ngx_http_upstream_create_main_conf,    /* create main configuration */
  331.     ngx_http_upstream_init_main_conf,      /* init main configuration */

  332.     NULL,                                  /* create server configuration */
  333.     NULL,                                  /* merge server configuration */

  334.     NULL,                                  /* create location configuration */
  335.     NULL                                   /* merge location configuration */
  336. };


  337. ngx_module_t  ngx_http_upstream_module = {
  338.     NGX_MODULE_V1,
  339.     &ngx_http_upstream_module_ctx,         /* module context */
  340.     ngx_http_upstream_commands,            /* module directives */
  341.     NGX_HTTP_MODULE,                       /* module type */
  342.     NULL,                                  /* init master */
  343.     NULL,                                  /* init module */
  344.     NULL,                                  /* init process */
  345.     NULL,                                  /* init thread */
  346.     NULL,                                  /* exit thread */
  347.     NULL,                                  /* exit process */
  348.     NULL,                                  /* exit master */
  349.     NGX_MODULE_V1_PADDING
  350. };


  351. static ngx_http_variable_t  ngx_http_upstream_vars[] = {

  352.     { ngx_string("upstream_addr"), NULL,
  353.       ngx_http_upstream_addr_variable, 0,
  354.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  355.     { ngx_string("upstream_status"), NULL,
  356.       ngx_http_upstream_status_variable, 0,
  357.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  358.     { ngx_string("upstream_connect_time"), NULL,
  359.       ngx_http_upstream_response_time_variable, 2,
  360.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  361.     { ngx_string("upstream_header_time"), NULL,
  362.       ngx_http_upstream_response_time_variable, 1,
  363.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  364.     { ngx_string("upstream_response_time"), NULL,
  365.       ngx_http_upstream_response_time_variable, 0,
  366.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  367.     { ngx_string("upstream_response_length"), NULL,
  368.       ngx_http_upstream_response_length_variable, 0,
  369.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  370.     { ngx_string("upstream_bytes_received"), NULL,
  371.       ngx_http_upstream_response_length_variable, 1,
  372.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  373.     { ngx_string("upstream_bytes_sent"), NULL,
  374.       ngx_http_upstream_response_length_variable, 2,
  375.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  376. #if (NGX_HTTP_CACHE)

  377.     { ngx_string("upstream_cache_status"), NULL,
  378.       ngx_http_upstream_cache_status, 0,
  379.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  380.     { ngx_string("upstream_cache_last_modified"), NULL,
  381.       ngx_http_upstream_cache_last_modified, 0,
  382.       NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_NOHASH, 0 },

  383.     { ngx_string("upstream_cache_etag"), NULL,
  384.       ngx_http_upstream_cache_etag, 0,
  385.       NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_NOHASH, 0 },

  386. #endif

  387.     { ngx_string("upstream_http_"), NULL, ngx_http_upstream_header_variable,
  388.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  389.     { ngx_string("upstream_trailer_"), NULL, ngx_http_upstream_trailer_variable,
  390.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  391.     { ngx_string("upstream_cookie_"), NULL, ngx_http_upstream_cookie_variable,
  392.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  393.       ngx_http_null_variable
  394. };


  395. static ngx_http_upstream_next_t  ngx_http_upstream_next_errors[] = {
  396.     { 500, NGX_HTTP_UPSTREAM_FT_HTTP_500 },
  397.     { 502, NGX_HTTP_UPSTREAM_FT_HTTP_502 },
  398.     { 503, NGX_HTTP_UPSTREAM_FT_HTTP_503 },
  399.     { 504, NGX_HTTP_UPSTREAM_FT_HTTP_504 },
  400.     { 403, NGX_HTTP_UPSTREAM_FT_HTTP_403 },
  401.     { 404, NGX_HTTP_UPSTREAM_FT_HTTP_404 },
  402.     { 429, NGX_HTTP_UPSTREAM_FT_HTTP_429 },
  403.     { 0, 0 }
  404. };


  405. ngx_conf_bitmask_t  ngx_http_upstream_cache_method_mask[] = {
  406.     { ngx_string("GET"), NGX_HTTP_GET },
  407.     { ngx_string("HEAD"), NGX_HTTP_HEAD },
  408.     { ngx_string("POST"), NGX_HTTP_POST },
  409.     { ngx_null_string, 0 }
  410. };


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


  423. ngx_int_t
  424. ngx_http_upstream_create(ngx_http_request_t *r)
  425. {
  426.     ngx_http_upstream_t  *u;

  427.     u = r->upstream;

  428.     if (u && u->cleanup) {
  429.         r->main->count++;
  430.         ngx_http_upstream_cleanup(r);
  431.     }

  432.     u = ngx_pcalloc(r->pool, sizeof(ngx_http_upstream_t));
  433.     if (u == NULL) {
  434.         return NGX_ERROR;
  435.     }

  436.     r->upstream = u;

  437.     u->peer.log = r->connection->log;
  438.     u->peer.log_error = NGX_ERROR_ERR;

  439. #if (NGX_HTTP_CACHE)
  440.     r->cache = NULL;
  441. #endif

  442.     u->headers_in.content_length_n = -1;
  443.     u->headers_in.last_modified_time = -1;

  444.     return NGX_OK;
  445. }


  446. void
  447. ngx_http_upstream_init(ngx_http_request_t *r)
  448. {
  449.     ngx_connection_t     *c;

  450.     c = r->connection;

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

  453. #if (NGX_HTTP_V2)
  454.     if (r->stream) {
  455.         ngx_http_upstream_init_request(r);
  456.         return;
  457.     }
  458. #endif

  459. #if (NGX_HTTP_V3)
  460.     if (c->quic) {
  461.         ngx_http_upstream_init_request(r);
  462.         return;
  463.     }
  464. #endif

  465.     if (c->read->timer_set) {
  466.         ngx_del_timer(c->read);
  467.     }

  468.     if (ngx_event_flags & NGX_USE_CLEAR_EVENT) {

  469.         if (!c->write->active) {
  470.             if (ngx_add_event(c->write, NGX_WRITE_EVENT, NGX_CLEAR_EVENT)
  471.                 == NGX_ERROR)
  472.             {
  473.                 ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  474.                 return;
  475.             }
  476.         }
  477.     }

  478.     ngx_http_upstream_init_request(r);
  479. }


  480. static void
  481. ngx_http_upstream_init_request(ngx_http_request_t *r)
  482. {
  483.     ngx_str_t                      *host;
  484.     ngx_uint_t                      i;
  485.     ngx_resolver_ctx_t             *ctx, temp;
  486.     ngx_http_cleanup_t             *cln;
  487.     ngx_http_upstream_t            *u;
  488.     ngx_http_core_loc_conf_t       *clcf;
  489.     ngx_http_upstream_srv_conf_t   *uscf, **uscfp;
  490.     ngx_http_upstream_main_conf_t  *umcf;

  491.     if (r->aio) {
  492.         return;
  493.     }

  494.     u = r->upstream;

  495. #if (NGX_HTTP_CACHE)

  496.     if (u->conf->cache) {
  497.         ngx_int_t  rc;

  498.         rc = ngx_http_upstream_cache(r, u);

  499.         if (rc == NGX_BUSY) {
  500.             r->write_event_handler = ngx_http_upstream_init_request;
  501.             return;
  502.         }

  503.         r->write_event_handler = ngx_http_request_empty_handler;

  504.         if (rc == NGX_ERROR) {
  505.             ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  506.             return;
  507.         }

  508.         if (rc == NGX_OK) {
  509.             rc = ngx_http_upstream_cache_send(r, u);

  510.             if (rc == NGX_DONE) {
  511.                 return;
  512.             }

  513.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  514.                 rc = NGX_DECLINED;
  515.                 r->cached = 0;
  516.                 u->buffer.start = NULL;
  517.                 u->cache_status = NGX_HTTP_CACHE_MISS;
  518.                 u->request_sent = 1;
  519.             }
  520.         }

  521.         if (rc != NGX_DECLINED) {
  522.             ngx_http_finalize_request(r, rc);
  523.             return;
  524.         }
  525.     }

  526. #endif

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

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

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

  531.         } else {
  532.             if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {
  533.                 ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  534.                 return;
  535.             }
  536.         }

  537.         r->read_event_handler = ngx_http_upstream_rd_check_broken_connection;
  538.         r->write_event_handler = ngx_http_upstream_wr_check_broken_connection;
  539.     }

  540.     if (r->request_body) {
  541.         u->request_bufs = r->request_body->bufs;
  542.     }

  543.     if (u->create_request(r) != NGX_OK) {
  544.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  545.         return;
  546.     }

  547.     if (ngx_http_upstream_set_local(r, u, u->conf->local) != NGX_OK) {
  548.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  549.         return;
  550.     }

  551.     if (u->conf->socket_keepalive) {
  552.         u->peer.so_keepalive = 1;
  553.     }

  554.     if (u->conf->socket_rcvbuf) {
  555.         u->peer.rcvbuf = (int) u->conf->socket_rcvbuf;
  556.     }

  557.     if (u->conf->socket_sndbuf) {
  558.         u->peer.sndbuf = (int) u->conf->socket_sndbuf;
  559.     }

  560.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  561.     u->output.alignment = clcf->directio_alignment;
  562.     u->output.pool = r->pool;
  563.     u->output.bufs.num = 1;
  564.     u->output.bufs.size = clcf->client_body_buffer_size;

  565.     if (u->output.output_filter == NULL) {
  566.         u->output.output_filter = ngx_chain_writer;
  567.         u->output.filter_ctx = &u->writer;
  568.     }

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

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

  571.         r->upstream_states = ngx_array_create(r->pool, 1,
  572.                                             sizeof(ngx_http_upstream_state_t));
  573.         if (r->upstream_states == NULL) {
  574.             ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  575.             return;
  576.         }

  577.     } else {

  578.         u->state = ngx_array_push(r->upstream_states);
  579.         if (u->state == NULL) {
  580.             ngx_http_upstream_finalize_request(r, u,
  581.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  582.             return;
  583.         }

  584.         ngx_memzero(u->state, sizeof(ngx_http_upstream_state_t));
  585.     }

  586.     cln = ngx_http_cleanup_add(r, 0);
  587.     if (cln == NULL) {
  588.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  589.         return;
  590.     }

  591.     cln->handler = ngx_http_upstream_cleanup;
  592.     cln->data = r;
  593.     u->cleanup = &cln->handler;

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

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

  596.     } else {

  597. #if (NGX_HTTP_SSL)
  598.         u->ssl_name = u->resolved->host;
  599. #endif

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

  601.         umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);

  602.         uscfp = umcf->upstreams.elts;

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

  604.             uscf = uscfp[i];

  605.             if (uscf->host.len == host->len
  606.                 && ((uscf->port == 0 && u->resolved->no_port)
  607.                      || uscf->port == u->resolved->port)
  608.                 && ngx_strncasecmp(uscf->host.data, host->data, host->len) == 0)
  609.             {
  610.                 goto found;
  611.             }
  612.         }

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

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

  623.             if (ngx_http_upstream_create_round_robin_peer(r, u->resolved)
  624.                 != NGX_OK)
  625.             {
  626.                 ngx_http_upstream_finalize_request(r, u,
  627.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  628.                 return;
  629.             }

  630.             ngx_http_upstream_connect(r, u);

  631.             return;
  632.         }

  633.         if (u->resolved->port == 0) {
  634.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  635.                           "no port in upstream \"%V\"", host);
  636.             ngx_http_upstream_finalize_request(r, u,
  637.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  638.             return;
  639.         }

  640.         temp.name = *host;

  641.         ctx = ngx_resolve_start(clcf->resolver, &temp);
  642.         if (ctx == NULL) {
  643.             ngx_http_upstream_finalize_request(r, u,
  644.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  645.             return;
  646.         }

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

  650.             ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  651.             return;
  652.         }

  653.         ctx->name = *host;
  654.         ctx->handler = ngx_http_upstream_resolve_handler;
  655.         ctx->data = r;
  656.         ctx->timeout = clcf->resolver_timeout;

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

  658.         if (ngx_resolve_name(ctx) != NGX_OK) {
  659.             u->resolved->ctx = NULL;
  660.             ngx_http_upstream_finalize_request(r, u,
  661.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  662.             return;
  663.         }

  664.         return;
  665.     }

  666. found:

  667.     if (uscf == NULL) {
  668.         ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0,
  669.                       "no upstream configuration");
  670.         ngx_http_upstream_finalize_request(r, u,
  671.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  672.         return;
  673.     }

  674.     u->upstream = uscf;

  675. #if (NGX_HTTP_SSL)
  676.     u->ssl_name = uscf->host;
  677. #endif

  678.     if (uscf->peer.init(r, uscf) != NGX_OK) {
  679.         ngx_http_upstream_finalize_request(r, u,
  680.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  681.         return;
  682.     }

  683.     u->peer.start_time = ngx_current_msec;

  684.     if (u->conf->next_upstream_tries
  685.         && u->peer.tries > u->conf->next_upstream_tries)
  686.     {
  687.         u->peer.tries = u->conf->next_upstream_tries;
  688.     }

  689.     ngx_http_upstream_connect(r, u);
  690. }


  691. #if (NGX_HTTP_CACHE)

  692. static ngx_int_t
  693. ngx_http_upstream_cache(ngx_http_request_t *r, ngx_http_upstream_t *u)
  694. {
  695.     ngx_int_t               rc;
  696.     ngx_http_cache_t       *c;
  697.     ngx_http_file_cache_t  *cache;

  698.     c = r->cache;

  699.     if (c == NULL) {

  700.         if (!(r->method & u->conf->cache_methods)) {
  701.             return NGX_DECLINED;
  702.         }

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

  704.         if (rc != NGX_OK) {
  705.             return rc;
  706.         }

  707.         if (r->method == NGX_HTTP_HEAD && u->conf->cache_convert_head) {
  708.             u->method = ngx_http_core_get_method;
  709.         }

  710.         if (ngx_http_file_cache_new(r) != NGX_OK) {
  711.             return NGX_ERROR;
  712.         }

  713.         if (u->create_key(r) != NGX_OK) {
  714.             return NGX_ERROR;
  715.         }

  716.         /* TODO: add keys */

  717.         ngx_http_file_cache_create_key(r);

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

  724.             r->cache = NULL;
  725.             return NGX_DECLINED;
  726.         }

  727.         u->cacheable = 1;

  728.         c = r->cache;

  729.         c->body_start = u->conf->buffer_size;
  730.         c->min_uses = u->conf->cache_min_uses;
  731.         c->file_cache = cache;

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

  733.         case NGX_ERROR:
  734.             return NGX_ERROR;

  735.         case NGX_DECLINED:
  736.             u->cache_status = NGX_HTTP_CACHE_BYPASS;
  737.             return NGX_DECLINED;

  738.         default: /* NGX_OK */
  739.             break;
  740.         }

  741.         c->lock = u->conf->cache_lock;
  742.         c->lock_timeout = u->conf->cache_lock_timeout;
  743.         c->lock_age = u->conf->cache_lock_age;

  744.         u->cache_status = NGX_HTTP_CACHE_MISS;
  745.     }

  746.     rc = ngx_http_file_cache_open(r);

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

  749.     switch (rc) {

  750.     case NGX_HTTP_CACHE_STALE:

  751.         if (((u->conf->cache_use_stale & NGX_HTTP_UPSTREAM_FT_UPDATING)
  752.              || c->stale_updating) && !r->background
  753.             && u->conf->cache_background_update)
  754.         {
  755.             if (ngx_http_upstream_cache_background_update(r, u) == NGX_OK) {
  756.                 r->cache->background = 1;
  757.                 u->cache_status = rc;
  758.                 rc = NGX_OK;

  759.             } else {
  760.                 rc = NGX_ERROR;
  761.             }
  762.         }

  763.         break;

  764.     case NGX_HTTP_CACHE_UPDATING:

  765.         if (((u->conf->cache_use_stale & NGX_HTTP_UPSTREAM_FT_UPDATING)
  766.              || c->stale_updating) && !r->background)
  767.         {
  768.             u->cache_status = rc;
  769.             rc = NGX_OK;

  770.         } else {
  771.             rc = NGX_HTTP_CACHE_STALE;
  772.         }

  773.         break;

  774.     case NGX_OK:
  775.         u->cache_status = NGX_HTTP_CACHE_HIT;
  776.     }

  777.     switch (rc) {

  778.     case NGX_OK:

  779.         return NGX_OK;

  780.     case NGX_HTTP_CACHE_STALE:

  781.         c->valid_sec = 0;
  782.         c->updating_sec = 0;
  783.         c->error_sec = 0;

  784.         u->buffer.start = NULL;
  785.         u->cache_status = NGX_HTTP_CACHE_EXPIRED;

  786.         break;

  787.     case NGX_DECLINED:

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

  790.         } else {
  791.             u->buffer.pos = u->buffer.start + c->header_start;
  792.             u->buffer.last = u->buffer.pos;
  793.         }

  794.         break;

  795.     case NGX_HTTP_CACHE_SCARCE:

  796.         u->cacheable = 0;

  797.         break;

  798.     case NGX_AGAIN:

  799.         return NGX_BUSY;

  800.     case NGX_ERROR:

  801.         return NGX_ERROR;

  802.     default:

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

  804.         u->cache_status = NGX_HTTP_CACHE_HIT;

  805.         return rc;
  806.     }

  807.     if (ngx_http_upstream_cache_check_range(r, u) == NGX_DECLINED) {
  808.         u->cacheable = 0;
  809.     }

  810.     r->cached = 0;

  811.     return NGX_DECLINED;
  812. }


  813. static ngx_int_t
  814. ngx_http_upstream_cache_get(ngx_http_request_t *r, ngx_http_upstream_t *u,
  815.     ngx_http_file_cache_t **cache)
  816. {
  817.     ngx_str_t               *name, val;
  818.     ngx_uint_t               i;
  819.     ngx_http_file_cache_t  **caches;

  820.     if (u->conf->cache_zone) {
  821.         *cache = u->conf->cache_zone->data;
  822.         return NGX_OK;
  823.     }

  824.     if (ngx_http_complex_value(r, u->conf->cache_value, &val) != NGX_OK) {
  825.         return NGX_ERROR;
  826.     }

  827.     if (val.len == 0
  828.         || (val.len == 3 && ngx_strncmp(val.data, "off", 3) == 0))
  829.     {
  830.         return NGX_DECLINED;
  831.     }

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

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

  835.         if (name->len == val.len
  836.             && ngx_strncmp(name->data, val.data, val.len) == 0)
  837.         {
  838.             *cache = caches[i];
  839.             return NGX_OK;
  840.         }
  841.     }

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

  844.     return NGX_ERROR;
  845. }


  846. static ngx_int_t
  847. ngx_http_upstream_cache_send(ngx_http_request_t *r, ngx_http_upstream_t *u)
  848. {
  849.     ngx_int_t          rc;
  850.     ngx_http_cache_t  *c;

  851.     r->cached = 1;
  852.     c = r->cache;

  853.     if (c->header_start == c->body_start) {
  854.         r->http_version = NGX_HTTP_VERSION_9;
  855.         return ngx_http_cache_send(r);
  856.     }

  857.     /* TODO: cache stack */

  858.     u->buffer = *c->buf;
  859.     u->buffer.pos += c->header_start;

  860.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  861.     u->headers_in.content_length_n = -1;
  862.     u->headers_in.last_modified_time = -1;

  863.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  864.                       sizeof(ngx_table_elt_t))
  865.         != NGX_OK)
  866.     {
  867.         return NGX_ERROR;
  868.     }

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

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

  876.     if (rc == NGX_OK) {

  877.         if (ngx_http_upstream_process_headers(r, u) != NGX_OK) {
  878.             return NGX_DONE;
  879.         }

  880.         return ngx_http_cache_send(r);
  881.     }

  882.     if (rc == NGX_ERROR) {
  883.         return NGX_ERROR;
  884.     }

  885.     if (rc == NGX_AGAIN || rc == NGX_HTTP_UPSTREAM_EARLY_HINTS) {
  886.         rc = NGX_HTTP_UPSTREAM_INVALID_HEADER;
  887.     }

  888.     /* rc == NGX_HTTP_UPSTREAM_INVALID_HEADER */

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

  892.     /* TODO: delete file */

  893.     return rc;
  894. }


  895. static ngx_int_t
  896. ngx_http_upstream_cache_background_update(ngx_http_request_t *r,
  897.     ngx_http_upstream_t *u)
  898. {
  899.     ngx_http_request_t  *sr;

  900.     if (r == r->main) {
  901.         r->preserve_body = 1;
  902.     }

  903.     if (ngx_http_subrequest(r, &r->uri, &r->args, &sr, NULL,
  904.                             NGX_HTTP_SUBREQUEST_CLONE
  905.                             |NGX_HTTP_SUBREQUEST_BACKGROUND)
  906.         != NGX_OK)
  907.     {
  908.         return NGX_ERROR;
  909.     }

  910.     sr->header_only = 1;

  911.     return NGX_OK;
  912. }


  913. static ngx_int_t
  914. ngx_http_upstream_cache_check_range(ngx_http_request_t *r,
  915.     ngx_http_upstream_t *u)
  916. {
  917.     off_t             offset;
  918.     u_char           *p, *start;
  919.     ngx_table_elt_t  *h;

  920.     h = r->headers_in.range;

  921.     if (h == NULL
  922.         || !u->cacheable
  923.         || u->conf->cache_max_range_offset == NGX_MAX_OFF_T_VALUE)
  924.     {
  925.         return NGX_OK;
  926.     }

  927.     if (u->conf->cache_max_range_offset == 0) {
  928.         return NGX_DECLINED;
  929.     }

  930.     if (h->value.len < 7
  931.         || ngx_strncasecmp(h->value.data, (u_char *) "bytes=", 6) != 0)
  932.     {
  933.         return NGX_OK;
  934.     }

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

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

  937.     if (*p == '-') {
  938.         return NGX_DECLINED;
  939.     }

  940.     start = p;

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

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

  943.     if (offset >= u->conf->cache_max_range_offset) {
  944.         return NGX_DECLINED;
  945.     }

  946.     return NGX_OK;
  947. }

  948. #endif


  949. static void
  950. ngx_http_upstream_resolve_handler(ngx_resolver_ctx_t *ctx)
  951. {
  952.     ngx_uint_t                     run_posted;
  953.     ngx_connection_t              *c;
  954.     ngx_http_request_t            *r;
  955.     ngx_http_upstream_t           *u;
  956.     ngx_http_upstream_resolved_t  *ur;

  957.     run_posted = ctx->async;

  958.     r = ctx->data;
  959.     c = r->connection;

  960.     u = r->upstream;
  961.     ur = u->resolved;

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

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

  965.     if (ctx->state) {
  966.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  967.                       "%V could not be resolved (%i: %s)",
  968.                       &ctx->name, ctx->state,
  969.                       ngx_resolver_strerror(ctx->state));

  970.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  971.         goto failed;
  972.     }

  973.     ur->naddrs = ctx->naddrs;
  974.     ur->addrs = ctx->addrs;

  975. #if (NGX_DEBUG)
  976.     {
  977.     u_char      text[NGX_SOCKADDR_STRLEN];
  978.     ngx_str_t   addr;
  979.     ngx_uint_t  i;

  980.     addr.data = text;

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

  984.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  985.                        "name was resolved to %V", &addr);
  986.     }
  987.     }
  988. #endif

  989.     if (ngx_http_upstream_create_round_robin_peer(r, ur) != NGX_OK) {
  990.         ngx_http_upstream_finalize_request(r, u,
  991.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  992.         goto failed;
  993.     }

  994.     ngx_resolve_name_done(ctx);
  995.     ur->ctx = NULL;

  996.     u->peer.start_time = ngx_current_msec;

  997.     if (u->conf->next_upstream_tries
  998.         && u->peer.tries > u->conf->next_upstream_tries)
  999.     {
  1000.         u->peer.tries = u->conf->next_upstream_tries;
  1001.     }

  1002.     ngx_http_upstream_connect(r, u);

  1003. failed:

  1004.     if (run_posted) {
  1005.         ngx_http_run_posted_requests(c);
  1006.     }
  1007. }


  1008. static void
  1009. ngx_http_upstream_handler(ngx_event_t *ev)
  1010. {
  1011.     ngx_connection_t     *c;
  1012.     ngx_http_request_t   *r;
  1013.     ngx_http_upstream_t  *u;

  1014.     c = ev->data;
  1015.     r = c->data;

  1016.     u = r->upstream;
  1017.     c = r->connection;

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

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

  1021.     if (ev->delayed && ev->timedout) {
  1022.         ev->delayed = 0;
  1023.         ev->timedout = 0;
  1024.     }

  1025.     if (ev->write) {
  1026.         u->write_event_handler(r, u);

  1027.     } else {
  1028.         u->read_event_handler(r, u);
  1029.     }

  1030.     ngx_http_run_posted_requests(c);
  1031. }


  1032. static void
  1033. ngx_http_upstream_rd_check_broken_connection(ngx_http_request_t *r)
  1034. {
  1035.     ngx_http_upstream_check_broken_connection(r, r->connection->read);
  1036. }


  1037. static void
  1038. ngx_http_upstream_wr_check_broken_connection(ngx_http_request_t *r)
  1039. {
  1040.     ngx_http_upstream_check_broken_connection(r, r->connection->write);
  1041. }


  1042. static void
  1043. ngx_http_upstream_check_broken_connection(ngx_http_request_t *r,
  1044.     ngx_event_t *ev)
  1045. {
  1046.     int                  n;
  1047.     char                 buf[1];
  1048.     ngx_err_t            err;
  1049.     ngx_int_t            event;
  1050.     ngx_connection_t     *c;
  1051.     ngx_http_upstream_t  *u;

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

  1055.     c = r->connection;
  1056.     u = r->upstream;

  1057.     if (c->error) {
  1058.         if ((ngx_event_flags & NGX_USE_LEVEL_EVENT) && ev->active) {

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

  1060.             if (ngx_del_event(ev, event, 0) != NGX_OK) {
  1061.                 ngx_http_upstream_finalize_request(r, u,
  1062.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1063.                 return;
  1064.             }
  1065.         }

  1066.         if (!u->cacheable) {
  1067.             ngx_http_upstream_finalize_request(r, u,
  1068.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1069.         }

  1070.         return;
  1071.     }

  1072. #if (NGX_HTTP_V2)
  1073.     if (r->stream) {
  1074.         return;
  1075.     }
  1076. #endif

  1077. #if (NGX_HTTP_V3)

  1078.     if (c->quic) {
  1079.         if (c->write->error) {
  1080.             ngx_http_upstream_finalize_request(r, u,
  1081.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1082.         }

  1083.         return;
  1084.     }

  1085. #endif

  1086. #if (NGX_HAVE_KQUEUE)

  1087.     if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) {

  1088.         if (!ev->pending_eof) {
  1089.             return;
  1090.         }

  1091.         ev->eof = 1;
  1092.         c->error = 1;

  1093.         if (ev->kq_errno) {
  1094.             ev->error = 1;
  1095.         }

  1096.         if (!u->cacheable && u->peer.connection) {
  1097.             ngx_log_error(NGX_LOG_INFO, ev->log, ev->kq_errno,
  1098.                           "kevent() reported that client prematurely closed "
  1099.                           "connection, so upstream connection is closed too");
  1100.             ngx_http_upstream_finalize_request(r, u,
  1101.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1102.             return;
  1103.         }

  1104.         ngx_log_error(NGX_LOG_INFO, ev->log, ev->kq_errno,
  1105.                       "kevent() reported that client prematurely closed "
  1106.                       "connection");

  1107.         if (u->peer.connection == NULL) {
  1108.             ngx_http_upstream_finalize_request(r, u,
  1109.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1110.         }

  1111.         return;
  1112.     }

  1113. #endif

  1114. #if (NGX_HAVE_EPOLLRDHUP)

  1115.     if ((ngx_event_flags & NGX_USE_EPOLL_EVENT) && ngx_use_epoll_rdhup) {
  1116.         socklen_t  len;

  1117.         if (!ev->pending_eof) {
  1118.             return;
  1119.         }

  1120.         ev->eof = 1;
  1121.         c->error = 1;

  1122.         err = 0;
  1123.         len = sizeof(ngx_err_t);

  1124.         /*
  1125.          * BSDs and Linux return 0 and set a pending error in err
  1126.          * Solaris returns -1 and sets errno
  1127.          */

  1128.         if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, (void *) &err, &len)
  1129.             == -1)
  1130.         {
  1131.             err = ngx_socket_errno;
  1132.         }

  1133.         if (err) {
  1134.             ev->error = 1;
  1135.         }

  1136.         if (!u->cacheable && u->peer.connection) {
  1137.             ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1138.                         "epoll_wait() reported that client prematurely closed "
  1139.                         "connection, so upstream connection is closed too");
  1140.             ngx_http_upstream_finalize_request(r, u,
  1141.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1142.             return;
  1143.         }

  1144.         ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1145.                       "epoll_wait() reported that client prematurely closed "
  1146.                       "connection");

  1147.         if (u->peer.connection == NULL) {
  1148.             ngx_http_upstream_finalize_request(r, u,
  1149.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1150.         }

  1151.         return;
  1152.     }

  1153. #endif

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

  1155.     err = ngx_socket_errno;

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

  1158.     if (ev->write && (n >= 0 || err == NGX_EAGAIN)) {
  1159.         return;
  1160.     }

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

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

  1163.         if (ngx_del_event(ev, event, 0) != NGX_OK) {
  1164.             ngx_http_upstream_finalize_request(r, u,
  1165.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1166.             return;
  1167.         }
  1168.     }

  1169.     if (n > 0) {
  1170.         return;
  1171.     }

  1172.     if (n == -1) {
  1173.         if (err == NGX_EAGAIN) {
  1174.             return;
  1175.         }

  1176.         ev->error = 1;

  1177.     } else { /* n == 0 */
  1178.         err = 0;
  1179.     }

  1180.     ev->eof = 1;
  1181.     c->error = 1;

  1182.     if (!u->cacheable && u->peer.connection) {
  1183.         ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1184.                       "client prematurely closed connection, "
  1185.                       "so upstream connection is closed too");
  1186.         ngx_http_upstream_finalize_request(r, u,
  1187.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1188.         return;
  1189.     }

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

  1192.     if (u->peer.connection == NULL) {
  1193.         ngx_http_upstream_finalize_request(r, u,
  1194.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1195.     }
  1196. }


  1197. static void
  1198. ngx_http_upstream_connect(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1199. {
  1200.     ngx_int_t                  rc;
  1201.     ngx_connection_t          *c;
  1202.     ngx_http_core_loc_conf_t  *clcf;

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

  1204.     if (u->state && u->state->response_time == (ngx_msec_t) -1) {
  1205.         u->state->response_time = ngx_current_msec - u->start_time;
  1206.     }

  1207.     u->state = ngx_array_push(r->upstream_states);
  1208.     if (u->state == NULL) {
  1209.         ngx_http_upstream_finalize_request(r, u,
  1210.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1211.         return;
  1212.     }

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

  1214.     u->start_time = ngx_current_msec;

  1215.     u->state->response_time = (ngx_msec_t) -1;
  1216.     u->state->connect_time = (ngx_msec_t) -1;
  1217.     u->state->header_time = (ngx_msec_t) -1;

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

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

  1221.     if (rc == NGX_ERROR) {
  1222.         ngx_http_upstream_finalize_request(r, u,
  1223.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1224.         return;
  1225.     }

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

  1227. #if (NGX_HTTP_UPSTREAM_ZONE)
  1228.     if (u->upstream && u->upstream->shm_zone
  1229.         && (u->upstream->flags & NGX_HTTP_UPSTREAM_MODIFY))
  1230.     {
  1231.         u->state->peer = ngx_palloc(r->pool,
  1232.                                     sizeof(ngx_str_t) + u->peer.name->len);
  1233.         if (u->state->peer == NULL) {
  1234.             ngx_http_upstream_finalize_request(r, u,
  1235.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1236.             return;
  1237.         }

  1238.         u->state->peer->len = u->peer.name->len;
  1239.         u->state->peer->data = (u_char *) (u->state->peer + 1);
  1240.         ngx_memcpy(u->state->peer->data, u->peer.name->data, u->peer.name->len);

  1241.         u->peer.name = u->state->peer;
  1242.     }
  1243. #endif

  1244.     if (rc == NGX_BUSY) {
  1245.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "no live upstreams");
  1246.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_NOLIVE);
  1247.         return;
  1248.     }

  1249.     if (rc == NGX_DECLINED) {
  1250.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1251.         return;
  1252.     }

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

  1254.     c = u->peer.connection;

  1255.     c->requests++;

  1256.     c->data = r;

  1257.     c->write->handler = ngx_http_upstream_handler;
  1258.     c->read->handler = ngx_http_upstream_handler;

  1259.     u->write_event_handler = ngx_http_upstream_send_request_handler;
  1260.     u->read_event_handler = ngx_http_upstream_process_header;

  1261.     c->sendfile &= r->connection->sendfile;
  1262.     u->output.sendfile = c->sendfile;

  1263.     if (r->connection->tcp_nopush == NGX_TCP_NOPUSH_DISABLED) {
  1264.         c->tcp_nopush = NGX_TCP_NOPUSH_DISABLED;
  1265.     }

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

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

  1268.         c->pool = ngx_create_pool(128, r->connection->log);
  1269.         if (c->pool == NULL) {
  1270.             ngx_http_upstream_finalize_request(r, u,
  1271.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1272.             return;
  1273.         }
  1274.     }

  1275.     c->log = r->connection->log;
  1276.     c->pool->log = c->log;
  1277.     c->read->log = c->log;
  1278.     c->write->log = c->log;

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

  1280.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  1281.     u->writer.out = NULL;
  1282.     u->writer.last = &u->writer.out;
  1283.     u->writer.connection = c;
  1284.     u->writer.limit = clcf->sendfile_max_chunk;

  1285.     if (u->request_sent || u->response_received) {
  1286.         if (ngx_http_upstream_reinit(r, u) != NGX_OK) {
  1287.             ngx_http_upstream_finalize_request(r, u,
  1288.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1289.             return;
  1290.         }
  1291.     }

  1292.     if (r->request_body
  1293.         && r->request_body->buf
  1294.         && r->request_body->temp_file
  1295.         && r == r->main)
  1296.     {
  1297.         /*
  1298.          * the r->request_body->buf can be reused for one request only,
  1299.          * the subrequests should allocate their own temporary bufs
  1300.          */

  1301.         u->output.free = ngx_alloc_chain_link(r->pool);
  1302.         if (u->output.free == NULL) {
  1303.             ngx_http_upstream_finalize_request(r, u,
  1304.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1305.             return;
  1306.         }

  1307.         u->output.free->buf = r->request_body->buf;
  1308.         u->output.free->next = NULL;
  1309.         u->output.allocated = 1;

  1310.         r->request_body->buf->pos = r->request_body->buf->start;
  1311.         r->request_body->buf->last = r->request_body->buf->start;
  1312.         r->request_body->buf->tag = u->output.tag;
  1313.     }

  1314.     u->request_sent = 0;
  1315.     u->request_body_sent = 0;
  1316.     u->request_body_blocked = 0;
  1317.     u->response_received = 0;

  1318.     if (rc == NGX_AGAIN) {
  1319.         ngx_add_timer(c->write, u->conf->connect_timeout);
  1320.         return;
  1321.     }

  1322. #if (NGX_HTTP_SSL)

  1323.     if (u->ssl && c->ssl == NULL) {
  1324.         ngx_http_upstream_ssl_init_connection(r, u, c);
  1325.         return;
  1326.     }

  1327. #endif

  1328.     ngx_http_upstream_send_request(r, u, 1);
  1329. }


  1330. #if (NGX_HTTP_SSL)

  1331. static void
  1332. ngx_http_upstream_ssl_init_connection(ngx_http_request_t *r,
  1333.     ngx_http_upstream_t *u, ngx_connection_t *c)
  1334. {
  1335.     ngx_int_t                  rc;
  1336.     ngx_http_core_loc_conf_t  *clcf;

  1337.     if (ngx_http_upstream_test_connect(c) != NGX_OK) {
  1338.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1339.         return;
  1340.     }

  1341.     if (ngx_ssl_create_connection(u->conf->ssl, c,
  1342.                                   NGX_SSL_BUFFER|NGX_SSL_CLIENT)
  1343.         != NGX_OK)
  1344.     {
  1345.         ngx_http_upstream_finalize_request(r, u,
  1346.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1347.         return;
  1348.     }

  1349.     if (u->conf->ssl_server_name || u->conf->ssl_verify) {
  1350.         if (ngx_http_upstream_ssl_name(r, u, c) != NGX_OK) {
  1351.             ngx_http_upstream_finalize_request(r, u,
  1352.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1353.             return;
  1354.         }
  1355.     }

  1356.     if (u->conf->ssl_certificate
  1357.         && u->conf->ssl_certificate->value.len
  1358.         && (u->conf->ssl_certificate->lengths
  1359.             || u->conf->ssl_certificate_key->lengths))
  1360.     {
  1361.         if (ngx_http_upstream_ssl_certificate(r, u, c) != NGX_OK) {
  1362.             ngx_http_upstream_finalize_request(r, u,
  1363.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1364.             return;
  1365.         }
  1366.     }

  1367. #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation

  1368.     if (u->ssl_alpn_protocol.len) {
  1369.         if (SSL_set_alpn_protos(c->ssl->connection, u->ssl_alpn_protocol.data,
  1370.                                 u->ssl_alpn_protocol.len)
  1371.             != 0)
  1372.         {
  1373.             ngx_ssl_error(NGX_LOG_ERR, c->log, 0,
  1374.                           "SSL_set_alpn_protos() failed");
  1375.             ngx_http_upstream_finalize_request(r, u,
  1376.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1377.             return;
  1378.         }
  1379.     }

  1380. #endif

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

  1383.         if (u->peer.set_session(&u->peer, u->peer.data) != NGX_OK) {
  1384.             ngx_http_upstream_finalize_request(r, u,
  1385.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1386.             return;
  1387.         }

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

  1389.         clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  1390.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  1391.             ngx_http_upstream_finalize_request(r, u,
  1392.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1393.             return;
  1394.         }
  1395.     }

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

  1397.     rc = ngx_ssl_handshake(c);

  1398.     if (rc == NGX_AGAIN) {

  1399.         if (!c->write->timer_set) {
  1400.             ngx_add_timer(c->write, u->conf->connect_timeout);
  1401.         }

  1402.         c->ssl->handler = ngx_http_upstream_ssl_handshake_handler;
  1403.         return;
  1404.     }

  1405.     ngx_http_upstream_ssl_handshake(r, u, c);
  1406. }


  1407. static void
  1408. ngx_http_upstream_ssl_handshake_handler(ngx_connection_t *c)
  1409. {
  1410.     ngx_http_request_t   *r;
  1411.     ngx_http_upstream_t  *u;

  1412.     r = c->data;

  1413.     u = r->upstream;
  1414.     c = r->connection;

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

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

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

  1420.     ngx_http_run_posted_requests(c);
  1421. }


  1422. static void
  1423. ngx_http_upstream_ssl_handshake(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1424.     ngx_connection_t *c)
  1425. {
  1426.     long  rc;

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

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

  1430.             if (rc != X509_V_OK) {
  1431.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1432.                               "upstream SSL certificate verify error: (%l:%s)",
  1433.                               rc, X509_verify_cert_error_string(rc));
  1434.                 goto failed;
  1435.             }

  1436.             if (ngx_ssl_check_host(c, &u->ssl_name) != NGX_OK) {
  1437.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1438.                               "upstream SSL certificate does not match \"%V\"",
  1439.                               &u->ssl_name);
  1440.                 goto failed;
  1441.             }
  1442.         }

  1443.         if (!c->ssl->sendfile) {
  1444.             c->sendfile = 0;
  1445.             u->output.sendfile = 0;
  1446.         }

  1447.         c->write->handler = ngx_http_upstream_handler;
  1448.         c->read->handler = ngx_http_upstream_handler;

  1449.         ngx_http_upstream_send_request(r, u, 1);

  1450.         return;
  1451.     }

  1452.     if (c->write->timedout) {
  1453.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1454.         return;
  1455.     }

  1456. failed:

  1457.     ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1458. }


  1459. static void
  1460. ngx_http_upstream_ssl_save_session(ngx_connection_t *c)
  1461. {
  1462.     ngx_http_request_t   *r;
  1463.     ngx_http_upstream_t  *u;

  1464.     if (c->idle) {
  1465.         return;
  1466.     }

  1467.     r = c->data;

  1468.     u = r->upstream;
  1469.     c = r->connection;

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

  1471.     u->peer.save_session(&u->peer, u->peer.data);
  1472. }


  1473. static ngx_int_t
  1474. ngx_http_upstream_ssl_name(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1475.     ngx_connection_t *c)
  1476. {
  1477.     u_char     *p, *last;
  1478.     ngx_str_t   name;

  1479.     if (u->conf->ssl_name) {
  1480.         if (ngx_http_complex_value(r, u->conf->ssl_name, &name) != NGX_OK) {
  1481.             return NGX_ERROR;
  1482.         }

  1483.     } else {
  1484.         name = u->ssl_name;
  1485.     }

  1486.     if (name.len == 0) {
  1487.         goto done;
  1488.     }

  1489.     /*
  1490.      * ssl name here may contain port, notably if derived from $proxy_host
  1491.      * or $http_host; we have to strip it
  1492.      */

  1493.     p = name.data;
  1494.     last = name.data + name.len;

  1495.     if (*p == '[') {
  1496.         p = ngx_strlchr(p, last, ']');

  1497.         if (p == NULL) {
  1498.             p = name.data;
  1499.         }
  1500.     }

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

  1502.     if (p != NULL) {
  1503.         name.len = p - name.data;
  1504.     }

  1505.     if (!u->conf->ssl_server_name) {
  1506.         goto done;
  1507.     }

  1508. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME

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

  1510.     if (name.len == 0 || *name.data == '[') {
  1511.         goto done;
  1512.     }

  1513.     if (ngx_inet_addr(name.data, name.len) != INADDR_NONE) {
  1514.         goto done;
  1515.     }

  1516.     /*
  1517.      * SSL_set_tlsext_host_name() needs a null-terminated string,
  1518.      * hence we explicitly null-terminate name here
  1519.      */

  1520.     p = ngx_pnalloc(r->pool, name.len + 1);
  1521.     if (p == NULL) {
  1522.         return NGX_ERROR;
  1523.     }

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

  1525.     name.data = p;

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

  1528.     if (SSL_set_tlsext_host_name(c->ssl->connection,
  1529.                                  (char *) name.data)
  1530.         == 0)
  1531.     {
  1532.         ngx_ssl_error(NGX_LOG_ERR, r->connection->log, 0,
  1533.                       "SSL_set_tlsext_host_name(\"%s\") failed", name.data);
  1534.         return NGX_ERROR;
  1535.     }

  1536. #endif

  1537. done:

  1538.     u->ssl_name = name;

  1539.     return NGX_OK;
  1540. }


  1541. static ngx_int_t
  1542. ngx_http_upstream_ssl_certificate(ngx_http_request_t *r,
  1543.     ngx_http_upstream_t *u, ngx_connection_t *c)
  1544. {
  1545.     ngx_str_t  cert, key;

  1546.     if (ngx_http_complex_value(r, u->conf->ssl_certificate, &cert)
  1547.         != NGX_OK)
  1548.     {
  1549.         return NGX_ERROR;
  1550.     }

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

  1553.     if (*cert.data == '\0') {
  1554.         return NGX_OK;
  1555.     }

  1556.     if (ngx_http_complex_value(r, u->conf->ssl_certificate_key, &key)
  1557.         != NGX_OK)
  1558.     {
  1559.         return NGX_ERROR;
  1560.     }

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

  1563.     if (ngx_ssl_connection_certificate(c, r->pool, &cert, &key,
  1564.                                        u->conf->ssl_certificate_cache,
  1565.                                        u->conf->ssl_passwords)
  1566.         != NGX_OK)
  1567.     {
  1568.         return NGX_ERROR;
  1569.     }

  1570.     return NGX_OK;
  1571. }

  1572. #endif


  1573. static ngx_int_t
  1574. ngx_http_upstream_reinit(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1575. {
  1576.     off_t         file_pos;
  1577.     ngx_chain_t  *cl;

  1578.     if (u->reinit_request(r) != NGX_OK) {
  1579.         return NGX_ERROR;
  1580.     }

  1581.     u->early_hints_length = 0;
  1582.     u->keepalive = 0;
  1583.     u->upgrade = 0;
  1584.     u->error = 0;

  1585.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  1586.     u->headers_in.content_length_n = -1;
  1587.     u->headers_in.last_modified_time = -1;

  1588.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  1589.                       sizeof(ngx_table_elt_t))
  1590.         != NGX_OK)
  1591.     {
  1592.         return NGX_ERROR;
  1593.     }

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

  1600.     /* reinit the request chain */

  1601.     file_pos = 0;

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

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

  1605.         if (cl->buf->in_file) {
  1606.             cl->buf->file_pos = file_pos;
  1607.             file_pos = cl->buf->file_last;
  1608.         }
  1609.     }

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

  1611.     if (r->request_body && r->request_body->temp_file
  1612.         && r != r->main && u->output.buf)
  1613.     {
  1614.         u->output.free = ngx_alloc_chain_link(r->pool);
  1615.         if (u->output.free == NULL) {
  1616.             return NGX_ERROR;
  1617.         }

  1618.         u->output.free->buf = u->output.buf;
  1619.         u->output.free->next = NULL;

  1620.         u->output.buf->pos = u->output.buf->start;
  1621.         u->output.buf->last = u->output.buf->start;
  1622.     }

  1623.     u->output.buf = NULL;
  1624.     u->output.in = NULL;
  1625.     u->output.busy = NULL;

  1626.     /* reinit u->buffer */

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

  1628. #if (NGX_HTTP_CACHE)

  1629.     if (r->cache) {
  1630.         u->buffer.pos += r->cache->header_start;
  1631.     }

  1632. #endif

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

  1634.     return NGX_OK;
  1635. }


  1636. static void
  1637. ngx_http_upstream_send_request(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1638.     ngx_uint_t do_write)
  1639. {
  1640.     ngx_int_t          rc;
  1641.     ngx_connection_t  *c;

  1642.     c = u->peer.connection;

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

  1645.     if (u->state->connect_time == (ngx_msec_t) -1) {
  1646.         u->state->connect_time = ngx_current_msec - u->start_time;
  1647.     }

  1648.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {
  1649.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1650.         return;
  1651.     }

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

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

  1654.     if (rc == NGX_ERROR) {
  1655.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1656.         return;
  1657.     }

  1658.     if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  1659.         ngx_http_upstream_finalize_request(r, u, rc);
  1660.         return;
  1661.     }

  1662.     if (rc == NGX_AGAIN) {
  1663.         if (!c->write->ready || u->request_body_blocked) {
  1664.             ngx_add_timer(c->write, u->conf->send_timeout);

  1665.         } else if (c->write->timer_set) {
  1666.             ngx_del_timer(c->write);
  1667.         }

  1668.         if (ngx_handle_write_event(c->write, u->conf->send_lowat) != NGX_OK) {
  1669.             ngx_http_upstream_finalize_request(r, u,
  1670.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1671.             return;
  1672.         }

  1673.         if (c->write->ready && c->tcp_nopush == NGX_TCP_NOPUSH_SET) {
  1674.             if (ngx_tcp_push(c->fd) == -1) {
  1675.                 ngx_log_error(NGX_LOG_CRIT, c->log, ngx_socket_errno,
  1676.                               ngx_tcp_push_n " failed");
  1677.                 ngx_http_upstream_finalize_request(r, u,
  1678.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1679.                 return;
  1680.             }

  1681.             c->tcp_nopush = NGX_TCP_NOPUSH_UNSET;
  1682.         }

  1683.         if (c->read->ready) {
  1684.             ngx_post_event(c->read, &ngx_posted_events);
  1685.         }

  1686.         return;
  1687.     }

  1688.     /* rc == NGX_OK */

  1689.     if (c->write->timer_set) {
  1690.         ngx_del_timer(c->write);
  1691.     }

  1692.     if (c->tcp_nopush == NGX_TCP_NOPUSH_SET) {
  1693.         if (ngx_tcp_push(c->fd) == -1) {
  1694.             ngx_log_error(NGX_LOG_CRIT, c->log, ngx_socket_errno,
  1695.                           ngx_tcp_push_n " failed");
  1696.             ngx_http_upstream_finalize_request(r, u,
  1697.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1698.             return;
  1699.         }

  1700.         c->tcp_nopush = NGX_TCP_NOPUSH_UNSET;
  1701.     }

  1702.     if (!u->conf->preserve_output) {
  1703.         u->write_event_handler = ngx_http_upstream_dummy_handler;
  1704.     }

  1705.     if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  1706.         ngx_http_upstream_finalize_request(r, u,
  1707.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1708.         return;
  1709.     }

  1710.     if (!u->request_body_sent) {
  1711.         u->request_body_sent = 1;

  1712.         if (u->header_sent) {
  1713.             return;
  1714.         }

  1715.         if (u->conf->ignore_input) {
  1716.             ngx_http_upstream_process_header(r, u);
  1717.             return;
  1718.         }

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

  1720.         if (c->read->ready) {
  1721.             ngx_http_upstream_process_header(r, u);
  1722.             return;
  1723.         }
  1724.     }
  1725. }


  1726. static ngx_int_t
  1727. ngx_http_upstream_send_request_body(ngx_http_request_t *r,
  1728.     ngx_http_upstream_t *u, ngx_uint_t do_write)
  1729. {
  1730.     ngx_int_t                  rc;
  1731.     ngx_chain_t               *out, *cl, *ln;
  1732.     ngx_connection_t          *c;
  1733.     ngx_http_core_loc_conf_t  *clcf;

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

  1736.     if (!r->request_body_no_buffering) {

  1737.         /* buffered request body */

  1738.         if (!u->request_sent) {
  1739.             u->request_sent = 1;
  1740.             out = u->request_bufs;

  1741.         } else {
  1742.             out = NULL;
  1743.         }

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

  1745.         if (rc == NGX_AGAIN) {
  1746.             u->request_body_blocked = 1;

  1747.         } else {
  1748.             u->request_body_blocked = 0;
  1749.         }

  1750.         return rc;
  1751.     }

  1752.     if (!u->request_sent) {
  1753.         u->request_sent = 1;
  1754.         out = u->request_bufs;

  1755.         if (r->request_body->bufs) {
  1756.             for (cl = out; cl->next; cl = cl->next) { /* void */ }
  1757.             cl->next = r->request_body->bufs;
  1758.             r->request_body->bufs = NULL;
  1759.         }

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

  1762.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  1763.             return NGX_ERROR;
  1764.         }

  1765.         r->read_event_handler = ngx_http_upstream_read_request_handler;

  1766.     } else {
  1767.         out = NULL;
  1768.     }

  1769.     for ( ;; ) {

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

  1772.             if (rc == NGX_ERROR) {
  1773.                 return NGX_ERROR;
  1774.             }

  1775.             while (out) {
  1776.                 ln = out;
  1777.                 out = out->next;
  1778.                 ngx_free_chain(r->pool, ln);
  1779.             }

  1780.             if (rc == NGX_AGAIN) {
  1781.                 u->request_body_blocked = 1;

  1782.             } else {
  1783.                 u->request_body_blocked = 0;
  1784.             }

  1785.             if (rc == NGX_OK && !r->reading_body) {
  1786.                 break;
  1787.             }
  1788.         }

  1789.         if (r->reading_body) {
  1790.             /* read client request body */

  1791.             rc = ngx_http_read_unbuffered_request_body(r);

  1792.             if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  1793.                 return rc;
  1794.             }

  1795.             out = r->request_body->bufs;
  1796.             r->request_body->bufs = NULL;
  1797.         }

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

  1799.         if (out == NULL) {
  1800.             rc = NGX_AGAIN;
  1801.             break;
  1802.         }

  1803.         do_write = 1;
  1804.     }

  1805.     if (!r->reading_body) {
  1806.         if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {
  1807.             r->read_event_handler =
  1808.                                   ngx_http_upstream_rd_check_broken_connection;
  1809.         }
  1810.     }

  1811.     return rc;
  1812. }


  1813. static void
  1814. ngx_http_upstream_send_request_handler(ngx_http_request_t *r,
  1815.     ngx_http_upstream_t *u)
  1816. {
  1817.     ngx_connection_t  *c;

  1818.     c = u->peer.connection;

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

  1821.     if (c->write->timedout) {
  1822.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1823.         return;
  1824.     }

  1825. #if (NGX_HTTP_SSL)

  1826.     if (u->ssl && c->ssl == NULL) {
  1827.         ngx_http_upstream_ssl_init_connection(r, u, c);
  1828.         return;
  1829.     }

  1830. #endif

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

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

  1834.         return;
  1835.     }

  1836.     ngx_http_upstream_send_request(r, u, 1);
  1837. }


  1838. static void
  1839. ngx_http_upstream_read_request_handler(ngx_http_request_t *r)
  1840. {
  1841.     ngx_connection_t     *c;
  1842.     ngx_http_upstream_t  *u;

  1843.     c = r->connection;
  1844.     u = r->upstream;

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

  1847.     if (c->read->timedout) {
  1848.         c->timedout = 1;
  1849.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  1850.         return;
  1851.     }

  1852.     ngx_http_upstream_send_request(r, u, 0);
  1853. }


  1854. static void
  1855. ngx_http_upstream_process_header(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1856. {
  1857.     ssize_t            n;
  1858.     ngx_int_t          rc;
  1859.     ngx_connection_t  *c;

  1860.     c = u->peer.connection;

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

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

  1864.     if (c->read->timedout) {
  1865.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1866.         return;
  1867.     }

  1868.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {
  1869.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1870.         return;
  1871.     }

  1872.     if (u->buffer.start == NULL) {
  1873.         u->buffer.start = ngx_palloc(r->pool, u->conf->buffer_size);
  1874.         if (u->buffer.start == NULL) {
  1875.             ngx_http_upstream_finalize_request(r, u,
  1876.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1877.             return;
  1878.         }

  1879.         u->buffer.pos = u->buffer.start;
  1880.         u->buffer.last = u->buffer.start;
  1881.         u->buffer.end = u->buffer.start + u->conf->buffer_size;
  1882.         u->buffer.temporary = 1;

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

  1884.         if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  1885.                           sizeof(ngx_table_elt_t))
  1886.             != NGX_OK)
  1887.         {
  1888.             ngx_http_upstream_finalize_request(r, u,
  1889.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1890.             return;
  1891.         }

  1892.         if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  1893.                           sizeof(ngx_table_elt_t))
  1894.             != NGX_OK)
  1895.         {
  1896.             ngx_http_upstream_finalize_request(r, u,
  1897.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1898.             return;
  1899.         }

  1900. #if (NGX_HTTP_CACHE)

  1901.         if (r->cache) {
  1902.             u->buffer.pos += r->cache->header_start;
  1903.             u->buffer.last = u->buffer.pos;
  1904.         }
  1905. #endif
  1906.     }

  1907.     if (u->conf->ignore_input) {
  1908.         rc = u->process_header(r);
  1909.         goto done;
  1910.     }

  1911.     for ( ;; ) {

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

  1913.         if (n == NGX_AGAIN) {
  1914. #if 0
  1915.             ngx_add_timer(rev, u->read_timeout);
  1916. #endif

  1917.             if (ngx_handle_read_event(c->read, 0) != NGX_OK) {
  1918.                 ngx_http_upstream_finalize_request(r, u,
  1919.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1920.                 return;
  1921.             }

  1922.             return;
  1923.         }

  1924.         if (n == 0) {
  1925.             ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1926.                           "upstream prematurely closed connection");
  1927.         }

  1928.         if (n == NGX_ERROR || n == 0) {
  1929.             ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1930.             return;
  1931.         }

  1932. #if (NGX_HTTP_SSL)
  1933.         if (u->ssl && c->ssl == NULL) {
  1934.             ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1935.                           "upstream prematurely sent response");
  1936.             ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1937.             return;
  1938.         }
  1939. #endif

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

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

  1942. #if 0
  1943.         u->valid_header_in = 0;

  1944.         u->peer.cached = 0;
  1945. #endif

  1946.         u->response_received = 1;

  1947. again:

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

  1949.         if (rc == NGX_AGAIN) {

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

  1953.                 ngx_http_upstream_next(r, u,
  1954.                                        NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  1955.                 return;
  1956.             }

  1957.             continue;
  1958.         }

  1959.         if (rc == NGX_HTTP_UPSTREAM_EARLY_HINTS) {
  1960.             rc = ngx_http_upstream_process_early_hints(r, u);

  1961.             if (rc == NGX_OK) {
  1962.                 goto again;
  1963.             }
  1964.         }

  1965.         break;
  1966.     }

  1967. done:

  1968.     if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  1969.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  1970.         return;
  1971.     }

  1972.     if (rc == NGX_ERROR) {
  1973.         ngx_http_upstream_finalize_request(r, u,
  1974.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1975.         return;
  1976.     }

  1977.     /* rc == NGX_OK */

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

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

  1980.         if (ngx_http_upstream_test_next(r, u) == NGX_OK) {
  1981.             return;
  1982.         }

  1983.         if (ngx_http_upstream_intercept_errors(r, u) == NGX_OK) {
  1984.             return;
  1985.         }
  1986.     }

  1987.     if (u->peer.notify) {
  1988.         u->peer.notify(&u->peer, u->peer.data, NGX_HTTP_UPSTREAM_NOTIFY_HEADER);
  1989.     }

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

  1993.     ngx_http_upstream_send_response(r, u);
  1994. }


  1995. static ngx_int_t
  1996. ngx_http_upstream_process_early_hints(ngx_http_request_t *r,
  1997.     ngx_http_upstream_t *u)
  1998. {
  1999.     u_char            *p;
  2000.     ngx_uint_t         i;
  2001.     ngx_list_part_t   *part;
  2002.     ngx_table_elt_t   *h, *ho;
  2003.     ngx_connection_t  *c;

  2004.     c = r->connection;

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

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

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

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

  2009.             part = &u->headers_in.headers.part;
  2010.             h = part->elts;

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

  2012.                 if (i >= part->nelts) {
  2013.                     if (part->next == NULL) {
  2014.                         break;
  2015.                     }

  2016.                     part = part->next;
  2017.                     h = part->elts;
  2018.                     i = 0;
  2019.                 }

  2020.                 if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2021.                                   h[i].lowcase_key, h[i].key.len))
  2022.                 {
  2023.                     continue;
  2024.                 }

  2025.                 ho = ngx_list_push(&r->headers_out.headers);
  2026.                 if (ho == NULL) {
  2027.                     return NGX_ERROR;
  2028.                 }

  2029.                 *ho = h[i];
  2030.             }

  2031.             if (ngx_http_send_early_hints(r) == NGX_ERROR) {
  2032.                 return NGX_ERROR;
  2033.             }

  2034.             if (c->buffered) {
  2035.                 if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  2036.                     return NGX_ERROR;
  2037.                 }

  2038.                 r->write_event_handler = ngx_http_upstream_early_hints_writer;
  2039.             }

  2040.         } else {
  2041.             ngx_log_error(NGX_LOG_INFO, c->log, 0,
  2042.                           "upstream sent too big early hints");
  2043.         }
  2044.     }

  2045.     ngx_http_clean_header(r);

  2046.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  2047.     u->headers_in.content_length_n = -1;
  2048.     u->headers_in.last_modified_time = -1;

  2049.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  2050.                       sizeof(ngx_table_elt_t))
  2051.         != NGX_OK)
  2052.     {
  2053.         return NGX_ERROR;
  2054.     }

  2055.     if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  2056.                       sizeof(ngx_table_elt_t))
  2057.         != NGX_OK)
  2058.     {
  2059.         return NGX_ERROR;
  2060.     }

  2061.     p = u->buffer.pos;

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

  2063. #if (NGX_HTTP_CACHE)

  2064.     if (r->cache) {
  2065.         u->buffer.pos += r->cache->header_start;
  2066.     }

  2067. #endif

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

  2069.     return NGX_OK;
  2070. }


  2071. static void
  2072. ngx_http_upstream_early_hints_writer(ngx_http_request_t *r)
  2073. {
  2074.     ngx_connection_t     *c;
  2075.     ngx_http_upstream_t  *u;

  2076.     c = r->connection;
  2077.     u = r->upstream;

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

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

  2081.     if (ngx_http_write_filter(r, NULL) == NGX_ERROR) {
  2082.         ngx_http_upstream_finalize_request(r, u,
  2083.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  2084.         return;
  2085.     }

  2086.     if (!c->buffered) {
  2087.         if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {
  2088.             r->write_event_handler =
  2089.                                   ngx_http_upstream_wr_check_broken_connection;

  2090.         } else {
  2091.             r->write_event_handler = ngx_http_request_empty_handler;
  2092.         }
  2093.     }

  2094.     if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  2095.         ngx_http_upstream_finalize_request(r, u,
  2096.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  2097.     }
  2098. }


  2099. static ngx_int_t
  2100. ngx_http_upstream_test_next(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2101. {
  2102.     ngx_msec_t                 timeout;
  2103.     ngx_uint_t                 status, mask;
  2104.     ngx_http_upstream_next_t  *un;

  2105.     status = u->headers_in.status_n;

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

  2107.         if (status != un->status) {
  2108.             continue;
  2109.         }

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

  2111.         if (u->request_sent
  2112.             && (r->method & (NGX_HTTP_POST|NGX_HTTP_LOCK|NGX_HTTP_PATCH)))
  2113.         {
  2114.             mask = un->mask | NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT;

  2115.         } else {
  2116.             mask = un->mask;
  2117.         }

  2118.         if (u->peer.tries > 1
  2119.             && ((u->conf->next_upstream & mask) == mask)
  2120.             && !(u->request_sent && r->request_body_no_buffering)
  2121.             && !(timeout && ngx_current_msec - u->peer.start_time >= timeout))
  2122.         {
  2123.             ngx_http_upstream_next(r, u, un->mask);
  2124.             return NGX_OK;
  2125.         }

  2126. #if (NGX_HTTP_CACHE)

  2127.         if (u->cache_status == NGX_HTTP_CACHE_EXPIRED
  2128.             && (u->conf->cache_use_stale & un->mask))
  2129.         {
  2130.             ngx_int_t  rc;

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

  2132.             if (rc != NGX_OK) {
  2133.                 ngx_http_upstream_finalize_request(r, u, rc);
  2134.                 return NGX_OK;
  2135.             }

  2136.             u->cache_status = NGX_HTTP_CACHE_STALE;
  2137.             rc = ngx_http_upstream_cache_send(r, u);

  2138.             if (rc == NGX_DONE) {
  2139.                 return NGX_OK;
  2140.             }

  2141.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  2142.                 rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  2143.             }

  2144.             ngx_http_upstream_finalize_request(r, u, rc);
  2145.             return NGX_OK;
  2146.         }

  2147. #endif

  2148.         break;
  2149.     }

  2150. #if (NGX_HTTP_CACHE)

  2151.     if (status == NGX_HTTP_NOT_MODIFIED
  2152.         && u->cache_status == NGX_HTTP_CACHE_EXPIRED
  2153.         && u->conf->cache_revalidate)
  2154.     {
  2155.         time_t     now, valid, updating, error;
  2156.         ngx_int_t  rc;

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

  2159.         now = ngx_time();

  2160.         valid = r->cache->valid_sec;
  2161.         updating = r->cache->updating_sec;
  2162.         error = r->cache->error_sec;

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

  2164.         if (rc != NGX_OK) {
  2165.             ngx_http_upstream_finalize_request(r, u, rc);
  2166.             return NGX_OK;
  2167.         }

  2168.         u->cache_status = NGX_HTTP_CACHE_REVALIDATED;
  2169.         rc = ngx_http_upstream_cache_send(r, u);

  2170.         if (rc == NGX_DONE) {
  2171.             return NGX_OK;
  2172.         }

  2173.         if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  2174.             rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  2175.         }

  2176.         if (valid == 0) {
  2177.             valid = r->cache->valid_sec;
  2178.             updating = r->cache->updating_sec;
  2179.             error = r->cache->error_sec;
  2180.         }

  2181.         if (valid == 0) {
  2182.             valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2183.                                               u->headers_in.status_n);
  2184.             if (valid) {
  2185.                 valid = now + valid;
  2186.             }
  2187.         }

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

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

  2193.             ngx_http_file_cache_update_header(r);
  2194.         }

  2195.         ngx_http_upstream_finalize_request(r, u, rc);
  2196.         return NGX_OK;
  2197.     }

  2198. #endif

  2199.     return NGX_DECLINED;
  2200. }


  2201. static ngx_int_t
  2202. ngx_http_upstream_intercept_errors(ngx_http_request_t *r,
  2203.     ngx_http_upstream_t *u)
  2204. {
  2205.     ngx_int_t                  status;
  2206.     ngx_uint_t                 i;
  2207.     ngx_table_elt_t           *h, *ho, **ph;
  2208.     ngx_http_err_page_t       *err_page;
  2209.     ngx_http_core_loc_conf_t  *clcf;

  2210.     status = u->headers_in.status_n;

  2211.     if (status == NGX_HTTP_NOT_FOUND && u->conf->intercept_404) {
  2212.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_NOT_FOUND);
  2213.         return NGX_OK;
  2214.     }

  2215.     if (!u->conf->intercept_errors) {
  2216.         return NGX_DECLINED;
  2217.     }

  2218.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2219.     if (clcf->error_pages == NULL) {
  2220.         return NGX_DECLINED;
  2221.     }

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

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

  2225.             if (status == NGX_HTTP_UNAUTHORIZED
  2226.                 && u->headers_in.www_authenticate)
  2227.             {
  2228.                 h = u->headers_in.www_authenticate;
  2229.                 ph = &r->headers_out.www_authenticate;

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

  2232.                     if (ho == NULL) {
  2233.                         ngx_http_upstream_finalize_request(r, u,
  2234.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  2235.                         return NGX_OK;
  2236.                     }

  2237.                     *ho = *h;
  2238.                     ho->next = NULL;

  2239.                     *ph = ho;
  2240.                     ph = &ho->next;

  2241.                     h = h->next;
  2242.                 }
  2243.             }

  2244. #if (NGX_HTTP_CACHE)

  2245.             if (r->cache) {

  2246.                 if (u->headers_in.no_cache || u->headers_in.expired) {
  2247.                     u->cacheable = 0;
  2248.                 }

  2249.                 if (u->cacheable) {
  2250.                     time_t  valid;

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

  2252.                     if (valid == 0) {
  2253.                         valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2254.                                                           status);
  2255.                         if (valid) {
  2256.                             r->cache->valid_sec = ngx_time() + valid;
  2257.                         }
  2258.                     }

  2259.                     if (valid) {
  2260.                         r->cache->error = status;
  2261.                     }
  2262.                 }

  2263.                 ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2264.             }
  2265. #endif
  2266.             ngx_http_upstream_finalize_request(r, u, status);

  2267.             return NGX_OK;
  2268.         }
  2269.     }

  2270.     return NGX_DECLINED;
  2271. }


  2272. static ngx_int_t
  2273. ngx_http_upstream_test_connect(ngx_connection_t *c)
  2274. {
  2275.     int        err;
  2276.     socklen_t  len;

  2277. #if (NGX_HAVE_KQUEUE)

  2278.     if (ngx_event_flags & NGX_USE_KQUEUE_EVENT)  {
  2279.         if (c->write->pending_eof || c->read->pending_eof) {
  2280.             if (c->write->pending_eof) {
  2281.                 err = c->write->kq_errno;

  2282.             } else {
  2283.                 err = c->read->kq_errno;
  2284.             }

  2285.             c->log->action = "connecting to upstream";
  2286.             (void) ngx_connection_error(c, err,
  2287.                                     "kevent() reported that connect() failed");
  2288.             return NGX_ERROR;
  2289.         }

  2290.     } else
  2291. #endif
  2292.     {
  2293.         err = 0;
  2294.         len = sizeof(int);

  2295.         /*
  2296.          * BSDs and Linux return 0 and set a pending error in err
  2297.          * Solaris returns -1 and sets errno
  2298.          */

  2299.         if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, (void *) &err, &len)
  2300.             == -1)
  2301.         {
  2302.             err = ngx_socket_errno;
  2303.         }

  2304.         if (err) {
  2305.             c->log->action = "connecting to upstream";
  2306.             (void) ngx_connection_error(c, err, "connect() failed");
  2307.             return NGX_ERROR;
  2308.         }
  2309.     }

  2310.     return NGX_OK;
  2311. }


  2312. static ngx_int_t
  2313. ngx_http_upstream_process_headers(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2314. {
  2315.     ngx_str_t                       uri, args;
  2316.     ngx_uint_t                      i, flags;
  2317.     ngx_list_part_t                *part;
  2318.     ngx_table_elt_t                *h;
  2319.     ngx_http_upstream_header_t     *hh;
  2320.     ngx_http_upstream_main_conf_t  *umcf;

  2321.     umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);

  2322.     if (u->headers_in.no_cache || u->headers_in.expired) {
  2323.         u->cacheable = 0;
  2324.     }

  2325.     if (u->headers_in.x_accel_redirect
  2326.         && !(u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_REDIRECT))
  2327.     {
  2328.         ngx_http_upstream_finalize_request(r, u, NGX_DECLINED);

  2329.         part = &u->headers_in.headers.part;
  2330.         h = part->elts;

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

  2332.             if (i >= part->nelts) {
  2333.                 if (part->next == NULL) {
  2334.                     break;
  2335.                 }

  2336.                 part = part->next;
  2337.                 h = part->elts;
  2338.                 i = 0;
  2339.             }

  2340.             if (h[i].hash == 0) {
  2341.                 continue;
  2342.             }

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

  2345.             if (hh && hh->redirect) {
  2346.                 if (hh->copy_handler(r, &h[i], hh->conf) != NGX_OK) {
  2347.                     ngx_http_finalize_request(r,
  2348.                                               NGX_HTTP_INTERNAL_SERVER_ERROR);
  2349.                     return NGX_DONE;
  2350.                 }
  2351.             }
  2352.         }

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

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

  2356.         } else {
  2357.             ngx_str_null(&args);
  2358.             flags = NGX_HTTP_LOG_UNSAFE;

  2359.             if (ngx_http_parse_unsafe_uri(r, &uri, &args, &flags) != NGX_OK) {
  2360.                 ngx_http_finalize_request(r, NGX_HTTP_NOT_FOUND);
  2361.                 return NGX_DONE;
  2362.             }

  2363.             if (r->method != NGX_HTTP_HEAD) {
  2364.                 r->method = NGX_HTTP_GET;
  2365.                 r->method_name = ngx_http_core_get_method;
  2366.             }

  2367.             ngx_http_internal_redirect(r, &uri, &args);
  2368.         }

  2369.         ngx_http_finalize_request(r, NGX_DONE);
  2370.         return NGX_DONE;
  2371.     }

  2372.     part = &u->headers_in.headers.part;
  2373.     h = part->elts;

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

  2375.         if (i >= part->nelts) {
  2376.             if (part->next == NULL) {
  2377.                 break;
  2378.             }

  2379.             part = part->next;
  2380.             h = part->elts;
  2381.             i = 0;
  2382.         }

  2383.         if (h[i].hash == 0) {
  2384.             continue;
  2385.         }

  2386.         if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2387.                           h[i].lowcase_key, h[i].key.len))
  2388.         {
  2389.             continue;
  2390.         }

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

  2393.         if (hh) {
  2394.             if (hh->copy_handler(r, &h[i], hh->conf) != NGX_OK) {
  2395.                 ngx_http_upstream_finalize_request(r, u,
  2396.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  2397.                 return NGX_DONE;
  2398.             }

  2399.             continue;
  2400.         }

  2401.         if (ngx_http_upstream_copy_header_line(r, &h[i], 0) != NGX_OK) {
  2402.             ngx_http_upstream_finalize_request(r, u,
  2403.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  2404.             return NGX_DONE;
  2405.         }
  2406.     }

  2407.     if (r->headers_out.server && r->headers_out.server->value.data == NULL) {
  2408.         r->headers_out.server->hash = 0;
  2409.     }

  2410.     if (r->headers_out.date && r->headers_out.date->value.data == NULL) {
  2411.         r->headers_out.date->hash = 0;
  2412.     }

  2413.     r->headers_out.status = u->headers_in.status_n;
  2414.     r->headers_out.status_line = u->headers_in.status_line;

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

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

  2417.     if (u->conf->force_ranges) {
  2418.         r->allow_ranges = 1;
  2419.         r->single_range = 1;

  2420. #if (NGX_HTTP_CACHE)
  2421.         if (r->cached) {
  2422.             r->single_range = 0;
  2423.         }
  2424. #endif
  2425.     }

  2426.     u->length = -1;

  2427.     return NGX_OK;
  2428. }


  2429. static ngx_int_t
  2430. ngx_http_upstream_process_trailers(ngx_http_request_t *r,
  2431.     ngx_http_upstream_t *u)
  2432. {
  2433.     ngx_uint_t        i;
  2434.     ngx_list_part_t  *part;
  2435.     ngx_table_elt_t  *h, *ho;

  2436.     if (!u->conf->pass_trailers) {
  2437.         return NGX_OK;
  2438.     }

  2439.     part = &u->headers_in.trailers.part;
  2440.     h = part->elts;

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

  2442.         if (i >= part->nelts) {
  2443.             if (part->next == NULL) {
  2444.                 break;
  2445.             }

  2446.             part = part->next;
  2447.             h = part->elts;
  2448.             i = 0;
  2449.         }

  2450.         if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2451.                           h[i].lowcase_key, h[i].key.len))
  2452.         {
  2453.             continue;
  2454.         }

  2455.         ho = ngx_list_push(&r->headers_out.trailers);
  2456.         if (ho == NULL) {
  2457.             return NGX_ERROR;
  2458.         }

  2459.         *ho = h[i];
  2460.     }

  2461.     return NGX_OK;
  2462. }


  2463. static void
  2464. ngx_http_upstream_send_response(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2465. {
  2466.     ssize_t                    n;
  2467.     ngx_int_t                  rc;
  2468.     ngx_event_pipe_t          *p;
  2469.     ngx_connection_t          *c;
  2470.     ngx_http_core_loc_conf_t  *clcf;

  2471.     rc = ngx_http_send_header(r);

  2472.     if (rc == NGX_ERROR || rc > NGX_OK || r->post_action) {
  2473.         ngx_http_upstream_finalize_request(r, u, rc);
  2474.         return;
  2475.     }

  2476.     u->header_sent = 1;

  2477.     if (u->upgrade) {

  2478. #if (NGX_HTTP_CACHE)

  2479.         if (r->cache) {
  2480.             ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2481.         }

  2482. #endif

  2483.         ngx_http_upstream_upgrade(r, u);
  2484.         return;
  2485.     }

  2486.     c = r->connection;

  2487.     if (r->header_only) {

  2488.         if (!u->buffering) {
  2489.             ngx_http_upstream_finalize_request(r, u, rc);
  2490.             return;
  2491.         }

  2492.         if (!u->cacheable && !u->store) {
  2493.             ngx_http_upstream_finalize_request(r, u, rc);
  2494.             return;
  2495.         }

  2496.         u->pipe->downstream_error = 1;
  2497.     }

  2498.     if (r->request_body && r->request_body->temp_file
  2499.         && r == r->main && !r->preserve_body
  2500.         && !u->conf->preserve_output)
  2501.     {
  2502.         ngx_pool_run_cleanup_file(r->pool, r->request_body->temp_file->file.fd);
  2503.         r->request_body->temp_file->file.fd = NGX_INVALID_FILE;
  2504.     }

  2505.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2506.     if (!u->buffering) {

  2507. #if (NGX_HTTP_CACHE)

  2508.         if (r->cache) {
  2509.             ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2510.         }

  2511. #endif

  2512.         if (u->input_filter == NULL) {
  2513.             u->input_filter_init = ngx_http_upstream_non_buffered_filter_init;
  2514.             u->input_filter = ngx_http_upstream_non_buffered_filter;
  2515.             u->input_filter_ctx = r;
  2516.         }

  2517.         u->read_event_handler = ngx_http_upstream_process_non_buffered_upstream;
  2518.         r->write_event_handler =
  2519.                              ngx_http_upstream_process_non_buffered_downstream;

  2520.         r->limit_rate = 0;
  2521.         r->limit_rate_set = 1;

  2522.         if (u->input_filter_init(u->input_filter_ctx) == NGX_ERROR) {
  2523.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2524.             return;
  2525.         }

  2526.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  2527.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2528.             return;
  2529.         }

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

  2531.         if (n) {
  2532.             u->buffer.last = u->buffer.pos;

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

  2534.             if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  2535.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2536.                 return;
  2537.             }

  2538.             ngx_http_upstream_process_non_buffered_downstream(r);

  2539.         } else {
  2540.             u->buffer.pos = u->buffer.start;
  2541.             u->buffer.last = u->buffer.start;

  2542.             if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {
  2543.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2544.                 return;
  2545.             }

  2546.             ngx_http_upstream_process_non_buffered_upstream(r, u);
  2547.         }

  2548.         return;
  2549.     }

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

  2551. #if (NGX_HTTP_CACHE)

  2552.     if (r->cache && r->cache->file.fd != NGX_INVALID_FILE) {
  2553.         ngx_pool_run_cleanup_file(r->pool, r->cache->file.fd);
  2554.         r->cache->file.fd = NGX_INVALID_FILE;
  2555.     }

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

  2557.     case NGX_ERROR:
  2558.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2559.         return;

  2560.     case NGX_DECLINED:
  2561.         u->cacheable = 0;
  2562.         break;

  2563.     default: /* NGX_OK */

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

  2565.             /* create cache if previously bypassed */

  2566.             if (ngx_http_file_cache_create(r) != NGX_OK) {
  2567.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2568.                 return;
  2569.             }
  2570.         }

  2571.         break;
  2572.     }

  2573.     if (u->cacheable) {
  2574.         time_t  now, valid;

  2575.         now = ngx_time();

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

  2577.         if (valid == 0) {
  2578.             valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2579.                                               u->headers_in.status_n);
  2580.             if (valid) {
  2581.                 r->cache->valid_sec = now + valid;
  2582.             }
  2583.         }

  2584.         if (valid) {
  2585.             r->cache->date = now;
  2586.             r->cache->body_start = (u_short) (u->buffer.pos - u->buffer.start);

  2587.             if (u->headers_in.status_n == NGX_HTTP_OK
  2588.                 || u->headers_in.status_n == NGX_HTTP_PARTIAL_CONTENT)
  2589.             {
  2590.                 r->cache->last_modified = u->headers_in.last_modified_time;

  2591.                 if (u->headers_in.etag) {
  2592.                     r->cache->etag = u->headers_in.etag->value;

  2593.                 } else {
  2594.                     ngx_str_null(&r->cache->etag);
  2595.                 }

  2596.             } else {
  2597.                 r->cache->last_modified = -1;
  2598.                 ngx_str_null(&r->cache->etag);
  2599.             }

  2600.             if (ngx_http_file_cache_set_header(r, u->buffer.start) != NGX_OK) {
  2601.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2602.                 return;
  2603.             }

  2604.         } else {
  2605.             u->cacheable = 0;
  2606.         }
  2607.     }

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

  2610.     if (u->cacheable == 0 && r->cache) {
  2611.         ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2612.     }

  2613.     if (r->header_only && !u->cacheable && !u->store) {
  2614.         ngx_http_upstream_finalize_request(r, u, 0);
  2615.         return;
  2616.     }

  2617. #endif

  2618.     p = u->pipe;

  2619.     p->output_filter = ngx_http_upstream_output_filter;
  2620.     p->output_ctx = r;
  2621.     p->tag = u->output.tag;
  2622.     p->bufs = u->conf->bufs;
  2623.     p->busy_size = u->conf->busy_buffers_size;
  2624.     p->upstream = u->peer.connection;
  2625.     p->downstream = c;
  2626.     p->pool = r->pool;
  2627.     p->log = c->log;
  2628.     p->limit_rate = ngx_http_complex_value_size(r, u->conf->limit_rate, 0);
  2629.     p->start_sec = ngx_time();

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

  2631.     p->temp_file = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t));
  2632.     if (p->temp_file == NULL) {
  2633.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2634.         return;
  2635.     }

  2636.     p->temp_file->file.fd = NGX_INVALID_FILE;
  2637.     p->temp_file->file.log = c->log;
  2638.     p->temp_file->path = u->conf->temp_path;
  2639.     p->temp_file->pool = r->pool;

  2640.     if (p->cacheable) {
  2641.         p->temp_file->persistent = 1;

  2642. #if (NGX_HTTP_CACHE)
  2643.         if (r->cache && !r->cache->file_cache->use_temp_path) {
  2644.             p->temp_file->path = r->cache->file_cache->path;
  2645.             p->temp_file->file.name = r->cache->file.name;
  2646.         }
  2647. #endif

  2648.     } else {
  2649.         p->temp_file->log_level = NGX_LOG_WARN;
  2650.         p->temp_file->warn = "an upstream response is buffered "
  2651.                              "to a temporary file";
  2652.     }

  2653.     p->max_temp_file_size = u->conf->max_temp_file_size;
  2654.     p->temp_file_write_size = u->conf->temp_file_write_size;

  2655. #if (NGX_THREADS)
  2656.     if (clcf->aio == NGX_HTTP_AIO_THREADS && clcf->aio_write) {
  2657.         p->thread_handler = ngx_http_upstream_thread_handler;
  2658.         p->thread_ctx = r;
  2659.     }
  2660. #endif

  2661.     p->preread_bufs = ngx_alloc_chain_link(r->pool);
  2662.     if (p->preread_bufs == NULL) {
  2663.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2664.         return;
  2665.     }

  2666.     p->preread_bufs->buf = &u->buffer;
  2667.     p->preread_bufs->next = NULL;
  2668.     u->buffer.recycled = 1;

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

  2670.     if (u->cacheable) {

  2671.         p->buf_to_file = ngx_calloc_buf(r->pool);
  2672.         if (p->buf_to_file == NULL) {
  2673.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2674.             return;
  2675.         }

  2676.         p->buf_to_file->start = u->buffer.start;
  2677.         p->buf_to_file->pos = u->buffer.start;
  2678.         p->buf_to_file->last = u->buffer.pos;
  2679.         p->buf_to_file->temporary = 1;
  2680.     }

  2681.     if (ngx_event_flags & NGX_USE_IOCP_EVENT) {
  2682.         /* the posted aio operation may corrupt a shadow buffer */
  2683.         p->single_buf = 1;
  2684.     }

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

  2687.     /*
  2688.      * event_pipe would do u->buffer.last += p->preread_size
  2689.      * as though these bytes were read
  2690.      */
  2691.     u->buffer.last = u->buffer.pos;

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

  2693.         /*
  2694.          * we need to disable the use of sendfile() if we use cyclic temp file
  2695.          * because the writing a new data may interfere with sendfile()
  2696.          * that uses the same kernel file pages (at least on FreeBSD)
  2697.          */

  2698.         p->cyclic_temp_file = 1;
  2699.         c->sendfile = 0;

  2700.     } else {
  2701.         p->cyclic_temp_file = 0;
  2702.     }

  2703.     p->read_timeout = u->conf->read_timeout;
  2704.     p->send_timeout = clcf->send_timeout;
  2705.     p->send_lowat = clcf->send_lowat;

  2706.     p->length = -1;

  2707.     if (u->input_filter_init
  2708.         && u->input_filter_init(p->input_ctx) != NGX_OK)
  2709.     {
  2710.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2711.         return;
  2712.     }

  2713.     u->read_event_handler = ngx_http_upstream_process_upstream;
  2714.     r->write_event_handler = ngx_http_upstream_process_downstream;

  2715.     ngx_http_upstream_process_upstream(r, u);
  2716. }


  2717. static void
  2718. ngx_http_upstream_upgrade(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2719. {
  2720.     ngx_connection_t          *c;
  2721.     ngx_http_core_loc_conf_t  *clcf;

  2722.     c = r->connection;
  2723.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

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

  2725.     if (r != r->main) {
  2726.         ngx_log_error(NGX_LOG_ERR, c->log, 0,
  2727.                       "connection upgrade in subrequest");
  2728.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2729.         return;
  2730.     }

  2731.     r->keepalive = 0;
  2732.     c->log->action = "proxying upgraded connection";

  2733.     u->read_event_handler = ngx_http_upstream_upgraded_read_upstream;
  2734.     u->write_event_handler = ngx_http_upstream_upgraded_write_upstream;
  2735.     r->read_event_handler = ngx_http_upstream_upgraded_read_downstream;
  2736.     r->write_event_handler = ngx_http_upstream_upgraded_write_downstream;

  2737.     if (clcf->tcp_nodelay) {

  2738.         if (ngx_tcp_nodelay(c) != NGX_OK) {
  2739.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2740.             return;
  2741.         }

  2742.         if (ngx_tcp_nodelay(u->peer.connection) != NGX_OK) {
  2743.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2744.             return;
  2745.         }
  2746.     }

  2747.     if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {
  2748.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2749.         return;
  2750.     }

  2751.     if (u->peer.connection->read->ready
  2752.         || u->buffer.pos != u->buffer.last)
  2753.     {
  2754.         ngx_post_event(c->read, &ngx_posted_events);
  2755.         ngx_http_upstream_process_upgraded(r, 1, 1);
  2756.         return;
  2757.     }

  2758.     ngx_http_upstream_process_upgraded(r, 0, 1);
  2759. }


  2760. static void
  2761. ngx_http_upstream_upgraded_read_downstream(ngx_http_request_t *r)
  2762. {
  2763.     ngx_http_upstream_process_upgraded(r, 0, 0);
  2764. }


  2765. static void
  2766. ngx_http_upstream_upgraded_write_downstream(ngx_http_request_t *r)
  2767. {
  2768.     ngx_http_upstream_process_upgraded(r, 1, 1);
  2769. }


  2770. static void
  2771. ngx_http_upstream_upgraded_read_upstream(ngx_http_request_t *r,
  2772.     ngx_http_upstream_t *u)
  2773. {
  2774.     ngx_http_upstream_process_upgraded(r, 1, 0);
  2775. }


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


  2782. static void
  2783. ngx_http_upstream_process_upgraded(ngx_http_request_t *r,
  2784.     ngx_uint_t from_upstream, ngx_uint_t do_write)
  2785. {
  2786.     size_t                     size;
  2787.     ssize_t                    n;
  2788.     ngx_buf_t                 *b;
  2789.     ngx_uint_t                 flags;
  2790.     ngx_connection_t          *c, *downstream, *upstream, *dst, *src;
  2791.     ngx_http_upstream_t       *u;
  2792.     ngx_http_core_loc_conf_t  *clcf;

  2793.     c = r->connection;
  2794.     u = r->upstream;

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

  2797.     downstream = c;
  2798.     upstream = u->peer.connection;

  2799.     if (downstream->write->timedout) {
  2800.         c->timedout = 1;
  2801.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");
  2802.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  2803.         return;
  2804.     }

  2805.     if (upstream->read->timedout || upstream->write->timedout) {
  2806.         ngx_connection_error(c, NGX_ETIMEDOUT, "upstream timed out");
  2807.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_GATEWAY_TIME_OUT);
  2808.         return;
  2809.     }

  2810.     if (from_upstream) {
  2811.         src = upstream;
  2812.         dst = downstream;
  2813.         b = &u->buffer;

  2814.     } else {
  2815.         src = downstream;
  2816.         dst = upstream;
  2817.         b = &u->from_client;

  2818.         if (r->header_in->last > r->header_in->pos) {
  2819.             b = r->header_in;
  2820.             b->end = b->last;
  2821.             do_write = 1;
  2822.         }

  2823.         if (b->start == NULL) {
  2824.             b->start = ngx_palloc(r->pool, u->conf->buffer_size);
  2825.             if (b->start == NULL) {
  2826.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2827.                 return;
  2828.             }

  2829.             b->pos = b->start;
  2830.             b->last = b->start;
  2831.             b->end = b->start + u->conf->buffer_size;
  2832.             b->temporary = 1;
  2833.             b->tag = u->output.tag;
  2834.         }
  2835.     }

  2836.     for ( ;; ) {

  2837.         if (do_write) {

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

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

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

  2841.                 if (n == NGX_ERROR) {
  2842.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2843.                     return;
  2844.                 }

  2845.                 if (n > 0) {
  2846.                     b->pos += n;

  2847.                     if (b->pos == b->last) {
  2848.                         b->pos = b->start;
  2849.                         b->last = b->start;
  2850.                     }
  2851.                 }
  2852.             }
  2853.         }

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

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

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

  2857.             if (n == NGX_AGAIN || n == 0) {
  2858.                 break;
  2859.             }

  2860.             if (n > 0) {
  2861.                 do_write = 1;
  2862.                 b->last += n;

  2863.                 if (from_upstream) {
  2864.                     u->state->bytes_received += n;
  2865.                 }

  2866.                 continue;
  2867.             }

  2868.             if (n == NGX_ERROR) {
  2869.                 src->read->eof = 1;
  2870.             }
  2871.         }

  2872.         break;
  2873.     }

  2874.     if ((upstream->read->eof && u->buffer.pos == u->buffer.last)
  2875.         || (downstream->read->eof && u->from_client.pos == u->from_client.last)
  2876.         || (downstream->read->eof && upstream->read->eof))
  2877.     {
  2878.         ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2879.                        "http upstream upgraded done");
  2880.         ngx_http_upstream_finalize_request(r, u, 0);
  2881.         return;
  2882.     }

  2883.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2884.     if (ngx_handle_write_event(upstream->write, u->conf->send_lowat)
  2885.         != NGX_OK)
  2886.     {
  2887.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2888.         return;
  2889.     }

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

  2892.     } else if (upstream->write->timer_set) {
  2893.         ngx_del_timer(upstream->write);
  2894.     }

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

  2897.     } else {
  2898.         flags = 0;
  2899.     }

  2900.     if (ngx_handle_read_event(upstream->read, flags) != NGX_OK) {
  2901.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2902.         return;
  2903.     }

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

  2906.     } else if (upstream->read->timer_set) {
  2907.         ngx_del_timer(upstream->read);
  2908.     }

  2909.     if (ngx_handle_write_event(downstream->write, clcf->send_lowat)
  2910.         != NGX_OK)
  2911.     {
  2912.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2913.         return;
  2914.     }

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

  2917.     } else {
  2918.         flags = 0;
  2919.     }

  2920.     if (ngx_handle_read_event(downstream->read, flags) != NGX_OK) {
  2921.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2922.         return;
  2923.     }

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

  2926.     } else if (downstream->write->timer_set) {
  2927.         ngx_del_timer(downstream->write);
  2928.     }
  2929. }


  2930. static void
  2931. ngx_http_upstream_process_non_buffered_downstream(ngx_http_request_t *r)
  2932. {
  2933.     ngx_event_t          *wev;
  2934.     ngx_connection_t     *c;
  2935.     ngx_http_upstream_t  *u;

  2936.     c = r->connection;
  2937.     u = r->upstream;
  2938.     wev = c->write;

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

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

  2942.     if (wev->timedout) {
  2943.         c->timedout = 1;
  2944.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");
  2945.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  2946.         return;
  2947.     }

  2948.     ngx_http_upstream_process_non_buffered_request(r, 1);
  2949. }


  2950. static void
  2951. ngx_http_upstream_process_non_buffered_upstream(ngx_http_request_t *r,
  2952.     ngx_http_upstream_t *u)
  2953. {
  2954.     ngx_connection_t  *c;

  2955.     c = u->peer.connection;

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

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

  2959.     if (c->read->timedout) {
  2960.         ngx_connection_error(c, NGX_ETIMEDOUT, "upstream timed out");
  2961.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_GATEWAY_TIME_OUT);
  2962.         return;
  2963.     }

  2964.     ngx_http_upstream_process_non_buffered_request(r, 0);
  2965. }


  2966. static void
  2967. ngx_http_upstream_process_non_buffered_request(ngx_http_request_t *r,
  2968.     ngx_uint_t do_write)
  2969. {
  2970.     size_t                     size;
  2971.     ssize_t                    n;
  2972.     ngx_buf_t                 *b;
  2973.     ngx_int_t                  rc;
  2974.     ngx_uint_t                 flags;
  2975.     ngx_connection_t          *downstream, *upstream;
  2976.     ngx_http_upstream_t       *u;
  2977.     ngx_http_core_loc_conf_t  *clcf;

  2978.     u = r->upstream;
  2979.     downstream = r->connection;
  2980.     upstream = u->peer.connection;

  2981.     b = &u->buffer;

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

  2983.     for ( ;; ) {

  2984.         if (do_write) {

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

  2987.                 if (rc == NGX_ERROR) {
  2988.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2989.                     return;
  2990.                 }

  2991.                 ngx_chain_update_chains(r->pool, &u->free_bufs, &u->busy_bufs,
  2992.                                         &u->out_bufs, u->output.tag);
  2993.             }

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

  2995.                 if (u->length == 0
  2996.                     || (upstream->read->eof && u->length == -1))
  2997.                 {
  2998.                     ngx_http_upstream_finalize_request(r, u, 0);
  2999.                     return;
  3000.                 }

  3001.                 if (upstream->read->eof) {
  3002.                     ngx_log_error(NGX_LOG_ERR, upstream->log, 0,
  3003.                                   "upstream prematurely closed connection");

  3004.                     ngx_http_upstream_finalize_request(r, u,
  3005.                                                        NGX_HTTP_BAD_GATEWAY);
  3006.                     return;
  3007.                 }

  3008.                 if (upstream->read->error || u->error) {
  3009.                     ngx_http_upstream_finalize_request(r, u,
  3010.                                                        NGX_HTTP_BAD_GATEWAY);
  3011.                     return;
  3012.                 }

  3013.                 b->pos = b->start;
  3014.                 b->last = b->start;
  3015.             }
  3016.         }

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

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

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

  3020.             if (n == NGX_AGAIN) {
  3021.                 break;
  3022.             }

  3023.             if (n > 0) {
  3024.                 u->state->bytes_received += n;
  3025.                 u->state->response_length += n;

  3026.                 if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  3027.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3028.                     return;
  3029.                 }
  3030.             }

  3031.             do_write = 1;

  3032.             continue;
  3033.         }

  3034.         break;
  3035.     }

  3036.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  3037.     if (downstream->data == r) {
  3038.         if (ngx_handle_write_event(downstream->write, clcf->send_lowat)
  3039.             != NGX_OK)
  3040.         {
  3041.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3042.             return;
  3043.         }
  3044.     }

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

  3047.     } else if (downstream->write->timer_set) {
  3048.         ngx_del_timer(downstream->write);
  3049.     }

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

  3052.     } else {
  3053.         flags = 0;
  3054.     }

  3055.     if (ngx_handle_read_event(upstream->read, flags) != NGX_OK) {
  3056.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3057.         return;
  3058.     }

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

  3061.     } else if (upstream->read->timer_set) {
  3062.         ngx_del_timer(upstream->read);
  3063.     }
  3064. }


  3065. ngx_int_t
  3066. ngx_http_upstream_non_buffered_filter_init(void *data)
  3067. {
  3068.     return NGX_OK;
  3069. }


  3070. ngx_int_t
  3071. ngx_http_upstream_non_buffered_filter(void *data, ssize_t bytes)
  3072. {
  3073.     ngx_http_request_t  *r = data;

  3074.     ngx_buf_t            *b;
  3075.     ngx_chain_t          *cl, **ll;
  3076.     ngx_http_upstream_t  *u;

  3077.     u = r->upstream;

  3078.     if (u->length == 0) {
  3079.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3080.                       "upstream sent more data than specified in "
  3081.                       "\"Content-Length\" header");
  3082.         return NGX_OK;
  3083.     }

  3084.     for (cl = u->out_bufs, ll = &u->out_bufs; cl; cl = cl->next) {
  3085.         ll = &cl->next;
  3086.     }

  3087.     cl = ngx_chain_get_free_buf(r->pool, &u->free_bufs);
  3088.     if (cl == NULL) {
  3089.         return NGX_ERROR;
  3090.     }

  3091.     *ll = cl;

  3092.     cl->buf->flush = 1;
  3093.     cl->buf->memory = 1;

  3094.     b = &u->buffer;

  3095.     cl->buf->pos = b->last;
  3096.     b->last += bytes;
  3097.     cl->buf->last = b->last;
  3098.     cl->buf->tag = u->output.tag;

  3099.     if (u->length == -1) {
  3100.         return NGX_OK;
  3101.     }

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

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

  3106.         cl->buf->last = cl->buf->pos + u->length;
  3107.         u->length = 0;

  3108.         return NGX_OK;
  3109.     }

  3110.     u->length -= bytes;

  3111.     return NGX_OK;
  3112. }


  3113. #if (NGX_THREADS)

  3114. static ngx_int_t
  3115. ngx_http_upstream_thread_handler(ngx_thread_task_t *task, ngx_file_t *file)
  3116. {
  3117.     ngx_str_t                  name;
  3118.     ngx_event_pipe_t          *p;
  3119.     ngx_connection_t          *c;
  3120.     ngx_thread_pool_t         *tp;
  3121.     ngx_http_request_t        *r;
  3122.     ngx_http_core_loc_conf_t  *clcf;

  3123.     r = file->thread_ctx;
  3124.     p = r->upstream->pipe;

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

  3132.         c = r->connection;

  3133. #if (NGX_HTTP_V2)
  3134.         if (r->stream) {
  3135.             c = r->stream->connection->connection;
  3136.         }
  3137. #endif

  3138.         if (task == c->sendfile_task) {
  3139.             return NGX_OK;
  3140.         }
  3141.     }

  3142.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
  3143.     tp = clcf->thread_pool;

  3144.     if (tp == NULL) {
  3145.         if (ngx_http_complex_value(r, clcf->thread_pool_value, &name)
  3146.             != NGX_OK)
  3147.         {
  3148.             return NGX_ERROR;
  3149.         }

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

  3151.         if (tp == NULL) {
  3152.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3153.                           "thread pool \"%V\" not found", &name);
  3154.             return NGX_ERROR;
  3155.         }
  3156.     }

  3157.     task->event.data = r;
  3158.     task->event.handler = ngx_http_upstream_thread_event_handler;

  3159.     if (ngx_thread_task_post(tp, task) != NGX_OK) {
  3160.         return NGX_ERROR;
  3161.     }

  3162.     r->main->blocked++;
  3163.     r->aio = 1;
  3164.     p->aio = 1;

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

  3166.     return NGX_OK;
  3167. }


  3168. static void
  3169. ngx_http_upstream_thread_event_handler(ngx_event_t *ev)
  3170. {
  3171.     ngx_connection_t    *c;
  3172.     ngx_http_request_t  *r;

  3173.     r = ev->data;
  3174.     c = r->connection;

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

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

  3178.     if (ev->timedout) {
  3179.         ngx_log_error(NGX_LOG_ALERT, c->log, 0,
  3180.                       "thread operation took too long");
  3181.         ev->timedout = 0;
  3182.         return;
  3183.     }

  3184.     if (ev->timer_set) {
  3185.         ngx_del_timer(ev);
  3186.     }

  3187.     r->main->blocked--;
  3188.     r->aio = 0;

  3189. #if (NGX_HTTP_V2)

  3190.     if (r->stream) {
  3191.         /*
  3192.          * for HTTP/2, update write event to make sure processing will
  3193.          * reach the main connection to handle sendfile() in threads
  3194.          */

  3195.         c->write->ready = 1;
  3196.         c->write->active = 0;
  3197.     }

  3198. #endif

  3199.     if (r->done || r->main->terminated) {
  3200.         /*
  3201.          * trigger connection event handler if the subrequest was
  3202.          * already finalized (this can happen if the handler is used
  3203.          * for sendfile() in threads), or if the request was terminated
  3204.          */

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

  3206.     } else {
  3207.         r->write_event_handler(r);
  3208.         ngx_http_run_posted_requests(c);
  3209.     }
  3210. }

  3211. #endif


  3212. static ngx_int_t
  3213. ngx_http_upstream_output_filter(void *data, ngx_chain_t *chain)
  3214. {
  3215.     ngx_int_t            rc;
  3216.     ngx_event_pipe_t    *p;
  3217.     ngx_http_request_t  *r;

  3218.     r = data;
  3219.     p = r->upstream->pipe;

  3220.     rc = ngx_http_output_filter(r, chain);

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

  3222.     return rc;
  3223. }


  3224. static void
  3225. ngx_http_upstream_process_downstream(ngx_http_request_t *r)
  3226. {
  3227.     ngx_event_t          *wev;
  3228.     ngx_connection_t     *c;
  3229.     ngx_event_pipe_t     *p;
  3230.     ngx_http_upstream_t  *u;

  3231.     c = r->connection;
  3232.     u = r->upstream;
  3233.     p = u->pipe;
  3234.     wev = c->write;

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

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

  3238. #if (NGX_THREADS)
  3239.     p->aio = r->aio;
  3240. #endif

  3241.     if (wev->timedout) {

  3242.         p->downstream_error = 1;
  3243.         c->timedout = 1;
  3244.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");

  3245.     } else {

  3246.         if (wev->delayed) {

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

  3249.             if (ngx_handle_write_event(wev, p->send_lowat) != NGX_OK) {
  3250.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3251.             }

  3252.             return;
  3253.         }

  3254.         if (ngx_event_pipe(p, 1) == NGX_ABORT) {
  3255.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3256.             return;
  3257.         }
  3258.     }

  3259.     ngx_http_upstream_process_request(r, u);
  3260. }


  3261. static void
  3262. ngx_http_upstream_process_upstream(ngx_http_request_t *r,
  3263.     ngx_http_upstream_t *u)
  3264. {
  3265.     ngx_event_t       *rev;
  3266.     ngx_event_pipe_t  *p;
  3267.     ngx_connection_t  *c;

  3268.     c = u->peer.connection;
  3269.     p = u->pipe;
  3270.     rev = c->read;

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

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

  3274.     if (rev->timedout) {

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

  3277.     } else {

  3278.         if (rev->delayed) {

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

  3281.             if (ngx_handle_read_event(rev, 0) != NGX_OK) {
  3282.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3283.             }

  3284.             return;
  3285.         }

  3286.         if (ngx_event_pipe(p, 0) == NGX_ABORT) {
  3287.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3288.             return;
  3289.         }
  3290.     }

  3291.     ngx_http_upstream_process_request(r, u);
  3292. }


  3293. static void
  3294. ngx_http_upstream_process_request(ngx_http_request_t *r,
  3295.     ngx_http_upstream_t *u)
  3296. {
  3297.     ngx_temp_file_t   *tf;
  3298.     ngx_event_pipe_t  *p;

  3299.     p = u->pipe;

  3300. #if (NGX_THREADS)

  3301.     if (p->writing && !p->aio) {

  3302.         /*
  3303.          * make sure to call ngx_event_pipe()
  3304.          * if there is an incomplete aio write
  3305.          */

  3306.         if (ngx_event_pipe(p, 1) == NGX_ABORT) {
  3307.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3308.             return;
  3309.         }
  3310.     }

  3311.     if (p->writing) {
  3312.         return;
  3313.     }

  3314. #endif

  3315.     if (u->peer.connection) {

  3316.         if (u->store) {

  3317.             if (p->upstream_eof || p->upstream_done) {

  3318.                 tf = p->temp_file;

  3319.                 if (u->headers_in.status_n == NGX_HTTP_OK
  3320.                     && (p->upstream_done || p->length == -1)
  3321.                     && (u->headers_in.content_length_n == -1
  3322.                         || u->headers_in.content_length_n == tf->offset))
  3323.                 {
  3324.                     ngx_http_upstream_store(r, u);
  3325.                 }
  3326.             }
  3327.         }

  3328. #if (NGX_HTTP_CACHE)

  3329.         if (u->cacheable) {

  3330.             if (p->upstream_done) {
  3331.                 ngx_http_file_cache_update(r, p->temp_file);

  3332.             } else if (p->upstream_eof) {

  3333.                 tf = p->temp_file;

  3334.                 if (p->length == -1
  3335.                     && (u->headers_in.content_length_n == -1
  3336.                         || u->headers_in.content_length_n
  3337.                            == tf->offset - (off_t) r->cache->body_start))
  3338.                 {
  3339.                     ngx_http_file_cache_update(r, tf);

  3340.                 } else {
  3341.                     ngx_http_file_cache_free(r->cache, tf);
  3342.                 }

  3343.             } else if (p->upstream_error) {
  3344.                 ngx_http_file_cache_free(r->cache, p->temp_file);
  3345.             }
  3346.         }

  3347. #endif

  3348.         if (p->upstream_done || p->upstream_eof || p->upstream_error) {
  3349.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3350.                            "http upstream exit: %p", p->out);

  3351.             if (p->upstream_done
  3352.                 || (p->upstream_eof && p->length == -1))
  3353.             {
  3354.                 ngx_http_upstream_finalize_request(r, u, 0);
  3355.                 return;
  3356.             }

  3357.             if (p->upstream_eof) {
  3358.                 ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3359.                               "upstream prematurely closed connection");
  3360.             }

  3361.             ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  3362.             return;
  3363.         }
  3364.     }

  3365.     if (p->downstream_error) {
  3366.         ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3367.                        "http upstream downstream error");

  3368.         if (!u->cacheable && !u->store && u->peer.connection) {
  3369.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3370.         }
  3371.     }
  3372. }


  3373. static void
  3374. ngx_http_upstream_store(ngx_http_request_t *r, ngx_http_upstream_t *u)
  3375. {
  3376.     size_t                  root;
  3377.     time_t                  lm;
  3378.     ngx_str_t               path;
  3379.     ngx_temp_file_t        *tf;
  3380.     ngx_ext_rename_file_t   ext;

  3381.     tf = u->pipe->temp_file;

  3382.     if (tf->file.fd == NGX_INVALID_FILE) {

  3383.         /* create file for empty 200 response */

  3384.         tf = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t));
  3385.         if (tf == NULL) {
  3386.             return;
  3387.         }

  3388.         tf->file.fd = NGX_INVALID_FILE;
  3389.         tf->file.log = r->connection->log;
  3390.         tf->path = u->conf->temp_path;
  3391.         tf->pool = r->pool;
  3392.         tf->persistent = 1;

  3393.         if (ngx_create_temp_file(&tf->file, tf->path, tf->pool,
  3394.                                  tf->persistent, tf->clean, tf->access)
  3395.             != NGX_OK)
  3396.         {
  3397.             return;
  3398.         }

  3399.         u->pipe->temp_file = tf;
  3400.     }

  3401.     ext.access = u->conf->store_access;
  3402.     ext.path_access = u->conf->store_access;
  3403.     ext.time = -1;
  3404.     ext.create_path = 1;
  3405.     ext.delete_file = 1;
  3406.     ext.log = r->connection->log;

  3407.     if (u->headers_in.last_modified) {

  3408.         lm = ngx_parse_http_time(u->headers_in.last_modified->value.data,
  3409.                                  u->headers_in.last_modified->value.len);

  3410.         if (lm != NGX_ERROR) {
  3411.             ext.time = lm;
  3412.             ext.fd = tf->file.fd;
  3413.         }
  3414.     }

  3415.     if (u->conf->store_lengths == NULL) {

  3416.         if (ngx_http_map_uri_to_path(r, &path, &root, 0) == NULL) {
  3417.             return;
  3418.         }

  3419.     } else {
  3420.         if (ngx_http_script_run(r, &path, u->conf->store_lengths->elts, 0,
  3421.                                 u->conf->store_values->elts)
  3422.             == NULL)
  3423.         {
  3424.             return;
  3425.         }
  3426.     }

  3427.     path.len--;

  3428.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3429.                    "upstream stores \"%s\" to \"%s\"",
  3430.                    tf->file.name.data, path.data);

  3431.     if (path.len == 0) {
  3432.         return;
  3433.     }

  3434.     (void) ngx_ext_rename_file(&tf->file.name, &path, &ext);

  3435.     u->store = 0;
  3436. }


  3437. static void
  3438. ngx_http_upstream_dummy_handler(ngx_http_request_t *r, ngx_http_upstream_t *u)
  3439. {
  3440.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3441.                    "http upstream dummy handler");
  3442. }


  3443. static void
  3444. ngx_http_upstream_next(ngx_http_request_t *r, ngx_http_upstream_t *u,
  3445.     ngx_uint_t ft_type)
  3446. {
  3447.     ngx_msec_t  timeout;
  3448.     ngx_uint_t  status, state;

  3449.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3450.                    "http next upstream, %xi", ft_type);

  3451.     if (u->peer.sockaddr) {

  3452.         if (u->peer.connection) {
  3453.             u->state->bytes_sent = u->peer.connection->sent;
  3454.         }

  3455.         if (ft_type == NGX_HTTP_UPSTREAM_FT_HTTP_403
  3456.             || ft_type == NGX_HTTP_UPSTREAM_FT_HTTP_404)
  3457.         {
  3458.             state = NGX_PEER_NEXT;

  3459.         } else {
  3460.             state = NGX_PEER_FAILED;
  3461.         }

  3462.         u->peer.free(&u->peer, u->peer.data, state);
  3463.         u->peer.sockaddr = NULL;

  3464. #if (NGX_HTTP_UPSTREAM_SID)
  3465.         u->peer.sid = NULL;
  3466. #endif
  3467.     }

  3468.     if (ft_type == NGX_HTTP_UPSTREAM_FT_TIMEOUT) {
  3469.         ngx_log_error(NGX_LOG_ERR, r->connection->log, NGX_ETIMEDOUT,
  3470.                       "upstream timed out");
  3471.     }

  3472.     if (u->peer.cached && ft_type == NGX_HTTP_UPSTREAM_FT_ERROR) {
  3473.         /* TODO: inform balancer instead */
  3474.         u->peer.tries++;
  3475.     }

  3476.     switch (ft_type) {

  3477.     case NGX_HTTP_UPSTREAM_FT_TIMEOUT:
  3478.     case NGX_HTTP_UPSTREAM_FT_HTTP_504:
  3479.         status = NGX_HTTP_GATEWAY_TIME_OUT;
  3480.         break;

  3481.     case NGX_HTTP_UPSTREAM_FT_HTTP_500:
  3482.         status = NGX_HTTP_INTERNAL_SERVER_ERROR;
  3483.         break;

  3484.     case NGX_HTTP_UPSTREAM_FT_HTTP_503:
  3485.         status = NGX_HTTP_SERVICE_UNAVAILABLE;
  3486.         break;

  3487.     case NGX_HTTP_UPSTREAM_FT_HTTP_403:
  3488.         status = NGX_HTTP_FORBIDDEN;
  3489.         break;

  3490.     case NGX_HTTP_UPSTREAM_FT_HTTP_404:
  3491.         status = NGX_HTTP_NOT_FOUND;
  3492.         break;

  3493.     case NGX_HTTP_UPSTREAM_FT_HTTP_429:
  3494.         status = NGX_HTTP_TOO_MANY_REQUESTS;
  3495.         break;

  3496.     /*
  3497.      * NGX_HTTP_UPSTREAM_FT_BUSY_LOCK and NGX_HTTP_UPSTREAM_FT_MAX_WAITING
  3498.      * never reach here
  3499.      */

  3500.     default:
  3501.         status = NGX_HTTP_BAD_GATEWAY;
  3502.     }

  3503.     if (r->connection->error) {
  3504.         ngx_http_upstream_finalize_request(r, u,
  3505.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  3506.         return;
  3507.     }

  3508.     u->state->status = status;

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

  3510.     if (u->request_sent
  3511.         && (r->method & (NGX_HTTP_POST|NGX_HTTP_LOCK|NGX_HTTP_PATCH)))
  3512.     {
  3513.         ft_type |= NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT;
  3514.     }

  3515.     if (u->peer.tries == 0
  3516.         || ((u->conf->next_upstream & ft_type) != ft_type)
  3517.         || (u->request_sent && r->request_body_no_buffering)
  3518.         || (timeout && ngx_current_msec - u->peer.start_time >= timeout))
  3519.     {
  3520. #if (NGX_HTTP_CACHE)

  3521.         if (u->cache_status == NGX_HTTP_CACHE_EXPIRED
  3522.             && ((u->conf->cache_use_stale & ft_type) || r->cache->stale_error))
  3523.         {
  3524.             ngx_int_t  rc;

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

  3526.             if (rc != NGX_OK) {
  3527.                 ngx_http_upstream_finalize_request(r, u, rc);
  3528.                 return;
  3529.             }

  3530.             u->cache_status = NGX_HTTP_CACHE_STALE;
  3531.             rc = ngx_http_upstream_cache_send(r, u);

  3532.             if (rc == NGX_DONE) {
  3533.                 return;
  3534.             }

  3535.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  3536.                 rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  3537.             }

  3538.             ngx_http_upstream_finalize_request(r, u, rc);
  3539.             return;
  3540.         }
  3541. #endif

  3542.         ngx_http_upstream_finalize_request(r, u, status);
  3543.         return;
  3544.     }

  3545.     if (u->peer.connection) {
  3546.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3547.                        "close http upstream connection: %d",
  3548.                        u->peer.connection->fd);
  3549. #if (NGX_HTTP_SSL)

  3550.         if (u->peer.connection->ssl) {
  3551.             u->peer.connection->ssl->no_wait_shutdown = 1;
  3552.             u->peer.connection->ssl->no_send_shutdown = 1;

  3553.             (void) ngx_ssl_shutdown(u->peer.connection);
  3554.         }
  3555. #endif

  3556.         if (u->peer.connection->pool) {
  3557.             ngx_destroy_pool(u->peer.connection->pool);
  3558.         }

  3559.         ngx_close_connection(u->peer.connection);
  3560.         u->peer.connection = NULL;
  3561.     }

  3562.     ngx_http_upstream_connect(r, u);
  3563. }


  3564. static void
  3565. ngx_http_upstream_cleanup(void *data)
  3566. {
  3567.     ngx_http_request_t *r = data;

  3568.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3569.                    "cleanup http upstream request: \"%V\"", &r->uri);

  3570.     ngx_http_upstream_finalize_request(r, r->upstream, NGX_DONE);
  3571. }


  3572. static void
  3573. ngx_http_upstream_finalize_request(ngx_http_request_t *r,
  3574.     ngx_http_upstream_t *u, ngx_int_t rc)
  3575. {
  3576.     ngx_uint_t  flush;

  3577.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3578.                    "finalize http upstream request: %i", rc);

  3579.     if (u->cleanup == NULL) {
  3580.         /* the request was already finalized */
  3581.         ngx_http_finalize_request(r, NGX_DONE);
  3582.         return;
  3583.     }

  3584.     *u->cleanup = NULL;
  3585.     u->cleanup = NULL;

  3586.     if (u->resolved && u->resolved->ctx) {
  3587.         ngx_resolve_name_done(u->resolved->ctx);
  3588.         u->resolved->ctx = NULL;
  3589.     }

  3590.     if (u->state && u->state->response_time == (ngx_msec_t) -1) {
  3591.         u->state->response_time = ngx_current_msec - u->start_time;

  3592.         if (u->pipe && u->pipe->read_length) {
  3593.             u->state->bytes_received += u->pipe->read_length
  3594.                                         - u->pipe->preread_size;
  3595.             u->state->response_length = u->pipe->read_length;
  3596.         }

  3597.         if (u->peer.connection) {
  3598.             u->state->bytes_sent = u->peer.connection->sent;
  3599.         }
  3600.     }

  3601.     u->finalize_request(r, rc);

  3602.     if (u->peer.free && u->peer.sockaddr) {
  3603.         u->peer.free(&u->peer, u->peer.data, 0);
  3604.         u->peer.sockaddr = NULL;

  3605. #if (NGX_HTTP_UPSTREAM_SID)
  3606.         u->peer.sid = NULL;
  3607. #endif
  3608.     }

  3609.     if (u->peer.connection) {

  3610. #if (NGX_HTTP_SSL)

  3611.         /* TODO: do not shutdown persistent connection */

  3612.         if (u->peer.connection->ssl) {

  3613.             /*
  3614.              * We send the "close notify" shutdown alert to the upstream only
  3615.              * and do not wait its "close notify" shutdown alert.
  3616.              * It is acceptable according to the TLS standard.
  3617.              */

  3618.             u->peer.connection->ssl->no_wait_shutdown = 1;

  3619.             (void) ngx_ssl_shutdown(u->peer.connection);
  3620.         }
  3621. #endif

  3622.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3623.                        "close http upstream connection: %d",
  3624.                        u->peer.connection->fd);

  3625.         if (u->peer.connection->pool) {
  3626.             ngx_destroy_pool(u->peer.connection->pool);
  3627.         }

  3628.         ngx_close_connection(u->peer.connection);
  3629.     }

  3630.     u->peer.connection = NULL;

  3631.     if (u->pipe) {
  3632.         u->pipe->upstream = NULL;
  3633.     }

  3634.     if (u->pipe && u->pipe->temp_file) {
  3635.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3636.                        "http upstream temp fd: %d",
  3637.                        u->pipe->temp_file->file.fd);
  3638.     }

  3639.     if (u->store && u->pipe && u->pipe->temp_file
  3640.         && u->pipe->temp_file->file.fd != NGX_INVALID_FILE)
  3641.     {
  3642.         if (ngx_delete_file(u->pipe->temp_file->file.name.data)
  3643.             == NGX_FILE_ERROR)
  3644.         {
  3645.             ngx_log_error(NGX_LOG_CRIT, r->connection->log, ngx_errno,
  3646.                           ngx_delete_file_n " \"%s\" failed",
  3647.                           u->pipe->temp_file->file.name.data);
  3648.         }
  3649.     }

  3650. #if (NGX_HTTP_CACHE)

  3651.     if (r->cache) {

  3652.         if (u->cacheable) {

  3653.             if (rc == NGX_HTTP_BAD_GATEWAY || rc == NGX_HTTP_GATEWAY_TIME_OUT) {
  3654.                 time_t  valid;

  3655.                 valid = ngx_http_file_cache_valid(u->conf->cache_valid, rc);

  3656.                 if (valid) {
  3657.                     r->cache->valid_sec = ngx_time() + valid;
  3658.                     r->cache->error = rc;
  3659.                 }
  3660.             }
  3661.         }

  3662.         ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  3663.     }

  3664. #endif

  3665.     r->read_event_handler = ngx_http_block_reading;

  3666.     if (rc == NGX_DECLINED) {
  3667.         return;
  3668.     }

  3669.     r->connection->log->action = "sending to client";

  3670.     if (!u->header_sent
  3671.         || rc == NGX_HTTP_REQUEST_TIME_OUT
  3672.         || rc == NGX_HTTP_CLIENT_CLOSED_REQUEST)
  3673.     {
  3674.         ngx_http_finalize_request(r, rc);
  3675.         return;
  3676.     }

  3677.     flush = 0;

  3678.     if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  3679.         rc = NGX_ERROR;
  3680.         flush = 1;
  3681.     }

  3682.     if (r->header_only
  3683.         || (u->pipe && u->pipe->downstream_error))
  3684.     {
  3685.         ngx_http_finalize_request(r, rc);
  3686.         return;
  3687.     }

  3688.     if (rc == 0) {

  3689.         if (ngx_http_upstream_process_trailers(r, u) != NGX_OK) {
  3690.             ngx_http_finalize_request(r, NGX_ERROR);
  3691.             return;
  3692.         }

  3693.         rc = ngx_http_send_special(r, NGX_HTTP_LAST);

  3694.     } else if (flush) {
  3695.         r->keepalive = 0;
  3696.         rc = ngx_http_send_special(r, NGX_HTTP_FLUSH);
  3697.     }

  3698.     ngx_http_finalize_request(r, rc);
  3699. }


  3700. static ngx_int_t
  3701. ngx_http_upstream_process_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  3702.     ngx_uint_t offset)
  3703. {
  3704.     ngx_table_elt_t  **ph;

  3705.     ph = (ngx_table_elt_t **) ((char *) &r->upstream->headers_in + offset);

  3706.     if (*ph) {
  3707.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3708.                       "upstream sent duplicate header line: \"%V: %V\", "
  3709.                       "previous value: \"%V: %V\", ignored",
  3710.                       &h->key, &h->value,
  3711.                       &(*ph)->key, &(*ph)->value);
  3712.         h->hash = 0;
  3713.         return NGX_OK;
  3714.     }

  3715.     *ph = h;
  3716.     h->next = NULL;

  3717.     return NGX_OK;
  3718. }


  3719. static ngx_int_t
  3720. ngx_http_upstream_process_multi_header_lines(ngx_http_request_t *r,
  3721.     ngx_table_elt_t *h, ngx_uint_t offset)
  3722. {
  3723.     ngx_table_elt_t  **ph;

  3724.     ph = (ngx_table_elt_t **) ((char *) &r->upstream->headers_in + offset);

  3725.     while (*ph) { ph = &(*ph)->next; }

  3726.     *ph = h;
  3727.     h->next = NULL;

  3728.     return NGX_OK;
  3729. }


  3730. static ngx_int_t
  3731. ngx_http_upstream_ignore_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  3732.     ngx_uint_t offset)
  3733. {
  3734.     return NGX_OK;
  3735. }


  3736. static ngx_int_t
  3737. ngx_http_upstream_process_content_length(ngx_http_request_t *r,
  3738.     ngx_table_elt_t *h, ngx_uint_t offset)
  3739. {
  3740.     ngx_http_upstream_t  *u;

  3741.     u = r->upstream;

  3742.     if (u->headers_in.content_length) {
  3743.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3744.                       "upstream sent duplicate header line: \"%V: %V\", "
  3745.                       "previous value: \"%V: %V\"",
  3746.                       &h->key, &h->value,
  3747.                       &u->headers_in.content_length->key,
  3748.                       &u->headers_in.content_length->value);
  3749.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3750.     }

  3751.     if (u->headers_in.transfer_encoding) {
  3752.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3753.                       "upstream sent \"Content-Length\" and "
  3754.                       "\"Transfer-Encoding\" headers at the same time");
  3755.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3756.     }

  3757.     h->next = NULL;
  3758.     u->headers_in.content_length = h;
  3759.     u->headers_in.content_length_n = ngx_atoof(h->value.data, h->value.len);

  3760.     if (u->headers_in.content_length_n == NGX_ERROR) {
  3761.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3762.                       "upstream sent invalid \"Content-Length\" header: "
  3763.                       "\"%V: %V\"", &h->key, &h->value);
  3764.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3765.     }

  3766.     return NGX_OK;
  3767. }


  3768. static ngx_int_t
  3769. ngx_http_upstream_process_last_modified(ngx_http_request_t *r,
  3770.     ngx_table_elt_t *h, ngx_uint_t offset)
  3771. {
  3772.     ngx_http_upstream_t  *u;

  3773.     u = r->upstream;

  3774.     if (u->headers_in.last_modified) {
  3775.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3776.                       "upstream sent duplicate header line: \"%V: %V\", "
  3777.                       "previous value: \"%V: %V\", ignored",
  3778.                       &h->key, &h->value,
  3779.                       &u->headers_in.last_modified->key,
  3780.                       &u->headers_in.last_modified->value);
  3781.         h->hash = 0;
  3782.         return NGX_OK;
  3783.     }

  3784.     h->next = NULL;
  3785.     u->headers_in.last_modified = h;
  3786.     u->headers_in.last_modified_time = ngx_parse_http_time(h->value.data,
  3787.                                                            h->value.len);

  3788.     return NGX_OK;
  3789. }


  3790. static ngx_int_t
  3791. ngx_http_upstream_process_set_cookie(ngx_http_request_t *r, ngx_table_elt_t *h,
  3792.     ngx_uint_t offset)
  3793. {
  3794.     ngx_table_elt_t      **ph;
  3795.     ngx_http_upstream_t   *u;

  3796.     u = r->upstream;
  3797.     ph = &u->headers_in.set_cookie;

  3798.     while (*ph) { ph = &(*ph)->next; }

  3799.     *ph = h;
  3800.     h->next = NULL;

  3801. #if (NGX_HTTP_CACHE)
  3802.     if (!(u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_SET_COOKIE)) {
  3803.         u->cacheable = 0;
  3804.     }
  3805. #endif

  3806.     return NGX_OK;
  3807. }


  3808. static ngx_int_t
  3809. ngx_http_upstream_process_cache_control(ngx_http_request_t *r,
  3810.     ngx_table_elt_t *h, ngx_uint_t offset)
  3811. {
  3812.     ngx_table_elt_t      **ph;
  3813.     ngx_http_upstream_t   *u;

  3814.     u = r->upstream;
  3815.     ph = &u->headers_in.cache_control;

  3816.     while (*ph) { ph = &(*ph)->next; }

  3817.     *ph = h;
  3818.     h->next = NULL;

  3819. #if (NGX_HTTP_CACHE)
  3820.     {
  3821.     u_char     *p, *start, *last;
  3822.     ngx_int_t   n;

  3823.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_CACHE_CONTROL) {
  3824.         return NGX_OK;
  3825.     }

  3826.     if (r->cache == NULL) {
  3827.         return NGX_OK;
  3828.     }

  3829.     start = h->value.data;
  3830.     last = start + h->value.len;

  3831.     if (r->cache->valid_sec != 0 && u->headers_in.x_accel_expires != NULL) {
  3832.         goto extensions;
  3833.     }

  3834.     if (ngx_strlcasestrn(start, last, (u_char *) "no-cache", 8 - 1) != NULL
  3835.         || ngx_strlcasestrn(start, last, (u_char *) "no-store", 8 - 1) != NULL
  3836.         || ngx_strlcasestrn(start, last, (u_char *) "private", 7 - 1) != NULL)
  3837.     {
  3838.         u->headers_in.no_cache = 1;
  3839.         return NGX_OK;
  3840.     }

  3841.     p = ngx_strlcasestrn(start, last, (u_char *) "s-maxage=", 9 - 1);
  3842.     offset = 9;

  3843.     if (p == NULL) {
  3844.         p = ngx_strlcasestrn(start, last, (u_char *) "max-age=", 8 - 1);
  3845.         offset = 8;
  3846.     }

  3847.     if (p) {
  3848.         n = ngx_http_upstream_process_delta_seconds(p + offset, last);

  3849.         if (n == NGX_ERROR) {
  3850.             u->cacheable = 0;
  3851.             return NGX_OK;
  3852.         }

  3853.         if (n == 0) {
  3854.             u->headers_in.no_cache = 1;
  3855.             return NGX_OK;
  3856.         }

  3857.         r->cache->valid_sec = ngx_min((ngx_uint_t) ngx_time() + n,
  3858.                                       NGX_MAX_INT_T_VALUE);
  3859.         u->headers_in.expired = 0;
  3860.     }

  3861. extensions:

  3862.     p = ngx_strlcasestrn(start, last, (u_char *) "stale-while-revalidate=",
  3863.                          23 - 1);

  3864.     if (p) {
  3865.         n = ngx_http_upstream_process_delta_seconds(p + 23, last);

  3866.         if (n == NGX_ERROR) {
  3867.             u->cacheable = 0;
  3868.             return NGX_OK;
  3869.         }

  3870.         r->cache->updating_sec = n;
  3871.         r->cache->error_sec = n;
  3872.     }

  3873.     p = ngx_strlcasestrn(start, last, (u_char *) "stale-if-error=", 15 - 1);

  3874.     if (p) {
  3875.         n = ngx_http_upstream_process_delta_seconds(p + 15, last);

  3876.         if (n == NGX_ERROR) {
  3877.             u->cacheable = 0;
  3878.             return NGX_OK;
  3879.         }

  3880.         r->cache->error_sec = n;
  3881.     }
  3882.     }
  3883. #endif

  3884.     return NGX_OK;
  3885. }


  3886. #if (NGX_HTTP_CACHE)

  3887. static ngx_int_t
  3888. ngx_http_upstream_process_delta_seconds(u_char *p, u_char *last)
  3889. {
  3890.     ngx_int_t  n, cutoff, cutlim;

  3891.     cutoff = NGX_MAX_INT_T_VALUE / 10;
  3892.     cutlim = NGX_MAX_INT_T_VALUE % 10;

  3893.     n = 0;

  3894.     for ( /* void */ ; p < last; p++) {
  3895.         if (*p == ',' || *p == ';' || *p == ' ') {
  3896.             break;
  3897.         }

  3898.         if (*p < '0' || *p > '9') {
  3899.             return NGX_ERROR;
  3900.         }

  3901.         if (n >= cutoff && (n > cutoff || *p - '0' > cutlim)) {
  3902.             n = NGX_MAX_INT_T_VALUE;
  3903.             break;
  3904.         }

  3905.         n = n * 10 + (*p - '0');
  3906.     }

  3907.     return n;
  3908. }

  3909. #endif


  3910. static ngx_int_t
  3911. ngx_http_upstream_process_expires(ngx_http_request_t *r, ngx_table_elt_t *h,
  3912.     ngx_uint_t offset)
  3913. {
  3914.     ngx_http_upstream_t  *u;

  3915.     u = r->upstream;

  3916.     if (u->headers_in.expires) {
  3917.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3918.                       "upstream sent duplicate header line: \"%V: %V\", "
  3919.                       "previous value: \"%V: %V\", ignored",
  3920.                       &h->key, &h->value,
  3921.                       &u->headers_in.expires->key,
  3922.                       &u->headers_in.expires->value);
  3923.         h->hash = 0;
  3924.         return NGX_OK;
  3925.     }

  3926.     u->headers_in.expires = h;
  3927.     h->next = NULL;

  3928. #if (NGX_HTTP_CACHE)
  3929.     {
  3930.     time_t  expires;

  3931.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_EXPIRES) {
  3932.         return NGX_OK;
  3933.     }

  3934.     if (r->cache == NULL) {
  3935.         return NGX_OK;
  3936.     }

  3937.     if (r->cache->valid_sec != 0) {
  3938.         return NGX_OK;
  3939.     }

  3940.     expires = ngx_parse_http_time(h->value.data, h->value.len);

  3941.     if (expires == NGX_ERROR || expires < ngx_time()) {
  3942.         u->headers_in.expired = 1;
  3943.         return NGX_OK;
  3944.     }

  3945.     r->cache->valid_sec = expires;
  3946.     }
  3947. #endif

  3948.     return NGX_OK;
  3949. }


  3950. static ngx_int_t
  3951. ngx_http_upstream_process_accel_expires(ngx_http_request_t *r,
  3952.     ngx_table_elt_t *h, ngx_uint_t offset)
  3953. {
  3954.     ngx_http_upstream_t  *u;

  3955.     u = r->upstream;

  3956.     if (u->headers_in.x_accel_expires) {
  3957.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3958.                       "upstream sent duplicate header line: \"%V: %V\", "
  3959.                       "previous value: \"%V: %V\", ignored",
  3960.                       &h->key, &h->value,
  3961.                       &u->headers_in.x_accel_expires->key,
  3962.                       &u->headers_in.x_accel_expires->value);
  3963.         h->hash = 0;
  3964.         return NGX_OK;
  3965.     }

  3966.     u->headers_in.x_accel_expires = h;
  3967.     h->next = NULL;

  3968. #if (NGX_HTTP_CACHE)
  3969.     {
  3970.     u_char     *p;
  3971.     size_t      len;
  3972.     ngx_int_t   n;

  3973.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_EXPIRES) {
  3974.         return NGX_OK;
  3975.     }

  3976.     if (r->cache == NULL) {
  3977.         return NGX_OK;
  3978.     }

  3979.     len = h->value.len;
  3980.     p = h->value.data;

  3981.     if (p[0] != '@') {
  3982.         n = ngx_atoi(p, len);

  3983.         switch (n) {
  3984.         case 0:
  3985.             u->cacheable = 0;
  3986.             /* fall through */

  3987.         case NGX_ERROR:
  3988.             return NGX_OK;

  3989.         default:
  3990.             r->cache->valid_sec = ngx_time() + n;
  3991.             u->headers_in.no_cache = 0;
  3992.             u->headers_in.expired = 0;
  3993.             return NGX_OK;
  3994.         }
  3995.     }

  3996.     p++;
  3997.     len--;

  3998.     n = ngx_atoi(p, len);

  3999.     if (n != NGX_ERROR) {
  4000.         r->cache->valid_sec = n;
  4001.         u->headers_in.no_cache = 0;
  4002.         u->headers_in.expired = 0;
  4003.     }
  4004.     }
  4005. #endif

  4006.     return NGX_OK;
  4007. }


  4008. static ngx_int_t
  4009. ngx_http_upstream_process_limit_rate(ngx_http_request_t *r, ngx_table_elt_t *h,
  4010.     ngx_uint_t offset)
  4011. {
  4012.     ngx_int_t             n;
  4013.     ngx_http_upstream_t  *u;

  4014.     u = r->upstream;

  4015.     if (u->headers_in.x_accel_limit_rate) {
  4016.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  4017.                       "upstream sent duplicate header line: \"%V: %V\", "
  4018.                       "previous value: \"%V: %V\", ignored",
  4019.                       &h->key, &h->value,
  4020.                       &u->headers_in.x_accel_limit_rate->key,
  4021.                       &u->headers_in.x_accel_limit_rate->value);
  4022.         h->hash = 0;
  4023.         return NGX_OK;
  4024.     }

  4025.     u->headers_in.x_accel_limit_rate = h;
  4026.     h->next = NULL;

  4027.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_LIMIT_RATE) {
  4028.         return NGX_OK;
  4029.     }

  4030.     n = ngx_atoi(h->value.data, h->value.len);

  4031.     if (n != NGX_ERROR) {
  4032.         r->limit_rate = (size_t) n;
  4033.         r->limit_rate_set = 1;
  4034.     }

  4035.     return NGX_OK;
  4036. }


  4037. static ngx_int_t
  4038. ngx_http_upstream_process_buffering(ngx_http_request_t *r, ngx_table_elt_t *h,
  4039.     ngx_uint_t offset)
  4040. {
  4041.     u_char                c0, c1, c2;
  4042.     ngx_http_upstream_t  *u;

  4043.     u = r->upstream;

  4044.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_BUFFERING) {
  4045.         return NGX_OK;
  4046.     }

  4047.     if (u->conf->change_buffering) {

  4048.         if (h->value.len == 2) {
  4049.             c0 = ngx_tolower(h->value.data[0]);
  4050.             c1 = ngx_tolower(h->value.data[1]);

  4051.             if (c0 == 'n' && c1 == 'o') {
  4052.                 u->buffering = 0;
  4053.             }

  4054.         } else if (h->value.len == 3) {
  4055.             c0 = ngx_tolower(h->value.data[0]);
  4056.             c1 = ngx_tolower(h->value.data[1]);
  4057.             c2 = ngx_tolower(h->value.data[2]);

  4058.             if (c0 == 'y' && c1 == 'e' && c2 == 's') {
  4059.                 u->buffering = 1;
  4060.             }
  4061.         }
  4062.     }

  4063.     return NGX_OK;
  4064. }


  4065. static ngx_int_t
  4066. ngx_http_upstream_process_charset(ngx_http_request_t *r, ngx_table_elt_t *h,
  4067.     ngx_uint_t offset)
  4068. {
  4069.     ngx_http_upstream_t  *u;

  4070.     u = r->upstream;

  4071.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_CHARSET) {
  4072.         return NGX_OK;
  4073.     }

  4074.     r->headers_out.override_charset = &h->value;

  4075.     return NGX_OK;
  4076. }


  4077. static ngx_int_t
  4078. ngx_http_upstream_process_connection(ngx_http_request_t *r, ngx_table_elt_t *h,
  4079.     ngx_uint_t offset)
  4080. {
  4081.     ngx_table_elt_t      **ph;
  4082.     ngx_http_upstream_t   *u;

  4083.     u = r->upstream;
  4084.     ph = &u->headers_in.connection;

  4085.     while (*ph) { ph = &(*ph)->next; }

  4086.     *ph = h;
  4087.     h->next = NULL;

  4088.     if (ngx_strlcasestrn(h->value.data, h->value.data + h->value.len,
  4089.                          (u_char *) "close", 5 - 1)
  4090.         != NULL)
  4091.     {
  4092.         u->headers_in.connection_close = 1;
  4093.     }

  4094.     return NGX_OK;
  4095. }


  4096. static ngx_int_t
  4097. ngx_http_upstream_process_transfer_encoding(ngx_http_request_t *r,
  4098.     ngx_table_elt_t *h, ngx_uint_t offset)
  4099. {
  4100.     ngx_http_upstream_t  *u;

  4101.     u = r->upstream;

  4102.     if (u->headers_in.transfer_encoding) {
  4103.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4104.                       "upstream sent duplicate header line: \"%V: %V\", "
  4105.                       "previous value: \"%V: %V\"",
  4106.                       &h->key, &h->value,
  4107.                       &u->headers_in.transfer_encoding->key,
  4108.                       &u->headers_in.transfer_encoding->value);
  4109.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4110.     }

  4111.     if (u->headers_in.content_length) {
  4112.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4113.                       "upstream sent \"Content-Length\" and "
  4114.                       "\"Transfer-Encoding\" headers at the same time");
  4115.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4116.     }

  4117.     u->headers_in.transfer_encoding = h;
  4118.     h->next = NULL;

  4119.     if (h->value.len == 7
  4120.         && ngx_strncasecmp(h->value.data, (u_char *) "chunked", 7) == 0)
  4121.     {
  4122.         u->headers_in.chunked = 1;

  4123.     } else {
  4124.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4125.                       "upstream sent unknown \"Transfer-Encoding\": \"%V\"",
  4126.                       &h->value);
  4127.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4128.     }

  4129.     return NGX_OK;
  4130. }


  4131. static ngx_int_t
  4132. ngx_http_upstream_process_vary(ngx_http_request_t *r,
  4133.     ngx_table_elt_t *h, ngx_uint_t offset)
  4134. {
  4135.     ngx_table_elt_t      **ph;
  4136.     ngx_http_upstream_t   *u;

  4137.     u = r->upstream;
  4138.     ph = &u->headers_in.vary;

  4139.     while (*ph) { ph = &(*ph)->next; }

  4140.     *ph = h;
  4141.     h->next = NULL;

  4142. #if (NGX_HTTP_CACHE)
  4143.     {
  4144.     u_char     *p;
  4145.     size_t      len;
  4146.     ngx_str_t   vary;

  4147.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_VARY) {
  4148.         return NGX_OK;
  4149.     }

  4150.     if (r->cache == NULL || !u->cacheable) {
  4151.         return NGX_OK;
  4152.     }

  4153.     if (h->value.len == 1 && h->value.data[0] == '*') {
  4154.         u->cacheable = 0;
  4155.         return NGX_OK;
  4156.     }

  4157.     if (u->headers_in.vary->next) {

  4158.         len = 0;

  4159.         for (h = u->headers_in.vary; h; h = h->next) {
  4160.             len += h->value.len + 2;
  4161.         }

  4162.         len -= 2;

  4163.         p = ngx_pnalloc(r->pool, len);
  4164.         if (p == NULL) {
  4165.             return NGX_ERROR;
  4166.         }

  4167.         vary.len = len;
  4168.         vary.data = p;

  4169.         for (h = u->headers_in.vary; h; h = h->next) {
  4170.             p = ngx_copy(p, h->value.data, h->value.len);

  4171.             if (h->next == NULL) {
  4172.                 break;
  4173.             }

  4174.             *p++ = ','; *p++ = ' ';
  4175.         }

  4176.     } else {
  4177.         vary = h->value;
  4178.     }

  4179.     if (vary.len > NGX_HTTP_CACHE_VARY_LEN) {
  4180.         u->cacheable = 0;
  4181.     }

  4182.     r->cache->vary = vary;
  4183.     }
  4184. #endif

  4185.     return NGX_OK;
  4186. }


  4187. static ngx_int_t
  4188. ngx_http_upstream_copy_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  4189.     ngx_uint_t offset)
  4190. {
  4191.     ngx_table_elt_t  *ho, **ph;

  4192.     ho = ngx_list_push(&r->headers_out.headers);
  4193.     if (ho == NULL) {
  4194.         return NGX_ERROR;
  4195.     }

  4196.     *ho = *h;

  4197.     if (offset) {
  4198.         ph = (ngx_table_elt_t **) ((char *) &r->headers_out + offset);
  4199.         *ph = ho;
  4200.         ho->next = NULL;
  4201.     }

  4202.     return NGX_OK;
  4203. }


  4204. static ngx_int_t
  4205. ngx_http_upstream_copy_multi_header_lines(ngx_http_request_t *r,
  4206.     ngx_table_elt_t *h, ngx_uint_t offset)
  4207. {
  4208.     ngx_table_elt_t  *ho, **ph;

  4209.     ho = ngx_list_push(&r->headers_out.headers);
  4210.     if (ho == NULL) {
  4211.         return NGX_ERROR;
  4212.     }

  4213.     *ho = *h;

  4214.     ph = (ngx_table_elt_t **) ((char *) &r->headers_out + offset);

  4215.     while (*ph) { ph = &(*ph)->next; }

  4216.     *ph = ho;
  4217.     ho->next = NULL;

  4218.     return NGX_OK;
  4219. }


  4220. static ngx_int_t
  4221. ngx_http_upstream_copy_content_type(ngx_http_request_t *r, ngx_table_elt_t *h,
  4222.     ngx_uint_t offset)
  4223. {
  4224.     u_char  *p, *last;

  4225.     r->headers_out.content_type_len = h->value.len;
  4226.     r->headers_out.content_type = h->value;
  4227.     r->headers_out.content_type_lowcase = NULL;

  4228.     for (p = h->value.data; *p; p++) {

  4229.         if (*p != ';') {
  4230.             continue;
  4231.         }

  4232.         last = p;

  4233.         while (*++p == ' ') { /* void */ }

  4234.         if (*p == '\0') {
  4235.             return NGX_OK;
  4236.         }

  4237.         if (ngx_strncasecmp(p, (u_char *) "charset=", 8) != 0) {
  4238.             continue;
  4239.         }

  4240.         p += 8;

  4241.         r->headers_out.content_type_len = last - h->value.data;

  4242.         if (*p == '"') {
  4243.             p++;
  4244.         }

  4245.         last = h->value.data + h->value.len;

  4246.         if (last > p && *(last - 1) == '"') {
  4247.             last--;
  4248.         }

  4249.         r->headers_out.charset.len = last - p;
  4250.         r->headers_out.charset.data = p;

  4251.         return NGX_OK;
  4252.     }

  4253.     return NGX_OK;
  4254. }


  4255. static ngx_int_t
  4256. ngx_http_upstream_copy_last_modified(ngx_http_request_t *r, ngx_table_elt_t *h,
  4257.     ngx_uint_t offset)
  4258. {
  4259.     ngx_table_elt_t  *ho;

  4260.     ho = ngx_list_push(&r->headers_out.headers);
  4261.     if (ho == NULL) {
  4262.         return NGX_ERROR;
  4263.     }

  4264.     *ho = *h;
  4265.     ho->next = NULL;

  4266.     r->headers_out.last_modified = ho;
  4267.     r->headers_out.last_modified_time =
  4268.                                     r->upstream->headers_in.last_modified_time;

  4269.     return NGX_OK;
  4270. }


  4271. static ngx_int_t
  4272. ngx_http_upstream_rewrite_location(ngx_http_request_t *r, ngx_table_elt_t *h,
  4273.     ngx_uint_t offset)
  4274. {
  4275.     ngx_int_t         rc;
  4276.     ngx_table_elt_t  *ho;

  4277.     ho = ngx_list_push(&r->headers_out.headers);
  4278.     if (ho == NULL) {
  4279.         return NGX_ERROR;
  4280.     }

  4281.     *ho = *h;
  4282.     ho->next = NULL;

  4283.     if (r->upstream->rewrite_redirect) {
  4284.         rc = r->upstream->rewrite_redirect(r, ho, 0);

  4285.         if (rc == NGX_DECLINED) {
  4286.             return NGX_OK;
  4287.         }

  4288.         if (rc == NGX_OK) {
  4289.             r->headers_out.location = ho;

  4290.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4291.                            "rewritten location: \"%V\"", &ho->value);
  4292.         }

  4293.         return rc;
  4294.     }

  4295.     if (ho->value.data[0] != '/') {
  4296.         r->headers_out.location = ho;
  4297.     }

  4298.     /*
  4299.      * we do not set r->headers_out.location here to avoid handling
  4300.      * relative redirects in ngx_http_header_filter()
  4301.      */

  4302.     return NGX_OK;
  4303. }


  4304. static ngx_int_t
  4305. ngx_http_upstream_rewrite_refresh(ngx_http_request_t *r, ngx_table_elt_t *h,
  4306.     ngx_uint_t offset)
  4307. {
  4308.     u_char           *p;
  4309.     ngx_int_t         rc;
  4310.     ngx_table_elt_t  *ho;

  4311.     ho = ngx_list_push(&r->headers_out.headers);
  4312.     if (ho == NULL) {
  4313.         return NGX_ERROR;
  4314.     }

  4315.     *ho = *h;
  4316.     ho->next = NULL;

  4317.     if (r->upstream->rewrite_redirect) {

  4318.         p = ngx_strcasestrn(ho->value.data, "url=", 4 - 1);

  4319.         if (p) {
  4320.             rc = r->upstream->rewrite_redirect(r, ho, p + 4 - ho->value.data);

  4321.         } else {
  4322.             return NGX_OK;
  4323.         }

  4324.         if (rc == NGX_DECLINED) {
  4325.             return NGX_OK;
  4326.         }

  4327.         if (rc == NGX_OK) {
  4328.             r->headers_out.refresh = ho;

  4329.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4330.                            "rewritten refresh: \"%V\"", &ho->value);
  4331.         }

  4332.         return rc;
  4333.     }

  4334.     r->headers_out.refresh = ho;

  4335.     return NGX_OK;
  4336. }


  4337. static ngx_int_t
  4338. ngx_http_upstream_rewrite_set_cookie(ngx_http_request_t *r, ngx_table_elt_t *h,
  4339.     ngx_uint_t offset)
  4340. {
  4341.     ngx_int_t         rc;
  4342.     ngx_table_elt_t  *ho;

  4343.     ho = ngx_list_push(&r->headers_out.headers);
  4344.     if (ho == NULL) {
  4345.         return NGX_ERROR;
  4346.     }

  4347.     *ho = *h;
  4348.     ho->next = NULL;

  4349.     if (r->upstream->rewrite_cookie) {
  4350.         rc = r->upstream->rewrite_cookie(r, ho);

  4351.         if (rc == NGX_DECLINED) {
  4352.             return NGX_OK;
  4353.         }

  4354. #if (NGX_DEBUG)
  4355.         if (rc == NGX_OK) {
  4356.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4357.                            "rewritten cookie: \"%V\"", &ho->value);
  4358.         }
  4359. #endif

  4360.         return rc;
  4361.     }

  4362.     return NGX_OK;
  4363. }


  4364. static ngx_int_t
  4365. ngx_http_upstream_copy_allow_ranges(ngx_http_request_t *r,
  4366.     ngx_table_elt_t *h, ngx_uint_t offset)
  4367. {
  4368.     ngx_table_elt_t  *ho;

  4369.     if (r->upstream->conf->force_ranges) {
  4370.         return NGX_OK;
  4371.     }

  4372. #if (NGX_HTTP_CACHE)

  4373.     if (r->cached) {
  4374.         r->allow_ranges = 1;
  4375.         return NGX_OK;
  4376.     }

  4377.     if (r->upstream->cacheable) {
  4378.         r->allow_ranges = 1;
  4379.         r->single_range = 1;
  4380.         return NGX_OK;
  4381.     }

  4382. #endif

  4383.     ho = ngx_list_push(&r->headers_out.headers);
  4384.     if (ho == NULL) {
  4385.         return NGX_ERROR;
  4386.     }

  4387.     *ho = *h;
  4388.     ho->next = NULL;

  4389.     r->headers_out.accept_ranges = ho;

  4390.     return NGX_OK;
  4391. }


  4392. static ngx_int_t
  4393. ngx_http_upstream_copy_upgrade(ngx_http_request_t *r, ngx_table_elt_t *h,
  4394.     ngx_uint_t offset)
  4395. {
  4396.     ngx_table_elt_t  *ho;

  4397.     if (r->http_version >= NGX_HTTP_VERSION_20) {
  4398.         return NGX_OK;
  4399.     }

  4400.     ho = ngx_list_push(&r->headers_out.headers);
  4401.     if (ho == NULL) {
  4402.         return NGX_ERROR;
  4403.     }

  4404.     *ho = *h;

  4405.     return NGX_OK;
  4406. }


  4407. static ngx_int_t
  4408. ngx_http_upstream_add_variables(ngx_conf_t *cf)
  4409. {
  4410.     ngx_http_variable_t  *var, *v;

  4411.     for (v = ngx_http_upstream_vars; v->name.len; v++) {
  4412.         var = ngx_http_add_variable(cf, &v->name, v->flags);
  4413.         if (var == NULL) {
  4414.             return NGX_ERROR;
  4415.         }

  4416.         var->get_handler = v->get_handler;
  4417.         var->data = v->data;
  4418.     }

  4419.     return NGX_OK;
  4420. }


  4421. static ngx_int_t
  4422. ngx_http_upstream_addr_variable(ngx_http_request_t *r,
  4423.     ngx_http_variable_value_t *v, uintptr_t data)
  4424. {
  4425.     u_char                     *p;
  4426.     size_t                      len;
  4427.     ngx_uint_t                  i;
  4428.     ngx_http_upstream_state_t  *state;

  4429.     v->valid = 1;
  4430.     v->no_cacheable = 0;
  4431.     v->not_found = 0;

  4432.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4433.         v->not_found = 1;
  4434.         return NGX_OK;
  4435.     }

  4436.     len = 0;
  4437.     state = r->upstream_states->elts;

  4438.     for (i = 0; i < r->upstream_states->nelts; i++) {
  4439.         if (state[i].peer) {
  4440.             len += state[i].peer->len + 2;

  4441.         } else {
  4442.             len += 3;
  4443.         }
  4444.     }

  4445.     p = ngx_pnalloc(r->pool, len);
  4446.     if (p == NULL) {
  4447.         return NGX_ERROR;
  4448.     }

  4449.     v->data = p;

  4450.     i = 0;

  4451.     for ( ;; ) {
  4452.         if (state[i].peer) {
  4453.             p = ngx_cpymem(p, state[i].peer->data, state[i].peer->len);
  4454.         }

  4455.         if (++i == r->upstream_states->nelts) {
  4456.             break;
  4457.         }

  4458.         if (state[i].peer) {
  4459.             *p++ = ',';
  4460.             *p++ = ' ';

  4461.         } else {
  4462.             *p++ = ' ';
  4463.             *p++ = ':';
  4464.             *p++ = ' ';

  4465.             if (++i == r->upstream_states->nelts) {
  4466.                 break;
  4467.             }

  4468.             continue;
  4469.         }
  4470.     }

  4471.     v->len = p - v->data;

  4472.     return NGX_OK;
  4473. }


  4474. static ngx_int_t
  4475. ngx_http_upstream_status_variable(ngx_http_request_t *r,
  4476.     ngx_http_variable_value_t *v, uintptr_t data)
  4477. {
  4478.     u_char                     *p;
  4479.     size_t                      len;
  4480.     ngx_uint_t                  i;
  4481.     ngx_http_upstream_state_t  *state;

  4482.     v->valid = 1;
  4483.     v->no_cacheable = 0;
  4484.     v->not_found = 0;

  4485.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4486.         v->not_found = 1;
  4487.         return NGX_OK;
  4488.     }

  4489.     len = r->upstream_states->nelts * (3 + 2);

  4490.     p = ngx_pnalloc(r->pool, len);
  4491.     if (p == NULL) {
  4492.         return NGX_ERROR;
  4493.     }

  4494.     v->data = p;

  4495.     i = 0;
  4496.     state = r->upstream_states->elts;

  4497.     for ( ;; ) {
  4498.         if (state[i].status) {
  4499.             p = ngx_sprintf(p, "%ui", state[i].status);

  4500.         } else {
  4501.             *p++ = '-';
  4502.         }

  4503.         if (++i == r->upstream_states->nelts) {
  4504.             break;
  4505.         }

  4506.         if (state[i].peer) {
  4507.             *p++ = ',';
  4508.             *p++ = ' ';

  4509.         } else {
  4510.             *p++ = ' ';
  4511.             *p++ = ':';
  4512.             *p++ = ' ';

  4513.             if (++i == r->upstream_states->nelts) {
  4514.                 break;
  4515.             }

  4516.             continue;
  4517.         }
  4518.     }

  4519.     v->len = p - v->data;

  4520.     return NGX_OK;
  4521. }


  4522. static ngx_int_t
  4523. ngx_http_upstream_response_time_variable(ngx_http_request_t *r,
  4524.     ngx_http_variable_value_t *v, uintptr_t data)
  4525. {
  4526.     u_char                     *p;
  4527.     size_t                      len;
  4528.     ngx_uint_t                  i;
  4529.     ngx_msec_int_t              ms;
  4530.     ngx_http_upstream_state_t  *state;

  4531.     v->valid = 1;
  4532.     v->no_cacheable = 0;
  4533.     v->not_found = 0;

  4534.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4535.         v->not_found = 1;
  4536.         return NGX_OK;
  4537.     }

  4538.     len = r->upstream_states->nelts * (NGX_TIME_T_LEN + 4 + 2);

  4539.     p = ngx_pnalloc(r->pool, len);
  4540.     if (p == NULL) {
  4541.         return NGX_ERROR;
  4542.     }

  4543.     v->data = p;

  4544.     i = 0;
  4545.     state = r->upstream_states->elts;

  4546.     for ( ;; ) {

  4547.         if (data == 1) {
  4548.             ms = state[i].header_time;

  4549.         } else if (data == 2) {
  4550.             ms = state[i].connect_time;

  4551.         } else {
  4552.             ms = state[i].response_time;
  4553.         }

  4554.         if (ms != -1) {
  4555.             ms = ngx_max(ms, 0);
  4556.             p = ngx_sprintf(p, "%T.%03M", (time_t) ms / 1000, ms % 1000);

  4557.         } else {
  4558.             *p++ = '-';
  4559.         }

  4560.         if (++i == r->upstream_states->nelts) {
  4561.             break;
  4562.         }

  4563.         if (state[i].peer) {
  4564.             *p++ = ',';
  4565.             *p++ = ' ';

  4566.         } else {
  4567.             *p++ = ' ';
  4568.             *p++ = ':';
  4569.             *p++ = ' ';

  4570.             if (++i == r->upstream_states->nelts) {
  4571.                 break;
  4572.             }

  4573.             continue;
  4574.         }
  4575.     }

  4576.     v->len = p - v->data;

  4577.     return NGX_OK;
  4578. }


  4579. static ngx_int_t
  4580. ngx_http_upstream_response_length_variable(ngx_http_request_t *r,
  4581.     ngx_http_variable_value_t *v, uintptr_t data)
  4582. {
  4583.     u_char                     *p;
  4584.     size_t                      len;
  4585.     ngx_uint_t                  i;
  4586.     ngx_http_upstream_state_t  *state;

  4587.     v->valid = 1;
  4588.     v->no_cacheable = 0;
  4589.     v->not_found = 0;

  4590.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4591.         v->not_found = 1;
  4592.         return NGX_OK;
  4593.     }

  4594.     len = r->upstream_states->nelts * (NGX_OFF_T_LEN + 2);

  4595.     p = ngx_pnalloc(r->pool, len);
  4596.     if (p == NULL) {
  4597.         return NGX_ERROR;
  4598.     }

  4599.     v->data = p;

  4600.     i = 0;
  4601.     state = r->upstream_states->elts;

  4602.     for ( ;; ) {

  4603.         if (data == 1) {
  4604.             p = ngx_sprintf(p, "%O", state[i].bytes_received);

  4605.         } else if (data == 2) {
  4606.             p = ngx_sprintf(p, "%O", state[i].bytes_sent);

  4607.         } else {
  4608.             p = ngx_sprintf(p, "%O", state[i].response_length);
  4609.         }

  4610.         if (++i == r->upstream_states->nelts) {
  4611.             break;
  4612.         }

  4613.         if (state[i].peer) {
  4614.             *p++ = ',';
  4615.             *p++ = ' ';

  4616.         } else {
  4617.             *p++ = ' ';
  4618.             *p++ = ':';
  4619.             *p++ = ' ';

  4620.             if (++i == r->upstream_states->nelts) {
  4621.                 break;
  4622.             }

  4623.             continue;
  4624.         }
  4625.     }

  4626.     v->len = p - v->data;

  4627.     return NGX_OK;
  4628. }


  4629. static ngx_int_t
  4630. ngx_http_upstream_header_variable(ngx_http_request_t *r,
  4631.     ngx_http_variable_value_t *v, uintptr_t data)
  4632. {
  4633.     if (r->upstream == NULL) {
  4634.         v->not_found = 1;
  4635.         return NGX_OK;
  4636.     }

  4637.     return ngx_http_variable_unknown_header(r, v, (ngx_str_t *) data,
  4638.                                          &r->upstream->headers_in.headers.part,
  4639.                                          sizeof("upstream_http_") - 1);
  4640. }


  4641. static ngx_int_t
  4642. ngx_http_upstream_trailer_variable(ngx_http_request_t *r,
  4643.     ngx_http_variable_value_t *v, uintptr_t data)
  4644. {
  4645.     if (r->upstream == NULL) {
  4646.         v->not_found = 1;
  4647.         return NGX_OK;
  4648.     }

  4649.     return ngx_http_variable_unknown_header(r, v, (ngx_str_t *) data,
  4650.                                         &r->upstream->headers_in.trailers.part,
  4651.                                         sizeof("upstream_trailer_") - 1);
  4652. }


  4653. static ngx_int_t
  4654. ngx_http_upstream_cookie_variable(ngx_http_request_t *r,
  4655.     ngx_http_variable_value_t *v, uintptr_t data)
  4656. {
  4657.     ngx_str_t  *name = (ngx_str_t *) data;

  4658.     ngx_str_t   cookie, s;

  4659.     if (r->upstream == NULL) {
  4660.         v->not_found = 1;
  4661.         return NGX_OK;
  4662.     }

  4663.     s.len = name->len - (sizeof("upstream_cookie_") - 1);
  4664.     s.data = name->data + sizeof("upstream_cookie_") - 1;

  4665.     if (ngx_http_parse_set_cookie_lines(r, r->upstream->headers_in.set_cookie,
  4666.                                         &s, &cookie)
  4667.         == NULL)
  4668.     {
  4669.         v->not_found = 1;
  4670.         return NGX_OK;
  4671.     }

  4672.     v->len = cookie.len;
  4673.     v->valid = 1;
  4674.     v->no_cacheable = 0;
  4675.     v->not_found = 0;
  4676.     v->data = cookie.data;

  4677.     return NGX_OK;
  4678. }


  4679. #if (NGX_HTTP_CACHE)

  4680. static ngx_int_t
  4681. ngx_http_upstream_cache_status(ngx_http_request_t *r,
  4682.     ngx_http_variable_value_t *v, uintptr_t data)
  4683. {
  4684.     ngx_uint_t  n;

  4685.     if (r->upstream == NULL || r->upstream->cache_status == 0) {
  4686.         v->not_found = 1;
  4687.         return NGX_OK;
  4688.     }

  4689.     n = r->upstream->cache_status - 1;

  4690.     v->valid = 1;
  4691.     v->no_cacheable = 0;
  4692.     v->not_found = 0;
  4693.     v->len = ngx_http_cache_status[n].len;
  4694.     v->data = ngx_http_cache_status[n].data;

  4695.     return NGX_OK;
  4696. }


  4697. static ngx_int_t
  4698. ngx_http_upstream_cache_last_modified(ngx_http_request_t *r,
  4699.     ngx_http_variable_value_t *v, uintptr_t data)
  4700. {
  4701.     u_char  *p;

  4702.     if (r->upstream == NULL
  4703.         || !r->upstream->conf->cache_revalidate
  4704.         || r->upstream->cache_status != NGX_HTTP_CACHE_EXPIRED
  4705.         || r->cache->last_modified == -1)
  4706.     {
  4707.         v->not_found = 1;
  4708.         return NGX_OK;
  4709.     }

  4710.     p = ngx_pnalloc(r->pool, sizeof("Mon, 28 Sep 1970 06:00:00 GMT") - 1);
  4711.     if (p == NULL) {
  4712.         return NGX_ERROR;
  4713.     }

  4714.     v->len = ngx_http_time(p, r->cache->last_modified) - p;
  4715.     v->valid = 1;
  4716.     v->no_cacheable = 0;
  4717.     v->not_found = 0;
  4718.     v->data = p;

  4719.     return NGX_OK;
  4720. }


  4721. static ngx_int_t
  4722. ngx_http_upstream_cache_etag(ngx_http_request_t *r,
  4723.     ngx_http_variable_value_t *v, uintptr_t data)
  4724. {
  4725.     if (r->upstream == NULL
  4726.         || !r->upstream->conf->cache_revalidate
  4727.         || r->upstream->cache_status != NGX_HTTP_CACHE_EXPIRED
  4728.         || r->cache->etag.len == 0)
  4729.     {
  4730.         v->not_found = 1;
  4731.         return NGX_OK;
  4732.     }

  4733.     v->valid = 1;
  4734.     v->no_cacheable = 0;
  4735.     v->not_found = 0;
  4736.     v->len = r->cache->etag.len;
  4737.     v->data = r->cache->etag.data;

  4738.     return NGX_OK;
  4739. }

  4740. #endif


  4741. static char *
  4742. ngx_http_upstream(ngx_conf_t *cf, ngx_command_t *cmd, void *dummy)
  4743. {
  4744.     char                          *rv;
  4745.     void                          *mconf;
  4746.     ngx_str_t                     *value;
  4747.     ngx_url_t                      u;
  4748.     ngx_uint_t                     m;
  4749.     ngx_conf_t                     pcf;
  4750.     ngx_http_module_t             *module;
  4751.     ngx_http_conf_ctx_t           *ctx, *http_ctx;
  4752.     ngx_http_upstream_srv_conf_t  *uscf;

  4753.     ngx_memzero(&u, sizeof(ngx_url_t));

  4754.     value = cf->args->elts;
  4755.     u.host = value[1];
  4756.     u.no_resolve = 1;
  4757.     u.no_port = 1;

  4758.     uscf = ngx_http_upstream_add(cf, &u, NGX_HTTP_UPSTREAM_CREATE
  4759.                                          |NGX_HTTP_UPSTREAM_MODIFY
  4760.                                          |NGX_HTTP_UPSTREAM_WEIGHT
  4761.                                          |NGX_HTTP_UPSTREAM_MAX_CONNS
  4762.                                          |NGX_HTTP_UPSTREAM_MAX_FAILS
  4763.                                          |NGX_HTTP_UPSTREAM_FAIL_TIMEOUT
  4764.                                          |NGX_HTTP_UPSTREAM_DOWN
  4765.                                          |NGX_HTTP_UPSTREAM_BACKUP);
  4766.     if (uscf == NULL) {
  4767.         return NGX_CONF_ERROR;
  4768.     }


  4769.     ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_conf_ctx_t));
  4770.     if (ctx == NULL) {
  4771.         return NGX_CONF_ERROR;
  4772.     }

  4773.     http_ctx = cf->ctx;
  4774.     ctx->main_conf = http_ctx->main_conf;

  4775.     /* the upstream{}'s srv_conf */

  4776.     ctx->srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  4777.     if (ctx->srv_conf == NULL) {
  4778.         return NGX_CONF_ERROR;
  4779.     }

  4780.     ctx->srv_conf[ngx_http_upstream_module.ctx_index] = uscf;

  4781.     uscf->srv_conf = ctx->srv_conf;


  4782.     /* the upstream{}'s loc_conf */

  4783.     ctx->loc_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  4784.     if (ctx->loc_conf == NULL) {
  4785.         return NGX_CONF_ERROR;
  4786.     }

  4787.     for (m = 0; cf->cycle->modules[m]; m++) {
  4788.         if (cf->cycle->modules[m]->type != NGX_HTTP_MODULE) {
  4789.             continue;
  4790.         }

  4791.         module = cf->cycle->modules[m]->ctx;

  4792.         if (module->create_srv_conf) {
  4793.             mconf = module->create_srv_conf(cf);
  4794.             if (mconf == NULL) {
  4795.                 return NGX_CONF_ERROR;
  4796.             }

  4797.             ctx->srv_conf[cf->cycle->modules[m]->ctx_index] = mconf;
  4798.         }

  4799.         if (module->create_loc_conf) {
  4800.             mconf = module->create_loc_conf(cf);
  4801.             if (mconf == NULL) {
  4802.                 return NGX_CONF_ERROR;
  4803.             }

  4804.             ctx->loc_conf[cf->cycle->modules[m]->ctx_index] = mconf;
  4805.         }
  4806.     }

  4807.     uscf->servers = ngx_array_create(cf->pool, 4,
  4808.                                      sizeof(ngx_http_upstream_server_t));
  4809.     if (uscf->servers == NULL) {
  4810.         return NGX_CONF_ERROR;
  4811.     }


  4812.     /* parse inside upstream{} */

  4813.     pcf = *cf;
  4814.     cf->ctx = ctx;
  4815.     cf->cmd_type = NGX_HTTP_UPS_CONF;

  4816.     rv = ngx_conf_parse(cf, NULL);

  4817.     *cf = pcf;

  4818.     if (rv != NGX_CONF_OK) {
  4819.         return rv;
  4820.     }

  4821.     if (uscf->servers->nelts == 0) {
  4822.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4823.                            "no servers are inside upstream");
  4824.         return NGX_CONF_ERROR;
  4825.     }

  4826.     return rv;
  4827. }


  4828. static char *
  4829. ngx_http_upstream_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  4830. {
  4831.     ngx_http_upstream_srv_conf_t  *uscf = conf;

  4832.     time_t                       fail_timeout;
  4833.     ngx_str_t                   *value, s;
  4834.     ngx_url_t                    u;
  4835.     ngx_int_t                    weight, max_conns, max_fails;
  4836.     ngx_uint_t                   i;
  4837. #if (NGX_HTTP_UPSTREAM_ZONE)
  4838.     ngx_uint_t                   resolve;
  4839. #endif
  4840.     ngx_http_upstream_server_t  *us;

  4841.     us = ngx_array_push(uscf->servers);
  4842.     if (us == NULL) {
  4843.         return NGX_CONF_ERROR;
  4844.     }

  4845.     ngx_memzero(us, sizeof(ngx_http_upstream_server_t));

  4846.     value = cf->args->elts;

  4847.     weight = 1;
  4848.     max_conns = 0;
  4849.     max_fails = 1;
  4850.     fail_timeout = 10;
  4851. #if (NGX_HTTP_UPSTREAM_ZONE)
  4852.     resolve = 0;
  4853. #endif

  4854.     for (i = 2; i < cf->args->nelts; i++) {

  4855.         if (ngx_strncmp(value[i].data, "weight=", 7) == 0) {

  4856.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_WEIGHT)) {
  4857.                 goto not_supported;
  4858.             }

  4859.             weight = ngx_atoi(&value[i].data[7], value[i].len - 7);

  4860.             if (weight == NGX_ERROR || weight == 0) {
  4861.                 goto invalid;
  4862.             }

  4863.             continue;
  4864.         }

  4865.         if (ngx_strncmp(value[i].data, "max_conns=", 10) == 0) {

  4866.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_MAX_CONNS)) {
  4867.                 goto not_supported;
  4868.             }

  4869.             max_conns = ngx_atoi(&value[i].data[10], value[i].len - 10);

  4870.             if (max_conns == NGX_ERROR) {
  4871.                 goto invalid;
  4872.             }

  4873.             continue;
  4874.         }

  4875.         if (ngx_strncmp(value[i].data, "max_fails=", 10) == 0) {

  4876.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_MAX_FAILS)) {
  4877.                 goto not_supported;
  4878.             }

  4879.             max_fails = ngx_atoi(&value[i].data[10], value[i].len - 10);

  4880.             if (max_fails == NGX_ERROR) {
  4881.                 goto invalid;
  4882.             }

  4883.             continue;
  4884.         }

  4885.         if (ngx_strncmp(value[i].data, "fail_timeout=", 13) == 0) {

  4886.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_FAIL_TIMEOUT)) {
  4887.                 goto not_supported;
  4888.             }

  4889.             s.len = value[i].len - 13;
  4890.             s.data = &value[i].data[13];

  4891.             fail_timeout = ngx_parse_time(&s, 1);

  4892.             if (fail_timeout == (time_t) NGX_ERROR) {
  4893.                 goto invalid;
  4894.             }

  4895.             continue;
  4896.         }

  4897.         if (ngx_strcmp(value[i].data, "backup") == 0) {

  4898.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_BACKUP)) {
  4899.                 goto not_supported;
  4900.             }

  4901.             us->backup = 1;

  4902.             continue;
  4903.         }

  4904.         if (ngx_strcmp(value[i].data, "down") == 0) {

  4905.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_DOWN)) {
  4906.                 goto not_supported;
  4907.             }

  4908.             us->down = NGX_HTTP_UPSTREAM_FAILED;

  4909.             continue;
  4910.         }

  4911. #if (NGX_HTTP_UPSTREAM_STICKY)
  4912.         if (ngx_strcmp(value[i].data, "drain") == 0) {

  4913.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_DOWN)) {
  4914.                 goto not_supported;
  4915.             }

  4916.             us->down = NGX_HTTP_UPSTREAM_DRAINING;

  4917.             continue;
  4918.         }
  4919. #endif

  4920. #if (NGX_HTTP_UPSTREAM_SID)
  4921.         if (ngx_strncmp(value[i].data, "route=", 6) == 0) {

  4922.             us->sid.data = &value[i].data[6];
  4923.             us->sid.len = value[i].len - 6;

  4924.             if (us->sid.len == 0) {
  4925.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "route is empty");
  4926.                 return NGX_CONF_ERROR;
  4927.             }

  4928.             if (us->sid.len > NGX_HTTP_UPSTREAM_SID_LEN) {
  4929.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4930.                                    "route is longer than %d",
  4931.                                    NGX_HTTP_UPSTREAM_SID_LEN);
  4932.                 return NGX_CONF_ERROR;
  4933.             }

  4934.             continue;
  4935.         }
  4936. #endif

  4937. #if (NGX_HTTP_UPSTREAM_ZONE)
  4938.         if (ngx_strcmp(value[i].data, "resolve") == 0) {
  4939.             resolve = 1;
  4940.             continue;
  4941.         }

  4942.         if (ngx_strncmp(value[i].data, "service=", 8) == 0) {

  4943.             us->service.len = value[i].len - 8;
  4944.             us->service.data = &value[i].data[8];

  4945.             if (us->service.len == 0) {
  4946.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "service is empty");
  4947.                 return NGX_CONF_ERROR;
  4948.             }

  4949.             continue;
  4950.         }
  4951. #endif

  4952.         goto invalid;
  4953.     }

  4954.     ngx_memzero(&u, sizeof(ngx_url_t));

  4955.     u.url = value[1];
  4956.     u.default_port = 80;

  4957. #if (NGX_HTTP_UPSTREAM_ZONE)
  4958.     if (resolve) {
  4959.         /* resolve at run time */
  4960.         u.no_resolve = 1;
  4961.     }

  4962.     if (us->service.len && !resolve) {
  4963.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4964.                            "service upstream \"%V\" requires "
  4965.                            "\"resolve\" parameter",
  4966.                            &u.url);
  4967.         return NGX_CONF_ERROR;
  4968.     }

  4969. #endif

  4970.     if (ngx_parse_url(cf->pool, &u) != NGX_OK) {
  4971.         if (u.err) {
  4972.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4973.                                "%s in upstream \"%V\"", u.err, &u.url);
  4974.         }

  4975.         return NGX_CONF_ERROR;
  4976.     }

  4977.     us->name = u.url;

  4978. #if (NGX_HTTP_UPSTREAM_ZONE)

  4979.     if (us->service.len && !u.no_port) {
  4980.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4981.                            "service upstream \"%V\" may not have port",
  4982.                            &us->name);

  4983.         return NGX_CONF_ERROR;
  4984.     }

  4985.     if (us->service.len && u.naddrs) {
  4986.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4987.                            "service upstream \"%V\" requires domain name",
  4988.                            &us->name);

  4989.         return NGX_CONF_ERROR;
  4990.     }

  4991.     if (resolve && u.naddrs == 0) {
  4992.         ngx_addr_t  *addr;

  4993.         /* save port */

  4994.         addr = ngx_pcalloc(cf->pool, sizeof(ngx_addr_t));
  4995.         if (addr == NULL) {
  4996.             return NGX_CONF_ERROR;
  4997.         }

  4998.         addr->sockaddr = ngx_palloc(cf->pool, u.socklen);
  4999.         if (addr->sockaddr == NULL) {
  5000.             return NGX_CONF_ERROR;
  5001.         }

  5002.         ngx_memcpy(addr->sockaddr, &u.sockaddr, u.socklen);

  5003.         addr->socklen = u.socklen;

  5004.         us->addrs = addr;
  5005.         us->naddrs = 1;

  5006.         us->host = u.host;

  5007.     } else {
  5008.         us->addrs = u.addrs;
  5009.         us->naddrs = u.naddrs;
  5010.     }

  5011. #else

  5012.     us->addrs = u.addrs;
  5013.     us->naddrs = u.naddrs;

  5014. #endif

  5015.     us->weight = weight;
  5016.     us->max_conns = max_conns;
  5017.     us->max_fails = max_fails;
  5018.     us->fail_timeout = fail_timeout;

  5019.     return NGX_CONF_OK;

  5020. invalid:

  5021.     ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5022.                        "invalid parameter \"%V\"", &value[i]);

  5023.     return NGX_CONF_ERROR;

  5024. not_supported:

  5025.     ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5026.                        "balancing method does not support parameter \"%V\"",
  5027.                        &value[i]);

  5028.     return NGX_CONF_ERROR;
  5029. }


  5030. #if (NGX_HTTP_UPSTREAM_ZONE)

  5031. static char *
  5032. ngx_http_upstream_resolver(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  5033. {
  5034.     ngx_http_upstream_srv_conf_t  *uscf = conf;

  5035.     ngx_str_t  *value;

  5036.     if (uscf->resolver) {
  5037.         return "is duplicate";
  5038.     }

  5039.     value = cf->args->elts;

  5040.     uscf->resolver = ngx_resolver_create(cf, &value[1], cf->args->nelts - 1);
  5041.     if (uscf->resolver == NULL) {
  5042.         return NGX_CONF_ERROR;
  5043.     }

  5044.     return NGX_CONF_OK;
  5045. }

  5046. #endif


  5047. ngx_http_upstream_srv_conf_t *
  5048. ngx_http_upstream_add(ngx_conf_t *cf, ngx_url_t *u, ngx_uint_t flags)
  5049. {
  5050.     ngx_uint_t                      i;
  5051.     ngx_http_upstream_server_t     *us;
  5052.     ngx_http_upstream_srv_conf_t   *uscf, **uscfp;
  5053.     ngx_http_upstream_main_conf_t  *umcf;

  5054.     if (!(flags & NGX_HTTP_UPSTREAM_CREATE)) {

  5055.         if (ngx_parse_url(cf->pool, u) != NGX_OK) {
  5056.             if (u->err) {
  5057.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5058.                                    "%s in upstream \"%V\"", u->err, &u->url);
  5059.             }

  5060.             return NULL;
  5061.         }
  5062.     }

  5063.     umcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_upstream_module);

  5064.     uscfp = umcf->upstreams.elts;

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

  5066.         if (uscfp[i]->host.len != u->host.len
  5067.             || ngx_strncasecmp(uscfp[i]->host.data, u->host.data, u->host.len)
  5068.                != 0)
  5069.         {
  5070.             continue;
  5071.         }

  5072.         if ((flags & NGX_HTTP_UPSTREAM_CREATE)
  5073.              && (uscfp[i]->flags & NGX_HTTP_UPSTREAM_CREATE))
  5074.         {
  5075.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5076.                                "duplicate upstream \"%V\"", &u->host);
  5077.             return NULL;
  5078.         }

  5079.         if ((uscfp[i]->flags & NGX_HTTP_UPSTREAM_CREATE) && !u->no_port) {
  5080.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5081.                                "upstream \"%V\" may not have port %d",
  5082.                                &u->host, u->port);
  5083.             return NULL;
  5084.         }

  5085.         if ((flags & NGX_HTTP_UPSTREAM_CREATE) && !uscfp[i]->no_port) {
  5086.             ngx_log_error(NGX_LOG_EMERG, cf->log, 0,
  5087.                           "upstream \"%V\" may not have port %d in %s:%ui",
  5088.                           &u->host, uscfp[i]->port,
  5089.                           uscfp[i]->file_name, uscfp[i]->line);
  5090.             return NULL;
  5091.         }

  5092.         if (uscfp[i]->port && u->port
  5093.             && uscfp[i]->port != u->port)
  5094.         {
  5095.             continue;
  5096.         }

  5097.         if (flags & NGX_HTTP_UPSTREAM_CREATE) {
  5098.             uscfp[i]->flags = flags;
  5099.             uscfp[i]->port = 0;
  5100.         }

  5101.         return uscfp[i];
  5102.     }

  5103.     uscf = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_srv_conf_t));
  5104.     if (uscf == NULL) {
  5105.         return NULL;
  5106.     }

  5107.     uscf->flags = flags;
  5108.     uscf->host = u->host;
  5109.     uscf->file_name = cf->conf_file->file.name.data;
  5110.     uscf->line = cf->conf_file->line;
  5111.     uscf->port = u->port;
  5112.     uscf->no_port = u->no_port;
  5113. #if (NGX_HTTP_UPSTREAM_ZONE)
  5114.     uscf->resolver_timeout = NGX_CONF_UNSET_MSEC;
  5115. #endif

  5116.     if (u->naddrs == 1 && (u->port || u->family == AF_UNIX)) {
  5117.         uscf->servers = ngx_array_create(cf->pool, 1,
  5118.                                          sizeof(ngx_http_upstream_server_t));
  5119.         if (uscf->servers == NULL) {
  5120.             return NULL;
  5121.         }

  5122.         us = ngx_array_push(uscf->servers);
  5123.         if (us == NULL) {
  5124.             return NULL;
  5125.         }

  5126.         ngx_memzero(us, sizeof(ngx_http_upstream_server_t));

  5127.         us->addrs = u->addrs;
  5128.         us->naddrs = 1;
  5129.     }

  5130.     uscfp = ngx_array_push(&umcf->upstreams);
  5131.     if (uscfp == NULL) {
  5132.         return NULL;
  5133.     }

  5134.     *uscfp = uscf;

  5135.     return uscf;
  5136. }


  5137. char *
  5138. ngx_http_upstream_bind_set_slot(ngx_conf_t *cf, ngx_command_t *cmd,
  5139.     void *conf)
  5140. {
  5141.     char  *p = conf;

  5142.     ngx_int_t                           rc;
  5143.     ngx_str_t                          *value;
  5144.     ngx_http_complex_value_t            cv;
  5145.     ngx_http_upstream_local_t         **plocal, *local;
  5146.     ngx_http_compile_complex_value_t    ccv;

  5147.     plocal = (ngx_http_upstream_local_t **) (p + cmd->offset);

  5148.     if (*plocal != NGX_CONF_UNSET_PTR) {
  5149.         return "is duplicate";
  5150.     }

  5151.     value = cf->args->elts;

  5152.     if (cf->args->nelts == 2 && ngx_strcmp(value[1].data, "off") == 0) {
  5153.         *plocal = NULL;
  5154.         return NGX_CONF_OK;
  5155.     }

  5156.     ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));

  5157.     ccv.cf = cf;
  5158.     ccv.value = &value[1];
  5159.     ccv.complex_value = &cv;

  5160.     if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
  5161.         return NGX_CONF_ERROR;
  5162.     }

  5163.     local = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_local_t));
  5164.     if (local == NULL) {
  5165.         return NGX_CONF_ERROR;
  5166.     }

  5167.     *plocal = local;

  5168.     if (cv.lengths) {
  5169.         local->value = ngx_palloc(cf->pool, sizeof(ngx_http_complex_value_t));
  5170.         if (local->value == NULL) {
  5171.             return NGX_CONF_ERROR;
  5172.         }

  5173.         *local->value = cv;

  5174.     } else {
  5175.         local->addr = ngx_palloc(cf->pool, sizeof(ngx_addr_t));
  5176.         if (local->addr == NULL) {
  5177.             return NGX_CONF_ERROR;
  5178.         }

  5179.         rc = ngx_parse_addr_port(cf->pool, local->addr, value[1].data,
  5180.                                  value[1].len);

  5181.         switch (rc) {
  5182.         case NGX_OK:
  5183.             local->addr->name = value[1];
  5184.             break;

  5185.         case NGX_DECLINED:
  5186.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5187.                                "invalid address \"%V\"", &value[1]);
  5188.             /* fall through */

  5189.         default:
  5190.             return NGX_CONF_ERROR;
  5191.         }
  5192.     }

  5193.     if (cf->args->nelts > 2) {
  5194.         if (ngx_strcmp(value[2].data, "transparent") == 0) {
  5195. #if (NGX_HAVE_TRANSPARENT_PROXY)
  5196.             ngx_core_conf_t  *ccf;

  5197.             ccf = (ngx_core_conf_t *) ngx_get_conf(cf->cycle->conf_ctx,
  5198.                                                    ngx_core_module);

  5199.             ccf->transparent = 1;
  5200.             local->transparent = 1;
  5201. #else
  5202.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5203.                                "transparent proxying is not supported "
  5204.                                "on this platform, ignored");
  5205. #endif
  5206.         } else {
  5207.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5208.                                "invalid parameter \"%V\"", &value[2]);
  5209.             return NGX_CONF_ERROR;
  5210.         }
  5211.     }

  5212.     return NGX_CONF_OK;
  5213. }


  5214. static ngx_int_t
  5215. ngx_http_upstream_set_local(ngx_http_request_t *r, ngx_http_upstream_t *u,
  5216.     ngx_http_upstream_local_t *local)
  5217. {
  5218.     ngx_int_t    rc;
  5219.     ngx_str_t    val;
  5220.     ngx_addr_t  *addr;

  5221.     if (local == NULL) {
  5222.         u->peer.local = NULL;
  5223.         return NGX_OK;
  5224.     }

  5225. #if (NGX_HAVE_TRANSPARENT_PROXY)
  5226.     u->peer.transparent = local->transparent;
  5227. #endif

  5228.     if (local->value == NULL) {
  5229.         u->peer.local = local->addr;
  5230.         return NGX_OK;
  5231.     }

  5232.     if (ngx_http_complex_value(r, local->value, &val) != NGX_OK) {
  5233.         return NGX_ERROR;
  5234.     }

  5235.     if (val.len == 0) {
  5236.         u->peer.local = NULL;
  5237.         return NGX_OK;
  5238.     }

  5239.     addr = ngx_palloc(r->pool, sizeof(ngx_addr_t));
  5240.     if (addr == NULL) {
  5241.         return NGX_ERROR;
  5242.     }

  5243.     rc = ngx_parse_addr_port(r->pool, addr, val.data, val.len);
  5244.     if (rc == NGX_ERROR) {
  5245.         return NGX_ERROR;
  5246.     }

  5247.     if (rc != NGX_OK) {
  5248.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  5249.                       "invalid local address \"%V\"", &val);
  5250.         u->peer.local = NULL;
  5251.         return NGX_OK;
  5252.     }

  5253.     addr->name = val;
  5254.     u->peer.local = addr;

  5255.     return NGX_OK;
  5256. }


  5257. char *
  5258. ngx_http_upstream_param_set_slot(ngx_conf_t *cf, ngx_command_t *cmd,
  5259.     void *conf)
  5260. {
  5261.     char  *p = conf;

  5262.     ngx_str_t                   *value;
  5263.     ngx_array_t                **a;
  5264.     ngx_http_upstream_param_t   *param;

  5265.     a = (ngx_array_t **) (p + cmd->offset);

  5266.     if (*a == NULL) {
  5267.         *a = ngx_array_create(cf->pool, 4, sizeof(ngx_http_upstream_param_t));
  5268.         if (*a == NULL) {
  5269.             return NGX_CONF_ERROR;
  5270.         }
  5271.     }

  5272.     param = ngx_array_push(*a);
  5273.     if (param == NULL) {
  5274.         return NGX_CONF_ERROR;
  5275.     }

  5276.     value = cf->args->elts;

  5277.     param->key = value[1];
  5278.     param->value = value[2];
  5279.     param->skip_empty = 0;

  5280.     if (cf->args->nelts == 4) {
  5281.         if (ngx_strcmp(value[3].data, "if_not_empty") != 0) {
  5282.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5283.                                "invalid parameter \"%V\"", &value[3]);
  5284.             return NGX_CONF_ERROR;
  5285.         }

  5286.         param->skip_empty = 1;
  5287.     }

  5288.     return NGX_CONF_OK;
  5289. }


  5290. ngx_int_t
  5291. ngx_http_upstream_hide_headers_hash(ngx_conf_t *cf,
  5292.     ngx_http_upstream_conf_t *conf, ngx_http_upstream_conf_t *prev,
  5293.     ngx_str_t *default_hide_headers, ngx_hash_init_t *hash)
  5294. {
  5295.     ngx_str_t       *h;
  5296.     ngx_uint_t       i, j;
  5297.     ngx_array_t      hide_headers;
  5298.     ngx_hash_key_t  *hk;

  5299.     if (conf->hide_headers == NGX_CONF_UNSET_PTR
  5300.         && conf->pass_headers == NGX_CONF_UNSET_PTR)
  5301.     {
  5302.         conf->hide_headers = prev->hide_headers;
  5303.         conf->pass_headers = prev->pass_headers;

  5304.         conf->hide_headers_hash = prev->hide_headers_hash;

  5305.         if (conf->hide_headers_hash.buckets) {
  5306.             return NGX_OK;
  5307.         }

  5308.     } else {
  5309.         if (conf->hide_headers == NGX_CONF_UNSET_PTR) {
  5310.             conf->hide_headers = prev->hide_headers;
  5311.         }

  5312.         if (conf->pass_headers == NGX_CONF_UNSET_PTR) {
  5313.             conf->pass_headers = prev->pass_headers;
  5314.         }
  5315.     }

  5316.     if (ngx_array_init(&hide_headers, cf->temp_pool, 4, sizeof(ngx_hash_key_t))
  5317.         != NGX_OK)
  5318.     {
  5319.         return NGX_ERROR;
  5320.     }

  5321.     for (h = default_hide_headers; h->len; h++) {
  5322.         hk = ngx_array_push(&hide_headers);
  5323.         if (hk == NULL) {
  5324.             return NGX_ERROR;
  5325.         }

  5326.         hk->key = *h;
  5327.         hk->key_hash = ngx_hash_key_lc(h->data, h->len);
  5328.         hk->value = (void *) 1;
  5329.     }

  5330.     if (conf->hide_headers != NGX_CONF_UNSET_PTR) {

  5331.         h = conf->hide_headers->elts;

  5332.         for (i = 0; i < conf->hide_headers->nelts; i++) {

  5333.             hk = hide_headers.elts;

  5334.             for (j = 0; j < hide_headers.nelts; j++) {
  5335.                 if (ngx_strcasecmp(h[i].data, hk[j].key.data) == 0) {
  5336.                     goto exist;
  5337.                 }
  5338.             }

  5339.             hk = ngx_array_push(&hide_headers);
  5340.             if (hk == NULL) {
  5341.                 return NGX_ERROR;
  5342.             }

  5343.             hk->key = h[i];
  5344.             hk->key_hash = ngx_hash_key_lc(h[i].data, h[i].len);
  5345.             hk->value = (void *) 1;

  5346.         exist:

  5347.             continue;
  5348.         }
  5349.     }

  5350.     if (conf->pass_headers != NGX_CONF_UNSET_PTR) {

  5351.         h = conf->pass_headers->elts;
  5352.         hk = hide_headers.elts;

  5353.         for (i = 0; i < conf->pass_headers->nelts; i++) {
  5354.             for (j = 0; j < hide_headers.nelts; j++) {

  5355.                 if (hk[j].key.data == NULL) {
  5356.                     continue;
  5357.                 }

  5358.                 if (ngx_strcasecmp(h[i].data, hk[j].key.data) == 0) {
  5359.                     hk[j].key.data = NULL;
  5360.                     break;
  5361.                 }
  5362.             }
  5363.         }
  5364.     }

  5365.     hash->hash = &conf->hide_headers_hash;
  5366.     hash->key = ngx_hash_key_lc;
  5367.     hash->pool = cf->pool;
  5368.     hash->temp_pool = NULL;

  5369.     if (ngx_hash_init(hash, hide_headers.elts, hide_headers.nelts) != NGX_OK) {
  5370.         return NGX_ERROR;
  5371.     }

  5372.     /*
  5373.      * special handling to preserve conf->hide_headers_hash
  5374.      * in the "http" section to inherit it to all servers
  5375.      */

  5376.     if (prev->hide_headers_hash.buckets == NULL
  5377.         && conf->hide_headers == prev->hide_headers
  5378.         && conf->pass_headers == prev->pass_headers)
  5379.     {
  5380.         prev->hide_headers_hash = conf->hide_headers_hash;
  5381.     }

  5382.     return NGX_OK;
  5383. }


  5384. #if (NGX_HTTP_SSL)

  5385. ngx_int_t
  5386. ngx_http_upstream_merge_ssl_passwords(ngx_conf_t *cf,
  5387.     ngx_http_upstream_conf_t *conf, ngx_http_upstream_conf_t *prev)
  5388. {
  5389.     ngx_uint_t  preserve;

  5390.     ngx_conf_merge_ptr_value(conf->ssl_passwords, prev->ssl_passwords, NULL);

  5391.     if (conf->ssl_certificate == NULL
  5392.         || conf->ssl_certificate->value.len == 0
  5393.         || conf->ssl_certificate_key == NULL)
  5394.     {
  5395.         return NGX_OK;
  5396.     }

  5397.     if (conf->ssl_certificate->lengths == NULL
  5398.         && conf->ssl_certificate_key->lengths == NULL)
  5399.     {
  5400.         if (conf->ssl_passwords && conf->ssl_passwords->pool == NULL) {
  5401.             /* un-preserve empty password list */
  5402.             conf->ssl_passwords = NULL;
  5403.         }

  5404.         return NGX_OK;
  5405.     }

  5406.     if (conf->ssl_passwords && conf->ssl_passwords->pool != cf->temp_pool) {
  5407.         /* already preserved */
  5408.         return NGX_OK;
  5409.     }

  5410.     preserve = (conf->ssl_passwords == prev->ssl_passwords) ? 1 : 0;

  5411.     conf->ssl_passwords = ngx_ssl_preserve_passwords(cf, conf->ssl_passwords);
  5412.     if (conf->ssl_passwords == NULL) {
  5413.         return NGX_ERROR;
  5414.     }

  5415.     /*
  5416.      * special handling to keep a preserved ssl_passwords copy
  5417.      * in the previous configuration to inherit it to all children
  5418.      */

  5419.     if (preserve) {
  5420.         prev->ssl_passwords = conf->ssl_passwords;
  5421.     }

  5422.     return NGX_OK;
  5423. }

  5424. #endif


  5425. static void *
  5426. ngx_http_upstream_create_main_conf(ngx_conf_t *cf)
  5427. {
  5428.     ngx_http_upstream_main_conf_t  *umcf;

  5429.     umcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_main_conf_t));
  5430.     if (umcf == NULL) {
  5431.         return NULL;
  5432.     }

  5433.     if (ngx_array_init(&umcf->upstreams, cf->pool, 4,
  5434.                        sizeof(ngx_http_upstream_srv_conf_t *))
  5435.         != NGX_OK)
  5436.     {
  5437.         return NULL;
  5438.     }

  5439.     return umcf;
  5440. }


  5441. static char *
  5442. ngx_http_upstream_init_main_conf(ngx_conf_t *cf, void *conf)
  5443. {
  5444.     ngx_http_upstream_main_conf_t  *umcf = conf;

  5445.     ngx_uint_t                      i;
  5446.     ngx_array_t                     headers_in;
  5447.     ngx_hash_key_t                 *hk;
  5448.     ngx_hash_init_t                 hash;
  5449.     ngx_http_upstream_init_pt       init;
  5450.     ngx_http_upstream_header_t     *header;
  5451.     ngx_http_upstream_srv_conf_t  **uscfp;

  5452.     uscfp = umcf->upstreams.elts;

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

  5454.         init = uscfp[i]->peer.init_upstream ? uscfp[i]->peer.init_upstream:
  5455.                                             ngx_http_upstream_init_round_robin;

  5456.         if (init(cf, uscfp[i]) != NGX_OK) {
  5457.             return NGX_CONF_ERROR;
  5458.         }
  5459.     }


  5460.     /* upstream_headers_in_hash */

  5461.     if (ngx_array_init(&headers_in, cf->temp_pool, 32, sizeof(ngx_hash_key_t))
  5462.         != NGX_OK)
  5463.     {
  5464.         return NGX_CONF_ERROR;
  5465.     }

  5466.     for (header = ngx_http_upstream_headers_in; header->name.len; header++) {
  5467.         hk = ngx_array_push(&headers_in);
  5468.         if (hk == NULL) {
  5469.             return NGX_CONF_ERROR;
  5470.         }

  5471.         hk->key = header->name;
  5472.         hk->key_hash = ngx_hash_key_lc(header->name.data, header->name.len);
  5473.         hk->value = header;
  5474.     }

  5475.     hash.hash = &umcf->headers_in_hash;
  5476.     hash.key = ngx_hash_key_lc;
  5477.     hash.max_size = 512;
  5478.     hash.bucket_size = ngx_align(64, ngx_cacheline_size);
  5479.     hash.name = "upstream_headers_in_hash";
  5480.     hash.pool = cf->pool;
  5481.     hash.temp_pool = NULL;

  5482.     if (ngx_hash_init(&hash, headers_in.elts, headers_in.nelts) != NGX_OK) {
  5483.         return NGX_CONF_ERROR;
  5484.     }

  5485.     return NGX_CONF_OK;
  5486. }