Coverage Report

Created: 2026-11-11 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/haproxy/src/backend.c
Line
Count
Source
1
/*
2
 * Backend variables and functions.
3
 *
4
 * Copyright 2000-2013 Willy Tarreau <w@1wt.eu>
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version
9
 * 2 of the License, or (at your option) any later version.
10
 *
11
 */
12
13
#include <errno.h>
14
#include <stdio.h>
15
#include <stdlib.h>
16
#include <syslog.h>
17
#include <string.h>
18
#include <ctype.h>
19
#include <sys/types.h>
20
21
#include <import/ceb64_tree.h>
22
23
#include <haproxy/api.h>
24
#include <haproxy/acl.h>
25
#include <haproxy/activity.h>
26
#include <haproxy/arg.h>
27
#include <haproxy/backend.h>
28
#include <haproxy/channel.h>
29
#include <haproxy/check.h>
30
#include <haproxy/counters.h>
31
#include <haproxy/frontend.h>
32
#include <haproxy/global.h>
33
#include <haproxy/hash.h>
34
#include <haproxy/http.h>
35
#include <haproxy/http_ana.h>
36
#include <haproxy/http_htx.h>
37
#include <haproxy/htx.h>
38
#include <haproxy/lb_chash.h>
39
#include <haproxy/lb_fas.h>
40
#include <haproxy/lb_fwlc.h>
41
#include <haproxy/lb_fwrr.h>
42
#include <haproxy/lb_map.h>
43
#include <haproxy/lb_ss.h>
44
#include <haproxy/log.h>
45
#include <haproxy/namespace.h>
46
#include <haproxy/obj_type.h>
47
#include <haproxy/payload.h>
48
#include <haproxy/proto_tcp.h>
49
#include <haproxy/protocol.h>
50
#include <haproxy/proxy.h>
51
#include <haproxy/queue.h>
52
#include <haproxy/sample.h>
53
#include <haproxy/sc_strm.h>
54
#include <haproxy/server.h>
55
#include <haproxy/session.h>
56
#include <haproxy/ssl_sock.h>
57
#include <haproxy/stconn.h>
58
#include <haproxy/stream.h>
59
#include <haproxy/task.h>
60
#include <haproxy/ticks.h>
61
#include <haproxy/time.h>
62
#include <haproxy/tools.h>
63
#include <haproxy/trace.h>
64
65
#define TRACE_SOURCE &trace_strm
66
67
struct list lb_ops_list = LIST_HEAD_INIT(lb_ops_list);
68
69
void lb_ops_register(struct lb_ops *ops)
70
0
{
71
0
  LIST_APPEND(&lb_ops_list, &ops->link);
72
0
}
73
74
/* helper function to invoke the correct hash method */
75
unsigned int gen_hash(const struct proxy* px, const char* key, unsigned long len)
76
0
{
77
0
  unsigned int hash;
78
79
0
  switch (px->lbprm.algo & BE_LB_HASH_FUNC) {
80
0
  case BE_LB_HFCN_DJB2:
81
0
    hash = hash_djb2(key, len);
82
0
    break;
83
0
  case BE_LB_HFCN_WT6:
84
0
    hash = hash_wt6(key, len);
85
0
    break;
86
0
  case BE_LB_HFCN_CRC32:
87
0
    hash = hash_crc32(key, len);
88
0
    break;
89
0
  case BE_LB_HFCN_NONE:
90
    /* use key as a hash. It MUST be in string format */
91
0
    {
92
0
      const char *_key = key;
93
94
0
      hash = read_int64(&_key, _key + len);
95
0
    }
96
0
    break;
97
0
  case BE_LB_HFCN_SDBM:
98
    /* this is the default hash function */
99
0
  default:
100
0
    hash = hash_sdbm(key, len);
101
0
    break;
102
0
  }
103
104
0
  if ((px->lbprm.algo & BE_LB_HASH_MOD) == BE_LB_HMOD_AVAL)
105
0
    hash = full_hash(hash);
106
107
0
  return hash;
108
0
}
109
110
/*
111
 * This function recounts the number of usable active and backup servers for
112
 * proxy <p>. These numbers are returned into the p->srv_act and p->srv_bck.
113
 * This function also recomputes the total active and backup weights. However,
114
 * it does not update tot_weight nor tot_used. Use update_backend_weight() for
115
 * this.
116
 * This functions is designed to be called before server's weight and state
117
 * commit so it uses 'next' weight and states values.
118
 *
119
 * threads: this is the caller responsibility to lock data. For now, this
120
 * function is called from lb modules, so it should be ok. But if you need to
121
 * call it from another place, be careful (and update this comment).
122
 */
123
void recount_servers(struct proxy *px)
124
0
{
125
0
  struct server *srv;
126
127
0
  px->srv_act = px->srv_bck = 0;
128
0
  px->lbprm.tot_wact = px->lbprm.tot_wbck = 0;
129
0
  px->lbprm.fbck = NULL;
130
0
  list_for_each_entry(srv, &px->servers, el_px) {
131
0
    if (!srv_willbe_usable(srv))
132
0
      continue;
133
134
0
    if (srv->flags & SRV_F_BACKUP) {
135
0
      if (!px->srv_bck &&
136
0
          !(px->options & PR_O_USE_ALL_BK))
137
0
        px->lbprm.fbck = srv;
138
0
      px->srv_bck++;
139
0
      srv->cumulative_weight = px->lbprm.tot_wbck;
140
0
      px->lbprm.tot_wbck += srv->next_eweight;
141
0
    } else {
142
0
      px->srv_act++;
143
0
      srv->cumulative_weight = px->lbprm.tot_wact;
144
0
      px->lbprm.tot_wact += srv->next_eweight;
145
0
    }
146
0
  }
147
0
}
148
149
/* This function simply updates the backend's tot_weight and tot_used values
150
 * after servers weights have been updated. It is designed to be used after
151
 * recount_servers() or equivalent.
152
 *
153
 * threads: this is the caller responsibility to lock data. For now, this
154
 * function is called from lb modules, so it should be ok. But if you need to
155
 * call it from another place, be careful (and update this comment).
156
 */
157
void update_backend_weight(struct proxy *px)
158
0
{
159
0
  if (px->srv_act) {
160
0
    px->lbprm.tot_weight = px->lbprm.tot_wact;
161
0
    px->lbprm.tot_used   = px->srv_act;
162
0
  }
163
0
  else if (px->lbprm.fbck) {
164
    /* use only the first backup server */
165
0
    px->lbprm.tot_weight = px->lbprm.fbck->next_eweight;
166
0
    px->lbprm.tot_used = 1;
167
0
  }
168
0
  else {
169
0
    px->lbprm.tot_weight = px->lbprm.tot_wbck;
170
0
    px->lbprm.tot_used   = px->srv_bck;
171
0
  }
172
0
}
173
174
/*
175
 * This function tries to find a running server for the proxy <px> following
176
 * the source hash method. Depending on the number of active/backup servers,
177
 * it will either look for active servers, or for backup servers.
178
 * If any server is found, it will be returned. If no valid server is found,
179
 * NULL is returned.
180
 */
181
struct server *get_server_sh(struct proxy *px, const char *addr, int len, const struct server *avoid)
182
0
{
183
0
  unsigned int h, l;
184
185
0
  if (px->lbprm.tot_weight == 0)
186
0
    return NULL;
187
188
0
  l = h = 0;
189
190
  /* note: we won't hash if there's only one server left */
191
0
  if (px->lbprm.tot_used == 1)
192
0
    goto hash_done;
193
194
0
  while ((l + sizeof (int)) <= len) {
195
0
    h ^= ntohl(*(unsigned int *)(&addr[l]));
196
0
    l += sizeof (int);
197
0
  }
198
  /* FIXME: why don't we use gen_hash() here as well?
199
   * -> we don't take into account hash function from "hash_type"
200
   * options here..
201
   */
202
0
  if ((px->lbprm.algo & BE_LB_HASH_MOD) == BE_LB_HMOD_AVAL)
203
0
    h = full_hash(h);
204
0
 hash_done:
205
0
  if ((px->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
206
0
    return chash_get_server_hash(px, h, avoid);
207
0
  else
208
0
    return map_get_server_hash(px, h);
209
0
}
210
211
/*
212
 * This function tries to find a running server for the proxy <px> following
213
 * the URI hash method. In order to optimize cache hits, the hash computation
214
 * ends at the question mark. Depending on the number of active/backup servers,
215
 * it will either look for active servers, or for backup servers.
216
 * If any server is found, it will be returned. If no valid server is found,
217
 * NULL is returned. The lbprm.arg_opt{1,2,3} values correspond respectively to
218
 * the "whole" optional argument (boolean, bit0), the "len" argument (numeric)
219
 * and the "depth" argument (numeric).
220
 *
221
 * This code was contributed by Guillaume Dallaire, who also selected this hash
222
 * algorithm out of a tens because it gave him the best results.
223
 *
224
 */
225
struct server *get_server_uh(struct proxy *px, char *uri, int uri_len, const struct server *avoid)
226
0
{
227
0
  unsigned int hash = 0;
228
0
  int c;
229
0
  int slashes = 0;
230
0
  const char *start, *end;
231
232
0
  if (px->lbprm.tot_weight == 0)
233
0
    return NULL;
234
235
  /* note: we won't hash if there's only one server left */
236
0
  if (px->lbprm.tot_used == 1)
237
0
    goto hash_done;
238
239
0
  if (px->lbprm.arg_opt2) // "len"
240
0
    uri_len = MIN(uri_len, px->lbprm.arg_opt2);
241
242
0
  start = end = uri;
243
0
  while (uri_len--) {
244
0
    c = *end;
245
0
    if (c == '/') {
246
0
      slashes++;
247
0
      if (slashes == px->lbprm.arg_opt3) /* depth+1 */
248
0
        break;
249
0
    }
250
0
    else if (c == '?' && !(px->lbprm.arg_opt1 & 1)) // "whole"
251
0
      break;
252
0
    end++;
253
0
  }
254
255
0
  hash = gen_hash(px, start, (end - start));
256
257
0
 hash_done:
258
0
  if ((px->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
259
0
    return chash_get_server_hash(px, hash, avoid);
260
0
  else
261
0
    return map_get_server_hash(px, hash);
262
0
}
263
264
/*
265
 * This function tries to find a running server for the proxy <px> following
266
 * the URL parameter hash method. It looks for a specific parameter in the
267
 * URL and hashes it to compute the server ID. This is useful to optimize
268
 * performance by avoiding bounces between servers in contexts where sessions
269
 * are shared but cookies are not usable. If the parameter is not found, NULL
270
 * is returned. If any server is found, it will be returned. If no valid server
271
 * is found, NULL is returned.
272
 */
273
struct server *get_server_ph(struct proxy *px, const char *uri, int uri_len, const struct server *avoid)
274
0
{
275
0
  unsigned int hash = 0;
276
0
  const char *start, *end;
277
0
  const char *p;
278
0
  const char *params;
279
0
  int plen;
280
281
  /* when tot_weight is 0 then so is srv_count */
282
0
  if (px->lbprm.tot_weight == 0)
283
0
    return NULL;
284
285
0
  if ((p = memchr(uri, '?', uri_len)) == NULL)
286
0
    return NULL;
287
288
0
  p++;
289
290
0
  uri_len -= (p - uri);
291
0
  plen = px->lbprm.arg_len;
292
0
  params = p;
293
294
0
  while (uri_len > plen) {
295
    /* Look for the parameter name followed by an equal symbol */
296
0
    if (params[plen] == '=') {
297
0
      if (memcmp(params, px->lbprm.arg_str, plen) == 0) {
298
        /* OK, we have the parameter here at <params>, and
299
         * the value after the equal sign, at <p>
300
         * skip the equal symbol
301
         */
302
0
        p += plen + 1;
303
0
        start = end = p;
304
0
        uri_len -= plen + 1;
305
306
0
        while (uri_len && *end != '&') {
307
0
          uri_len--;
308
0
          end++;
309
0
        }
310
0
        hash = gen_hash(px, start, (end - start));
311
312
0
        if ((px->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
313
0
          return chash_get_server_hash(px, hash, avoid);
314
0
        else
315
0
          return map_get_server_hash(px, hash);
316
0
      }
317
0
    }
318
    /* skip to next parameter */
319
0
    p = memchr(params, '&', uri_len);
320
0
    if (!p)
321
0
      return NULL;
322
0
    p++;
323
0
    uri_len -= (p - params);
324
0
    params = p;
325
0
  }
326
0
  return NULL;
327
0
}
328
329
/*
330
 * this does the same as the previous server_ph, but check the body contents
331
 */
332
struct server *get_server_ph_post(struct stream *s, const struct server *avoid)
333
0
{
334
0
  unsigned int hash = 0;
335
0
  struct channel  *req  = &s->req;
336
0
  struct proxy    *px   = s->be;
337
0
  struct htx      *htx = htxbuf(&req->buf);
338
0
  struct htx_blk  *blk;
339
0
  unsigned int     plen = px->lbprm.arg_len;
340
0
  unsigned long    len;
341
0
  const char      *params, *p, *start, *end;
342
343
0
  if (px->lbprm.tot_weight == 0)
344
0
    return NULL;
345
346
0
  p = params = NULL;
347
0
  len = 0;
348
0
  for (blk = htx_get_first_blk(htx); blk; blk = htx_get_next_blk(htx, blk)) {
349
0
    enum htx_blk_type type = htx_get_blk_type(blk);
350
0
    struct ist v;
351
352
0
    if (type != HTX_BLK_DATA)
353
0
      continue;
354
0
    v = htx_get_blk_value(htx, blk);
355
0
    p = params = v.ptr;
356
0
    len = v.len;
357
0
    break;
358
0
  }
359
360
0
  while (len > plen) {
361
    /* Look for the parameter name followed by an equal symbol */
362
0
    if (params[plen] == '=') {
363
0
      if (memcmp(params, px->lbprm.arg_str, plen) == 0) {
364
        /* OK, we have the parameter here at <params>, and
365
         * the value after the equal sign, at <p>
366
         * skip the equal symbol
367
         */
368
0
        p += plen + 1;
369
0
        start = end = p;
370
0
        len -= plen + 1;
371
372
0
        while (len && *end != '&') {
373
0
          if (unlikely(!HTTP_IS_TOKEN(*end))) {
374
            /* if in a POST, body must be URI encoded or it's not a URI.
375
             * Do not interpret any possible binary data as a parameter.
376
             */
377
0
            if (likely(HTTP_IS_LWS(*end))) /* eol, uncertain uri len */
378
0
              break;
379
0
            return NULL;                 /* oh, no; this is not uri-encoded.
380
                        * This body does not contain parameters.
381
                        */
382
0
          }
383
0
          len--;
384
0
          end++;
385
          /* should we break if vlen exceeds limit? */
386
0
        }
387
0
        hash = gen_hash(px, start, (end - start));
388
389
0
        if ((px->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
390
0
          return chash_get_server_hash(px, hash, avoid);
391
0
        else
392
0
          return map_get_server_hash(px, hash);
393
0
      }
394
0
    }
395
    /* skip to next parameter */
396
0
    p = memchr(params, '&', len);
397
0
    if (!p)
398
0
      return NULL;
399
0
    p++;
400
0
    len -= (p - params);
401
0
    params = p;
402
0
  }
403
0
  return NULL;
404
0
}
405
406
407
/*
408
 * This function tries to find a running server for the proxy <px> following
409
 * the Header parameter hash method. It looks for a specific parameter in the
410
 * URL and hashes it to compute the server ID. This is useful to optimize
411
 * performance by avoiding bounces between servers in contexts where sessions
412
 * are shared but cookies are not usable. If the parameter is not found, NULL
413
 * is returned. If any server is found, it will be returned. If no valid server
414
 * is found, NULL is returned. When lbprm.arg_opt1 is set, the hash will only
415
 * apply to the middle part of a domain name ("use_domain_only" option).
416
 */
417
struct server *get_server_hh(struct stream *s, const struct server *avoid)
418
0
{
419
0
  unsigned int hash = 0;
420
0
  struct proxy    *px   = s->be;
421
0
  unsigned int     plen = px->lbprm.arg_len;
422
0
  unsigned long    len;
423
0
  const char      *p;
424
0
  const char *start, *end;
425
0
  struct htx *htx = htxbuf(&s->req.buf);
426
0
  struct http_hdr_ctx ctx = { .blk = NULL };
427
428
  /* tot_weight appears to mean srv_count */
429
0
  if (px->lbprm.tot_weight == 0)
430
0
    return NULL;
431
432
  /* note: we won't hash if there's only one server left */
433
0
  if (px->lbprm.tot_used == 1)
434
0
    goto hash_done;
435
436
0
  http_find_header(htx, ist2(px->lbprm.arg_str, plen), &ctx, 0);
437
438
  /* if the header is not found or empty, let's fallback to round robin */
439
0
  if (!ctx.blk || !ctx.value.len)
440
0
    return NULL;
441
442
  /* Found a the param_name in the headers.
443
   * we will compute the hash based on this value ctx.val.
444
   */
445
0
  len = ctx.value.len;
446
0
  p   = ctx.value.ptr;
447
448
0
  if (!px->lbprm.arg_opt1) {
449
0
    hash = gen_hash(px, p, len);
450
0
  } else {
451
0
    int dohash = 0;
452
0
    p += len;
453
    /* special computation, use only main domain name, not tld/host
454
     * going back from the end of string, start hashing at first
455
     * dot stop at next.
456
     * This is designed to work with the 'Host' header, and requires
457
     * a special option to activate this.
458
     */
459
0
    end = p;
460
0
    while (len) {
461
0
      if (dohash) {
462
        /* Rewind the pointer until the previous char
463
         * is a dot, this will allow to set the start
464
         * position of the domain. */
465
0
        if (*(p - 1) == '.')
466
0
          break;
467
0
      }
468
0
      else if (*p == '.') {
469
        /* The pointer is rewound to the dot before the
470
         * tld, we memorize the end of the domain and
471
         * can enter the domain processing. */
472
0
        end = p;
473
0
        dohash = 1;
474
0
      }
475
0
      p--;
476
0
      len--;
477
0
    }
478
0
    start = p;
479
0
    hash = gen_hash(px, start, (end - start));
480
0
  }
481
482
0
 hash_done:
483
0
  if ((px->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
484
0
    return chash_get_server_hash(px, hash, avoid);
485
0
  else
486
0
    return map_get_server_hash(px, hash);
487
0
}
488
489
/* RDP Cookie HASH.  */
490
struct server *get_server_rch(struct stream *s, const struct server *avoid)
491
0
{
492
0
  unsigned int hash = 0;
493
0
  struct proxy    *px   = s->be;
494
0
  unsigned long    len;
495
0
  int              ret;
496
0
  struct sample    smp;
497
0
  int rewind;
498
499
  /* tot_weight appears to mean srv_count */
500
0
  if (px->lbprm.tot_weight == 0)
501
0
    return NULL;
502
503
0
  memset(&smp, 0, sizeof(smp));
504
505
0
  rewind = co_data(&s->req);
506
0
  c_rew(&s->req, rewind);
507
508
0
  ret = fetch_rdp_cookie_name(s, &smp, px->lbprm.arg_str, px->lbprm.arg_len);
509
0
  len = smp.data.u.str.data;
510
511
0
  c_adv(&s->req, rewind);
512
513
0
  if (ret == 0 || (smp.flags & SMP_F_MAY_CHANGE) || len == 0)
514
0
    return NULL;
515
516
  /* note: we won't hash if there's only one server left */
517
0
  if (px->lbprm.tot_used == 1)
518
0
    goto hash_done;
519
520
  /* Found the param_name in the headers.
521
   * we will compute the hash based on this value ctx.val.
522
   */
523
0
  hash = gen_hash(px, smp.data.u.str.area, len);
524
525
0
 hash_done:
526
0
  if ((px->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
527
0
    return chash_get_server_hash(px, hash, avoid);
528
0
  else
529
0
    return map_get_server_hash(px, hash);
530
0
}
531
532
/* sample expression HASH. Returns NULL if the sample is not found or if there
533
 * are no server, relying on the caller to fall back to round robin instead.
534
 */
535
struct server *get_server_expr(struct stream *s, const struct server *avoid)
536
0
{
537
0
  struct proxy  *px = s->be;
538
0
  struct sample *smp;
539
0
  unsigned int hash = 0;
540
541
0
  if (px->lbprm.tot_weight == 0)
542
0
    return NULL;
543
544
  /* note: no need to hash if there's only one server left */
545
0
  if (px->lbprm.tot_used == 1)
546
0
    goto hash_done;
547
548
  /* Note that if the hash-type doesn't hash the key, we must provide it
549
   * as a string representing a number as it will be parsed by read_int64().
550
   * Otherwise it's binary. The difference happens on samples returing
551
   * ints (e.g. rand()) as well as IP addresses, which, when turned to
552
   * binary, are just binary-encoded and cannot be parsed.
553
   */
554
0
  smp = sample_fetch_as_type(px, s->sess, s, SMP_OPT_DIR_REQ | SMP_OPT_FINAL, px->lbprm.expr,
555
0
           ((px->lbprm.algo & BE_LB_HASH_FUNC) == BE_LB_HFCN_NONE) ? SMP_T_STR : SMP_T_BIN);
556
0
  if (!smp)
557
0
    return NULL;
558
559
  /* We have the desired data. Let's hash it according to the configured
560
   * options and algorithm.
561
   */
562
0
  hash = gen_hash(px, smp->data.u.str.area, smp->data.u.str.data);
563
564
0
 hash_done:
565
0
  if ((px->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
566
0
    return chash_get_server_hash(px, hash, avoid);
567
0
  else
568
0
    return map_get_server_hash(px, hash);
569
0
}
570
571
/* random value  */
572
struct server *get_server_rnd(struct stream *s, const struct server *avoid)
573
0
{
574
0
  unsigned int hash = 0;
575
0
  struct proxy  *px = s->be;
576
0
  struct server *prev, *curr;
577
0
  int draws = px->lbprm.arg_opt1; // number of draws
578
579
  /* tot_weight appears to mean srv_count */
580
0
  if (px->lbprm.tot_weight == 0)
581
0
    return NULL;
582
583
0
  curr = NULL;
584
0
  do {
585
0
    prev = curr;
586
0
    hash = statistical_prng();
587
0
    curr = chash_get_server_hash(px, hash, avoid);
588
0
    if (!curr)
589
0
      break;
590
591
    /* compare the new server to the previous best choice and pick
592
     * the one with the least currently served requests.
593
     */
594
0
    if (prev && prev != curr) {
595
0
      uint64_t wcurr = (uint64_t)curr->served * prev->cur_eweight;
596
0
      uint64_t wprev = (uint64_t)prev->served * curr->cur_eweight;
597
598
0
      if (wcurr > wprev)
599
0
        curr = prev;
600
0
      else if (wcurr == wprev && curr->counters.shared.tg && prev->counters.shared.tg) {
601
        /* same load: pick the lowest weighted request rate */
602
0
        wcurr = read_freq_ctr_period_estimate(&curr->counters.shared.tg[tgid - 1]->sess_per_sec, MS_TO_TICKS(1000));
603
0
        wprev = read_freq_ctr_period_estimate(&prev->counters.shared.tg[tgid - 1]->sess_per_sec, MS_TO_TICKS(1000));
604
0
        if (wprev * curr->cur_eweight < wcurr * prev->cur_eweight)
605
0
          curr = prev;
606
0
      }
607
0
    }
608
0
  } while (--draws > 0);
609
610
  /* if the selected server is full, pretend we have none so that we reach
611
   * the backend's queue instead.
612
   */
613
0
  if (curr &&
614
0
      (curr->queueslength || (curr->maxconn && curr->served >= srv_dynamic_maxconn(curr))))
615
0
    curr = NULL;
616
617
0
  return curr;
618
0
}
619
620
/*
621
 * This function applies the load-balancing algorithm to the stream, as
622
 * defined by the backend it is assigned to. The stream is then marked as
623
 * 'assigned'.
624
 *
625
 * This function MAY NOT be called with SF_ASSIGNED already set. If the stream
626
 * had a server previously assigned, it is rebalanced, trying to avoid the same
627
 * server, which should still be present in target_srv(&s->target) before the call.
628
 * The function tries to keep the original connection slot if it reconnects to
629
 * the same server, otherwise it releases it and tries to offer it.
630
 *
631
 * It is illegal to call this function with a stream in a queue.
632
 *
633
 * It may return :
634
 *   SRV_STATUS_OK       if everything is OK. ->srv and ->target are assigned.
635
 *   SRV_STATUS_NOSRV    if no server is available. Stream is not ASSIGNED
636
 *   SRV_STATUS_FULL     if all servers are saturated. Stream is not ASSIGNED
637
 *   SRV_STATUS_INTERNAL for other unrecoverable errors.
638
 *
639
 * Upon successful return, the stream flag SF_ASSIGNED is set to indicate that
640
 * it does not need to be called anymore. This means that target_srv(&s->target)
641
 * can be trusted in balance and direct modes.
642
 *
643
 */
644
645
int assign_server(struct stream *s)
646
0
{
647
0
  struct connection *conn = NULL;
648
0
  struct server *conn_slot;
649
0
  struct server *srv = NULL, *prev_srv;
650
0
  int err;
651
652
0
  err = SRV_STATUS_INTERNAL;
653
0
  if (unlikely(s->pend_pos || s->flags & SF_ASSIGNED))
654
0
    goto out_err;
655
656
0
  prev_srv  = objt_server(s->target);
657
0
  conn_slot = s->srv_conn;
658
659
  /* We have to release any connection slot before applying any LB algo,
660
   * otherwise we may erroneously end up with no available slot.
661
   */
662
0
  if (conn_slot)
663
0
    sess_change_server(s, NULL);
664
665
  /* We will now try to find the good server and store it into <objt_server(s->target)>.
666
   * Note that <objt_server(s->target)> may be NULL in case of dispatch or proxy mode,
667
   * as well as if no server is available (check error code).
668
   */
669
670
0
  srv = NULL;
671
0
  stream_set_target(s, NULL);
672
673
0
  if ((s->be->lbprm.algo & BE_LB_KIND) != BE_LB_KIND_HI &&
674
0
      ((s->sess->flags & SESS_FL_PREFER_LAST) ||
675
0
       (s->be->options & PR_O_PREF_LAST))) {
676
0
    struct sess_priv_conns *pconns;
677
0
    list_for_each_entry(pconns, &s->sess->priv_conns, sess_el) {
678
0
      struct server *tmpsrv = objt_server(pconns->target);
679
680
0
      if (tmpsrv && tmpsrv->proxy == s->be &&
681
0
          ((s->sess->flags & SESS_FL_PREFER_LAST) ||
682
0
           (!s->be->max_ka_queue ||
683
0
            server_has_room(tmpsrv) || (
684
0
            tmpsrv->queueslength + 1 < s->be->max_ka_queue))) &&
685
0
          srv_currently_usable(tmpsrv)) {
686
0
        list_for_each_entry(conn, &pconns->conn_list, sess_el) {
687
0
          if (!(conn->flags & CO_FL_WAIT_XPRT)) {
688
0
            srv = tmpsrv;
689
0
            stream_set_srv_target(s, srv);
690
0
            goto out_ok;
691
0
          }
692
0
        }
693
0
      }
694
0
    }
695
0
  }
696
697
0
  if (s->be->lbprm.algo & BE_LB_KIND) {
698
    /* we must check if we have at least one server available */
699
0
    if (!s->be->lbprm.tot_weight) {
700
0
      err = SRV_STATUS_NOSRV;
701
0
      goto out;
702
0
    }
703
704
    /* if there's some queue on the backend, with certain algos we
705
     * know it's because all servers are full.
706
     */
707
0
    if (s->be->queueslength && s->be->served && s->be->queueslength != s->be->beconn &&
708
0
        (((s->be->lbprm.algo & (BE_LB_KIND|BE_LB_NEED|BE_LB_PARM)) == BE_LB_ALGO_FAS)||   // first
709
0
         ((s->be->lbprm.algo & (BE_LB_KIND|BE_LB_NEED|BE_LB_PARM)) == BE_LB_ALGO_RR) ||   // roundrobin
710
0
         ((s->be->lbprm.algo & (BE_LB_KIND|BE_LB_NEED|BE_LB_PARM)) == BE_LB_ALGO_SRR))) { // static-rr
711
0
      err = SRV_STATUS_FULL;
712
0
      goto out;
713
0
    }
714
715
    /* First check whether we need to fetch some data or simply call
716
     * the LB lookup function. Only the hashing functions will need
717
     * some input data in fact, and will support multiple algorithms.
718
     */
719
0
    switch (s->be->lbprm.algo & BE_LB_LKUP) {
720
0
    case BE_LB_LKUP_RRTREE:
721
0
      srv = fwrr_get_next_server(s->be, prev_srv);
722
0
      break;
723
724
0
    case BE_LB_LKUP_FSTREE:
725
0
      srv = fas_get_next_server(s->be, prev_srv);
726
0
      break;
727
728
0
    case BE_LB_LKUP_LCTREE:
729
0
      srv = fwlc_get_next_server(s->be, prev_srv);
730
0
      break;
731
732
0
    case BE_LB_LKUP_CHTREE:
733
0
    case BE_LB_LKUP_MAP:
734
0
      if ((s->be->lbprm.algo & BE_LB_KIND) == BE_LB_KIND_RR) {
735
        /* static-rr (map) or random (chash) */
736
0
        if ((s->be->lbprm.algo & BE_LB_PARM) == BE_LB_RR_RANDOM)
737
0
          srv = get_server_rnd(s, prev_srv);
738
0
        else
739
0
          srv = map_get_server_rr(s->be, prev_srv);
740
0
        break;
741
0
      }
742
0
      else if ((s->be->lbprm.algo & BE_LB_KIND) != BE_LB_KIND_HI) {
743
        /* unknown balancing algorithm */
744
0
        err = SRV_STATUS_INTERNAL;
745
0
        goto out;
746
0
      }
747
748
0
      switch (s->be->lbprm.algo & BE_LB_PARM) {
749
0
        const struct sockaddr_storage *src;
750
751
0
      case BE_LB_HASH_SRC:
752
0
        src = sc_src(s->scf);
753
0
        if (src && src->ss_family == AF_INET) {
754
0
          srv = get_server_sh(s->be,
755
0
                  (void *)&((struct sockaddr_in *)src)->sin_addr,
756
0
                  4, prev_srv);
757
0
        }
758
0
        else if (src && src->ss_family == AF_INET6) {
759
0
          srv = get_server_sh(s->be,
760
0
                  (void *)&((struct sockaddr_in6 *)src)->sin6_addr,
761
0
                  16, prev_srv);
762
0
        }
763
0
        break;
764
765
0
      case BE_LB_HASH_URI:
766
        /* URI hashing */
767
0
        if (IS_HTX_STRM(s) && s->txn.http->req.msg_state >= HTTP_MSG_BODY) {
768
0
          struct ist uri;
769
770
0
          uri = htx_sl_req_uri(http_get_stline(htxbuf(&s->req.buf)));
771
0
          if (s->be->lbprm.arg_opt1 & 2) {
772
0
            struct http_uri_parser parser =
773
0
              http_uri_parser_init(uri);
774
775
0
            uri = http_parse_path(&parser);
776
0
            if (!isttest(uri))
777
0
              uri = ist("");
778
0
          }
779
0
          srv = get_server_uh(s->be, uri.ptr, uri.len, prev_srv);
780
0
        }
781
0
        break;
782
783
0
      case BE_LB_HASH_PRM:
784
        /* URL Parameter hashing */
785
0
        if (IS_HTX_STRM(s) && s->txn.http->req.msg_state >= HTTP_MSG_BODY) {
786
0
          struct ist uri;
787
788
0
          uri = htx_sl_req_uri(http_get_stline(htxbuf(&s->req.buf)));
789
0
          srv = get_server_ph(s->be, uri.ptr, uri.len, prev_srv);
790
791
0
          if (!srv && s->txn.http->meth == HTTP_METH_POST)
792
0
            srv = get_server_ph_post(s, prev_srv);
793
0
        }
794
0
        break;
795
796
0
      case BE_LB_HASH_HDR:
797
        /* Header Parameter hashing */
798
0
        if (IS_HTX_STRM(s) && s->txn.http->req.msg_state >= HTTP_MSG_BODY)
799
0
          srv = get_server_hh(s, prev_srv);
800
0
        break;
801
802
0
      case BE_LB_HASH_RDP:
803
        /* RDP Cookie hashing */
804
0
        srv = get_server_rch(s, prev_srv);
805
0
        break;
806
807
0
      case BE_LB_HASH_SMP:
808
        /* sample expression hashing */
809
0
        srv = get_server_expr(s, prev_srv);
810
0
        break;
811
812
0
      default:
813
        /* unknown balancing algorithm */
814
0
        err = SRV_STATUS_INTERNAL;
815
0
        goto out;
816
0
      }
817
818
      /* If the hashing parameter was not found, let's fall
819
       * back to round robin on the map.
820
       */
821
0
      if (!srv) {
822
0
        if ((s->be->lbprm.algo & BE_LB_LKUP) == BE_LB_LKUP_CHTREE)
823
0
          srv = chash_get_next_server(s->be, prev_srv);
824
0
        else
825
0
          srv = map_get_server_rr(s->be, prev_srv);
826
0
      }
827
828
      /* end of map-based LB */
829
0
      break;
830
831
0
    default:
832
0
      if ((s->be->lbprm.algo & BE_LB_KIND) == BE_LB_KIND_SA) {
833
        /* some special algos that cannot be grouped together */
834
835
0
        if ((s->be->lbprm.algo & BE_LB_PARM) == BE_LB_SA_SS)
836
0
          srv = ss_get_server(s->be);
837
838
0
        break;
839
0
      }
840
      /* unknown balancing algorithm */
841
0
      err = SRV_STATUS_INTERNAL;
842
0
      goto out;
843
0
    }
844
845
0
    if (!srv) {
846
0
      err = SRV_STATUS_FULL;
847
0
      goto out;
848
0
    }
849
0
    else if (srv != prev_srv) {
850
0
      if (s->be_tgcounters)
851
0
        _HA_ATOMIC_INC(&s->be_tgcounters->cum_lbconn);
852
0
      if (srv->counters.shared.tg)
853
0
        _HA_ATOMIC_INC(&srv->counters.shared.tg[tgid - 1]->cum_lbconn);
854
0
    }
855
0
    stream_set_srv_target(s, srv);
856
0
  }
857
0
  else {
858
0
    err = SRV_STATUS_NOSRV;
859
0
    goto out;
860
0
  }
861
862
0
out_ok:
863
0
  s->flags |= SF_ASSIGNED;
864
0
  err = SRV_STATUS_OK;
865
0
 out:
866
867
  /* Either we take back our connection slot, or we offer it to someone
868
   * else if we don't need it anymore.
869
   */
870
0
  if (conn_slot) {
871
0
    if (conn_slot == srv) {
872
0
      sess_change_server(s, srv);
873
0
    } else {
874
0
      if (may_dequeue_tasks(conn_slot, s->be))
875
0
        process_srv_queue(conn_slot);
876
0
    }
877
0
  }
878
879
0
 out_err:
880
0
  return err;
881
0
}
882
883
/* Allocate <*ss> address unless already set. Address is then set to the
884
 * destination endpoint of <srv> server, or via <s> from a dispatch or
885
 * transparent address.
886
 *
887
 * Note that no address is allocated if server relies on reverse HTTP.
888
 *
889
 * Returns SRV_STATUS_OK on success, or if already already set. Else an error
890
 * code is returned and <*ss> is not allocated.
891
 */
892
static int alloc_dst_address(struct sockaddr_storage **ss,
893
                             struct server *srv, struct stream *s)
894
0
{
895
0
  const struct sockaddr_storage *dst;
896
897
0
  if (*ss)
898
0
    return SRV_STATUS_OK;
899
900
0
  if (srv && (srv->flags & SRV_F_RHTTP)) {
901
    /* For reverse HTTP, destination address is unknown. */
902
0
    return SRV_STATUS_OK;
903
0
  }
904
905
0
  if ((s->flags & SF_DIRECT) || (s->be->lbprm.algo & BE_LB_KIND)) {
906
    /* A server is necessarily known for this stream */
907
0
    if (!(s->flags & SF_ASSIGNED))
908
0
      return SRV_STATUS_INTERNAL;
909
910
0
    if (!sockaddr_alloc(ss, NULL, 0))
911
0
      return SRV_STATUS_INTERNAL;
912
913
0
    ASSUME_NONNULL(srv); /* srv is guaranteed by SF_ASSIGNED */
914
915
0
    **ss = srv->addr;
916
0
    set_host_port(*ss, srv->svc_port);
917
0
    if (!is_addr(*ss)) {
918
      /* if the server has no address, we use the same address
919
       * the client asked, which is handy for remapping ports
920
       * locally on multiple addresses at once. Nothing is done
921
       * for AF_UNIX addresses.
922
       */
923
0
      dst = sc_dst(s->scf);
924
0
      if (dst && dst->ss_family == AF_INET) {
925
0
        ((struct sockaddr_in *)*ss)->sin_family = AF_INET;
926
0
        ((struct sockaddr_in *)*ss)->sin_addr =
927
0
          ((struct sockaddr_in *)dst)->sin_addr;
928
0
      } else if (dst && dst->ss_family == AF_INET6) {
929
0
        ((struct sockaddr_in6 *)*ss)->sin6_family = AF_INET6;
930
0
        ((struct sockaddr_in6 *)*ss)->sin6_addr =
931
0
          ((struct sockaddr_in6 *)dst)->sin6_addr;
932
0
      }
933
0
    }
934
935
    /* if this server remaps proxied ports, we'll use
936
     * the port the client connected to with an offset. */
937
0
    if ((srv->flags & SRV_F_MAPPORTS)) {
938
0
      int base_port;
939
940
0
      dst = sc_dst(s->scf);
941
0
      if (dst) {
942
        /* First, retrieve the port from the incoming connection */
943
0
        base_port = get_host_port(dst);
944
945
        /* Second, assign the outgoing connection's port */
946
0
        base_port += get_host_port(*ss);
947
0
        set_host_port(*ss, base_port);
948
0
      }
949
0
    }
950
0
  }
951
0
  else {
952
    /* no server and no LB algorithm ! */
953
0
    return SRV_STATUS_INTERNAL;
954
0
  }
955
956
0
  return SRV_STATUS_OK;
957
0
}
958
959
/* This function assigns a server to stream <s> if required, and can add the
960
 * connection to either the assigned server's queue or to the proxy's queue.
961
 * If ->srv_conn is set, the stream is first released from the server.
962
 * It may also be called with SF_DIRECT and/or SF_ASSIGNED though. It will
963
 * be called before any connection and after any retry or redispatch occurs.
964
 *
965
 * It is not allowed to call this function with a stream in a queue.
966
 *
967
 * Returns :
968
 *
969
 *   SRV_STATUS_OK       if everything is OK.
970
 *   SRV_STATUS_NOSRV    if no server is available. objt_server(s->target) = NULL.
971
 *   SRV_STATUS_QUEUED   if the connection has been queued.
972
 *   SRV_STATUS_FULL     if the server(s) is/are saturated and the
973
 *                       connection could not be queued at the server's,
974
 *                       which may be NULL if we queue on the backend.
975
 *   SRV_STATUS_INTERNAL for other unrecoverable errors.
976
 *
977
 */
978
int assign_server_and_queue(struct stream *s)
979
0
{
980
0
  struct pendconn *p;
981
0
  struct server *srv;
982
0
  int err;
983
984
0
  if (s->pend_pos)
985
0
    return SRV_STATUS_INTERNAL;
986
987
0
  err = SRV_STATUS_OK;
988
0
  if (!(s->flags & SF_ASSIGNED)) {
989
0
    struct server *prev_srv = objt_server(s->target);
990
991
0
    err = assign_server(s);
992
0
    if (prev_srv) {
993
      /* This stream was previously assigned to a server. We have to
994
       * update the stream's and the server's stats :
995
       *  - if the server changed :
996
       *    - set TX_CK_DOWN if txn.flags was TX_CK_VALID
997
       *    - set SF_REDISP if it was successfully redispatched
998
       *    - increment srv->redispatches and be->redispatches
999
       *  - if the server remained the same : update retries.
1000
       */
1001
1002
0
      if (prev_srv != objt_server(s->target)) {
1003
0
        if (s->txn.http && (s->txn.http->flags & TX_CK_MASK) == TX_CK_VALID) {
1004
0
          s->txn.http->flags &= ~TX_CK_MASK;
1005
0
          s->txn.http->flags |= TX_CK_DOWN;
1006
0
        }
1007
0
        s->flags |= SF_REDISP;
1008
0
        if (prev_srv->counters.shared.tg)
1009
0
          _HA_ATOMIC_INC(&prev_srv->counters.shared.tg[tgid - 1]->redispatches);
1010
0
        if (s->be_tgcounters)
1011
0
          _HA_ATOMIC_INC(&s->be_tgcounters->redispatches);
1012
0
      } else {
1013
0
        if (prev_srv->counters.shared.tg)
1014
0
          _HA_ATOMIC_INC(&prev_srv->counters.shared.tg[tgid - 1]->retries);
1015
0
        if (s->be_tgcounters)
1016
0
          _HA_ATOMIC_INC(&s->be_tgcounters->retries);
1017
0
      }
1018
0
    }
1019
0
  }
1020
1021
0
  switch (err) {
1022
0
  case SRV_STATUS_OK:
1023
    /* we have SF_ASSIGNED set */
1024
0
    srv = objt_server(s->target);
1025
0
    if (!srv)
1026
0
      return SRV_STATUS_OK;   /* dispatch or proxy mode */
1027
1028
    /* If we already have a connection slot, no need to check any queue */
1029
0
    if (s->srv_conn == srv)
1030
0
      return SRV_STATUS_OK;
1031
1032
    /* OK, this stream already has an assigned server, but no
1033
     * connection slot yet. Either it is a redispatch, or it was
1034
     * assigned from persistence information (direct mode).
1035
     */
1036
0
    if ((s->flags & SF_REDIRECTABLE) && srv->rdr_len) {
1037
      /* server scheduled for redirection, and already assigned. We
1038
       * don't want to go further nor check the queue.
1039
       */
1040
0
      sess_change_server(s, srv); /* not really needed in fact */
1041
0
      return SRV_STATUS_OK;
1042
0
    }
1043
1044
    /* We might have to queue this stream if the assigned server is full.
1045
     * We know we have to queue it into the server's queue, so if a maxqueue
1046
     * is set on the server, we must also check that the server's queue is
1047
     * not full, in which case we have to return FULL.
1048
     */
1049
0
    if (srv->maxconn) {
1050
0
      struct queue *queue = &srv->per_tgrp[tgid - 1].queue;
1051
0
      int served;
1052
0
      int got_it = 0;
1053
1054
      /*
1055
       * Make sure that there's still a slot on the server.
1056
       * Try to increment its served, while making sure
1057
       * it is < maxconn.
1058
       */
1059
0
      if (!queue->length &&
1060
0
          (served = srv->served) < srv_dynamic_maxconn(srv)) {
1061
        /*
1062
         * Attempt to increment served, while
1063
         * making sure it is always below maxconn
1064
         */
1065
1066
0
        do {
1067
0
          got_it = _HA_ATOMIC_CAS(&srv->served,
1068
0
                      &served, served + 1);
1069
0
        } while (!got_it && served < srv_dynamic_maxconn(srv) &&
1070
0
           __ha_cpu_relax());
1071
0
      }
1072
0
      if (!got_it) {
1073
0
        if (srv->maxqueue > 0 && srv->queueslength >= srv->maxqueue)
1074
0
          return SRV_STATUS_FULL;
1075
1076
0
        p = pendconn_add(s);
1077
0
        if (p) {
1078
          /* There's a TOCTOU here: it may happen that between the
1079
           * moment we decided to queue the request and the moment
1080
           * it was done, the last active request on the server
1081
           * ended and no new one will be able to dequeue that one.
1082
           * Since we already have our server we don't care, this
1083
           * will be handled by the caller which will check for
1084
           * this condition and will immediately dequeue it if
1085
           * possible.
1086
           */
1087
0
          return SRV_STATUS_QUEUED;
1088
0
        }
1089
0
        else
1090
0
          return SRV_STATUS_INTERNAL;
1091
0
      }
1092
0
    } else
1093
0
      _HA_ATOMIC_INC(&srv->served);
1094
1095
    /* OK, we can use this server. Let's reserve our place */
1096
0
    sess_change_server(s, srv);
1097
0
    return SRV_STATUS_OK;
1098
1099
0
  case SRV_STATUS_FULL:
1100
    /* queue this stream into the proxy's queue */
1101
0
    p = pendconn_add(s);
1102
0
    if (p) {
1103
      /* There's a TOCTOU here: it may happen that between the
1104
       * moment we decided to queue the request and the moment
1105
       * it was done, the last active request in the backend
1106
       * ended and no new one will be able to dequeue that one.
1107
       * This is more visible with maxconn 1 where it can
1108
       * happen 1/1000 times, though the vast majority are
1109
       * correctly recovered from.
1110
       * To work around that, when a server is getting idle,
1111
       * it will set the ready_srv field of the proxy.
1112
       * Here, if ready_srv is non-NULL, we get that server,
1113
       * and we attempt to increment its served counter up to
1114
       * maxconn. If it works, then we can just run, otherwise,
1115
       * it means another stream will be running, and will
1116
       * dequeue us eventually, so we can just do nothing.
1117
       */
1118
0
      if (unlikely(s->be->ready_srv != NULL)) {
1119
0
        struct server *newserv;
1120
1121
0
        newserv = HA_ATOMIC_XCHG(&s->be->ready_srv, NULL);
1122
0
        if (newserv != NULL) {
1123
0
          int got_slot = 0;
1124
1125
0
          while (_HA_ATOMIC_LOAD(&newserv->served) == 0) {
1126
0
            int served = 0;
1127
1128
0
            if (_HA_ATOMIC_CAS(&newserv->served, &served, 1)) {
1129
0
              got_slot = 1;
1130
0
              break;
1131
0
            }
1132
0
          }
1133
0
          if (!got_slot) {
1134
            /*
1135
             * Somebody else can now
1136
             * wake up us, stop now.
1137
             */
1138
0
            return SRV_STATUS_QUEUED;
1139
0
          }
1140
1141
0
          HA_SPIN_LOCK(QUEUE_LOCK, &p->queue->lock);
1142
0
          if (!p->node.node.leaf_p) {
1143
0
            HA_SPIN_UNLOCK(QUEUE_LOCK, &p->queue->lock);
1144
            /*
1145
             * Okay we've been queued and
1146
             * unqueued already, just leave
1147
             */
1148
0
            _HA_ATOMIC_DEC(&newserv->served);
1149
0
            return SRV_STATUS_QUEUED;
1150
0
          }
1151
0
          eb32_delete(&p->node);
1152
0
          HA_SPIN_UNLOCK(QUEUE_LOCK, &p->queue->lock);
1153
1154
0
          _HA_ATOMIC_DEC(&p->queue->length);
1155
1156
0
          if (p->queue->sv)
1157
0
            _HA_ATOMIC_DEC(&p->queue->sv->queueslength);
1158
0
          else
1159
0
            _HA_ATOMIC_DEC(&p->queue->px->queueslength);
1160
1161
0
          _HA_ATOMIC_INC(&p->queue->idx);
1162
0
          _HA_ATOMIC_DEC(&s->be->totpend);
1163
1164
0
          pool_free(pool_head_pendconn, p);
1165
1166
0
          s->flags |= SF_ASSIGNED;
1167
0
          stream_set_srv_target(s, newserv);
1168
1169
0
          s->pend_pos = NULL;
1170
0
          sess_change_server(s, newserv);
1171
0
          return SRV_STATUS_OK;
1172
0
        }
1173
0
      }
1174
1175
0
      return SRV_STATUS_QUEUED;
1176
0
    }
1177
0
    else
1178
0
      return SRV_STATUS_INTERNAL;
1179
1180
0
  case SRV_STATUS_NOSRV:
1181
0
    return err;
1182
1183
0
  case SRV_STATUS_INTERNAL:
1184
0
    return err;
1185
1186
0
  default:
1187
0
    return SRV_STATUS_INTERNAL;
1188
0
  }
1189
0
}
1190
1191
/* Allocate an address if an explicit source address must be used for a backend
1192
 * connection.
1193
 *
1194
 * Two parameters are taken into account to check if specific source address is
1195
 * configured. The first one is <srv> which is the server instance to connect
1196
 * to. It may be NULL when dispatching is used. The second one <be> is the
1197
 * backend instance which contains the target server or dispatch.
1198
 *
1199
 * A stream instance <s> can be used to set the stream owner of the backend
1200
 * connection. It is a required parameter if the source address is a dynamic
1201
 * parameter.
1202
 *
1203
 * Returns SRV_STATUS_OK if either no specific source address specified or its
1204
 * allocation is done correctly. On error returns SRV_STATUS_INTERNAL.
1205
 */
1206
int alloc_bind_address(struct sockaddr_storage **ss,
1207
                       struct server *srv, struct proxy *be,
1208
                       struct stream *s)
1209
0
{
1210
0
#if defined(CONFIG_HAP_TRANSPARENT)
1211
0
  const struct sockaddr_storage *addr;
1212
0
  struct conn_src *src = NULL;
1213
0
  struct sockaddr_in *sin;
1214
0
  char *vptr;
1215
0
  size_t vlen;
1216
0
#endif
1217
1218
  /* Ensure the function will not overwrite an allocated address. */
1219
0
  BUG_ON(*ss);
1220
1221
0
#if defined(CONFIG_HAP_TRANSPARENT)
1222
0
  if (srv && srv->conn_src.opts & CO_SRC_BIND)
1223
0
    src = &srv->conn_src;
1224
0
  else if (be->conn_src.opts & CO_SRC_BIND)
1225
0
    src = &be->conn_src;
1226
1227
  /* no transparent mode, no need to allocate an address, returns OK */
1228
0
  if (!src)
1229
0
    return SRV_STATUS_OK;
1230
1231
0
  switch (src->opts & CO_SRC_TPROXY_MASK) {
1232
0
  case CO_SRC_TPROXY_ADDR:
1233
0
    if (!sockaddr_alloc(ss, NULL, 0))
1234
0
      return SRV_STATUS_INTERNAL;
1235
1236
0
    **ss = src->tproxy_addr;
1237
0
    break;
1238
1239
0
  case CO_SRC_TPROXY_CLI:
1240
0
  case CO_SRC_TPROXY_CIP:
1241
0
    BUG_ON(!s); /* Dynamic source setting requires a stream instance. */
1242
1243
    /* FIXME: what can we do if the client connects in IPv6 or unix socket ? */
1244
0
    addr = sc_src(s->scf);
1245
0
    if (!addr)
1246
0
      return SRV_STATUS_INTERNAL;
1247
1248
0
    if (!sockaddr_alloc(ss, NULL, 0))
1249
0
      return SRV_STATUS_INTERNAL;
1250
1251
0
    **ss = *addr;
1252
0
    if ((src->opts & CO_SRC_TPROXY_MASK) == CO_SRC_TPROXY_CIP) {
1253
      /* always set port to zero when using "clientip", or
1254
       * the idle connection hash will include the port part.
1255
       */
1256
0
      if (addr->ss_family == AF_INET)
1257
0
        ((struct sockaddr_in *)*ss)->sin_port = 0;
1258
0
      else if (addr->ss_family == AF_INET6)
1259
0
        ((struct sockaddr_in6 *)*ss)->sin6_port = 0;
1260
0
    }
1261
0
    break;
1262
1263
0
  case CO_SRC_TPROXY_DYN:
1264
0
    BUG_ON(!s); /* Dynamic source setting requires a stream instance. */
1265
1266
0
    if (!src->bind_hdr_occ || !IS_HTX_STRM(s))
1267
0
      return SRV_STATUS_INTERNAL;
1268
1269
0
    if (!sockaddr_alloc(ss, NULL, 0))
1270
0
      return SRV_STATUS_INTERNAL;
1271
1272
    /* bind to the IP in a header */
1273
0
    sin = (struct sockaddr_in *)*ss;
1274
0
    sin->sin_family = AF_INET;
1275
0
    sin->sin_port = 0;
1276
0
    sin->sin_addr.s_addr = 0;
1277
0
    if (!http_get_htx_hdr(htxbuf(&s->req.buf),
1278
0
                          ist2(src->bind_hdr_name, src->bind_hdr_len),
1279
0
                          src->bind_hdr_occ, NULL, &vptr, &vlen)) {
1280
0
      sockaddr_free(ss);
1281
0
      return SRV_STATUS_INTERNAL;
1282
0
    }
1283
1284
0
    sin->sin_addr.s_addr = htonl(inetaddr_host_lim(vptr, vptr + vlen));
1285
0
    break;
1286
1287
0
  default:
1288
0
    ;
1289
0
  }
1290
0
#endif
1291
1292
0
  return SRV_STATUS_OK;
1293
0
}
1294
1295
/* Attempt to retrieve a connection matching <hash> from <srv> server lists for
1296
 * connection reuse. If <is_safe> is true, only connections considered safe for
1297
 * reuse are inspected. Thread-local list is inspected first. If no matching
1298
 * connection is found, takeover may be performed to steal a connection from a
1299
 * foreign thread.
1300
 *
1301
 * If <reuse_mode> backend policy is safe and connection MUX is subject to
1302
 * head-of-line blocking, connection is attached to <sess> session, which
1303
 * prevents mixing several frontend client over it.
1304
 *
1305
 * Returns the connection instance if found.
1306
 */
1307
struct connection *conn_backend_get(int reuse_mode,
1308
                                    struct server *srv, struct session *sess,
1309
                                    int is_safe, int64_t hash)
1310
0
{
1311
0
  const struct tgroup_info *curtg = tg;
1312
0
  struct connection *conn = NULL;
1313
0
  unsigned int curtgid = tgid;
1314
0
  int i; // thread number
1315
0
  int found = 0;
1316
0
  int stop;
1317
1318
  /* We need to lock even if this is our own list, because another
1319
   * thread may be trying to migrate that connection, and we don't want
1320
   * to end up with two threads using the same connection.
1321
   */
1322
0
  i = tid;
1323
0
  HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
1324
0
  conn = srv_lookup_conn(is_safe ? &srv->per_thr[tid].safe_conns : &srv->per_thr[tid].idle_conns, hash);
1325
0
  if (conn)
1326
0
    conn_delete_from_tree(conn, tid);
1327
1328
  /* If we failed to pick a connection from the idle list, let's try again with
1329
   * the safe list.
1330
   */
1331
0
  if (!conn && !is_safe && srv->curr_safe_nb > 0) {
1332
0
    conn = srv_lookup_conn(&srv->per_thr[tid].safe_conns, hash);
1333
0
    if (conn) {
1334
0
      conn_delete_from_tree(conn, tid);
1335
0
      is_safe = 1;
1336
0
    }
1337
0
  }
1338
0
  HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
1339
1340
  /* If we found a connection in our own list, and we don't have to
1341
   * steal one from another thread, then we're done.
1342
   */
1343
0
  if (conn)
1344
0
    goto done;
1345
1346
  /* pool sharing globally disabled ? */
1347
0
  if (!(global.tune.options & GTUNE_IDLE_POOL_SHARED))
1348
0
    goto done;
1349
1350
  /* Are we allowed to pick from another thread ? We'll still try
1351
   * it if we're running low on FDs as we don't want to create
1352
   * extra conns in this case, otherwise we can give up if we have
1353
   * too few idle conns and the server protocol supports establishing
1354
   * connections (i.e. not a reverse-http server for example).
1355
   */
1356
0
  if (srv->curr_idle_conns < srv->low_idle_conns &&
1357
0
      ha_used_fds < global.tune.pool_low_count) {
1358
0
    const struct protocol *srv_proto = protocol_lookup(srv->addr.ss_family, PROTO_TYPE_STREAM, 0);
1359
1360
0
    if (srv_proto && srv_proto->connect)
1361
0
      goto done;
1362
0
  }
1363
1364
  /* Lookup all other threads for an idle connection, starting from last
1365
   * unvisited thread, but always staying in the same group.
1366
   */
1367
0
  stop = srv->per_tgrp[tgid - 1].next_takeover;
1368
0
  if (stop >= curtg->count)
1369
0
    stop %= curtg->count;
1370
0
  stop += curtg->base;
1371
0
check_tgid:
1372
0
  i = stop;
1373
0
  do {
1374
    /* safe requests looked up conns in idle tree first, then safe
1375
     * tree; unsafe requests are looked up in the safe conns tree.
1376
     */
1377
0
    int search_tree = is_safe ? 1 : 0; // 0 = idle, 1 = safe
1378
0
    struct ceb_root **tree;
1379
1380
0
    if (!srv->curr_idle_thr[i] || i == tid)
1381
0
      continue;
1382
1383
0
    if (HA_SPIN_TRYLOCK(IDLE_CONNS_LOCK, &idle_conns[i].idle_conns_lock) != 0)
1384
0
      continue;
1385
1386
0
    do {
1387
0
      if ((search_tree && !srv->curr_safe_nb) ||
1388
0
          (!search_tree && !srv->curr_idle_nb))
1389
0
        continue;
1390
1391
0
      tree = search_tree ? &srv->per_thr[i].safe_conns : &srv->per_thr[i].idle_conns;
1392
0
      conn = srv_lookup_conn(tree, hash);
1393
0
      while (conn) {
1394
0
        if (conn->mux->takeover && CALL_MUX_WITH_RET(conn->mux, takeover(conn, i, 0)) == 0) {
1395
0
          conn_delete_from_tree(conn, i);
1396
0
          _HA_ATOMIC_INC(&activity[tid].fd_takeover);
1397
0
          found = 1;
1398
0
          break;
1399
0
        }
1400
0
        conn = srv_lookup_conn_next(tree, conn);
1401
0
      }
1402
0
    } while (!found && ++search_tree <= 1);
1403
1404
0
    HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[i].idle_conns_lock);
1405
0
  } while (!found && (i = (i + 1 == curtg->base + curtg->count) ? curtg->base : i + 1) != stop);
1406
1407
0
  if (!found && (global.tune.tg_takeover == FULL_THREADGROUP_TAKEOVER ||
1408
0
      (global.tune.tg_takeover == RESTRICTED_THREADGROUP_TAKEOVER &&
1409
0
      srv->flags & (SRV_F_RHTTP | SRV_F_STRICT_MAXCONN))) &&
1410
0
      !(global.tune.options & GTUNE_NO_TG_FD_SHARING)) {
1411
0
    curtgid = curtgid + 1;
1412
0
    if (curtgid == global.nbtgroups + 1)
1413
0
      curtgid = 1;
1414
    /* If we haven't looped yet */
1415
0
    if (MAX_TGROUPS > 1 && curtgid != tgid) {
1416
0
      curtg = &ha_tgroup_info[curtgid - 1];
1417
0
      stop = curtg->base;
1418
0
      goto check_tgid;
1419
0
    }
1420
0
  }
1421
0
  if (!found)
1422
0
    conn = NULL;
1423
0
 done:
1424
0
  if (conn) {
1425
0
    _HA_ATOMIC_STORE(&srv->per_tgrp[tgid - 1].next_takeover, (i + 1 == tg->base + tg->count) ? tg->base : i + 1);
1426
1427
0
    srv_use_conn(srv, conn);
1428
1429
0
    _HA_ATOMIC_DEC(&srv->curr_idle_conns);
1430
0
    _HA_ATOMIC_DEC(conn->flags & CO_FL_SAFE_LIST ? &srv->curr_safe_nb : &srv->curr_idle_nb);
1431
0
    _HA_ATOMIC_DEC(&srv->curr_idle_thr[i]);
1432
0
    conn->flags &= ~CO_FL_LIST_MASK;
1433
0
    __ha_barrier_atomic_store();
1434
1435
0
    if (reuse_mode == PR_O_REUSE_SAFE && conn->mux->flags & MX_FL_HOL_RISK) {
1436
      /* attach the connection to the session private list */
1437
0
      session_add_conn(sess, conn);
1438
0
    }
1439
0
    else {
1440
0
      srv_add_to_avail_list(srv, conn);
1441
0
    }
1442
0
  }
1443
1444
0
  return conn;
1445
0
}
1446
1447
static int do_connect_server(struct stream *s, struct connection *conn)
1448
0
{
1449
0
  int ret = SF_ERR_NONE;
1450
0
  int conn_flags = 0;
1451
1452
0
  if (unlikely(!conn || !conn->ctrl || !conn->ctrl->connect))
1453
0
    return SF_ERR_INTERNAL;
1454
1455
0
  if (co_data(&s->req))
1456
0
    conn_flags |= CONNECT_HAS_DATA;
1457
0
  if (s->conn_retries == 0)
1458
0
    conn_flags |= CONNECT_CAN_USE_TFO;
1459
0
  if (!conn_ctrl_ready(conn) || !conn_xprt_ready(conn)) {
1460
0
    ret = conn->ctrl->connect(conn, conn_flags);
1461
0
    if (ret != SF_ERR_NONE)
1462
0
      return ret;
1463
1464
    /* we're in the process of establishing a connection */
1465
0
    s->scb->state = SC_ST_CON;
1466
0
  }
1467
0
  else {
1468
    /* try to reuse the existing connection, it will be
1469
     * confirmed once we can send on it.
1470
     */
1471
    /* Is the connection really ready ? */
1472
0
    if (conn->mux->ctl(conn, MUX_CTL_STATUS, NULL) & MUX_STATUS_READY)
1473
0
      s->scb->state = SC_ST_RDY;
1474
0
    else
1475
0
      s->scb->state = SC_ST_CON;
1476
0
  }
1477
1478
  /* needs src ip/port for logging */
1479
0
  if (s->flags & SF_SRC_ADDR)
1480
0
    conn_get_src(conn);
1481
1482
0
  return ret;
1483
0
}
1484
1485
/*
1486
 * Returns the first connection from a tree we managed to take over,
1487
 * if any.
1488
 */
1489
static struct connection *
1490
takeover_random_idle_conn(struct ceb_root **root, int curtid)
1491
0
{
1492
0
  struct connection *conn = NULL;
1493
1494
0
  conn = ceb64_item_first(root, hash_node.node, hash_node.key, struct connection);
1495
0
  while (conn) {
1496
0
    if (conn->mux->takeover && CALL_MUX_WITH_RET(conn->mux, takeover(conn, curtid, 1)) == 0) {
1497
0
      conn_delete_from_tree(conn, curtid);
1498
0
      return conn;
1499
0
    }
1500
0
    conn = ceb64_item_next(root, hash_node.node, hash_node.key, conn);
1501
0
  }
1502
1503
0
  return NULL;
1504
0
}
1505
1506
/*
1507
 * Kills an idle connection, any idle connection we can get a hold on.
1508
 * The goal is just to free a connection in case we reached the max and
1509
 * have to establish a new one.
1510
 * Returns -1 if there is no idle connection to kill, 0 if there are some
1511
 * available but we failed to get one, and 1 if we successfully killed one.
1512
 */
1513
static int
1514
kill_random_idle_conn(struct server *srv)
1515
0
{
1516
0
  struct connection *conn = NULL;
1517
0
  uint base = 0, count = global.nbthread, start = tid;
1518
0
  int i;
1519
0
  int curtid;
1520
  /* No idle conn, then there is nothing we can do at this point */
1521
1522
0
  if (srv->curr_idle_conns == 0)
1523
0
    return -1;
1524
1525
  /*
1526
   *  with per-thread-group fd tables, a connection cannot be taken over
1527
   * from a thread of another group, as its fd is only valid in the
1528
   * owner group's table, so only consider our own group's threads.
1529
   */
1530
0
  if (global.tune.options & GTUNE_NO_TG_FD_SHARING) {
1531
0
    base = tg->base;
1532
0
    count = tg->count;
1533
0
    start = ti->ltid;
1534
0
  }
1535
0
  for (i = 0; i < count; i++) {
1536
0
    curtid = base + (start + i) % count;
1537
1538
0
    if (HA_SPIN_TRYLOCK(IDLE_CONNS_LOCK, &idle_conns[curtid].idle_conns_lock) != 0)
1539
0
      continue;
1540
0
    conn = takeover_random_idle_conn(&srv->per_thr[curtid].idle_conns, curtid);
1541
0
    if (!conn)
1542
0
      conn = takeover_random_idle_conn(&srv->per_thr[curtid].safe_conns, curtid);
1543
0
    HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[curtid].idle_conns_lock);
1544
0
    if (conn)
1545
0
      break;
1546
0
  }
1547
0
  if (conn) {
1548
    /*
1549
     * We have to manually decrement counters, as srv_release_conn()
1550
     * will attempt to access the current tid's counters, while
1551
     * we may have taken the connection from a different thread.
1552
     */
1553
0
    if (conn->flags & CO_FL_LIST_MASK) {
1554
0
      _HA_ATOMIC_DEC(&srv->curr_idle_conns);
1555
0
      _HA_ATOMIC_DEC(conn->flags & CO_FL_SAFE_LIST ? &srv->curr_safe_nb : &srv->curr_idle_nb);
1556
0
      _HA_ATOMIC_DEC(&srv->curr_idle_thr[curtid]);
1557
0
      conn->flags &= ~CO_FL_LIST_MASK;
1558
      /*
1559
       * If we have no list flag then srv_release_conn()
1560
       * will consider the connection is used, so let's
1561
       * pretend it is.
1562
       */
1563
0
      _HA_ATOMIC_INC(&srv->curr_used_conns);
1564
0
    }
1565
0
    CALL_MUX_NO_RET(conn->mux, destroy(conn->ctx));
1566
0
    return 1;
1567
0
  }
1568
0
  return 0;
1569
0
}
1570
1571
/* Returns backend reuse policy depending on <be>. It can be forced to always
1572
 * mode if <srv> is not NULL and uses reverse HTTP.
1573
 */
1574
int be_reuse_mode(const struct proxy *be, const struct server *srv)
1575
0
{
1576
0
  if (srv && srv->flags & SRV_F_RHTTP) {
1577
    /* Override reuse-mode if reverse-connect is used. */
1578
0
    return PR_O_REUSE_ALWS;
1579
0
  }
1580
1581
0
  return be->options & PR_O_REUSE_MASK;
1582
0
}
1583
1584
/* Calculate hash to select a matching connection for reuse. Here is the list
1585
 * of input parameters :
1586
 * - <srv> is the server instance. Can be NULL on dispatch/transparent proxy.
1587
 * - <strm> is the stream instance. Can be NULL if no stream is used.
1588
 * - <src> is the bind address if an explicit source address is used.
1589
 * - <dst> is the destination address. Must be set in every cases, except on
1590
 *   reverse HTTP.
1591
 * - <name> is a string identifier associated to the connection. Set by
1592
 *   pool-conn-name, also used for SSL SNI matching.
1593
 *
1594
 * Note that all input parameters can be NULL. The only requirement is that
1595
 * it's not possible to have both <srv> and <strm> NULL at the same time.
1596
 *
1597
 * Returns the calculated hash.
1598
 */
1599
int64_t be_calculate_conn_hash(struct server *srv, struct stream *strm,
1600
                               struct session *sess,
1601
                               struct sockaddr_storage *src,
1602
                               struct sockaddr_storage *dst,
1603
                               struct ist name)
1604
0
{
1605
0
  struct conn_hash_params hash_params;
1606
1607
  /* Caller cannot set both <srv> and <strm> to NULL. */
1608
0
  BUG_ON_HOT(!srv && !strm);
1609
1610
  /* first, set unique connection parameters and then calculate hash */
1611
0
  memset(&hash_params, 0, sizeof(hash_params));
1612
1613
  /* 1. target */
1614
0
  hash_params.target = srv ? &srv->obj_type : strm->target;
1615
1616
  /* 2. pool-conn-name */
1617
0
  if (istlen(name)) {
1618
0
    hash_params.name_prehash =
1619
0
      conn_hash_prehash(istptr(name), istlen(name));
1620
0
  }
1621
1622
  /* 3. destination address */
1623
0
  hash_params.dst_addr = dst;
1624
1625
  /* 4. source address */
1626
0
  hash_params.src_addr = src;
1627
1628
  /* 5. proxy protocol */
1629
0
  if (strm && srv && srv->pp_opts & SRV_PP_ENABLED) {
1630
0
    struct connection *cli_conn = objt_conn(strm_orig(strm));
1631
0
    int proxy_line_ret = make_proxy_line(trash.area, trash.size,
1632
0
                                         srv, cli_conn, strm, sess);
1633
0
    if (proxy_line_ret) {
1634
0
      hash_params.proxy_prehash =
1635
0
        conn_hash_prehash(trash.area, proxy_line_ret);
1636
0
    }
1637
0
  }
1638
1639
  /* 6. Custom mark, tos? */
1640
0
  if (strm && (strm->flags & (SF_BC_MARK | SF_BC_TOS))) {
1641
    /* mark: 32bits, tos: 8bits = 40bits
1642
     * last 2 bits are there to indicate if mark and/or tos are set
1643
     * total: 42bits:
1644
     *
1645
     * 63==== (unused) ====42    39----32 31-----------------------------0
1646
     * 0000000000000000000000 11 00000111 00000000000000000000000000000011
1647
     *                        ^^ ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1648
     *                        ||    |                     |
1649
     *                       /  \    \                     \
1650
     *                      /    \    \                     \
1651
     *                    tos?   mark? \             mark value (32bits)
1652
     *                            tos value (8bits)
1653
     * ie: in the above example:
1654
     *  - mark is set, mark = 3
1655
     *  - tos is set, tos = 7
1656
     */
1657
0
    if (strm->flags & SF_BC_MARK) {
1658
0
      hash_params.mark_tos_prehash |= strm->bc_mark;
1659
      /* 41th bit: mark set */
1660
0
      hash_params.mark_tos_prehash |= 1ULL << 40;
1661
0
    }
1662
0
    if (strm->flags & SF_BC_TOS) {
1663
0
      hash_params.mark_tos_prehash |= (uint64_t)strm->bc_tos << 32;
1664
      /* 42th bit: tos set */
1665
0
      hash_params.mark_tos_prehash |= 1ULL << 41;
1666
0
    }
1667
0
  }
1668
1669
0
  return conn_calculate_hash(&hash_params);
1670
0
}
1671
1672
/* Try to reuse a connection, first from <sess> session, then to <srv> server
1673
 * lists if not NULL, matching <hash> value and <be> reuse policy. If reuse is
1674
 * on <be> proxy successful, connection is attached to <sc> stconn instance.
1675
 *
1676
 * <target> must point either to the server instance, or a stream target on
1677
 * dispatch/transparent proxy.
1678
 *
1679
 * <not_first_req> must be set if the underlying request is not the first one
1680
 * conducted on <sess> session. This allows to use a connection not yet
1681
 * labelled as safe under http-reuse safe policy.
1682
 *
1683
 * This function should only be called for backends which supports connection
1684
 * reuse. It may be necessary to extend be_supports_conn_reuse() when
1685
 * implementing a new proxy mode.
1686
 *
1687
 * Returns SF_ERR_NONE if a connection has been reused. The connection instance
1688
 * can be retrieve via <sc> stconn. SF_ERR_RESOURCE is returned if no matching
1689
 * connection found. SF_ERR_INTERNAL is used on internal error.
1690
 */
1691
int be_reuse_connection(int64_t hash, struct session *sess,
1692
                        struct proxy *be, struct server *srv,
1693
                        struct stconn *sc, enum obj_type *target, int not_first_req)
1694
0
{
1695
0
  struct connection *srv_conn;
1696
0
  const int reuse_mode = be_reuse_mode(be, srv);
1697
1698
  /* first, search for a matching connection in the session's idle conns */
1699
0
  srv_conn = session_get_conn(sess, target, hash);
1700
0
  if (srv_conn) {
1701
    //DBG_TRACE_STATE("reuse connection from session", STRM_EV_STRM_PROC|STRM_EV_CS_ST, strm);
1702
0
  }
1703
0
  else if (srv && reuse_mode != PR_O_REUSE_NEVR) {
1704
    /* Below we pick connections from the safe, idle  or
1705
     * available (which are safe too) lists based
1706
     * on the strategy, the fact that this is a first or second
1707
     * (retryable) request, with the indicated priority (1 or 2) :
1708
     *
1709
     *          SAFE                 AGGR                ALWS
1710
     *
1711
     *      +-----+-----+        +-----+-----+       +-----+-----+
1712
     *   req| 1st | 2nd |     req| 1st | 2nd |    req| 1st | 2nd |
1713
     *  ----+-----+-----+    ----+-----+-----+   ----+-----+-----+
1714
     *  safe|  -  |  2  |    safe|  1  |  2  |   safe|  1  |  2  |
1715
     *  ----+-----+-----+    ----+-----+-----+   ----+-----+-----+
1716
     *  idle|  -  |  1  |    idle|  -  |  1  |   idle|  2  |  1  |
1717
     *  ----+-----+-----+    ----+-----+-----+   ----+-----+-----+
1718
     *
1719
     * Idle conns are necessarily looked up on the same thread so
1720
     * that there is no concurrency issues.
1721
     */
1722
0
    if (!ceb_isempty(&srv->per_thr[tid].avail_conns)) {
1723
0
      srv_conn = srv_lookup_conn(&srv->per_thr[tid].avail_conns, hash);
1724
0
      if (srv_conn) {
1725
        /* connection cannot be in idle list if used as an avail idle conn. */
1726
0
        BUG_ON(LIST_INLIST(&srv_conn->idle_list));
1727
        //DBG_TRACE_STATE("reuse connection from avail", STRM_EV_STRM_PROC|STRM_EV_CS_ST, strm);
1728
0
      }
1729
0
    }
1730
1731
    /* if no available connections found, search for an idle/safe */
1732
0
    if (!srv_conn && srv->max_idle_conns && srv->curr_idle_conns > 0) {
1733
0
      const int idle = srv->curr_idle_nb > 0;
1734
0
      const int safe = srv->curr_safe_nb > 0;
1735
0
      const int retry_safe = (be->retry_type & (PR_RE_CONN_FAILED | PR_RE_DISCONNECTED | PR_RE_TIMEOUT)) ==
1736
0
                                               (PR_RE_CONN_FAILED | PR_RE_DISCONNECTED | PR_RE_TIMEOUT);
1737
1738
      /* second column of the tables above, search for an idle then safe conn */
1739
0
      if (not_first_req || retry_safe) {
1740
0
        if (idle || safe)
1741
0
          srv_conn = conn_backend_get(reuse_mode, srv, sess, 0, hash);
1742
0
      }
1743
      /* first column of the tables above */
1744
0
      else if (reuse_mode >= PR_O_REUSE_AGGR) {
1745
        /* search for a safe conn */
1746
0
        if (safe)
1747
0
          srv_conn = conn_backend_get(reuse_mode, srv, sess, 1, hash);
1748
1749
        /* search for an idle conn if no safe conn found on always reuse mode */
1750
0
        if (!srv_conn &&
1751
0
            reuse_mode == PR_O_REUSE_ALWS && idle) {
1752
          /* TODO conn_backend_get should not check the safe list is this case */
1753
0
          srv_conn = conn_backend_get(reuse_mode, srv, sess, 0, hash);
1754
0
        }
1755
0
      }
1756
1757
0
      if (srv_conn) {
1758
        //DBG_TRACE_STATE("reuse connection from idle/safe", STRM_EV_STRM_PROC|STRM_EV_CS_ST, strm);
1759
0
      }
1760
0
    }
1761
0
  }
1762
1763
0
  if (srv_conn) {
1764
0
    if (srv_conn->mux) {
1765
0
      int avail = srv_conn->mux->avail_streams(srv_conn);
1766
1767
0
      if (avail <= 1) {
1768
        /* no more streams available, remove it from the list */
1769
0
        HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
1770
0
        conn_delete_from_tree(srv_conn, tid);
1771
0
        HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
1772
0
      }
1773
1774
0
      if (avail >= 1) {
1775
0
        if (CALL_MUX_WITH_RET(srv_conn->mux, attach(srv_conn, sc->sedesc, sess)) == -1) {
1776
0
          if (sc_reset_endp(sc) < 0)
1777
0
            goto err;
1778
0
          sc_ep_clr(sc, ~SE_FL_DETACHED);
1779
0
        }
1780
0
      }
1781
0
      else {
1782
        /* TODO cannot reuse conn finally due to no more avail
1783
         * streams. May be possible to lookup for a new conn
1784
         * to improve reuse rate, with a max retry limit.
1785
         */
1786
0
        srv_conn = NULL;
1787
0
      }
1788
0
    }
1789
0
  }
1790
1791
0
  return srv_conn ? SF_ERR_NONE : SF_ERR_RESOURCE;
1792
1793
0
 err:
1794
0
  return SF_ERR_INTERNAL;
1795
0
}
1796
1797
/*
1798
 * This function initiates a connection to the server assigned to this stream
1799
 * (s->target, (s->scb)->addr.to). It will assign a server if none
1800
 * is assigned yet.
1801
 * It can return one of :
1802
 *  - SF_ERR_NONE if everything's OK
1803
 *  - SF_ERR_SRVTO if there are no more servers
1804
 *  - SF_ERR_SRVCL if the connection was refused by the server
1805
 *  - SF_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1806
 *  - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1807
 *  - SF_ERR_INTERNAL for any other purely internal errors
1808
 * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
1809
 * The server-facing stream connector is expected to hold a pre-allocated connection.
1810
 */
1811
int connect_server(struct stream *s)
1812
0
{
1813
0
  struct connection *cli_conn = objt_conn(strm_orig(s));
1814
0
  struct connection *srv_conn = NULL;
1815
0
  const struct mux_proto_list *mux_proto = NULL;
1816
0
  struct server *srv;
1817
0
  struct ist name = IST_NULL;
1818
0
  struct sample *name_smp;
1819
0
  int reuse_mode;
1820
0
  int reuse __maybe_unused = 0;
1821
0
  int may_use_early_data __maybe_unused = 1; // are we allowed to use early data ?
1822
0
  int may_start_mux_now = 1; // are we allowed to start the mux now ?
1823
0
  int err;
1824
0
  struct sockaddr_storage *bind_addr = NULL;
1825
0
  int64_t hash = 0;
1826
1827
  /* in standard configuration, srv will be valid
1828
   * it can be NULL for dispatch mode or transparent backend */
1829
0
  srv = objt_server(s->target);
1830
0
  reuse_mode = be_reuse_mode(s->be, srv);
1831
1832
0
  err = alloc_dst_address(&s->scb->dst, srv, s);
1833
0
  if (err != SRV_STATUS_OK)
1834
0
    return SF_ERR_INTERNAL;
1835
1836
0
  err = alloc_bind_address(&bind_addr, srv, s->be, s);
1837
0
  if (err != SRV_STATUS_OK)
1838
0
    return SF_ERR_INTERNAL;
1839
1840
0
  if (srv && srv->pool_conn_name_expr) {
1841
0
    name_smp = sample_fetch_as_type(s->be, s->sess, s,
1842
0
        SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
1843
0
        srv->pool_conn_name_expr, SMP_T_STR);
1844
0
    if (name_smp) {
1845
0
      name = ist2(name_smp->data.u.str.area,
1846
0
          name_smp->data.u.str.data);
1847
0
    }
1848
0
  }
1849
0
  hash = be_calculate_conn_hash(srv, s, s->sess, bind_addr, s->scb->dst, name);
1850
1851
0
  if (!be_supports_conn_reuse(s->be))
1852
0
    goto skip_reuse;
1853
1854
  /* disable reuse if websocket stream and the protocol to use is not the
1855
   * same as the main protocol of the server.
1856
   */
1857
0
  if (unlikely(s->flags & SF_WEBSOCKET) && srv && !srv_check_reuse_ws(srv)) {
1858
0
    DBG_TRACE_STATE("skip idle connections reuse: websocket stream", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
1859
0
  }
1860
0
  else {
1861
0
    const int not_first_req = s->txn.http && s->txn.http->flags & TX_NOT_FIRST;
1862
1863
0
    err = be_reuse_connection(hash, s->sess, s->be, srv, s->scb,
1864
0
                              s->target, not_first_req);
1865
0
    if (err == SF_ERR_INTERNAL)
1866
0
      return err;
1867
1868
0
    if (err == SF_ERR_NONE) {
1869
0
      srv_conn = sc_conn(s->scb);
1870
0
      reuse = 1;
1871
0
      if (srv_conn && srv_conn->mux)
1872
0
        may_start_mux_now = 0;
1873
0
    }
1874
0
  }
1875
1876
0
  if (ha_used_fds > global.tune.pool_high_count && srv) {
1877
    /* We have more FDs than deemed acceptable, attempt to kill an idling connection. */
1878
0
    struct connection *tokill_conn = NULL;
1879
    /* First, try from our own idle list */
1880
0
    HA_SPIN_LOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
1881
0
    if (!LIST_ISEMPTY(&srv->per_thr[tid].idle_conn_list)) {
1882
0
      tokill_conn = LIST_ELEM(srv->per_thr[tid].idle_conn_list.n, struct connection *, idle_list);
1883
0
      conn_delete_from_tree(tokill_conn, tid);
1884
0
      HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
1885
1886
      /* Release the idle lock before calling mux->destroy.
1887
       * It will in turn call srv_release_conn through
1888
       * conn_free which also uses it.
1889
       */
1890
0
      CALL_MUX_NO_RET(tokill_conn->mux, destroy(tokill_conn->ctx));
1891
0
    }
1892
0
    else {
1893
0
      HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[tid].idle_conns_lock);
1894
0
    }
1895
1896
    /* If not, iterate over other thread's idling pool, and try to grab one */
1897
0
    if (!tokill_conn) {
1898
0
      int i;
1899
1900
0
      for (i = tid; (i = ((i + 1 == global.nbthread) ? 0 : i + 1)) != tid;) {
1901
        // just silence stupid gcc which reports an absurd
1902
        // out-of-bounds warning for <i> which is always
1903
        // exactly zero without threads, but it seems to
1904
        // see it possibly larger.
1905
0
        ALREADY_CHECKED(i);
1906
1907
0
        if (HA_SPIN_TRYLOCK(IDLE_CONNS_LOCK, &idle_conns[i].idle_conns_lock) != 0)
1908
0
          continue;
1909
1910
0
        if (!LIST_ISEMPTY(&srv->per_thr[i].idle_conn_list)) {
1911
0
          tokill_conn = LIST_ELEM(srv->per_thr[i].idle_conn_list.n, struct connection *, idle_list);
1912
0
          conn_delete_from_tree(tokill_conn, i);
1913
0
        }
1914
0
        HA_SPIN_UNLOCK(IDLE_CONNS_LOCK, &idle_conns[i].idle_conns_lock);
1915
1916
0
        if (tokill_conn) {
1917
          /* We got one, put it into the concerned thread's to kill list, and wake it's kill task */
1918
1919
0
          MT_LIST_APPEND(&idle_conns[i].toremove_conns,
1920
0
                         &tokill_conn->toremove_list);
1921
0
          task_wakeup(idle_conns[i].cleanup_task, TASK_WOKEN_OTHER);
1922
0
          break;
1923
0
        }
1924
1925
0
        if (!(global.tune.options & GTUNE_IDLE_POOL_SHARED))
1926
0
          break;
1927
0
      }
1928
0
    }
1929
0
  }
1930
1931
0
 skip_reuse:
1932
  /* no reuse or failed to reuse the connection above, pick a new one */
1933
0
  if (!srv_conn) {
1934
0
    unsigned int total_conns;
1935
1936
0
    if (srv && (srv->flags & SRV_F_RHTTP)) {
1937
0
      DBG_TRACE_USER("cannot open a new connection for reverse server", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
1938
0
      s->conn_err_type = STRM_ET_CONN_ERR;
1939
0
      return SF_ERR_INTERNAL;
1940
0
    }
1941
1942
0
    if (srv && (srv->flags & SRV_F_STRICT_MAXCONN)) {
1943
0
      int kill_tries = 0;
1944
      /*
1945
       * Before creating a new connection, make sure we still
1946
       * have a slot for that
1947
       */
1948
0
      total_conns = srv->curr_total_conns;
1949
1950
0
      while (1) {
1951
0
        if (total_conns < srv->maxconn) {
1952
0
          if (_HA_ATOMIC_CAS(&srv->curr_total_conns,
1953
0
              &total_conns, total_conns + 1))
1954
0
            break;
1955
0
          __ha_cpu_relax();
1956
0
        } else {
1957
0
          int ret = kill_random_idle_conn(srv);
1958
1959
          /*
1960
           * There is no idle connection to kill
1961
           * so there is nothing we can do at
1962
           * that point but to report an
1963
           * error.
1964
           */
1965
0
          if (ret == -1)
1966
0
            return SF_ERR_RESOURCE;
1967
0
          kill_tries++;
1968
          /*
1969
           * We tried 3 times to kill an idle
1970
           * connection, we failed, give up now.
1971
           */
1972
0
          if (ret == 0 && kill_tries == 3)
1973
0
            return SF_ERR_RESOURCE;
1974
0
        }
1975
0
      }
1976
0
    }
1977
0
    srv_conn = conn_new(s->target);
1978
0
    if (srv_conn) {
1979
0
      DBG_TRACE_STATE("alloc new be connection", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
1980
0
      srv_conn->owner = s->sess;
1981
1982
      /* connection will be attached to the session if
1983
       * http-reuse mode is never or it is not targeted to a
1984
       * server */
1985
0
      if (reuse_mode == PR_O_REUSE_NEVR || !srv)
1986
0
        conn_set_private(srv_conn);
1987
1988
      /* assign bind_addr to srv_conn */
1989
0
      srv_conn->src = bind_addr;
1990
0
      bind_addr = NULL;
1991
1992
      /* copy the target address into the connection */
1993
0
      *srv_conn->dst = *s->scb->dst;
1994
1995
      /* mark? */
1996
0
      if (s->flags & SF_BC_MARK) {
1997
0
        srv_conn->mark = s->bc_mark;
1998
0
        srv_conn->flags |= CO_FL_OPT_MARK;
1999
0
      }
2000
2001
      /* tos? */
2002
0
      if (s->flags & SF_BC_TOS) {
2003
0
        srv_conn->tos = s->bc_tos;
2004
0
        srv_conn->flags |= CO_FL_OPT_TOS;
2005
0
      }
2006
2007
0
      srv_conn->hash_node.key = hash;
2008
0
    } else if (srv && (srv->flags & SRV_F_STRICT_MAXCONN))
2009
0
      _HA_ATOMIC_DEC(&srv->curr_total_conns);
2010
0
  }
2011
2012
  /* if bind_addr is non NULL free it */
2013
0
  sockaddr_free(&bind_addr);
2014
2015
  /* srv_conn is still NULL only on allocation failure */
2016
0
  if (!srv_conn)
2017
0
    return SF_ERR_RESOURCE;
2018
2019
#if defined(HAVE_SSL_0RTT)
2020
  /* We may be allowed to use 0-RTT involving early data, to send
2021
   * the request. This may only be done in the following conditions:
2022
   *   - the SSL ctx does not support early data
2023
   *   - the connection was not reused (it must be a new one)
2024
   *   - the client already used early data, or we have L7 retries on
2025
   *   - 0rtt is configured on the server line and we have not yet failed
2026
   *     any connection attempt on this stream (in order to avoid failing
2027
   *     multiple times in a row)
2028
   *   - there are data to be sent
2029
   * otherwise we cannot make use of early data. Let's first eliminate
2030
   * the cases which don't match this above. The conditions will tighten
2031
   * later in the function when needed.
2032
   */
2033
2034
  if (!srv || !(srv->ssl_ctx.options & SRV_SSL_O_EARLY_DATA))
2035
    may_use_early_data = 0;
2036
2037
  if (reuse)
2038
    may_use_early_data = 0;
2039
2040
  if (!(cli_conn && cli_conn->flags & CO_FL_EARLY_DATA) &&
2041
      (!(s->be->retry_type & PR_RE_EARLY_ERROR) || s->conn_retries > 0))
2042
    may_use_early_data = 0;
2043
2044
  if (!co_data(sc_oc(s->scb)))
2045
    may_use_early_data = 0;
2046
#endif
2047
2048
  /* Copy network namespace from client connection */
2049
0
  srv_conn->proxy_netns = cli_conn ? cli_conn->proxy_netns : NULL;
2050
2051
0
  if (!srv_conn->xprt) {
2052
    /* set the correct protocol on the output stream connector */
2053
2054
0
    if (srv) {
2055
0
      struct protocol *proto = protocol_lookup(srv_conn->dst->ss_family, srv->addr_type.proto_type, srv->alt_proto);
2056
#ifdef USE_OPENSSL
2057
      struct sample *sni_smp = NULL;
2058
      struct ist sni = IST_NULL;
2059
2060
      /* Set socket SNI */
2061
      if (srv->xprt->get_ssl_sock_ctx && srv->ssl_ctx.sni) {
2062
        sni_smp = sample_fetch_as_type(s->be, s->sess, s,
2063
                     SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
2064
                     srv->ssl_ctx.sni, SMP_T_STR);
2065
        if (smp_make_safe(sni_smp)) {
2066
          sni = ist2(b_orig(&sni_smp->data.u.str), b_data(&sni_smp->data.u.str));
2067
          srv_conn->sni_hash = ssl_sock_sni_hash(sni);
2068
        }
2069
      }
2070
2071
#if defined(TLSEXT_TYPE_application_layer_protocol_negotiation)
2072
      /* Delay mux initialization if SSL and ALPN/NPN is set
2073
       * and server cache is not yet populated. Note that in
2074
       * TCP mode this check is ignored as only mux-pt is
2075
       * available.
2076
       *
2077
       * This check must be performed before conn_prepare()
2078
       * to ensure consistency across the whole stack, in
2079
       * particular for QUIC between quic-conn and mux layer.
2080
       */
2081
      if (IS_HTX_STRM(s) && srv->use_ssl &&
2082
          (srv->ssl_ctx.alpn_str || srv->ssl_ctx.npn_str)) {
2083
        HA_RWLOCK_RDLOCK(SERVER_LOCK, &srv->path_params.param_lock);
2084
        if (srv->path_params.srv_hash != hash || srv->path_params.nego_alpn[0] == 0)
2085
          may_start_mux_now = 0;
2086
        HA_RWLOCK_RDUNLOCK(SERVER_LOCK, &srv->path_params.param_lock);
2087
      }
2088
#endif /* TLSEXT_TYPE_application_layer_protocol_negotiation */
2089
2090
#endif /* USE_OPENSSL */
2091
2092
0
      if (conn_prepare(srv_conn, proto, srv->xprt)) {
2093
0
        conn_free(srv_conn);
2094
0
        return SF_ERR_INTERNAL;
2095
0
      }
2096
#ifdef USE_OPENSSL
2097
      if (isttest(sni))
2098
        ssl_sock_set_servername(srv_conn, istptr(sni));
2099
2100
#endif
2101
0
    } else if (obj_type(s->target) == OBJ_TYPE_PROXY) {
2102
0
      int ret;
2103
2104
      /* proxies exclusively run on raw_sock right now */
2105
0
      ret = conn_prepare(srv_conn, protocol_lookup(srv_conn->dst->ss_family, PROTO_TYPE_STREAM, 0), xprt_get(XPRT_RAW));
2106
0
      if (ret < 0 || !(srv_conn->ctrl)) {
2107
0
        conn_free(srv_conn);
2108
0
        return SF_ERR_INTERNAL;
2109
0
      }
2110
0
    }
2111
0
    else {
2112
0
      conn_free(srv_conn);
2113
0
      return SF_ERR_INTERNAL;  /* how did we get there ? */
2114
0
    }
2115
2116
0
    if (sc_attach_mux(s->scb, NULL, srv_conn) < 0) {
2117
0
      conn_free(srv_conn);
2118
0
      return SF_ERR_INTERNAL;  /* how did we get there ? */
2119
0
    }
2120
0
    srv_conn->ctx = s->scb;
2121
2122
    /* process the case where the server requires the PROXY protocol to be sent */
2123
0
    srv_conn->send_proxy_ofs = 0;
2124
2125
0
    if (srv && (srv->pp_opts & SRV_PP_ENABLED)) {
2126
0
      srv_conn->flags |= CO_FL_SEND_PROXY;
2127
0
      srv_conn->send_proxy_ofs = 1; /* must compute size */
2128
0
    }
2129
2130
0
    if (srv && (srv->flags & SRV_F_SOCKS4_PROXY)) {
2131
0
      srv_conn->send_proxy_ofs = 1;
2132
0
      srv_conn->flags |= CO_FL_SOCKS4;
2133
0
    }
2134
2135
0
    if (may_start_mux_now) {
2136
      /* Delay MUX init if an XPRT handshake is required prior. */
2137
0
      mux_proto = conn_select_mux_be(srv_conn);
2138
0
      if (mux_proto && mux_proto->init_xprt)
2139
0
        may_start_mux_now = 0;
2140
0
    }
2141
2142
#if defined(USE_OPENSSL) && defined(TLSEXT_TYPE_application_layer_protocol_negotiation)
2143
    /* if websocket stream, try to update connection ALPN. */
2144
    if (unlikely(s->flags & SF_WEBSOCKET) &&
2145
        srv && srv->use_ssl && srv->ssl_ctx.alpn_str) {
2146
      char *alpn = "";
2147
      int force = 0;
2148
2149
      switch (srv->ws) {
2150
      case SRV_WS_AUTO:
2151
        alpn = "\x08http/1.1";
2152
        force = 0;
2153
        break;
2154
      case SRV_WS_H1:
2155
        alpn = "\x08http/1.1";
2156
        force = 1;
2157
        break;
2158
      case SRV_WS_H2:
2159
        alpn = "\x02h2";
2160
        force = 1;
2161
        break;
2162
      }
2163
2164
      if (!conn_update_alpn(srv_conn, ist(alpn), force)) {
2165
        /*
2166
         * Possibly the ALPN will be different,
2167
         * so don't use any cached value.
2168
         */
2169
        may_start_mux_now = 0;
2170
        srv_conn->flags |= CO_FL_SSL_NO_CACHED_INFO;
2171
        DBG_TRACE_STATE("update alpn for websocket", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2172
      }
2173
    }
2174
#endif
2175
0
  }
2176
0
  else {
2177
0
    s->flags |= SF_SRV_REUSED;
2178
2179
    /* Currently there seems to be no known cases of xprt ready
2180
     * without the mux installed here.
2181
     */
2182
0
    BUG_ON(!srv_conn->mux);
2183
2184
0
    if (!(srv_conn->mux->ctl(srv_conn, MUX_CTL_STATUS, NULL) & MUX_STATUS_READY))
2185
0
      s->flags |= SF_SRV_REUSED_ANTICIPATED;
2186
0
  }
2187
2188
  /* flag for logging source ip/port */
2189
0
  if (strm_fe(s)->options2 & PR_O2_SRC_ADDR)
2190
0
    s->flags |= SF_SRC_ADDR;
2191
2192
  /* disable lingering */
2193
0
  if (s->be->options & PR_O_TCP_NOLING)
2194
0
    s->scb->flags |= SC_FL_NOLINGER;
2195
2196
0
  if (s->flags & SF_SRV_REUSED) {
2197
0
    if (s->be_tgcounters)
2198
0
      _HA_ATOMIC_INC(&s->be_tgcounters->reuse);
2199
0
    if (s->sv_tgcounters)
2200
0
      _HA_ATOMIC_INC(&s->sv_tgcounters->reuse);
2201
0
  } else {
2202
0
    if (s->be_tgcounters)
2203
0
      _HA_ATOMIC_INC(&s->be_tgcounters->connect);
2204
0
    if (s->sv_tgcounters)
2205
0
      _HA_ATOMIC_INC(&s->sv_tgcounters->connect);
2206
0
  }
2207
2208
0
  err = do_connect_server(s, srv_conn);
2209
0
  if (err != SF_ERR_NONE)
2210
0
    return err;
2211
2212
  /* The CO_FL_SEND_PROXY flag may have been set by the connect method,
2213
   * if so, add our handshake pseudo-XPRT now.
2214
   */
2215
0
  if ((srv_conn->flags & CO_FL_HANDSHAKE)) {
2216
0
    if (xprt_add_hs(srv_conn) < 0) {
2217
0
      conn_full_close(srv_conn);
2218
0
      return SF_ERR_INTERNAL;
2219
0
    }
2220
0
  }
2221
2222
  /* We have to defer the mux initialization until after si_connect()
2223
   * has been called, as we need the xprt to have been properly
2224
   * initialized, or any attempt to recv during the mux init may
2225
   * fail, and flag the connection as CO_FL_ERROR.
2226
   */
2227
0
  if (may_start_mux_now) {
2228
0
    const struct mux_ops *alt_mux =
2229
0
      likely(!(s->flags & SF_WEBSOCKET) || !srv) ? NULL : srv_get_ws_proto(srv);
2230
0
    if (conn_install_mux_be(srv_conn, s->scb, s->sess, alt_mux) < 0) {
2231
0
      conn_full_close(srv_conn);
2232
0
      return SF_ERR_INTERNAL;
2233
0
    }
2234
0
    if (IS_HTX_STRM(s)) {
2235
      /* If we're doing http-reuse always, and the connection
2236
       * is not private with available streams (an http2
2237
       * connection), add it to the available list, so that
2238
       * others can use it right away. If the connection is
2239
       * private or we're doing http-reuse safe and the mux
2240
       * protocol supports multiplexing, add it in the
2241
       * session server list.
2242
       */
2243
0
      if (srv && reuse_mode == PR_O_REUSE_ALWS &&
2244
0
          !(srv_conn->flags & CO_FL_PRIVATE) &&
2245
0
          srv_conn->mux->avail_streams(srv_conn) > 0) {
2246
0
        srv_add_to_avail_list(srv, srv_conn);
2247
0
      }
2248
0
      else if (srv_conn->flags & CO_FL_PRIVATE ||
2249
0
               (reuse_mode == PR_O_REUSE_SAFE &&
2250
0
                srv_conn->mux->flags & MX_FL_HOL_RISK)) {
2251
        /* If it fail now, the same will be done in mux->detach() callback */
2252
0
        session_add_conn(s->sess, srv_conn);
2253
0
      }
2254
0
    }
2255
0
  }
2256
0
  else if (mux_proto && mux_proto->init_xprt) {
2257
    /* Add handshake layer prior to MUX init if required. Does nothing if SSL layer is active though. */
2258
0
    if (xprt_add_l6hs(srv_conn, mux_proto->init_xprt)) {
2259
0
      conn_full_close(srv_conn);
2260
0
      return SF_ERR_INTERNAL;
2261
0
    }
2262
0
  }
2263
2264
  /*
2265
   * Now that the mux may have been created, we can start the xprt.
2266
   * We had to wait until then, because the xprt may behave differently
2267
   * depending on if a mux already exists, and it can receive data
2268
   * from the stream, or not.
2269
   */
2270
0
  conn_xprt_start(srv_conn);
2271
2272
#if defined(HAVE_SSL_0RTT)
2273
  /* The flags change below deserve some explanation: when we want to
2274
   * use early data, we first want to make sure that a mux is installed
2275
   * (otherwise we'll have nothing to send), and then we'll temporarily
2276
   * pretend that we're done with the SSL handshake. This way the data
2277
   * layer of the stack will be able to start sending data. The xprt
2278
   * layer will notice that these data are sent in the context of 0-rtt,
2279
   * and will produce early data, and then immediately restore these
2280
   * flags to say "I was lying, the SSL layer is not ready in fact". This
2281
   * effectively allows early data to be sent with the very first SSL
2282
   * communication with the server, while still having the ability to
2283
   * later wait for the end of the handshake.
2284
   */
2285
  if (may_use_early_data && srv && srv_conn->mux &&
2286
      srv_conn->flags & CO_FL_SSL_WAIT_HS)
2287
    srv_conn->flags &= ~(CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN);
2288
#endif
2289
2290
  /* set connect timeout */
2291
0
  s->conn_exp = tick_add_ifset(now_ms, s->connect_timeout);
2292
2293
0
  if (srv) {
2294
0
    int count;
2295
2296
0
    s->flags |= SF_CURR_SESS;
2297
0
    count = _HA_ATOMIC_ADD_FETCH(&srv->cur_sess, 1);
2298
0
    COUNTERS_UPDATE_MAX(&srv->counters.cur_sess_max, count);
2299
0
    if (s->be->lbprm.ops && s->be->lbprm.ops->server_take_conn)
2300
0
      s->be->lbprm.ops->server_take_conn(srv);
2301
0
  }
2302
2303
  /* Now handle synchronously connected sockets. We know the stream connector
2304
   * is at least in state SC_ST_CON. These ones typically are UNIX
2305
   * sockets, socket pairs, andoccasionally TCP connections on the
2306
   * loopback on a heavily loaded system.
2307
   */
2308
0
  if (srv_conn->flags & CO_FL_ERROR)
2309
0
    s->scb->flags |= SC_FL_ERROR;
2310
2311
  /* If we had early data, and the handshake ended, then
2312
   * we can remove the flag, and attempt to wake the task up,
2313
   * in the event there's an analyser waiting for the end of
2314
   * the handshake.
2315
   */
2316
0
  if (!(srv_conn->flags & (CO_FL_WAIT_XPRT | CO_FL_EARLY_SSL_HS)))
2317
0
    sc_ep_clr(s->scb, SE_FL_WAIT_FOR_HS);
2318
2319
0
  if (!sc_state_in(s->scb->state, SC_SB_EST|SC_SB_DIS|SC_SB_CLO) &&
2320
0
      (srv_conn->flags & CO_FL_WAIT_XPRT) == 0) {
2321
0
    s->conn_exp = TICK_ETERNITY;
2322
0
    sc_oc(s->scb)->flags |= CF_WRITE_EVENT;
2323
0
    if (s->scb->state == SC_ST_CON)
2324
0
      s->scb->state = SC_ST_RDY;
2325
0
  }
2326
2327
  /* Report EOI on the channel if it was reached from the mux point of
2328
   * view.
2329
   *
2330
   * Note: This test is only required because si_cs_process is also the SI
2331
   *       wake callback. Otherwise si_cs_recv()/si_cs_send() already take
2332
   *       care of it.
2333
   */
2334
0
  if (sc_ep_test(s->scb, SE_FL_EOI) && !(s->scb->flags & SC_FL_EOI)) {
2335
0
    s->scb->flags |= SC_FL_EOI;
2336
0
    sc_ic(s->scb)->flags |= CF_READ_EVENT;
2337
0
  }
2338
2339
  /* catch all sync connect while the mux is not already installed */
2340
0
  if (!srv_conn->mux && !(srv_conn->flags & CO_FL_WAIT_XPRT)) {
2341
0
    int closed_connection;
2342
2343
0
    if (conn_create_mux(srv_conn, &closed_connection) < 0) {
2344
0
      if (closed_connection == 0)
2345
0
        conn_full_close(srv_conn);
2346
0
      return SF_ERR_INTERNAL;
2347
0
    }
2348
0
  }
2349
2350
0
  return SF_ERR_NONE;  /* connection is OK */
2351
0
}
2352
2353
2354
/* This function performs the "redispatch" part of a connection attempt. It
2355
 * will assign a server if required, queue the connection if required, and
2356
 * handle errors that might arise at this level. It can change the server
2357
 * state. It will return 1 if it encounters an error, switches the server
2358
 * state, or has to queue a connection. Otherwise, it will return 0 indicating
2359
 * that the connection is ready to use.
2360
 */
2361
2362
int srv_redispatch_connect(struct stream *s)
2363
0
{
2364
0
  struct server *srv;
2365
0
  int conn_err;
2366
2367
  /* We know that we don't have any connection pending, so we will
2368
   * try to get a new one, and wait in this state if it's queued
2369
   */
2370
0
 redispatch:
2371
0
  conn_err = assign_server_and_queue(s);
2372
0
  srv = objt_server(s->target);
2373
2374
0
  switch (conn_err) {
2375
0
  case SRV_STATUS_OK:
2376
0
    break;
2377
2378
0
  case SRV_STATUS_FULL:
2379
    /* The server has reached its maxqueue limit. Either PR_O_REDISP is set
2380
     * and we can redispatch to another server, or it is not and we return
2381
     * 503. This only makes sense in DIRECT mode however, because normal LB
2382
     * algorithms would never select such a server, and hash algorithms
2383
     * would bring us on the same server again. Note that s->target is set
2384
     * in this case.
2385
     */
2386
0
    if (((s->flags & (SF_DIRECT|SF_FORCE_PRST)) == SF_DIRECT) &&
2387
0
        (s->be->options & PR_O_REDISP)) {
2388
0
      s->flags &= ~(SF_DIRECT | SF_ASSIGNED);
2389
0
      sockaddr_free(&s->scb->dst);
2390
0
      goto redispatch;
2391
0
    }
2392
2393
0
    if (!s->conn_err_type) {
2394
0
      s->conn_err_type = STRM_ET_QUEUE_ERR;
2395
0
    }
2396
2397
0
    if (s->sv_tgcounters)
2398
0
      _HA_ATOMIC_INC(&s->sv_tgcounters->failed_conns);
2399
0
    if (s->be_tgcounters)
2400
0
      _HA_ATOMIC_INC(&s->be_tgcounters->failed_conns);
2401
0
    return 1;
2402
2403
0
  case SRV_STATUS_NOSRV:
2404
    /* note: it is guaranteed that srv == NULL here */
2405
0
    if (!s->conn_err_type) {
2406
0
      s->conn_err_type = STRM_ET_CONN_ERR;
2407
0
    }
2408
2409
0
    if (s->be_tgcounters)
2410
0
      _HA_ATOMIC_INC(&s->be_tgcounters->failed_conns);
2411
0
    return 1;
2412
2413
0
  case SRV_STATUS_QUEUED:
2414
0
    s->conn_exp = tick_add_ifset(now_ms, s->queue_timeout);
2415
0
    s->scb->state = SC_ST_QUE;
2416
2417
    /* handle the unlikely event where we added to the server's
2418
     * queue just after checking the server was full and before
2419
     * it released its last entry (with extremely low maxconn).
2420
     * Not needed for backend queues, already handled in
2421
     * assign_server_and_queue().
2422
     */
2423
0
    if (unlikely(srv && may_dequeue_tasks(srv, s->be)))
2424
0
      process_srv_queue(srv);
2425
2426
0
    return 1;
2427
2428
0
  case SRV_STATUS_INTERNAL:
2429
0
  default:
2430
0
    if (!s->conn_err_type) {
2431
0
      s->conn_err_type = STRM_ET_CONN_OTHER;
2432
0
    }
2433
2434
0
    if (srv)
2435
0
      srv_inc_sess_ctr(srv);
2436
0
    if (srv)
2437
0
      srv_set_sess_last(srv);
2438
0
    if (s->sv_tgcounters)
2439
0
      _HA_ATOMIC_INC(&s->sv_tgcounters->failed_conns);
2440
0
    if (s->be_tgcounters)
2441
0
      _HA_ATOMIC_INC(&s->be_tgcounters->failed_conns);
2442
2443
    /* release other streams waiting for this server */
2444
0
    if (may_dequeue_tasks(srv, s->be))
2445
0
      process_srv_queue(srv);
2446
0
    return 1;
2447
0
  }
2448
  /* if we get here, it's because we got SRV_STATUS_OK, which also
2449
   * means that the connection has not been queued.
2450
   */
2451
0
  return 0;
2452
0
}
2453
2454
/* Check if the connection request is in such a state that it can be aborted. */
2455
static int back_may_abort_req(struct channel *req, struct stream *s)
2456
0
{
2457
0
  return ((s->scf->flags & SC_FL_ERROR) ||
2458
0
          ((s->scb->flags & (SC_FL_SHUT_WANTED|SC_FL_SHUT_DONE)) &&  /* empty and client aborted */
2459
0
           (!co_data(req) || proxy_abrt_close(s->be))));
2460
0
}
2461
2462
/* Update back stream connector status for input states SC_ST_ASS, SC_ST_QUE,
2463
 * SC_ST_TAR. Other input states are simply ignored.
2464
 * Possible output states are SC_ST_CLO, SC_ST_TAR, SC_ST_ASS, SC_ST_REQ, SC_ST_CON
2465
 * and SC_ST_EST. Flags must have previously been updated for timeouts and other
2466
 * conditions.
2467
 */
2468
void back_try_conn_req(struct stream *s)
2469
0
{
2470
0
  struct server *srv = objt_server(s->target);
2471
0
  struct stconn *sc = s->scb;
2472
0
  struct channel *req = &s->req;
2473
2474
0
  DBG_TRACE_ENTER(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2475
2476
0
  if (sc->state == SC_ST_ASS) {
2477
    /* Server assigned to connection request, we have to try to connect now */
2478
0
    int conn_err;
2479
2480
    /* Before we try to initiate the connection, see if the
2481
     * request may be aborted instead.
2482
     */
2483
0
    if (back_may_abort_req(req, s)) {
2484
0
      s->conn_err_type |= STRM_ET_CONN_ABRT;
2485
0
      DBG_TRACE_STATE("connection aborted", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2486
0
      goto abort_connection;
2487
0
    }
2488
2489
0
    conn_err = connect_server(s);
2490
0
    srv = objt_server(s->target);
2491
2492
0
    if (conn_err == SF_ERR_NONE) {
2493
      /* state = SC_ST_CON or SC_ST_EST now */
2494
0
      if (srv)
2495
0
        srv_inc_sess_ctr(srv);
2496
0
      if (srv)
2497
0
        srv_set_sess_last(srv);
2498
0
      DBG_TRACE_STATE("connection attempt", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2499
0
      goto end;
2500
0
    }
2501
2502
    /* We have received a synchronous error. We might have to
2503
     * abort, retry immediately or redispatch.
2504
     */
2505
0
    if (conn_err == SF_ERR_INTERNAL) {
2506
0
      if (!s->conn_err_type) {
2507
0
        s->conn_err_type = STRM_ET_CONN_OTHER;
2508
0
      }
2509
2510
0
      if (srv)
2511
0
        srv_inc_sess_ctr(srv);
2512
0
      if (srv)
2513
0
        srv_set_sess_last(srv);
2514
0
      if (s->sv_tgcounters)
2515
0
        _HA_ATOMIC_INC(&s->sv_tgcounters->failed_conns);
2516
0
      if (s->be_tgcounters)
2517
0
        _HA_ATOMIC_INC(&s->be_tgcounters->failed_conns);
2518
2519
      /* release other streams waiting for this server */
2520
0
      sess_change_server(s, NULL);
2521
0
      if (may_dequeue_tasks(srv, s->be))
2522
0
        process_srv_queue(srv);
2523
2524
      /* Failed and not retryable. */
2525
0
      sc_abort(sc);
2526
0
      sc_shutdown(sc);
2527
0
      sc->flags |= SC_FL_ERROR;
2528
2529
0
      s->logs.t_queue = ns_to_ms(now_ns - s->logs.accept_ts);
2530
2531
      /* we may need to know the position in the queue for logging */
2532
0
      pendconn_cond_unlink(s->pend_pos);
2533
2534
      /* no stream was ever accounted for this server */
2535
0
      sc->state = SC_ST_CLO;
2536
0
      if (s->srv_error)
2537
0
        s->srv_error(s, sc);
2538
0
      DBG_TRACE_STATE("internal error during connection", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2539
0
      goto end;
2540
0
    }
2541
2542
    /* We are facing a retryable error, but we don't want to run a
2543
     * turn-around now, as the problem is likely a source port
2544
     * allocation problem, so we want to retry now.
2545
     */
2546
0
    sc->state = SC_ST_CER;
2547
0
    sc->flags &= ~SC_FL_ERROR;
2548
0
    back_handle_st_cer(s);
2549
2550
0
    DBG_TRACE_STATE("connection error, retry", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2551
    /* now sc->state is one of SC_ST_CLO, SC_ST_TAR, SC_ST_ASS, SC_ST_REQ */
2552
0
  }
2553
0
  else if (sc->state == SC_ST_QUE) {
2554
    /* connection request was queued, check for any update */
2555
0
    if (!pendconn_dequeue(s)) {
2556
      /* The connection is not in the queue anymore. Either
2557
       * we have a server connection slot available and we
2558
       * go directly to the assigned state, or we need to
2559
       * load-balance first and go to the INI state.
2560
       */
2561
0
      s->conn_exp = TICK_ETERNITY;
2562
0
      if (unlikely(!(s->flags & SF_ASSIGNED)))
2563
0
        sc->state = SC_ST_REQ;
2564
0
      else {
2565
0
        s->logs.t_queue = ns_to_ms(now_ns - s->logs.accept_ts);
2566
0
        sc->state = SC_ST_ASS;
2567
0
      }
2568
0
      DBG_TRACE_STATE("dequeue connection request", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2569
0
      goto end;
2570
0
    }
2571
2572
    /* Connection request still in queue... */
2573
0
    if (s->flags & SF_CONN_EXP) {
2574
      /* ... and timeout expired */
2575
0
      s->conn_exp = TICK_ETERNITY;
2576
0
      s->flags &= ~SF_CONN_EXP;
2577
0
      s->logs.t_queue = ns_to_ms(now_ns - s->logs.accept_ts);
2578
2579
      /* we may need to know the position in the queue for logging */
2580
0
      pendconn_cond_unlink(s->pend_pos);
2581
2582
0
      if (s->sv_tgcounters)
2583
0
        _HA_ATOMIC_INC(&s->sv_tgcounters->failed_conns);
2584
0
      if (s->be_tgcounters)
2585
0
        _HA_ATOMIC_INC(&s->be_tgcounters->failed_conns);
2586
0
      sc_abort(sc);
2587
0
      sc_shutdown(sc);
2588
0
      req->flags |= CF_WRITE_TIMEOUT;
2589
0
      if (!s->conn_err_type)
2590
0
        s->conn_err_type = STRM_ET_QUEUE_TO;
2591
0
      sc->state = SC_ST_CLO;
2592
0
      if (s->srv_error)
2593
0
        s->srv_error(s, sc);
2594
0
      DBG_TRACE_STATE("connection request still queued", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2595
0
      goto end;
2596
0
    }
2597
2598
    /* Connection remains in queue, check if we have to abort it */
2599
0
    if (back_may_abort_req(req, s)) {
2600
0
      s->logs.t_queue = ns_to_ms(now_ns - s->logs.accept_ts);
2601
2602
      /* we may need to know the position in the queue for logging */
2603
0
      pendconn_cond_unlink(s->pend_pos);
2604
2605
0
      s->conn_err_type |= STRM_ET_QUEUE_ABRT;
2606
0
      DBG_TRACE_STATE("abort queued connection request", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2607
0
      goto abort_connection;
2608
0
    }
2609
2610
    /* Nothing changed */
2611
0
  }
2612
0
  else if (sc->state == SC_ST_TAR) {
2613
    /* Connection request might be aborted */
2614
0
    if (back_may_abort_req(req, s)) {
2615
0
      s->conn_err_type |= STRM_ET_CONN_ABRT;
2616
0
      DBG_TRACE_STATE("connection aborted", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2617
0
      goto abort_connection;
2618
0
    }
2619
2620
0
    if (!(s->flags & SF_CONN_EXP))
2621
0
      return;  /* still in turn-around */
2622
2623
0
    s->flags &= ~SF_CONN_EXP;
2624
0
    s->conn_exp = TICK_ETERNITY;
2625
2626
    /* we keep trying on the same server as long as the stream is
2627
     * marked "assigned".
2628
     * FIXME: Should we force a redispatch attempt when the server is down ?
2629
     */
2630
0
    if (s->flags & SF_ASSIGNED)
2631
0
      sc->state = SC_ST_ASS;
2632
0
    else
2633
0
      sc->state = SC_ST_REQ;
2634
2635
0
    DBG_TRACE_STATE("retry connection now", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2636
0
  }
2637
2638
0
  end:
2639
0
  DBG_TRACE_LEAVE(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2640
0
  return;
2641
2642
0
abort_connection:
2643
  /* give up */
2644
0
  s->conn_exp = TICK_ETERNITY;
2645
0
  s->flags &= ~SF_CONN_EXP;
2646
0
  sc_abort(sc);
2647
0
  sc_shutdown(sc);
2648
0
  sc->state = SC_ST_CLO;
2649
0
  if (s->srv_error)
2650
0
    s->srv_error(s, sc);
2651
0
  DBG_TRACE_DEVEL("leaving on error", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2652
0
  return;
2653
0
}
2654
2655
/* This function initiates a server connection request on a stream connector
2656
 * already in SC_ST_REQ state. Upon success, the state goes to SC_ST_ASS for
2657
 * a real connection to a server, indicating that a server has been assigned,
2658
 * or SC_ST_RDY for a successful connection to an applet. It may also return
2659
 * SC_ST_QUE, or SC_ST_CLO upon error.
2660
 */
2661
void back_handle_st_req(struct stream *s)
2662
0
{
2663
0
  struct stconn *sc = s->scb;
2664
2665
0
  if (sc->state != SC_ST_REQ)
2666
0
    return;
2667
2668
0
  DBG_TRACE_ENTER(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2669
2670
0
  if (unlikely(obj_type(s->target) == OBJ_TYPE_APPLET)) {
2671
0
    struct appctx *appctx;
2672
2673
    /* The target is an applet but the SC is in SC_ST_REQ. Thus it
2674
     * means no appctx are attached to the SC. Otherwise, it will be
2675
     * in SC_ST_RDY state. So, try to create the appctx now.
2676
     */
2677
0
    BUG_ON(sc_appctx(sc));
2678
0
    appctx = sc_applet_create(sc, objt_applet(s->target));
2679
0
    if (!appctx) {
2680
      /* No more memory, let's immediately abort. Force the
2681
       * error code to ignore the ERR_LOCAL which is not a
2682
       * real error.
2683
       */
2684
0
      s->flags &= ~(SF_ERR_MASK | SF_FINST_MASK);
2685
2686
0
      sc_abort(sc);
2687
0
      sc_shutdown(sc);
2688
0
      sc->flags |= SC_FL_ERROR;
2689
0
      s->conn_err_type = STRM_ET_CONN_RES;
2690
0
      sc->state = SC_ST_CLO;
2691
0
      if (s->srv_error)
2692
0
        s->srv_error(s, sc);
2693
0
      DBG_TRACE_STATE("failed to register applet", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2694
0
      goto end;
2695
0
    }
2696
2697
0
    DBG_TRACE_STATE("applet registered", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2698
0
    goto end;
2699
0
  }
2700
2701
  /* Try to assign a server */
2702
0
  if (srv_redispatch_connect(s) != 0) {
2703
    /* We did not get a server. Either we queued the
2704
     * connection request, or we encountered an error.
2705
     */
2706
0
    if (sc->state == SC_ST_QUE) {
2707
0
      DBG_TRACE_STATE("connection request queued", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2708
0
      goto end;
2709
0
    }
2710
2711
    /* we did not get any server, let's check the cause */
2712
0
    sc_abort(sc);
2713
0
    sc_shutdown(sc);
2714
0
    sc->flags |= SC_FL_ERROR;
2715
0
    if (!s->conn_err_type)
2716
0
      s->conn_err_type = STRM_ET_CONN_OTHER;
2717
0
    sc->state = SC_ST_CLO;
2718
0
    if (s->srv_error)
2719
0
      s->srv_error(s, sc);
2720
0
    DBG_TRACE_STATE("connection request failed", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2721
0
    goto end;
2722
0
  }
2723
2724
  /* The server is assigned */
2725
0
  s->logs.t_queue = ns_to_ms(now_ns - s->logs.accept_ts);
2726
0
  sc->state = SC_ST_ASS;
2727
0
  be_set_sess_last(s->be);
2728
0
  DBG_TRACE_STATE("connection request assigned to a server", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2729
2730
0
  end:
2731
0
  DBG_TRACE_LEAVE(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2732
0
}
2733
2734
/* This function is called with (sc->state == SC_ST_CON) meaning that a
2735
 * connection was attempted and that the file descriptor is already allocated.
2736
 * We must check for timeout, error and abort. Possible output states are
2737
 * SC_ST_CER (error), SC_ST_DIS (abort), and SC_ST_CON (no change). This only
2738
 * works with connection-based streams. We know that there were no I/O event
2739
 * when reaching this function. Timeouts and errors are *not* cleared.
2740
 */
2741
void back_handle_st_con(struct stream *s)
2742
0
{
2743
0
  struct stconn *sc = s->scb;
2744
0
  struct channel *req = &s->req;
2745
2746
0
  DBG_TRACE_ENTER(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2747
2748
  /* the client might want to abort */
2749
0
  if ((s->scf->flags & SC_FL_SHUT_DONE) ||
2750
0
      ((s->scb->flags & SC_FL_SHUT_WANTED) &&
2751
0
       (!co_data(req) || proxy_abrt_close(s->be)))) {
2752
0
    sc->flags |= SC_FL_NOLINGER;
2753
0
    sc_shutdown(sc);
2754
0
    s->conn_err_type |= STRM_ET_CONN_ABRT;
2755
0
    if (s->srv_error)
2756
0
      s->srv_error(s, sc);
2757
    /* Note: state = SC_ST_DIS now */
2758
0
    DBG_TRACE_STATE("client abort during connection attempt", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2759
0
    goto end;
2760
0
  }
2761
2762
0
 done:
2763
  /* retryable error ? */
2764
0
  if ((s->flags & SF_CONN_EXP) || (sc->flags & SC_FL_ERROR)) {
2765
0
    if (!s->conn_err_type) {
2766
0
      if ((sc->flags & SC_FL_ERROR))
2767
0
        s->conn_err_type = STRM_ET_CONN_ERR;
2768
0
      else
2769
0
        s->conn_err_type = STRM_ET_CONN_TO;
2770
0
    }
2771
2772
0
    sc->state  = SC_ST_CER;
2773
0
    DBG_TRACE_STATE("connection failed, retry", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2774
0
  }
2775
2776
0
 end:
2777
0
  DBG_TRACE_LEAVE(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2778
0
}
2779
2780
/* This function is called with (sc->state == SC_ST_CER) meaning that a
2781
 * previous connection attempt has failed and that the file descriptor
2782
 * has already been released. Possible causes include asynchronous error
2783
 * notification and time out. Possible output states are SC_ST_CLO when
2784
 * retries are exhausted, SC_ST_TAR when a delay is wanted before a new
2785
 * connection attempt, SC_ST_ASS when it's wise to retry on the same server,
2786
 * and SC_ST_REQ when an immediate redispatch is wanted. The buffers are
2787
 * marked as in error state. Timeouts and errors are cleared before retrying.
2788
 */
2789
void back_handle_st_cer(struct stream *s)
2790
0
{
2791
0
  struct stconn *sc = s->scb;
2792
0
  int must_tar = !!(sc->flags & SC_FL_ERROR);
2793
2794
0
  DBG_TRACE_ENTER(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2795
2796
0
  s->conn_exp = TICK_ETERNITY;
2797
0
  s->flags &= ~SF_CONN_EXP;
2798
2799
  /* we probably have to release last stream from the server */
2800
0
  if (objt_server(s->target)) {
2801
0
    struct connection *conn = sc_conn(sc);
2802
2803
0
    health_adjust(__objt_server(s->target), HANA_STATUS_L4_ERR);
2804
2805
0
    if (s->flags & SF_CURR_SESS) {
2806
0
      s->flags &= ~SF_CURR_SESS;
2807
0
      _HA_ATOMIC_DEC(&__objt_server(s->target)->cur_sess);
2808
0
    }
2809
2810
0
    if ((sc->flags & SC_FL_ERROR) &&
2811
0
        conn && conn->err_code == CO_ER_SSL_MISMATCH_SNI) {
2812
      /* We tried to connect to a server which is configured
2813
       * with "verify required" and which doesn't have the
2814
       * "verifyhost" directive. The server presented a wrong
2815
       * certificate (a certificate for an unexpected name),
2816
       * which implies that we have used SNI in the handshake,
2817
       * and that the server doesn't have the associated cert
2818
       * and presented a default one.
2819
       *
2820
       * This is a serious enough issue not to retry. It's
2821
       * especially important because this wrong name might
2822
       * either be the result of a configuration error, and
2823
       * retrying will only hammer the server, or is caused
2824
       * by the use of a wrong SNI value, most likely
2825
       * provided by the client and we don't want to let the
2826
       * client provoke retries.
2827
       */
2828
0
      s->conn_retries = s->max_retries;
2829
0
      DBG_TRACE_DEVEL("Bad SSL cert, disable connection retries", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2830
0
    }
2831
0
  }
2832
2833
  /* ensure that we have enough retries left */
2834
0
  if (s->conn_retries >= s->max_retries || !(s->be->retry_type & PR_RE_CONN_FAILED)) {
2835
0
    if (!s->conn_err_type) {
2836
0
      s->conn_err_type = STRM_ET_CONN_ERR;
2837
0
    }
2838
2839
0
    if (s->sv_tgcounters)
2840
0
      _HA_ATOMIC_INC(&s->sv_tgcounters->failed_conns);
2841
0
    if (s->be_tgcounters)
2842
0
      _HA_ATOMIC_INC(&s->be_tgcounters->failed_conns);
2843
0
    sess_change_server(s, NULL);
2844
0
    if (may_dequeue_tasks(objt_server(s->target), s->be))
2845
0
      process_srv_queue(objt_server(s->target));
2846
2847
    /* shutw is enough to stop a connecting socket */
2848
0
    sc_shutdown(sc);
2849
0
    sc->flags |= SC_FL_ERROR;
2850
2851
0
    sc->state = SC_ST_CLO;
2852
0
    if (s->srv_error)
2853
0
      s->srv_error(s, sc);
2854
2855
0
    DBG_TRACE_STATE("connection failed", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2856
0
    goto end;
2857
0
  }
2858
2859
  /* At this stage, we will trigger a connection retry (with or without
2860
   * redispatch). Thus we must reset the SI endpoint on the server side
2861
   * an close the attached connection. It is especially important to do it
2862
   * now if the retry is not immediately performed, to be sure to release
2863
   * resources as soon as possible and to not catch errors from the lower
2864
   * layers in an unexpected state (i.e < ST_CONN).
2865
   *
2866
   * Note: the stream connector will be switched to ST_REQ, ST_ASS or
2867
   * ST_TAR and SC_FL_ERROR and SF_CONN_EXP flags will be unset.
2868
   */
2869
0
  if (sc_reset_endp(sc) < 0) {
2870
0
    if (!s->conn_err_type)
2871
0
      s->conn_err_type = STRM_ET_CONN_OTHER;
2872
2873
0
    if (s->sv_tgcounters)
2874
0
      _HA_ATOMIC_INC(&s->sv_tgcounters->internal_errors);
2875
0
    if (s->be_tgcounters)
2876
0
      _HA_ATOMIC_INC(&s->be_tgcounters->internal_errors);
2877
0
    sess_change_server(s, NULL);
2878
0
    if (may_dequeue_tasks(objt_server(s->target), s->be))
2879
0
      process_srv_queue(objt_server(s->target));
2880
2881
    /* shutw is enough to stop a connecting socket */
2882
0
    sc_shutdown(sc);
2883
0
    sc->flags |= SC_FL_ERROR;
2884
2885
0
    sc->state = SC_ST_CLO;
2886
0
    if (s->srv_error)
2887
0
      s->srv_error(s, sc);
2888
2889
0
    DBG_TRACE_STATE("error resetting endpoint", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2890
0
    goto end;
2891
0
  }
2892
2893
0
  s->conn_retries++;
2894
0
  stream_choose_redispatch(s);
2895
2896
0
  if (must_tar) {
2897
    /* The error was an asynchronous connection error, and we will
2898
     * likely have to retry connecting to the same server, most
2899
     * likely leading to the same result. To avoid this, we wait
2900
     * MIN(one second, connect timeout) before retrying. We don't
2901
     * do it when the failure happened on a reused connection
2902
     * though.
2903
     */
2904
2905
0
    int delay = 1000;
2906
0
    const int reused = (s->flags & SF_SRV_REUSED) &&
2907
0
                       !(s->flags & SF_SRV_REUSED_ANTICIPATED);
2908
2909
0
    if (s->be->timeout.connect && s->be->timeout.connect < delay)
2910
0
      delay = s->be->timeout.connect;
2911
2912
0
    if (!s->conn_err_type)
2913
0
      s->conn_err_type = STRM_ET_CONN_ERR;
2914
2915
    /* only wait when we're retrying on the same server */
2916
0
    if ((sc->state == SC_ST_ASS ||
2917
0
         (s->be->srv_act <= 1)) && !reused) {
2918
0
      sc->state = SC_ST_TAR;
2919
0
      s->conn_exp = tick_add(now_ms, MS_TO_TICKS(delay));
2920
0
    }
2921
0
    DBG_TRACE_STATE("retry a new connection", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2922
0
  }
2923
2924
0
  end:
2925
0
  DBG_TRACE_LEAVE(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2926
0
}
2927
2928
/* This function is called with (sc->state == SC_ST_RDY) meaning that a
2929
 * connection was attempted, that the file descriptor is already allocated,
2930
 * and that it has succeeded. We must still check for errors and aborts.
2931
 * Possible output states are SC_ST_EST (established), SC_ST_CER (error),
2932
 * and SC_ST_DIS (abort). This only works with connection-based streams.
2933
 * Timeouts and errors are *not* cleared.
2934
 */
2935
void back_handle_st_rdy(struct stream *s)
2936
0
{
2937
0
  struct stconn *sc = s->scb;
2938
0
  struct channel *req = &s->req;
2939
2940
0
  DBG_TRACE_ENTER(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
2941
2942
0
  if (unlikely(obj_type(s->target) == OBJ_TYPE_APPLET)) {
2943
    /* Here the appctx must exists because the SC was set to
2944
     * SC_ST_RDY state when the appctx was created.
2945
     */
2946
0
    BUG_ON(!sc_appctx(s->scb));
2947
2948
0
    if (!s->logs.request_ts)
2949
0
      s->logs.request_ts = now_ns;
2950
0
    s->logs.t_queue = ns_to_ms(now_ns - s->logs.accept_ts);
2951
0
    be_set_sess_last(s->be);
2952
0
  }
2953
2954
  /* We know the connection at least succeeded, though it could have
2955
   * since met an error for any other reason. At least it didn't time out
2956
   * even though the timeout might have been reported right after success.
2957
   * We need to take care of various situations here :
2958
   *   - everything might be OK. We have to switch to established.
2959
   *   - an I/O error might have been reported after a successful transfer,
2960
   *     which is not retryable and needs to be logged correctly, and needs
2961
   *     established as well
2962
   *   - SC_ST_CON implies !CF_WROTE_DATA but not conversely as we could
2963
   *     have validated a connection with incoming data (e.g. TCP with a
2964
   *     banner protocol), or just a successful connect() probe.
2965
   *   - the client might have requested a connection abort, this needs to
2966
   *     be checked before we decide to retry anything.
2967
   */
2968
2969
  /* it's still possible to handle client aborts or connection retries
2970
   * before any data were sent.
2971
   */
2972
0
  if (!(req->flags & CF_WROTE_DATA)) {
2973
    /* client abort ? */
2974
0
    if ((s->scf->flags & SC_FL_SHUT_DONE) ||
2975
0
        ((s->scb->flags & SC_FL_SHUT_WANTED) &&
2976
0
         (!co_data(req) || proxy_abrt_close(s->be)))) {
2977
      /* give up */
2978
0
      sc->flags |= SC_FL_NOLINGER;
2979
0
      sc_shutdown(sc);
2980
0
      s->conn_err_type |= STRM_ET_CONN_ABRT;
2981
0
      if (s->srv_error)
2982
0
        s->srv_error(s, sc);
2983
0
      DBG_TRACE_STATE("client abort during connection attempt", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2984
0
      goto end;
2985
0
    }
2986
2987
    /* retryable error ? */
2988
0
    if (sc->flags & SC_FL_ERROR) {
2989
0
      if (!s->conn_err_type)
2990
0
        s->conn_err_type = STRM_ET_CONN_ERR;
2991
0
      sc->state = SC_ST_CER;
2992
0
      DBG_TRACE_STATE("connection failed, retry", STRM_EV_STRM_PROC|STRM_EV_CS_ST|STRM_EV_STRM_ERR, s);
2993
0
      goto end;
2994
0
    }
2995
0
  }
2996
2997
  /* data were sent and/or we had no error, back_establish() will
2998
   * now take over.
2999
   */
3000
0
  DBG_TRACE_STATE("connection established", STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
3001
0
  s->conn_err_type = STRM_ET_NONE;
3002
0
  sc->state = SC_ST_EST;
3003
3004
0
  end:
3005
0
  DBG_TRACE_LEAVE(STRM_EV_STRM_PROC|STRM_EV_CS_ST, s);
3006
0
}
3007
3008
/* sends a log message when a backend goes down, and also sets last
3009
 * change date.
3010
 */
3011
void set_backend_down(struct proxy *be)
3012
0
{
3013
0
  be->last_change = ns_to_sec(now_ns);
3014
0
  HA_ATOMIC_STORE(&be->be_counters.shared.tg[tgid - 1]->last_state_change, be->last_change);
3015
0
  _HA_ATOMIC_INC(&be->be_counters.shared.tg[tgid - 1]->down_trans);
3016
3017
0
  if (!(global.mode & MODE_STARTING)) {
3018
0
    ha_alert("%s '%s' has no server available!\n", proxy_type_str(be), be->id);
3019
0
    send_log(be, LOG_EMERG, "%s %s has no server available!\n", proxy_type_str(be), be->id);
3020
0
  }
3021
0
}
3022
3023
/* Apply RDP cookie persistence to the current stream. For this, the function
3024
 * tries to extract an RDP cookie from the request buffer, and look for the
3025
 * matching server in the list. If the server is found, it is assigned to the
3026
 * stream. This always returns 1, and the analyser removes itself from the
3027
 * list. Nothing is performed if a server was already assigned.
3028
 */
3029
int tcp_persist_rdp_cookie(struct stream *s, struct channel *req, int an_bit)
3030
0
{
3031
0
  struct proxy    *px   = s->be;
3032
0
  int              ret;
3033
0
  struct sample    smp;
3034
0
  struct server *srv;
3035
0
  uint16_t port;
3036
0
  uint32_t addr;
3037
0
  char *p;
3038
3039
0
  DBG_TRACE_ENTER(STRM_EV_STRM_ANA|STRM_EV_TCP_ANA, s);
3040
3041
0
  if (s->flags & SF_ASSIGNED)
3042
0
    goto no_cookie;
3043
3044
0
  memset(&smp, 0, sizeof(smp));
3045
3046
0
  ret = fetch_rdp_cookie_name(s, &smp, s->be->rdp_cookie_name, s->be->rdp_cookie_len);
3047
0
  if (ret == 0 || (smp.flags & SMP_F_MAY_CHANGE) || smp.data.u.str.data == 0)
3048
0
    goto no_cookie;
3049
3050
  /* Considering an rdp cookie detected using acl, str ended with <cr><lf> and should return.
3051
   * The cookie format is <ip> "." <port> where "ip" is the integer corresponding to the
3052
   * server's IP address in network order, and "port" is the integer corresponding to the
3053
   * server's port in network order. Comments please Emeric.
3054
   */
3055
0
  addr = strtoul(smp.data.u.str.area, &p, 10);
3056
0
  if (*p != '.')
3057
0
    goto no_cookie;
3058
0
  p++;
3059
3060
0
  port = ntohs(strtoul(p, &p, 10));
3061
0
  if (*p != '.')
3062
0
    goto no_cookie;
3063
3064
0
  stream_set_target(s, NULL);
3065
0
  list_for_each_entry(srv, &px->servers, el_px) {
3066
0
    if (srv->addr.ss_family == AF_INET &&
3067
0
        port == srv->svc_port &&
3068
0
        addr == ((struct sockaddr_in *)&srv->addr)->sin_addr.s_addr) {
3069
0
      if ((srv->cur_state != SRV_ST_STOPPED) || (px->options & PR_O_PERSIST)) {
3070
        /* we found the server and it is usable */
3071
0
        s->flags |= SF_DIRECT | SF_ASSIGNED;
3072
0
        stream_set_srv_target(s, srv);
3073
0
        break;
3074
0
      }
3075
0
    }
3076
0
  }
3077
3078
0
no_cookie:
3079
0
  req->analysers &= ~an_bit;
3080
0
  req->analyse_exp = TICK_ETERNITY;
3081
0
  DBG_TRACE_LEAVE(STRM_EV_STRM_ANA|STRM_EV_TCP_ANA, s);
3082
0
  return 1;
3083
0
}
3084
3085
0
int be_downtime(struct proxy *px) {
3086
0
  if (px->lbprm.tot_weight && px->last_change < ns_to_sec(now_ns))  // ignore negative time
3087
0
    return px->down_time;
3088
3089
0
  return ns_to_sec(now_ns) - px->last_change + px->down_time;
3090
0
}
3091
3092
/* Checks if <px> backend supports the addition of servers at runtime. Either a
3093
 * backend or a defaults proxy are supported. If proxy is incompatible, <msg>
3094
 * will be allocated to contain a textual explanation.
3095
 */
3096
int be_supports_dynamic_srv(struct proxy *px, char **msg)
3097
0
{
3098
0
  if (px->lbprm.algo && !(px->lbprm.algo & BE_LB_PROP_DYN)) {
3099
0
    memprintf(msg, "%s '%s' uses a non dynamic load balancing method",
3100
0
              proxy_cap_str(px->cap), px->id);
3101
0
    return 0;
3102
0
  }
3103
3104
0
  if (px->mode == PR_MODE_SYSLOG) {
3105
0
    memprintf(msg, "%s '%s' uses mode log",
3106
0
              proxy_cap_str(px->cap), px->id);
3107
0
    return 0;
3108
0
  }
3109
3110
0
  return 1;
3111
0
}
3112
3113
/*
3114
 * This function returns a string containing the balancing
3115
 * mode of the proxy in a format suitable for stats.
3116
 */
3117
3118
0
const char *backend_lb_algo_str(int algo) {
3119
3120
0
  if (algo == BE_LB_ALGO_RR)
3121
0
    return "roundrobin";
3122
0
  else if (algo == BE_LB_ALGO_SRR)
3123
0
    return "static-rr";
3124
0
  else if (algo == BE_LB_ALGO_FAS)
3125
0
    return "first";
3126
0
  else if (algo == BE_LB_ALGO_LC)
3127
0
    return "leastconn";
3128
0
  else if (algo == BE_LB_ALGO_SH)
3129
0
    return "source";
3130
0
  else if (algo == BE_LB_ALGO_UH)
3131
0
    return "uri";
3132
0
  else if (algo == BE_LB_ALGO_PH)
3133
0
    return "url_param";
3134
0
  else if (algo == BE_LB_ALGO_HH)
3135
0
    return "hdr";
3136
0
  else if (algo == BE_LB_ALGO_RCH)
3137
0
    return "rdp-cookie";
3138
0
  else if (algo == BE_LB_ALGO_SMP)
3139
0
    return "hash";
3140
0
  else if (algo == BE_LB_ALGO_NONE)
3141
0
    return "none";
3142
0
  else
3143
0
    return "unknown";
3144
0
}
3145
3146
/* This function parses a "balance" statement in a backend section describing
3147
 * <curproxy>. It returns -1 if there is any error, otherwise zero. If it
3148
 * returns -1, it will write an error message into the <err> buffer which will
3149
 * automatically be allocated and must be passed as NULL. The trailing '\n'
3150
 * will not be written. The function must be called with <args> pointing to the
3151
 * first word after "balance".
3152
 */
3153
int backend_parse_balance(const char **args, char **err, struct proxy *curproxy)
3154
0
{
3155
0
  if (!*(args[0])) {
3156
    /* if no option is set, use random by default */
3157
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3158
0
    curproxy->lbprm.algo |= BE_LB_ALGO_RND;
3159
0
    return 0;
3160
0
  }
3161
3162
0
  if (strcmp(args[0], "roundrobin") == 0) {
3163
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3164
0
    curproxy->lbprm.algo |= BE_LB_ALGO_RR;
3165
0
  }
3166
0
  else if (strcmp(args[0], "static-rr") == 0) {
3167
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3168
0
    curproxy->lbprm.algo |= BE_LB_ALGO_SRR;
3169
0
  }
3170
0
  else if (strcmp(args[0], "first") == 0) {
3171
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3172
0
    curproxy->lbprm.algo |= BE_LB_ALGO_FAS;
3173
0
  }
3174
0
  else if (strcmp(args[0], "leastconn") == 0) {
3175
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3176
0
    curproxy->lbprm.algo |= BE_LB_ALGO_LC;
3177
0
  }
3178
0
  else if (!strncmp(args[0], "random", 6)) {
3179
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3180
0
    curproxy->lbprm.algo |= BE_LB_ALGO_RND;
3181
0
    curproxy->lbprm.arg_opt1 = 2;
3182
3183
0
    if (*(args[0] + 6) == '(' && *(args[0] + 7) != ')') { /* number of draws */
3184
0
      const char *beg;
3185
0
      char *end;
3186
3187
0
      beg = args[0] + 7;
3188
0
      curproxy->lbprm.arg_opt1 = strtol(beg, &end, 0);
3189
3190
0
      if (*end != ')') {
3191
0
        if (!*end)
3192
0
          memprintf(err, "random : missing closing parenthesis.");
3193
0
        else
3194
0
          memprintf(err, "random : unexpected character '%c' after argument.", *end);
3195
0
        return -1;
3196
0
      }
3197
3198
0
      if (curproxy->lbprm.arg_opt1 < 1) {
3199
0
        memprintf(err, "random : number of draws must be at least 1.");
3200
0
        return -1;
3201
0
      }
3202
0
    }
3203
0
  }
3204
0
  else if (strcmp(args[0], "source") == 0) {
3205
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3206
0
    curproxy->lbprm.algo |= BE_LB_ALGO_SH;
3207
0
  }
3208
0
  else if (strcmp(args[0], "uri") == 0) {
3209
0
    int arg = 1;
3210
3211
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3212
0
    curproxy->lbprm.algo |= BE_LB_ALGO_UH;
3213
0
    curproxy->lbprm.arg_opt1 = 0; // "whole", "path-only"
3214
0
    curproxy->lbprm.arg_opt2 = 0; // "len"
3215
0
    curproxy->lbprm.arg_opt3 = 0; // "depth"
3216
3217
0
    while (*args[arg]) {
3218
0
      if (strcmp(args[arg], "len") == 0) {
3219
0
        if (!*args[arg+1] || (atoi(args[arg+1]) <= 0)) {
3220
0
          memprintf(err, "%s : '%s' expects a positive integer (got '%s').", args[0], args[arg], args[arg+1]);
3221
0
          return -1;
3222
0
        }
3223
0
        curproxy->lbprm.arg_opt2 = atoi(args[arg+1]);
3224
0
        arg += 2;
3225
0
      }
3226
0
      else if (strcmp(args[arg], "depth") == 0) {
3227
0
        if (!*args[arg+1] || (atoi(args[arg+1]) <= 0)) {
3228
0
          memprintf(err, "%s : '%s' expects a positive integer (got '%s').", args[0], args[arg], args[arg+1]);
3229
0
          return -1;
3230
0
        }
3231
        /* hint: we store the position of the ending '/' (depth+1) so
3232
         * that we avoid a comparison while computing the hash.
3233
         */
3234
0
        curproxy->lbprm.arg_opt3 = atoi(args[arg+1]) + 1;
3235
0
        arg += 2;
3236
0
      }
3237
0
      else if (strcmp(args[arg], "whole") == 0) {
3238
0
        curproxy->lbprm.arg_opt1 |= 1;
3239
0
        arg += 1;
3240
0
      }
3241
0
      else if (strcmp(args[arg], "path-only") == 0) {
3242
0
        curproxy->lbprm.arg_opt1 |= 2;
3243
0
        arg += 1;
3244
0
      }
3245
0
      else {
3246
0
        memprintf(err, "%s only accepts parameters 'len', 'depth', 'path-only', and 'whole' (got '%s').", args[0], args[arg]);
3247
0
        return -1;
3248
0
      }
3249
0
    }
3250
0
  }
3251
0
  else if (strcmp(args[0], "url_param") == 0) {
3252
0
    if (!*args[1]) {
3253
0
      memprintf(err, "%s requires an URL parameter name.", args[0]);
3254
0
      return -1;
3255
0
    }
3256
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3257
0
    curproxy->lbprm.algo |= BE_LB_ALGO_PH;
3258
3259
0
    free(curproxy->lbprm.arg_str);
3260
0
    curproxy->lbprm.arg_str = strdup(args[1]);
3261
0
    curproxy->lbprm.arg_len = strlen(args[1]);
3262
0
    if (*args[2]) {
3263
0
      if (strcmp(args[2], "check_post") != 0) {
3264
0
        memprintf(err, "%s only accepts 'check_post' modifier (got '%s').", args[0], args[2]);
3265
0
        return -1;
3266
0
      }
3267
0
    }
3268
0
  }
3269
0
  else if (strcmp(args[0], "hash") == 0) {
3270
0
    if (!*args[1]) {
3271
0
      memprintf(err, "%s requires a sample expression.", args[0]);
3272
0
      return -1;
3273
0
    }
3274
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3275
0
    curproxy->lbprm.algo |= BE_LB_ALGO_SMP;
3276
3277
0
    ha_free(&curproxy->lbprm.arg_str);
3278
0
    curproxy->lbprm.arg_str = strdup(args[1]);
3279
0
    curproxy->lbprm.arg_len = strlen(args[1]);
3280
3281
0
    if (*args[2]) {
3282
0
      memprintf(err, "%s takes no other argument (got '%s').", args[0], args[2]);
3283
0
      return -1;
3284
0
    }
3285
0
  }
3286
0
  else if (!strncmp(args[0], "hdr(", 4)) {
3287
0
    const char *beg, *end;
3288
3289
0
    beg = args[0] + 4;
3290
0
    end = strchr(beg, ')');
3291
3292
0
    if (!end || end == beg) {
3293
0
      memprintf(err, "hdr requires an http header field name.");
3294
0
      return -1;
3295
0
    }
3296
3297
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3298
0
    curproxy->lbprm.algo |= BE_LB_ALGO_HH;
3299
3300
0
    free(curproxy->lbprm.arg_str);
3301
0
    curproxy->lbprm.arg_len = end - beg;
3302
0
    curproxy->lbprm.arg_str = my_strndup(beg, end - beg);
3303
0
    curproxy->lbprm.arg_opt1 = 0;
3304
3305
0
    if (*args[1]) {
3306
0
      if (strcmp(args[1], "use_domain_only") != 0) {
3307
0
        memprintf(err, "%s only accepts 'use_domain_only' modifier (got '%s').", args[0], args[1]);
3308
0
        return -1;
3309
0
      }
3310
0
      curproxy->lbprm.arg_opt1 = 1;
3311
0
    }
3312
0
  }
3313
0
  else if (!strncmp(args[0], "rdp-cookie", 10)) {
3314
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3315
0
    curproxy->lbprm.algo |= BE_LB_ALGO_RCH;
3316
3317
0
    if ( *(args[0] + 10 ) == '(' ) { /* cookie name */
3318
0
      const char *beg, *end;
3319
3320
0
      beg = args[0] + 11;
3321
0
      end = strchr(beg, ')');
3322
3323
0
      if (!end || end == beg) {
3324
0
        memprintf(err, "rdp-cookie : missing cookie name.");
3325
0
        return -1;
3326
0
      }
3327
3328
0
      free(curproxy->lbprm.arg_str);
3329
0
      curproxy->lbprm.arg_str = my_strndup(beg, end - beg);
3330
0
      curproxy->lbprm.arg_len = end - beg;
3331
0
    }
3332
0
    else if ( *(args[0] + 10 ) == '\0' ) { /* default cookie name 'mstshash' */
3333
0
      free(curproxy->lbprm.arg_str);
3334
0
      curproxy->lbprm.arg_str = strdup("mstshash");
3335
0
      curproxy->lbprm.arg_len = strlen(curproxy->lbprm.arg_str);
3336
0
    }
3337
0
    else { /* syntax */
3338
0
      memprintf(err, "rdp-cookie : missing cookie name.");
3339
0
      return -1;
3340
0
    }
3341
0
  }
3342
0
  else if (strcmp(args[0], "log-hash") == 0) {
3343
0
    if (!*args[1]) {
3344
0
      memprintf(err, "%s requires a converter list.", args[0]);
3345
0
      return -1;
3346
0
    }
3347
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3348
0
    curproxy->lbprm.algo |= BE_LB_ALGO_LH;
3349
3350
0
    ha_free(&curproxy->lbprm.arg_str);
3351
0
    curproxy->lbprm.arg_str = strdup(args[1]);
3352
0
  }
3353
0
  else if (strcmp(args[0], "sticky") == 0) {
3354
0
    curproxy->lbprm.algo &= ~BE_LB_ALGO;
3355
0
    curproxy->lbprm.algo |= BE_LB_ALGO_SS;
3356
0
  }
3357
0
  else {
3358
0
    memprintf(err, "only supports 'roundrobin', 'static-rr', 'leastconn', 'source', 'uri', 'url_param', 'hash', 'hdr(name)', 'rdp-cookie(name)', 'log-hash' and 'sticky' options.");
3359
0
    return -1;
3360
0
  }
3361
0
  return 0;
3362
0
}
3363
3364
3365
/************************************************************************/
3366
/*      All supported sample and ACL keywords must be declared here.    */
3367
/************************************************************************/
3368
3369
/* set temp integer to the number of enabled servers on the proxy.
3370
 * Accepts exactly 1 argument. Argument is a backend, other types will lead to
3371
 * undefined behaviour.
3372
 */
3373
static int
3374
smp_fetch_nbsrv(const struct arg *args, struct sample *smp, const char *kw, void *private)
3375
0
{
3376
0
  struct proxy *px = args->data.prx;
3377
3378
0
  if (px == NULL)
3379
0
    return 0;
3380
0
  if (px->cap & PR_CAP_DEF)
3381
0
    px = smp->px;
3382
3383
0
  smp->flags = SMP_F_VOL_TEST;
3384
0
  smp->data.type = SMP_T_SINT;
3385
3386
0
  smp->data.u.sint = be_usable_srv(px);
3387
3388
0
  return 1;
3389
0
}
3390
3391
/* report in smp->flags a success or failure depending on the designated
3392
 * server's state. There is no match function involved since there's no pattern.
3393
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3394
 * undefined behaviour.
3395
 */
3396
static int
3397
smp_fetch_srv_is_up(const struct arg *args, struct sample *smp, const char *kw, void *private)
3398
0
{
3399
0
  struct server *srv = args->data.srv;
3400
3401
0
  smp->flags = SMP_F_VOL_TEST;
3402
0
  smp->data.type = SMP_T_BOOL;
3403
0
  if (!(srv->cur_admin & SRV_ADMF_MAINT) &&
3404
0
      (!(srv->check.state & CHK_ST_CONFIGURED) || (srv->cur_state != SRV_ST_STOPPED)))
3405
0
    smp->data.u.sint = 1;
3406
0
  else
3407
0
    smp->data.u.sint = 0;
3408
0
  return 1;
3409
0
}
3410
3411
/* set temp integer to the number of enabled servers on the proxy.
3412
 * Accepts exactly 1 argument. Argument is a backend, other types will lead to
3413
 * undefined behaviour.
3414
 */
3415
static int
3416
smp_fetch_connslots(const struct arg *args, struct sample *smp, const char *kw, void *private)
3417
0
{
3418
0
  struct server *iterator;
3419
0
  struct proxy *px = args->data.prx;
3420
3421
0
  if (px == NULL)
3422
0
    return 0;
3423
0
  if (px->cap & PR_CAP_DEF)
3424
0
    px = smp->px;
3425
3426
0
  smp->flags = SMP_F_VOL_TEST;
3427
0
  smp->data.type = SMP_T_SINT;
3428
0
  smp->data.u.sint = 0;
3429
3430
0
  list_for_each_entry(iterator, &px->servers, el_px) {
3431
0
    if (iterator->cur_state == SRV_ST_STOPPED)
3432
0
      continue;
3433
3434
0
    if (iterator->maxconn == 0 || iterator->maxqueue == 0) {
3435
      /* configuration is stupid */
3436
0
      smp->data.u.sint = -1;  /* FIXME: stupid value! */
3437
0
      return 1;
3438
0
    }
3439
3440
0
    smp->data.u.sint += (iterator->maxconn - iterator->cur_sess)
3441
0
                           +  (iterator->maxqueue - iterator->queueslength);
3442
0
  }
3443
3444
0
  return 1;
3445
0
}
3446
3447
/* set temp integer to the id of the backend */
3448
static int
3449
smp_fetch_be_id(const struct arg *args, struct sample *smp, const char *kw, void *private)
3450
0
{
3451
0
  struct proxy *px = NULL;
3452
3453
0
  if (smp->strm)
3454
0
    px = smp->strm->be;
3455
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3456
0
    px = __objt_check(smp->sess->origin)->proxy;
3457
0
  if (!px)
3458
0
    return 0;
3459
3460
0
  smp->flags = SMP_F_VOL_TXN;
3461
0
  smp->data.type = SMP_T_SINT;
3462
0
  smp->data.u.sint = px->uuid;
3463
0
  return 1;
3464
0
}
3465
3466
/* set string to the name of the backend */
3467
static int
3468
smp_fetch_be_name(const struct arg *args, struct sample *smp, const char *kw, void *private)
3469
0
{
3470
0
  struct proxy *px = NULL;
3471
3472
0
  if (smp->strm)
3473
0
    px = smp->strm->be;
3474
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3475
0
    px = __objt_check(smp->sess->origin)->proxy;
3476
0
  if (!px)
3477
0
    return 0;
3478
3479
0
  smp->data.u.str.area = (char *)px->id;
3480
0
  if (!smp->data.u.str.area)
3481
0
          return 0;
3482
3483
0
  smp->data.type = SMP_T_STR;
3484
0
  smp->flags = SMP_F_CONST;
3485
0
  smp->data.u.str.data = strlen(smp->data.u.str.area);
3486
3487
0
  return 1;
3488
0
}
3489
3490
/* set temp integer to the id of the server */
3491
static int
3492
smp_fetch_srv_id(const struct arg *args, struct sample *smp, const char *kw, void *private)
3493
0
{
3494
0
  struct server *srv = NULL;
3495
3496
0
  if (smp->strm)
3497
0
    srv = objt_server(smp->strm->target);
3498
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3499
0
    srv = __objt_check(smp->sess->origin)->server;
3500
0
  if (!srv)
3501
0
    return 0;
3502
3503
0
  smp->data.type = SMP_T_SINT;
3504
0
  smp->data.u.sint = srv->puid;
3505
3506
0
  return 1;
3507
0
}
3508
3509
/* set string to the name of the server */
3510
static int
3511
smp_fetch_srv_name(const struct arg *args, struct sample *smp, const char *kw, void *private)
3512
0
{
3513
0
  struct server *srv = NULL;
3514
3515
0
  if (smp->strm)
3516
0
    srv = objt_server(smp->strm->target);
3517
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3518
0
    srv = __objt_check(smp->sess->origin)->server;
3519
0
  if (!srv)
3520
0
    return 0;
3521
3522
0
  smp->data.u.str.area = srv->id;
3523
0
  if (!smp->data.u.str.area)
3524
0
          return 0;
3525
3526
0
  smp->data.type = SMP_T_STR;
3527
0
  smp->flags = SMP_F_CONST;
3528
0
  smp->data.u.str.data = strlen(smp->data.u.str.area);
3529
3530
0
  return 1;
3531
0
}
3532
3533
/* set temp integer to the number of connections per second reaching the backend.
3534
 * Accepts exactly 1 argument. Argument is a backend, other types will lead to
3535
 * undefined behaviour.
3536
 */
3537
static int
3538
smp_fetch_be_sess_rate(const struct arg *args, struct sample *smp, const char *kw, void *private)
3539
0
{
3540
0
  struct proxy *px = args->data.prx;
3541
3542
0
  if (px == NULL)
3543
0
    return 0;
3544
0
  if (px->cap & PR_CAP_DEF)
3545
0
    px = smp->px;
3546
3547
0
  smp->flags = SMP_F_VOL_TEST;
3548
0
  smp->data.type = SMP_T_SINT;
3549
0
  smp->data.u.sint = COUNTERS_SHARED_TOTAL(px->be_counters.shared.tg, sess_per_sec, read_freq_ctr);
3550
0
  return 1;
3551
0
}
3552
3553
/* set temp integer to the number of concurrent connections on the backend.
3554
 * Accepts exactly 1 argument. Argument is a backend, other types will lead to
3555
 * undefined behaviour.
3556
 */
3557
static int
3558
smp_fetch_be_conn(const struct arg *args, struct sample *smp, const char *kw, void *private)
3559
0
{
3560
0
  struct proxy *px = args->data.prx;
3561
3562
0
  if (px == NULL)
3563
0
    return 0;
3564
0
  if (px->cap & PR_CAP_DEF)
3565
0
    px = smp->px;
3566
3567
0
  smp->flags = SMP_F_VOL_TEST;
3568
0
  smp->data.type = SMP_T_SINT;
3569
0
  smp->data.u.sint = px->beconn;
3570
0
  return 1;
3571
0
}
3572
3573
/* set temp integer to the number of available connections across available
3574
  * servers on the backend.
3575
 * Accepts exactly 1 argument. Argument is a backend, other types will lead to
3576
 * undefined behaviour.
3577
  */
3578
static int
3579
smp_fetch_be_conn_free(const struct arg *args, struct sample *smp, const char *kw, void *private)
3580
0
{
3581
0
  struct server *iterator;
3582
0
  struct proxy *px = args->data.prx;
3583
0
  unsigned int maxconn;
3584
3585
0
  if (px == NULL)
3586
0
    return 0;
3587
0
  if (px->cap & PR_CAP_DEF)
3588
0
    px = smp->px;
3589
3590
0
  smp->flags = SMP_F_VOL_TEST;
3591
0
  smp->data.type = SMP_T_SINT;
3592
0
  smp->data.u.sint = 0;
3593
3594
0
  list_for_each_entry(iterator, &px->servers, el_px) {
3595
0
    if (iterator->cur_state == SRV_ST_STOPPED)
3596
0
      continue;
3597
3598
0
    px = iterator->proxy;
3599
0
    if (!srv_currently_usable(iterator) ||
3600
0
        ((iterator->flags & SRV_F_BACKUP) &&
3601
0
         (px->srv_act || (iterator != px->lbprm.fbck && !(px->options & PR_O_USE_ALL_BK)))))
3602
0
      continue;
3603
3604
0
    if (iterator->maxconn == 0) {
3605
      /* one active server is unlimited, return -1 */
3606
0
      smp->data.u.sint = -1;
3607
0
      return 1;
3608
0
    }
3609
3610
0
    maxconn = srv_dynamic_maxconn(iterator);
3611
0
    if (maxconn > iterator->cur_sess)
3612
0
      smp->data.u.sint += maxconn - iterator->cur_sess;
3613
0
  }
3614
3615
0
  return 1;
3616
0
}
3617
3618
/* set temp integer to the total number of queued connections on the backend.
3619
 * Accepts exactly 1 argument. Argument is a backend, other types will lead to
3620
 * undefined behaviour.
3621
 */
3622
static int
3623
smp_fetch_queue_size(const struct arg *args, struct sample *smp, const char *kw, void *private)
3624
0
{
3625
0
  struct proxy *px = args->data.prx;
3626
3627
0
  if (px == NULL)
3628
0
    return 0;
3629
0
  if (px->cap & PR_CAP_DEF)
3630
0
    px = smp->px;
3631
3632
0
  smp->flags = SMP_F_VOL_TEST;
3633
0
  smp->data.type = SMP_T_SINT;
3634
0
  smp->data.u.sint = px->totpend;
3635
0
  return 1;
3636
0
}
3637
3638
/* set temp integer to the total number of queued connections on the backend divided
3639
 * by the number of running servers and rounded up. If there is no running
3640
 * server, we return twice the total, just as if we had half a running server.
3641
 * This is more or less correct anyway, since we expect the last server to come
3642
 * back soon.
3643
 * Accepts exactly 1 argument. Argument is a backend, other types will lead to
3644
 * undefined behaviour.
3645
 */
3646
static int
3647
smp_fetch_avg_queue_size(const struct arg *args, struct sample *smp, const char *kw, void *private)
3648
0
{
3649
0
  struct proxy *px = args->data.prx;
3650
0
  int nbsrv;
3651
3652
0
  if (px == NULL)
3653
0
    return 0;
3654
0
  if (px->cap & PR_CAP_DEF)
3655
0
    px = smp->px;
3656
3657
0
  smp->flags = SMP_F_VOL_TEST;
3658
0
  smp->data.type = SMP_T_SINT;
3659
3660
0
  nbsrv = be_usable_srv(px);
3661
3662
0
  if (nbsrv > 0)
3663
0
    smp->data.u.sint = (px->totpend + nbsrv - 1) / nbsrv;
3664
0
  else
3665
0
    smp->data.u.sint = px->totpend * 2;
3666
3667
0
  return 1;
3668
0
}
3669
3670
/* set temp integer to the number of concurrent connections on the server in the backend.
3671
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3672
 * undefined behaviour.
3673
 */
3674
static int
3675
smp_fetch_srv_conn(const struct arg *args, struct sample *smp, const char *kw, void *private)
3676
0
{
3677
0
  smp->flags = SMP_F_VOL_TEST;
3678
0
  smp->data.type = SMP_T_SINT;
3679
0
  smp->data.u.sint = args->data.srv->cur_sess;
3680
0
  return 1;
3681
0
}
3682
3683
/* set temp integer to the number of available connections on the server in the backend.
3684
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3685
 * undefined behaviour.
3686
 */
3687
static int
3688
smp_fetch_srv_conn_free(const struct arg *args, struct sample *smp, const char *kw, void *private)
3689
0
{
3690
0
  unsigned int maxconn;
3691
3692
0
  smp->flags = SMP_F_VOL_TEST;
3693
0
  smp->data.type = SMP_T_SINT;
3694
3695
0
  if (args->data.srv->maxconn == 0) {
3696
    /* one active server is unlimited, return -1 */
3697
0
    smp->data.u.sint = -1;
3698
0
    return 1;
3699
0
  }
3700
3701
0
  maxconn = srv_dynamic_maxconn(args->data.srv);
3702
0
  if (maxconn > args->data.srv->cur_sess)
3703
0
    smp->data.u.sint = maxconn - args->data.srv->cur_sess;
3704
0
  else
3705
0
    smp->data.u.sint = 0;
3706
3707
0
  return 1;
3708
0
}
3709
3710
/* set temp integer to the number of connections pending in the server's queue.
3711
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3712
 * undefined behaviour.
3713
 */
3714
static int
3715
smp_fetch_srv_queue(const struct arg *args, struct sample *smp, const char *kw, void *private)
3716
0
{
3717
0
  smp->flags = SMP_F_VOL_TEST;
3718
0
  smp->data.type = SMP_T_SINT;
3719
0
  smp->data.u.sint = args->data.srv->queueslength;
3720
0
  return 1;
3721
0
}
3722
3723
/* set temp integer to the number of enabled servers on the proxy.
3724
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3725
 * undefined behaviour.
3726
 */
3727
static int
3728
smp_fetch_srv_sess_rate(const struct arg *args, struct sample *smp, const char *kw, void *private)
3729
0
{
3730
0
  smp->flags = SMP_F_VOL_TEST;
3731
0
  smp->data.type = SMP_T_SINT;
3732
0
  smp->data.u.sint = COUNTERS_SHARED_TOTAL(args->data.srv->counters.shared.tg, sess_per_sec, read_freq_ctr);
3733
0
  return 1;
3734
0
}
3735
3736
/* set temp integer to the server weight.
3737
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3738
 * undefined behaviour.
3739
 */
3740
static int
3741
smp_fetch_srv_weight(const struct arg *args, struct sample *smp, const char *kw, void *private)
3742
0
{
3743
0
  struct server *srv = args->data.srv;
3744
0
  struct proxy *px = srv->proxy;
3745
3746
0
  smp->flags = SMP_F_VOL_TEST;
3747
0
  smp->data.type = SMP_T_SINT;
3748
0
  smp->data.u.sint = (srv->cur_eweight * px->lbprm.wmult + px->lbprm.wdiv - 1) / px->lbprm.wdiv;
3749
0
  return 1;
3750
0
}
3751
3752
/* set temp integer to the server initial weight.
3753
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3754
 * undefined behaviour.
3755
 */
3756
static int
3757
smp_fetch_srv_iweight(const struct arg *args, struct sample *smp, const char *kw, void *private)
3758
0
{
3759
0
  smp->flags = SMP_F_VOL_TEST;
3760
0
  smp->data.type = SMP_T_SINT;
3761
0
  smp->data.u.sint = args->data.srv->iweight;
3762
0
  return 1;
3763
0
}
3764
3765
/* set temp integer to the server user-specified weight.
3766
 * Accepts exactly 1 argument. Argument is a server, other types will lead to
3767
 * undefined behaviour.
3768
 */
3769
static int
3770
smp_fetch_srv_uweight(const struct arg *args, struct sample *smp, const char *kw, void *private)
3771
0
{
3772
0
  smp->flags = SMP_F_VOL_TEST;
3773
0
  smp->data.type = SMP_T_SINT;
3774
0
  smp->data.u.sint = args->data.srv->uweight;
3775
0
  return 1;
3776
0
}
3777
3778
static int
3779
smp_fetch_be_max_retries(const struct arg *args, struct sample *smp, const char *km, void *private)
3780
0
{
3781
0
  struct proxy *px = NULL;
3782
3783
0
  if (smp->strm)
3784
0
    px = smp->strm->be;
3785
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3786
0
    px = __objt_check(smp->sess->origin)->proxy;
3787
0
  if (!px)
3788
0
    return 0;
3789
3790
0
  smp->flags = SMP_F_VOL_TXN;
3791
0
  smp->data.type = SMP_T_SINT;
3792
0
  smp->data.u.sint = px->conn_retries;
3793
0
  return 1;
3794
0
}
3795
3796
static int
3797
smp_fetch_be_connect_timeout(const struct arg *args, struct sample *smp, const char *km, void *private)
3798
0
{
3799
0
  struct proxy *px = NULL;
3800
3801
0
  if (smp->strm)
3802
0
    px = smp->strm->be;
3803
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3804
0
    px = __objt_check(smp->sess->origin)->proxy;
3805
0
  if (!px)
3806
0
    return 0;
3807
3808
0
  smp->flags = SMP_F_VOL_TXN;
3809
0
  smp->data.type = SMP_T_SINT;
3810
0
  smp->data.u.sint = TICKS_TO_MS(px->timeout.connect);
3811
0
  return 1;
3812
0
}
3813
3814
static int
3815
smp_fetch_be_queue_timeout(const struct arg *args, struct sample *smp, const char *km, void *private)
3816
0
{
3817
0
  struct proxy *px = NULL;
3818
3819
0
  if (smp->strm)
3820
0
    px = smp->strm->be;
3821
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3822
0
    px = __objt_check(smp->sess->origin)->proxy;
3823
0
  if (!px)
3824
0
    return 0;
3825
3826
0
  smp->flags = SMP_F_VOL_TXN;
3827
0
  smp->data.type = SMP_T_SINT;
3828
0
  smp->data.u.sint = TICKS_TO_MS(px->timeout.queue);
3829
0
  return 1;
3830
0
}
3831
3832
static int
3833
smp_fetch_be_server_timeout(const struct arg *args, struct sample *smp, const char *km, void *private)
3834
0
{
3835
0
  struct proxy *px = NULL;
3836
3837
0
  if (smp->strm)
3838
0
    px = smp->strm->be;
3839
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3840
0
    px = __objt_check(smp->sess->origin)->proxy;
3841
0
  if (!px)
3842
0
    return 0;
3843
3844
0
  smp->flags = SMP_F_VOL_TXN;
3845
0
  smp->data.type = SMP_T_SINT;
3846
0
  smp->data.u.sint = TICKS_TO_MS(px->timeout.server);
3847
0
  return 1;
3848
0
}
3849
3850
static int
3851
smp_fetch_be_tarpit_timeout(const struct arg *args, struct sample *smp, const char *km, void *private)
3852
0
{
3853
0
  struct proxy *px = NULL;
3854
3855
0
  if (smp->strm)
3856
0
    px = smp->strm->be;
3857
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3858
0
    px = __objt_check(smp->sess->origin)->proxy;
3859
0
  if (!px)
3860
0
    return 0;
3861
3862
0
  smp->flags = SMP_F_VOL_TXN;
3863
0
  smp->data.type = SMP_T_SINT;
3864
0
  smp->data.u.sint = TICKS_TO_MS(px->timeout.tarpit);
3865
0
  return 1;
3866
0
}
3867
3868
static int
3869
smp_fetch_be_tunnel_timeout(const struct arg *args, struct sample *smp, const char *km, void *private)
3870
0
{
3871
0
  struct proxy *px = NULL;
3872
3873
0
  if (smp->strm)
3874
0
    px = smp->strm->be;
3875
0
  else if (obj_type(smp->sess->origin) == OBJ_TYPE_CHECK)
3876
0
    px = __objt_check(smp->sess->origin)->proxy;
3877
0
  if (!px)
3878
0
    return 0;
3879
3880
0
  smp->flags = SMP_F_VOL_TXN;
3881
0
  smp->data.type = SMP_T_SINT;
3882
0
  smp->data.u.sint = TICKS_TO_MS(px->timeout.tunnel);
3883
0
  return 1;
3884
0
}
3885
3886
static int sample_conv_nbsrv(const struct arg *args, struct sample *smp, void *private)
3887
0
{
3888
3889
0
  struct proxy *px;
3890
3891
0
  if (!smp_make_safe(smp))
3892
0
    return 0;
3893
3894
0
  px = proxy_find_by_name(smp->data.u.str.area, PR_CAP_BE, 0);
3895
0
  if (!px)
3896
0
    return 0;
3897
3898
0
  smp->data.type = SMP_T_SINT;
3899
0
  smp->data.u.sint = be_usable_srv(px);
3900
3901
0
  return 1;
3902
0
}
3903
3904
static struct server *sample_conv_srv(struct sample *smp)
3905
0
{
3906
0
  struct proxy *px;
3907
0
  char *bksep;
3908
3909
0
  if (!smp_make_safe(smp))
3910
0
    return 0;
3911
3912
0
  bksep = strchr(smp->data.u.str.area, '/');
3913
3914
0
  if (bksep) {
3915
0
    *bksep = '\0';
3916
0
    px = proxy_find_by_name(smp->data.u.str.area, PR_CAP_BE, 0);
3917
0
    if (!px)
3918
0
      return NULL;
3919
0
    smp->data.u.str.area = bksep + 1;
3920
0
  } else {
3921
0
    if (!(smp->px->cap & PR_CAP_BE))
3922
0
      return NULL;
3923
0
    px = smp->px;
3924
0
  }
3925
3926
0
  return server_find(px, smp->data.u.str.area);
3927
0
}
3928
3929
static int
3930
sample_conv_srv_is_up(const struct arg *args, struct sample *smp, void *private)
3931
0
{
3932
0
  struct server *srv = sample_conv_srv(smp);
3933
3934
0
  if (!srv)
3935
0
    return 0;
3936
3937
0
  smp->data.type = SMP_T_BOOL;
3938
0
  if (!(srv->cur_admin & SRV_ADMF_MAINT) &&
3939
0
      (!(srv->check.state & CHK_ST_CONFIGURED) || (srv->cur_state != SRV_ST_STOPPED)))
3940
0
    smp->data.u.sint = 1;
3941
0
  else
3942
0
    smp->data.u.sint = 0;
3943
0
  return 1;
3944
0
}
3945
3946
static int
3947
sample_conv_srv_queue(const struct arg *args, struct sample *smp, void *private)
3948
0
{
3949
0
  struct server *srv = sample_conv_srv(smp);
3950
3951
0
  if (!srv)
3952
0
    return 0;
3953
3954
0
  smp->data.type = SMP_T_SINT;
3955
0
  smp->data.u.sint = srv->queueslength;
3956
0
  return 1;
3957
0
}
3958
3959
/* Note: must not be declared <const> as its list will be overwritten.
3960
 * Please take care of keeping this list alphabetically sorted.
3961
 */
3962
static struct sample_fetch_kw_list smp_kws = {ILH, {
3963
  { "avg_queue",         smp_fetch_avg_queue_size,    ARG1(1,BE),  NULL, SMP_T_SINT, SMP_USE_INTRN, },
3964
  { "be_conn",           smp_fetch_be_conn,           ARG1(1,BE),  NULL, SMP_T_SINT, SMP_USE_INTRN, },
3965
  { "be_conn_free",      smp_fetch_be_conn_free,      ARG1(1,BE),  NULL, SMP_T_SINT, SMP_USE_INTRN, },
3966
  { "be_id",             smp_fetch_be_id,             0,           NULL, SMP_T_SINT, SMP_USE_BKEND, },
3967
  { "be_name",           smp_fetch_be_name,           0,           NULL, SMP_T_STR,  SMP_USE_BKEND, },
3968
  { "be_connect_timeout",smp_fetch_be_connect_timeout,0,           NULL, SMP_T_SINT, SMP_USE_BKEND, },
3969
  { "be_max_retries",    smp_fetch_be_max_retries,    0,           NULL, SMP_T_SINT, SMP_USE_BKEND, },
3970
  { "be_queue_timeout",  smp_fetch_be_queue_timeout,  0,           NULL, SMP_T_SINT, SMP_USE_BKEND, },
3971
  { "be_server_timeout", smp_fetch_be_server_timeout, 0,           NULL, SMP_T_SINT, SMP_USE_BKEND, },
3972
  { "be_sess_rate",      smp_fetch_be_sess_rate,      ARG1(1,BE),  NULL, SMP_T_SINT, SMP_USE_INTRN, },
3973
  { "be_tarpit_timeout", smp_fetch_be_tarpit_timeout, 0,           NULL, SMP_T_SINT, SMP_USE_BKEND, },
3974
  { "be_tunnel_timeout", smp_fetch_be_tunnel_timeout, 0,           NULL, SMP_T_SINT, SMP_USE_BKEND, },
3975
  { "connslots",         smp_fetch_connslots,         ARG1(1,BE),  NULL, SMP_T_SINT, SMP_USE_INTRN, },
3976
  { "nbsrv",             smp_fetch_nbsrv,             ARG1(1,BE),  NULL, SMP_T_SINT, SMP_USE_INTRN, },
3977
  { "queue",             smp_fetch_queue_size,        ARG1(1,BE),  NULL, SMP_T_SINT, SMP_USE_INTRN, },
3978
  { "srv_conn",          smp_fetch_srv_conn,          ARG1(1,SRV), NULL, SMP_T_SINT, SMP_USE_INTRN, },
3979
  { "srv_conn_free",     smp_fetch_srv_conn_free,     ARG1(1,SRV), NULL, SMP_T_SINT, SMP_USE_INTRN, },
3980
  { "srv_id",            smp_fetch_srv_id,            0,           NULL, SMP_T_SINT, SMP_USE_SERVR, },
3981
  { "srv_is_up",         smp_fetch_srv_is_up,         ARG1(1,SRV), NULL, SMP_T_BOOL, SMP_USE_INTRN, },
3982
  { "srv_name",          smp_fetch_srv_name,          0,           NULL, SMP_T_STR,  SMP_USE_SERVR, },
3983
  { "srv_queue",         smp_fetch_srv_queue,         ARG1(1,SRV), NULL, SMP_T_SINT, SMP_USE_INTRN, },
3984
  { "srv_sess_rate",     smp_fetch_srv_sess_rate,     ARG1(1,SRV), NULL, SMP_T_SINT, SMP_USE_INTRN, },
3985
  { "srv_weight",        smp_fetch_srv_weight,        ARG1(1,SRV), NULL, SMP_T_SINT, SMP_USE_INTRN, },
3986
  { "srv_iweight",       smp_fetch_srv_iweight,       ARG1(1,SRV), NULL, SMP_T_SINT, SMP_USE_INTRN, },
3987
  { "srv_uweight",       smp_fetch_srv_uweight,       ARG1(1,SRV), NULL, SMP_T_SINT, SMP_USE_INTRN, },
3988
  { /* END */ },
3989
}};
3990
3991
INITCALL1(STG_REGISTER, sample_register_fetches, &smp_kws);
3992
3993
/* Note: must not be declared <const> as its list will be overwritten */
3994
static struct sample_conv_kw_list sample_conv_kws = {ILH, {
3995
  { "nbsrv",     sample_conv_nbsrv,     0, NULL, SMP_T_STR, SMP_T_SINT },
3996
  { "srv_is_up", sample_conv_srv_is_up, 0, NULL, SMP_T_STR, SMP_T_BOOL },
3997
  { "srv_queue", sample_conv_srv_queue, 0, NULL, SMP_T_STR, SMP_T_SINT },
3998
  { /* END */ },
3999
}};
4000
4001
INITCALL1(STG_REGISTER, sample_register_convs, &sample_conv_kws);
4002
4003
/* Note: must not be declared <const> as its list will be overwritten.
4004
 * Please take care of keeping this list alphabetically sorted.
4005
 */
4006
static struct acl_kw_list acl_kws = {ILH, {
4007
  { /* END */ },
4008
}};
4009
4010
INITCALL1(STG_REGISTER, acl_register_keywords, &acl_kws);
4011
4012
/*
4013
 * Local variables:
4014
 *  c-indent-level: 8
4015
 *  c-basic-offset: 8
4016
 * End:
4017
 */