src/http/ngx_http_upstream.c - nginx

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

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

  174. static ngx_int_t ngx_http_upstream_set_local(ngx_http_request_t *r,
  175.   ngx_http_upstream_t *u, ngx_http_upstream_local_t *local);

  176. static void *ngx_http_upstream_create_main_conf(ngx_conf_t *cf);
  177. static char *ngx_http_upstream_init_main_conf(ngx_conf_t *cf, void *conf);

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


  190. static ngx_http_upstream_header_t  ngx_http_upstream_headers_in[] = {

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

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

  199.     { ngx_string("Content-Length"),
  200.                  ngx_http_upstream_process_content_length, 0,
  201.                  ngx_http_upstream_ignore_header_line, 0, 0 },

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

  207.     { ngx_string("Last-Modified"),
  208.                  ngx_http_upstream_process_last_modified, 0,
  209.                  ngx_http_upstream_copy_last_modified, 0, 0 },

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

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

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

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

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

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

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

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

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

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

  251.     { ngx_string("Content-Range"),
  252.                  ngx_http_upstream_ignore_header_line, 0,
  253.                  ngx_http_upstream_copy_header_line,
  254.                  offsetof(ngx_http_headers_out_t, content_range), 0 },

  255.     { ngx_string("Connection"),
  256.                  ngx_http_upstream_process_connection, 0,
  257.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  258.     { ngx_string("Keep-Alive"),
  259.                  ngx_http_upstream_ignore_header_line, 0,
  260.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  261.     { ngx_string("Vary"),
  262.                  ngx_http_upstream_process_vary, 0,
  263.                  ngx_http_upstream_copy_header_line, 0, 0 },

  264.     { ngx_string("Link"),
  265.                  ngx_http_upstream_ignore_header_line, 0,
  266.                  ngx_http_upstream_copy_multi_header_lines,
  267.                  offsetof(ngx_http_headers_out_t, link), 0 },

  268.     { ngx_string("X-Accel-Expires"),
  269.                  ngx_http_upstream_process_accel_expires, 0,
  270.                  ngx_http_upstream_copy_header_line, 0, 0 },

  271.     { ngx_string("X-Accel-Redirect"),
  272.                  ngx_http_upstream_process_header_line,
  273.                  offsetof(ngx_http_upstream_headers_in_t, x_accel_redirect),
  274.                  ngx_http_upstream_copy_header_line, 0, 0 },

  275.     { ngx_string("X-Accel-Limit-Rate"),
  276.                  ngx_http_upstream_process_limit_rate, 0,
  277.                  ngx_http_upstream_copy_header_line, 0, 0 },

  278.     { ngx_string("X-Accel-Buffering"),
  279.                  ngx_http_upstream_process_buffering, 0,
  280.                  ngx_http_upstream_copy_header_line, 0, 0 },

  281.     { ngx_string("X-Accel-Charset"),
  282.                  ngx_http_upstream_process_charset, 0,
  283.                  ngx_http_upstream_copy_header_line, 0, 0 },

  284.     { ngx_string("Transfer-Encoding"),
  285.                  ngx_http_upstream_process_transfer_encoding, 0,
  286.                  ngx_http_upstream_ignore_header_line, 0, 0 },

  287.     { ngx_string("Content-Encoding"),
  288.                  ngx_http_upstream_ignore_header_line, 0,
  289.                  ngx_http_upstream_copy_header_line,
  290.                  offsetof(ngx_http_headers_out_t, content_encoding), 0 },

  291.     { ngx_null_string, NULL, 0, NULL, 0, 0 }
  292. };


  293. static ngx_command_t  ngx_http_upstream_commands[] = {

  294.     { ngx_string("upstream"),
  295.       NGX_HTTP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE1,
  296.       ngx_http_upstream,
  297.       0,
  298.       0,
  299.       NULL },

  300.     { ngx_string("server"),
  301.       NGX_HTTP_UPS_CONF|NGX_CONF_1MORE,
  302.       ngx_http_upstream_server,
  303.       NGX_HTTP_SRV_CONF_OFFSET,
  304.       0,
  305.       NULL },

  306. #if (NGX_HTTP_UPSTREAM_ZONE)

  307.     { ngx_string("resolver"),
  308.       NGX_HTTP_UPS_CONF|NGX_CONF_1MORE,
  309.       ngx_http_upstream_resolver,
  310.       NGX_HTTP_SRV_CONF_OFFSET,
  311.       0,
  312.       NULL },

  313.     { ngx_string("resolver_timeout"),
  314.       NGX_HTTP_UPS_CONF|NGX_CONF_TAKE1,
  315.       ngx_conf_set_msec_slot,
  316.       NGX_HTTP_SRV_CONF_OFFSET,
  317.       offsetof(ngx_http_upstream_srv_conf_t, resolver_timeout),
  318.       NULL },

  319. #endif

  320.       ngx_null_command
  321. };


  322. static ngx_http_module_t  ngx_http_upstream_module_ctx = {
  323.     ngx_http_upstream_add_variables,       /* preconfiguration */
  324.     NULL,                                  /* postconfiguration */

  325.     ngx_http_upstream_create_main_conf,    /* create main configuration */
  326.     ngx_http_upstream_init_main_conf,      /* init main configuration */

  327.     NULL,                                  /* create server configuration */
  328.     NULL,                                  /* merge server configuration */

  329.     NULL,                                  /* create location configuration */
  330.     NULL                                   /* merge location configuration */
  331. };


  332. ngx_module_t  ngx_http_upstream_module = {
  333.     NGX_MODULE_V1,
  334.     &ngx_http_upstream_module_ctx,         /* module context */
  335.     ngx_http_upstream_commands,            /* module directives */
  336.     NGX_HTTP_MODULE,                       /* module type */
  337.     NULL,                                  /* init master */
  338.     NULL,                                  /* init module */
  339.     NULL,                                  /* init process */
  340.     NULL,                                  /* init thread */
  341.     NULL,                                  /* exit thread */
  342.     NULL,                                  /* exit process */
  343.     NULL,                                  /* exit master */
  344.     NGX_MODULE_V1_PADDING
  345. };


  346. static ngx_http_variable_t  ngx_http_upstream_vars[] = {

  347.     { ngx_string("upstream_addr"), NULL,
  348.       ngx_http_upstream_addr_variable, 0,
  349.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  350.     { ngx_string("upstream_status"), NULL,
  351.       ngx_http_upstream_status_variable, 0,
  352.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  353.     { ngx_string("upstream_connect_time"), NULL,
  354.       ngx_http_upstream_response_time_variable, 2,
  355.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  356.     { ngx_string("upstream_header_time"), NULL,
  357.       ngx_http_upstream_response_time_variable, 1,
  358.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  359.     { ngx_string("upstream_response_time"), NULL,
  360.       ngx_http_upstream_response_time_variable, 0,
  361.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  362.     { ngx_string("upstream_response_length"), NULL,
  363.       ngx_http_upstream_response_length_variable, 0,
  364.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  365.     { ngx_string("upstream_bytes_received"), NULL,
  366.       ngx_http_upstream_response_length_variable, 1,
  367.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  368.     { ngx_string("upstream_bytes_sent"), NULL,
  369.       ngx_http_upstream_response_length_variable, 2,
  370.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  371. #if (NGX_HTTP_CACHE)

  372.     { ngx_string("upstream_cache_status"), NULL,
  373.       ngx_http_upstream_cache_status, 0,
  374.       NGX_HTTP_VAR_NOCACHEABLE, 0 },

  375.     { ngx_string("upstream_cache_last_modified"), NULL,
  376.       ngx_http_upstream_cache_last_modified, 0,
  377.       NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_NOHASH, 0 },

  378.     { ngx_string("upstream_cache_etag"), NULL,
  379.       ngx_http_upstream_cache_etag, 0,
  380.       NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_NOHASH, 0 },

  381. #endif

  382.     { ngx_string("upstream_http_"), NULL, ngx_http_upstream_header_variable,
  383.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  384.     { ngx_string("upstream_trailer_"), NULL, ngx_http_upstream_trailer_variable,
  385.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  386.     { ngx_string("upstream_cookie_"), NULL, ngx_http_upstream_cookie_variable,
  387.       0, NGX_HTTP_VAR_NOCACHEABLE|NGX_HTTP_VAR_PREFIX, 0 },

  388.       ngx_http_null_variable
  389. };


  390. static ngx_http_upstream_next_t  ngx_http_upstream_next_errors[] = {
  391.     { 500, NGX_HTTP_UPSTREAM_FT_HTTP_500 },
  392.     { 502, NGX_HTTP_UPSTREAM_FT_HTTP_502 },
  393.     { 503, NGX_HTTP_UPSTREAM_FT_HTTP_503 },
  394.     { 504, NGX_HTTP_UPSTREAM_FT_HTTP_504 },
  395.     { 403, NGX_HTTP_UPSTREAM_FT_HTTP_403 },
  396.     { 404, NGX_HTTP_UPSTREAM_FT_HTTP_404 },
  397.     { 429, NGX_HTTP_UPSTREAM_FT_HTTP_429 },
  398.     { 0, 0 }
  399. };


  400. ngx_conf_bitmask_t  ngx_http_upstream_cache_method_mask[] = {
  401.     { ngx_string("GET"), NGX_HTTP_GET },
  402.     { ngx_string("HEAD"), NGX_HTTP_HEAD },
  403.     { ngx_string("POST"), NGX_HTTP_POST },
  404.     { ngx_null_string, 0 }
  405. };


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


  418. ngx_int_t
  419. ngx_http_upstream_create(ngx_http_request_t *r)
  420. {
  421.     ngx_http_upstream_t  *u;

  422.     u = r->upstream;

  423.     if (u && u->cleanup) {
  424.         r->main->count++;
  425.         ngx_http_upstream_cleanup(r);
  426.     }

  427.     u = ngx_pcalloc(r->pool, sizeof(ngx_http_upstream_t));
  428.     if (u == NULL) {
  429.         return NGX_ERROR;
  430.     }

  431.     r->upstream = u;

  432.     u->peer.log = r->connection->log;
  433.     u->peer.log_error = NGX_ERROR_ERR;

  434. #if (NGX_HTTP_CACHE)
  435.     r->cache = NULL;
  436. #endif

  437.     u->headers_in.content_length_n = -1;
  438.     u->headers_in.last_modified_time = -1;

  439.     return NGX_OK;
  440. }


  441. void
  442. ngx_http_upstream_init(ngx_http_request_t *r)
  443. {
  444.     ngx_connection_t     *c;

  445.     c = r->connection;

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

  448. #if (NGX_HTTP_V2)
  449.     if (r->stream) {
  450.         ngx_http_upstream_init_request(r);
  451.         return;
  452.     }
  453. #endif

  454. #if (NGX_HTTP_V3)
  455.     if (c->quic) {
  456.         ngx_http_upstream_init_request(r);
  457.         return;
  458.     }
  459. #endif

  460.     if (c->read->timer_set) {
  461.         ngx_del_timer(c->read);
  462.     }

  463.     if (ngx_event_flags & NGX_USE_CLEAR_EVENT) {

  464.         if (!c->write->active) {
  465.             if (ngx_add_event(c->write, NGX_WRITE_EVENT, NGX_CLEAR_EVENT)
  466.                 == NGX_ERROR)
  467.             {
  468.                 ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  469.                 return;
  470.             }
  471.         }
  472.     }

  473.     ngx_http_upstream_init_request(r);
  474. }


  475. static void
  476. ngx_http_upstream_init_request(ngx_http_request_t *r)
  477. {
  478.     ngx_str_t                      *host;
  479.     ngx_uint_t                      i;
  480.     ngx_resolver_ctx_t             *ctx, temp;
  481.     ngx_http_cleanup_t             *cln;
  482.     ngx_http_upstream_t            *u;
  483.     ngx_http_core_loc_conf_t       *clcf;
  484.     ngx_http_upstream_srv_conf_t   *uscf, **uscfp;
  485.     ngx_http_upstream_main_conf_t  *umcf;

  486.     if (r->aio) {
  487.         return;
  488.     }

  489.     u = r->upstream;

  490. #if (NGX_HTTP_CACHE)

  491.     if (u->conf->cache) {
  492.         ngx_int_t  rc;

  493.         rc = ngx_http_upstream_cache(r, u);

  494.         if (rc == NGX_BUSY) {
  495.             r->write_event_handler = ngx_http_upstream_init_request;
  496.             return;
  497.         }

  498.         r->write_event_handler = ngx_http_request_empty_handler;

  499.         if (rc == NGX_ERROR) {
  500.             ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  501.             return;
  502.         }

  503.         if (rc == NGX_OK) {
  504.             rc = ngx_http_upstream_cache_send(r, u);

  505.             if (rc == NGX_DONE) {
  506.                 return;
  507.             }

  508.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  509.                 rc = NGX_DECLINED;
  510.                 r->cached = 0;
  511.                 u->buffer.start = NULL;
  512.                 u->cache_status = NGX_HTTP_CACHE_MISS;
  513.                 u->request_sent = 1;
  514.             }
  515.         }

  516.         if (rc != NGX_DECLINED) {
  517.             ngx_http_finalize_request(r, rc);
  518.             return;
  519.         }
  520.     }

  521. #endif

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

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

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

  526.         } else {
  527.             if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {
  528.                 ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  529.                 return;
  530.             }
  531.         }

  532.         r->read_event_handler = ngx_http_upstream_rd_check_broken_connection;
  533.         r->write_event_handler = ngx_http_upstream_wr_check_broken_connection;
  534.     }

  535.     if (r->request_body) {
  536.         u->request_bufs = r->request_body->bufs;
  537.     }

  538.     if (u->create_request(r) != NGX_OK) {
  539.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  540.         return;
  541.     }

  542.     if (ngx_http_upstream_set_local(r, u, u->conf->local) != NGX_OK) {
  543.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  544.         return;
  545.     }

  546.     if (u->conf->socket_keepalive) {
  547.         u->peer.so_keepalive = 1;
  548.     }

  549.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  550.     u->output.alignment = clcf->directio_alignment;
  551.     u->output.pool = r->pool;
  552.     u->output.bufs.num = 1;
  553.     u->output.bufs.size = clcf->client_body_buffer_size;

  554.     if (u->output.output_filter == NULL) {
  555.         u->output.output_filter = ngx_chain_writer;
  556.         u->output.filter_ctx = &u->writer;
  557.     }

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

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

  560.         r->upstream_states = ngx_array_create(r->pool, 1,
  561.                                             sizeof(ngx_http_upstream_state_t));
  562.         if (r->upstream_states == NULL) {
  563.             ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  564.             return;
  565.         }

  566.     } else {

  567.         u->state = ngx_array_push(r->upstream_states);
  568.         if (u->state == NULL) {
  569.             ngx_http_upstream_finalize_request(r, u,
  570.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  571.             return;
  572.         }

  573.         ngx_memzero(u->state, sizeof(ngx_http_upstream_state_t));
  574.     }

  575.     cln = ngx_http_cleanup_add(r, 0);
  576.     if (cln == NULL) {
  577.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
  578.         return;
  579.     }

  580.     cln->handler = ngx_http_upstream_cleanup;
  581.     cln->data = r;
  582.     u->cleanup = &cln->handler;

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

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

  585.     } else {

  586. #if (NGX_HTTP_SSL)
  587.         u->ssl_name = u->resolved->host;
  588. #endif

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

  590.         umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);

  591.         uscfp = umcf->upstreams.elts;

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

  593.             uscf = uscfp[i];

  594.             if (uscf->host.len == host->len
  595.                 && ((uscf->port == 0 && u->resolved->no_port)
  596.                      || uscf->port == u->resolved->port)
  597.                 && ngx_strncasecmp(uscf->host.data, host->data, host->len) == 0)
  598.             {
  599.                 goto found;
  600.             }
  601.         }

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

  603.             if (u->resolved->port == 0
  604.                 && u->resolved->sockaddr->sa_family != AF_UNIX)
  605.             {
  606.                 ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  607.                               "no port in upstream \"%V\"", host);
  608.                 ngx_http_upstream_finalize_request(r, u,
  609.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  610.                 return;
  611.             }

  612.             if (ngx_http_upstream_create_round_robin_peer(r, u->resolved)
  613.                 != NGX_OK)
  614.             {
  615.                 ngx_http_upstream_finalize_request(r, u,
  616.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  617.                 return;
  618.             }

  619.             ngx_http_upstream_connect(r, u);

  620.             return;
  621.         }

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

  629.         temp.name = *host;

  630.         ctx = ngx_resolve_start(clcf->resolver, &temp);
  631.         if (ctx == NULL) {
  632.             ngx_http_upstream_finalize_request(r, u,
  633.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  634.             return;
  635.         }

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

  639.             ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  640.             return;
  641.         }

  642.         ctx->name = *host;
  643.         ctx->handler = ngx_http_upstream_resolve_handler;
  644.         ctx->data = r;
  645.         ctx->timeout = clcf->resolver_timeout;

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

  647.         if (ngx_resolve_name(ctx) != NGX_OK) {
  648.             u->resolved->ctx = NULL;
  649.             ngx_http_upstream_finalize_request(r, u,
  650.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  651.             return;
  652.         }

  653.         return;
  654.     }

  655. found:

  656.     if (uscf == NULL) {
  657.         ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0,
  658.                       "no upstream configuration");
  659.         ngx_http_upstream_finalize_request(r, u,
  660.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  661.         return;
  662.     }

  663.     u->upstream = uscf;

  664. #if (NGX_HTTP_SSL)
  665.     u->ssl_name = uscf->host;
  666. #endif

  667.     if (uscf->peer.init(r, uscf) != NGX_OK) {
  668.         ngx_http_upstream_finalize_request(r, u,
  669.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  670.         return;
  671.     }

  672.     u->peer.start_time = ngx_current_msec;

  673.     if (u->conf->next_upstream_tries
  674.         && u->peer.tries > u->conf->next_upstream_tries)
  675.     {
  676.         u->peer.tries = u->conf->next_upstream_tries;
  677.     }

  678.     ngx_http_upstream_connect(r, u);
  679. }


  680. #if (NGX_HTTP_CACHE)

  681. static ngx_int_t
  682. ngx_http_upstream_cache(ngx_http_request_t *r, ngx_http_upstream_t *u)
  683. {
  684.     ngx_int_t               rc;
  685.     ngx_http_cache_t       *c;
  686.     ngx_http_file_cache_t  *cache;

  687.     c = r->cache;

  688.     if (c == NULL) {

  689.         if (!(r->method & u->conf->cache_methods)) {
  690.             return NGX_DECLINED;
  691.         }

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

  693.         if (rc != NGX_OK) {
  694.             return rc;
  695.         }

  696.         if (r->method == NGX_HTTP_HEAD && u->conf->cache_convert_head) {
  697.             u->method = ngx_http_core_get_method;
  698.         }

  699.         if (ngx_http_file_cache_new(r) != NGX_OK) {
  700.             return NGX_ERROR;
  701.         }

  702.         if (u->create_key(r) != NGX_OK) {
  703.             return NGX_ERROR;
  704.         }

  705.         /* TODO: add keys */

  706.         ngx_http_file_cache_create_key(r);

  707.         if (r->cache->header_start + 256 > u->conf->buffer_size) {
  708.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  709.                           "%V_buffer_size %uz is not enough for cache key, "
  710.                           "it should be increased to at least %uz",
  711.                           &u->conf->module, u->conf->buffer_size,
  712.                           ngx_align(r->cache->header_start + 256, 1024));

  713.             r->cache = NULL;
  714.             return NGX_DECLINED;
  715.         }

  716.         u->cacheable = 1;

  717.         c = r->cache;

  718.         c->body_start = u->conf->buffer_size;
  719.         c->min_uses = u->conf->cache_min_uses;
  720.         c->file_cache = cache;

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

  722.         case NGX_ERROR:
  723.             return NGX_ERROR;

  724.         case NGX_DECLINED:
  725.             u->cache_status = NGX_HTTP_CACHE_BYPASS;
  726.             return NGX_DECLINED;

  727.         default: /* NGX_OK */
  728.             break;
  729.         }

  730.         c->lock = u->conf->cache_lock;
  731.         c->lock_timeout = u->conf->cache_lock_timeout;
  732.         c->lock_age = u->conf->cache_lock_age;

  733.         u->cache_status = NGX_HTTP_CACHE_MISS;
  734.     }

  735.     rc = ngx_http_file_cache_open(r);

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

  738.     switch (rc) {

  739.     case NGX_HTTP_CACHE_STALE:

  740.         if (((u->conf->cache_use_stale & NGX_HTTP_UPSTREAM_FT_UPDATING)
  741.              || c->stale_updating) && !r->background
  742.             && u->conf->cache_background_update)
  743.         {
  744.             if (ngx_http_upstream_cache_background_update(r, u) == NGX_OK) {
  745.                 r->cache->background = 1;
  746.                 u->cache_status = rc;
  747.                 rc = NGX_OK;

  748.             } else {
  749.                 rc = NGX_ERROR;
  750.             }
  751.         }

  752.         break;

  753.     case NGX_HTTP_CACHE_UPDATING:

  754.         if (((u->conf->cache_use_stale & NGX_HTTP_UPSTREAM_FT_UPDATING)
  755.              || c->stale_updating) && !r->background)
  756.         {
  757.             u->cache_status = rc;
  758.             rc = NGX_OK;

  759.         } else {
  760.             rc = NGX_HTTP_CACHE_STALE;
  761.         }

  762.         break;

  763.     case NGX_OK:
  764.         u->cache_status = NGX_HTTP_CACHE_HIT;
  765.     }

  766.     switch (rc) {

  767.     case NGX_OK:

  768.         return NGX_OK;

  769.     case NGX_HTTP_CACHE_STALE:

  770.         c->valid_sec = 0;
  771.         c->updating_sec = 0;
  772.         c->error_sec = 0;

  773.         u->buffer.start = NULL;
  774.         u->cache_status = NGX_HTTP_CACHE_EXPIRED;

  775.         break;

  776.     case NGX_DECLINED:

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

  779.         } else {
  780.             u->buffer.pos = u->buffer.start + c->header_start;
  781.             u->buffer.last = u->buffer.pos;
  782.         }

  783.         break;

  784.     case NGX_HTTP_CACHE_SCARCE:

  785.         u->cacheable = 0;

  786.         break;

  787.     case NGX_AGAIN:

  788.         return NGX_BUSY;

  789.     case NGX_ERROR:

  790.         return NGX_ERROR;

  791.     default:

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

  793.         u->cache_status = NGX_HTTP_CACHE_HIT;

  794.         return rc;
  795.     }

  796.     if (ngx_http_upstream_cache_check_range(r, u) == NGX_DECLINED) {
  797.         u->cacheable = 0;
  798.     }

  799.     r->cached = 0;

  800.     return NGX_DECLINED;
  801. }


  802. static ngx_int_t
  803. ngx_http_upstream_cache_get(ngx_http_request_t *r, ngx_http_upstream_t *u,
  804.     ngx_http_file_cache_t **cache)
  805. {
  806.     ngx_str_t               *name, val;
  807.     ngx_uint_t               i;
  808.     ngx_http_file_cache_t  **caches;

  809.     if (u->conf->cache_zone) {
  810.         *cache = u->conf->cache_zone->data;
  811.         return NGX_OK;
  812.     }

  813.     if (ngx_http_complex_value(r, u->conf->cache_value, &val) != NGX_OK) {
  814.         return NGX_ERROR;
  815.     }

  816.     if (val.len == 0
  817.         || (val.len == 3 && ngx_strncmp(val.data, "off", 3) == 0))
  818.     {
  819.         return NGX_DECLINED;
  820.     }

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

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

  824.         if (name->len == val.len
  825.             && ngx_strncmp(name->data, val.data, val.len) == 0)
  826.         {
  827.             *cache = caches[i];
  828.             return NGX_OK;
  829.         }
  830.     }

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

  833.     return NGX_ERROR;
  834. }


  835. static ngx_int_t
  836. ngx_http_upstream_cache_send(ngx_http_request_t *r, ngx_http_upstream_t *u)
  837. {
  838.     ngx_int_t          rc;
  839.     ngx_http_cache_t  *c;

  840.     r->cached = 1;
  841.     c = r->cache;

  842.     if (c->header_start == c->body_start) {
  843.         r->http_version = NGX_HTTP_VERSION_9;
  844.         return ngx_http_cache_send(r);
  845.     }

  846.     /* TODO: cache stack */

  847.     u->buffer = *c->buf;
  848.     u->buffer.pos += c->header_start;

  849.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  850.     u->headers_in.content_length_n = -1;
  851.     u->headers_in.last_modified_time = -1;

  852.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  853.                       sizeof(ngx_table_elt_t))
  854.         != NGX_OK)
  855.     {
  856.         return NGX_ERROR;
  857.     }

  858.     if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  859.                       sizeof(ngx_table_elt_t))
  860.         != NGX_OK)
  861.     {
  862.         return NGX_ERROR;
  863.     }

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

  865.     if (rc == NGX_OK) {

  866.         if (ngx_http_upstream_process_headers(r, u) != NGX_OK) {
  867.             return NGX_DONE;
  868.         }

  869.         return ngx_http_cache_send(r);
  870.     }

  871.     if (rc == NGX_ERROR) {
  872.         return NGX_ERROR;
  873.     }

  874.     if (rc == NGX_AGAIN || rc == NGX_HTTP_UPSTREAM_EARLY_HINTS) {
  875.         rc = NGX_HTTP_UPSTREAM_INVALID_HEADER;
  876.     }

  877.     /* rc == NGX_HTTP_UPSTREAM_INVALID_HEADER */

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

  881.     /* TODO: delete file */

  882.     return rc;
  883. }


  884. static ngx_int_t
  885. ngx_http_upstream_cache_background_update(ngx_http_request_t *r,
  886.     ngx_http_upstream_t *u)
  887. {
  888.     ngx_http_request_t  *sr;

  889.     if (r == r->main) {
  890.         r->preserve_body = 1;
  891.     }

  892.     if (ngx_http_subrequest(r, &r->uri, &r->args, &sr, NULL,
  893.                             NGX_HTTP_SUBREQUEST_CLONE
  894.                             |NGX_HTTP_SUBREQUEST_BACKGROUND)
  895.         != NGX_OK)
  896.     {
  897.         return NGX_ERROR;
  898.     }

  899.     sr->header_only = 1;

  900.     return NGX_OK;
  901. }


  902. static ngx_int_t
  903. ngx_http_upstream_cache_check_range(ngx_http_request_t *r,
  904.     ngx_http_upstream_t *u)
  905. {
  906.     off_t             offset;
  907.     u_char           *p, *start;
  908.     ngx_table_elt_t  *h;

  909.     h = r->headers_in.range;

  910.     if (h == NULL
  911.         || !u->cacheable
  912.         || u->conf->cache_max_range_offset == NGX_MAX_OFF_T_VALUE)
  913.     {
  914.         return NGX_OK;
  915.     }

  916.     if (u->conf->cache_max_range_offset == 0) {
  917.         return NGX_DECLINED;
  918.     }

  919.     if (h->value.len < 7
  920.         || ngx_strncasecmp(h->value.data, (u_char *) "bytes=", 6) != 0)
  921.     {
  922.         return NGX_OK;
  923.     }

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

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

  926.     if (*p == '-') {
  927.         return NGX_DECLINED;
  928.     }

  929.     start = p;

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

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

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

  935.     return NGX_OK;
  936. }

  937. #endif


  938. static void
  939. ngx_http_upstream_resolve_handler(ngx_resolver_ctx_t *ctx)
  940. {
  941.     ngx_uint_t                     run_posted;
  942.     ngx_connection_t              *c;
  943.     ngx_http_request_t            *r;
  944.     ngx_http_upstream_t           *u;
  945.     ngx_http_upstream_resolved_t  *ur;

  946.     run_posted = ctx->async;

  947.     r = ctx->data;
  948.     c = r->connection;

  949.     u = r->upstream;
  950.     ur = u->resolved;

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

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

  954.     if (ctx->state) {
  955.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  956.                       "%V could not be resolved (%i: %s)",
  957.                       &ctx->name, ctx->state,
  958.                       ngx_resolver_strerror(ctx->state));

  959.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  960.         goto failed;
  961.     }

  962.     ur->naddrs = ctx->naddrs;
  963.     ur->addrs = ctx->addrs;

  964. #if (NGX_DEBUG)
  965.     {
  966.     u_char      text[NGX_SOCKADDR_STRLEN];
  967.     ngx_str_t   addr;
  968.     ngx_uint_t  i;

  969.     addr.data = text;

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

  973.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  974.                        "name was resolved to %V", &addr);
  975.     }
  976.     }
  977. #endif

  978.     if (ngx_http_upstream_create_round_robin_peer(r, ur) != NGX_OK) {
  979.         ngx_http_upstream_finalize_request(r, u,
  980.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  981.         goto failed;
  982.     }

  983.     ngx_resolve_name_done(ctx);
  984.     ur->ctx = NULL;

  985.     u->peer.start_time = ngx_current_msec;

  986.     if (u->conf->next_upstream_tries
  987.         && u->peer.tries > u->conf->next_upstream_tries)
  988.     {
  989.         u->peer.tries = u->conf->next_upstream_tries;
  990.     }

  991.     ngx_http_upstream_connect(r, u);

  992. failed:

  993.     if (run_posted) {
  994.         ngx_http_run_posted_requests(c);
  995.     }
  996. }


  997. static void
  998. ngx_http_upstream_handler(ngx_event_t *ev)
  999. {
  1000.     ngx_connection_t     *c;
  1001.     ngx_http_request_t   *r;
  1002.     ngx_http_upstream_t  *u;

  1003.     c = ev->data;
  1004.     r = c->data;

  1005.     u = r->upstream;
  1006.     c = r->connection;

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

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

  1010.     if (ev->delayed && ev->timedout) {
  1011.         ev->delayed = 0;
  1012.         ev->timedout = 0;
  1013.     }

  1014.     if (ev->write) {
  1015.         u->write_event_handler(r, u);

  1016.     } else {
  1017.         u->read_event_handler(r, u);
  1018.     }

  1019.     ngx_http_run_posted_requests(c);
  1020. }


  1021. static void
  1022. ngx_http_upstream_rd_check_broken_connection(ngx_http_request_t *r)
  1023. {
  1024.     ngx_http_upstream_check_broken_connection(r, r->connection->read);
  1025. }


  1026. static void
  1027. ngx_http_upstream_wr_check_broken_connection(ngx_http_request_t *r)
  1028. {
  1029.     ngx_http_upstream_check_broken_connection(r, r->connection->write);
  1030. }


  1031. static void
  1032. ngx_http_upstream_check_broken_connection(ngx_http_request_t *r,
  1033.     ngx_event_t *ev)
  1034. {
  1035.     int                  n;
  1036.     char                 buf[1];
  1037.     ngx_err_t            err;
  1038.     ngx_int_t            event;
  1039.     ngx_connection_t     *c;
  1040.     ngx_http_upstream_t  *u;

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

  1044.     c = r->connection;
  1045.     u = r->upstream;

  1046.     if (c->error) {
  1047.         if ((ngx_event_flags & NGX_USE_LEVEL_EVENT) && ev->active) {

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

  1049.             if (ngx_del_event(ev, event, 0) != NGX_OK) {
  1050.                 ngx_http_upstream_finalize_request(r, u,
  1051.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1052.                 return;
  1053.             }
  1054.         }

  1055.         if (!u->cacheable) {
  1056.             ngx_http_upstream_finalize_request(r, u,
  1057.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1058.         }

  1059.         return;
  1060.     }

  1061. #if (NGX_HTTP_V2)
  1062.     if (r->stream) {
  1063.         return;
  1064.     }
  1065. #endif

  1066. #if (NGX_HTTP_V3)

  1067.     if (c->quic) {
  1068.         if (c->write->error) {
  1069.             ngx_http_upstream_finalize_request(r, u,
  1070.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1071.         }

  1072.         return;
  1073.     }

  1074. #endif

  1075. #if (NGX_HAVE_KQUEUE)

  1076.     if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) {

  1077.         if (!ev->pending_eof) {
  1078.             return;
  1079.         }

  1080.         ev->eof = 1;
  1081.         c->error = 1;

  1082.         if (ev->kq_errno) {
  1083.             ev->error = 1;
  1084.         }

  1085.         if (!u->cacheable && u->peer.connection) {
  1086.             ngx_log_error(NGX_LOG_INFO, ev->log, ev->kq_errno,
  1087.                           "kevent() reported that client prematurely closed "
  1088.                           "connection, so upstream connection is closed too");
  1089.             ngx_http_upstream_finalize_request(r, u,
  1090.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1091.             return;
  1092.         }

  1093.         ngx_log_error(NGX_LOG_INFO, ev->log, ev->kq_errno,
  1094.                       "kevent() reported that client prematurely closed "
  1095.                       "connection");

  1096.         if (u->peer.connection == NULL) {
  1097.             ngx_http_upstream_finalize_request(r, u,
  1098.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1099.         }

  1100.         return;
  1101.     }

  1102. #endif

  1103. #if (NGX_HAVE_EPOLLRDHUP)

  1104.     if ((ngx_event_flags & NGX_USE_EPOLL_EVENT) && ngx_use_epoll_rdhup) {
  1105.         socklen_t  len;

  1106.         if (!ev->pending_eof) {
  1107.             return;
  1108.         }

  1109.         ev->eof = 1;
  1110.         c->error = 1;

  1111.         err = 0;
  1112.         len = sizeof(ngx_err_t);

  1113.         /*
  1114.          * BSDs and Linux return 0 and set a pending error in err
  1115.          * Solaris returns -1 and sets errno
  1116.          */

  1117.         if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, (void *) &err, &len)
  1118.             == -1)
  1119.         {
  1120.             err = ngx_socket_errno;
  1121.         }

  1122.         if (err) {
  1123.             ev->error = 1;
  1124.         }

  1125.         if (!u->cacheable && u->peer.connection) {
  1126.             ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1127.                         "epoll_wait() reported that client prematurely closed "
  1128.                         "connection, so upstream connection is closed too");
  1129.             ngx_http_upstream_finalize_request(r, u,
  1130.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1131.             return;
  1132.         }

  1133.         ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1134.                       "epoll_wait() reported that client prematurely closed "
  1135.                       "connection");

  1136.         if (u->peer.connection == NULL) {
  1137.             ngx_http_upstream_finalize_request(r, u,
  1138.                                                NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1139.         }

  1140.         return;
  1141.     }

  1142. #endif

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

  1144.     err = ngx_socket_errno;

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

  1147.     if (ev->write && (n >= 0 || err == NGX_EAGAIN)) {
  1148.         return;
  1149.     }

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

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

  1152.         if (ngx_del_event(ev, event, 0) != NGX_OK) {
  1153.             ngx_http_upstream_finalize_request(r, u,
  1154.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1155.             return;
  1156.         }
  1157.     }

  1158.     if (n > 0) {
  1159.         return;
  1160.     }

  1161.     if (n == -1) {
  1162.         if (err == NGX_EAGAIN) {
  1163.             return;
  1164.         }

  1165.         ev->error = 1;

  1166.     } else { /* n == 0 */
  1167.         err = 0;
  1168.     }

  1169.     ev->eof = 1;
  1170.     c->error = 1;

  1171.     if (!u->cacheable && u->peer.connection) {
  1172.         ngx_log_error(NGX_LOG_INFO, ev->log, err,
  1173.                       "client prematurely closed connection, "
  1174.                       "so upstream connection is closed too");
  1175.         ngx_http_upstream_finalize_request(r, u,
  1176.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1177.         return;
  1178.     }

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

  1181.     if (u->peer.connection == NULL) {
  1182.         ngx_http_upstream_finalize_request(r, u,
  1183.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  1184.     }
  1185. }


  1186. static void
  1187. ngx_http_upstream_connect(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1188. {
  1189.     ngx_int_t                  rc;
  1190.     ngx_connection_t          *c;
  1191.     ngx_http_core_loc_conf_t  *clcf;

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

  1193.     if (u->state && u->state->response_time == (ngx_msec_t) -1) {
  1194.         u->state->response_time = ngx_current_msec - u->start_time;
  1195.     }

  1196.     u->state = ngx_array_push(r->upstream_states);
  1197.     if (u->state == NULL) {
  1198.         ngx_http_upstream_finalize_request(r, u,
  1199.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1200.         return;
  1201.     }

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

  1203.     u->start_time = ngx_current_msec;

  1204.     u->state->response_time = (ngx_msec_t) -1;
  1205.     u->state->connect_time = (ngx_msec_t) -1;
  1206.     u->state->header_time = (ngx_msec_t) -1;

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

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

  1210.     if (rc == NGX_ERROR) {
  1211.         ngx_http_upstream_finalize_request(r, u,
  1212.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1213.         return;
  1214.     }

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

  1216. #if (NGX_HTTP_UPSTREAM_ZONE)
  1217.     if (u->upstream && u->upstream->shm_zone
  1218.         && (u->upstream->flags & NGX_HTTP_UPSTREAM_MODIFY))
  1219.     {
  1220.         u->state->peer = ngx_palloc(r->pool,
  1221.                                     sizeof(ngx_str_t) + u->peer.name->len);
  1222.         if (u->state->peer == NULL) {
  1223.             ngx_http_upstream_finalize_request(r, u,
  1224.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1225.             return;
  1226.         }

  1227.         u->state->peer->len = u->peer.name->len;
  1228.         u->state->peer->data = (u_char *) (u->state->peer + 1);
  1229.         ngx_memcpy(u->state->peer->data, u->peer.name->data, u->peer.name->len);

  1230.         u->peer.name = u->state->peer;
  1231.     }
  1232. #endif

  1233.     if (rc == NGX_BUSY) {
  1234.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "no live upstreams");
  1235.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_NOLIVE);
  1236.         return;
  1237.     }

  1238.     if (rc == NGX_DECLINED) {
  1239.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1240.         return;
  1241.     }

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

  1243.     c = u->peer.connection;

  1244.     c->requests++;

  1245.     c->data = r;

  1246.     c->write->handler = ngx_http_upstream_handler;
  1247.     c->read->handler = ngx_http_upstream_handler;

  1248.     u->write_event_handler = ngx_http_upstream_send_request_handler;
  1249.     u->read_event_handler = ngx_http_upstream_process_header;

  1250.     c->sendfile &= r->connection->sendfile;
  1251.     u->output.sendfile = c->sendfile;

  1252.     if (r->connection->tcp_nopush == NGX_TCP_NOPUSH_DISABLED) {
  1253.         c->tcp_nopush = NGX_TCP_NOPUSH_DISABLED;
  1254.     }

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

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

  1257.         c->pool = ngx_create_pool(128, r->connection->log);
  1258.         if (c->pool == NULL) {
  1259.             ngx_http_upstream_finalize_request(r, u,
  1260.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1261.             return;
  1262.         }
  1263.     }

  1264.     c->log = r->connection->log;
  1265.     c->pool->log = c->log;
  1266.     c->read->log = c->log;
  1267.     c->write->log = c->log;

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

  1269.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  1270.     u->writer.out = NULL;
  1271.     u->writer.last = &u->writer.out;
  1272.     u->writer.connection = c;
  1273.     u->writer.limit = clcf->sendfile_max_chunk;

  1274.     if (u->request_sent || u->response_received) {
  1275.         if (ngx_http_upstream_reinit(r, u) != NGX_OK) {
  1276.             ngx_http_upstream_finalize_request(r, u,
  1277.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1278.             return;
  1279.         }
  1280.     }

  1281.     if (r->request_body
  1282.         && r->request_body->buf
  1283.         && r->request_body->temp_file
  1284.         && r == r->main)
  1285.     {
  1286.         /*
  1287.          * the r->request_body->buf can be reused for one request only,
  1288.          * the subrequests should allocate their own temporary bufs
  1289.          */

  1290.         u->output.free = ngx_alloc_chain_link(r->pool);
  1291.         if (u->output.free == NULL) {
  1292.             ngx_http_upstream_finalize_request(r, u,
  1293.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1294.             return;
  1295.         }

  1296.         u->output.free->buf = r->request_body->buf;
  1297.         u->output.free->next = NULL;
  1298.         u->output.allocated = 1;

  1299.         r->request_body->buf->pos = r->request_body->buf->start;
  1300.         r->request_body->buf->last = r->request_body->buf->start;
  1301.         r->request_body->buf->tag = u->output.tag;
  1302.     }

  1303.     u->request_sent = 0;
  1304.     u->request_body_sent = 0;
  1305.     u->request_body_blocked = 0;
  1306.     u->response_received = 0;

  1307.     if (rc == NGX_AGAIN) {
  1308.         ngx_add_timer(c->write, u->conf->connect_timeout);
  1309.         return;
  1310.     }

  1311. #if (NGX_HTTP_SSL)

  1312.     if (u->ssl && c->ssl == NULL) {
  1313.         ngx_http_upstream_ssl_init_connection(r, u, c);
  1314.         return;
  1315.     }

  1316. #endif

  1317.     ngx_http_upstream_send_request(r, u, 1);
  1318. }


  1319. #if (NGX_HTTP_SSL)

  1320. static void
  1321. ngx_http_upstream_ssl_init_connection(ngx_http_request_t *r,
  1322.     ngx_http_upstream_t *u, ngx_connection_t *c)
  1323. {
  1324.     ngx_int_t                  rc;
  1325.     ngx_http_core_loc_conf_t  *clcf;

  1326.     if (ngx_http_upstream_test_connect(c) != NGX_OK) {
  1327.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1328.         return;
  1329.     }

  1330.     if (ngx_ssl_create_connection(u->conf->ssl, c,
  1331.                                   NGX_SSL_BUFFER|NGX_SSL_CLIENT)
  1332.         != NGX_OK)
  1333.     {
  1334.         ngx_http_upstream_finalize_request(r, u,
  1335.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1336.         return;
  1337.     }

  1338.     if (u->conf->ssl_server_name || u->conf->ssl_verify) {
  1339.         if (ngx_http_upstream_ssl_name(r, u, c) != NGX_OK) {
  1340.             ngx_http_upstream_finalize_request(r, u,
  1341.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1342.             return;
  1343.         }
  1344.     }

  1345.     if (u->conf->ssl_certificate
  1346.         && u->conf->ssl_certificate->value.len
  1347.         && (u->conf->ssl_certificate->lengths
  1348.             || u->conf->ssl_certificate_key->lengths))
  1349.     {
  1350.         if (ngx_http_upstream_ssl_certificate(r, u, c) != NGX_OK) {
  1351.             ngx_http_upstream_finalize_request(r, u,
  1352.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1353.             return;
  1354.         }
  1355.     }

  1356. #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation

  1357.     if (u->ssl_alpn_protocol.len) {
  1358.         if (SSL_set_alpn_protos(c->ssl->connection, u->ssl_alpn_protocol.data,
  1359.                                 u->ssl_alpn_protocol.len)
  1360.             != 0)
  1361.         {
  1362.             ngx_ssl_error(NGX_LOG_ERR, c->log, 0,
  1363.                           "SSL_set_alpn_protos() failed");
  1364.             ngx_http_upstream_finalize_request(r, u,
  1365.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1366.             return;
  1367.         }
  1368.     }

  1369. #endif

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

  1372.         if (u->peer.set_session(&u->peer, u->peer.data) != NGX_OK) {
  1373.             ngx_http_upstream_finalize_request(r, u,
  1374.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1375.             return;
  1376.         }

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

  1378.         clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  1379.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  1380.             ngx_http_upstream_finalize_request(r, u,
  1381.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1382.             return;
  1383.         }
  1384.     }

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

  1386.     rc = ngx_ssl_handshake(c);

  1387.     if (rc == NGX_AGAIN) {

  1388.         if (!c->write->timer_set) {
  1389.             ngx_add_timer(c->write, u->conf->connect_timeout);
  1390.         }

  1391.         c->ssl->handler = ngx_http_upstream_ssl_handshake_handler;
  1392.         return;
  1393.     }

  1394.     ngx_http_upstream_ssl_handshake(r, u, c);
  1395. }


  1396. static void
  1397. ngx_http_upstream_ssl_handshake_handler(ngx_connection_t *c)
  1398. {
  1399.     ngx_http_request_t   *r;
  1400.     ngx_http_upstream_t  *u;

  1401.     r = c->data;

  1402.     u = r->upstream;
  1403.     c = r->connection;

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

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

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

  1409.     ngx_http_run_posted_requests(c);
  1410. }


  1411. static void
  1412. ngx_http_upstream_ssl_handshake(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1413.     ngx_connection_t *c)
  1414. {
  1415.     long  rc;

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

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

  1419.             if (rc != X509_V_OK) {
  1420.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1421.                               "upstream SSL certificate verify error: (%l:%s)",
  1422.                               rc, X509_verify_cert_error_string(rc));
  1423.                 goto failed;
  1424.             }

  1425.             if (ngx_ssl_check_host(c, &u->ssl_name) != NGX_OK) {
  1426.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1427.                               "upstream SSL certificate does not match \"%V\"",
  1428.                               &u->ssl_name);
  1429.                 goto failed;
  1430.             }
  1431.         }

  1432.         if (!c->ssl->sendfile) {
  1433.             c->sendfile = 0;
  1434.             u->output.sendfile = 0;
  1435.         }

  1436.         c->write->handler = ngx_http_upstream_handler;
  1437.         c->read->handler = ngx_http_upstream_handler;

  1438.         ngx_http_upstream_send_request(r, u, 1);

  1439.         return;
  1440.     }

  1441.     if (c->write->timedout) {
  1442.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1443.         return;
  1444.     }

  1445. failed:

  1446.     ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1447. }


  1448. static void
  1449. ngx_http_upstream_ssl_save_session(ngx_connection_t *c)
  1450. {
  1451.     ngx_http_request_t   *r;
  1452.     ngx_http_upstream_t  *u;

  1453.     if (c->idle) {
  1454.         return;
  1455.     }

  1456.     r = c->data;

  1457.     u = r->upstream;
  1458.     c = r->connection;

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

  1460.     u->peer.save_session(&u->peer, u->peer.data);
  1461. }


  1462. static ngx_int_t
  1463. ngx_http_upstream_ssl_name(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1464.     ngx_connection_t *c)
  1465. {
  1466.     u_char     *p, *last;
  1467.     ngx_str_t   name;

  1468.     if (u->conf->ssl_name) {
  1469.         if (ngx_http_complex_value(r, u->conf->ssl_name, &name) != NGX_OK) {
  1470.             return NGX_ERROR;
  1471.         }

  1472.     } else {
  1473.         name = u->ssl_name;
  1474.     }

  1475.     if (name.len == 0) {
  1476.         goto done;
  1477.     }

  1478.     /*
  1479.      * ssl name here may contain port, notably if derived from $proxy_host
  1480.      * or $http_host; we have to strip it
  1481.      */

  1482.     p = name.data;
  1483.     last = name.data + name.len;

  1484.     if (*p == '[') {
  1485.         p = ngx_strlchr(p, last, ']');

  1486.         if (p == NULL) {
  1487.             p = name.data;
  1488.         }
  1489.     }

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

  1491.     if (p != NULL) {
  1492.         name.len = p - name.data;
  1493.     }

  1494.     if (!u->conf->ssl_server_name) {
  1495.         goto done;
  1496.     }

  1497. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME

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

  1499.     if (name.len == 0 || *name.data == '[') {
  1500.         goto done;
  1501.     }

  1502.     if (ngx_inet_addr(name.data, name.len) != INADDR_NONE) {
  1503.         goto done;
  1504.     }

  1505.     /*
  1506.      * SSL_set_tlsext_host_name() needs a null-terminated string,
  1507.      * hence we explicitly null-terminate name here
  1508.      */

  1509.     p = ngx_pnalloc(r->pool, name.len + 1);
  1510.     if (p == NULL) {
  1511.         return NGX_ERROR;
  1512.     }

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

  1514.     name.data = p;

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

  1517.     if (SSL_set_tlsext_host_name(c->ssl->connection,
  1518.                                  (char *) name.data)
  1519.         == 0)
  1520.     {
  1521.         ngx_ssl_error(NGX_LOG_ERR, r->connection->log, 0,
  1522.                       "SSL_set_tlsext_host_name(\"%s\") failed", name.data);
  1523.         return NGX_ERROR;
  1524.     }

  1525. #endif

  1526. done:

  1527.     u->ssl_name = name;

  1528.     return NGX_OK;
  1529. }


  1530. static ngx_int_t
  1531. ngx_http_upstream_ssl_certificate(ngx_http_request_t *r,
  1532.     ngx_http_upstream_t *u, ngx_connection_t *c)
  1533. {
  1534.     ngx_str_t  cert, key;

  1535.     if (ngx_http_complex_value(r, u->conf->ssl_certificate, &cert)
  1536.         != NGX_OK)
  1537.     {
  1538.         return NGX_ERROR;
  1539.     }

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

  1542.     if (*cert.data == '\0') {
  1543.         return NGX_OK;
  1544.     }

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

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

  1552.     if (ngx_ssl_connection_certificate(c, r->pool, &cert, &key,
  1553.                                        u->conf->ssl_certificate_cache,
  1554.                                        u->conf->ssl_passwords)
  1555.         != NGX_OK)
  1556.     {
  1557.         return NGX_ERROR;
  1558.     }

  1559.     return NGX_OK;
  1560. }

  1561. #endif


  1562. static ngx_int_t
  1563. ngx_http_upstream_reinit(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1564. {
  1565.     off_t         file_pos;
  1566.     ngx_chain_t  *cl;

  1567.     if (u->reinit_request(r) != NGX_OK) {
  1568.         return NGX_ERROR;
  1569.     }

  1570.     u->early_hints_length = 0;
  1571.     u->keepalive = 0;
  1572.     u->upgrade = 0;
  1573.     u->error = 0;

  1574.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  1575.     u->headers_in.content_length_n = -1;
  1576.     u->headers_in.last_modified_time = -1;

  1577.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  1578.                       sizeof(ngx_table_elt_t))
  1579.         != NGX_OK)
  1580.     {
  1581.         return NGX_ERROR;
  1582.     }

  1583.     if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  1584.                       sizeof(ngx_table_elt_t))
  1585.         != NGX_OK)
  1586.     {
  1587.         return NGX_ERROR;
  1588.     }

  1589.     /* reinit the request chain */

  1590.     file_pos = 0;

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

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

  1594.         if (cl->buf->in_file) {
  1595.             cl->buf->file_pos = file_pos;
  1596.             file_pos = cl->buf->file_last;
  1597.         }
  1598.     }

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

  1600.     if (r->request_body && r->request_body->temp_file
  1601.         && r != r->main && u->output.buf)
  1602.     {
  1603.         u->output.free = ngx_alloc_chain_link(r->pool);
  1604.         if (u->output.free == NULL) {
  1605.             return NGX_ERROR;
  1606.         }

  1607.         u->output.free->buf = u->output.buf;
  1608.         u->output.free->next = NULL;

  1609.         u->output.buf->pos = u->output.buf->start;
  1610.         u->output.buf->last = u->output.buf->start;
  1611.     }

  1612.     u->output.buf = NULL;
  1613.     u->output.in = NULL;
  1614.     u->output.busy = NULL;

  1615.     /* reinit u->buffer */

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

  1617. #if (NGX_HTTP_CACHE)

  1618.     if (r->cache) {
  1619.         u->buffer.pos += r->cache->header_start;
  1620.     }

  1621. #endif

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

  1623.     return NGX_OK;
  1624. }


  1625. static void
  1626. ngx_http_upstream_send_request(ngx_http_request_t *r, ngx_http_upstream_t *u,
  1627.     ngx_uint_t do_write)
  1628. {
  1629.     ngx_int_t          rc;
  1630.     ngx_connection_t  *c;

  1631.     c = u->peer.connection;

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

  1634.     if (u->state->connect_time == (ngx_msec_t) -1) {
  1635.         u->state->connect_time = ngx_current_msec - u->start_time;
  1636.     }

  1637.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {
  1638.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1639.         return;
  1640.     }

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

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

  1643.     if (rc == NGX_ERROR) {
  1644.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1645.         return;
  1646.     }

  1647.     if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  1648.         ngx_http_upstream_finalize_request(r, u, rc);
  1649.         return;
  1650.     }

  1651.     if (rc == NGX_AGAIN) {
  1652.         if (!c->write->ready || u->request_body_blocked) {
  1653.             ngx_add_timer(c->write, u->conf->send_timeout);

  1654.         } else if (c->write->timer_set) {
  1655.             ngx_del_timer(c->write);
  1656.         }

  1657.         if (ngx_handle_write_event(c->write, u->conf->send_lowat) != NGX_OK) {
  1658.             ngx_http_upstream_finalize_request(r, u,
  1659.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1660.             return;
  1661.         }

  1662.         if (c->write->ready && c->tcp_nopush == NGX_TCP_NOPUSH_SET) {
  1663.             if (ngx_tcp_push(c->fd) == -1) {
  1664.                 ngx_log_error(NGX_LOG_CRIT, c->log, ngx_socket_errno,
  1665.                               ngx_tcp_push_n " failed");
  1666.                 ngx_http_upstream_finalize_request(r, u,
  1667.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1668.                 return;
  1669.             }

  1670.             c->tcp_nopush = NGX_TCP_NOPUSH_UNSET;
  1671.         }

  1672.         if (c->read->ready) {
  1673.             ngx_post_event(c->read, &ngx_posted_events);
  1674.         }

  1675.         return;
  1676.     }

  1677.     /* rc == NGX_OK */

  1678.     if (c->write->timer_set) {
  1679.         ngx_del_timer(c->write);
  1680.     }

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

  1689.         c->tcp_nopush = NGX_TCP_NOPUSH_UNSET;
  1690.     }

  1691.     if (!u->conf->preserve_output) {
  1692.         u->write_event_handler = ngx_http_upstream_dummy_handler;
  1693.     }

  1694.     if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  1695.         ngx_http_upstream_finalize_request(r, u,
  1696.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1697.         return;
  1698.     }

  1699.     if (!u->request_body_sent) {
  1700.         u->request_body_sent = 1;

  1701.         if (u->header_sent) {
  1702.             return;
  1703.         }

  1704.         if (u->conf->ignore_input) {
  1705.             ngx_http_upstream_process_header(r, u);
  1706.             return;
  1707.         }

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

  1709.         if (c->read->ready) {
  1710.             ngx_http_upstream_process_header(r, u);
  1711.             return;
  1712.         }
  1713.     }
  1714. }


  1715. static ngx_int_t
  1716. ngx_http_upstream_send_request_body(ngx_http_request_t *r,
  1717.     ngx_http_upstream_t *u, ngx_uint_t do_write)
  1718. {
  1719.     ngx_int_t                  rc;
  1720.     ngx_chain_t               *out, *cl, *ln;
  1721.     ngx_connection_t          *c;
  1722.     ngx_http_core_loc_conf_t  *clcf;

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

  1725.     if (!r->request_body_no_buffering) {

  1726.         /* buffered request body */

  1727.         if (!u->request_sent) {
  1728.             u->request_sent = 1;
  1729.             out = u->request_bufs;

  1730.         } else {
  1731.             out = NULL;
  1732.         }

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

  1734.         if (rc == NGX_AGAIN) {
  1735.             u->request_body_blocked = 1;

  1736.         } else {
  1737.             u->request_body_blocked = 0;
  1738.         }

  1739.         return rc;
  1740.     }

  1741.     if (!u->request_sent) {
  1742.         u->request_sent = 1;
  1743.         out = u->request_bufs;

  1744.         if (r->request_body->bufs) {
  1745.             for (cl = out; cl->next; cl = cl->next) { /* void */ }
  1746.             cl->next = r->request_body->bufs;
  1747.             r->request_body->bufs = NULL;
  1748.         }

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

  1751.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  1752.             return NGX_ERROR;
  1753.         }

  1754.         r->read_event_handler = ngx_http_upstream_read_request_handler;

  1755.     } else {
  1756.         out = NULL;
  1757.     }

  1758.     for ( ;; ) {

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

  1761.             if (rc == NGX_ERROR) {
  1762.                 return NGX_ERROR;
  1763.             }

  1764.             while (out) {
  1765.                 ln = out;
  1766.                 out = out->next;
  1767.                 ngx_free_chain(r->pool, ln);
  1768.             }

  1769.             if (rc == NGX_AGAIN) {
  1770.                 u->request_body_blocked = 1;

  1771.             } else {
  1772.                 u->request_body_blocked = 0;
  1773.             }

  1774.             if (rc == NGX_OK && !r->reading_body) {
  1775.                 break;
  1776.             }
  1777.         }

  1778.         if (r->reading_body) {
  1779.             /* read client request body */

  1780.             rc = ngx_http_read_unbuffered_request_body(r);

  1781.             if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  1782.                 return rc;
  1783.             }

  1784.             out = r->request_body->bufs;
  1785.             r->request_body->bufs = NULL;
  1786.         }

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

  1788.         if (out == NULL) {
  1789.             rc = NGX_AGAIN;
  1790.             break;
  1791.         }

  1792.         do_write = 1;
  1793.     }

  1794.     if (!r->reading_body) {
  1795.         if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {
  1796.             r->read_event_handler =
  1797.                                   ngx_http_upstream_rd_check_broken_connection;
  1798.         }
  1799.     }

  1800.     return rc;
  1801. }


  1802. static void
  1803. ngx_http_upstream_send_request_handler(ngx_http_request_t *r,
  1804.     ngx_http_upstream_t *u)
  1805. {
  1806.     ngx_connection_t  *c;

  1807.     c = u->peer.connection;

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

  1810.     if (c->write->timedout) {
  1811.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1812.         return;
  1813.     }

  1814. #if (NGX_HTTP_SSL)

  1815.     if (u->ssl && c->ssl == NULL) {
  1816.         ngx_http_upstream_ssl_init_connection(r, u, c);
  1817.         return;
  1818.     }

  1819. #endif

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

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

  1823.         return;
  1824.     }

  1825.     ngx_http_upstream_send_request(r, u, 1);
  1826. }


  1827. static void
  1828. ngx_http_upstream_read_request_handler(ngx_http_request_t *r)
  1829. {
  1830.     ngx_connection_t     *c;
  1831.     ngx_http_upstream_t  *u;

  1832.     c = r->connection;
  1833.     u = r->upstream;

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

  1836.     if (c->read->timedout) {
  1837.         c->timedout = 1;
  1838.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  1839.         return;
  1840.     }

  1841.     ngx_http_upstream_send_request(r, u, 0);
  1842. }


  1843. static void
  1844. ngx_http_upstream_process_header(ngx_http_request_t *r, ngx_http_upstream_t *u)
  1845. {
  1846.     ssize_t            n;
  1847.     ngx_int_t          rc;
  1848.     ngx_connection_t  *c;

  1849.     c = u->peer.connection;

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

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

  1853.     if (c->read->timedout) {
  1854.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);
  1855.         return;
  1856.     }

  1857.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {
  1858.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1859.         return;
  1860.     }

  1861.     if (u->buffer.start == NULL) {
  1862.         u->buffer.start = ngx_palloc(r->pool, u->conf->buffer_size);
  1863.         if (u->buffer.start == NULL) {
  1864.             ngx_http_upstream_finalize_request(r, u,
  1865.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1866.             return;
  1867.         }

  1868.         u->buffer.pos = u->buffer.start;
  1869.         u->buffer.last = u->buffer.start;
  1870.         u->buffer.end = u->buffer.start + u->conf->buffer_size;
  1871.         u->buffer.temporary = 1;

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

  1873.         if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  1874.                           sizeof(ngx_table_elt_t))
  1875.             != NGX_OK)
  1876.         {
  1877.             ngx_http_upstream_finalize_request(r, u,
  1878.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1879.             return;
  1880.         }

  1881.         if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  1882.                           sizeof(ngx_table_elt_t))
  1883.             != NGX_OK)
  1884.         {
  1885.             ngx_http_upstream_finalize_request(r, u,
  1886.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1887.             return;
  1888.         }

  1889. #if (NGX_HTTP_CACHE)

  1890.         if (r->cache) {
  1891.             u->buffer.pos += r->cache->header_start;
  1892.             u->buffer.last = u->buffer.pos;
  1893.         }
  1894. #endif
  1895.     }

  1896.     if (u->conf->ignore_input) {
  1897.         rc = u->process_header(r);
  1898.         goto done;
  1899.     }

  1900.     for ( ;; ) {

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

  1902.         if (n == NGX_AGAIN) {
  1903. #if 0
  1904.             ngx_add_timer(rev, u->read_timeout);
  1905. #endif

  1906.             if (ngx_handle_read_event(c->read, 0) != NGX_OK) {
  1907.                 ngx_http_upstream_finalize_request(r, u,
  1908.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  1909.                 return;
  1910.             }

  1911.             return;
  1912.         }

  1913.         if (n == 0) {
  1914.             ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1915.                           "upstream prematurely closed connection");
  1916.         }

  1917.         if (n == NGX_ERROR || n == 0) {
  1918.             ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1919.             return;
  1920.         }

  1921. #if (NGX_HTTP_SSL)
  1922.         if (u->ssl && c->ssl == NULL) {
  1923.             ngx_log_error(NGX_LOG_ERR, c->log, 0,
  1924.                           "upstream prematurely sent response");
  1925.             ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);
  1926.             return;
  1927.         }
  1928. #endif

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

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

  1931. #if 0
  1932.         u->valid_header_in = 0;

  1933.         u->peer.cached = 0;
  1934. #endif

  1935.         u->response_received = 1;

  1936. again:

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

  1938.         if (rc == NGX_AGAIN) {

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

  1942.                 ngx_http_upstream_next(r, u,
  1943.                                        NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  1944.                 return;
  1945.             }

  1946.             continue;
  1947.         }

  1948.         if (rc == NGX_HTTP_UPSTREAM_EARLY_HINTS) {
  1949.             rc = ngx_http_upstream_process_early_hints(r, u);

  1950.             if (rc == NGX_OK) {
  1951.                 goto again;
  1952.             }
  1953.         }

  1954.         break;
  1955.     }

  1956. done:

  1957.     if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  1958.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);
  1959.         return;
  1960.     }

  1961.     if (rc == NGX_ERROR) {
  1962.         ngx_http_upstream_finalize_request(r, u,
  1963.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  1964.         return;
  1965.     }

  1966.     /* rc == NGX_OK */

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

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

  1969.         if (ngx_http_upstream_test_next(r, u) == NGX_OK) {
  1970.             return;
  1971.         }

  1972.         if (ngx_http_upstream_intercept_errors(r, u) == NGX_OK) {
  1973.             return;
  1974.         }
  1975.     }

  1976.     if (u->peer.notify) {
  1977.         u->peer.notify(&u->peer, u->peer.data, NGX_HTTP_UPSTREAM_NOTIFY_HEADER);
  1978.     }

  1979.     if (ngx_http_upstream_process_headers(r, u) != NGX_OK) {
  1980.         return;
  1981.     }

  1982.     ngx_http_upstream_send_response(r, u);
  1983. }


  1984. static ngx_int_t
  1985. ngx_http_upstream_process_early_hints(ngx_http_request_t *r,
  1986.     ngx_http_upstream_t *u)
  1987. {
  1988.     u_char            *p;
  1989.     ngx_uint_t         i;
  1990.     ngx_list_part_t   *part;
  1991.     ngx_table_elt_t   *h, *ho;
  1992.     ngx_connection_t  *c;

  1993.     c = r->connection;

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

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

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

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

  1998.             part = &u->headers_in.headers.part;
  1999.             h = part->elts;

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

  2001.                 if (i >= part->nelts) {
  2002.                     if (part->next == NULL) {
  2003.                         break;
  2004.                     }

  2005.                     part = part->next;
  2006.                     h = part->elts;
  2007.                     i = 0;
  2008.                 }

  2009.                 if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2010.                                   h[i].lowcase_key, h[i].key.len))
  2011.                 {
  2012.                     continue;
  2013.                 }

  2014.                 ho = ngx_list_push(&r->headers_out.headers);
  2015.                 if (ho == NULL) {
  2016.                     return NGX_ERROR;
  2017.                 }

  2018.                 *ho = h[i];
  2019.             }

  2020.             if (ngx_http_send_early_hints(r) == NGX_ERROR) {
  2021.                 return NGX_ERROR;
  2022.             }

  2023.             if (c->buffered) {
  2024.                 if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  2025.                     return NGX_ERROR;
  2026.                 }

  2027.                 r->write_event_handler = ngx_http_upstream_early_hints_writer;
  2028.             }

  2029.         } else {
  2030.             ngx_log_error(NGX_LOG_INFO, c->log, 0,
  2031.                           "upstream sent too big early hints");
  2032.         }
  2033.     }

  2034.     ngx_http_clean_header(r);

  2035.     ngx_memzero(&u->headers_in, sizeof(ngx_http_upstream_headers_in_t));
  2036.     u->headers_in.content_length_n = -1;
  2037.     u->headers_in.last_modified_time = -1;

  2038.     if (ngx_list_init(&u->headers_in.headers, r->pool, 8,
  2039.                       sizeof(ngx_table_elt_t))
  2040.         != NGX_OK)
  2041.     {
  2042.         return NGX_ERROR;
  2043.     }

  2044.     if (ngx_list_init(&u->headers_in.trailers, r->pool, 2,
  2045.                       sizeof(ngx_table_elt_t))
  2046.         != NGX_OK)
  2047.     {
  2048.         return NGX_ERROR;
  2049.     }

  2050.     p = u->buffer.pos;

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

  2052. #if (NGX_HTTP_CACHE)

  2053.     if (r->cache) {
  2054.         u->buffer.pos += r->cache->header_start;
  2055.     }

  2056. #endif

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

  2058.     return NGX_OK;
  2059. }


  2060. static void
  2061. ngx_http_upstream_early_hints_writer(ngx_http_request_t *r)
  2062. {
  2063.     ngx_connection_t     *c;
  2064.     ngx_http_upstream_t  *u;

  2065.     c = r->connection;
  2066.     u = r->upstream;

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

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

  2070.     if (ngx_http_write_filter(r, NULL) == NGX_ERROR) {
  2071.         ngx_http_upstream_finalize_request(r, u,
  2072.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  2073.         return;
  2074.     }

  2075.     if (!c->buffered) {
  2076.         if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {
  2077.             r->write_event_handler =
  2078.                                   ngx_http_upstream_wr_check_broken_connection;

  2079.         } else {
  2080.             r->write_event_handler = ngx_http_request_empty_handler;
  2081.         }
  2082.     }

  2083.     if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
  2084.         ngx_http_upstream_finalize_request(r, u,
  2085.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);
  2086.     }
  2087. }


  2088. static ngx_int_t
  2089. ngx_http_upstream_test_next(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2090. {
  2091.     ngx_msec_t                 timeout;
  2092.     ngx_uint_t                 status, mask;
  2093.     ngx_http_upstream_next_t  *un;

  2094.     status = u->headers_in.status_n;

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

  2096.         if (status != un->status) {
  2097.             continue;
  2098.         }

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

  2100.         if (u->request_sent
  2101.             && (r->method & (NGX_HTTP_POST|NGX_HTTP_LOCK|NGX_HTTP_PATCH)))
  2102.         {
  2103.             mask = un->mask | NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT;

  2104.         } else {
  2105.             mask = un->mask;
  2106.         }

  2107.         if (u->peer.tries > 1
  2108.             && ((u->conf->next_upstream & mask) == mask)
  2109.             && !(u->request_sent && r->request_body_no_buffering)
  2110.             && !(timeout && ngx_current_msec - u->peer.start_time >= timeout))
  2111.         {
  2112.             ngx_http_upstream_next(r, u, un->mask);
  2113.             return NGX_OK;
  2114.         }

  2115. #if (NGX_HTTP_CACHE)

  2116.         if (u->cache_status == NGX_HTTP_CACHE_EXPIRED
  2117.             && (u->conf->cache_use_stale & un->mask))
  2118.         {
  2119.             ngx_int_t  rc;

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

  2121.             if (rc != NGX_OK) {
  2122.                 ngx_http_upstream_finalize_request(r, u, rc);
  2123.                 return NGX_OK;
  2124.             }

  2125.             u->cache_status = NGX_HTTP_CACHE_STALE;
  2126.             rc = ngx_http_upstream_cache_send(r, u);

  2127.             if (rc == NGX_DONE) {
  2128.                 return NGX_OK;
  2129.             }

  2130.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  2131.                 rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  2132.             }

  2133.             ngx_http_upstream_finalize_request(r, u, rc);
  2134.             return NGX_OK;
  2135.         }

  2136. #endif

  2137.         break;
  2138.     }

  2139. #if (NGX_HTTP_CACHE)

  2140.     if (status == NGX_HTTP_NOT_MODIFIED
  2141.         && u->cache_status == NGX_HTTP_CACHE_EXPIRED
  2142.         && u->conf->cache_revalidate)
  2143.     {
  2144.         time_t     now, valid, updating, error;
  2145.         ngx_int_t  rc;

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

  2148.         now = ngx_time();

  2149.         valid = r->cache->valid_sec;
  2150.         updating = r->cache->updating_sec;
  2151.         error = r->cache->error_sec;

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

  2153.         if (rc != NGX_OK) {
  2154.             ngx_http_upstream_finalize_request(r, u, rc);
  2155.             return NGX_OK;
  2156.         }

  2157.         u->cache_status = NGX_HTTP_CACHE_REVALIDATED;
  2158.         rc = ngx_http_upstream_cache_send(r, u);

  2159.         if (rc == NGX_DONE) {
  2160.             return NGX_OK;
  2161.         }

  2162.         if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  2163.             rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  2164.         }

  2165.         if (valid == 0) {
  2166.             valid = r->cache->valid_sec;
  2167.             updating = r->cache->updating_sec;
  2168.             error = r->cache->error_sec;
  2169.         }

  2170.         if (valid == 0) {
  2171.             valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2172.                                               u->headers_in.status_n);
  2173.             if (valid) {
  2174.                 valid = now + valid;
  2175.             }
  2176.         }

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

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

  2182.             ngx_http_file_cache_update_header(r);
  2183.         }

  2184.         ngx_http_upstream_finalize_request(r, u, rc);
  2185.         return NGX_OK;
  2186.     }

  2187. #endif

  2188.     return NGX_DECLINED;
  2189. }


  2190. static ngx_int_t
  2191. ngx_http_upstream_intercept_errors(ngx_http_request_t *r,
  2192.     ngx_http_upstream_t *u)
  2193. {
  2194.     ngx_int_t                  status;
  2195.     ngx_uint_t                 i;
  2196.     ngx_table_elt_t           *h, *ho, **ph;
  2197.     ngx_http_err_page_t       *err_page;
  2198.     ngx_http_core_loc_conf_t  *clcf;

  2199.     status = u->headers_in.status_n;

  2200.     if (status == NGX_HTTP_NOT_FOUND && u->conf->intercept_404) {
  2201.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_NOT_FOUND);
  2202.         return NGX_OK;
  2203.     }

  2204.     if (!u->conf->intercept_errors) {
  2205.         return NGX_DECLINED;
  2206.     }

  2207.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2208.     if (clcf->error_pages == NULL) {
  2209.         return NGX_DECLINED;
  2210.     }

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

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

  2214.             if (status == NGX_HTTP_UNAUTHORIZED
  2215.                 && u->headers_in.www_authenticate)
  2216.             {
  2217.                 h = u->headers_in.www_authenticate;
  2218.                 ph = &r->headers_out.www_authenticate;

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

  2221.                     if (ho == NULL) {
  2222.                         ngx_http_upstream_finalize_request(r, u,
  2223.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  2224.                         return NGX_OK;
  2225.                     }

  2226.                     *ho = *h;
  2227.                     ho->next = NULL;

  2228.                     *ph = ho;
  2229.                     ph = &ho->next;

  2230.                     h = h->next;
  2231.                 }
  2232.             }

  2233. #if (NGX_HTTP_CACHE)

  2234.             if (r->cache) {

  2235.                 if (u->headers_in.no_cache || u->headers_in.expired) {
  2236.                     u->cacheable = 0;
  2237.                 }

  2238.                 if (u->cacheable) {
  2239.                     time_t  valid;

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

  2241.                     if (valid == 0) {
  2242.                         valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2243.                                                           status);
  2244.                         if (valid) {
  2245.                             r->cache->valid_sec = ngx_time() + valid;
  2246.                         }
  2247.                     }

  2248.                     if (valid) {
  2249.                         r->cache->error = status;
  2250.                     }
  2251.                 }

  2252.                 ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2253.             }
  2254. #endif
  2255.             ngx_http_upstream_finalize_request(r, u, status);

  2256.             return NGX_OK;
  2257.         }
  2258.     }

  2259.     return NGX_DECLINED;
  2260. }


  2261. static ngx_int_t
  2262. ngx_http_upstream_test_connect(ngx_connection_t *c)
  2263. {
  2264.     int        err;
  2265.     socklen_t  len;

  2266. #if (NGX_HAVE_KQUEUE)

  2267.     if (ngx_event_flags & NGX_USE_KQUEUE_EVENT)  {
  2268.         if (c->write->pending_eof || c->read->pending_eof) {
  2269.             if (c->write->pending_eof) {
  2270.                 err = c->write->kq_errno;

  2271.             } else {
  2272.                 err = c->read->kq_errno;
  2273.             }

  2274.             c->log->action = "connecting to upstream";
  2275.             (void) ngx_connection_error(c, err,
  2276.                                     "kevent() reported that connect() failed");
  2277.             return NGX_ERROR;
  2278.         }

  2279.     } else
  2280. #endif
  2281.     {
  2282.         err = 0;
  2283.         len = sizeof(int);

  2284.         /*
  2285.          * BSDs and Linux return 0 and set a pending error in err
  2286.          * Solaris returns -1 and sets errno
  2287.          */

  2288.         if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, (void *) &err, &len)
  2289.             == -1)
  2290.         {
  2291.             err = ngx_socket_errno;
  2292.         }

  2293.         if (err) {
  2294.             c->log->action = "connecting to upstream";
  2295.             (void) ngx_connection_error(c, err, "connect() failed");
  2296.             return NGX_ERROR;
  2297.         }
  2298.     }

  2299.     return NGX_OK;
  2300. }


  2301. static ngx_int_t
  2302. ngx_http_upstream_process_headers(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2303. {
  2304.     ngx_str_t                       uri, args;
  2305.     ngx_uint_t                      i, flags;
  2306.     ngx_list_part_t                *part;
  2307.     ngx_table_elt_t                *h;
  2308.     ngx_http_upstream_header_t     *hh;
  2309.     ngx_http_upstream_main_conf_t  *umcf;

  2310.     umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);

  2311.     if (u->headers_in.no_cache || u->headers_in.expired) {
  2312.         u->cacheable = 0;
  2313.     }

  2314.     if (u->headers_in.x_accel_redirect
  2315.         && !(u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_REDIRECT))
  2316.     {
  2317.         ngx_http_upstream_finalize_request(r, u, NGX_DECLINED);

  2318.         part = &u->headers_in.headers.part;
  2319.         h = part->elts;

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

  2321.             if (i >= part->nelts) {
  2322.                 if (part->next == NULL) {
  2323.                     break;
  2324.                 }

  2325.                 part = part->next;
  2326.                 h = part->elts;
  2327.                 i = 0;
  2328.             }

  2329.             if (h[i].hash == 0) {
  2330.                 continue;
  2331.             }

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

  2334.             if (hh && hh->redirect) {
  2335.                 if (hh->copy_handler(r, &h[i], hh->conf) != NGX_OK) {
  2336.                     ngx_http_finalize_request(r,
  2337.                                               NGX_HTTP_INTERNAL_SERVER_ERROR);
  2338.                     return NGX_DONE;
  2339.                 }
  2340.             }
  2341.         }

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

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

  2345.         } else {
  2346.             ngx_str_null(&args);
  2347.             flags = NGX_HTTP_LOG_UNSAFE;

  2348.             if (ngx_http_parse_unsafe_uri(r, &uri, &args, &flags) != NGX_OK) {
  2349.                 ngx_http_finalize_request(r, NGX_HTTP_NOT_FOUND);
  2350.                 return NGX_DONE;
  2351.             }

  2352.             if (r->method != NGX_HTTP_HEAD) {
  2353.                 r->method = NGX_HTTP_GET;
  2354.                 r->method_name = ngx_http_core_get_method;
  2355.             }

  2356.             ngx_http_internal_redirect(r, &uri, &args);
  2357.         }

  2358.         ngx_http_finalize_request(r, NGX_DONE);
  2359.         return NGX_DONE;
  2360.     }

  2361.     part = &u->headers_in.headers.part;
  2362.     h = part->elts;

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

  2364.         if (i >= part->nelts) {
  2365.             if (part->next == NULL) {
  2366.                 break;
  2367.             }

  2368.             part = part->next;
  2369.             h = part->elts;
  2370.             i = 0;
  2371.         }

  2372.         if (h[i].hash == 0) {
  2373.             continue;
  2374.         }

  2375.         if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2376.                           h[i].lowcase_key, h[i].key.len))
  2377.         {
  2378.             continue;
  2379.         }

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

  2382.         if (hh) {
  2383.             if (hh->copy_handler(r, &h[i], hh->conf) != NGX_OK) {
  2384.                 ngx_http_upstream_finalize_request(r, u,
  2385.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  2386.                 return NGX_DONE;
  2387.             }

  2388.             continue;
  2389.         }

  2390.         if (ngx_http_upstream_copy_header_line(r, &h[i], 0) != NGX_OK) {
  2391.             ngx_http_upstream_finalize_request(r, u,
  2392.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);
  2393.             return NGX_DONE;
  2394.         }
  2395.     }

  2396.     if (r->headers_out.server && r->headers_out.server->value.data == NULL) {
  2397.         r->headers_out.server->hash = 0;
  2398.     }

  2399.     if (r->headers_out.date && r->headers_out.date->value.data == NULL) {
  2400.         r->headers_out.date->hash = 0;
  2401.     }

  2402.     r->headers_out.status = u->headers_in.status_n;
  2403.     r->headers_out.status_line = u->headers_in.status_line;

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

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

  2406.     if (u->conf->force_ranges) {
  2407.         r->allow_ranges = 1;
  2408.         r->single_range = 1;

  2409. #if (NGX_HTTP_CACHE)
  2410.         if (r->cached) {
  2411.             r->single_range = 0;
  2412.         }
  2413. #endif
  2414.     }

  2415.     u->length = -1;

  2416.     return NGX_OK;
  2417. }


  2418. static ngx_int_t
  2419. ngx_http_upstream_process_trailers(ngx_http_request_t *r,
  2420.     ngx_http_upstream_t *u)
  2421. {
  2422.     ngx_uint_t        i;
  2423.     ngx_list_part_t  *part;
  2424.     ngx_table_elt_t  *h, *ho;

  2425.     if (!u->conf->pass_trailers) {
  2426.         return NGX_OK;
  2427.     }

  2428.     part = &u->headers_in.trailers.part;
  2429.     h = part->elts;

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

  2431.         if (i >= part->nelts) {
  2432.             if (part->next == NULL) {
  2433.                 break;
  2434.             }

  2435.             part = part->next;
  2436.             h = part->elts;
  2437.             i = 0;
  2438.         }

  2439.         if (ngx_hash_find(&u->conf->hide_headers_hash, h[i].hash,
  2440.                           h[i].lowcase_key, h[i].key.len))
  2441.         {
  2442.             continue;
  2443.         }

  2444.         ho = ngx_list_push(&r->headers_out.trailers);
  2445.         if (ho == NULL) {
  2446.             return NGX_ERROR;
  2447.         }

  2448.         *ho = h[i];
  2449.     }

  2450.     return NGX_OK;
  2451. }


  2452. static void
  2453. ngx_http_upstream_send_response(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2454. {
  2455.     ssize_t                    n;
  2456.     ngx_int_t                  rc;
  2457.     ngx_event_pipe_t          *p;
  2458.     ngx_connection_t          *c;
  2459.     ngx_http_core_loc_conf_t  *clcf;

  2460.     rc = ngx_http_send_header(r);

  2461.     if (rc == NGX_ERROR || rc > NGX_OK || r->post_action) {
  2462.         ngx_http_upstream_finalize_request(r, u, rc);
  2463.         return;
  2464.     }

  2465.     u->header_sent = 1;

  2466.     if (u->upgrade) {

  2467. #if (NGX_HTTP_CACHE)

  2468.         if (r->cache) {
  2469.             ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2470.         }

  2471. #endif

  2472.         ngx_http_upstream_upgrade(r, u);
  2473.         return;
  2474.     }

  2475.     c = r->connection;

  2476.     if (r->header_only) {

  2477.         if (!u->buffering) {
  2478.             ngx_http_upstream_finalize_request(r, u, rc);
  2479.             return;
  2480.         }

  2481.         if (!u->cacheable && !u->store) {
  2482.             ngx_http_upstream_finalize_request(r, u, rc);
  2483.             return;
  2484.         }

  2485.         u->pipe->downstream_error = 1;
  2486.     }

  2487.     if (r->request_body && r->request_body->temp_file
  2488.         && r == r->main && !r->preserve_body
  2489.         && !u->conf->preserve_output)
  2490.     {
  2491.         ngx_pool_run_cleanup_file(r->pool, r->request_body->temp_file->file.fd);
  2492.         r->request_body->temp_file->file.fd = NGX_INVALID_FILE;
  2493.     }

  2494.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2495.     if (!u->buffering) {

  2496. #if (NGX_HTTP_CACHE)

  2497.         if (r->cache) {
  2498.             ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2499.         }

  2500. #endif

  2501.         if (u->input_filter == NULL) {
  2502.             u->input_filter_init = ngx_http_upstream_non_buffered_filter_init;
  2503.             u->input_filter = ngx_http_upstream_non_buffered_filter;
  2504.             u->input_filter_ctx = r;
  2505.         }

  2506.         u->read_event_handler = ngx_http_upstream_process_non_buffered_upstream;
  2507.         r->write_event_handler =
  2508.                              ngx_http_upstream_process_non_buffered_downstream;

  2509.         r->limit_rate = 0;
  2510.         r->limit_rate_set = 1;

  2511.         if (u->input_filter_init(u->input_filter_ctx) == NGX_ERROR) {
  2512.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2513.             return;
  2514.         }

  2515.         if (clcf->tcp_nodelay && ngx_tcp_nodelay(c) != NGX_OK) {
  2516.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2517.             return;
  2518.         }

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

  2520.         if (n) {
  2521.             u->buffer.last = u->buffer.pos;

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

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

  2527.             ngx_http_upstream_process_non_buffered_downstream(r);

  2528.         } else {
  2529.             u->buffer.pos = u->buffer.start;
  2530.             u->buffer.last = u->buffer.start;

  2531.             if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {
  2532.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2533.                 return;
  2534.             }

  2535.             ngx_http_upstream_process_non_buffered_upstream(r, u);
  2536.         }

  2537.         return;
  2538.     }

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

  2540. #if (NGX_HTTP_CACHE)

  2541.     if (r->cache && r->cache->file.fd != NGX_INVALID_FILE) {
  2542.         ngx_pool_run_cleanup_file(r->pool, r->cache->file.fd);
  2543.         r->cache->file.fd = NGX_INVALID_FILE;
  2544.     }

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

  2546.     case NGX_ERROR:
  2547.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2548.         return;

  2549.     case NGX_DECLINED:
  2550.         u->cacheable = 0;
  2551.         break;

  2552.     default: /* NGX_OK */

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

  2554.             /* create cache if previously bypassed */

  2555.             if (ngx_http_file_cache_create(r) != NGX_OK) {
  2556.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2557.                 return;
  2558.             }
  2559.         }

  2560.         break;
  2561.     }

  2562.     if (u->cacheable) {
  2563.         time_t  now, valid;

  2564.         now = ngx_time();

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

  2566.         if (valid == 0) {
  2567.             valid = ngx_http_file_cache_valid(u->conf->cache_valid,
  2568.                                               u->headers_in.status_n);
  2569.             if (valid) {
  2570.                 r->cache->valid_sec = now + valid;
  2571.             }
  2572.         }

  2573.         if (valid) {
  2574.             r->cache->date = now;
  2575.             r->cache->body_start = (u_short) (u->buffer.pos - u->buffer.start);

  2576.             if (u->headers_in.status_n == NGX_HTTP_OK
  2577.                 || u->headers_in.status_n == NGX_HTTP_PARTIAL_CONTENT)
  2578.             {
  2579.                 r->cache->last_modified = u->headers_in.last_modified_time;

  2580.                 if (u->headers_in.etag) {
  2581.                     r->cache->etag = u->headers_in.etag->value;

  2582.                 } else {
  2583.                     ngx_str_null(&r->cache->etag);
  2584.                 }

  2585.             } else {
  2586.                 r->cache->last_modified = -1;
  2587.                 ngx_str_null(&r->cache->etag);
  2588.             }

  2589.             if (ngx_http_file_cache_set_header(r, u->buffer.start) != NGX_OK) {
  2590.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2591.                 return;
  2592.             }

  2593.         } else {
  2594.             u->cacheable = 0;
  2595.         }
  2596.     }

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

  2599.     if (u->cacheable == 0 && r->cache) {
  2600.         ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  2601.     }

  2602.     if (r->header_only && !u->cacheable && !u->store) {
  2603.         ngx_http_upstream_finalize_request(r, u, 0);
  2604.         return;
  2605.     }

  2606. #endif

  2607.     p = u->pipe;

  2608.     p->output_filter = ngx_http_upstream_output_filter;
  2609.     p->output_ctx = r;
  2610.     p->tag = u->output.tag;
  2611.     p->bufs = u->conf->bufs;
  2612.     p->busy_size = u->conf->busy_buffers_size;
  2613.     p->upstream = u->peer.connection;
  2614.     p->downstream = c;
  2615.     p->pool = r->pool;
  2616.     p->log = c->log;
  2617.     p->limit_rate = ngx_http_complex_value_size(r, u->conf->limit_rate, 0);
  2618.     p->start_sec = ngx_time();

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

  2620.     p->temp_file = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t));
  2621.     if (p->temp_file == NULL) {
  2622.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2623.         return;
  2624.     }

  2625.     p->temp_file->file.fd = NGX_INVALID_FILE;
  2626.     p->temp_file->file.log = c->log;
  2627.     p->temp_file->path = u->conf->temp_path;
  2628.     p->temp_file->pool = r->pool;

  2629.     if (p->cacheable) {
  2630.         p->temp_file->persistent = 1;

  2631. #if (NGX_HTTP_CACHE)
  2632.         if (r->cache && !r->cache->file_cache->use_temp_path) {
  2633.             p->temp_file->path = r->cache->file_cache->path;
  2634.             p->temp_file->file.name = r->cache->file.name;
  2635.         }
  2636. #endif

  2637.     } else {
  2638.         p->temp_file->log_level = NGX_LOG_WARN;
  2639.         p->temp_file->warn = "an upstream response is buffered "
  2640.                              "to a temporary file";
  2641.     }

  2642.     p->max_temp_file_size = u->conf->max_temp_file_size;
  2643.     p->temp_file_write_size = u->conf->temp_file_write_size;

  2644. #if (NGX_THREADS)
  2645.     if (clcf->aio == NGX_HTTP_AIO_THREADS && clcf->aio_write) {
  2646.         p->thread_handler = ngx_http_upstream_thread_handler;
  2647.         p->thread_ctx = r;
  2648.     }
  2649. #endif

  2650.     p->preread_bufs = ngx_alloc_chain_link(r->pool);
  2651.     if (p->preread_bufs == NULL) {
  2652.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2653.         return;
  2654.     }

  2655.     p->preread_bufs->buf = &u->buffer;
  2656.     p->preread_bufs->next = NULL;
  2657.     u->buffer.recycled = 1;

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

  2659.     if (u->cacheable) {

  2660.         p->buf_to_file = ngx_calloc_buf(r->pool);
  2661.         if (p->buf_to_file == NULL) {
  2662.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2663.             return;
  2664.         }

  2665.         p->buf_to_file->start = u->buffer.start;
  2666.         p->buf_to_file->pos = u->buffer.start;
  2667.         p->buf_to_file->last = u->buffer.pos;
  2668.         p->buf_to_file->temporary = 1;
  2669.     }

  2670.     if (ngx_event_flags & NGX_USE_IOCP_EVENT) {
  2671.         /* the posted aio operation may corrupt a shadow buffer */
  2672.         p->single_buf = 1;
  2673.     }

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

  2676.     /*
  2677.      * event_pipe would do u->buffer.last += p->preread_size
  2678.      * as though these bytes were read
  2679.      */
  2680.     u->buffer.last = u->buffer.pos;

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

  2682.         /*
  2683.          * we need to disable the use of sendfile() if we use cyclic temp file
  2684.          * because the writing a new data may interfere with sendfile()
  2685.          * that uses the same kernel file pages (at least on FreeBSD)
  2686.          */

  2687.         p->cyclic_temp_file = 1;
  2688.         c->sendfile = 0;

  2689.     } else {
  2690.         p->cyclic_temp_file = 0;
  2691.     }

  2692.     p->read_timeout = u->conf->read_timeout;
  2693.     p->send_timeout = clcf->send_timeout;
  2694.     p->send_lowat = clcf->send_lowat;

  2695.     p->length = -1;

  2696.     if (u->input_filter_init
  2697.         && u->input_filter_init(p->input_ctx) != NGX_OK)
  2698.     {
  2699.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2700.         return;
  2701.     }

  2702.     u->read_event_handler = ngx_http_upstream_process_upstream;
  2703.     r->write_event_handler = ngx_http_upstream_process_downstream;

  2704.     ngx_http_upstream_process_upstream(r, u);
  2705. }


  2706. static void
  2707. ngx_http_upstream_upgrade(ngx_http_request_t *r, ngx_http_upstream_t *u)
  2708. {
  2709.     ngx_connection_t          *c;
  2710.     ngx_http_core_loc_conf_t  *clcf;

  2711.     c = r->connection;
  2712.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

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

  2714.     if (r != r->main) {
  2715.         ngx_log_error(NGX_LOG_ERR, c->log, 0,
  2716.                       "connection upgrade in subrequest");
  2717.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2718.         return;
  2719.     }

  2720.     r->keepalive = 0;
  2721.     c->log->action = "proxying upgraded connection";

  2722.     u->read_event_handler = ngx_http_upstream_upgraded_read_upstream;
  2723.     u->write_event_handler = ngx_http_upstream_upgraded_write_upstream;
  2724.     r->read_event_handler = ngx_http_upstream_upgraded_read_downstream;
  2725.     r->write_event_handler = ngx_http_upstream_upgraded_write_downstream;

  2726.     if (clcf->tcp_nodelay) {

  2727.         if (ngx_tcp_nodelay(c) != NGX_OK) {
  2728.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2729.             return;
  2730.         }

  2731.         if (ngx_tcp_nodelay(u->peer.connection) != NGX_OK) {
  2732.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2733.             return;
  2734.         }
  2735.     }

  2736.     if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {
  2737.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2738.         return;
  2739.     }

  2740.     if (u->peer.connection->read->ready
  2741.         || u->buffer.pos != u->buffer.last)
  2742.     {
  2743.         ngx_post_event(c->read, &ngx_posted_events);
  2744.         ngx_http_upstream_process_upgraded(r, 1, 1);
  2745.         return;
  2746.     }

  2747.     ngx_http_upstream_process_upgraded(r, 0, 1);
  2748. }


  2749. static void
  2750. ngx_http_upstream_upgraded_read_downstream(ngx_http_request_t *r)
  2751. {
  2752.     ngx_http_upstream_process_upgraded(r, 0, 0);
  2753. }


  2754. static void
  2755. ngx_http_upstream_upgraded_write_downstream(ngx_http_request_t *r)
  2756. {
  2757.     ngx_http_upstream_process_upgraded(r, 1, 1);
  2758. }


  2759. static void
  2760. ngx_http_upstream_upgraded_read_upstream(ngx_http_request_t *r,
  2761.     ngx_http_upstream_t *u)
  2762. {
  2763.     ngx_http_upstream_process_upgraded(r, 1, 0);
  2764. }


  2765. static void
  2766. ngx_http_upstream_upgraded_write_upstream(ngx_http_request_t *r,
  2767.     ngx_http_upstream_t *u)
  2768. {
  2769.     ngx_http_upstream_process_upgraded(r, 0, 1);
  2770. }


  2771. static void
  2772. ngx_http_upstream_process_upgraded(ngx_http_request_t *r,
  2773.     ngx_uint_t from_upstream, ngx_uint_t do_write)
  2774. {
  2775.     size_t                     size;
  2776.     ssize_t                    n;
  2777.     ngx_buf_t                 *b;
  2778.     ngx_uint_t                 flags;
  2779.     ngx_connection_t          *c, *downstream, *upstream, *dst, *src;
  2780.     ngx_http_upstream_t       *u;
  2781.     ngx_http_core_loc_conf_t  *clcf;

  2782.     c = r->connection;
  2783.     u = r->upstream;

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

  2786.     downstream = c;
  2787.     upstream = u->peer.connection;

  2788.     if (downstream->write->timedout) {
  2789.         c->timedout = 1;
  2790.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");
  2791.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  2792.         return;
  2793.     }

  2794.     if (upstream->read->timedout || upstream->write->timedout) {
  2795.         ngx_connection_error(c, NGX_ETIMEDOUT, "upstream timed out");
  2796.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_GATEWAY_TIME_OUT);
  2797.         return;
  2798.     }

  2799.     if (from_upstream) {
  2800.         src = upstream;
  2801.         dst = downstream;
  2802.         b = &u->buffer;

  2803.     } else {
  2804.         src = downstream;
  2805.         dst = upstream;
  2806.         b = &u->from_client;

  2807.         if (r->header_in->last > r->header_in->pos) {
  2808.             b = r->header_in;
  2809.             b->end = b->last;
  2810.             do_write = 1;
  2811.         }

  2812.         if (b->start == NULL) {
  2813.             b->start = ngx_palloc(r->pool, u->conf->buffer_size);
  2814.             if (b->start == NULL) {
  2815.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2816.                 return;
  2817.             }

  2818.             b->pos = b->start;
  2819.             b->last = b->start;
  2820.             b->end = b->start + u->conf->buffer_size;
  2821.             b->temporary = 1;
  2822.             b->tag = u->output.tag;
  2823.         }
  2824.     }

  2825.     for ( ;; ) {

  2826.         if (do_write) {

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

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

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

  2830.                 if (n == NGX_ERROR) {
  2831.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2832.                     return;
  2833.                 }

  2834.                 if (n > 0) {
  2835.                     b->pos += n;

  2836.                     if (b->pos == b->last) {
  2837.                         b->pos = b->start;
  2838.                         b->last = b->start;
  2839.                     }
  2840.                 }
  2841.             }
  2842.         }

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

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

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

  2846.             if (n == NGX_AGAIN || n == 0) {
  2847.                 break;
  2848.             }

  2849.             if (n > 0) {
  2850.                 do_write = 1;
  2851.                 b->last += n;

  2852.                 if (from_upstream) {
  2853.                     u->state->bytes_received += n;
  2854.                 }

  2855.                 continue;
  2856.             }

  2857.             if (n == NGX_ERROR) {
  2858.                 src->read->eof = 1;
  2859.             }
  2860.         }

  2861.         break;
  2862.     }

  2863.     if ((upstream->read->eof && u->buffer.pos == u->buffer.last)
  2864.         || (downstream->read->eof && u->from_client.pos == u->from_client.last)
  2865.         || (downstream->read->eof && upstream->read->eof))
  2866.     {
  2867.         ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,
  2868.                        "http upstream upgraded done");
  2869.         ngx_http_upstream_finalize_request(r, u, 0);
  2870.         return;
  2871.     }

  2872.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  2873.     if (ngx_handle_write_event(upstream->write, u->conf->send_lowat)
  2874.         != NGX_OK)
  2875.     {
  2876.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2877.         return;
  2878.     }

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

  2881.     } else if (upstream->write->timer_set) {
  2882.         ngx_del_timer(upstream->write);
  2883.     }

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

  2886.     } else {
  2887.         flags = 0;
  2888.     }

  2889.     if (ngx_handle_read_event(upstream->read, flags) != NGX_OK) {
  2890.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2891.         return;
  2892.     }

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

  2895.     } else if (upstream->read->timer_set) {
  2896.         ngx_del_timer(upstream->read);
  2897.     }

  2898.     if (ngx_handle_write_event(downstream->write, clcf->send_lowat)
  2899.         != NGX_OK)
  2900.     {
  2901.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2902.         return;
  2903.     }

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

  2906.     } else {
  2907.         flags = 0;
  2908.     }

  2909.     if (ngx_handle_read_event(downstream->read, flags) != NGX_OK) {
  2910.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2911.         return;
  2912.     }

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

  2915.     } else if (downstream->write->timer_set) {
  2916.         ngx_del_timer(downstream->write);
  2917.     }
  2918. }


  2919. static void
  2920. ngx_http_upstream_process_non_buffered_downstream(ngx_http_request_t *r)
  2921. {
  2922.     ngx_event_t          *wev;
  2923.     ngx_connection_t     *c;
  2924.     ngx_http_upstream_t  *u;

  2925.     c = r->connection;
  2926.     u = r->upstream;
  2927.     wev = c->write;

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

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

  2931.     if (wev->timedout) {
  2932.         c->timedout = 1;
  2933.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");
  2934.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_REQUEST_TIME_OUT);
  2935.         return;
  2936.     }

  2937.     ngx_http_upstream_process_non_buffered_request(r, 1);
  2938. }


  2939. static void
  2940. ngx_http_upstream_process_non_buffered_upstream(ngx_http_request_t *r,
  2941.     ngx_http_upstream_t *u)
  2942. {
  2943.     ngx_connection_t  *c;

  2944.     c = u->peer.connection;

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

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

  2948.     if (c->read->timedout) {
  2949.         ngx_connection_error(c, NGX_ETIMEDOUT, "upstream timed out");
  2950.         ngx_http_upstream_finalize_request(r, u, NGX_HTTP_GATEWAY_TIME_OUT);
  2951.         return;
  2952.     }

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


  2955. static void
  2956. ngx_http_upstream_process_non_buffered_request(ngx_http_request_t *r,
  2957.     ngx_uint_t do_write)
  2958. {
  2959.     size_t                     size;
  2960.     ssize_t                    n;
  2961.     ngx_buf_t                 *b;
  2962.     ngx_int_t                  rc;
  2963.     ngx_uint_t                 flags;
  2964.     ngx_connection_t          *downstream, *upstream;
  2965.     ngx_http_upstream_t       *u;
  2966.     ngx_http_core_loc_conf_t  *clcf;

  2967.     u = r->upstream;
  2968.     downstream = r->connection;
  2969.     upstream = u->peer.connection;

  2970.     b = &u->buffer;

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

  2972.     for ( ;; ) {

  2973.         if (do_write) {

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

  2976.                 if (rc == NGX_ERROR) {
  2977.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  2978.                     return;
  2979.                 }

  2980.                 ngx_chain_update_chains(r->pool, &u->free_bufs, &u->busy_bufs,
  2981.                                         &u->out_bufs, u->output.tag);
  2982.             }

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

  2984.                 if (u->length == 0
  2985.                     || (upstream->read->eof && u->length == -1))
  2986.                 {
  2987.                     ngx_http_upstream_finalize_request(r, u, 0);
  2988.                     return;
  2989.                 }

  2990.                 if (upstream->read->eof) {
  2991.                     ngx_log_error(NGX_LOG_ERR, upstream->log, 0,
  2992.                                   "upstream prematurely closed connection");

  2993.                     ngx_http_upstream_finalize_request(r, u,
  2994.                                                        NGX_HTTP_BAD_GATEWAY);
  2995.                     return;
  2996.                 }

  2997.                 if (upstream->read->error || u->error) {
  2998.                     ngx_http_upstream_finalize_request(r, u,
  2999.                                                        NGX_HTTP_BAD_GATEWAY);
  3000.                     return;
  3001.                 }

  3002.                 b->pos = b->start;
  3003.                 b->last = b->start;
  3004.             }
  3005.         }

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

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

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

  3009.             if (n == NGX_AGAIN) {
  3010.                 break;
  3011.             }

  3012.             if (n > 0) {
  3013.                 u->state->bytes_received += n;
  3014.                 u->state->response_length += n;

  3015.                 if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {
  3016.                     ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3017.                     return;
  3018.                 }
  3019.             }

  3020.             do_write = 1;

  3021.             continue;
  3022.         }

  3023.         break;
  3024.     }

  3025.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);

  3026.     if (downstream->data == r) {
  3027.         if (ngx_handle_write_event(downstream->write, clcf->send_lowat)
  3028.             != NGX_OK)
  3029.         {
  3030.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3031.             return;
  3032.         }
  3033.     }

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

  3036.     } else if (downstream->write->timer_set) {
  3037.         ngx_del_timer(downstream->write);
  3038.     }

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

  3041.     } else {
  3042.         flags = 0;
  3043.     }

  3044.     if (ngx_handle_read_event(upstream->read, flags) != NGX_OK) {
  3045.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3046.         return;
  3047.     }

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

  3050.     } else if (upstream->read->timer_set) {
  3051.         ngx_del_timer(upstream->read);
  3052.     }
  3053. }


  3054. ngx_int_t
  3055. ngx_http_upstream_non_buffered_filter_init(void *data)
  3056. {
  3057.     return NGX_OK;
  3058. }


  3059. ngx_int_t
  3060. ngx_http_upstream_non_buffered_filter(void *data, ssize_t bytes)
  3061. {
  3062.     ngx_http_request_t  *r = data;

  3063.     ngx_buf_t            *b;
  3064.     ngx_chain_t          *cl, **ll;
  3065.     ngx_http_upstream_t  *u;

  3066.     u = r->upstream;

  3067.     if (u->length == 0) {
  3068.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3069.                       "upstream sent more data than specified in "
  3070.                       "\"Content-Length\" header");
  3071.         return NGX_OK;
  3072.     }

  3073.     for (cl = u->out_bufs, ll = &u->out_bufs; cl; cl = cl->next) {
  3074.         ll = &cl->next;
  3075.     }

  3076.     cl = ngx_chain_get_free_buf(r->pool, &u->free_bufs);
  3077.     if (cl == NULL) {
  3078.         return NGX_ERROR;
  3079.     }

  3080.     *ll = cl;

  3081.     cl->buf->flush = 1;
  3082.     cl->buf->memory = 1;

  3083.     b = &u->buffer;

  3084.     cl->buf->pos = b->last;
  3085.     b->last += bytes;
  3086.     cl->buf->last = b->last;
  3087.     cl->buf->tag = u->output.tag;

  3088.     if (u->length == -1) {
  3089.         return NGX_OK;
  3090.     }

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

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

  3095.         cl->buf->last = cl->buf->pos + u->length;
  3096.         u->length = 0;

  3097.         return NGX_OK;
  3098.     }

  3099.     u->length -= bytes;

  3100.     return NGX_OK;
  3101. }


  3102. #if (NGX_THREADS)

  3103. static ngx_int_t
  3104. ngx_http_upstream_thread_handler(ngx_thread_task_t *task, ngx_file_t *file)
  3105. {
  3106.     ngx_str_t                  name;
  3107.     ngx_event_pipe_t          *p;
  3108.     ngx_connection_t          *c;
  3109.     ngx_thread_pool_t         *tp;
  3110.     ngx_http_request_t        *r;
  3111.     ngx_http_core_loc_conf_t  *clcf;

  3112.     r = file->thread_ctx;
  3113.     p = r->upstream->pipe;

  3114.     if (r->aio) {
  3115.         /*
  3116.          * tolerate sendfile() calls if another operation is already
  3117.          * running; this can happen due to subrequests, multiple calls
  3118.          * of the next body filter from a filter, or in HTTP/2 due to
  3119.          * a write event on the main connection
  3120.          */

  3121.         c = r->connection;

  3122. #if (NGX_HTTP_V2)
  3123.         if (r->stream) {
  3124.             c = r->stream->connection->connection;
  3125.         }
  3126. #endif

  3127.         if (task == c->sendfile_task) {
  3128.             return NGX_OK;
  3129.         }
  3130.     }

  3131.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
  3132.     tp = clcf->thread_pool;

  3133.     if (tp == NULL) {
  3134.         if (ngx_http_complex_value(r, clcf->thread_pool_value, &name)
  3135.             != NGX_OK)
  3136.         {
  3137.             return NGX_ERROR;
  3138.         }

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

  3140.         if (tp == NULL) {
  3141.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3142.                           "thread pool \"%V\" not found", &name);
  3143.             return NGX_ERROR;
  3144.         }
  3145.     }

  3146.     task->event.data = r;
  3147.     task->event.handler = ngx_http_upstream_thread_event_handler;

  3148.     if (ngx_thread_task_post(tp, task) != NGX_OK) {
  3149.         return NGX_ERROR;
  3150.     }

  3151.     r->main->blocked++;
  3152.     r->aio = 1;
  3153.     p->aio = 1;

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

  3155.     return NGX_OK;
  3156. }


  3157. static void
  3158. ngx_http_upstream_thread_event_handler(ngx_event_t *ev)
  3159. {
  3160.     ngx_connection_t    *c;
  3161.     ngx_http_request_t  *r;

  3162.     r = ev->data;
  3163.     c = r->connection;

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

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

  3167.     if (ev->timedout) {
  3168.         ngx_log_error(NGX_LOG_ALERT, c->log, 0,
  3169.                       "thread operation took too long");
  3170.         ev->timedout = 0;
  3171.         return;
  3172.     }

  3173.     if (ev->timer_set) {
  3174.         ngx_del_timer(ev);
  3175.     }

  3176.     r->main->blocked--;
  3177.     r->aio = 0;

  3178. #if (NGX_HTTP_V2)

  3179.     if (r->stream) {
  3180.         /*
  3181.          * for HTTP/2, update write event to make sure processing will
  3182.          * reach the main connection to handle sendfile() in threads
  3183.          */

  3184.         c->write->ready = 1;
  3185.         c->write->active = 0;
  3186.     }

  3187. #endif

  3188.     if (r->done || r->main->terminated) {
  3189.         /*
  3190.          * trigger connection event handler if the subrequest was
  3191.          * already finalized (this can happen if the handler is used
  3192.          * for sendfile() in threads), or if the request was terminated
  3193.          */

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

  3195.     } else {
  3196.         r->write_event_handler(r);
  3197.         ngx_http_run_posted_requests(c);
  3198.     }
  3199. }

  3200. #endif


  3201. static ngx_int_t
  3202. ngx_http_upstream_output_filter(void *data, ngx_chain_t *chain)
  3203. {
  3204.     ngx_int_t            rc;
  3205.     ngx_event_pipe_t    *p;
  3206.     ngx_http_request_t  *r;

  3207.     r = data;
  3208.     p = r->upstream->pipe;

  3209.     rc = ngx_http_output_filter(r, chain);

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

  3211.     return rc;
  3212. }


  3213. static void
  3214. ngx_http_upstream_process_downstream(ngx_http_request_t *r)
  3215. {
  3216.     ngx_event_t          *wev;
  3217.     ngx_connection_t     *c;
  3218.     ngx_event_pipe_t     *p;
  3219.     ngx_http_upstream_t  *u;

  3220.     c = r->connection;
  3221.     u = r->upstream;
  3222.     p = u->pipe;
  3223.     wev = c->write;

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

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

  3227. #if (NGX_THREADS)
  3228.     p->aio = r->aio;
  3229. #endif

  3230.     if (wev->timedout) {

  3231.         p->downstream_error = 1;
  3232.         c->timedout = 1;
  3233.         ngx_connection_error(c, NGX_ETIMEDOUT, "client timed out");

  3234.     } else {

  3235.         if (wev->delayed) {

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

  3238.             if (ngx_handle_write_event(wev, p->send_lowat) != NGX_OK) {
  3239.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3240.             }

  3241.             return;
  3242.         }

  3243.         if (ngx_event_pipe(p, 1) == NGX_ABORT) {
  3244.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3245.             return;
  3246.         }
  3247.     }

  3248.     ngx_http_upstream_process_request(r, u);
  3249. }


  3250. static void
  3251. ngx_http_upstream_process_upstream(ngx_http_request_t *r,
  3252.     ngx_http_upstream_t *u)
  3253. {
  3254.     ngx_event_t       *rev;
  3255.     ngx_event_pipe_t  *p;
  3256.     ngx_connection_t  *c;

  3257.     c = u->peer.connection;
  3258.     p = u->pipe;
  3259.     rev = c->read;

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

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

  3263.     if (rev->timedout) {

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

  3266.     } else {

  3267.         if (rev->delayed) {

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

  3270.             if (ngx_handle_read_event(rev, 0) != NGX_OK) {
  3271.                 ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3272.             }

  3273.             return;
  3274.         }

  3275.         if (ngx_event_pipe(p, 0) == NGX_ABORT) {
  3276.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3277.             return;
  3278.         }
  3279.     }

  3280.     ngx_http_upstream_process_request(r, u);
  3281. }


  3282. static void
  3283. ngx_http_upstream_process_request(ngx_http_request_t *r,
  3284.     ngx_http_upstream_t *u)
  3285. {
  3286.     ngx_temp_file_t   *tf;
  3287.     ngx_event_pipe_t  *p;

  3288.     p = u->pipe;

  3289. #if (NGX_THREADS)

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

  3291.         /*
  3292.          * make sure to call ngx_event_pipe()
  3293.          * if there is an incomplete aio write
  3294.          */

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

  3300.     if (p->writing) {
  3301.         return;
  3302.     }

  3303. #endif

  3304.     if (u->peer.connection) {

  3305.         if (u->store) {

  3306.             if (p->upstream_eof || p->upstream_done) {

  3307.                 tf = p->temp_file;

  3308.                 if (u->headers_in.status_n == NGX_HTTP_OK
  3309.                     && (p->upstream_done || p->length == -1)
  3310.                     && (u->headers_in.content_length_n == -1
  3311.                         || u->headers_in.content_length_n == tf->offset))
  3312.                 {
  3313.                     ngx_http_upstream_store(r, u);
  3314.                 }
  3315.             }
  3316.         }

  3317. #if (NGX_HTTP_CACHE)

  3318.         if (u->cacheable) {

  3319.             if (p->upstream_done) {
  3320.                 ngx_http_file_cache_update(r, p->temp_file);

  3321.             } else if (p->upstream_eof) {

  3322.                 tf = p->temp_file;

  3323.                 if (p->length == -1
  3324.                     && (u->headers_in.content_length_n == -1
  3325.                         || u->headers_in.content_length_n
  3326.                            == tf->offset - (off_t) r->cache->body_start))
  3327.                 {
  3328.                     ngx_http_file_cache_update(r, tf);

  3329.                 } else {
  3330.                     ngx_http_file_cache_free(r->cache, tf);
  3331.                 }

  3332.             } else if (p->upstream_error) {
  3333.                 ngx_http_file_cache_free(r->cache, p->temp_file);
  3334.             }
  3335.         }

  3336. #endif

  3337.         if (p->upstream_done || p->upstream_eof || p->upstream_error) {
  3338.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3339.                            "http upstream exit: %p", p->out);

  3340.             if (p->upstream_done
  3341.                 || (p->upstream_eof && p->length == -1))
  3342.             {
  3343.                 ngx_http_upstream_finalize_request(r, u, 0);
  3344.                 return;
  3345.             }

  3346.             if (p->upstream_eof) {
  3347.                 ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3348.                               "upstream prematurely closed connection");
  3349.             }

  3350.             ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);
  3351.             return;
  3352.         }
  3353.     }

  3354.     if (p->downstream_error) {
  3355.         ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3356.                        "http upstream downstream error");

  3357.         if (!u->cacheable && !u->store && u->peer.connection) {
  3358.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);
  3359.         }
  3360.     }
  3361. }


  3362. static void
  3363. ngx_http_upstream_store(ngx_http_request_t *r, ngx_http_upstream_t *u)
  3364. {
  3365.     size_t                  root;
  3366.     time_t                  lm;
  3367.     ngx_str_t               path;
  3368.     ngx_temp_file_t        *tf;
  3369.     ngx_ext_rename_file_t   ext;

  3370.     tf = u->pipe->temp_file;

  3371.     if (tf->file.fd == NGX_INVALID_FILE) {

  3372.         /* create file for empty 200 response */

  3373.         tf = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t));
  3374.         if (tf == NULL) {
  3375.             return;
  3376.         }

  3377.         tf->file.fd = NGX_INVALID_FILE;
  3378.         tf->file.log = r->connection->log;
  3379.         tf->path = u->conf->temp_path;
  3380.         tf->pool = r->pool;
  3381.         tf->persistent = 1;

  3382.         if (ngx_create_temp_file(&tf->file, tf->path, tf->pool,
  3383.                                  tf->persistent, tf->clean, tf->access)
  3384.             != NGX_OK)
  3385.         {
  3386.             return;
  3387.         }

  3388.         u->pipe->temp_file = tf;
  3389.     }

  3390.     ext.access = u->conf->store_access;
  3391.     ext.path_access = u->conf->store_access;
  3392.     ext.time = -1;
  3393.     ext.create_path = 1;
  3394.     ext.delete_file = 1;
  3395.     ext.log = r->connection->log;

  3396.     if (u->headers_in.last_modified) {

  3397.         lm = ngx_parse_http_time(u->headers_in.last_modified->value.data,
  3398.                                  u->headers_in.last_modified->value.len);

  3399.         if (lm != NGX_ERROR) {
  3400.             ext.time = lm;
  3401.             ext.fd = tf->file.fd;
  3402.         }
  3403.     }

  3404.     if (u->conf->store_lengths == NULL) {

  3405.         if (ngx_http_map_uri_to_path(r, &path, &root, 0) == NULL) {
  3406.             return;
  3407.         }

  3408.     } else {
  3409.         if (ngx_http_script_run(r, &path, u->conf->store_lengths->elts, 0,
  3410.                                 u->conf->store_values->elts)
  3411.             == NULL)
  3412.         {
  3413.             return;
  3414.         }
  3415.     }

  3416.     path.len--;

  3417.     ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3418.                    "upstream stores \"%s\" to \"%s\"",
  3419.                    tf->file.name.data, path.data);

  3420.     if (path.len == 0) {
  3421.         return;
  3422.     }

  3423.     (void) ngx_ext_rename_file(&tf->file.name, &path, &ext);

  3424.     u->store = 0;
  3425. }


  3426. static void
  3427. ngx_http_upstream_dummy_handler(ngx_http_request_t *r, ngx_http_upstream_t *u)
  3428. {
  3429.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3430.                    "http upstream dummy handler");
  3431. }


  3432. static void
  3433. ngx_http_upstream_next(ngx_http_request_t *r, ngx_http_upstream_t *u,
  3434.     ngx_uint_t ft_type)
  3435. {
  3436.     ngx_msec_t  timeout;
  3437.     ngx_uint_t  status, state;

  3438.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3439.                    "http next upstream, %xi", ft_type);

  3440.     if (u->peer.sockaddr) {

  3441.         if (u->peer.connection) {
  3442.             u->state->bytes_sent = u->peer.connection->sent;
  3443.         }

  3444.         if (ft_type == NGX_HTTP_UPSTREAM_FT_HTTP_403
  3445.             || ft_type == NGX_HTTP_UPSTREAM_FT_HTTP_404)
  3446.         {
  3447.             state = NGX_PEER_NEXT;

  3448.         } else {
  3449.             state = NGX_PEER_FAILED;
  3450.         }

  3451.         u->peer.free(&u->peer, u->peer.data, state);
  3452.         u->peer.sockaddr = NULL;

  3453. #if (NGX_HTTP_UPSTREAM_SID)
  3454.         u->peer.sid = NULL;
  3455. #endif
  3456.     }

  3457.     if (ft_type == NGX_HTTP_UPSTREAM_FT_TIMEOUT) {
  3458.         ngx_log_error(NGX_LOG_ERR, r->connection->log, NGX_ETIMEDOUT,
  3459.                       "upstream timed out");
  3460.     }

  3461.     if (u->peer.cached && ft_type == NGX_HTTP_UPSTREAM_FT_ERROR) {
  3462.         /* TODO: inform balancer instead */
  3463.         u->peer.tries++;
  3464.     }

  3465.     switch (ft_type) {

  3466.     case NGX_HTTP_UPSTREAM_FT_TIMEOUT:
  3467.     case NGX_HTTP_UPSTREAM_FT_HTTP_504:
  3468.         status = NGX_HTTP_GATEWAY_TIME_OUT;
  3469.         break;

  3470.     case NGX_HTTP_UPSTREAM_FT_HTTP_500:
  3471.         status = NGX_HTTP_INTERNAL_SERVER_ERROR;
  3472.         break;

  3473.     case NGX_HTTP_UPSTREAM_FT_HTTP_503:
  3474.         status = NGX_HTTP_SERVICE_UNAVAILABLE;
  3475.         break;

  3476.     case NGX_HTTP_UPSTREAM_FT_HTTP_403:
  3477.         status = NGX_HTTP_FORBIDDEN;
  3478.         break;

  3479.     case NGX_HTTP_UPSTREAM_FT_HTTP_404:
  3480.         status = NGX_HTTP_NOT_FOUND;
  3481.         break;

  3482.     case NGX_HTTP_UPSTREAM_FT_HTTP_429:
  3483.         status = NGX_HTTP_TOO_MANY_REQUESTS;
  3484.         break;

  3485.     /*
  3486.      * NGX_HTTP_UPSTREAM_FT_BUSY_LOCK and NGX_HTTP_UPSTREAM_FT_MAX_WAITING
  3487.      * never reach here
  3488.      */

  3489.     default:
  3490.         status = NGX_HTTP_BAD_GATEWAY;
  3491.     }

  3492.     if (r->connection->error) {
  3493.         ngx_http_upstream_finalize_request(r, u,
  3494.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);
  3495.         return;
  3496.     }

  3497.     u->state->status = status;

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

  3499.     if (u->request_sent
  3500.         && (r->method & (NGX_HTTP_POST|NGX_HTTP_LOCK|NGX_HTTP_PATCH)))
  3501.     {
  3502.         ft_type |= NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT;
  3503.     }

  3504.     if (u->peer.tries == 0
  3505.         || ((u->conf->next_upstream & ft_type) != ft_type)
  3506.         || (u->request_sent && r->request_body_no_buffering)
  3507.         || (timeout && ngx_current_msec - u->peer.start_time >= timeout))
  3508.     {
  3509. #if (NGX_HTTP_CACHE)

  3510.         if (u->cache_status == NGX_HTTP_CACHE_EXPIRED
  3511.             && ((u->conf->cache_use_stale & ft_type) || r->cache->stale_error))
  3512.         {
  3513.             ngx_int_t  rc;

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

  3515.             if (rc != NGX_OK) {
  3516.                 ngx_http_upstream_finalize_request(r, u, rc);
  3517.                 return;
  3518.             }

  3519.             u->cache_status = NGX_HTTP_CACHE_STALE;
  3520.             rc = ngx_http_upstream_cache_send(r, u);

  3521.             if (rc == NGX_DONE) {
  3522.                 return;
  3523.             }

  3524.             if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {
  3525.                 rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
  3526.             }

  3527.             ngx_http_upstream_finalize_request(r, u, rc);
  3528.             return;
  3529.         }
  3530. #endif

  3531.         ngx_http_upstream_finalize_request(r, u, status);
  3532.         return;
  3533.     }

  3534.     if (u->peer.connection) {
  3535.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3536.                        "close http upstream connection: %d",
  3537.                        u->peer.connection->fd);
  3538. #if (NGX_HTTP_SSL)

  3539.         if (u->peer.connection->ssl) {
  3540.             u->peer.connection->ssl->no_wait_shutdown = 1;
  3541.             u->peer.connection->ssl->no_send_shutdown = 1;

  3542.             (void) ngx_ssl_shutdown(u->peer.connection);
  3543.         }
  3544. #endif

  3545.         if (u->peer.connection->pool) {
  3546.             ngx_destroy_pool(u->peer.connection->pool);
  3547.         }

  3548.         ngx_close_connection(u->peer.connection);
  3549.         u->peer.connection = NULL;
  3550.     }

  3551.     ngx_http_upstream_connect(r, u);
  3552. }


  3553. static void
  3554. ngx_http_upstream_cleanup(void *data)
  3555. {
  3556.     ngx_http_request_t *r = data;

  3557.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3558.                    "cleanup http upstream request: \"%V\"", &r->uri);

  3559.     ngx_http_upstream_finalize_request(r, r->upstream, NGX_DONE);
  3560. }


  3561. static void
  3562. ngx_http_upstream_finalize_request(ngx_http_request_t *r,
  3563.     ngx_http_upstream_t *u, ngx_int_t rc)
  3564. {
  3565.     ngx_uint_t  flush;

  3566.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3567.                    "finalize http upstream request: %i", rc);

  3568.     if (u->cleanup == NULL) {
  3569.         /* the request was already finalized */
  3570.         ngx_http_finalize_request(r, NGX_DONE);
  3571.         return;
  3572.     }

  3573.     *u->cleanup = NULL;
  3574.     u->cleanup = NULL;

  3575.     if (u->resolved && u->resolved->ctx) {
  3576.         ngx_resolve_name_done(u->resolved->ctx);
  3577.         u->resolved->ctx = NULL;
  3578.     }

  3579.     if (u->state && u->state->response_time == (ngx_msec_t) -1) {
  3580.         u->state->response_time = ngx_current_msec - u->start_time;

  3581.         if (u->pipe && u->pipe->read_length) {
  3582.             u->state->bytes_received += u->pipe->read_length
  3583.                                         - u->pipe->preread_size;
  3584.             u->state->response_length = u->pipe->read_length;
  3585.         }

  3586.         if (u->peer.connection) {
  3587.             u->state->bytes_sent = u->peer.connection->sent;
  3588.         }
  3589.     }

  3590.     u->finalize_request(r, rc);

  3591.     if (u->peer.free && u->peer.sockaddr) {
  3592.         u->peer.free(&u->peer, u->peer.data, 0);
  3593.         u->peer.sockaddr = NULL;

  3594. #if (NGX_HTTP_UPSTREAM_SID)
  3595.         u->peer.sid = NULL;
  3596. #endif
  3597.     }

  3598.     if (u->peer.connection) {

  3599. #if (NGX_HTTP_SSL)

  3600.         /* TODO: do not shutdown persistent connection */

  3601.         if (u->peer.connection->ssl) {

  3602.             /*
  3603.              * We send the "close notify" shutdown alert to the upstream only
  3604.              * and do not wait its "close notify" shutdown alert.
  3605.              * It is acceptable according to the TLS standard.
  3606.              */

  3607.             u->peer.connection->ssl->no_wait_shutdown = 1;

  3608.             (void) ngx_ssl_shutdown(u->peer.connection);
  3609.         }
  3610. #endif

  3611.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3612.                        "close http upstream connection: %d",
  3613.                        u->peer.connection->fd);

  3614.         if (u->peer.connection->pool) {
  3615.             ngx_destroy_pool(u->peer.connection->pool);
  3616.         }

  3617.         ngx_close_connection(u->peer.connection);
  3618.     }

  3619.     u->peer.connection = NULL;

  3620.     if (u->pipe) {
  3621.         u->pipe->upstream = NULL;
  3622.     }

  3623.     if (u->pipe && u->pipe->temp_file) {
  3624.         ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  3625.                        "http upstream temp fd: %d",
  3626.                        u->pipe->temp_file->file.fd);
  3627.     }

  3628.     if (u->store && u->pipe && u->pipe->temp_file
  3629.         && u->pipe->temp_file->file.fd != NGX_INVALID_FILE)
  3630.     {
  3631.         if (ngx_delete_file(u->pipe->temp_file->file.name.data)
  3632.             == NGX_FILE_ERROR)
  3633.         {
  3634.             ngx_log_error(NGX_LOG_CRIT, r->connection->log, ngx_errno,
  3635.                           ngx_delete_file_n " \"%s\" failed",
  3636.                           u->pipe->temp_file->file.name.data);
  3637.         }
  3638.     }

  3639. #if (NGX_HTTP_CACHE)

  3640.     if (r->cache) {

  3641.         if (u->cacheable) {

  3642.             if (rc == NGX_HTTP_BAD_GATEWAY || rc == NGX_HTTP_GATEWAY_TIME_OUT) {
  3643.                 time_t  valid;

  3644.                 valid = ngx_http_file_cache_valid(u->conf->cache_valid, rc);

  3645.                 if (valid) {
  3646.                     r->cache->valid_sec = ngx_time() + valid;
  3647.                     r->cache->error = rc;
  3648.                 }
  3649.             }
  3650.         }

  3651.         ngx_http_file_cache_free(r->cache, u->pipe->temp_file);
  3652.     }

  3653. #endif

  3654.     r->read_event_handler = ngx_http_block_reading;

  3655.     if (rc == NGX_DECLINED) {
  3656.         return;
  3657.     }

  3658.     r->connection->log->action = "sending to client";

  3659.     if (!u->header_sent
  3660.         || rc == NGX_HTTP_REQUEST_TIME_OUT
  3661.         || rc == NGX_HTTP_CLIENT_CLOSED_REQUEST)
  3662.     {
  3663.         ngx_http_finalize_request(r, rc);
  3664.         return;
  3665.     }

  3666.     flush = 0;

  3667.     if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
  3668.         rc = NGX_ERROR;
  3669.         flush = 1;
  3670.     }

  3671.     if (r->header_only
  3672.         || (u->pipe && u->pipe->downstream_error))
  3673.     {
  3674.         ngx_http_finalize_request(r, rc);
  3675.         return;
  3676.     }

  3677.     if (rc == 0) {

  3678.         if (ngx_http_upstream_process_trailers(r, u) != NGX_OK) {
  3679.             ngx_http_finalize_request(r, NGX_ERROR);
  3680.             return;
  3681.         }

  3682.         rc = ngx_http_send_special(r, NGX_HTTP_LAST);

  3683.     } else if (flush) {
  3684.         r->keepalive = 0;
  3685.         rc = ngx_http_send_special(r, NGX_HTTP_FLUSH);
  3686.     }

  3687.     ngx_http_finalize_request(r, rc);
  3688. }


  3689. static ngx_int_t
  3690. ngx_http_upstream_process_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  3691.     ngx_uint_t offset)
  3692. {
  3693.     ngx_table_elt_t  **ph;

  3694.     ph = (ngx_table_elt_t **) ((char *) &r->upstream->headers_in + offset);

  3695.     if (*ph) {
  3696.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3697.                       "upstream sent duplicate header line: \"%V: %V\", "
  3698.                       "previous value: \"%V: %V\", ignored",
  3699.                       &h->key, &h->value,
  3700.                       &(*ph)->key, &(*ph)->value);
  3701.         h->hash = 0;
  3702.         return NGX_OK;
  3703.     }

  3704.     *ph = h;
  3705.     h->next = NULL;

  3706.     return NGX_OK;
  3707. }


  3708. static ngx_int_t
  3709. ngx_http_upstream_process_multi_header_lines(ngx_http_request_t *r,
  3710.     ngx_table_elt_t *h, ngx_uint_t offset)
  3711. {
  3712.     ngx_table_elt_t  **ph;

  3713.     ph = (ngx_table_elt_t **) ((char *) &r->upstream->headers_in + offset);

  3714.     while (*ph) { ph = &(*ph)->next; }

  3715.     *ph = h;
  3716.     h->next = NULL;

  3717.     return NGX_OK;
  3718. }


  3719. static ngx_int_t
  3720. ngx_http_upstream_ignore_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  3721.     ngx_uint_t offset)
  3722. {
  3723.     return NGX_OK;
  3724. }


  3725. static ngx_int_t
  3726. ngx_http_upstream_process_content_length(ngx_http_request_t *r,
  3727.     ngx_table_elt_t *h, ngx_uint_t offset)
  3728. {
  3729.     ngx_http_upstream_t  *u;

  3730.     u = r->upstream;

  3731.     if (u->headers_in.content_length) {
  3732.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3733.                       "upstream sent duplicate header line: \"%V: %V\", "
  3734.                       "previous value: \"%V: %V\"",
  3735.                       &h->key, &h->value,
  3736.                       &u->headers_in.content_length->key,
  3737.                       &u->headers_in.content_length->value);
  3738.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3739.     }

  3740.     if (u->headers_in.transfer_encoding) {
  3741.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3742.                       "upstream sent \"Content-Length\" and "
  3743.                       "\"Transfer-Encoding\" headers at the same time");
  3744.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3745.     }

  3746.     h->next = NULL;
  3747.     u->headers_in.content_length = h;
  3748.     u->headers_in.content_length_n = ngx_atoof(h->value.data, h->value.len);

  3749.     if (u->headers_in.content_length_n == NGX_ERROR) {
  3750.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  3751.                       "upstream sent invalid \"Content-Length\" header: "
  3752.                       "\"%V: %V\"", &h->key, &h->value);
  3753.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  3754.     }

  3755.     return NGX_OK;
  3756. }


  3757. static ngx_int_t
  3758. ngx_http_upstream_process_last_modified(ngx_http_request_t *r,
  3759.     ngx_table_elt_t *h, ngx_uint_t offset)
  3760. {
  3761.     ngx_http_upstream_t  *u;

  3762.     u = r->upstream;

  3763.     if (u->headers_in.last_modified) {
  3764.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3765.                       "upstream sent duplicate header line: \"%V: %V\", "
  3766.                       "previous value: \"%V: %V\", ignored",
  3767.                       &h->key, &h->value,
  3768.                       &u->headers_in.last_modified->key,
  3769.                       &u->headers_in.last_modified->value);
  3770.         h->hash = 0;
  3771.         return NGX_OK;
  3772.     }

  3773.     h->next = NULL;
  3774.     u->headers_in.last_modified = h;
  3775.     u->headers_in.last_modified_time = ngx_parse_http_time(h->value.data,
  3776.                                                            h->value.len);

  3777.     return NGX_OK;
  3778. }


  3779. static ngx_int_t
  3780. ngx_http_upstream_process_set_cookie(ngx_http_request_t *r, ngx_table_elt_t *h,
  3781.     ngx_uint_t offset)
  3782. {
  3783.     ngx_table_elt_t      **ph;
  3784.     ngx_http_upstream_t   *u;

  3785.     u = r->upstream;
  3786.     ph = &u->headers_in.set_cookie;

  3787.     while (*ph) { ph = &(*ph)->next; }

  3788.     *ph = h;
  3789.     h->next = NULL;

  3790. #if (NGX_HTTP_CACHE)
  3791.     if (!(u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_SET_COOKIE)) {
  3792.         u->cacheable = 0;
  3793.     }
  3794. #endif

  3795.     return NGX_OK;
  3796. }


  3797. static ngx_int_t
  3798. ngx_http_upstream_process_cache_control(ngx_http_request_t *r,
  3799.     ngx_table_elt_t *h, ngx_uint_t offset)
  3800. {
  3801.     ngx_table_elt_t      **ph;
  3802.     ngx_http_upstream_t   *u;

  3803.     u = r->upstream;
  3804.     ph = &u->headers_in.cache_control;

  3805.     while (*ph) { ph = &(*ph)->next; }

  3806.     *ph = h;
  3807.     h->next = NULL;

  3808. #if (NGX_HTTP_CACHE)
  3809.     {
  3810.     u_char     *p, *start, *last;
  3811.     ngx_int_t   n;

  3812.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_CACHE_CONTROL) {
  3813.         return NGX_OK;
  3814.     }

  3815.     if (r->cache == NULL) {
  3816.         return NGX_OK;
  3817.     }

  3818.     start = h->value.data;
  3819.     last = start + h->value.len;

  3820.     if (r->cache->valid_sec != 0 && u->headers_in.x_accel_expires != NULL) {
  3821.         goto extensions;
  3822.     }

  3823.     if (ngx_strlcasestrn(start, last, (u_char *) "no-cache", 8 - 1) != NULL
  3824.         || ngx_strlcasestrn(start, last, (u_char *) "no-store", 8 - 1) != NULL
  3825.         || ngx_strlcasestrn(start, last, (u_char *) "private", 7 - 1) != NULL)
  3826.     {
  3827.         u->headers_in.no_cache = 1;
  3828.         return NGX_OK;
  3829.     }

  3830.     p = ngx_strlcasestrn(start, last, (u_char *) "s-maxage=", 9 - 1);
  3831.     offset = 9;

  3832.     if (p == NULL) {
  3833.         p = ngx_strlcasestrn(start, last, (u_char *) "max-age=", 8 - 1);
  3834.         offset = 8;
  3835.     }

  3836.     if (p) {
  3837.         n = ngx_http_upstream_process_delta_seconds(p + offset, last);

  3838.         if (n == NGX_ERROR) {
  3839.             u->cacheable = 0;
  3840.             return NGX_OK;
  3841.         }

  3842.         if (n == 0) {
  3843.             u->headers_in.no_cache = 1;
  3844.             return NGX_OK;
  3845.         }

  3846.         r->cache->valid_sec = ngx_min((ngx_uint_t) ngx_time() + n,
  3847.                                       NGX_MAX_INT_T_VALUE);
  3848.         u->headers_in.expired = 0;
  3849.     }

  3850. extensions:

  3851.     p = ngx_strlcasestrn(start, last, (u_char *) "stale-while-revalidate=",
  3852.                          23 - 1);

  3853.     if (p) {
  3854.         n = ngx_http_upstream_process_delta_seconds(p + 23, last);

  3855.         if (n == NGX_ERROR) {
  3856.             u->cacheable = 0;
  3857.             return NGX_OK;
  3858.         }

  3859.         r->cache->updating_sec = n;
  3860.         r->cache->error_sec = n;
  3861.     }

  3862.     p = ngx_strlcasestrn(start, last, (u_char *) "stale-if-error=", 15 - 1);

  3863.     if (p) {
  3864.         n = ngx_http_upstream_process_delta_seconds(p + 15, last);

  3865.         if (n == NGX_ERROR) {
  3866.             u->cacheable = 0;
  3867.             return NGX_OK;
  3868.         }

  3869.         r->cache->error_sec = n;
  3870.     }
  3871.     }
  3872. #endif

  3873.     return NGX_OK;
  3874. }


  3875. #if (NGX_HTTP_CACHE)

  3876. static ngx_int_t
  3877. ngx_http_upstream_process_delta_seconds(u_char *p, u_char *last)
  3878. {
  3879.     ngx_int_t  n, cutoff, cutlim;

  3880.     cutoff = NGX_MAX_INT_T_VALUE / 10;
  3881.     cutlim = NGX_MAX_INT_T_VALUE % 10;

  3882.     n = 0;

  3883.     for ( /* void */ ; p < last; p++) {
  3884.         if (*p == ',' || *p == ';' || *p == ' ') {
  3885.             break;
  3886.         }

  3887.         if (*p < '0' || *p > '9') {
  3888.             return NGX_ERROR;
  3889.         }

  3890.         if (n >= cutoff && (n > cutoff || *p - '0' > cutlim)) {
  3891.             n = NGX_MAX_INT_T_VALUE;
  3892.             break;
  3893.         }

  3894.         n = n * 10 + (*p - '0');
  3895.     }

  3896.     return n;
  3897. }

  3898. #endif


  3899. static ngx_int_t
  3900. ngx_http_upstream_process_expires(ngx_http_request_t *r, ngx_table_elt_t *h,
  3901.     ngx_uint_t offset)
  3902. {
  3903.     ngx_http_upstream_t  *u;

  3904.     u = r->upstream;

  3905.     if (u->headers_in.expires) {
  3906.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3907.                       "upstream sent duplicate header line: \"%V: %V\", "
  3908.                       "previous value: \"%V: %V\", ignored",
  3909.                       &h->key, &h->value,
  3910.                       &u->headers_in.expires->key,
  3911.                       &u->headers_in.expires->value);
  3912.         h->hash = 0;
  3913.         return NGX_OK;
  3914.     }

  3915.     u->headers_in.expires = h;
  3916.     h->next = NULL;

  3917. #if (NGX_HTTP_CACHE)
  3918.     {
  3919.     time_t  expires;

  3920.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_EXPIRES) {
  3921.         return NGX_OK;
  3922.     }

  3923.     if (r->cache == NULL) {
  3924.         return NGX_OK;
  3925.     }

  3926.     if (r->cache->valid_sec != 0) {
  3927.         return NGX_OK;
  3928.     }

  3929.     expires = ngx_parse_http_time(h->value.data, h->value.len);

  3930.     if (expires == NGX_ERROR || expires < ngx_time()) {
  3931.         u->headers_in.expired = 1;
  3932.         return NGX_OK;
  3933.     }

  3934.     r->cache->valid_sec = expires;
  3935.     }
  3936. #endif

  3937.     return NGX_OK;
  3938. }


  3939. static ngx_int_t
  3940. ngx_http_upstream_process_accel_expires(ngx_http_request_t *r,
  3941.     ngx_table_elt_t *h, ngx_uint_t offset)
  3942. {
  3943.     ngx_http_upstream_t  *u;

  3944.     u = r->upstream;

  3945.     if (u->headers_in.x_accel_expires) {
  3946.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  3947.                       "upstream sent duplicate header line: \"%V: %V\", "
  3948.                       "previous value: \"%V: %V\", ignored",
  3949.                       &h->key, &h->value,
  3950.                       &u->headers_in.x_accel_expires->key,
  3951.                       &u->headers_in.x_accel_expires->value);
  3952.         h->hash = 0;
  3953.         return NGX_OK;
  3954.     }

  3955.     u->headers_in.x_accel_expires = h;
  3956.     h->next = NULL;

  3957. #if (NGX_HTTP_CACHE)
  3958.     {
  3959.     u_char     *p;
  3960.     size_t      len;
  3961.     ngx_int_t   n;

  3962.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_EXPIRES) {
  3963.         return NGX_OK;
  3964.     }

  3965.     if (r->cache == NULL) {
  3966.         return NGX_OK;
  3967.     }

  3968.     len = h->value.len;
  3969.     p = h->value.data;

  3970.     if (p[0] != '@') {
  3971.         n = ngx_atoi(p, len);

  3972.         switch (n) {
  3973.         case 0:
  3974.             u->cacheable = 0;
  3975.             /* fall through */

  3976.         case NGX_ERROR:
  3977.             return NGX_OK;

  3978.         default:
  3979.             r->cache->valid_sec = ngx_time() + n;
  3980.             u->headers_in.no_cache = 0;
  3981.             u->headers_in.expired = 0;
  3982.             return NGX_OK;
  3983.         }
  3984.     }

  3985.     p++;
  3986.     len--;

  3987.     n = ngx_atoi(p, len);

  3988.     if (n != NGX_ERROR) {
  3989.         r->cache->valid_sec = n;
  3990.         u->headers_in.no_cache = 0;
  3991.         u->headers_in.expired = 0;
  3992.     }
  3993.     }
  3994. #endif

  3995.     return NGX_OK;
  3996. }


  3997. static ngx_int_t
  3998. ngx_http_upstream_process_limit_rate(ngx_http_request_t *r, ngx_table_elt_t *h,
  3999.     ngx_uint_t offset)
  4000. {
  4001.     ngx_int_t             n;
  4002.     ngx_http_upstream_t  *u;

  4003.     u = r->upstream;

  4004.     if (u->headers_in.x_accel_limit_rate) {
  4005.         ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
  4006.                       "upstream sent duplicate header line: \"%V: %V\", "
  4007.                       "previous value: \"%V: %V\", ignored",
  4008.                       &h->key, &h->value,
  4009.                       &u->headers_in.x_accel_limit_rate->key,
  4010.                       &u->headers_in.x_accel_limit_rate->value);
  4011.         h->hash = 0;
  4012.         return NGX_OK;
  4013.     }

  4014.     u->headers_in.x_accel_limit_rate = h;
  4015.     h->next = NULL;

  4016.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_LIMIT_RATE) {
  4017.         return NGX_OK;
  4018.     }

  4019.     n = ngx_atoi(h->value.data, h->value.len);

  4020.     if (n != NGX_ERROR) {
  4021.         r->limit_rate = (size_t) n;
  4022.         r->limit_rate_set = 1;
  4023.     }

  4024.     return NGX_OK;
  4025. }


  4026. static ngx_int_t
  4027. ngx_http_upstream_process_buffering(ngx_http_request_t *r, ngx_table_elt_t *h,
  4028.     ngx_uint_t offset)
  4029. {
  4030.     u_char                c0, c1, c2;
  4031.     ngx_http_upstream_t  *u;

  4032.     u = r->upstream;

  4033.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_BUFFERING) {
  4034.         return NGX_OK;
  4035.     }

  4036.     if (u->conf->change_buffering) {

  4037.         if (h->value.len == 2) {
  4038.             c0 = ngx_tolower(h->value.data[0]);
  4039.             c1 = ngx_tolower(h->value.data[1]);

  4040.             if (c0 == 'n' && c1 == 'o') {
  4041.                 u->buffering = 0;
  4042.             }

  4043.         } else if (h->value.len == 3) {
  4044.             c0 = ngx_tolower(h->value.data[0]);
  4045.             c1 = ngx_tolower(h->value.data[1]);
  4046.             c2 = ngx_tolower(h->value.data[2]);

  4047.             if (c0 == 'y' && c1 == 'e' && c2 == 's') {
  4048.                 u->buffering = 1;
  4049.             }
  4050.         }
  4051.     }

  4052.     return NGX_OK;
  4053. }


  4054. static ngx_int_t
  4055. ngx_http_upstream_process_charset(ngx_http_request_t *r, ngx_table_elt_t *h,
  4056.     ngx_uint_t offset)
  4057. {
  4058.     ngx_http_upstream_t  *u;

  4059.     u = r->upstream;

  4060.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_XA_CHARSET) {
  4061.         return NGX_OK;
  4062.     }

  4063.     r->headers_out.override_charset = &h->value;

  4064.     return NGX_OK;
  4065. }


  4066. static ngx_int_t
  4067. ngx_http_upstream_process_connection(ngx_http_request_t *r, ngx_table_elt_t *h,
  4068.     ngx_uint_t offset)
  4069. {
  4070.     ngx_table_elt_t      **ph;
  4071.     ngx_http_upstream_t   *u;

  4072.     u = r->upstream;
  4073.     ph = &u->headers_in.connection;

  4074.     while (*ph) { ph = &(*ph)->next; }

  4075.     *ph = h;
  4076.     h->next = NULL;

  4077.     if (ngx_strlcasestrn(h->value.data, h->value.data + h->value.len,
  4078.                          (u_char *) "close", 5 - 1)
  4079.         != NULL)
  4080.     {
  4081.         u->headers_in.connection_close = 1;
  4082.     }

  4083.     return NGX_OK;
  4084. }


  4085. static ngx_int_t
  4086. ngx_http_upstream_process_transfer_encoding(ngx_http_request_t *r,
  4087.     ngx_table_elt_t *h, ngx_uint_t offset)
  4088. {
  4089.     ngx_http_upstream_t  *u;

  4090.     u = r->upstream;

  4091.     if (u->headers_in.transfer_encoding) {
  4092.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4093.                       "upstream sent duplicate header line: \"%V: %V\", "
  4094.                       "previous value: \"%V: %V\"",
  4095.                       &h->key, &h->value,
  4096.                       &u->headers_in.transfer_encoding->key,
  4097.                       &u->headers_in.transfer_encoding->value);
  4098.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4099.     }

  4100.     if (u->headers_in.content_length) {
  4101.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4102.                       "upstream sent \"Content-Length\" and "
  4103.                       "\"Transfer-Encoding\" headers at the same time");
  4104.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4105.     }

  4106.     u->headers_in.transfer_encoding = h;
  4107.     h->next = NULL;

  4108.     if (h->value.len == 7
  4109.         && ngx_strncasecmp(h->value.data, (u_char *) "chunked", 7) == 0)
  4110.     {
  4111.         u->headers_in.chunked = 1;

  4112.     } else {
  4113.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  4114.                       "upstream sent unknown \"Transfer-Encoding\": \"%V\"",
  4115.                       &h->value);
  4116.         return NGX_HTTP_UPSTREAM_INVALID_HEADER;
  4117.     }

  4118.     return NGX_OK;
  4119. }


  4120. static ngx_int_t
  4121. ngx_http_upstream_process_vary(ngx_http_request_t *r,
  4122.     ngx_table_elt_t *h, ngx_uint_t offset)
  4123. {
  4124.     ngx_table_elt_t      **ph;
  4125.     ngx_http_upstream_t   *u;

  4126.     u = r->upstream;
  4127.     ph = &u->headers_in.vary;

  4128.     while (*ph) { ph = &(*ph)->next; }

  4129.     *ph = h;
  4130.     h->next = NULL;

  4131. #if (NGX_HTTP_CACHE)
  4132.     {
  4133.     u_char     *p;
  4134.     size_t      len;
  4135.     ngx_str_t   vary;

  4136.     if (u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_VARY) {
  4137.         return NGX_OK;
  4138.     }

  4139.     if (r->cache == NULL || !u->cacheable) {
  4140.         return NGX_OK;
  4141.     }

  4142.     if (h->value.len == 1 && h->value.data[0] == '*') {
  4143.         u->cacheable = 0;
  4144.         return NGX_OK;
  4145.     }

  4146.     if (u->headers_in.vary->next) {

  4147.         len = 0;

  4148.         for (h = u->headers_in.vary; h; h = h->next) {
  4149.             len += h->value.len + 2;
  4150.         }

  4151.         len -= 2;

  4152.         p = ngx_pnalloc(r->pool, len);
  4153.         if (p == NULL) {
  4154.             return NGX_ERROR;
  4155.         }

  4156.         vary.len = len;
  4157.         vary.data = p;

  4158.         for (h = u->headers_in.vary; h; h = h->next) {
  4159.             p = ngx_copy(p, h->value.data, h->value.len);

  4160.             if (h->next == NULL) {
  4161.                 break;
  4162.             }

  4163.             *p++ = ','; *p++ = ' ';
  4164.         }

  4165.     } else {
  4166.         vary = h->value;
  4167.     }

  4168.     if (vary.len > NGX_HTTP_CACHE_VARY_LEN) {
  4169.         u->cacheable = 0;
  4170.     }

  4171.     r->cache->vary = vary;
  4172.     }
  4173. #endif

  4174.     return NGX_OK;
  4175. }


  4176. static ngx_int_t
  4177. ngx_http_upstream_copy_header_line(ngx_http_request_t *r, ngx_table_elt_t *h,
  4178.     ngx_uint_t offset)
  4179. {
  4180.     ngx_table_elt_t  *ho, **ph;

  4181.     ho = ngx_list_push(&r->headers_out.headers);
  4182.     if (ho == NULL) {
  4183.         return NGX_ERROR;
  4184.     }

  4185.     *ho = *h;

  4186.     if (offset) {
  4187.         ph = (ngx_table_elt_t **) ((char *) &r->headers_out + offset);
  4188.         *ph = ho;
  4189.         ho->next = NULL;
  4190.     }

  4191.     return NGX_OK;
  4192. }


  4193. static ngx_int_t
  4194. ngx_http_upstream_copy_multi_header_lines(ngx_http_request_t *r,
  4195.     ngx_table_elt_t *h, ngx_uint_t offset)
  4196. {
  4197.     ngx_table_elt_t  *ho, **ph;

  4198.     ho = ngx_list_push(&r->headers_out.headers);
  4199.     if (ho == NULL) {
  4200.         return NGX_ERROR;
  4201.     }

  4202.     *ho = *h;

  4203.     ph = (ngx_table_elt_t **) ((char *) &r->headers_out + offset);

  4204.     while (*ph) { ph = &(*ph)->next; }

  4205.     *ph = ho;
  4206.     ho->next = NULL;

  4207.     return NGX_OK;
  4208. }


  4209. static ngx_int_t
  4210. ngx_http_upstream_copy_content_type(ngx_http_request_t *r, ngx_table_elt_t *h,
  4211.     ngx_uint_t offset)
  4212. {
  4213.     u_char  *p, *last;

  4214.     r->headers_out.content_type_len = h->value.len;
  4215.     r->headers_out.content_type = h->value;
  4216.     r->headers_out.content_type_lowcase = NULL;

  4217.     for (p = h->value.data; *p; p++) {

  4218.         if (*p != ';') {
  4219.             continue;
  4220.         }

  4221.         last = p;

  4222.         while (*++p == ' ') { /* void */ }

  4223.         if (*p == '\0') {
  4224.             return NGX_OK;
  4225.         }

  4226.         if (ngx_strncasecmp(p, (u_char *) "charset=", 8) != 0) {
  4227.             continue;
  4228.         }

  4229.         p += 8;

  4230.         r->headers_out.content_type_len = last - h->value.data;

  4231.         if (*p == '"') {
  4232.             p++;
  4233.         }

  4234.         last = h->value.data + h->value.len;

  4235.         if (last > p && *(last - 1) == '"') {
  4236.             last--;
  4237.         }

  4238.         r->headers_out.charset.len = last - p;
  4239.         r->headers_out.charset.data = p;

  4240.         return NGX_OK;
  4241.     }

  4242.     return NGX_OK;
  4243. }


  4244. static ngx_int_t
  4245. ngx_http_upstream_copy_last_modified(ngx_http_request_t *r, ngx_table_elt_t *h,
  4246.     ngx_uint_t offset)
  4247. {
  4248.     ngx_table_elt_t  *ho;

  4249.     ho = ngx_list_push(&r->headers_out.headers);
  4250.     if (ho == NULL) {
  4251.         return NGX_ERROR;
  4252.     }

  4253.     *ho = *h;
  4254.     ho->next = NULL;

  4255.     r->headers_out.last_modified = ho;
  4256.     r->headers_out.last_modified_time =
  4257.                                     r->upstream->headers_in.last_modified_time;

  4258.     return NGX_OK;
  4259. }


  4260. static ngx_int_t
  4261. ngx_http_upstream_rewrite_location(ngx_http_request_t *r, ngx_table_elt_t *h,
  4262.     ngx_uint_t offset)
  4263. {
  4264.     ngx_int_t         rc;
  4265.     ngx_table_elt_t  *ho;

  4266.     ho = ngx_list_push(&r->headers_out.headers);
  4267.     if (ho == NULL) {
  4268.         return NGX_ERROR;
  4269.     }

  4270.     *ho = *h;
  4271.     ho->next = NULL;

  4272.     if (r->upstream->rewrite_redirect) {
  4273.         rc = r->upstream->rewrite_redirect(r, ho, 0);

  4274.         if (rc == NGX_DECLINED) {
  4275.             return NGX_OK;
  4276.         }

  4277.         if (rc == NGX_OK) {
  4278.             r->headers_out.location = ho;

  4279.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4280.                            "rewritten location: \"%V\"", &ho->value);
  4281.         }

  4282.         return rc;
  4283.     }

  4284.     if (ho->value.data[0] != '/') {
  4285.         r->headers_out.location = ho;
  4286.     }

  4287.     /*
  4288.      * we do not set r->headers_out.location here to avoid handling
  4289.      * relative redirects in ngx_http_header_filter()
  4290.      */

  4291.     return NGX_OK;
  4292. }


  4293. static ngx_int_t
  4294. ngx_http_upstream_rewrite_refresh(ngx_http_request_t *r, ngx_table_elt_t *h,
  4295.     ngx_uint_t offset)
  4296. {
  4297.     u_char           *p;
  4298.     ngx_int_t         rc;
  4299.     ngx_table_elt_t  *ho;

  4300.     ho = ngx_list_push(&r->headers_out.headers);
  4301.     if (ho == NULL) {
  4302.         return NGX_ERROR;
  4303.     }

  4304.     *ho = *h;
  4305.     ho->next = NULL;

  4306.     if (r->upstream->rewrite_redirect) {

  4307.         p = ngx_strcasestrn(ho->value.data, "url=", 4 - 1);

  4308.         if (p) {
  4309.             rc = r->upstream->rewrite_redirect(r, ho, p + 4 - ho->value.data);

  4310.         } else {
  4311.             return NGX_OK;
  4312.         }

  4313.         if (rc == NGX_DECLINED) {
  4314.             return NGX_OK;
  4315.         }

  4316.         if (rc == NGX_OK) {
  4317.             r->headers_out.refresh = ho;

  4318.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4319.                            "rewritten refresh: \"%V\"", &ho->value);
  4320.         }

  4321.         return rc;
  4322.     }

  4323.     r->headers_out.refresh = ho;

  4324.     return NGX_OK;
  4325. }


  4326. static ngx_int_t
  4327. ngx_http_upstream_rewrite_set_cookie(ngx_http_request_t *r, ngx_table_elt_t *h,
  4328.     ngx_uint_t offset)
  4329. {
  4330.     ngx_int_t         rc;
  4331.     ngx_table_elt_t  *ho;

  4332.     ho = ngx_list_push(&r->headers_out.headers);
  4333.     if (ho == NULL) {
  4334.         return NGX_ERROR;
  4335.     }

  4336.     *ho = *h;
  4337.     ho->next = NULL;

  4338.     if (r->upstream->rewrite_cookie) {
  4339.         rc = r->upstream->rewrite_cookie(r, ho);

  4340.         if (rc == NGX_DECLINED) {
  4341.             return NGX_OK;
  4342.         }

  4343. #if (NGX_DEBUG)
  4344.         if (rc == NGX_OK) {
  4345.             ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  4346.                            "rewritten cookie: \"%V\"", &ho->value);
  4347.         }
  4348. #endif

  4349.         return rc;
  4350.     }

  4351.     return NGX_OK;
  4352. }


  4353. static ngx_int_t
  4354. ngx_http_upstream_copy_allow_ranges(ngx_http_request_t *r,
  4355.     ngx_table_elt_t *h, ngx_uint_t offset)
  4356. {
  4357.     ngx_table_elt_t  *ho;

  4358.     if (r->upstream->conf->force_ranges) {
  4359.         return NGX_OK;
  4360.     }

  4361. #if (NGX_HTTP_CACHE)

  4362.     if (r->cached) {
  4363.         r->allow_ranges = 1;
  4364.         return NGX_OK;
  4365.     }

  4366.     if (r->upstream->cacheable) {
  4367.         r->allow_ranges = 1;
  4368.         r->single_range = 1;
  4369.         return NGX_OK;
  4370.     }

  4371. #endif

  4372.     ho = ngx_list_push(&r->headers_out.headers);
  4373.     if (ho == NULL) {
  4374.         return NGX_ERROR;
  4375.     }

  4376.     *ho = *h;
  4377.     ho->next = NULL;

  4378.     r->headers_out.accept_ranges = ho;

  4379.     return NGX_OK;
  4380. }


  4381. static ngx_int_t
  4382. ngx_http_upstream_add_variables(ngx_conf_t *cf)
  4383. {
  4384.     ngx_http_variable_t  *var, *v;

  4385.     for (v = ngx_http_upstream_vars; v->name.len; v++) {
  4386.         var = ngx_http_add_variable(cf, &v->name, v->flags);
  4387.         if (var == NULL) {
  4388.             return NGX_ERROR;
  4389.         }

  4390.         var->get_handler = v->get_handler;
  4391.         var->data = v->data;
  4392.     }

  4393.     return NGX_OK;
  4394. }


  4395. static ngx_int_t
  4396. ngx_http_upstream_addr_variable(ngx_http_request_t *r,
  4397.     ngx_http_variable_value_t *v, uintptr_t data)
  4398. {
  4399.     u_char                     *p;
  4400.     size_t                      len;
  4401.     ngx_uint_t                  i;
  4402.     ngx_http_upstream_state_t  *state;

  4403.     v->valid = 1;
  4404.     v->no_cacheable = 0;
  4405.     v->not_found = 0;

  4406.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4407.         v->not_found = 1;
  4408.         return NGX_OK;
  4409.     }

  4410.     len = 0;
  4411.     state = r->upstream_states->elts;

  4412.     for (i = 0; i < r->upstream_states->nelts; i++) {
  4413.         if (state[i].peer) {
  4414.             len += state[i].peer->len + 2;

  4415.         } else {
  4416.             len += 3;
  4417.         }
  4418.     }

  4419.     p = ngx_pnalloc(r->pool, len);
  4420.     if (p == NULL) {
  4421.         return NGX_ERROR;
  4422.     }

  4423.     v->data = p;

  4424.     i = 0;

  4425.     for ( ;; ) {
  4426.         if (state[i].peer) {
  4427.             p = ngx_cpymem(p, state[i].peer->data, state[i].peer->len);
  4428.         }

  4429.         if (++i == r->upstream_states->nelts) {
  4430.             break;
  4431.         }

  4432.         if (state[i].peer) {
  4433.             *p++ = ',';
  4434.             *p++ = ' ';

  4435.         } else {
  4436.             *p++ = ' ';
  4437.             *p++ = ':';
  4438.             *p++ = ' ';

  4439.             if (++i == r->upstream_states->nelts) {
  4440.                 break;
  4441.             }

  4442.             continue;
  4443.         }
  4444.     }

  4445.     v->len = p - v->data;

  4446.     return NGX_OK;
  4447. }


  4448. static ngx_int_t
  4449. ngx_http_upstream_status_variable(ngx_http_request_t *r,
  4450.     ngx_http_variable_value_t *v, uintptr_t data)
  4451. {
  4452.     u_char                     *p;
  4453.     size_t                      len;
  4454.     ngx_uint_t                  i;
  4455.     ngx_http_upstream_state_t  *state;

  4456.     v->valid = 1;
  4457.     v->no_cacheable = 0;
  4458.     v->not_found = 0;

  4459.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4460.         v->not_found = 1;
  4461.         return NGX_OK;
  4462.     }

  4463.     len = r->upstream_states->nelts * (3 + 2);

  4464.     p = ngx_pnalloc(r->pool, len);
  4465.     if (p == NULL) {
  4466.         return NGX_ERROR;
  4467.     }

  4468.     v->data = p;

  4469.     i = 0;
  4470.     state = r->upstream_states->elts;

  4471.     for ( ;; ) {
  4472.         if (state[i].status) {
  4473.             p = ngx_sprintf(p, "%ui", state[i].status);

  4474.         } else {
  4475.             *p++ = '-';
  4476.         }

  4477.         if (++i == r->upstream_states->nelts) {
  4478.             break;
  4479.         }

  4480.         if (state[i].peer) {
  4481.             *p++ = ',';
  4482.             *p++ = ' ';

  4483.         } else {
  4484.             *p++ = ' ';
  4485.             *p++ = ':';
  4486.             *p++ = ' ';

  4487.             if (++i == r->upstream_states->nelts) {
  4488.                 break;
  4489.             }

  4490.             continue;
  4491.         }
  4492.     }

  4493.     v->len = p - v->data;

  4494.     return NGX_OK;
  4495. }


  4496. static ngx_int_t
  4497. ngx_http_upstream_response_time_variable(ngx_http_request_t *r,
  4498.     ngx_http_variable_value_t *v, uintptr_t data)
  4499. {
  4500.     u_char                     *p;
  4501.     size_t                      len;
  4502.     ngx_uint_t                  i;
  4503.     ngx_msec_int_t              ms;
  4504.     ngx_http_upstream_state_t  *state;

  4505.     v->valid = 1;
  4506.     v->no_cacheable = 0;
  4507.     v->not_found = 0;

  4508.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4509.         v->not_found = 1;
  4510.         return NGX_OK;
  4511.     }

  4512.     len = r->upstream_states->nelts * (NGX_TIME_T_LEN + 4 + 2);

  4513.     p = ngx_pnalloc(r->pool, len);
  4514.     if (p == NULL) {
  4515.         return NGX_ERROR;
  4516.     }

  4517.     v->data = p;

  4518.     i = 0;
  4519.     state = r->upstream_states->elts;

  4520.     for ( ;; ) {

  4521.         if (data == 1) {
  4522.             ms = state[i].header_time;

  4523.         } else if (data == 2) {
  4524.             ms = state[i].connect_time;

  4525.         } else {
  4526.             ms = state[i].response_time;
  4527.         }

  4528.         if (ms != -1) {
  4529.             ms = ngx_max(ms, 0);
  4530.             p = ngx_sprintf(p, "%T.%03M", (time_t) ms / 1000, ms % 1000);

  4531.         } else {
  4532.             *p++ = '-';
  4533.         }

  4534.         if (++i == r->upstream_states->nelts) {
  4535.             break;
  4536.         }

  4537.         if (state[i].peer) {
  4538.             *p++ = ',';
  4539.             *p++ = ' ';

  4540.         } else {
  4541.             *p++ = ' ';
  4542.             *p++ = ':';
  4543.             *p++ = ' ';

  4544.             if (++i == r->upstream_states->nelts) {
  4545.                 break;
  4546.             }

  4547.             continue;
  4548.         }
  4549.     }

  4550.     v->len = p - v->data;

  4551.     return NGX_OK;
  4552. }


  4553. static ngx_int_t
  4554. ngx_http_upstream_response_length_variable(ngx_http_request_t *r,
  4555.     ngx_http_variable_value_t *v, uintptr_t data)
  4556. {
  4557.     u_char                     *p;
  4558.     size_t                      len;
  4559.     ngx_uint_t                  i;
  4560.     ngx_http_upstream_state_t  *state;

  4561.     v->valid = 1;
  4562.     v->no_cacheable = 0;
  4563.     v->not_found = 0;

  4564.     if (r->upstream_states == NULL || r->upstream_states->nelts == 0) {
  4565.         v->not_found = 1;
  4566.         return NGX_OK;
  4567.     }

  4568.     len = r->upstream_states->nelts * (NGX_OFF_T_LEN + 2);

  4569.     p = ngx_pnalloc(r->pool, len);
  4570.     if (p == NULL) {
  4571.         return NGX_ERROR;
  4572.     }

  4573.     v->data = p;

  4574.     i = 0;
  4575.     state = r->upstream_states->elts;

  4576.     for ( ;; ) {

  4577.         if (data == 1) {
  4578.             p = ngx_sprintf(p, "%O", state[i].bytes_received);

  4579.         } else if (data == 2) {
  4580.             p = ngx_sprintf(p, "%O", state[i].bytes_sent);

  4581.         } else {
  4582.             p = ngx_sprintf(p, "%O", state[i].response_length);
  4583.         }

  4584.         if (++i == r->upstream_states->nelts) {
  4585.             break;
  4586.         }

  4587.         if (state[i].peer) {
  4588.             *p++ = ',';
  4589.             *p++ = ' ';

  4590.         } else {
  4591.             *p++ = ' ';
  4592.             *p++ = ':';
  4593.             *p++ = ' ';

  4594.             if (++i == r->upstream_states->nelts) {
  4595.                 break;
  4596.             }

  4597.             continue;
  4598.         }
  4599.     }

  4600.     v->len = p - v->data;

  4601.     return NGX_OK;
  4602. }


  4603. static ngx_int_t
  4604. ngx_http_upstream_header_variable(ngx_http_request_t *r,
  4605.     ngx_http_variable_value_t *v, uintptr_t data)
  4606. {
  4607.     if (r->upstream == NULL) {
  4608.         v->not_found = 1;
  4609.         return NGX_OK;
  4610.     }

  4611.     return ngx_http_variable_unknown_header(r, v, (ngx_str_t *) data,
  4612.                                          &r->upstream->headers_in.headers.part,
  4613.                                          sizeof("upstream_http_") - 1);
  4614. }


  4615. static ngx_int_t
  4616. ngx_http_upstream_trailer_variable(ngx_http_request_t *r,
  4617.     ngx_http_variable_value_t *v, uintptr_t data)
  4618. {
  4619.     if (r->upstream == NULL) {
  4620.         v->not_found = 1;
  4621.         return NGX_OK;
  4622.     }

  4623.     return ngx_http_variable_unknown_header(r, v, (ngx_str_t *) data,
  4624.                                         &r->upstream->headers_in.trailers.part,
  4625.                                         sizeof("upstream_trailer_") - 1);
  4626. }


  4627. static ngx_int_t
  4628. ngx_http_upstream_cookie_variable(ngx_http_request_t *r,
  4629.     ngx_http_variable_value_t *v, uintptr_t data)
  4630. {
  4631.     ngx_str_t  *name = (ngx_str_t *) data;

  4632.     ngx_str_t   cookie, s;

  4633.     if (r->upstream == NULL) {
  4634.         v->not_found = 1;
  4635.         return NGX_OK;
  4636.     }

  4637.     s.len = name->len - (sizeof("upstream_cookie_") - 1);
  4638.     s.data = name->data + sizeof("upstream_cookie_") - 1;

  4639.     if (ngx_http_parse_set_cookie_lines(r, r->upstream->headers_in.set_cookie,
  4640.                                         &s, &cookie)
  4641.         == NULL)
  4642.     {
  4643.         v->not_found = 1;
  4644.         return NGX_OK;
  4645.     }

  4646.     v->len = cookie.len;
  4647.     v->valid = 1;
  4648.     v->no_cacheable = 0;
  4649.     v->not_found = 0;
  4650.     v->data = cookie.data;

  4651.     return NGX_OK;
  4652. }


  4653. #if (NGX_HTTP_CACHE)

  4654. static ngx_int_t
  4655. ngx_http_upstream_cache_status(ngx_http_request_t *r,
  4656.     ngx_http_variable_value_t *v, uintptr_t data)
  4657. {
  4658.     ngx_uint_t  n;

  4659.     if (r->upstream == NULL || r->upstream->cache_status == 0) {
  4660.         v->not_found = 1;
  4661.         return NGX_OK;
  4662.     }

  4663.     n = r->upstream->cache_status - 1;

  4664.     v->valid = 1;
  4665.     v->no_cacheable = 0;
  4666.     v->not_found = 0;
  4667.     v->len = ngx_http_cache_status[n].len;
  4668.     v->data = ngx_http_cache_status[n].data;

  4669.     return NGX_OK;
  4670. }


  4671. static ngx_int_t
  4672. ngx_http_upstream_cache_last_modified(ngx_http_request_t *r,
  4673.     ngx_http_variable_value_t *v, uintptr_t data)
  4674. {
  4675.     u_char  *p;

  4676.     if (r->upstream == NULL
  4677.         || !r->upstream->conf->cache_revalidate
  4678.         || r->upstream->cache_status != NGX_HTTP_CACHE_EXPIRED
  4679.         || r->cache->last_modified == -1)
  4680.     {
  4681.         v->not_found = 1;
  4682.         return NGX_OK;
  4683.     }

  4684.     p = ngx_pnalloc(r->pool, sizeof("Mon, 28 Sep 1970 06:00:00 GMT") - 1);
  4685.     if (p == NULL) {
  4686.         return NGX_ERROR;
  4687.     }

  4688.     v->len = ngx_http_time(p, r->cache->last_modified) - p;
  4689.     v->valid = 1;
  4690.     v->no_cacheable = 0;
  4691.     v->not_found = 0;
  4692.     v->data = p;

  4693.     return NGX_OK;
  4694. }


  4695. static ngx_int_t
  4696. ngx_http_upstream_cache_etag(ngx_http_request_t *r,
  4697.     ngx_http_variable_value_t *v, uintptr_t data)
  4698. {
  4699.     if (r->upstream == NULL
  4700.         || !r->upstream->conf->cache_revalidate
  4701.         || r->upstream->cache_status != NGX_HTTP_CACHE_EXPIRED
  4702.         || r->cache->etag.len == 0)
  4703.     {
  4704.         v->not_found = 1;
  4705.         return NGX_OK;
  4706.     }

  4707.     v->valid = 1;
  4708.     v->no_cacheable = 0;
  4709.     v->not_found = 0;
  4710.     v->len = r->cache->etag.len;
  4711.     v->data = r->cache->etag.data;

  4712.     return NGX_OK;
  4713. }

  4714. #endif


  4715. static char *
  4716. ngx_http_upstream(ngx_conf_t *cf, ngx_command_t *cmd, void *dummy)
  4717. {
  4718.     char                          *rv;
  4719.     void                          *mconf;
  4720.     ngx_str_t                     *value;
  4721.     ngx_url_t                      u;
  4722.     ngx_uint_t                     m;
  4723.     ngx_conf_t                     pcf;
  4724.     ngx_http_module_t             *module;
  4725.     ngx_http_conf_ctx_t           *ctx, *http_ctx;
  4726.     ngx_http_upstream_srv_conf_t  *uscf;

  4727.     ngx_memzero(&u, sizeof(ngx_url_t));

  4728.     value = cf->args->elts;
  4729.     u.host = value[1];
  4730.     u.no_resolve = 1;
  4731.     u.no_port = 1;

  4732.     uscf = ngx_http_upstream_add(cf, &u, NGX_HTTP_UPSTREAM_CREATE
  4733.                                          |NGX_HTTP_UPSTREAM_MODIFY
  4734.                                          |NGX_HTTP_UPSTREAM_WEIGHT
  4735.                                          |NGX_HTTP_UPSTREAM_MAX_CONNS
  4736.                                          |NGX_HTTP_UPSTREAM_MAX_FAILS
  4737.                                          |NGX_HTTP_UPSTREAM_FAIL_TIMEOUT
  4738.                                          |NGX_HTTP_UPSTREAM_DOWN
  4739.                                          |NGX_HTTP_UPSTREAM_BACKUP);
  4740.     if (uscf == NULL) {
  4741.         return NGX_CONF_ERROR;
  4742.     }


  4743.     ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_conf_ctx_t));
  4744.     if (ctx == NULL) {
  4745.         return NGX_CONF_ERROR;
  4746.     }

  4747.     http_ctx = cf->ctx;
  4748.     ctx->main_conf = http_ctx->main_conf;

  4749.     /* the upstream{}'s srv_conf */

  4750.     ctx->srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  4751.     if (ctx->srv_conf == NULL) {
  4752.         return NGX_CONF_ERROR;
  4753.     }

  4754.     ctx->srv_conf[ngx_http_upstream_module.ctx_index] = uscf;

  4755.     uscf->srv_conf = ctx->srv_conf;


  4756.     /* the upstream{}'s loc_conf */

  4757.     ctx->loc_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  4758.     if (ctx->loc_conf == NULL) {
  4759.         return NGX_CONF_ERROR;
  4760.     }

  4761.     for (m = 0; cf->cycle->modules[m]; m++) {
  4762.         if (cf->cycle->modules[m]->type != NGX_HTTP_MODULE) {
  4763.             continue;
  4764.         }

  4765.         module = cf->cycle->modules[m]->ctx;

  4766.         if (module->create_srv_conf) {
  4767.             mconf = module->create_srv_conf(cf);
  4768.             if (mconf == NULL) {
  4769.                 return NGX_CONF_ERROR;
  4770.             }

  4771.             ctx->srv_conf[cf->cycle->modules[m]->ctx_index] = mconf;
  4772.         }

  4773.         if (module->create_loc_conf) {
  4774.             mconf = module->create_loc_conf(cf);
  4775.             if (mconf == NULL) {
  4776.                 return NGX_CONF_ERROR;
  4777.             }

  4778.             ctx->loc_conf[cf->cycle->modules[m]->ctx_index] = mconf;
  4779.         }
  4780.     }

  4781.     uscf->servers = ngx_array_create(cf->pool, 4,
  4782.                                      sizeof(ngx_http_upstream_server_t));
  4783.     if (uscf->servers == NULL) {
  4784.         return NGX_CONF_ERROR;
  4785.     }


  4786.     /* parse inside upstream{} */

  4787.     pcf = *cf;
  4788.     cf->ctx = ctx;
  4789.     cf->cmd_type = NGX_HTTP_UPS_CONF;

  4790.     rv = ngx_conf_parse(cf, NULL);

  4791.     *cf = pcf;

  4792.     if (rv != NGX_CONF_OK) {
  4793.         return rv;
  4794.     }

  4795.     if (uscf->servers->nelts == 0) {
  4796.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4797.                            "no servers are inside upstream");
  4798.         return NGX_CONF_ERROR;
  4799.     }

  4800.     return rv;
  4801. }


  4802. static char *
  4803. ngx_http_upstream_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  4804. {
  4805.     ngx_http_upstream_srv_conf_t  *uscf = conf;

  4806.     time_t                       fail_timeout;
  4807.     ngx_str_t                   *value, s;
  4808.     ngx_url_t                    u;
  4809.     ngx_int_t                    weight, max_conns, max_fails;
  4810.     ngx_uint_t                   i;
  4811. #if (NGX_HTTP_UPSTREAM_ZONE)
  4812.     ngx_uint_t                   resolve;
  4813. #endif
  4814.     ngx_http_upstream_server_t  *us;

  4815.     us = ngx_array_push(uscf->servers);
  4816.     if (us == NULL) {
  4817.         return NGX_CONF_ERROR;
  4818.     }

  4819.     ngx_memzero(us, sizeof(ngx_http_upstream_server_t));

  4820.     value = cf->args->elts;

  4821.     weight = 1;
  4822.     max_conns = 0;
  4823.     max_fails = 1;
  4824.     fail_timeout = 10;
  4825. #if (NGX_HTTP_UPSTREAM_ZONE)
  4826.     resolve = 0;
  4827. #endif

  4828.     for (i = 2; i < cf->args->nelts; i++) {

  4829.         if (ngx_strncmp(value[i].data, "weight=", 7) == 0) {

  4830.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_WEIGHT)) {
  4831.                 goto not_supported;
  4832.             }

  4833.             weight = ngx_atoi(&value[i].data[7], value[i].len - 7);

  4834.             if (weight == NGX_ERROR || weight == 0) {
  4835.                 goto invalid;
  4836.             }

  4837.             continue;
  4838.         }

  4839.         if (ngx_strncmp(value[i].data, "max_conns=", 10) == 0) {

  4840.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_MAX_CONNS)) {
  4841.                 goto not_supported;
  4842.             }

  4843.             max_conns = ngx_atoi(&value[i].data[10], value[i].len - 10);

  4844.             if (max_conns == NGX_ERROR) {
  4845.                 goto invalid;
  4846.             }

  4847.             continue;
  4848.         }

  4849.         if (ngx_strncmp(value[i].data, "max_fails=", 10) == 0) {

  4850.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_MAX_FAILS)) {
  4851.                 goto not_supported;
  4852.             }

  4853.             max_fails = ngx_atoi(&value[i].data[10], value[i].len - 10);

  4854.             if (max_fails == NGX_ERROR) {
  4855.                 goto invalid;
  4856.             }

  4857.             continue;
  4858.         }

  4859.         if (ngx_strncmp(value[i].data, "fail_timeout=", 13) == 0) {

  4860.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_FAIL_TIMEOUT)) {
  4861.                 goto not_supported;
  4862.             }

  4863.             s.len = value[i].len - 13;
  4864.             s.data = &value[i].data[13];

  4865.             fail_timeout = ngx_parse_time(&s, 1);

  4866.             if (fail_timeout == (time_t) NGX_ERROR) {
  4867.                 goto invalid;
  4868.             }

  4869.             continue;
  4870.         }

  4871.         if (ngx_strcmp(value[i].data, "backup") == 0) {

  4872.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_BACKUP)) {
  4873.                 goto not_supported;
  4874.             }

  4875.             us->backup = 1;

  4876.             continue;
  4877.         }

  4878.         if (ngx_strcmp(value[i].data, "down") == 0) {

  4879.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_DOWN)) {
  4880.                 goto not_supported;
  4881.             }

  4882.             us->down = NGX_HTTP_UPSTREAM_FAILED;

  4883.             continue;
  4884.         }

  4885. #if (NGX_HTTP_UPSTREAM_STICKY)
  4886.         if (ngx_strcmp(value[i].data, "drain") == 0) {

  4887.             if (!(uscf->flags & NGX_HTTP_UPSTREAM_DOWN)) {
  4888.                 goto not_supported;
  4889.             }

  4890.             us->down = NGX_HTTP_UPSTREAM_DRAINING;

  4891.             continue;
  4892.         }
  4893. #endif

  4894. #if (NGX_HTTP_UPSTREAM_SID)
  4895.         if (ngx_strncmp(value[i].data, "route=", 6) == 0) {

  4896.             us->sid.data = &value[i].data[6];
  4897.             us->sid.len = value[i].len - 6;

  4898.             if (us->sid.len == 0) {
  4899.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "route is empty");
  4900.                 return NGX_CONF_ERROR;
  4901.             }

  4902.             if (us->sid.len > NGX_HTTP_UPSTREAM_SID_LEN) {
  4903.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4904.                                    "route is longer than %d",
  4905.                                    NGX_HTTP_UPSTREAM_SID_LEN);
  4906.                 return NGX_CONF_ERROR;
  4907.             }

  4908.             continue;
  4909.         }
  4910. #endif

  4911. #if (NGX_HTTP_UPSTREAM_ZONE)
  4912.         if (ngx_strcmp(value[i].data, "resolve") == 0) {
  4913.             resolve = 1;
  4914.             continue;
  4915.         }

  4916.         if (ngx_strncmp(value[i].data, "service=", 8) == 0) {

  4917.             us->service.len = value[i].len - 8;
  4918.             us->service.data = &value[i].data[8];

  4919.             if (us->service.len == 0) {
  4920.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "service is empty");
  4921.                 return NGX_CONF_ERROR;
  4922.             }

  4923.             continue;
  4924.         }
  4925. #endif

  4926.         goto invalid;
  4927.     }

  4928.     ngx_memzero(&u, sizeof(ngx_url_t));

  4929.     u.url = value[1];
  4930.     u.default_port = 80;

  4931. #if (NGX_HTTP_UPSTREAM_ZONE)
  4932.     if (resolve) {
  4933.         /* resolve at run time */
  4934.         u.no_resolve = 1;
  4935.     }

  4936.     if (us->service.len && !resolve) {
  4937.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4938.                            "service upstream \"%V\" requires "
  4939.                            "\"resolve\" parameter",
  4940.                            &u.url);
  4941.         return NGX_CONF_ERROR;
  4942.     }

  4943. #endif

  4944.     if (ngx_parse_url(cf->pool, &u) != NGX_OK) {
  4945.         if (u.err) {
  4946.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4947.                                "%s in upstream \"%V\"", u.err, &u.url);
  4948.         }

  4949.         return NGX_CONF_ERROR;
  4950.     }

  4951.     us->name = u.url;

  4952. #if (NGX_HTTP_UPSTREAM_ZONE)

  4953.     if (us->service.len && !u.no_port) {
  4954.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4955.                            "service upstream \"%V\" may not have port",
  4956.                            &us->name);

  4957.         return NGX_CONF_ERROR;
  4958.     }

  4959.     if (us->service.len && u.naddrs) {
  4960.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4961.                            "service upstream \"%V\" requires domain name",
  4962.                            &us->name);

  4963.         return NGX_CONF_ERROR;
  4964.     }

  4965.     if (resolve && u.naddrs == 0) {
  4966.         ngx_addr_t  *addr;

  4967.         /* save port */

  4968.         addr = ngx_pcalloc(cf->pool, sizeof(ngx_addr_t));
  4969.         if (addr == NULL) {
  4970.             return NGX_CONF_ERROR;
  4971.         }

  4972.         addr->sockaddr = ngx_palloc(cf->pool, u.socklen);
  4973.         if (addr->sockaddr == NULL) {
  4974.             return NGX_CONF_ERROR;
  4975.         }

  4976.         ngx_memcpy(addr->sockaddr, &u.sockaddr, u.socklen);

  4977.         addr->socklen = u.socklen;

  4978.         us->addrs = addr;
  4979.         us->naddrs = 1;

  4980.         us->host = u.host;

  4981.     } else {
  4982.         us->addrs = u.addrs;
  4983.         us->naddrs = u.naddrs;
  4984.     }

  4985. #else

  4986.     us->addrs = u.addrs;
  4987.     us->naddrs = u.naddrs;

  4988. #endif

  4989.     us->weight = weight;
  4990.     us->max_conns = max_conns;
  4991.     us->max_fails = max_fails;
  4992.     us->fail_timeout = fail_timeout;

  4993.     return NGX_CONF_OK;

  4994. invalid:

  4995.     ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  4996.                        "invalid parameter \"%V\"", &value[i]);

  4997.     return NGX_CONF_ERROR;

  4998. not_supported:

  4999.     ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5000.                        "balancing method does not support parameter \"%V\"",
  5001.                        &value[i]);

  5002.     return NGX_CONF_ERROR;
  5003. }


  5004. #if (NGX_HTTP_UPSTREAM_ZONE)

  5005. static char *
  5006. ngx_http_upstream_resolver(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  5007. {
  5008.     ngx_http_upstream_srv_conf_t  *uscf = conf;

  5009.     ngx_str_t  *value;

  5010.     if (uscf->resolver) {
  5011.         return "is duplicate";
  5012.     }

  5013.     value = cf->args->elts;

  5014.     uscf->resolver = ngx_resolver_create(cf, &value[1], cf->args->nelts - 1);
  5015.     if (uscf->resolver == NULL) {
  5016.         return NGX_CONF_ERROR;
  5017.     }

  5018.     return NGX_CONF_OK;
  5019. }

  5020. #endif


  5021. ngx_http_upstream_srv_conf_t *
  5022. ngx_http_upstream_add(ngx_conf_t *cf, ngx_url_t *u, ngx_uint_t flags)
  5023. {
  5024.     ngx_uint_t                      i;
  5025.     ngx_http_upstream_server_t     *us;
  5026.     ngx_http_upstream_srv_conf_t   *uscf, **uscfp;
  5027.     ngx_http_upstream_main_conf_t  *umcf;

  5028.     if (!(flags & NGX_HTTP_UPSTREAM_CREATE)) {

  5029.         if (ngx_parse_url(cf->pool, u) != NGX_OK) {
  5030.             if (u->err) {
  5031.                 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5032.                                    "%s in upstream \"%V\"", u->err, &u->url);
  5033.             }

  5034.             return NULL;
  5035.         }
  5036.     }

  5037.     umcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_upstream_module);

  5038.     uscfp = umcf->upstreams.elts;

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

  5040.         if (uscfp[i]->host.len != u->host.len
  5041.             || ngx_strncasecmp(uscfp[i]->host.data, u->host.data, u->host.len)
  5042.                != 0)
  5043.         {
  5044.             continue;
  5045.         }

  5046.         if ((flags & NGX_HTTP_UPSTREAM_CREATE)
  5047.              && (uscfp[i]->flags & NGX_HTTP_UPSTREAM_CREATE))
  5048.         {
  5049.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5050.                                "duplicate upstream \"%V\"", &u->host);
  5051.             return NULL;
  5052.         }

  5053.         if ((uscfp[i]->flags & NGX_HTTP_UPSTREAM_CREATE) && !u->no_port) {
  5054.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5055.                                "upstream \"%V\" may not have port %d",
  5056.                                &u->host, u->port);
  5057.             return NULL;
  5058.         }

  5059.         if ((flags & NGX_HTTP_UPSTREAM_CREATE) && !uscfp[i]->no_port) {
  5060.             ngx_log_error(NGX_LOG_EMERG, cf->log, 0,
  5061.                           "upstream \"%V\" may not have port %d in %s:%ui",
  5062.                           &u->host, uscfp[i]->port,
  5063.                           uscfp[i]->file_name, uscfp[i]->line);
  5064.             return NULL;
  5065.         }

  5066.         if (uscfp[i]->port && u->port
  5067.             && uscfp[i]->port != u->port)
  5068.         {
  5069.             continue;
  5070.         }

  5071.         if (flags & NGX_HTTP_UPSTREAM_CREATE) {
  5072.             uscfp[i]->flags = flags;
  5073.             uscfp[i]->port = 0;
  5074.         }

  5075.         return uscfp[i];
  5076.     }

  5077.     uscf = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_srv_conf_t));
  5078.     if (uscf == NULL) {
  5079.         return NULL;
  5080.     }

  5081.     uscf->flags = flags;
  5082.     uscf->host = u->host;
  5083.     uscf->file_name = cf->conf_file->file.name.data;
  5084.     uscf->line = cf->conf_file->line;
  5085.     uscf->port = u->port;
  5086.     uscf->no_port = u->no_port;
  5087. #if (NGX_HTTP_UPSTREAM_ZONE)
  5088.     uscf->resolver_timeout = NGX_CONF_UNSET_MSEC;
  5089. #endif

  5090.     if (u->naddrs == 1 && (u->port || u->family == AF_UNIX)) {
  5091.         uscf->servers = ngx_array_create(cf->pool, 1,
  5092.                                          sizeof(ngx_http_upstream_server_t));
  5093.         if (uscf->servers == NULL) {
  5094.             return NULL;
  5095.         }

  5096.         us = ngx_array_push(uscf->servers);
  5097.         if (us == NULL) {
  5098.             return NULL;
  5099.         }

  5100.         ngx_memzero(us, sizeof(ngx_http_upstream_server_t));

  5101.         us->addrs = u->addrs;
  5102.         us->naddrs = 1;
  5103.     }

  5104.     uscfp = ngx_array_push(&umcf->upstreams);
  5105.     if (uscfp == NULL) {
  5106.         return NULL;
  5107.     }

  5108.     *uscfp = uscf;

  5109.     return uscf;
  5110. }


  5111. char *
  5112. ngx_http_upstream_bind_set_slot(ngx_conf_t *cf, ngx_command_t *cmd,
  5113.     void *conf)
  5114. {
  5115.     char  *p = conf;

  5116.     ngx_int_t                           rc;
  5117.     ngx_str_t                          *value;
  5118.     ngx_http_complex_value_t            cv;
  5119.     ngx_http_upstream_local_t         **plocal, *local;
  5120.     ngx_http_compile_complex_value_t    ccv;

  5121.     plocal = (ngx_http_upstream_local_t **) (p + cmd->offset);

  5122.     if (*plocal != NGX_CONF_UNSET_PTR) {
  5123.         return "is duplicate";
  5124.     }

  5125.     value = cf->args->elts;

  5126.     if (cf->args->nelts == 2 && ngx_strcmp(value[1].data, "off") == 0) {
  5127.         *plocal = NULL;
  5128.         return NGX_CONF_OK;
  5129.     }

  5130.     ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));

  5131.     ccv.cf = cf;
  5132.     ccv.value = &value[1];
  5133.     ccv.complex_value = &cv;

  5134.     if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
  5135.         return NGX_CONF_ERROR;
  5136.     }

  5137.     local = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_local_t));
  5138.     if (local == NULL) {
  5139.         return NGX_CONF_ERROR;
  5140.     }

  5141.     *plocal = local;

  5142.     if (cv.lengths) {
  5143.         local->value = ngx_palloc(cf->pool, sizeof(ngx_http_complex_value_t));
  5144.         if (local->value == NULL) {
  5145.             return NGX_CONF_ERROR;
  5146.         }

  5147.         *local->value = cv;

  5148.     } else {
  5149.         local->addr = ngx_palloc(cf->pool, sizeof(ngx_addr_t));
  5150.         if (local->addr == NULL) {
  5151.             return NGX_CONF_ERROR;
  5152.         }

  5153.         rc = ngx_parse_addr_port(cf->pool, local->addr, value[1].data,
  5154.                                  value[1].len);

  5155.         switch (rc) {
  5156.         case NGX_OK:
  5157.             local->addr->name = value[1];
  5158.             break;

  5159.         case NGX_DECLINED:
  5160.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5161.                                "invalid address \"%V\"", &value[1]);
  5162.             /* fall through */

  5163.         default:
  5164.             return NGX_CONF_ERROR;
  5165.         }
  5166.     }

  5167.     if (cf->args->nelts > 2) {
  5168.         if (ngx_strcmp(value[2].data, "transparent") == 0) {
  5169. #if (NGX_HAVE_TRANSPARENT_PROXY)
  5170.             ngx_core_conf_t  *ccf;

  5171.             ccf = (ngx_core_conf_t *) ngx_get_conf(cf->cycle->conf_ctx,
  5172.                                                    ngx_core_module);

  5173.             ccf->transparent = 1;
  5174.             local->transparent = 1;
  5175. #else
  5176.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5177.                                "transparent proxying is not supported "
  5178.                                "on this platform, ignored");
  5179. #endif
  5180.         } else {
  5181.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5182.                                "invalid parameter \"%V\"", &value[2]);
  5183.             return NGX_CONF_ERROR;
  5184.         }
  5185.     }

  5186.     return NGX_CONF_OK;
  5187. }


  5188. static ngx_int_t
  5189. ngx_http_upstream_set_local(ngx_http_request_t *r, ngx_http_upstream_t *u,
  5190.     ngx_http_upstream_local_t *local)
  5191. {
  5192.     ngx_int_t    rc;
  5193.     ngx_str_t    val;
  5194.     ngx_addr_t  *addr;

  5195.     if (local == NULL) {
  5196.         u->peer.local = NULL;
  5197.         return NGX_OK;
  5198.     }

  5199. #if (NGX_HAVE_TRANSPARENT_PROXY)
  5200.     u->peer.transparent = local->transparent;
  5201. #endif

  5202.     if (local->value == NULL) {
  5203.         u->peer.local = local->addr;
  5204.         return NGX_OK;
  5205.     }

  5206.     if (ngx_http_complex_value(r, local->value, &val) != NGX_OK) {
  5207.         return NGX_ERROR;
  5208.     }

  5209.     if (val.len == 0) {
  5210.         u->peer.local = NULL;
  5211.         return NGX_OK;
  5212.     }

  5213.     addr = ngx_palloc(r->pool, sizeof(ngx_addr_t));
  5214.     if (addr == NULL) {
  5215.         return NGX_ERROR;
  5216.     }

  5217.     rc = ngx_parse_addr_port(r->pool, addr, val.data, val.len);
  5218.     if (rc == NGX_ERROR) {
  5219.         return NGX_ERROR;
  5220.     }

  5221.     if (rc != NGX_OK) {
  5222.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
  5223.                       "invalid local address \"%V\"", &val);
  5224.         u->peer.local = NULL;
  5225.         return NGX_OK;
  5226.     }

  5227.     addr->name = val;
  5228.     u->peer.local = addr;

  5229.     return NGX_OK;
  5230. }


  5231. char *
  5232. ngx_http_upstream_param_set_slot(ngx_conf_t *cf, ngx_command_t *cmd,
  5233.     void *conf)
  5234. {
  5235.     char  *p = conf;

  5236.     ngx_str_t                   *value;
  5237.     ngx_array_t                **a;
  5238.     ngx_http_upstream_param_t   *param;

  5239.     a = (ngx_array_t **) (p + cmd->offset);

  5240.     if (*a == NULL) {
  5241.         *a = ngx_array_create(cf->pool, 4, sizeof(ngx_http_upstream_param_t));
  5242.         if (*a == NULL) {
  5243.             return NGX_CONF_ERROR;
  5244.         }
  5245.     }

  5246.     param = ngx_array_push(*a);
  5247.     if (param == NULL) {
  5248.         return NGX_CONF_ERROR;
  5249.     }

  5250.     value = cf->args->elts;

  5251.     param->key = value[1];
  5252.     param->value = value[2];
  5253.     param->skip_empty = 0;

  5254.     if (cf->args->nelts == 4) {
  5255.         if (ngx_strcmp(value[3].data, "if_not_empty") != 0) {
  5256.             ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  5257.                                "invalid parameter \"%V\"", &value[3]);
  5258.             return NGX_CONF_ERROR;
  5259.         }

  5260.         param->skip_empty = 1;
  5261.     }

  5262.     return NGX_CONF_OK;
  5263. }


  5264. ngx_int_t
  5265. ngx_http_upstream_hide_headers_hash(ngx_conf_t *cf,
  5266.     ngx_http_upstream_conf_t *conf, ngx_http_upstream_conf_t *prev,
  5267.     ngx_str_t *default_hide_headers, ngx_hash_init_t *hash)
  5268. {
  5269.     ngx_str_t       *h;
  5270.     ngx_uint_t       i, j;
  5271.     ngx_array_t      hide_headers;
  5272.     ngx_hash_key_t  *hk;

  5273.     if (conf->hide_headers == NGX_CONF_UNSET_PTR
  5274.         && conf->pass_headers == NGX_CONF_UNSET_PTR)
  5275.     {
  5276.         conf->hide_headers = prev->hide_headers;
  5277.         conf->pass_headers = prev->pass_headers;

  5278.         conf->hide_headers_hash = prev->hide_headers_hash;

  5279.         if (conf->hide_headers_hash.buckets) {
  5280.             return NGX_OK;
  5281.         }

  5282.     } else {
  5283.         if (conf->hide_headers == NGX_CONF_UNSET_PTR) {
  5284.             conf->hide_headers = prev->hide_headers;
  5285.         }

  5286.         if (conf->pass_headers == NGX_CONF_UNSET_PTR) {
  5287.             conf->pass_headers = prev->pass_headers;
  5288.         }
  5289.     }

  5290.     if (ngx_array_init(&hide_headers, cf->temp_pool, 4, sizeof(ngx_hash_key_t))
  5291.         != NGX_OK)
  5292.     {
  5293.         return NGX_ERROR;
  5294.     }

  5295.     for (h = default_hide_headers; h->len; h++) {
  5296.         hk = ngx_array_push(&hide_headers);
  5297.         if (hk == NULL) {
  5298.             return NGX_ERROR;
  5299.         }

  5300.         hk->key = *h;
  5301.         hk->key_hash = ngx_hash_key_lc(h->data, h->len);
  5302.         hk->value = (void *) 1;
  5303.     }

  5304.     if (conf->hide_headers != NGX_CONF_UNSET_PTR) {

  5305.         h = conf->hide_headers->elts;

  5306.         for (i = 0; i < conf->hide_headers->nelts; i++) {

  5307.             hk = hide_headers.elts;

  5308.             for (j = 0; j < hide_headers.nelts; j++) {
  5309.                 if (ngx_strcasecmp(h[i].data, hk[j].key.data) == 0) {
  5310.                     goto exist;
  5311.                 }
  5312.             }

  5313.             hk = ngx_array_push(&hide_headers);
  5314.             if (hk == NULL) {
  5315.                 return NGX_ERROR;
  5316.             }

  5317.             hk->key = h[i];
  5318.             hk->key_hash = ngx_hash_key_lc(h[i].data, h[i].len);
  5319.             hk->value = (void *) 1;

  5320.         exist:

  5321.             continue;
  5322.         }
  5323.     }

  5324.     if (conf->pass_headers != NGX_CONF_UNSET_PTR) {

  5325.         h = conf->pass_headers->elts;
  5326.         hk = hide_headers.elts;

  5327.         for (i = 0; i < conf->pass_headers->nelts; i++) {
  5328.             for (j = 0; j < hide_headers.nelts; j++) {

  5329.                 if (hk[j].key.data == NULL) {
  5330.                     continue;
  5331.                 }

  5332.                 if (ngx_strcasecmp(h[i].data, hk[j].key.data) == 0) {
  5333.                     hk[j].key.data = NULL;
  5334.                     break;
  5335.                 }
  5336.             }
  5337.         }
  5338.     }

  5339.     hash->hash = &conf->hide_headers_hash;
  5340.     hash->key = ngx_hash_key_lc;
  5341.     hash->pool = cf->pool;
  5342.     hash->temp_pool = NULL;

  5343.     if (ngx_hash_init(hash, hide_headers.elts, hide_headers.nelts) != NGX_OK) {
  5344.         return NGX_ERROR;
  5345.     }

  5346.     /*
  5347.      * special handling to preserve conf->hide_headers_hash
  5348.      * in the "http" section to inherit it to all servers
  5349.      */

  5350.     if (prev->hide_headers_hash.buckets == NULL
  5351.         && conf->hide_headers == prev->hide_headers
  5352.         && conf->pass_headers == prev->pass_headers)
  5353.     {
  5354.         prev->hide_headers_hash = conf->hide_headers_hash;
  5355.     }

  5356.     return NGX_OK;
  5357. }


  5358. #if (NGX_HTTP_SSL)

  5359. ngx_int_t
  5360. ngx_http_upstream_merge_ssl_passwords(ngx_conf_t *cf,
  5361.     ngx_http_upstream_conf_t *conf, ngx_http_upstream_conf_t *prev)
  5362. {
  5363.     ngx_uint_t  preserve;

  5364.     ngx_conf_merge_ptr_value(conf->ssl_passwords, prev->ssl_passwords, NULL);

  5365.     if (conf->ssl_certificate == NULL
  5366.         || conf->ssl_certificate->value.len == 0
  5367.         || conf->ssl_certificate_key == NULL)
  5368.     {
  5369.         return NGX_OK;
  5370.     }

  5371.     if (conf->ssl_certificate->lengths == NULL
  5372.         && conf->ssl_certificate_key->lengths == NULL)
  5373.     {
  5374.         if (conf->ssl_passwords && conf->ssl_passwords->pool == NULL) {
  5375.             /* un-preserve empty password list */
  5376.             conf->ssl_passwords = NULL;
  5377.         }

  5378.         return NGX_OK;
  5379.     }

  5380.     if (conf->ssl_passwords && conf->ssl_passwords->pool != cf->temp_pool) {
  5381.         /* already preserved */
  5382.         return NGX_OK;
  5383.     }

  5384.     preserve = (conf->ssl_passwords == prev->ssl_passwords) ? 1 : 0;

  5385.     conf->ssl_passwords = ngx_ssl_preserve_passwords(cf, conf->ssl_passwords);
  5386.     if (conf->ssl_passwords == NULL) {
  5387.         return NGX_ERROR;
  5388.     }

  5389.     /*
  5390.      * special handling to keep a preserved ssl_passwords copy
  5391.      * in the previous configuration to inherit it to all children
  5392.      */

  5393.     if (preserve) {
  5394.         prev->ssl_passwords = conf->ssl_passwords;
  5395.     }

  5396.     return NGX_OK;
  5397. }

  5398. #endif


  5399. static void *
  5400. ngx_http_upstream_create_main_conf(ngx_conf_t *cf)
  5401. {
  5402.     ngx_http_upstream_main_conf_t  *umcf;

  5403.     umcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_upstream_main_conf_t));
  5404.     if (umcf == NULL) {
  5405.         return NULL;
  5406.     }

  5407.     if (ngx_array_init(&umcf->upstreams, cf->pool, 4,
  5408.                        sizeof(ngx_http_upstream_srv_conf_t *))
  5409.         != NGX_OK)
  5410.     {
  5411.         return NULL;
  5412.     }

  5413.     return umcf;
  5414. }


  5415. static char *
  5416. ngx_http_upstream_init_main_conf(ngx_conf_t *cf, void *conf)
  5417. {
  5418.     ngx_http_upstream_main_conf_t  *umcf = conf;

  5419.     ngx_uint_t                      i;
  5420.     ngx_array_t                     headers_in;
  5421.     ngx_hash_key_t                 *hk;
  5422.     ngx_hash_init_t                 hash;
  5423.     ngx_http_upstream_init_pt       init;
  5424.     ngx_http_upstream_header_t     *header;
  5425.     ngx_http_upstream_srv_conf_t  **uscfp;

  5426.     uscfp = umcf->upstreams.elts;

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

  5428.         init = uscfp[i]->peer.init_upstream ? uscfp[i]->peer.init_upstream:
  5429.                                             ngx_http_upstream_init_round_robin;

  5430.         if (init(cf, uscfp[i]) != NGX_OK) {
  5431.             return NGX_CONF_ERROR;
  5432.         }
  5433.     }


  5434.     /* upstream_headers_in_hash */

  5435.     if (ngx_array_init(&headers_in, cf->temp_pool, 32, sizeof(ngx_hash_key_t))
  5436.         != NGX_OK)
  5437.     {
  5438.         return NGX_CONF_ERROR;
  5439.     }

  5440.     for (header = ngx_http_upstream_headers_in; header->name.len; header++) {
  5441.         hk = ngx_array_push(&headers_in);
  5442.         if (hk == NULL) {
  5443.             return NGX_CONF_ERROR;
  5444.         }

  5445.         hk->key = header->name;
  5446.         hk->key_hash = ngx_hash_key_lc(header->name.data, header->name.len);
  5447.         hk->value = header;
  5448.     }

  5449.     hash.hash = &umcf->headers_in_hash;
  5450.     hash.key = ngx_hash_key_lc;
  5451.     hash.max_size = 512;
  5452.     hash.bucket_size = ngx_align(64, ngx_cacheline_size);
  5453.     hash.name = "upstream_headers_in_hash";
  5454.     hash.pool = cf->pool;
  5455.     hash.temp_pool = NULL;

  5456.     if (ngx_hash_init(&hash, headers_in.elts, headers_in.nelts) != NGX_OK) {
  5457.         return NGX_CONF_ERROR;
  5458.     }

  5459.     return NGX_CONF_OK;
  5460. }