blob: f520e1ac9061d9c73a4fc331962425d6a88b3fc2 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
Willy Tarreaua5357cd2021-05-09 06:14:25 +02002 * HAProxy : High Availability-enabled HTTP/TCP proxy
Willy Tarreau421ed392021-01-06 17:41:32 +01003 * Copyright 2000-2021 Willy Tarreau <willy@haproxy.org>.
Willy Tarreaubaaee002006-06-26 02:48:02 +02004 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version
8 * 2 of the License, or (at your option) any later version.
9 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +050010 * Please refer to RFC7230 - RFC7235 information about HTTP protocol, and
11 * RFC6265 for information about cookies usage. More generally, the IETF HTTP
Willy Tarreaubaaee002006-06-26 02:48:02 +020012 * Working Group's web site should be consulted for protocol related changes :
13 *
14 * http://ftp.ics.uci.edu/pub/ietf/http/
15 *
16 * Pending bugs (may be not fixed because never reproduced) :
17 * - solaris only : sometimes, an HTTP proxy with only a dispatch address causes
18 * the proxy to terminate (no core) if the client breaks the connection during
19 * the response. Seen on 1.1.8pre4, but never reproduced. May not be related to
20 * the snprintf() bug since requests were simple (GET / HTTP/1.0), but may be
21 * related to missing setsid() (fixed in 1.1.15)
22 * - a proxy with an invalid config will prevent the startup even if disabled.
23 *
24 * ChangeLog has moved to the CHANGELOG file.
25 *
Willy Tarreaubaaee002006-06-26 02:48:02 +020026 */
27
David Carlier7ece0962015-12-08 21:43:09 +000028#define _GNU_SOURCE
Willy Tarreaubaaee002006-06-26 02:48:02 +020029#include <stdio.h>
30#include <stdlib.h>
31#include <unistd.h>
32#include <string.h>
33#include <ctype.h>
Maxime de Roucy379d9c72016-05-13 23:52:56 +020034#include <dirent.h>
Maxime de Roucy379d9c72016-05-13 23:52:56 +020035#include <sys/stat.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020036#include <sys/time.h>
37#include <sys/types.h>
38#include <sys/socket.h>
39#include <netinet/tcp.h>
40#include <netinet/in.h>
41#include <arpa/inet.h>
42#include <netdb.h>
43#include <fcntl.h>
44#include <errno.h>
45#include <signal.h>
46#include <stdarg.h>
47#include <sys/resource.h>
Tim Duesterhusdfad6a42020-04-18 16:02:47 +020048#include <sys/utsname.h>
Marc-Antoine Perennou992709b2013-02-12 10:53:52 +010049#include <sys/wait.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020050#include <time.h>
51#include <syslog.h>
Michael Schererab012dd2013-01-12 18:35:19 +010052#include <grp.h>
Willy Tarreaufc6c0322012-11-16 16:12:27 +010053#ifdef USE_CPU_AFFINITY
Willy Tarreaufc6c0322012-11-16 16:12:27 +010054#include <sched.h>
David Carlier42d9e5a2018-11-12 16:22:19 +000055#if defined(__FreeBSD__) || defined(__DragonFly__)
Pieter Baauwcaa6a1b2015-09-17 21:26:40 +020056#include <sys/param.h>
David Carlier42d9e5a2018-11-12 16:22:19 +000057#ifdef __FreeBSD__
Pieter Baauwcaa6a1b2015-09-17 21:26:40 +020058#include <sys/cpuset.h>
David Carlier42d9e5a2018-11-12 16:22:19 +000059#endif
David Carlier6d5c8412017-11-29 11:02:32 +000060#include <pthread_np.h>
Pieter Baauwcaa6a1b2015-09-17 21:26:40 +020061#endif
David Carlier5e4c8e22019-09-13 05:12:58 +010062#ifdef __APPLE__
63#include <mach/mach_types.h>
64#include <mach/thread_act.h>
65#include <mach/thread_policy.h>
66#endif
Willy Tarreaufc6c0322012-11-16 16:12:27 +010067#endif
Willy Tarreaubaaee002006-06-26 02:48:02 +020068
Willy Tarreau636848a2019-04-15 19:38:50 +020069#if defined(USE_PRCTL)
70#include <sys/prctl.h>
71#endif
72
Willy Tarreaubaaee002006-06-26 02:48:02 +020073#ifdef DEBUG_FULL
74#include <assert.h>
75#endif
Tim Duesterhusd6942c82017-11-20 15:58:35 +010076#if defined(USE_SYSTEMD)
77#include <systemd/sd-daemon.h>
78#endif
Willy Tarreaubaaee002006-06-26 02:48:02 +020079
Willy Tarreau6c3a6812020-03-06 18:57:15 +010080#include <import/sha1.h>
81
Willy Tarreaub2551052020-06-09 09:07:15 +020082#include <haproxy/acl.h>
Amaury Denoyelle68fd7e42021-03-25 17:15:52 +010083#include <haproxy/action.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020084#include <haproxy/activity.h>
85#include <haproxy/api.h>
86#include <haproxy/arg.h>
87#include <haproxy/auth.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020088#include <haproxy/base64.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020089#include <haproxy/capture-t.h>
Amaury Denoyelle5a6926d2021-03-30 17:34:24 +020090#include <haproxy/cfgdiag.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020091#include <haproxy/cfgparse.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020092#include <haproxy/chunk.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020093#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020094#include <haproxy/connection.h>
Amaury Denoyellea6f9c5d2021-04-23 16:58:08 +020095#ifdef USE_CPU_AFFINITY
Amaury Denoyelle982fb532021-04-21 18:39:58 +020096#include <haproxy/cpuset.h>
Amaury Denoyellea6f9c5d2021-04-23 16:58:08 +020097#endif
Willy Tarreaueb92deb2020-06-04 10:53:16 +020098#include <haproxy/dns.h>
Willy Tarreau2741c8c2020-06-02 11:28:02 +020099#include <haproxy/dynbuf.h>
Willy Tarreau8d366972020-05-27 16:10:29 +0200100#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +0200101#include <haproxy/fd.h>
Willy Tarreauc7babd82020-06-04 21:29:29 +0200102#include <haproxy/filters.h>
Willy Tarreaub2551052020-06-09 09:07:15 +0200103#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +0200104#include <haproxy/hlua.h>
Willy Tarreauc761f842020-06-04 11:40:28 +0200105#include <haproxy/http_rules.h>
Willy Tarreau853b2972020-05-27 18:01:47 +0200106#include <haproxy/list.h>
Willy Tarreau213e9902020-06-04 14:58:24 +0200107#include <haproxy/listener.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +0200108#include <haproxy/log.h>
Willy Tarreaub5abe5b2020-06-04 14:07:37 +0200109#include <haproxy/mworker.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +0200110#include <haproxy/namespace.h>
Willy Tarreau6131d6a2020-06-02 16:48:09 +0200111#include <haproxy/net_helper.h>
Willy Tarreau6019fab2020-05-27 16:26:00 +0200112#include <haproxy/openssl-compat.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +0200113#include <haproxy/pattern.h>
Willy Tarreau3c2a7c22020-06-04 18:38:21 +0200114#include <haproxy/peers.h>
Willy Tarreaub2551052020-06-09 09:07:15 +0200115#include <haproxy/pool.h>
116#include <haproxy/protocol.h>
Willy Tarreaubf3b06b2020-08-26 10:23:40 +0200117#include <haproxy/proto_tcp.h>
Willy Tarreaua264d962020-06-04 22:29:18 +0200118#include <haproxy/proxy.h>
Willy Tarreau7cd8b6e2020-06-02 17:32:26 +0200119#include <haproxy/regex.h>
Willy Tarreaub2551052020-06-09 09:07:15 +0200120#include <haproxy/sample.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +0200121#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +0200122#include <haproxy/session.h>
Willy Tarreau3727a8a2020-06-04 17:37:26 +0200123#include <haproxy/signal.h>
Willy Tarreau063d47d2020-08-28 16:29:53 +0200124#include <haproxy/sock.h>
Willy Tarreau25140cc2020-08-28 15:40:33 +0200125#include <haproxy/sock_inet.h>
Willy Tarreau209108d2020-06-04 20:30:20 +0200126#include <haproxy/ssl_sock.h>
Amaury Denoyelleee63d4b2020-10-05 11:49:42 +0200127#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +0200128#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +0200129#include <haproxy/task.h>
Willy Tarreau3f567e42020-05-28 15:29:19 +0200130#include <haproxy/thread.h>
Willy Tarreaub2551052020-06-09 09:07:15 +0200131#include <haproxy/time.h>
132#include <haproxy/tools.h>
133#include <haproxy/uri_auth-t.h>
Willy Tarreaua1718922020-06-04 16:25:31 +0200134#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +0200135#include <haproxy/version.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +0200136
Willy Tarreaubaaee002006-06-26 02:48:02 +0200137
Willy Tarreau7b5654f2019-03-29 21:30:17 +0100138/* array of init calls for older platforms */
139DECLARE_INIT_STAGES;
140
Willy Tarreauf4596402021-04-10 16:53:05 +0200141/* create a read_mostly section to hold variables which are accessed a lot
142 * but which almost never change. The purpose is to isolate them in their
143 * own cache lines where they don't risk to be perturbated by write accesses
144 * to neighbor variables. We need to create an empty aligned variable for
145 * this. The fact that the variable is of size zero means that it will be
146 * eliminated at link time if no other variable uses it, but alignment will
147 * be respected.
148 */
149empty_t __read_mostly_align HA_SECTION("read_mostly") ALIGNED(64);
150
Willy Tarreauf0d3b732021-05-06 16:30:32 +0200151#ifdef BUILD_FEATURES
152const char *build_features = BUILD_FEATURES;
153#else
154const char *build_features = "";
155#endif
156
Willy Tarreau477ecd82010-01-03 21:12:30 +0100157/* list of config files */
158static struct list cfg_cfgfiles = LIST_HEAD_INIT(cfg_cfgfiles);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200159int pid; /* current process id */
Willy Tarreau28156642007-11-26 16:13:36 +0100160int relative_pid = 1; /* process id starting at 1 */
Willy Tarreaubaaee002006-06-26 02:48:02 +0200161
Willy Tarreauf8ea00e2020-03-12 17:24:53 +0100162volatile unsigned long sleeping_thread_mask = 0; /* Threads that are about to sleep in poll() */
Willy Tarreau4b3f27b2020-03-12 17:28:01 +0100163volatile unsigned long stopping_thread_mask = 0; /* Threads acknowledged stopping */
Willy Tarreauf8ea00e2020-03-12 17:24:53 +0100164
Willy Tarreaubaaee002006-06-26 02:48:02 +0200165/* global options */
166struct global global = {
Cyril Bonté203ec5a2017-03-23 22:44:13 +0100167 .hard_stop_after = TICK_ETERNITY,
Amaury Denoyelle0f50cb92021-03-26 18:50:33 +0100168 .numa_cpu_mapping = 1,
Willy Tarreau149ab772019-01-26 14:27:06 +0100169 .nbthread = 0,
William Lallemand5f232402012-04-05 18:02:55 +0200170 .req_count = 0,
William Lallemand0f99e342011-10-12 17:50:54 +0200171 .logsrvs = LIST_HEAD_INIT(global.logsrvs),
William Lallemand9d5f5482012-11-07 16:12:57 +0100172 .maxzlibmem = 0,
William Lallemandd85f9172012-11-09 17:05:39 +0100173 .comp_rate_lim = 0,
Emeric Brun850efd52014-01-29 12:24:34 +0100174 .ssl_server_verify = SSL_SERVER_VERIFY_REQUIRED,
Emeric Bruned760922010-10-22 17:59:25 +0200175 .unix_bind = {
176 .ux = {
177 .uid = -1,
178 .gid = -1,
179 .mode = 0,
180 }
181 },
Willy Tarreau27a674e2009-08-17 07:23:33 +0200182 .tune = {
Willy Tarreau7ac908b2019-02-27 12:02:18 +0100183 .options = GTUNE_LISTENER_MQ,
Willy Tarreauc77d3642018-12-12 06:19:42 +0100184 .bufsize = (BUFSIZE + 2*sizeof(void *) - 1) & -(2*sizeof(void *)),
Christopher Faulet546c4692020-01-22 14:31:21 +0100185 .maxrewrite = MAXREWRITE,
Willy Tarreaua24adf02014-11-27 01:11:56 +0100186 .reserved_bufs = RESERVED_BUFS,
Willy Tarreauf3045d22015-04-29 16:24:50 +0200187 .pattern_cache = DEFAULT_PAT_LRU_SIZE,
Olivier Houchard88698d92019-04-16 19:07:22 +0200188 .pool_low_ratio = 20,
189 .pool_high_ratio = 25,
Christopher Faulet41ba36f2019-07-19 09:36:45 +0200190 .max_http_hdr = MAX_HTTP_HDR,
Emeric Brunfc32aca2012-09-03 12:10:29 +0200191#ifdef USE_OPENSSL
Emeric Brun46635772012-11-14 11:32:56 +0100192 .sslcachesize = SSLCACHESIZE,
Emeric Brunfc32aca2012-09-03 12:10:29 +0200193#endif
William Lallemandf3747832012-11-09 12:33:10 +0100194 .comp_maxlevel = 1,
Willy Tarreau7e312732014-02-12 16:35:14 +0100195#ifdef DEFAULT_IDLE_TIMER
196 .idle_timer = DEFAULT_IDLE_TIMER,
197#else
198 .idle_timer = 1000, /* 1 second */
199#endif
Willy Tarreau27a674e2009-08-17 07:23:33 +0200200 },
Emeric Brun76d88952012-10-05 15:47:31 +0200201#ifdef USE_OPENSSL
202#ifdef DEFAULT_MAXSSLCONN
Willy Tarreau403edff2012-09-06 11:58:37 +0200203 .maxsslconn = DEFAULT_MAXSSLCONN,
204#endif
Emeric Brun76d88952012-10-05 15:47:31 +0200205#endif
Willy Tarreaubaaee002006-06-26 02:48:02 +0200206 /* others NULL OK */
207};
208
209/*********************************************************************/
210
211int stopping; /* non zero means stopping in progress */
Cyril Bonté203ec5a2017-03-23 22:44:13 +0100212int killed; /* non zero means a hard-stop is triggered */
Willy Tarreauaf7ad002010-08-31 15:39:26 +0200213int jobs = 0; /* number of active jobs (conns, listeners, active tasks, ...) */
William Lallemanda7199262018-11-16 16:57:20 +0100214int unstoppable_jobs = 0; /* number of active jobs that can't be stopped during a soft stop */
Willy Tarreau199ad242018-11-05 16:31:22 +0100215int active_peers = 0; /* number of active peers (connection attempts and connected) */
Willy Tarreau2d372c22018-11-05 17:12:27 +0100216int connected_peers = 0; /* number of connected peers (verified ones) */
Willy Tarreaubaaee002006-06-26 02:48:02 +0200217
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500218/* Here we store information about the pids of the processes we may pause
Willy Tarreaubaaee002006-06-26 02:48:02 +0200219 * or kill. We will send them a signal every 10 ms until we can bind to all
220 * our ports. With 200 retries, that's about 2 seconds.
221 */
222#define MAX_START_RETRIES 200
Willy Tarreaubaaee002006-06-26 02:48:02 +0200223static int *oldpids = NULL;
224static int oldpids_sig; /* use USR1 or TERM */
225
Olivier Houchardf73629d2017-04-05 22:33:04 +0200226/* Path to the unix socket we use to retrieve listener sockets from the old process */
227static const char *old_unixsocket;
228
William Lallemand85b0bd92017-06-01 17:38:53 +0200229static char *cur_unixsocket = NULL;
230
William Lallemandcb11fd22017-06-01 17:38:52 +0200231int atexit_flag = 0;
232
Willy Tarreaubb545b42010-08-25 12:58:59 +0200233int nb_oldpids = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200234const int zero = 0;
235const int one = 1;
Alexandre Cassen87ea5482007-10-11 20:48:58 +0200236const struct linger nolinger = { .l_onoff = 1, .l_linger = 0 };
Willy Tarreaubaaee002006-06-26 02:48:02 +0200237
Willy Tarreau1d21e0a2010-03-12 21:58:54 +0100238char hostname[MAX_HOSTNAME_LEN];
Dragan Dosen4f014152020-06-18 16:56:47 +0200239char *localpeer = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200240
William Lallemand00417412020-06-05 14:08:41 +0200241static char **old_argv = NULL; /* previous argv but cleaned up */
William Lallemand73b85e72017-06-01 17:38:51 +0200242
William Lallemandbc193052018-09-11 10:06:26 +0200243struct list proc_list = LIST_HEAD_INIT(proc_list);
244
245int master = 0; /* 1 if in master, 0 if in child */
Willy Tarreaubf696402019-03-01 10:09:28 +0100246unsigned int rlim_fd_cur_at_boot = 0;
247unsigned int rlim_fd_max_at_boot = 0;
William Lallemandbc193052018-09-11 10:06:26 +0200248
Willy Tarreau6c3a6812020-03-06 18:57:15 +0100249/* per-boot randomness */
250unsigned char boot_seed[20]; /* per-boot random seed (160 bits initially) */
251
William Lallemandb3f2be32018-09-11 10:06:18 +0200252static void *run_thread_poll_loop(void *data);
253
Willy Tarreauff055502014-04-28 22:27:06 +0200254/* bitfield of a few warnings to emit just once (WARN_*) */
255unsigned int warned = 0;
256
Amaury Denoyelle484454d2021-05-05 16:18:45 +0200257/* set if experimental features have been used for the current process */
258static unsigned int tainted = 0;
259
Amaury Denoyelled2e53cd2021-05-06 16:21:39 +0200260unsigned int experimental_directives_allowed = 0;
261
262int check_kw_experimental(struct cfg_keyword *kw, const char *file, int linenum,
263 char **errmsg)
264{
265 if (kw->flags & KWF_EXPERIMENTAL) {
266 if (!experimental_directives_allowed) {
Amaury Denoyelle86c1d0f2021-05-07 15:07:21 +0200267 memprintf(errmsg, "parsing [%s:%d] : '%s' directive is experimental, must be allowed via a global 'expose-experimental-directives'",
Amaury Denoyelled2e53cd2021-05-06 16:21:39 +0200268 file, linenum, kw->kw);
269 return 1;
270 }
271 mark_tainted(TAINTED_CONFIG_EXP_KW_DECLARED);
272 }
273
274 return 0;
275}
276
William Lallemande7361152018-10-26 14:47:36 +0200277/* master CLI configuration (-S flag) */
278struct list mworker_cli_conf = LIST_HEAD_INIT(mworker_cli_conf);
Willy Tarreaucdb737e2016-12-21 18:43:10 +0100279
280/* These are strings to be reported in the output of "haproxy -vv". They may
281 * either be constants (in which case must_free must be zero) or dynamically
282 * allocated strings to pass to free() on exit, and in this case must_free
283 * must be non-zero.
284 */
285struct list build_opts_list = LIST_HEAD_INIT(build_opts_list);
286struct build_opts_str {
287 struct list list;
288 const char *str;
289 int must_free;
290};
291
Willy Tarreaubaaee002006-06-26 02:48:02 +0200292/*********************************************************************/
293/* general purpose functions ***************************************/
294/*********************************************************************/
295
Willy Tarreaucdb737e2016-12-21 18:43:10 +0100296/* used to register some build option strings at boot. Set must_free to
297 * non-zero if the string must be freed upon exit.
298 */
299void hap_register_build_opts(const char *str, int must_free)
300{
301 struct build_opts_str *b;
302
303 b = calloc(1, sizeof(*b));
304 if (!b) {
305 fprintf(stderr, "out of memory\n");
306 exit(1);
307 }
308 b->str = str;
309 b->must_free = must_free;
Willy Tarreau2b718102021-04-21 07:32:39 +0200310 LIST_APPEND(&build_opts_list, &b->list);
Willy Tarreaucdb737e2016-12-21 18:43:10 +0100311}
312
Willy Tarreaua43dfda2021-05-06 07:43:35 +0200313#define VERSION_MAX_ELTS 7
314
315/* This function splits an haproxy version string into an array of integers.
316 * The syntax of the supported version string is the following:
317 *
318 * <a>[.<b>[.<c>[.<d>]]][-{dev,pre,rc}<f>][-*][-<g>]
319 *
320 * This validates for example:
321 * 1.2.1-pre2, 1.2.1, 1.2.10.1, 1.3.16-rc1, 1.4-dev3, 1.5-dev18, 1.5-dev18-43
322 * 2.4-dev18-f6818d-20
323 *
324 * The result is set in a array of <VERSION_MAX_ELTS> elements. Each letter has
325 * one fixed place in the array. The tags take a numeric value called <e> which
326 * defaults to 3. "dev" is 1, "rc" and "pre" are 2. Numbers not encountered are
327 * considered as zero (henxe 1.5 and 1.5.0 are the same).
328 *
329 * The resulting values are:
330 * 1.2.1-pre2 1, 2, 1, 0, 2, 2, 0
331 * 1.2.1 1, 2, 1, 0, 3, 0, 0
332 * 1.2.10.1 1, 2, 10, 1, 3, 0, 0
333 * 1.3.16-rc1 1, 3, 16, 0, 2, 1, 0
334 * 1.4-dev3 1, 4, 0, 0, 1, 3, 0
335 * 1.5-dev18 1, 5, 0, 0, 1, 18, 0
336 * 1.5-dev18-43 1, 5, 0, 0, 1, 18, 43
337 * 2.4-dev18-f6818d-20 2, 4, 0, 0, 1, 18, 20
338 *
339 * The function returns non-zero if the conversion succeeded, or zero if it
340 * failed.
341 */
342int split_version(const char *version, unsigned int *value)
343{
344 const char *p, *s;
345 char *error;
346 int nelts;
347
348 /* Initialize array with zeroes */
349 for (nelts = 0; nelts < VERSION_MAX_ELTS; nelts++)
350 value[nelts] = 0;
351 value[4] = 3;
352
353 p = version;
354
355 /* If the version number is empty, return false */
356 if (*p == '\0')
357 return 0;
358
359 /* Convert first number <a> */
360 value[0] = strtol(p, &error, 10);
361 p = error + 1;
362 if (*error == '\0')
363 return 1;
364 if (*error == '-')
365 goto split_version_tag;
366 if (*error != '.')
367 return 0;
368
369 /* Convert first number <b> */
370 value[1] = strtol(p, &error, 10);
371 p = error + 1;
372 if (*error == '\0')
373 return 1;
374 if (*error == '-')
375 goto split_version_tag;
376 if (*error != '.')
377 return 0;
378
379 /* Convert first number <c> */
380 value[2] = strtol(p, &error, 10);
381 p = error + 1;
382 if (*error == '\0')
383 return 1;
384 if (*error == '-')
385 goto split_version_tag;
386 if (*error != '.')
387 return 0;
388
389 /* Convert first number <d> */
390 value[3] = strtol(p, &error, 10);
391 p = error + 1;
392 if (*error == '\0')
393 return 1;
394 if (*error != '-')
395 return 0;
396
397 split_version_tag:
398 /* Check for commit number */
399 if (*p >= '0' && *p <= '9')
400 goto split_version_commit;
401
402 /* Read tag */
403 if (strncmp(p, "dev", 3) == 0) { value[4] = 1; p += 3; }
404 else if (strncmp(p, "rc", 2) == 0) { value[4] = 2; p += 2; }
405 else if (strncmp(p, "pre", 3) == 0) { value[4] = 2; p += 3; }
406 else
407 goto split_version_commit;
408
409 /* Convert tag number */
410 value[5] = strtol(p, &error, 10);
411 p = error + 1;
412 if (*error == '\0')
413 return 1;
414 if (*error != '-')
415 return 0;
416
417 split_version_commit:
418 /* Search the last "-" */
419 s = strrchr(p, '-');
420 if (s) {
421 s++;
422 if (*s == '\0')
423 return 0;
424 value[6] = strtol(s, &error, 10);
425 if (*error != '\0')
426 value[6] = 0;
427 return 1;
428 }
429
430 /* convert the version */
431 value[6] = strtol(p, &error, 10);
432 if (*error != '\0')
433 value[6] = 0;
434
435 return 1;
436}
437
438/* This function compares the current haproxy version with an arbitrary version
439 * string. It returns:
440 * -1 : the version in argument is older than the current haproxy version
441 * 0 : the version in argument is the same as the current haproxy version
442 * 1 : the version in argument is newer than the current haproxy version
443 *
444 * Or some errors:
445 * -2 : the current haproxy version is not parsable
446 * -3 : the version in argument is not parsable
447 */
448int compare_current_version(const char *version)
449{
450 unsigned int loc[VERSION_MAX_ELTS];
451 unsigned int mod[VERSION_MAX_ELTS];
452 int i;
453
454 /* split versions */
455 if (!split_version(haproxy_version, loc))
456 return -2;
457 if (!split_version(version, mod))
458 return -3;
459
460 /* compare versions */
461 for (i = 0; i < VERSION_MAX_ELTS; i++) {
462 if (mod[i] < loc[i])
463 return -1;
464 else if (mod[i] > loc[i])
465 return 1;
466 }
467 return 0;
468}
469
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100470static void display_version()
Willy Tarreaubaaee002006-06-26 02:48:02 +0200471{
Tim Duesterhusdfad6a42020-04-18 16:02:47 +0200472 struct utsname utsname;
473
Willy Tarreaua5357cd2021-05-09 06:14:25 +0200474 printf("HAProxy version %s %s - https://haproxy.org/\n"
Willy Tarreau08dd2022019-11-21 18:07:30 +0100475 PRODUCT_STATUS "\n", haproxy_version, haproxy_date);
Willy Tarreau47479eb2019-11-21 18:48:20 +0100476
477 if (strlen(PRODUCT_URL_BUGS) > 0) {
478 char base_version[20];
479 int dots = 0;
480 char *del;
481
482 /* only retrieve the base version without distro-specific extensions */
483 for (del = haproxy_version; *del; del++) {
484 if (*del == '.')
485 dots++;
486 else if (*del < '0' || *del > '9')
487 break;
488 }
489
490 strlcpy2(base_version, haproxy_version, del - haproxy_version + 1);
491 if (dots < 2)
492 printf("Known bugs: https://github.com/haproxy/haproxy/issues?q=is:issue+is:open\n");
493 else
494 printf("Known bugs: " PRODUCT_URL_BUGS "\n", base_version);
495 }
Tim Duesterhusdfad6a42020-04-18 16:02:47 +0200496
497 if (uname(&utsname) == 0) {
498 printf("Running on: %s %s %s %s\n", utsname.sysname, utsname.release, utsname.version, utsname.machine);
499 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200500}
501
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100502static void display_build_opts()
Willy Tarreau7b066db2007-12-02 11:28:59 +0100503{
Willy Tarreaucdb737e2016-12-21 18:43:10 +0100504 struct build_opts_str *item;
505
Willy Tarreau7b066db2007-12-02 11:28:59 +0100506 printf("Build options :"
507#ifdef BUILD_TARGET
Willy Tarreau9f2b7302008-01-02 20:48:34 +0100508 "\n TARGET = " BUILD_TARGET
Willy Tarreau7b066db2007-12-02 11:28:59 +0100509#endif
510#ifdef BUILD_CPU
Willy Tarreau9f2b7302008-01-02 20:48:34 +0100511 "\n CPU = " BUILD_CPU
Willy Tarreau7b066db2007-12-02 11:28:59 +0100512#endif
513#ifdef BUILD_CC
Willy Tarreau9f2b7302008-01-02 20:48:34 +0100514 "\n CC = " BUILD_CC
515#endif
516#ifdef BUILD_CFLAGS
517 "\n CFLAGS = " BUILD_CFLAGS
Willy Tarreau7b066db2007-12-02 11:28:59 +0100518#endif
Willy Tarreau9f2b7302008-01-02 20:48:34 +0100519#ifdef BUILD_OPTIONS
520 "\n OPTIONS = " BUILD_OPTIONS
Willy Tarreau7b066db2007-12-02 11:28:59 +0100521#endif
Tim Duesterhusc8d19702020-11-21 18:07:59 +0100522#ifdef BUILD_DEBUG
523 "\n DEBUG = " BUILD_DEBUG
524#endif
Willy Tarreau7728ed32019-03-27 13:20:08 +0100525#ifdef BUILD_FEATURES
526 "\n\nFeature list : " BUILD_FEATURES
527#endif
Willy Tarreau27a674e2009-08-17 07:23:33 +0200528 "\n\nDefault settings :"
Willy Tarreauca783d42019-03-13 10:03:07 +0100529 "\n bufsize = %d, maxrewrite = %d, maxpollevents = %d"
Willy Tarreau27a674e2009-08-17 07:23:33 +0200530 "\n\n",
Willy Tarreauca783d42019-03-13 10:03:07 +0100531 BUFSIZE, MAXREWRITE, MAX_POLL_EVENTS);
Willy Tarreaube5b6852009-10-03 18:57:08 +0200532
Willy Tarreaucdb737e2016-12-21 18:43:10 +0100533 list_for_each_entry(item, &build_opts_list, list) {
534 puts(item->str);
535 }
536
Krzysztof Piotr Oledzki96105042010-01-29 17:50:44 +0100537 putchar('\n');
538
Willy Tarreaube5b6852009-10-03 18:57:08 +0200539 list_pollers(stdout);
540 putchar('\n');
Christopher Faulet98d9fe22018-04-10 14:37:32 +0200541 list_mux_proto(stdout);
542 putchar('\n');
Willy Tarreau679bba12019-03-19 08:08:10 +0100543 list_services(stdout);
544 putchar('\n');
Christopher Fauletb3f4e142016-03-07 12:46:38 +0100545 list_filters(stdout);
546 putchar('\n');
Willy Tarreau7b066db2007-12-02 11:28:59 +0100547}
548
Willy Tarreaubaaee002006-06-26 02:48:02 +0200549/*
550 * This function prints the command line usage and exits
551 */
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100552static void usage(char *name)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200553{
554 display_version();
555 fprintf(stderr,
Maxime de Roucy379d9c72016-05-13 23:52:56 +0200556 "Usage : %s [-f <cfgfile|cfgdir>]* [ -vdV"
Willy Tarreaubaaee002006-06-26 02:48:02 +0200557 "D ] [ -n <maxconn> ] [ -N <maxpconn> ]\n"
Willy Tarreaua088d312015-10-08 11:58:48 +0200558 " [ -p <pidfile> ] [ -m <max megs> ] [ -C <dir> ] [-- <cfgfile>*]\n"
Willy Tarreau7b066db2007-12-02 11:28:59 +0100559 " -v displays version ; -vv shows known build options.\n"
Willy Tarreaubaaee002006-06-26 02:48:02 +0200560 " -d enters debug mode ; -db only disables background mode.\n"
Willy Tarreau6e064432012-05-08 15:40:42 +0200561 " -dM[<byte>] poisons memory with <byte> (defaults to 0x50)\n"
Willy Tarreaubaaee002006-06-26 02:48:02 +0200562 " -V enters verbose mode (disables quiet mode)\n"
Willy Tarreau576132e2011-09-10 19:26:56 +0200563 " -D goes daemon ; -C changes to <dir> before loading files.\n"
William Lallemand095ba4c2017-06-01 17:38:50 +0200564 " -W master-worker mode.\n"
Tim Duesterhusd6942c82017-11-20 15:58:35 +0100565#if defined(USE_SYSTEMD)
566 " -Ws master-worker mode with systemd notify support.\n"
567#endif
Willy Tarreaubaaee002006-06-26 02:48:02 +0200568 " -q quiet mode : don't display messages\n"
Willy Tarreau5d01a632009-06-22 16:02:30 +0200569 " -c check mode : only check config files and exit\n"
Maximilian Maderfc0cceb2021-06-06 00:50:22 +0200570 " -cc check condition : evaluate a condition and exit\n"
Willy Tarreauca783d42019-03-13 10:03:07 +0100571 " -n sets the maximum total # of connections (uses ulimit -n)\n"
Willy Tarreaubaaee002006-06-26 02:48:02 +0200572 " -m limits the usable amount of memory (in MB)\n"
573 " -N sets the default, per-proxy maximum # of connections (%d)\n"
Emeric Brun2b920a12010-09-23 18:30:22 +0200574 " -L set local peer name (default to hostname)\n"
Willy Tarreaubaaee002006-06-26 02:48:02 +0200575 " -p writes pids of all children to this file\n"
Willy Tarreaue5733232019-05-22 19:24:06 +0200576#if defined(USE_EPOLL)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200577 " -de disables epoll() usage even when available\n"
578#endif
Willy Tarreaue5733232019-05-22 19:24:06 +0200579#if defined(USE_KQUEUE)
Willy Tarreau1e63130a2007-04-09 12:03:06 +0200580 " -dk disables kqueue() usage even when available\n"
581#endif
Willy Tarreaue5733232019-05-22 19:24:06 +0200582#if defined(USE_EVPORTS)
Emmanuel Hocdet0ba4f482019-04-08 16:53:32 +0000583 " -dv disables event ports usage even when available\n"
584#endif
Willy Tarreaue5733232019-05-22 19:24:06 +0200585#if defined(USE_POLL)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200586 " -dp disables poll() usage even when available\n"
587#endif
Willy Tarreaue5733232019-05-22 19:24:06 +0200588#if defined(USE_LINUX_SPLICE)
Willy Tarreau3ab68cf2009-01-25 16:03:28 +0100589 " -dS disables splice usage (broken on old kernels)\n"
590#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200591#if defined(USE_GETADDRINFO)
592 " -dG disables getaddrinfo() usage\n"
593#endif
Lukas Tribusa0bcbdc2016-09-12 21:42:20 +0000594#if defined(SO_REUSEPORT)
595 " -dR disables SO_REUSEPORT usage\n"
596#endif
Willy Tarreau3eed10e2016-11-07 21:03:16 +0100597 " -dr ignores server address resolution failures\n"
Emeric Brun850efd52014-01-29 12:24:34 +0100598 " -dV disables SSL verify on servers side\n"
Willy Tarreau3eb10b82020-04-15 16:42:39 +0200599 " -dW fails if any warning is emitted\n"
Amaury Denoyelle7b01a8d2021-03-29 10:29:07 +0200600 " -dD diagnostic mode : warn about suspicious configuration statements\n"
Willy Tarreauc6ca1aa2015-10-08 11:32:32 +0200601 " -sf/-st [pid ]* finishes/terminates old pids.\n"
Olivier Houchardf73629d2017-04-05 22:33:04 +0200602 " -x <unix_socket> get listening sockets from a unix socket\n"
William Lallemand63329e32019-06-13 17:03:37 +0200603 " -S <bind>[,<bind options>...] new master CLI\n"
Willy Tarreaubaaee002006-06-26 02:48:02 +0200604 "\n",
Willy Tarreauca783d42019-03-13 10:03:07 +0100605 name, cfg_maxpconn);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200606 exit(1);
607}
608
609
610
611/*********************************************************************/
612/* more specific functions ***************************************/
613/*********************************************************************/
614
William Lallemand73b85e72017-06-01 17:38:51 +0200615/* sends the signal <sig> to all pids found in <oldpids>. Returns the number of
616 * pids the signal was correctly delivered to.
617 */
William Lallemande25473c2019-04-01 11:29:56 +0200618int tell_old_pids(int sig)
William Lallemand73b85e72017-06-01 17:38:51 +0200619{
620 int p;
621 int ret = 0;
622 for (p = 0; p < nb_oldpids; p++)
623 if (kill(oldpids[p], sig) == 0)
624 ret++;
625 return ret;
626}
627
William Lallemand75ea0a02017-11-15 19:02:58 +0100628/*
William Lallemand73b85e72017-06-01 17:38:51 +0200629 * remove a pid forom the olpid array and decrease nb_oldpids
630 * return 1 pid was found otherwise return 0
631 */
632
633int delete_oldpid(int pid)
634{
635 int i;
636
637 for (i = 0; i < nb_oldpids; i++) {
638 if (oldpids[i] == pid) {
639 oldpids[i] = oldpids[nb_oldpids - 1];
640 oldpids[nb_oldpids - 1] = 0;
641 nb_oldpids--;
642 return 1;
643 }
644 }
645 return 0;
646}
647
William Lallemand85b0bd92017-06-01 17:38:53 +0200648
649static void get_cur_unixsocket()
650{
651 /* if -x was used, try to update the stat socket if not available anymore */
Willy Tarreau4975d142021-03-13 11:00:33 +0100652 if (global.cli_fe) {
William Lallemand85b0bd92017-06-01 17:38:53 +0200653 struct bind_conf *bind_conf;
654
655 /* pass through all stats socket */
Willy Tarreau4975d142021-03-13 11:00:33 +0100656 list_for_each_entry(bind_conf, &global.cli_fe->conf.bind, by_fe) {
William Lallemand85b0bd92017-06-01 17:38:53 +0200657 struct listener *l;
658
659 list_for_each_entry(l, &bind_conf->listeners, by_bind) {
660
Willy Tarreau37159062020-08-27 07:48:42 +0200661 if (l->rx.addr.ss_family == AF_UNIX &&
William Lallemand85b0bd92017-06-01 17:38:53 +0200662 (bind_conf->level & ACCESS_FD_LISTENERS)) {
663 const struct sockaddr_un *un;
664
Willy Tarreau37159062020-08-27 07:48:42 +0200665 un = (struct sockaddr_un *)&l->rx.addr;
William Lallemand85b0bd92017-06-01 17:38:53 +0200666 /* priority to old_unixsocket */
667 if (!cur_unixsocket) {
668 cur_unixsocket = strdup(un->sun_path);
669 } else {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +0100670 if (old_unixsocket && strcmp(un->sun_path, old_unixsocket) == 0) {
William Lallemand85b0bd92017-06-01 17:38:53 +0200671 free(cur_unixsocket);
672 cur_unixsocket = strdup(old_unixsocket);
673 return;
674 }
675 }
676 }
677 }
678 }
679 }
680 if (!cur_unixsocket && old_unixsocket)
681 cur_unixsocket = strdup(old_unixsocket);
682}
683
William Lallemand73b85e72017-06-01 17:38:51 +0200684/*
685 * When called, this function reexec haproxy with -sf followed by current
Joseph Herlant03420902018-11-15 10:41:50 -0800686 * children PIDs and possibly old children PIDs if they didn't leave yet.
William Lallemand73b85e72017-06-01 17:38:51 +0200687 */
William Lallemanda57b7e32018-12-14 21:11:31 +0100688void mworker_reload()
William Lallemand73b85e72017-06-01 17:38:51 +0200689{
William Lallemand00417412020-06-05 14:08:41 +0200690 char **next_argv = NULL;
691 int old_argc = 0; /* previous number of argument */
William Lallemand73b85e72017-06-01 17:38:51 +0200692 int next_argc = 0;
William Lallemand00417412020-06-05 14:08:41 +0200693 int i = 0;
William Lallemand73b85e72017-06-01 17:38:51 +0200694 char *msg = NULL;
Willy Tarreau8dca1952019-03-01 10:21:55 +0100695 struct rlimit limit;
William Lallemand7c756a82018-11-26 11:53:40 +0100696 struct per_thread_deinit_fct *ptdf;
William Lallemand73b85e72017-06-01 17:38:51 +0200697
698 mworker_block_signals();
Tim Duesterhusd6942c82017-11-20 15:58:35 +0100699#if defined(USE_SYSTEMD)
700 if (global.tune.options & GTUNE_USE_SYSTEMD)
701 sd_notify(0, "RELOADING=1");
702#endif
William Lallemand73b85e72017-06-01 17:38:51 +0200703 setenv("HAPROXY_MWORKER_REEXEC", "1", 1);
704
William Lallemandbc193052018-09-11 10:06:26 +0200705 mworker_proc_list_to_env(); /* put the children description in the env */
706
William Lallemand7c756a82018-11-26 11:53:40 +0100707 /* during the reload we must ensure that every FDs that can't be
708 * reuse (ie those that are not referenced in the proc_list)
709 * are closed or they will leak. */
710
711 /* close the listeners FD */
712 mworker_cli_proxy_stop();
William Lallemand16866672019-06-24 17:40:48 +0200713
714 if (getenv("HAPROXY_MWORKER_WAIT_ONLY") == NULL) {
715 /* close the poller FD and the thread waker pipe FD */
716 list_for_each_entry(ptdf, &per_thread_deinit_list, list)
717 ptdf->fct();
718 if (fdtab)
719 deinit_pollers();
720 }
Ilya Shipitsin98a9e1b2021-02-19 23:42:53 +0500721#ifdef HAVE_SSL_RAND_KEEP_RANDOM_DEVICES_OPEN
William Lallemand5fdb5b32019-10-15 14:04:08 +0200722 /* close random device FDs */
723 RAND_keep_random_devices_open(0);
Rob Allen56996da2019-05-03 09:11:32 +0100724#endif
William Lallemand7c756a82018-11-26 11:53:40 +0100725
Willy Tarreau8dca1952019-03-01 10:21:55 +0100726 /* restore the initial FD limits */
727 limit.rlim_cur = rlim_fd_cur_at_boot;
728 limit.rlim_max = rlim_fd_max_at_boot;
729 if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
730 getrlimit(RLIMIT_NOFILE, &limit);
731 ha_warning("Failed to restore initial FD limits (cur=%u max=%u), using cur=%u max=%u\n",
732 rlim_fd_cur_at_boot, rlim_fd_max_at_boot,
733 (unsigned int)limit.rlim_cur, (unsigned int)limit.rlim_max);
734 }
735
William Lallemand73b85e72017-06-01 17:38:51 +0200736 /* compute length */
William Lallemand00417412020-06-05 14:08:41 +0200737 while (old_argv[old_argc])
738 old_argc++;
William Lallemand73b85e72017-06-01 17:38:51 +0200739
William Lallemand85b0bd92017-06-01 17:38:53 +0200740 /* 1 for haproxy -sf, 2 for -x /socket */
William Lallemandaba7f8b2021-04-21 16:55:34 +0200741 next_argv = calloc(old_argc + 1 + 2 + mworker_child_nb() + 1,
Tim Duesterhuse52b6e52020-09-12 20:26:43 +0200742 sizeof(*next_argv));
William Lallemand73b85e72017-06-01 17:38:51 +0200743 if (next_argv == NULL)
744 goto alloc_error;
745
William Lallemand00417412020-06-05 14:08:41 +0200746 /* copy the program name */
747 next_argv[next_argc++] = old_argv[0];
748
749 /* insert the new options just after argv[0] in case we have a -- */
750
William Lallemand73b85e72017-06-01 17:38:51 +0200751 /* add -sf <PID>* to argv */
William Lallemand3f128872019-04-01 11:29:59 +0200752 if (mworker_child_nb() > 0) {
753 struct mworker_proc *child;
754
William Lallemand73b85e72017-06-01 17:38:51 +0200755 next_argv[next_argc++] = "-sf";
William Lallemand3f128872019-04-01 11:29:59 +0200756
757 list_for_each_entry(child, &proc_list, list) {
William Lallemand677e2f22019-11-19 17:04:18 +0100758 if (!(child->options & (PROC_O_TYPE_WORKER|PROC_O_TYPE_PROG)) || child->pid <= -1 )
William Lallemand3f128872019-04-01 11:29:59 +0200759 continue;
William Lallemand00417412020-06-05 14:08:41 +0200760 if ((next_argv[next_argc++] = memprintf(&msg, "%d", child->pid)) == NULL)
William Lallemand73b85e72017-06-01 17:38:51 +0200761 goto alloc_error;
762 msg = NULL;
763 }
764 }
William Lallemand2bf6d622017-06-20 11:20:23 +0200765 /* add the -x option with the stat socket */
William Lallemand85b0bd92017-06-01 17:38:53 +0200766 if (cur_unixsocket) {
William Lallemand2bf6d622017-06-20 11:20:23 +0200767 next_argv[next_argc++] = "-x";
768 next_argv[next_argc++] = (char *)cur_unixsocket;
William Lallemand85b0bd92017-06-01 17:38:53 +0200769 }
770
William Lallemand00417412020-06-05 14:08:41 +0200771 /* copy the previous options */
772 for (i = 1; i < old_argc; i++)
773 next_argv[next_argc++] = old_argv[i];
774
Christopher Faulet767a84b2017-11-24 16:50:31 +0100775 ha_warning("Reexecuting Master process\n");
Willy Tarreaue0d86e22019-08-26 10:37:39 +0200776 signal(SIGPROF, SIG_IGN);
Tim Duesterhus0436ab72017-11-12 17:39:18 +0100777 execvp(next_argv[0], next_argv);
William Lallemand73b85e72017-06-01 17:38:51 +0200778
Christopher Faulet767a84b2017-11-24 16:50:31 +0100779 ha_warning("Failed to reexecute the master process [%d]: %s\n", pid, strerror(errno));
Willy Tarreau61cfdf42021-02-20 10:46:51 +0100780 ha_free(&next_argv);
William Lallemand722d4ca2017-11-15 19:02:55 +0100781 return;
782
William Lallemand73b85e72017-06-01 17:38:51 +0200783alloc_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +0100784 ha_free(&next_argv);
Joseph Herlant07a08342018-11-15 10:43:05 -0800785 ha_warning("Failed to reexecute the master process [%d]: Cannot allocate memory\n", pid);
William Lallemand73b85e72017-06-01 17:38:51 +0200786 return;
787}
788
William Lallemandb3f2be32018-09-11 10:06:18 +0200789static void mworker_loop()
790{
791
792#if defined(USE_SYSTEMD)
793 if (global.tune.options & GTUNE_USE_SYSTEMD)
794 sd_notifyf(0, "READY=1\nMAINPID=%lu", (unsigned long)getpid());
795#endif
Willy Tarreaud83b6c12019-04-18 11:31:36 +0200796 /* Busy polling makes no sense in the master :-) */
797 global.tune.options &= ~GTUNE_BUSY_POLLING;
William Lallemandb3f2be32018-09-11 10:06:18 +0200798
William Lallemandbc193052018-09-11 10:06:26 +0200799 master = 1;
800
Willy Tarreaud26c9f92019-12-11 14:24:07 +0100801 signal_unregister(SIGTTIN);
802 signal_unregister(SIGTTOU);
William Lallemand0564d412018-11-20 17:36:53 +0100803 signal_unregister(SIGUSR1);
804 signal_unregister(SIGHUP);
805 signal_unregister(SIGQUIT);
806
William Lallemandb3f2be32018-09-11 10:06:18 +0200807 signal_register_fct(SIGTERM, mworker_catch_sigterm, SIGTERM);
808 signal_register_fct(SIGUSR1, mworker_catch_sigterm, SIGUSR1);
Willy Tarreaud26c9f92019-12-11 14:24:07 +0100809 signal_register_fct(SIGTTIN, mworker_broadcast_signal, SIGTTIN);
810 signal_register_fct(SIGTTOU, mworker_broadcast_signal, SIGTTOU);
William Lallemandb3f2be32018-09-11 10:06:18 +0200811 signal_register_fct(SIGINT, mworker_catch_sigterm, SIGINT);
812 signal_register_fct(SIGHUP, mworker_catch_sighup, SIGHUP);
813 signal_register_fct(SIGUSR2, mworker_catch_sighup, SIGUSR2);
814 signal_register_fct(SIGCHLD, mworker_catch_sigchld, SIGCHLD);
815
816 mworker_unblock_signals();
817 mworker_cleanlisteners();
William Lallemand27f3fa52018-12-06 14:05:20 +0100818 mworker_cleantasks();
William Lallemandb3f2be32018-09-11 10:06:18 +0200819
William Lallemandbc193052018-09-11 10:06:26 +0200820 mworker_catch_sigchld(NULL); /* ensure we clean the children in case
821 some SIGCHLD were lost */
822
William Lallemandb3f2be32018-09-11 10:06:18 +0200823 global.nbthread = 1;
824 relative_pid = 1;
William Lallemandb3f2be32018-09-11 10:06:18 +0200825
William Lallemand2672eb92018-12-14 15:52:39 +0100826#ifdef USE_THREAD
827 tid_bit = 1;
828 all_threads_mask = 1;
829#endif
830
William Lallemandb3f2be32018-09-11 10:06:18 +0200831 jobs++; /* this is the "master" job, we want to take care of the
832 signals even if there is no listener so the poll loop don't
833 leave */
834
835 fork_poller();
Willy Tarreaub4f7cc32019-05-03 09:27:30 +0200836 run_thread_poll_loop(0);
William Lallemandb3f2be32018-09-11 10:06:18 +0200837}
William Lallemandcb11fd22017-06-01 17:38:52 +0200838
839/*
840 * Reexec the process in failure mode, instead of exiting
841 */
842void reexec_on_failure()
843{
844 if (!atexit_flag)
845 return;
846
847 setenv("HAPROXY_MWORKER_WAIT_ONLY", "1", 1);
848
Christopher Faulet767a84b2017-11-24 16:50:31 +0100849 ha_warning("Reexecuting Master process in waitpid mode\n");
William Lallemandcb11fd22017-06-01 17:38:52 +0200850 mworker_reload();
William Lallemandcb11fd22017-06-01 17:38:52 +0200851}
William Lallemand73b85e72017-06-01 17:38:51 +0200852
853
854/*
Willy Tarreaud0807c32010-08-27 18:26:11 +0200855 * upon SIGUSR1, let's have a soft stop. Note that soft_stop() broadcasts
856 * a signal zero to all subscribers. This means that it's as easy as
857 * subscribing to signal 0 to get informed about an imminent shutdown.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200858 */
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100859static void sig_soft_stop(struct sig_handler *sh)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200860{
861 soft_stop();
Willy Tarreau24f4efa2010-08-27 17:56:48 +0200862 signal_unregister_handler(sh);
Willy Tarreaubafbe012017-11-24 17:34:44 +0100863 pool_gc(NULL);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200864}
865
866/*
867 * upon SIGTTOU, we pause everything
868 */
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100869static void sig_pause(struct sig_handler *sh)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200870{
Willy Tarreau775e0012020-09-24 16:36:26 +0200871 if (protocol_pause_all() & ERR_FATAL) {
872 const char *msg = "Some proxies refused to pause, performing soft stop now.\n";
Willy Tarreau0a002df2020-10-09 19:26:27 +0200873 ha_warning("%s", msg);
874 send_log(NULL, LOG_WARNING, "%s", msg);
Willy Tarreau775e0012020-09-24 16:36:26 +0200875 soft_stop();
876 }
Willy Tarreaubafbe012017-11-24 17:34:44 +0100877 pool_gc(NULL);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200878}
879
880/*
881 * upon SIGTTIN, let's have a soft stop.
882 */
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100883static void sig_listen(struct sig_handler *sh)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200884{
Willy Tarreau775e0012020-09-24 16:36:26 +0200885 if (protocol_resume_all() & ERR_FATAL) {
886 const char *msg = "Some proxies refused to resume, probably due to a conflict on a listening port. You may want to try again after the conflicting application is stopped, otherwise a restart might be needed to resume safe operations.\n";
Willy Tarreau0a002df2020-10-09 19:26:27 +0200887 ha_warning("%s", msg);
888 send_log(NULL, LOG_WARNING, "%s", msg);
Willy Tarreau775e0012020-09-24 16:36:26 +0200889 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200890}
891
892/*
893 * this function dumps every server's state when the process receives SIGHUP.
894 */
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100895static void sig_dump_state(struct sig_handler *sh)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200896{
Olivier Houchardfbc74e82017-11-24 16:54:05 +0100897 struct proxy *p = proxies_list;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200898
Christopher Faulet767a84b2017-11-24 16:50:31 +0100899 ha_warning("SIGHUP received, dumping servers states.\n");
Willy Tarreaubaaee002006-06-26 02:48:02 +0200900 while (p) {
901 struct server *s = p->srv;
902
903 send_log(p, LOG_NOTICE, "SIGHUP received, dumping servers states for proxy %s.\n", p->id);
904 while (s) {
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100905 chunk_printf(&trash,
906 "SIGHUP: Server %s/%s is %s. Conn: %d act, %d pend, %lld tot.",
907 p->id, s->id,
Emeric Brun52a91d32017-08-31 14:41:55 +0200908 (s->cur_state != SRV_ST_STOPPED) ? "UP" : "DOWN",
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100909 s->cur_sess, s->nbpend, s->counters.cum_sess);
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200910 ha_warning("%s\n", trash.area);
911 send_log(p, LOG_NOTICE, "%s\n", trash.area);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200912 s = s->next;
913 }
914
Willy Tarreau5fcc8f12007-09-17 11:27:09 +0200915 /* FIXME: those info are a bit outdated. We should be able to distinguish between FE and BE. */
916 if (!p->srv) {
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100917 chunk_printf(&trash,
918 "SIGHUP: Proxy %s has no servers. Conn: act(FE+BE): %d+%d, %d pend (%d unass), tot(FE+BE): %lld+%lld.",
919 p->id,
920 p->feconn, p->beconn, p->totpend, p->nbpend, p->fe_counters.cum_conn, p->be_counters.cum_conn);
Willy Tarreau5fcc8f12007-09-17 11:27:09 +0200921 } else if (p->srv_act == 0) {
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100922 chunk_printf(&trash,
923 "SIGHUP: Proxy %s %s ! Conn: act(FE+BE): %d+%d, %d pend (%d unass), tot(FE+BE): %lld+%lld.",
924 p->id,
925 (p->srv_bck) ? "is running on backup servers" : "has no server available",
926 p->feconn, p->beconn, p->totpend, p->nbpend, p->fe_counters.cum_conn, p->be_counters.cum_conn);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200927 } else {
Willy Tarreau19d14ef2012-10-29 16:51:55 +0100928 chunk_printf(&trash,
929 "SIGHUP: Proxy %s has %d active servers and %d backup servers available."
930 " Conn: act(FE+BE): %d+%d, %d pend (%d unass), tot(FE+BE): %lld+%lld.",
931 p->id, p->srv_act, p->srv_bck,
932 p->feconn, p->beconn, p->totpend, p->nbpend, p->fe_counters.cum_conn, p->be_counters.cum_conn);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200933 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200934 ha_warning("%s\n", trash.area);
935 send_log(p, LOG_NOTICE, "%s\n", trash.area);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200936
937 p = p->next;
938 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200939}
940
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100941static void dump(struct sig_handler *sh)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200942{
Willy Tarreauc6ca1a02007-05-13 19:43:47 +0200943 /* dump memory usage then free everything possible */
944 dump_pools();
Willy Tarreaubafbe012017-11-24 17:34:44 +0100945 pool_gc(NULL);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200946}
947
William Lallemande1340412017-12-28 16:09:36 +0100948/*
949 * This function dup2 the stdio FDs (0,1,2) with <fd>, then closes <fd>
950 * If <fd> < 0, it opens /dev/null and use it to dup
951 *
952 * In the case of chrooting, you have to open /dev/null before the chroot, and
953 * pass the <fd> to this function
954 */
955static void stdio_quiet(int fd)
956{
957 if (fd < 0)
958 fd = open("/dev/null", O_RDWR, 0);
959
960 if (fd > -1) {
961 fclose(stdin);
962 fclose(stdout);
963 fclose(stderr);
964
965 dup2(fd, 0);
966 dup2(fd, 1);
967 dup2(fd, 2);
968 if (fd > 2)
969 close(fd);
970 return;
971 }
972
973 ha_alert("Cannot open /dev/null\n");
974 exit(EXIT_FAILURE);
975}
976
977
Joseph Herlant03420902018-11-15 10:41:50 -0800978/* This function checks if cfg_cfgfiles contains directories.
979 * If it finds one, it adds all the files (and only files) it contains
980 * in cfg_cfgfiles in place of the directory (and removes the directory).
981 * It adds the files in lexical order.
982 * It adds only files with .cfg extension.
Maxime de Roucy379d9c72016-05-13 23:52:56 +0200983 * It doesn't add files with name starting with '.'
984 */
Willy Tarreau1b5af7c2016-12-21 18:19:57 +0100985static void cfgfiles_expand_directories(void)
Maxime de Roucy379d9c72016-05-13 23:52:56 +0200986{
987 struct wordlist *wl, *wlb;
988 char *err = NULL;
989
990 list_for_each_entry_safe(wl, wlb, &cfg_cfgfiles, list) {
991 struct stat file_stat;
992 struct dirent **dir_entries = NULL;
993 int dir_entries_nb;
994 int dir_entries_it;
995
996 if (stat(wl->s, &file_stat)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100997 ha_alert("Cannot open configuration file/directory %s : %s\n",
998 wl->s,
999 strerror(errno));
Maxime de Roucy379d9c72016-05-13 23:52:56 +02001000 exit(1);
1001 }
1002
1003 if (!S_ISDIR(file_stat.st_mode))
1004 continue;
1005
1006 /* from this point wl->s is a directory */
1007
1008 dir_entries_nb = scandir(wl->s, &dir_entries, NULL, alphasort);
1009 if (dir_entries_nb < 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001010 ha_alert("Cannot open configuration directory %s : %s\n",
1011 wl->s,
1012 strerror(errno));
Maxime de Roucy379d9c72016-05-13 23:52:56 +02001013 exit(1);
1014 }
1015
1016 /* for each element in the directory wl->s */
1017 for (dir_entries_it = 0; dir_entries_it < dir_entries_nb; dir_entries_it++) {
1018 struct dirent *dir_entry = dir_entries[dir_entries_it];
1019 char *filename = NULL;
1020 char *d_name_cfgext = strstr(dir_entry->d_name, ".cfg");
1021
1022 /* don't add filename that begin with .
Joseph Herlant03420902018-11-15 10:41:50 -08001023 * only add filename with .cfg extension
Maxime de Roucy379d9c72016-05-13 23:52:56 +02001024 */
1025 if (dir_entry->d_name[0] == '.' ||
1026 !(d_name_cfgext && d_name_cfgext[4] == '\0'))
1027 goto next_dir_entry;
1028
1029 if (!memprintf(&filename, "%s/%s", wl->s, dir_entry->d_name)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001030 ha_alert("Cannot load configuration files %s : out of memory.\n",
1031 filename);
Maxime de Roucy379d9c72016-05-13 23:52:56 +02001032 exit(1);
1033 }
1034
1035 if (stat(filename, &file_stat)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001036 ha_alert("Cannot open configuration file %s : %s\n",
1037 wl->s,
1038 strerror(errno));
Maxime de Roucy379d9c72016-05-13 23:52:56 +02001039 exit(1);
1040 }
1041
1042 /* don't add anything else than regular file in cfg_cfgfiles
1043 * this way we avoid loops
1044 */
1045 if (!S_ISREG(file_stat.st_mode))
1046 goto next_dir_entry;
1047
1048 if (!list_append_word(&wl->list, filename, &err)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001049 ha_alert("Cannot load configuration files %s : %s\n",
1050 filename,
1051 err);
Maxime de Roucy379d9c72016-05-13 23:52:56 +02001052 exit(1);
1053 }
1054
1055next_dir_entry:
1056 free(filename);
1057 free(dir_entry);
1058 }
1059
1060 free(dir_entries);
1061
1062 /* remove the current directory (wl) from cfg_cfgfiles */
1063 free(wl->s);
Willy Tarreau2b718102021-04-21 07:32:39 +02001064 LIST_DELETE(&wl->list);
Maxime de Roucy379d9c72016-05-13 23:52:56 +02001065 free(wl);
1066 }
1067
1068 free(err);
1069}
1070
Willy Tarreaubaaee002006-06-26 02:48:02 +02001071/*
William Lallemand73b85e72017-06-01 17:38:51 +02001072 * copy and cleanup the current argv
William Lallemanddf6c5a82020-06-04 17:40:23 +02001073 * Remove the -sf /-st / -x parameters
William Lallemand73b85e72017-06-01 17:38:51 +02001074 * Return an allocated copy of argv
1075 */
1076
1077static char **copy_argv(int argc, char **argv)
1078{
William Lallemanddf6c5a82020-06-04 17:40:23 +02001079 char **newargv, **retargv;
William Lallemand73b85e72017-06-01 17:38:51 +02001080
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02001081 newargv = calloc(argc + 2, sizeof(*newargv));
William Lallemand73b85e72017-06-01 17:38:51 +02001082 if (newargv == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001083 ha_warning("Cannot allocate memory\n");
William Lallemand73b85e72017-06-01 17:38:51 +02001084 return NULL;
1085 }
William Lallemanddf6c5a82020-06-04 17:40:23 +02001086 retargv = newargv;
William Lallemand73b85e72017-06-01 17:38:51 +02001087
William Lallemanddf6c5a82020-06-04 17:40:23 +02001088 /* first copy argv[0] */
1089 *newargv++ = *argv++;
1090 argc--;
1091
1092 while (argc > 0) {
1093 if (**argv != '-') {
1094 /* non options are copied but will fail in the argument parser */
1095 *newargv++ = *argv++;
1096 argc--;
1097
1098 } else {
1099 char *flag;
1100
1101 flag = *argv + 1;
1102
1103 if (flag[0] == '-' && flag[1] == 0) {
1104 /* "--\0" copy every arguments till the end of argv */
1105 *newargv++ = *argv++;
1106 argc--;
1107
1108 while (argc > 0) {
1109 *newargv++ = *argv++;
1110 argc--;
1111 }
1112 } else {
1113 switch (*flag) {
1114 case 's':
1115 /* -sf / -st and their parameters are ignored */
1116 if (flag[1] == 'f' || flag[1] == 't') {
1117 argc--;
1118 argv++;
1119 /* The list can't contain a negative value since the only
1120 way to know the end of this list is by looking for the
1121 next option or the end of the options */
1122 while (argc > 0 && argv[0][0] != '-') {
1123 argc--;
1124 argv++;
1125 }
William Lallemand398da622020-09-02 16:12:23 +02001126 } else {
1127 argc--;
1128 argv++;
1129
William Lallemanddf6c5a82020-06-04 17:40:23 +02001130 }
1131 break;
1132
1133 case 'x':
1134 /* this option and its parameter are ignored */
1135 argc--;
1136 argv++;
1137 if (argc > 0) {
1138 argc--;
1139 argv++;
1140 }
1141 break;
1142
1143 case 'C':
1144 case 'n':
1145 case 'm':
1146 case 'N':
1147 case 'L':
1148 case 'f':
1149 case 'p':
1150 case 'S':
1151 /* these options have only 1 parameter which must be copied and can start with a '-' */
1152 *newargv++ = *argv++;
1153 argc--;
1154 if (argc == 0)
1155 goto error;
1156 *newargv++ = *argv++;
1157 argc--;
1158 break;
1159 default:
1160 /* for other options just copy them without parameters, this is also done
1161 * for options like "--foo", but this will fail in the argument parser.
1162 * */
1163 *newargv++ = *argv++;
1164 argc--;
1165 break;
1166 }
William Lallemand73b85e72017-06-01 17:38:51 +02001167 }
1168 }
William Lallemand73b85e72017-06-01 17:38:51 +02001169 }
William Lallemand2bf6d622017-06-20 11:20:23 +02001170
William Lallemanddf6c5a82020-06-04 17:40:23 +02001171 return retargv;
1172
1173error:
1174 free(retargv);
1175 return NULL;
William Lallemand73b85e72017-06-01 17:38:51 +02001176}
1177
Willy Tarreau6c3a6812020-03-06 18:57:15 +01001178
1179/* Performs basic random seed initialization. The main issue with this is that
1180 * srandom_r() only takes 32 bits and purposely provides a reproducible sequence,
1181 * which means that there will only be 4 billion possible random sequences once
1182 * srandom() is called, regardless of the internal state. Not calling it is
1183 * even worse as we'll always produce the same randoms sequences. What we do
1184 * here is to create an initial sequence from various entropy sources, hash it
1185 * using SHA1 and keep the resulting 160 bits available globally.
1186 *
1187 * We initialize the current process with the first 32 bits before starting the
1188 * polling loop, where all this will be changed to have process specific and
1189 * thread specific sequences.
Willy Tarreau52bf8392020-03-08 00:42:37 +01001190 *
1191 * Before starting threads, it's still possible to call random() as srandom()
1192 * is initialized from this, but after threads and/or processes are started,
1193 * only ha_random() is expected to be used to guarantee distinct sequences.
Willy Tarreau6c3a6812020-03-06 18:57:15 +01001194 */
1195static void ha_random_boot(char *const *argv)
1196{
1197 unsigned char message[256];
1198 unsigned char *m = message;
1199 struct timeval tv;
1200 blk_SHA_CTX ctx;
1201 unsigned long l;
1202 int fd;
1203 int i;
1204
1205 /* start with current time as pseudo-random seed */
1206 gettimeofday(&tv, NULL);
1207 write_u32(m, tv.tv_sec); m += 4;
1208 write_u32(m, tv.tv_usec); m += 4;
1209
1210 /* PID and PPID add some OS-based randomness */
1211 write_u16(m, getpid()); m += 2;
1212 write_u16(m, getppid()); m += 2;
1213
1214 /* take up to 160 bits bytes from /dev/urandom if available (non-blocking) */
1215 fd = open("/dev/urandom", O_RDONLY);
1216 if (fd >= 0) {
1217 i = read(fd, m, 20);
1218 if (i > 0)
1219 m += i;
1220 close(fd);
1221 }
1222
1223 /* take up to 160 bits bytes from openssl (non-blocking) */
1224#ifdef USE_OPENSSL
1225 if (RAND_bytes(m, 20) == 1)
1226 m += 20;
1227#endif
1228
1229 /* take 160 bits from existing random in case it was already initialized */
1230 for (i = 0; i < 5; i++) {
1231 write_u32(m, random());
1232 m += 4;
1233 }
1234
1235 /* stack address (benefit form operating system's ASLR) */
1236 l = (unsigned long)&m;
1237 memcpy(m, &l, sizeof(l)); m += sizeof(l);
1238
1239 /* argv address (benefit form operating system's ASLR) */
1240 l = (unsigned long)&argv;
1241 memcpy(m, &l, sizeof(l)); m += sizeof(l);
1242
1243 /* use tv_usec again after all the operations above */
1244 gettimeofday(&tv, NULL);
1245 write_u32(m, tv.tv_usec); m += 4;
1246
1247 /*
1248 * At this point, ~84-92 bytes have been used
1249 */
1250
1251 /* finish with the hostname */
1252 strncpy((char *)m, hostname, message + sizeof(message) - m);
1253 m += strlen(hostname);
1254
1255 /* total message length */
1256 l = m - message;
1257
1258 memset(&ctx, 0, sizeof(ctx));
1259 blk_SHA1_Init(&ctx);
1260 blk_SHA1_Update(&ctx, message, l);
1261 blk_SHA1_Final(boot_seed, &ctx);
1262
1263 srandom(read_u32(boot_seed));
Willy Tarreau52bf8392020-03-08 00:42:37 +01001264 ha_random_seed(boot_seed, sizeof(boot_seed));
Willy Tarreau6c3a6812020-03-06 18:57:15 +01001265}
1266
Willy Tarreau5a023f02019-03-01 14:19:31 +01001267/* considers splicing proxies' maxconn, computes the ideal global.maxpipes
1268 * setting, and returns it. It may return -1 meaning "unlimited" if some
1269 * unlimited proxies have been found and the global.maxconn value is not yet
1270 * set. It may also return a value greater than maxconn if it's not yet set.
1271 * Note that a value of zero means there is no need for pipes. -1 is never
1272 * returned if global.maxconn is valid.
1273 */
1274static int compute_ideal_maxpipes()
1275{
1276 struct proxy *cur;
1277 int nbfe = 0, nbbe = 0;
1278 int unlimited = 0;
1279 int pipes;
1280 int max;
1281
1282 for (cur = proxies_list; cur; cur = cur->next) {
1283 if (cur->options2 & (PR_O2_SPLIC_ANY)) {
1284 if (cur->cap & PR_CAP_FE) {
1285 max = cur->maxconn;
1286 nbfe += max;
1287 if (!max) {
1288 unlimited = 1;
1289 break;
1290 }
1291 }
1292 if (cur->cap & PR_CAP_BE) {
1293 max = cur->fullconn ? cur->fullconn : global.maxconn;
1294 nbbe += max;
1295 if (!max) {
1296 unlimited = 1;
1297 break;
1298 }
1299 }
1300 }
1301 }
1302
1303 pipes = MAX(nbfe, nbbe);
1304 if (global.maxconn) {
1305 if (pipes > global.maxconn || unlimited)
1306 pipes = global.maxconn;
1307 } else if (unlimited) {
1308 pipes = -1;
1309 }
1310
1311 return pipes >= 4 ? pipes / 4 : pipes;
1312}
1313
Willy Tarreauac350932019-03-01 15:43:14 +01001314/* considers global.maxsocks, global.maxpipes, async engines, SSL frontends and
1315 * rlimits and computes an ideal maxconn. It's meant to be called only when
1316 * maxsock contains the sum of listening FDs, before it is updated based on
Willy Tarreaudf23c0c2019-03-13 10:10:49 +01001317 * maxconn and pipes. If there are not enough FDs left, DEFAULT_MAXCONN (by
1318 * default 100) is returned as it is expected that it will even run on tight
1319 * environments, and will maintain compatibility with previous packages that
1320 * used to rely on this value as the default one. The system will emit a
1321 * warning indicating how many FDs are missing anyway if needed.
Willy Tarreauac350932019-03-01 15:43:14 +01001322 */
1323static int compute_ideal_maxconn()
1324{
1325 int ssl_sides = !!global.ssl_used_frontend + !!global.ssl_used_backend;
1326 int engine_fds = global.ssl_used_async_engines * ssl_sides;
1327 int pipes = compute_ideal_maxpipes();
Willy Tarreaub1beaa32020-03-06 10:25:31 +01001328 int remain = MAX(rlim_fd_cur_at_boot, rlim_fd_max_at_boot);
Willy Tarreauac350932019-03-01 15:43:14 +01001329 int maxconn;
1330
1331 /* we have to take into account these elements :
1332 * - number of engine_fds, which inflates the number of FD needed per
1333 * connection by this number.
1334 * - number of pipes per connection on average : for the unlimited
1335 * case, this is 0.5 pipe FDs per connection, otherwise it's a
1336 * fixed value of 2*pipes.
1337 * - two FDs per connection
1338 */
1339
1340 /* subtract listeners and checks */
1341 remain -= global.maxsock;
1342
Willy Tarreau3f200852019-03-14 19:13:17 +01001343 /* one epoll_fd/kqueue_fd per thread */
1344 remain -= global.nbthread;
1345
1346 /* one wake-up pipe (2 fd) per thread */
1347 remain -= 2 * global.nbthread;
1348
Willy Tarreauac350932019-03-01 15:43:14 +01001349 /* Fixed pipes values : we only subtract them if they're not larger
1350 * than the remaining FDs because pipes are optional.
1351 */
1352 if (pipes >= 0 && pipes * 2 < remain)
1353 remain -= pipes * 2;
1354
1355 if (pipes < 0) {
1356 /* maxsock = maxconn * 2 + maxconn/4 * 2 + maxconn * engine_fds.
1357 * = maxconn * (2 + 0.5 + engine_fds)
1358 * = maxconn * (4 + 1 + 2*engine_fds) / 2
1359 */
1360 maxconn = 2 * remain / (5 + 2 * engine_fds);
1361 } else {
1362 /* maxsock = maxconn * 2 + maxconn * engine_fds.
1363 * = maxconn * (2 + engine_fds)
1364 */
1365 maxconn = remain / (2 + engine_fds);
1366 }
1367
Willy Tarreaudf23c0c2019-03-13 10:10:49 +01001368 return MAX(maxconn, DEFAULT_MAXCONN);
Willy Tarreauac350932019-03-01 15:43:14 +01001369}
1370
Willy Tarreaua409f302020-03-10 17:08:53 +01001371/* computes the estimated maxsock value for the given maxconn based on the
1372 * possibly set global.maxpipes and existing partial global.maxsock. It may
1373 * temporarily change global.maxconn for the time needed to propagate the
1374 * computations, and will reset it.
1375 */
1376static int compute_ideal_maxsock(int maxconn)
1377{
1378 int maxpipes = global.maxpipes;
1379 int maxsock = global.maxsock;
1380
1381
1382 if (!maxpipes) {
1383 int old_maxconn = global.maxconn;
1384
1385 global.maxconn = maxconn;
1386 maxpipes = compute_ideal_maxpipes();
1387 global.maxconn = old_maxconn;
1388 }
1389
1390 maxsock += maxconn * 2; /* each connection needs two sockets */
1391 maxsock += maxpipes * 2; /* each pipe needs two FDs */
1392 maxsock += global.nbthread; /* one epoll_fd/kqueue_fd per thread */
1393 maxsock += 2 * global.nbthread; /* one wake-up pipe (2 fd) per thread */
1394
1395 /* compute fd used by async engines */
1396 if (global.ssl_used_async_engines) {
1397 int sides = !!global.ssl_used_frontend + !!global.ssl_used_backend;
1398
1399 maxsock += maxconn * sides * global.ssl_used_async_engines;
1400 }
1401 return maxsock;
1402}
1403
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07001404/* Tests if it is possible to set the current process's RLIMIT_NOFILE to
Willy Tarreau304e17e2020-03-10 17:54:54 +01001405 * <maxsock>, then sets it back to the previous value. Returns non-zero if the
1406 * value is accepted, non-zero otherwise. This is used to determine if an
1407 * automatic limit may be applied or not. When it is not, the caller knows that
1408 * the highest we can do is the rlim_max at boot. In case of error, we return
1409 * that the setting is possible, so that we defer the error processing to the
1410 * final stage in charge of enforcing this.
1411 */
1412static int check_if_maxsock_permitted(int maxsock)
1413{
1414 struct rlimit orig_limit, test_limit;
1415 int ret;
1416
1417 if (getrlimit(RLIMIT_NOFILE, &orig_limit) != 0)
1418 return 1;
1419
1420 /* don't go further if we can't even set to what we have */
1421 if (setrlimit(RLIMIT_NOFILE, &orig_limit) != 0)
1422 return 1;
1423
1424 test_limit.rlim_max = MAX(maxsock, orig_limit.rlim_max);
1425 test_limit.rlim_cur = test_limit.rlim_max;
1426 ret = setrlimit(RLIMIT_NOFILE, &test_limit);
1427
1428 if (setrlimit(RLIMIT_NOFILE, &orig_limit) != 0)
1429 return 1;
1430
1431 return ret == 0;
1432}
1433
Amaury Denoyelle484454d2021-05-05 16:18:45 +02001434void mark_tainted(const enum tainted_flags flag)
1435{
1436 HA_ATOMIC_OR(&tainted, flag);
1437}
1438
1439unsigned int get_tainted()
1440{
1441 int tainted_state;
1442 HA_ATOMIC_STORE(&tainted_state, tainted);
1443 return tainted_state;
1444}
Willy Tarreau304e17e2020-03-10 17:54:54 +01001445
William Lallemand73b85e72017-06-01 17:38:51 +02001446/*
Willy Tarreaubaaee002006-06-26 02:48:02 +02001447 * This function initializes all the necessary variables. It only returns
1448 * if everything is OK. If something fails, it exits.
1449 */
Willy Tarreau1b5af7c2016-12-21 18:19:57 +01001450static void init(int argc, char **argv)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001451{
Willy Tarreaubaaee002006-06-26 02:48:02 +02001452 int arg_mode = 0; /* MODE_DEBUG, ... */
Willy Tarreaubaaee002006-06-26 02:48:02 +02001453 char *tmp;
1454 char *cfg_pidfile = NULL;
Willy Tarreau058e9072009-07-20 09:30:05 +02001455 int err_code = 0;
Maxime de Roucy0f503922016-05-13 23:52:55 +02001456 char *err_msg = NULL;
Willy Tarreau477ecd82010-01-03 21:12:30 +01001457 struct wordlist *wl;
Kevinm48936af2010-12-22 16:08:21 +00001458 char *progname;
Willy Tarreau576132e2011-09-10 19:26:56 +02001459 char *change_dir = NULL;
Christopher Fauletd7c91962015-04-30 11:48:27 +02001460 struct proxy *px;
Willy Tarreaue6945732016-12-21 19:57:00 +01001461 struct post_check_fct *pcf;
Willy Tarreauac350932019-03-01 15:43:14 +01001462 int ideal_maxconn;
Maximilian Maderfc0cceb2021-06-06 00:50:22 +02001463 char *check_condition = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001464
Christopher Faulete3a5e352017-10-24 13:53:54 +02001465 global.mode = MODE_STARTING;
William Lallemand00417412020-06-05 14:08:41 +02001466 old_argv = copy_argv(argc, argv);
1467 if (!old_argv) {
William Lallemanddf6c5a82020-06-04 17:40:23 +02001468 ha_alert("failed to copy argv.\n");
1469 exit(1);
1470 }
William Lallemand73b85e72017-06-01 17:38:51 +02001471
Christopher Fauletcd7879a2017-10-27 13:53:47 +02001472 if (!init_trash_buffers(1)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001473 ha_alert("failed to initialize trash buffers.\n");
Christopher Faulet748919a2017-07-26 14:59:46 +02001474 exit(1);
1475 }
David du Colombier7af46052012-05-16 14:16:48 +02001476
Emeric Brun2b920a12010-09-23 18:30:22 +02001477 /* NB: POSIX does not make it mandatory for gethostname() to NULL-terminate
1478 * the string in case of truncation, and at least FreeBSD appears not to do
1479 * it.
1480 */
1481 memset(hostname, 0, sizeof(hostname));
1482 gethostname(hostname, sizeof(hostname) - 1);
Dragan Dosen4f014152020-06-18 16:56:47 +02001483
1484 if ((localpeer = strdup(hostname)) == NULL) {
1485 ha_alert("Cannot allocate memory for local peer.\n");
1486 exit(EXIT_FAILURE);
1487 }
William Lallemanddaf4cd22018-04-17 16:46:13 +02001488 setenv("HAPROXY_LOCALPEER", localpeer, 1);
Emeric Brun2b920a12010-09-23 18:30:22 +02001489
William Lallemand24c928c2020-01-14 17:58:18 +01001490 /* we were in mworker mode, we should restart in mworker mode */
1491 if (getenv("HAPROXY_MWORKER_REEXEC") != NULL)
1492 global.mode |= MODE_MWORKER;
1493
Willy Tarreaubaaee002006-06-26 02:48:02 +02001494 /*
1495 * Initialize the previously static variables.
1496 */
Christopher Fauletcd7879a2017-10-27 13:53:47 +02001497
Willy Tarreau173d9952018-01-26 21:48:23 +01001498 totalconn = actconn = listeners = stopping = 0;
Cyril Bonté203ec5a2017-03-23 22:44:13 +01001499 killed = 0;
Christopher Fauletcd7879a2017-10-27 13:53:47 +02001500
Willy Tarreaubaaee002006-06-26 02:48:02 +02001501
1502#ifdef HAPROXY_MEMMAX
Willy Tarreau70060452015-12-14 12:46:07 +01001503 global.rlimit_memmax_all = HAPROXY_MEMMAX;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001504#endif
1505
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02001506 tzset();
Willy Tarreauc4c80fb2021-04-11 15:00:34 +02001507 tv_init_process_date();
Willy Tarreaubaaee002006-06-26 02:48:02 +02001508 start_date = now;
1509
Willy Tarreau6c3a6812020-03-06 18:57:15 +01001510 ha_random_boot(argv);
Willy Tarreau84310e22014-02-14 11:59:04 +01001511
Willy Tarreau8ed669b2013-01-11 15:49:37 +01001512 if (init_acl() != 0)
1513 exit(1);
Willy Tarreaub6b3df32018-11-26 16:31:20 +01001514
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001515 /* Initialise lua. */
1516 hlua_init();
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001517
Christopher Fauletff2613e2016-11-09 11:36:17 +01001518 /* Initialize process vars */
Willy Tarreaucfc4f242021-05-08 11:41:28 +02001519 vars_init(&proc_vars, SCOPE_PROC);
Christopher Fauletff2613e2016-11-09 11:36:17 +01001520
Willy Tarreau43b78992009-01-25 15:42:27 +01001521 global.tune.options |= GTUNE_USE_SELECT; /* select() is always available */
Willy Tarreaue5733232019-05-22 19:24:06 +02001522#if defined(USE_POLL)
Willy Tarreau43b78992009-01-25 15:42:27 +01001523 global.tune.options |= GTUNE_USE_POLL;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001524#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001525#if defined(USE_EPOLL)
Willy Tarreau43b78992009-01-25 15:42:27 +01001526 global.tune.options |= GTUNE_USE_EPOLL;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001527#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001528#if defined(USE_KQUEUE)
Willy Tarreau43b78992009-01-25 15:42:27 +01001529 global.tune.options |= GTUNE_USE_KQUEUE;
Willy Tarreau1e63130a2007-04-09 12:03:06 +02001530#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001531#if defined(USE_EVPORTS)
Emmanuel Hocdet0ba4f482019-04-08 16:53:32 +00001532 global.tune.options |= GTUNE_USE_EVPORTS;
1533#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001534#if defined(USE_LINUX_SPLICE)
Willy Tarreau3ab68cf2009-01-25 16:03:28 +01001535 global.tune.options |= GTUNE_USE_SPLICE;
1536#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +02001537#if defined(USE_GETADDRINFO)
1538 global.tune.options |= GTUNE_USE_GAI;
1539#endif
Lukas Tribusa0bcbdc2016-09-12 21:42:20 +00001540#if defined(SO_REUSEPORT)
1541 global.tune.options |= GTUNE_USE_REUSEPORT;
1542#endif
Willy Tarreau76cc6992020-07-01 18:49:24 +02001543#ifdef USE_THREAD
1544 global.tune.options |= GTUNE_IDLE_POOL_SHARED;
1545#endif
William Dauchya5194602020-03-28 19:29:58 +01001546 global.tune.options |= GTUNE_STRICT_LIMITS;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001547
1548 pid = getpid();
1549 progname = *argv;
1550 while ((tmp = strchr(progname, '/')) != NULL)
1551 progname = tmp + 1;
1552
Kevinm48936af2010-12-22 16:08:21 +00001553 /* the process name is used for the logs only */
Eric Salama7cea6062020-10-02 11:58:19 +02001554 chunk_initlen(&global.log_tag, strdup(progname), strlen(progname), strlen(progname));
1555 if (b_orig(&global.log_tag) == NULL) {
1556 chunk_destroy(&global.log_tag);
1557 ha_alert("Cannot allocate memory for log_tag.\n");
1558 exit(EXIT_FAILURE);
1559 }
Kevinm48936af2010-12-22 16:08:21 +00001560
Willy Tarreaubaaee002006-06-26 02:48:02 +02001561 argc--; argv++;
1562 while (argc > 0) {
1563 char *flag;
1564
1565 if (**argv == '-') {
1566 flag = *argv+1;
1567
1568 /* 1 arg */
1569 if (*flag == 'v') {
1570 display_version();
Willy Tarreau7b066db2007-12-02 11:28:59 +01001571 if (flag[1] == 'v') /* -vv */
1572 display_build_opts();
Willy Tarreaubaaee002006-06-26 02:48:02 +02001573 exit(0);
1574 }
Willy Tarreaue5733232019-05-22 19:24:06 +02001575#if defined(USE_EPOLL)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001576 else if (*flag == 'd' && flag[1] == 'e')
Willy Tarreau43b78992009-01-25 15:42:27 +01001577 global.tune.options &= ~GTUNE_USE_EPOLL;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001578#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001579#if defined(USE_POLL)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001580 else if (*flag == 'd' && flag[1] == 'p')
Willy Tarreau43b78992009-01-25 15:42:27 +01001581 global.tune.options &= ~GTUNE_USE_POLL;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001582#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001583#if defined(USE_KQUEUE)
Willy Tarreau1e63130a2007-04-09 12:03:06 +02001584 else if (*flag == 'd' && flag[1] == 'k')
Willy Tarreau43b78992009-01-25 15:42:27 +01001585 global.tune.options &= ~GTUNE_USE_KQUEUE;
Willy Tarreau1e63130a2007-04-09 12:03:06 +02001586#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001587#if defined(USE_EVPORTS)
Emmanuel Hocdet0ba4f482019-04-08 16:53:32 +00001588 else if (*flag == 'd' && flag[1] == 'v')
1589 global.tune.options &= ~GTUNE_USE_EVPORTS;
1590#endif
Willy Tarreaue5733232019-05-22 19:24:06 +02001591#if defined(USE_LINUX_SPLICE)
Willy Tarreau3ab68cf2009-01-25 16:03:28 +01001592 else if (*flag == 'd' && flag[1] == 'S')
1593 global.tune.options &= ~GTUNE_USE_SPLICE;
1594#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +02001595#if defined(USE_GETADDRINFO)
1596 else if (*flag == 'd' && flag[1] == 'G')
1597 global.tune.options &= ~GTUNE_USE_GAI;
1598#endif
Lukas Tribusa0bcbdc2016-09-12 21:42:20 +00001599#if defined(SO_REUSEPORT)
1600 else if (*flag == 'd' && flag[1] == 'R')
1601 global.tune.options &= ~GTUNE_USE_REUSEPORT;
1602#endif
Emeric Brun850efd52014-01-29 12:24:34 +01001603 else if (*flag == 'd' && flag[1] == 'V')
1604 global.ssl_server_verify = SSL_SERVER_VERIFY_NONE;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001605 else if (*flag == 'V')
1606 arg_mode |= MODE_VERBOSE;
1607 else if (*flag == 'd' && flag[1] == 'b')
1608 arg_mode |= MODE_FOREGROUND;
Amaury Denoyelle7b01a8d2021-03-29 10:29:07 +02001609 else if (*flag == 'd' && flag[1] == 'D')
1610 arg_mode |= MODE_DIAG;
Willy Tarreau3eb10b82020-04-15 16:42:39 +02001611 else if (*flag == 'd' && flag[1] == 'W')
1612 arg_mode |= MODE_ZERO_WARNING;
Willy Tarreau6e064432012-05-08 15:40:42 +02001613 else if (*flag == 'd' && flag[1] == 'M')
1614 mem_poison_byte = flag[2] ? strtol(flag + 2, NULL, 0) : 'P';
Willy Tarreau3eed10e2016-11-07 21:03:16 +01001615 else if (*flag == 'd' && flag[1] == 'r')
1616 global.tune.options |= GTUNE_RESOLVE_DONTFAIL;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001617 else if (*flag == 'd')
1618 arg_mode |= MODE_DEBUG;
Maximilian Maderfc0cceb2021-06-06 00:50:22 +02001619 else if (*flag == 'c' && flag[1] == 'c') {
1620 arg_mode |= MODE_CHECK_CONDITION;
1621 argv++;
1622 argc--;
1623 check_condition = *argv;
1624 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001625 else if (*flag == 'c')
1626 arg_mode |= MODE_CHECK;
William Lallemand095ba4c2017-06-01 17:38:50 +02001627 else if (*flag == 'D')
Willy Tarreau6bde87b2009-05-18 16:29:51 +02001628 arg_mode |= MODE_DAEMON;
Tim Duesterhusd6942c82017-11-20 15:58:35 +01001629 else if (*flag == 'W' && flag[1] == 's') {
Lukas Tribusf46bf952017-11-21 12:39:34 +01001630 arg_mode |= MODE_MWORKER | MODE_FOREGROUND;
Tim Duesterhusd6942c82017-11-20 15:58:35 +01001631#if defined(USE_SYSTEMD)
1632 global.tune.options |= GTUNE_USE_SYSTEMD;
1633#else
Christopher Faulet767a84b2017-11-24 16:50:31 +01001634 ha_alert("master-worker mode with systemd support (-Ws) requested, but not compiled. Use master-worker mode (-W) if you are not using Type=notify in your unit file or recompile with USE_SYSTEMD=1.\n\n");
Tim Duesterhusd6942c82017-11-20 15:58:35 +01001635 usage(progname);
1636#endif
1637 }
William Lallemand095ba4c2017-06-01 17:38:50 +02001638 else if (*flag == 'W')
1639 arg_mode |= MODE_MWORKER;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001640 else if (*flag == 'q')
1641 arg_mode |= MODE_QUIET;
Olivier Houchardf73629d2017-04-05 22:33:04 +02001642 else if (*flag == 'x') {
William Lallemand4f71d302020-06-04 23:41:29 +02001643 if (argc <= 1) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001644 ha_alert("Unix socket path expected with the -x flag\n\n");
William Lallemand45eff442017-06-19 15:57:55 +02001645 usage(progname);
Olivier Houchardf73629d2017-04-05 22:33:04 +02001646 }
William Lallemand4fc09692017-06-19 16:37:19 +02001647 if (old_unixsocket)
Christopher Faulet767a84b2017-11-24 16:50:31 +01001648 ha_warning("-x option already set, overwriting the value\n");
Olivier Houchardf73629d2017-04-05 22:33:04 +02001649 old_unixsocket = argv[1];
William Lallemand4fc09692017-06-19 16:37:19 +02001650
Olivier Houchardf73629d2017-04-05 22:33:04 +02001651 argv++;
1652 argc--;
1653 }
William Lallemande7361152018-10-26 14:47:36 +02001654 else if (*flag == 'S') {
1655 struct wordlist *c;
1656
William Lallemanda6b32492020-06-04 23:49:20 +02001657 if (argc <= 1) {
William Lallemande7361152018-10-26 14:47:36 +02001658 ha_alert("Socket and optional bind parameters expected with the -S flag\n");
1659 usage(progname);
1660 }
1661 if ((c = malloc(sizeof(*c))) == NULL || (c->s = strdup(argv[1])) == NULL) {
1662 ha_alert("Cannot allocate memory\n");
1663 exit(EXIT_FAILURE);
1664 }
Willy Tarreau2b718102021-04-21 07:32:39 +02001665 LIST_INSERT(&mworker_cli_conf, &c->list);
William Lallemande7361152018-10-26 14:47:36 +02001666
1667 argv++;
1668 argc--;
1669 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001670 else if (*flag == 's' && (flag[1] == 'f' || flag[1] == 't')) {
1671 /* list of pids to finish ('f') or terminate ('t') */
1672
1673 if (flag[1] == 'f')
1674 oldpids_sig = SIGUSR1; /* finish then exit */
1675 else
1676 oldpids_sig = SIGTERM; /* terminate immediately */
Willy Tarreauc6ca1aa2015-10-08 11:32:32 +02001677 while (argc > 1 && argv[1][0] != '-') {
Chris Lane236062f2018-02-05 23:15:44 +00001678 char * endptr = NULL;
Willy Tarreauc6ca1aa2015-10-08 11:32:32 +02001679 oldpids = realloc(oldpids, (nb_oldpids + 1) * sizeof(int));
1680 if (!oldpids) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001681 ha_alert("Cannot allocate old pid : out of memory.\n");
Willy Tarreauc6ca1aa2015-10-08 11:32:32 +02001682 exit(1);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001683 }
Willy Tarreauc6ca1aa2015-10-08 11:32:32 +02001684 argc--; argv++;
Chris Lane236062f2018-02-05 23:15:44 +00001685 errno = 0;
1686 oldpids[nb_oldpids] = strtol(*argv, &endptr, 10);
1687 if (errno) {
1688 ha_alert("-%2s option: failed to parse {%s}: %s\n",
1689 flag,
1690 *argv, strerror(errno));
1691 exit(1);
1692 } else if (endptr && strlen(endptr)) {
Willy Tarreau90807112020-02-25 08:16:33 +01001693 while (isspace((unsigned char)*endptr)) endptr++;
Aurélien Nephtali39b89882018-02-17 20:53:11 +01001694 if (*endptr != 0) {
Chris Lane236062f2018-02-05 23:15:44 +00001695 ha_alert("-%2s option: some bytes unconsumed in PID list {%s}\n",
1696 flag, endptr);
1697 exit(1);
Aurélien Nephtali39b89882018-02-17 20:53:11 +01001698 }
Chris Lane236062f2018-02-05 23:15:44 +00001699 }
Willy Tarreauc6ca1aa2015-10-08 11:32:32 +02001700 if (oldpids[nb_oldpids] <= 0)
1701 usage(progname);
1702 nb_oldpids++;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001703 }
1704 }
Willy Tarreaua088d312015-10-08 11:58:48 +02001705 else if (flag[0] == '-' && flag[1] == 0) { /* "--" */
1706 /* now that's a cfgfile list */
1707 argv++; argc--;
1708 while (argc > 0) {
Maxime de Roucy0f503922016-05-13 23:52:55 +02001709 if (!list_append_word(&cfg_cfgfiles, *argv, &err_msg)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001710 ha_alert("Cannot load configuration file/directory %s : %s\n",
1711 *argv,
1712 err_msg);
Willy Tarreaua088d312015-10-08 11:58:48 +02001713 exit(1);
1714 }
Willy Tarreaua088d312015-10-08 11:58:48 +02001715 argv++; argc--;
1716 }
1717 break;
1718 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001719 else { /* >=2 args */
1720 argv++; argc--;
1721 if (argc == 0)
Willy Tarreau3bafcdc2011-09-10 19:20:23 +02001722 usage(progname);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001723
1724 switch (*flag) {
Willy Tarreau576132e2011-09-10 19:26:56 +02001725 case 'C' : change_dir = *argv; break;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001726 case 'n' : cfg_maxconn = atol(*argv); break;
Willy Tarreau70060452015-12-14 12:46:07 +01001727 case 'm' : global.rlimit_memmax_all = atol(*argv); break;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001728 case 'N' : cfg_maxpconn = atol(*argv); break;
William Lallemanddaf4cd22018-04-17 16:46:13 +02001729 case 'L' :
Dragan Dosen4f014152020-06-18 16:56:47 +02001730 free(localpeer);
1731 if ((localpeer = strdup(*argv)) == NULL) {
1732 ha_alert("Cannot allocate memory for local peer.\n");
1733 exit(EXIT_FAILURE);
1734 }
William Lallemanddaf4cd22018-04-17 16:46:13 +02001735 setenv("HAPROXY_LOCALPEER", localpeer, 1);
Dragan Dosen13cd54c2020-06-18 18:24:05 +02001736 global.localpeer_cmdline = 1;
William Lallemanddaf4cd22018-04-17 16:46:13 +02001737 break;
Willy Tarreau5d01a632009-06-22 16:02:30 +02001738 case 'f' :
Maxime de Roucy0f503922016-05-13 23:52:55 +02001739 if (!list_append_word(&cfg_cfgfiles, *argv, &err_msg)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001740 ha_alert("Cannot load configuration file/directory %s : %s\n",
1741 *argv,
1742 err_msg);
Willy Tarreau5d01a632009-06-22 16:02:30 +02001743 exit(1);
1744 }
Willy Tarreau5d01a632009-06-22 16:02:30 +02001745 break;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001746 case 'p' : cfg_pidfile = *argv; break;
Willy Tarreau3bafcdc2011-09-10 19:20:23 +02001747 default: usage(progname);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001748 }
1749 }
1750 }
1751 else
Willy Tarreau3bafcdc2011-09-10 19:20:23 +02001752 usage(progname);
Willy Tarreaubaaee002006-06-26 02:48:02 +02001753 argv++; argc--;
1754 }
1755
Christopher Faulete3a5e352017-10-24 13:53:54 +02001756 global.mode |= (arg_mode & (MODE_DAEMON | MODE_MWORKER | MODE_FOREGROUND | MODE_VERBOSE
Amaury Denoyelle7b01a8d2021-03-29 10:29:07 +02001757 | MODE_QUIET | MODE_CHECK | MODE_DEBUG | MODE_ZERO_WARNING
Maximilian Maderfc0cceb2021-06-06 00:50:22 +02001758 | MODE_DIAG | MODE_CHECK_CONDITION));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001759
William Lallemand944e6192018-11-21 15:48:31 +01001760 if (getenv("HAPROXY_MWORKER_WAIT_ONLY")) {
William Lallemandcb11fd22017-06-01 17:38:52 +02001761 unsetenv("HAPROXY_MWORKER_WAIT_ONLY");
William Lallemand944e6192018-11-21 15:48:31 +01001762 global.mode |= MODE_MWORKER_WAIT;
1763 global.mode &= ~MODE_MWORKER;
William Lallemandcb11fd22017-06-01 17:38:52 +02001764 }
1765
1766 if ((global.mode & MODE_MWORKER) && (getenv("HAPROXY_MWORKER_REEXEC") != NULL)) {
1767 atexit_flag = 1;
1768 atexit(reexec_on_failure);
1769 }
1770
Willy Tarreau576132e2011-09-10 19:26:56 +02001771 if (change_dir && chdir(change_dir) < 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001772 ha_alert("Could not change to directory %s : %s\n", change_dir, strerror(errno));
Willy Tarreau576132e2011-09-10 19:26:56 +02001773 exit(1);
1774 }
1775
Willy Tarreaubaaee002006-06-26 02:48:02 +02001776 global.maxsock = 10; /* reserve 10 fds ; will be incremented by socket eaters */
Willy Tarreau915e1eb2009-06-22 15:48:36 +02001777
Amaury Denoyellea6f9c5d2021-04-23 16:58:08 +02001778#ifdef USE_CPU_AFFINITY
1779 {
1780 int i;
Willy Tarreau44ea6312021-06-15 08:57:56 +02001781 ha_cpuset_zero(&cpu_map.proc);
1782 ha_cpuset_zero(&cpu_map.proc_t1);
Willy Tarreau26f42a02021-05-14 08:26:38 +02001783 for (i = 0; i < MAX_THREADS; ++i) {
Amaury Denoyellefc6ac532021-04-27 10:46:36 +02001784 ha_cpuset_zero(&cpu_map.thread[i]);
Amaury Denoyellea6f9c5d2021-04-23 16:58:08 +02001785 }
Amaury Denoyelle982fb532021-04-21 18:39:58 +02001786 }
Amaury Denoyellea6f9c5d2021-04-23 16:58:08 +02001787#endif
Amaury Denoyelle982fb532021-04-21 18:39:58 +02001788
Amaury Denoyelle11124302021-06-04 18:22:08 +02001789 usermsgs_clr("config");
1790
Maximilian Maderfc0cceb2021-06-06 00:50:22 +02001791 if (global.mode & MODE_CHECK_CONDITION) {
1792 int result;
1793
1794 uint32_t err;
1795 const char *errptr;
1796 char *errmsg = NULL;
1797
1798 char *args[MAX_LINE_ARGS+1];
1799 int arg = sizeof(args) / sizeof(*args);
1800 size_t outlen = strlen(check_condition) + 1;
1801
1802 err = parse_line(check_condition, check_condition, &outlen, args, &arg,
1803 PARSE_OPT_DQUOTE | PARSE_OPT_SQUOTE | PARSE_OPT_BKSLASH,
1804 &errptr);
1805
1806 if (err & PARSE_ERR_QUOTE) {
1807 ha_alert("Syntax Error in condition: Unmatched quote.\n");
1808 exit(2);
1809 }
1810
1811 if (err & PARSE_ERR_HEX) {
1812 ha_alert("Syntax Error in condition: Truncated or invalid hexadecimal sequence.\n");
1813 exit(2);
1814 }
1815
1816 if (err & (PARSE_ERR_TOOLARGE|PARSE_ERR_OVERLAP)) {
1817 ha_alert("Error in condition: Line too long.\n");
1818 exit(2);
1819 }
1820
1821 if (err & PARSE_ERR_TOOMANY) {
1822 ha_alert("Error in condition: Too many words.\n");
1823 exit(2);
1824 }
1825
1826 if (err) {
1827 ha_alert("Unhandled error in condition, please report this to the developers.\n");
1828 exit(2);
1829 }
1830
1831 result = cfg_eval_condition(args, &errmsg, &errptr);
1832
1833 if (result < 0) {
1834 if (errmsg)
1835 ha_alert("Failed to evaluate condition: %s\n", errmsg);
1836
1837 exit(2);
1838 }
1839
1840 exit(result ? 0 : 1);
1841 }
1842
William Lallemand944e6192018-11-21 15:48:31 +01001843 /* in wait mode, we don't try to read the configuration files */
1844 if (!(global.mode & MODE_MWORKER_WAIT)) {
Christopher Faulet4e366822021-01-12 18:57:38 +01001845 char *env_cfgfiles = NULL;
1846 int env_err = 0;
Willy Tarreauc4382422009-12-06 13:10:44 +01001847
William Lallemand944e6192018-11-21 15:48:31 +01001848 /* handle cfgfiles that are actually directories */
1849 cfgfiles_expand_directories();
1850
1851 if (LIST_ISEMPTY(&cfg_cfgfiles))
1852 usage(progname);
1853
1854
1855 list_for_each_entry(wl, &cfg_cfgfiles, list) {
1856 int ret;
1857
Christopher Faulet4e366822021-01-12 18:57:38 +01001858 if (env_err == 0) {
1859 if (!memprintf(&env_cfgfiles, "%s%s%s",
1860 (env_cfgfiles ? env_cfgfiles : ""),
1861 (env_cfgfiles ? ";" : ""), wl->s))
1862 env_err = 1;
1863 }
William Lallemand7b302d82019-05-20 11:15:37 +02001864
William Lallemand944e6192018-11-21 15:48:31 +01001865 ret = readcfgfile(wl->s);
1866 if (ret == -1) {
1867 ha_alert("Could not open configuration file %s : %s\n",
1868 wl->s, strerror(errno));
Christopher Faulet4e366822021-01-12 18:57:38 +01001869 free(env_cfgfiles);
William Lallemand944e6192018-11-21 15:48:31 +01001870 exit(1);
1871 }
1872 if (ret & (ERR_ABORT|ERR_FATAL))
1873 ha_alert("Error(s) found in configuration file : %s\n", wl->s);
1874 err_code |= ret;
Christopher Faulet4e366822021-01-12 18:57:38 +01001875 if (err_code & ERR_ABORT) {
1876 free(env_cfgfiles);
William Lallemand944e6192018-11-21 15:48:31 +01001877 exit(1);
Christopher Faulet4e366822021-01-12 18:57:38 +01001878 }
Willy Tarreauc4382422009-12-06 13:10:44 +01001879 }
Krzysztof Oledzkib304dc72007-10-14 23:40:01 +02001880
William Lallemand944e6192018-11-21 15:48:31 +01001881 /* do not try to resolve arguments nor to spot inconsistencies when
1882 * the configuration contains fatal errors caused by files not found
1883 * or failed memory allocations.
1884 */
1885 if (err_code & (ERR_ABORT|ERR_FATAL)) {
1886 ha_alert("Fatal errors found in configuration.\n");
Christopher Faulet4e366822021-01-12 18:57:38 +01001887 free(env_cfgfiles);
William Lallemand944e6192018-11-21 15:48:31 +01001888 exit(1);
1889 }
Christopher Faulet4e366822021-01-12 18:57:38 +01001890 if (env_err) {
1891 ha_alert("Could not allocate memory for HAPROXY_CFGFILES env variable\n");
1892 exit(1);
1893 }
1894 setenv("HAPROXY_CFGFILES", env_cfgfiles, 1);
1895 free(env_cfgfiles);
William Lallemand7b302d82019-05-20 11:15:37 +02001896
Willy Tarreaub83dc3d2017-04-19 11:24:07 +02001897 }
William Lallemandce83b4a2018-10-26 14:47:30 +02001898 if (global.mode & MODE_MWORKER) {
William Lallemand16dd1b32018-11-19 18:46:18 +01001899 struct mworker_proc *tmproc;
1900
William Lallemand482f9a92019-04-12 16:15:00 +02001901 setenv("HAPROXY_MWORKER", "1", 1);
1902
William Lallemand16dd1b32018-11-19 18:46:18 +01001903 if (getenv("HAPROXY_MWORKER_REEXEC") == NULL) {
1904
William Lallemandf3a86832019-04-01 11:29:58 +02001905 tmproc = calloc(1, sizeof(*tmproc));
William Lallemand16dd1b32018-11-19 18:46:18 +01001906 if (!tmproc) {
1907 ha_alert("Cannot allocate process structures.\n");
1908 exit(EXIT_FAILURE);
1909 }
William Lallemand8f7069a2019-04-12 16:09:23 +02001910 tmproc->options |= PROC_O_TYPE_MASTER; /* master */
William Lallemand16dd1b32018-11-19 18:46:18 +01001911 tmproc->reloads = 0;
1912 tmproc->relative_pid = 0;
1913 tmproc->pid = pid;
1914 tmproc->timestamp = start_date.tv_sec;
1915 tmproc->ipc_fd[0] = -1;
1916 tmproc->ipc_fd[1] = -1;
1917
1918 proc_self = tmproc;
1919
Willy Tarreau2b718102021-04-21 07:32:39 +02001920 LIST_APPEND(&proc_list, &tmproc->list);
William Lallemand16dd1b32018-11-19 18:46:18 +01001921 }
William Lallemandce83b4a2018-10-26 14:47:30 +02001922
Willy Tarreau6185a032021-06-15 08:02:06 +02001923 tmproc = calloc(1, sizeof(*tmproc));
1924 if (!tmproc) {
1925 ha_alert("Cannot allocate process structures.\n");
1926 exit(EXIT_FAILURE);
1927 }
William Lallemandce83b4a2018-10-26 14:47:30 +02001928
Willy Tarreau6185a032021-06-15 08:02:06 +02001929 tmproc->options |= PROC_O_TYPE_WORKER; /* worker */
1930 tmproc->pid = -1;
1931 tmproc->reloads = 0;
1932 tmproc->timestamp = -1;
1933 tmproc->relative_pid = 1;
1934 tmproc->ipc_fd[0] = -1;
1935 tmproc->ipc_fd[1] = -1;
William Lallemandce83b4a2018-10-26 14:47:30 +02001936
Willy Tarreau6185a032021-06-15 08:02:06 +02001937 if (mworker_cli_sockpair_new(tmproc, 0) < 0) {
1938 exit(EXIT_FAILURE);
William Lallemandce83b4a2018-10-26 14:47:30 +02001939 }
Willy Tarreau6185a032021-06-15 08:02:06 +02001940
1941 LIST_APPEND(&proc_list, &tmproc->list);
William Lallemand944e6192018-11-21 15:48:31 +01001942 }
1943 if (global.mode & (MODE_MWORKER|MODE_MWORKER_WAIT)) {
1944 struct wordlist *it, *c;
1945
Remi Tricot-Le Breton1f4fa902021-05-19 10:45:12 +02001946 /* get the info of the children in the env */
1947 if (mworker_env_to_proc_list() < 0) {
1948 exit(EXIT_FAILURE);
1949 }
William Lallemande7361152018-10-26 14:47:36 +02001950
William Lallemand550db6d2018-11-06 17:37:12 +01001951 if (!LIST_ISEMPTY(&mworker_cli_conf)) {
William Lallemande7361152018-10-26 14:47:36 +02001952
William Lallemand550db6d2018-11-06 17:37:12 +01001953 if (mworker_cli_proxy_create() < 0) {
William Lallemande7361152018-10-26 14:47:36 +02001954 ha_alert("Can't create the master's CLI.\n");
1955 exit(EXIT_FAILURE);
1956 }
William Lallemande7361152018-10-26 14:47:36 +02001957
William Lallemand550db6d2018-11-06 17:37:12 +01001958 list_for_each_entry_safe(c, it, &mworker_cli_conf, list) {
1959
1960 if (mworker_cli_proxy_new_listener(c->s) < 0) {
1961 ha_alert("Can't create the master's CLI.\n");
1962 exit(EXIT_FAILURE);
1963 }
Willy Tarreau2b718102021-04-21 07:32:39 +02001964 LIST_DELETE(&c->list);
William Lallemand550db6d2018-11-06 17:37:12 +01001965 free(c->s);
1966 free(c);
1967 }
1968 }
William Lallemandce83b4a2018-10-26 14:47:30 +02001969 }
1970
Eric Salama5ba83352021-03-16 15:11:17 +01001971 if (!LIST_ISEMPTY(&mworker_cli_conf) && !(arg_mode & MODE_MWORKER)) {
1972 ha_warning("a master CLI socket was defined, but master-worker mode (-W) is not enabled.\n");
1973 }
1974
Willy Tarreaue90904d2021-02-12 14:08:31 +01001975 /* defaults sections are not needed anymore */
1976 proxy_destroy_all_defaults();
1977
Willy Tarreaubb925012009-07-23 13:36:36 +02001978 err_code |= check_config_validity();
Christopher Fauletc1692962019-08-12 09:51:07 +02001979 for (px = proxies_list; px; px = px->next) {
1980 struct server *srv;
1981 struct post_proxy_check_fct *ppcf;
1982 struct post_server_check_fct *pscf;
1983
Christopher Fauletd5bd8242020-11-02 16:20:13 +01001984 if (px->disabled)
1985 continue;
1986
Christopher Fauletc1692962019-08-12 09:51:07 +02001987 list_for_each_entry(pscf, &post_server_check_list, list) {
1988 for (srv = px->srv; srv; srv = srv->next)
1989 err_code |= pscf->fct(srv);
1990 }
1991 list_for_each_entry(ppcf, &post_proxy_check_list, list)
1992 err_code |= ppcf->fct(px);
1993 }
Willy Tarreaubb925012009-07-23 13:36:36 +02001994 if (err_code & (ERR_ABORT|ERR_FATAL)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001995 ha_alert("Fatal errors found in configuration.\n");
Willy Tarreau915e1eb2009-06-22 15:48:36 +02001996 exit(1);
1997 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001998
Carl Henrik Lundef91ac192020-02-27 16:45:50 +01001999 err_code |= pattern_finalize_config();
2000 if (err_code & (ERR_ABORT|ERR_FATAL)) {
2001 ha_alert("Failed to finalize pattern config.\n");
2002 exit(1);
2003 }
Willy Tarreau0f936722019-04-11 14:47:08 +02002004
Willy Tarreau91358592021-06-15 08:08:04 +02002005 /* recompute the amount of per-process memory depending on
2006 * the shared SSL cache size
Willy Tarreau70060452015-12-14 12:46:07 +01002007 */
2008 if (global.rlimit_memmax_all) {
2009#if defined (USE_OPENSSL) && !defined(USE_PRIVATE_CACHE)
2010 int64_t ssl_cache_bytes = global.tune.sslcachesize * 200LL;
2011
2012 global.rlimit_memmax =
Willy Tarreau91358592021-06-15 08:08:04 +02002013 ((((int64_t)global.rlimit_memmax_all * 1048576LL) - ssl_cache_bytes) +
Willy Tarreau70060452015-12-14 12:46:07 +01002014 ssl_cache_bytes + 1048575LL) / 1048576LL;
2015#else
Willy Tarreau91358592021-06-15 08:08:04 +02002016 global.rlimit_memmax = global.rlimit_memmax_all;
Willy Tarreau70060452015-12-14 12:46:07 +01002017#endif
2018 }
2019
Willy Tarreaue5733232019-05-22 19:24:06 +02002020#ifdef USE_NS
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01002021 err_code |= netns_init();
2022 if (err_code & (ERR_ABORT|ERR_FATAL)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002023 ha_alert("Failed to initialize namespace support.\n");
KOVACS Krisztianb3e54fe2014-11-17 15:11:45 +01002024 exit(1);
2025 }
2026#endif
2027
Baptiste Assmann4215d7d2016-11-02 15:33:15 +01002028 /* Apply server states */
2029 apply_server_state();
2030
Olivier Houchardfbc74e82017-11-24 16:54:05 +01002031 for (px = proxies_list; px; px = px->next)
Baptiste Assmann4215d7d2016-11-02 15:33:15 +01002032 srv_compute_all_admin_states(px);
2033
Baptiste Assmann83cbaa52016-11-02 15:34:05 +01002034 /* Apply servers' configured address */
2035 err_code |= srv_init_addr();
2036 if (err_code & (ERR_ABORT|ERR_FATAL)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002037 ha_alert("Failed to initialize server(s) addr.\n");
Baptiste Assmann83cbaa52016-11-02 15:34:05 +01002038 exit(1);
2039 }
2040
Willy Tarreau3eb10b82020-04-15 16:42:39 +02002041 if (warned & WARN_ANY && global.mode & MODE_ZERO_WARNING) {
2042 ha_alert("Some warnings were found and 'zero-warning' is set. Aborting.\n");
2043 exit(1);
2044 }
2045
Willy Tarreaubaaee002006-06-26 02:48:02 +02002046 if (global.mode & MODE_CHECK) {
Willy Tarreau8b15ba12012-02-02 17:48:18 +01002047 struct peers *pr;
2048 struct proxy *px;
2049
Willy Tarreaubebd2122020-04-15 16:06:11 +02002050 if (warned & WARN_ANY)
2051 qfprintf(stdout, "Warnings were found.\n");
2052
Frédéric Lécailleed2b4a62017-07-13 09:07:09 +02002053 for (pr = cfg_peers; pr; pr = pr->next)
Willy Tarreau8b15ba12012-02-02 17:48:18 +01002054 if (pr->peers_fe)
2055 break;
2056
Olivier Houchardfbc74e82017-11-24 16:54:05 +01002057 for (px = proxies_list; px; px = px->next)
Willy Tarreauc3914d42020-09-24 08:39:22 +02002058 if (!px->disabled && px->li_all)
Willy Tarreau8b15ba12012-02-02 17:48:18 +01002059 break;
2060
2061 if (pr || px) {
2062 /* At least one peer or one listener has been found */
2063 qfprintf(stdout, "Configuration file is valid\n");
Tim Duesterhus0a3b43d2020-06-14 00:37:42 +02002064 deinit_and_exit(0);
Willy Tarreau8b15ba12012-02-02 17:48:18 +01002065 }
2066 qfprintf(stdout, "Configuration file has no error but will not start (no listener) => exit(2).\n");
2067 exit(2);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002068 }
Willy Tarreaue9b26022011-08-01 20:57:55 +02002069
Amaury Denoyelle5a6926d2021-03-30 17:34:24 +02002070 if (global.mode & MODE_DIAG) {
2071 cfg_run_diagnostics();
2072 }
2073
Willy Tarreau8263d2b2012-08-28 00:06:31 +02002074 /* now we know the buffer size, we can initialize the channels and buffers */
Willy Tarreau9b28e032012-10-12 23:49:43 +02002075 init_buffer();
Willy Tarreau8280d642009-09-23 23:37:52 +02002076
Willy Tarreaue6945732016-12-21 19:57:00 +01002077 list_for_each_entry(pcf, &post_check_list, list) {
2078 err_code |= pcf->fct();
2079 if (err_code & (ERR_ABORT|ERR_FATAL))
2080 exit(1);
2081 }
2082
Willy Tarreaubaaee002006-06-26 02:48:02 +02002083 if (cfg_maxconn > 0)
2084 global.maxconn = cfg_maxconn;
2085
Willy Tarreau4975d142021-03-13 11:00:33 +01002086 if (global.cli_fe)
2087 global.maxsock += global.cli_fe->maxconn;
Willy Tarreau8d687d82019-03-01 09:39:42 +01002088
2089 if (cfg_peers) {
2090 /* peers also need to bypass global maxconn */
2091 struct peers *p = cfg_peers;
2092
2093 for (p = cfg_peers; p; p = p->next)
2094 if (p->peers_fe)
2095 global.maxsock += p->peers_fe->maxconn;
2096 }
2097
Willy Tarreaubaaee002006-06-26 02:48:02 +02002098 if (cfg_pidfile) {
Willy Tarreaua534fea2008-08-03 12:19:50 +02002099 free(global.pidfile);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002100 global.pidfile = strdup(cfg_pidfile);
2101 }
2102
Willy Tarreaud0256482015-01-15 21:45:22 +01002103 /* Now we want to compute the maxconn and possibly maxsslconn values.
Willy Tarreauac350932019-03-01 15:43:14 +01002104 * It's a bit tricky. Maxconn defaults to the pre-computed value based
2105 * on rlim_fd_cur and the number of FDs in use due to the configuration,
2106 * and maxsslconn defaults to DEFAULT_MAXSSLCONN. On top of that we can
2107 * enforce a lower limit based on memmax.
Willy Tarreaud0256482015-01-15 21:45:22 +01002108 *
2109 * If memmax is set, then it depends on which values are set. If
2110 * maxsslconn is set, we use memmax to determine how many cleartext
2111 * connections may be added, and set maxconn to the sum of the two.
2112 * If maxconn is set and not maxsslconn, maxsslconn is computed from
2113 * the remaining amount of memory between memmax and the cleartext
2114 * connections. If neither are set, then it is considered that all
2115 * connections are SSL-capable, and maxconn is computed based on this,
2116 * then maxsslconn accordingly. We need to know if SSL is used on the
2117 * frontends, backends, or both, because when it's used on both sides,
2118 * we need twice the value for maxsslconn, but we only count the
2119 * handshake once since it is not performed on the two sides at the
2120 * same time (frontend-side is terminated before backend-side begins).
2121 * The SSL stack is supposed to have filled ssl_session_cost and
Willy Tarreau474b96a2015-01-28 19:03:21 +01002122 * ssl_handshake_cost during its initialization. In any case, if
2123 * SYSTEM_MAXCONN is set, we still enforce it as an upper limit for
2124 * maxconn in order to protect the system.
Willy Tarreaud0256482015-01-15 21:45:22 +01002125 */
Willy Tarreauac350932019-03-01 15:43:14 +01002126 ideal_maxconn = compute_ideal_maxconn();
2127
Willy Tarreaud0256482015-01-15 21:45:22 +01002128 if (!global.rlimit_memmax) {
2129 if (global.maxconn == 0) {
Willy Tarreauac350932019-03-01 15:43:14 +01002130 global.maxconn = ideal_maxconn;
Willy Tarreaud0256482015-01-15 21:45:22 +01002131 if (global.mode & (MODE_VERBOSE|MODE_DEBUG))
2132 fprintf(stderr, "Note: setting global.maxconn to %d.\n", global.maxconn);
2133 }
2134 }
2135#ifdef USE_OPENSSL
2136 else if (!global.maxconn && !global.maxsslconn &&
2137 (global.ssl_used_frontend || global.ssl_used_backend)) {
2138 /* memmax is set, compute everything automatically. Here we want
2139 * to ensure that all SSL connections will be served. We take
2140 * care of the number of sides where SSL is used, and consider
2141 * the worst case : SSL used on both sides and doing a handshake
2142 * simultaneously. Note that we can't have more than maxconn
2143 * handshakes at a time by definition, so for the worst case of
2144 * two SSL conns per connection, we count a single handshake.
2145 */
2146 int sides = !!global.ssl_used_frontend + !!global.ssl_used_backend;
2147 int64_t mem = global.rlimit_memmax * 1048576ULL;
Willy Tarreau304e17e2020-03-10 17:54:54 +01002148 int retried = 0;
Willy Tarreaud0256482015-01-15 21:45:22 +01002149
2150 mem -= global.tune.sslcachesize * 200; // about 200 bytes per SSL cache entry
2151 mem -= global.maxzlibmem;
2152 mem = mem * MEM_USABLE_RATIO;
2153
Willy Tarreau304e17e2020-03-10 17:54:54 +01002154 /* Principle: we test once to set maxconn according to the free
2155 * memory. If it results in values the system rejects, we try a
2156 * second time by respecting rlim_fd_max. If it fails again, we
2157 * go back to the initial value and will let the final code
2158 * dealing with rlimit report the error. That's up to 3 attempts.
2159 */
2160 do {
2161 global.maxconn = mem /
2162 ((STREAM_MAX_COST + 2 * global.tune.bufsize) + // stream + 2 buffers per stream
2163 sides * global.ssl_session_max_cost + // SSL buffers, one per side
2164 global.ssl_handshake_max_cost); // 1 handshake per connection max
Willy Tarreaud0256482015-01-15 21:45:22 +01002165
Willy Tarreau304e17e2020-03-10 17:54:54 +01002166 if (retried == 1)
2167 global.maxconn = MIN(global.maxconn, ideal_maxconn);
2168 global.maxconn = round_2dig(global.maxconn);
Willy Tarreau474b96a2015-01-28 19:03:21 +01002169#ifdef SYSTEM_MAXCONN
Willy Tarreau304e17e2020-03-10 17:54:54 +01002170 if (global.maxconn > SYSTEM_MAXCONN)
2171 global.maxconn = SYSTEM_MAXCONN;
Willy Tarreau474b96a2015-01-28 19:03:21 +01002172#endif /* SYSTEM_MAXCONN */
Willy Tarreau304e17e2020-03-10 17:54:54 +01002173 global.maxsslconn = sides * global.maxconn;
2174
2175 if (check_if_maxsock_permitted(compute_ideal_maxsock(global.maxconn)))
2176 break;
2177 } while (retried++ < 2);
2178
Willy Tarreaud0256482015-01-15 21:45:22 +01002179 if (global.mode & (MODE_VERBOSE|MODE_DEBUG))
2180 fprintf(stderr, "Note: setting global.maxconn to %d and global.maxsslconn to %d.\n",
2181 global.maxconn, global.maxsslconn);
2182 }
2183 else if (!global.maxsslconn &&
2184 (global.ssl_used_frontend || global.ssl_used_backend)) {
2185 /* memmax and maxconn are known, compute maxsslconn automatically.
2186 * maxsslconn being forced, we don't know how many of it will be
2187 * on each side if both sides are being used. The worst case is
2188 * when all connections use only one SSL instance because
2189 * handshakes may be on two sides at the same time.
2190 */
2191 int sides = !!global.ssl_used_frontend + !!global.ssl_used_backend;
2192 int64_t mem = global.rlimit_memmax * 1048576ULL;
2193 int64_t sslmem;
2194
2195 mem -= global.tune.sslcachesize * 200; // about 200 bytes per SSL cache entry
2196 mem -= global.maxzlibmem;
2197 mem = mem * MEM_USABLE_RATIO;
2198
Willy Tarreau87b09662015-04-03 00:22:06 +02002199 sslmem = mem - global.maxconn * (int64_t)(STREAM_MAX_COST + 2 * global.tune.bufsize);
Willy Tarreaud0256482015-01-15 21:45:22 +01002200 global.maxsslconn = sslmem / (global.ssl_session_max_cost + global.ssl_handshake_max_cost);
2201 global.maxsslconn = round_2dig(global.maxsslconn);
2202
2203 if (sslmem <= 0 || global.maxsslconn < sides) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002204 ha_alert("Cannot compute the automatic maxsslconn because global.maxconn is already too "
2205 "high for the global.memmax value (%d MB). The absolute maximum possible value "
2206 "without SSL is %d, but %d was found and SSL is in use.\n",
2207 global.rlimit_memmax,
2208 (int)(mem / (STREAM_MAX_COST + 2 * global.tune.bufsize)),
2209 global.maxconn);
Willy Tarreaud0256482015-01-15 21:45:22 +01002210 exit(1);
2211 }
2212
2213 if (global.maxsslconn > sides * global.maxconn)
2214 global.maxsslconn = sides * global.maxconn;
2215
2216 if (global.mode & (MODE_VERBOSE|MODE_DEBUG))
2217 fprintf(stderr, "Note: setting global.maxsslconn to %d\n", global.maxsslconn);
2218 }
2219#endif
2220 else if (!global.maxconn) {
2221 /* memmax and maxsslconn are known/unused, compute maxconn automatically */
2222 int sides = !!global.ssl_used_frontend + !!global.ssl_used_backend;
2223 int64_t mem = global.rlimit_memmax * 1048576ULL;
2224 int64_t clearmem;
Willy Tarreau304e17e2020-03-10 17:54:54 +01002225 int retried = 0;
Willy Tarreaud0256482015-01-15 21:45:22 +01002226
2227 if (global.ssl_used_frontend || global.ssl_used_backend)
2228 mem -= global.tune.sslcachesize * 200; // about 200 bytes per SSL cache entry
2229
2230 mem -= global.maxzlibmem;
2231 mem = mem * MEM_USABLE_RATIO;
2232
2233 clearmem = mem;
2234 if (sides)
2235 clearmem -= (global.ssl_session_max_cost + global.ssl_handshake_max_cost) * (int64_t)global.maxsslconn;
2236
Willy Tarreau304e17e2020-03-10 17:54:54 +01002237 /* Principle: we test once to set maxconn according to the free
2238 * memory. If it results in values the system rejects, we try a
2239 * second time by respecting rlim_fd_max. If it fails again, we
2240 * go back to the initial value and will let the final code
2241 * dealing with rlimit report the error. That's up to 3 attempts.
2242 */
2243 do {
2244 global.maxconn = clearmem / (STREAM_MAX_COST + 2 * global.tune.bufsize);
2245 if (retried == 1)
2246 global.maxconn = MIN(global.maxconn, ideal_maxconn);
2247 global.maxconn = round_2dig(global.maxconn);
Willy Tarreau474b96a2015-01-28 19:03:21 +01002248#ifdef SYSTEM_MAXCONN
Willy Tarreau304e17e2020-03-10 17:54:54 +01002249 if (global.maxconn > SYSTEM_MAXCONN)
2250 global.maxconn = SYSTEM_MAXCONN;
Willy Tarreau474b96a2015-01-28 19:03:21 +01002251#endif /* SYSTEM_MAXCONN */
Willy Tarreaud0256482015-01-15 21:45:22 +01002252
Willy Tarreau304e17e2020-03-10 17:54:54 +01002253 if (clearmem <= 0 || !global.maxconn) {
2254 ha_alert("Cannot compute the automatic maxconn because global.maxsslconn is already too "
2255 "high for the global.memmax value (%d MB). The absolute maximum possible value "
2256 "is %d, but %d was found.\n",
2257 global.rlimit_memmax,
Christopher Faulet767a84b2017-11-24 16:50:31 +01002258 (int)(mem / (global.ssl_session_max_cost + global.ssl_handshake_max_cost)),
Willy Tarreau304e17e2020-03-10 17:54:54 +01002259 global.maxsslconn);
2260 exit(1);
2261 }
2262
2263 if (check_if_maxsock_permitted(compute_ideal_maxsock(global.maxconn)))
2264 break;
2265 } while (retried++ < 2);
Willy Tarreaud0256482015-01-15 21:45:22 +01002266
2267 if (global.mode & (MODE_VERBOSE|MODE_DEBUG)) {
2268 if (sides && global.maxsslconn > sides * global.maxconn) {
2269 fprintf(stderr, "Note: global.maxsslconn is forced to %d which causes global.maxconn "
2270 "to be limited to %d. Better reduce global.maxsslconn to get more "
2271 "room for extra connections.\n", global.maxsslconn, global.maxconn);
2272 }
2273 fprintf(stderr, "Note: setting global.maxconn to %d\n", global.maxconn);
2274 }
Willy Tarreau66aa61f2009-01-18 21:44:07 +01002275 }
2276
Willy Tarreaua409f302020-03-10 17:08:53 +01002277 global.maxsock = compute_ideal_maxsock(global.maxconn);
2278 global.hardmaxconn = global.maxconn;
Willy Tarreaua4818db2020-06-19 16:20:59 +02002279 if (!global.maxpipes)
2280 global.maxpipes = compute_ideal_maxpipes();
Willy Tarreaubaaee002006-06-26 02:48:02 +02002281
Olivier Houchard88698d92019-04-16 19:07:22 +02002282 /* update connection pool thresholds */
2283 global.tune.pool_low_count = ((long long)global.maxsock * global.tune.pool_low_ratio + 99) / 100;
2284 global.tune.pool_high_count = ((long long)global.maxsock * global.tune.pool_high_ratio + 99) / 100;
2285
Willy Tarreauc8d5b952019-02-27 17:25:52 +01002286 proxy_adjust_all_maxconn();
2287
Willy Tarreau1db37712007-06-03 17:16:49 +02002288 if (global.tune.maxpollevents <= 0)
2289 global.tune.maxpollevents = MAX_POLL_EVENTS;
2290
Willy Tarreau060a7612021-03-10 11:06:26 +01002291 if (global.tune.runqueue_depth <= 0) {
2292 /* tests on various thread counts from 1 to 64 have shown an
2293 * optimal queue depth following roughly 1/sqrt(threads).
2294 */
2295 int s = my_flsl(global.nbthread);
2296 s += (global.nbthread / s); // roughly twice the sqrt.
2297 global.tune.runqueue_depth = RUNQUEUE_DEPTH * 2 / s;
2298 }
Olivier Houchard1599b802018-05-24 18:59:04 +02002299
Willy Tarreau6f4a82c2009-03-21 20:43:57 +01002300 if (global.tune.recv_enough == 0)
2301 global.tune.recv_enough = MIN_RECV_AT_ONCE_ENOUGH;
2302
Willy Tarreau27a674e2009-08-17 07:23:33 +02002303 if (global.tune.maxrewrite >= global.tune.bufsize / 2)
2304 global.tune.maxrewrite = global.tune.bufsize / 2;
2305
Amaury Denoyelle11124302021-06-04 18:22:08 +02002306 usermsgs_clr(NULL);
2307
Willy Tarreaubaaee002006-06-26 02:48:02 +02002308 if (arg_mode & (MODE_DEBUG | MODE_FOREGROUND)) {
2309 /* command line debug mode inhibits configuration mode */
William Lallemand095ba4c2017-06-01 17:38:50 +02002310 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
Willy Tarreau772f0dd2012-10-26 16:04:28 +02002311 global.mode |= (arg_mode & (MODE_DEBUG | MODE_FOREGROUND));
2312 }
2313
William Lallemand095ba4c2017-06-01 17:38:50 +02002314 if (arg_mode & MODE_DAEMON) {
Willy Tarreau772f0dd2012-10-26 16:04:28 +02002315 /* command line daemon mode inhibits foreground and debug modes mode */
2316 global.mode &= ~(MODE_DEBUG | MODE_FOREGROUND);
William Lallemand095ba4c2017-06-01 17:38:50 +02002317 global.mode |= arg_mode & MODE_DAEMON;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002318 }
Willy Tarreau772f0dd2012-10-26 16:04:28 +02002319
2320 global.mode |= (arg_mode & (MODE_QUIET | MODE_VERBOSE));
Willy Tarreaubaaee002006-06-26 02:48:02 +02002321
William Lallemand095ba4c2017-06-01 17:38:50 +02002322 if ((global.mode & MODE_DEBUG) && (global.mode & (MODE_DAEMON | MODE_QUIET))) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002323 ha_warning("<debug> mode incompatible with <quiet> and <daemon>. Keeping <debug> only.\n");
William Lallemand095ba4c2017-06-01 17:38:50 +02002324 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002325 }
2326
Christopher Fauletbe0faa22017-08-29 15:37:10 +02002327 if (global.nbthread < 1)
2328 global.nbthread = 1;
2329
Christopher Faulet3ef26392017-08-29 16:46:57 +02002330 /* Realloc trash buffers because global.tune.bufsize may have changed */
Christopher Fauletcd7879a2017-10-27 13:53:47 +02002331 if (!init_trash_buffers(0)) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002332 ha_alert("failed to initialize trash buffers.\n");
Christopher Faulet3ef26392017-08-29 16:46:57 +02002333 exit(1);
2334 }
2335
Christopher Faulet96d44832017-11-14 22:02:30 +01002336 if (!init_log_buffers()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002337 ha_alert("failed to initialize log buffers.\n");
Christopher Faulet96d44832017-11-14 22:02:30 +01002338 exit(1);
2339 }
2340
Willy Tarreauef1d1f82007-04-16 00:25:25 +02002341 /*
2342 * Note: we could register external pollers here.
2343 * Built-in pollers have been registered before main().
2344 */
Willy Tarreau4f60f162007-04-08 16:39:58 +02002345
Willy Tarreau43b78992009-01-25 15:42:27 +01002346 if (!(global.tune.options & GTUNE_USE_KQUEUE))
Willy Tarreau1e63130a2007-04-09 12:03:06 +02002347 disable_poller("kqueue");
2348
Emmanuel Hocdet0ba4f482019-04-08 16:53:32 +00002349 if (!(global.tune.options & GTUNE_USE_EVPORTS))
2350 disable_poller("evports");
2351
Willy Tarreau43b78992009-01-25 15:42:27 +01002352 if (!(global.tune.options & GTUNE_USE_EPOLL))
Willy Tarreau4f60f162007-04-08 16:39:58 +02002353 disable_poller("epoll");
2354
Willy Tarreau43b78992009-01-25 15:42:27 +01002355 if (!(global.tune.options & GTUNE_USE_POLL))
Willy Tarreau4f60f162007-04-08 16:39:58 +02002356 disable_poller("poll");
2357
Willy Tarreau43b78992009-01-25 15:42:27 +01002358 if (!(global.tune.options & GTUNE_USE_SELECT))
Willy Tarreau4f60f162007-04-08 16:39:58 +02002359 disable_poller("select");
2360
2361 /* Note: we could disable any poller by name here */
2362
Christopher Fauletb3f4e142016-03-07 12:46:38 +01002363 if (global.mode & (MODE_VERBOSE|MODE_DEBUG)) {
Willy Tarreau2ff76222007-04-09 19:29:56 +02002364 list_pollers(stderr);
Christopher Fauletb3f4e142016-03-07 12:46:38 +01002365 fprintf(stderr, "\n");
2366 list_filters(stderr);
2367 }
Willy Tarreau2ff76222007-04-09 19:29:56 +02002368
Willy Tarreau4f60f162007-04-08 16:39:58 +02002369 if (!init_pollers()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002370 ha_alert("No polling mechanism available.\n"
2371 " It is likely that haproxy was built with TARGET=generic and that FD_SETSIZE\n"
2372 " is too low on this platform to support maxconn and the number of listeners\n"
2373 " and servers. You should rebuild haproxy specifying your system using TARGET=\n"
2374 " in order to support other polling systems (poll, epoll, kqueue) or reduce the\n"
2375 " global maxconn setting to accommodate the system's limitation. For reference,\n"
2376 " FD_SETSIZE=%d on this system, global.maxconn=%d resulting in a maximum of\n"
2377 " %d file descriptors. You should thus reduce global.maxconn by %d. Also,\n"
2378 " check build settings using 'haproxy -vv'.\n\n",
2379 FD_SETSIZE, global.maxconn, global.maxsock, (global.maxsock + 1 - FD_SETSIZE) / 2);
Willy Tarreau4f60f162007-04-08 16:39:58 +02002380 exit(1);
2381 }
Willy Tarreau2ff76222007-04-09 19:29:56 +02002382 if (global.mode & (MODE_VERBOSE|MODE_DEBUG)) {
2383 printf("Using %s() as the polling mechanism.\n", cur_poller.name);
Willy Tarreau4f60f162007-04-08 16:39:58 +02002384 }
2385
Krzysztof Piotr Oledzki48cb2ae2009-10-02 22:51:14 +02002386 if (!global.node)
2387 global.node = strdup(hostname);
2388
Willy Tarreau02b092f2020-10-07 18:36:54 +02002389 /* stop disabled proxies */
2390 for (px = proxies_list; px; px = px->next) {
Willy Tarreauc3914d42020-09-24 08:39:22 +02002391 if (px->disabled)
Willy Tarreau02b092f2020-10-07 18:36:54 +02002392 stop_proxy(px);
2393 }
2394
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01002395 if (!hlua_post_init())
2396 exit(1);
Thomas Holmes6abded42015-05-12 16:23:58 +01002397
Maxime de Roucy0f503922016-05-13 23:52:55 +02002398 free(err_msg);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002399}
2400
Cyril Bonté203ec5a2017-03-23 22:44:13 +01002401void deinit(void)
Willy Tarreaubaaee002006-06-26 02:48:02 +02002402{
Olivier Houchardfbc74e82017-11-24 16:54:05 +01002403 struct proxy *p = proxies_list, *p0;
Willy Tarreaudeb9ed82010-01-03 21:03:22 +01002404 struct wordlist *wl, *wlb;
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002405 struct uri_auth *uap, *ua = NULL;
William Lallemand0f99e342011-10-12 17:50:54 +02002406 struct logsrv *log, *logb;
Willy Tarreaucdb737e2016-12-21 18:43:10 +01002407 struct build_opts_str *bol, *bolb;
Tim Duesterhusfdf904a2020-07-04 11:49:48 +02002408 struct post_deinit_fct *pdf, *pdfb;
Tim Duesterhus17e363f2020-07-04 11:49:47 +02002409 struct proxy_deinit_fct *pxdf, *pxdfb;
Tim Duesterhus0837eb12020-07-04 11:49:49 +02002410 struct server_deinit_fct *srvdf, *srvdfb;
Tim Duesterhusf0c25d22020-09-10 19:46:41 +02002411 struct per_thread_init_fct *tif, *tifb;
2412 struct per_thread_deinit_fct *tdf, *tdfb;
2413 struct per_thread_alloc_fct *taf, *tafb;
2414 struct per_thread_free_fct *tff, *tffb;
Tim Duesterhus34bef072020-07-04 11:49:50 +02002415 struct post_server_check_fct *pscf, *pscfb;
Tim Duesterhusfc854942020-09-10 19:46:42 +02002416 struct post_check_fct *pcf, *pcfb;
Tim Duesterhus53508d62020-09-10 19:46:40 +02002417 struct post_proxy_check_fct *ppcf, *ppcfb;
Willy Tarreauae7bc4a2020-09-23 16:46:22 +02002418 int cur_fd;
2419
2420 /* At this point the listeners state is weird:
2421 * - most listeners are still bound and referenced in their protocol
2422 * - some might be zombies that are not in their proto anymore, but
2423 * still appear in their proxy's listeners with a valid FD.
2424 * - some might be stopped and still appear in their proxy as FD #-1
2425 * - among all of them, some might be inherited hence shared and we're
2426 * not allowed to pause them or whatever, we must just close them.
2427 * - finally some are not listeners (pipes, logs, stdout, etc) and
2428 * must be left intact.
2429 *
2430 * The safe way to proceed is to unbind (and close) whatever is not yet
2431 * unbound so that no more receiver/listener remains alive. Then close
2432 * remaining listener FDs, which correspond to zombie listeners (those
2433 * belonging to disabled proxies that were in another process).
2434 * objt_listener() would be cleaner here but not converted yet.
2435 */
2436 protocol_unbind_all();
2437
2438 for (cur_fd = 0; cur_fd < global.maxsock; cur_fd++) {
Willy Tarreau1a3770c2020-10-14 12:13:51 +02002439 if (!fdtab || !fdtab[cur_fd].owner)
Willy Tarreauae7bc4a2020-09-23 16:46:22 +02002440 continue;
2441
Willy Tarreaua74cb382020-10-15 21:29:49 +02002442 if (fdtab[cur_fd].iocb == &sock_accept_iocb) {
Willy Tarreauae7bc4a2020-09-23 16:46:22 +02002443 struct listener *l = fdtab[cur_fd].owner;
2444
2445 BUG_ON(l->state != LI_INIT);
2446 unbind_listener(l);
2447 }
2448 }
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002449
Willy Tarreau24f4efa2010-08-27 17:56:48 +02002450 deinit_signals();
Willy Tarreaubaaee002006-06-26 02:48:02 +02002451 while (p) {
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002452 /* build a list of unique uri_auths */
2453 if (!ua)
2454 ua = p->uri_auth;
2455 else {
2456 /* check if p->uri_auth is unique */
2457 for (uap = ua; uap; uap=uap->next)
2458 if (uap == p->uri_auth)
2459 break;
2460
Willy Tarreauaccc4e12008-06-24 11:14:45 +02002461 if (!uap && p->uri_auth) {
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002462 /* add it, if it is */
2463 p->uri_auth->next = ua;
2464 ua = p->uri_auth;
2465 }
William Lallemand0f99e342011-10-12 17:50:54 +02002466 }
2467
Willy Tarreau4d2d0982007-05-14 00:39:29 +02002468 p0 = p;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002469 p = p->next;
Amaury Denoyelle27fefa12021-03-24 16:13:20 +01002470 free_proxy(p0);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002471 }/* end while(p) */
Willy Tarreaudd815982007-10-16 12:25:14 +02002472
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002473 while (ua) {
Tim Duesterhus00f00cf2020-09-10 19:46:38 +02002474 struct stat_scope *scope, *scopep;
2475
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002476 uap = ua;
2477 ua = ua->next;
2478
Willy Tarreaua534fea2008-08-03 12:19:50 +02002479 free(uap->uri_prefix);
2480 free(uap->auth_realm);
Krzysztof Piotr Oledzki48cb2ae2009-10-02 22:51:14 +02002481 free(uap->node);
2482 free(uap->desc);
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002483
Krzysztof Piotr Oledzki8c8bd452010-01-29 19:29:32 +01002484 userlist_free(uap->userlist);
Amaury Denoyelle68fd7e42021-03-25 17:15:52 +01002485 free_act_rules(&uap->http_req_rules);
Krzysztof Piotr Oledzki8c8bd452010-01-29 19:29:32 +01002486
Tim Duesterhus00f00cf2020-09-10 19:46:38 +02002487 scope = uap->scope;
2488 while (scope) {
2489 scopep = scope;
2490 scope = scope->next;
2491
2492 free(scopep->px_id);
2493 free(scopep);
2494 }
2495
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002496 free(uap);
2497 }
2498
Krzysztof Piotr Oledzki96105042010-01-29 17:50:44 +01002499 userlist_free(userlist);
2500
David Carlier834cb2e2015-09-25 12:02:25 +01002501 cfg_unregister_sections();
2502
Christopher Faulet0132d062017-07-26 15:33:35 +02002503 deinit_log_buffers();
David Carlier834cb2e2015-09-25 12:02:25 +01002504
Willy Tarreau05554e62016-12-21 20:46:26 +01002505 list_for_each_entry(pdf, &post_deinit_list, list)
2506 pdf->fct();
2507
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002508 ha_free(&global.log_send_hostname);
Dragan Dosen43885c72015-10-01 13:18:13 +02002509 chunk_destroy(&global.log_tag);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002510 ha_free(&global.chroot);
2511 ha_free(&global.pidfile);
2512 ha_free(&global.node);
2513 ha_free(&global.desc);
2514 ha_free(&oldpids);
2515 ha_free(&old_argv);
2516 ha_free(&localpeer);
2517 ha_free(&global.server_state_base);
2518 ha_free(&global.server_state_file);
Olivier Houchard3f795f72019-04-17 22:51:06 +02002519 task_destroy(idle_conn_task);
Olivier Houchard9ea5d362019-02-14 18:29:09 +01002520 idle_conn_task = NULL;
Krzysztof Piotr Oledzki8001d612008-05-31 13:53:23 +02002521
William Lallemand0f99e342011-10-12 17:50:54 +02002522 list_for_each_entry_safe(log, logb, &global.logsrvs, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002523 LIST_DELETE(&log->list);
Amaury Denoyelled688e012021-04-20 17:05:47 +02002524 free(log->conf.file);
William Lallemand0f99e342011-10-12 17:50:54 +02002525 free(log);
2526 }
Willy Tarreau477ecd82010-01-03 21:12:30 +01002527 list_for_each_entry_safe(wl, wlb, &cfg_cfgfiles, list) {
Maxime de Roucy0f503922016-05-13 23:52:55 +02002528 free(wl->s);
Willy Tarreau2b718102021-04-21 07:32:39 +02002529 LIST_DELETE(&wl->list);
Willy Tarreau477ecd82010-01-03 21:12:30 +01002530 free(wl);
2531 }
2532
Willy Tarreaucdb737e2016-12-21 18:43:10 +01002533 list_for_each_entry_safe(bol, bolb, &build_opts_list, list) {
2534 if (bol->must_free)
2535 free((void *)bol->str);
Willy Tarreau2b718102021-04-21 07:32:39 +02002536 LIST_DELETE(&bol->list);
Willy Tarreaucdb737e2016-12-21 18:43:10 +01002537 free(bol);
2538 }
2539
Tim Duesterhus17e363f2020-07-04 11:49:47 +02002540 list_for_each_entry_safe(pxdf, pxdfb, &proxy_deinit_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002541 LIST_DELETE(&pxdf->list);
Tim Duesterhus17e363f2020-07-04 11:49:47 +02002542 free(pxdf);
2543 }
2544
Tim Duesterhusfdf904a2020-07-04 11:49:48 +02002545 list_for_each_entry_safe(pdf, pdfb, &post_deinit_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002546 LIST_DELETE(&pdf->list);
Tim Duesterhusfdf904a2020-07-04 11:49:48 +02002547 free(pdf);
2548 }
2549
Tim Duesterhus0837eb12020-07-04 11:49:49 +02002550 list_for_each_entry_safe(srvdf, srvdfb, &server_deinit_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002551 LIST_DELETE(&srvdf->list);
Tim Duesterhus0837eb12020-07-04 11:49:49 +02002552 free(srvdf);
2553 }
2554
Tim Duesterhusfc854942020-09-10 19:46:42 +02002555 list_for_each_entry_safe(pcf, pcfb, &post_check_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002556 LIST_DELETE(&pcf->list);
Tim Duesterhusfc854942020-09-10 19:46:42 +02002557 free(pcf);
2558 }
2559
Tim Duesterhus34bef072020-07-04 11:49:50 +02002560 list_for_each_entry_safe(pscf, pscfb, &post_server_check_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002561 LIST_DELETE(&pscf->list);
Tim Duesterhus34bef072020-07-04 11:49:50 +02002562 free(pscf);
2563 }
2564
Tim Duesterhus53508d62020-09-10 19:46:40 +02002565 list_for_each_entry_safe(ppcf, ppcfb, &post_proxy_check_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002566 LIST_DELETE(&ppcf->list);
Tim Duesterhus53508d62020-09-10 19:46:40 +02002567 free(ppcf);
2568 }
2569
Tim Duesterhusf0c25d22020-09-10 19:46:41 +02002570 list_for_each_entry_safe(tif, tifb, &per_thread_init_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002571 LIST_DELETE(&tif->list);
Tim Duesterhusf0c25d22020-09-10 19:46:41 +02002572 free(tif);
2573 }
2574
2575 list_for_each_entry_safe(tdf, tdfb, &per_thread_deinit_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002576 LIST_DELETE(&tdf->list);
Tim Duesterhusf0c25d22020-09-10 19:46:41 +02002577 free(tdf);
2578 }
2579
2580 list_for_each_entry_safe(taf, tafb, &per_thread_alloc_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002581 LIST_DELETE(&taf->list);
Tim Duesterhusf0c25d22020-09-10 19:46:41 +02002582 free(taf);
2583 }
2584
2585 list_for_each_entry_safe(tff, tffb, &per_thread_free_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002586 LIST_DELETE(&tff->list);
Tim Duesterhusf0c25d22020-09-10 19:46:41 +02002587 free(tff);
2588 }
2589
Willy Tarreaucfc4f242021-05-08 11:41:28 +02002590 vars_prune(&proc_vars, NULL, NULL);
Willy Tarreau2455ceb2018-11-26 15:57:34 +01002591 pool_destroy_all();
Krzysztof Piotr Oledzkia643baf2008-05-29 23:53:44 +02002592 deinit_pollers();
Willy Tarreaubaaee002006-06-26 02:48:02 +02002593} /* end deinit() */
2594
Willy Tarreauf3ca5a02020-06-15 18:43:46 +02002595__attribute__((noreturn)) void deinit_and_exit(int status)
Tim Duesterhus26540552020-06-14 00:37:41 +02002596{
2597 deinit();
2598 exit(status);
2599}
William Lallemand72160322018-11-06 17:37:16 +01002600
Amaury Denoyelled3a88c12021-05-03 10:47:51 +02002601/* Handler of the task of mux_stopping_data.
2602 * Called on soft-stop.
2603 */
2604struct task *mux_stopping_process(struct task *t, void *ctx, unsigned int state)
2605{
2606 struct connection *conn, *back;
2607
2608 list_for_each_entry_safe(conn, back, &mux_stopping_data[tid].list, stopping_list) {
2609 if (conn->mux && conn->mux->wake)
2610 conn->mux->wake(conn);
2611 }
2612
2613 return t;
2614}
2615
Willy Tarreau918ff602011-07-25 16:33:49 +02002616/* Runs the polling loop */
Willy Tarreau3ebd55e2020-03-03 14:59:56 +01002617void run_poll_loop()
Willy Tarreau4f60f162007-04-08 16:39:58 +02002618{
Willy Tarreau2ae84e42019-05-28 16:44:05 +02002619 int next, wake;
Willy Tarreau4f60f162007-04-08 16:39:58 +02002620
Amaury Denoyelled3a88c12021-05-03 10:47:51 +02002621 /* allocates the thread bound mux_stopping_data task */
2622 mux_stopping_data[tid].task = task_new(tid_bit);
2623 mux_stopping_data[tid].task->process = mux_stopping_process;
2624 LIST_INIT(&mux_stopping_data[tid].list);
2625
Willy Tarreaub0b37bc2008-06-23 14:00:57 +02002626 tv_update_date(0,1);
Willy Tarreau4f60f162007-04-08 16:39:58 +02002627 while (1) {
Willy Tarreauc49ba522019-12-11 08:12:23 +01002628 wake_expired_tasks();
2629
William Lallemand1aab50b2018-06-07 09:46:01 +02002630 /* check if we caught some signals and process them in the
2631 first thread */
Willy Tarreaua7ad4ae2020-06-19 12:06:34 +02002632 if (signal_queue_len && tid == 0) {
2633 activity[tid].wake_signal++;
William Lallemand1aab50b2018-06-07 09:46:01 +02002634 signal_process_queue();
Willy Tarreaua7ad4ae2020-06-19 12:06:34 +02002635 }
2636
2637 /* Process a few tasks */
2638 process_runnable_tasks();
Willy Tarreau29857942009-05-10 09:01:21 +02002639
Willy Tarreau7067b3a2019-06-02 11:11:29 +02002640 /* also stop if we failed to cleanly stop all tasks */
2641 if (killed > 1)
2642 break;
2643
Willy Tarreau10146c92015-04-13 20:44:19 +02002644 /* expire immediately if events are pending */
Willy Tarreau2ae84e42019-05-28 16:44:05 +02002645 wake = 1;
Olivier Houchard305d5ab2019-07-24 18:07:06 +02002646 if (thread_has_tasks())
Willy Tarreaud80cb4e2018-01-20 19:30:13 +01002647 activity[tid].wake_tasks++;
Olivier Houchard79321b92018-07-26 17:55:11 +02002648 else {
Olivier Houchardb23a61f2019-03-08 18:51:17 +01002649 _HA_ATOMIC_OR(&sleeping_thread_mask, tid_bit);
2650 __ha_barrier_atomic_store();
Willy Tarreau95abd5b2020-03-23 09:33:32 +01002651 if (thread_has_tasks()) {
Olivier Houchard79321b92018-07-26 17:55:11 +02002652 activity[tid].wake_tasks++;
Olivier Houchardb23a61f2019-03-08 18:51:17 +01002653 _HA_ATOMIC_AND(&sleeping_thread_mask, ~tid_bit);
Olivier Houchard79321b92018-07-26 17:55:11 +02002654 } else
Willy Tarreau2ae84e42019-05-28 16:44:05 +02002655 wake = 0;
Olivier Houchard79321b92018-07-26 17:55:11 +02002656 }
Willy Tarreau10146c92015-04-13 20:44:19 +02002657
Willy Tarreau4f46a352020-03-23 09:27:28 +01002658 if (!wake) {
Willy Tarreaud7a6b2f2020-05-13 13:51:01 +02002659 int i;
2660
2661 if (stopping) {
Ilya Shipitsin3df59892021-05-10 12:50:00 +05002662 /* stop muxes before acknowledging stopping */
Amaury Denoyelled3a88c12021-05-03 10:47:51 +02002663 if (!(stopping_thread_mask & tid_bit)) {
2664 task_wakeup(mux_stopping_data[tid].task, TASK_WOKEN_OTHER);
2665 wake = 1;
2666 }
2667
Willy Tarreau1db42732021-04-06 11:44:07 +02002668 if (_HA_ATOMIC_OR_FETCH(&stopping_thread_mask, tid_bit) == tid_bit) {
Willy Tarreaud6455742020-05-13 14:30:25 +02002669 /* notify all threads that stopping was just set */
2670 for (i = 0; i < global.nbthread; i++)
Willy Tarreau369a2ef2020-06-29 19:23:19 +02002671 if (((all_threads_mask & ~stopping_thread_mask) >> i) & 1)
Willy Tarreaud6455742020-05-13 14:30:25 +02002672 wake_thread(i);
2673 }
Willy Tarreaud7a6b2f2020-05-13 13:51:01 +02002674 }
Willy Tarreau4f46a352020-03-23 09:27:28 +01002675
2676 /* stop when there's nothing left to do */
2677 if ((jobs - unstoppable_jobs) == 0 &&
Willy Tarreaud7a6b2f2020-05-13 13:51:01 +02002678 (stopping_thread_mask & all_threads_mask) == all_threads_mask) {
2679 /* wake all threads waiting on jobs==0 */
2680 for (i = 0; i < global.nbthread; i++)
2681 if (((all_threads_mask & ~tid_bit) >> i) & 1)
2682 wake_thread(i);
Willy Tarreau4f46a352020-03-23 09:27:28 +01002683 break;
Willy Tarreaud7a6b2f2020-05-13 13:51:01 +02002684 }
Willy Tarreau4f46a352020-03-23 09:27:28 +01002685 }
2686
Willy Tarreauc49ba522019-12-11 08:12:23 +01002687 /* If we have to sleep, measure how long */
2688 next = wake ? TICK_ETERNITY : next_timer_expiry();
2689
Willy Tarreau58b458d2008-06-29 22:40:23 +02002690 /* The poller will ensure it returns around <next> */
Willy Tarreau2ae84e42019-05-28 16:44:05 +02002691 cur_poller.poll(&cur_poller, next, wake);
Emeric Brun64cc49c2017-10-03 14:46:45 +02002692
Willy Tarreaud80cb4e2018-01-20 19:30:13 +01002693 activity[tid].loops++;
Willy Tarreau4f60f162007-04-08 16:39:58 +02002694 }
Amaury Denoyelled3a88c12021-05-03 10:47:51 +02002695
2696 task_destroy(mux_stopping_data[tid].task);
Willy Tarreau4f60f162007-04-08 16:39:58 +02002697}
2698
Christopher Faulet1d17c102017-08-29 15:38:48 +02002699static void *run_thread_poll_loop(void *data)
2700{
Willy Tarreau082b6282019-05-22 14:42:12 +02002701 struct per_thread_alloc_fct *ptaf;
Christopher Faulet1d17c102017-08-29 15:38:48 +02002702 struct per_thread_init_fct *ptif;
2703 struct per_thread_deinit_fct *ptdf;
Willy Tarreau082b6282019-05-22 14:42:12 +02002704 struct per_thread_free_fct *ptff;
Willy Tarreau34a150c2019-06-11 09:16:41 +02002705 static int init_left = 0;
Willy Tarreauaf613e82020-06-05 08:40:51 +02002706 __decl_thread(static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER);
2707 __decl_thread(static pthread_cond_t init_cond = PTHREAD_COND_INITIALIZER);
Christopher Faulet1d17c102017-08-29 15:38:48 +02002708
Willy Tarreaub4f7cc32019-05-03 09:27:30 +02002709 ha_set_tid((unsigned long)data);
Willy Tarreaud022e9c2019-09-24 08:25:15 +02002710 sched = &task_per_thread[tid];
Willy Tarreau91e6df02019-05-03 17:21:18 +02002711
Willy Tarreauf6178242019-05-21 19:46:58 +02002712#if (_POSIX_TIMERS > 0) && defined(_POSIX_THREAD_CPUTIME)
Willy Tarreau91e6df02019-05-03 17:21:18 +02002713#ifdef USE_THREAD
Willy Tarreau8323a372019-05-20 18:57:53 +02002714 pthread_getcpuclockid(pthread_self(), &ti->clock_id);
Willy Tarreau624dcbf2019-05-20 20:23:06 +02002715#else
Willy Tarreau8323a372019-05-20 18:57:53 +02002716 ti->clock_id = CLOCK_THREAD_CPUTIME_ID;
Willy Tarreau91e6df02019-05-03 17:21:18 +02002717#endif
Willy Tarreau663fda42019-05-21 15:14:08 +02002718#endif
Willy Tarreau6ec902a2019-06-07 14:41:11 +02002719 /* Now, initialize one thread init at a time. This is better since
2720 * some init code is a bit tricky and may release global resources
2721 * after reallocating them locally. This will also ensure there is
2722 * no race on file descriptors allocation.
2723 */
Willy Tarreau34a150c2019-06-11 09:16:41 +02002724#ifdef USE_THREAD
2725 pthread_mutex_lock(&init_mutex);
2726#endif
2727 /* The first thread must set the number of threads left */
2728 if (!init_left)
2729 init_left = global.nbthread;
2730 init_left--;
Willy Tarreau91e6df02019-05-03 17:21:18 +02002731
Willy Tarreauc4c80fb2021-04-11 15:00:34 +02002732 tv_init_thread_date();
Christopher Faulet1d17c102017-08-29 15:38:48 +02002733
Willy Tarreau082b6282019-05-22 14:42:12 +02002734 /* per-thread alloc calls performed here are not allowed to snoop on
2735 * other threads, so they are free to initialize at their own rhythm
2736 * as long as they act as if they were alone. None of them may rely
2737 * on resources initialized by the other ones.
2738 */
2739 list_for_each_entry(ptaf, &per_thread_alloc_list, list) {
2740 if (!ptaf->fct()) {
2741 ha_alert("failed to allocate resources for thread %u.\n", tid);
2742 exit(1);
2743 }
2744 }
2745
Willy Tarreau3078e9f2019-05-20 10:50:43 +02002746 /* per-thread init calls performed here are not allowed to snoop on
2747 * other threads, so they are free to initialize at their own rhythm
2748 * as long as they act as if they were alone.
2749 */
Christopher Faulet1d17c102017-08-29 15:38:48 +02002750 list_for_each_entry(ptif, &per_thread_init_list, list) {
2751 if (!ptif->fct()) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002752 ha_alert("failed to initialize thread %u.\n", tid);
Christopher Faulet1d17c102017-08-29 15:38:48 +02002753 exit(1);
2754 }
2755 }
2756
Willy Tarreau71092822019-06-10 09:51:04 +02002757 /* enabling protocols will result in fd_insert() calls to be performed,
2758 * we want all threads to have already allocated their local fd tables
Willy Tarreau34a150c2019-06-11 09:16:41 +02002759 * before doing so, thus only the last thread does it.
Willy Tarreau71092822019-06-10 09:51:04 +02002760 */
Willy Tarreau34a150c2019-06-11 09:16:41 +02002761 if (init_left == 0)
Willy Tarreaue4d7c9d2019-06-10 10:14:52 +02002762 protocol_enable_all();
Willy Tarreau6ec902a2019-06-07 14:41:11 +02002763
Willy Tarreau34a150c2019-06-11 09:16:41 +02002764#ifdef USE_THREAD
2765 pthread_cond_broadcast(&init_cond);
2766 pthread_mutex_unlock(&init_mutex);
2767
2768 /* now wait for other threads to finish starting */
2769 pthread_mutex_lock(&init_mutex);
2770 while (init_left)
2771 pthread_cond_wait(&init_cond, &init_mutex);
2772 pthread_mutex_unlock(&init_mutex);
2773#endif
Willy Tarreau3078e9f2019-05-20 10:50:43 +02002774
Willy Tarreaua45a8b52019-12-06 16:31:45 +01002775#if defined(PR_SET_NO_NEW_PRIVS) && defined(USE_PRCTL)
2776 /* Let's refrain from using setuid executables. This way the impact of
2777 * an eventual vulnerability in a library remains limited. It may
2778 * impact external checks but who cares about them anyway ? In the
2779 * worst case it's possible to disable the option. Obviously we do this
2780 * in workers only. We can't hard-fail on this one as it really is
2781 * implementation dependent though we're interested in feedback, hence
2782 * the warning.
2783 */
2784 if (!(global.tune.options & GTUNE_INSECURE_SETUID) && !master) {
2785 static int warn_fail;
Willy Tarreau18515722021-04-06 11:57:41 +02002786 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1 && !_HA_ATOMIC_FETCH_ADD(&warn_fail, 1)) {
Willy Tarreaua45a8b52019-12-06 16:31:45 +01002787 ha_warning("Failed to disable setuid, please report to developers with detailed "
2788 "information about your operating system. You can silence this warning "
2789 "by adding 'insecure-setuid-wanted' in the 'global' section.\n");
2790 }
2791 }
2792#endif
2793
Willy Tarreaud96f1122019-12-03 07:07:36 +01002794#if defined(RLIMIT_NPROC)
2795 /* all threads have started, it's now time to prevent any new thread
2796 * or process from starting. Obviously we do this in workers only. We
2797 * can't hard-fail on this one as it really is implementation dependent
2798 * though we're interested in feedback, hence the warning.
2799 */
2800 if (!(global.tune.options & GTUNE_INSECURE_FORK) && !master) {
2801 struct rlimit limit = { .rlim_cur = 0, .rlim_max = 0 };
2802 static int warn_fail;
2803
Willy Tarreau18515722021-04-06 11:57:41 +02002804 if (setrlimit(RLIMIT_NPROC, &limit) == -1 && !_HA_ATOMIC_FETCH_ADD(&warn_fail, 1)) {
Willy Tarreaud96f1122019-12-03 07:07:36 +01002805 ha_warning("Failed to disable forks, please report to developers with detailed "
2806 "information about your operating system. You can silence this warning "
2807 "by adding 'insecure-fork-wanted' in the 'global' section.\n");
2808 }
2809 }
2810#endif
Christopher Faulet1d17c102017-08-29 15:38:48 +02002811 run_poll_loop();
2812
2813 list_for_each_entry(ptdf, &per_thread_deinit_list, list)
2814 ptdf->fct();
2815
Willy Tarreau082b6282019-05-22 14:42:12 +02002816 list_for_each_entry(ptff, &per_thread_free_list, list)
2817 ptff->fct();
2818
Christopher Fauletcd7879a2017-10-27 13:53:47 +02002819#ifdef USE_THREAD
Olivier Houchardb23a61f2019-03-08 18:51:17 +01002820 _HA_ATOMIC_AND(&all_threads_mask, ~tid_bit);
Christopher Fauletcd7879a2017-10-27 13:53:47 +02002821 if (tid > 0)
2822 pthread_exit(NULL);
Christopher Faulet1d17c102017-08-29 15:38:48 +02002823#endif
Christopher Fauletcd7879a2017-10-27 13:53:47 +02002824 return NULL;
2825}
Christopher Faulet1d17c102017-08-29 15:38:48 +02002826
William Dauchyf9af9d72019-11-17 15:47:16 +01002827/* set uid/gid depending on global settings */
2828static void set_identity(const char *program_name)
2829{
2830 if (global.gid) {
2831 if (getgroups(0, NULL) > 0 && setgroups(0, NULL) == -1)
2832 ha_warning("[%s.main()] Failed to drop supplementary groups. Using 'gid'/'group'"
2833 " without 'uid'/'user' is generally useless.\n", program_name);
2834
2835 if (setgid(global.gid) == -1) {
2836 ha_alert("[%s.main()] Cannot set gid %d.\n", program_name, global.gid);
2837 protocol_unbind_all();
2838 exit(1);
2839 }
2840 }
2841
2842 if (global.uid && setuid(global.uid) == -1) {
2843 ha_alert("[%s.main()] Cannot set uid %d.\n", program_name, global.uid);
2844 protocol_unbind_all();
2845 exit(1);
2846 }
2847}
2848
Willy Tarreaubaaee002006-06-26 02:48:02 +02002849int main(int argc, char **argv)
2850{
2851 int err, retry;
2852 struct rlimit limit;
Willy Tarreau269ab312012-09-05 08:02:48 +02002853 int pidfd = -1;
Willy Tarreaubaaee002006-06-26 02:48:02 +02002854
Olivier Houchard5fa300d2018-02-03 15:15:21 +01002855 setvbuf(stdout, NULL, _IONBF, 0);
Willy Tarreau5794fb02018-11-25 18:43:29 +01002856
Willy Tarreauff9c9142019-02-07 10:39:36 +01002857 /* this can only safely be done here, though it's optimized away by
2858 * the compiler.
2859 */
2860 if (MAX_PROCS < 1 || MAX_PROCS > LONGBITS) {
2861 ha_alert("MAX_PROCS value must be between 1 and %d inclusive; "
2862 "HAProxy was built with value %d, please fix it and rebuild.\n",
2863 LONGBITS, MAX_PROCS);
2864 exit(1);
2865 }
2866
Willy Tarreaubf696402019-03-01 10:09:28 +01002867 /* take a copy of initial limits before we possibly change them */
2868 getrlimit(RLIMIT_NOFILE, &limit);
Willy Tarreau2bd0f812020-10-13 15:36:08 +02002869
2870 if (limit.rlim_max == RLIM_INFINITY)
2871 limit.rlim_max = limit.rlim_cur;
Willy Tarreaubf696402019-03-01 10:09:28 +01002872 rlim_fd_cur_at_boot = limit.rlim_cur;
2873 rlim_fd_max_at_boot = limit.rlim_max;
2874
Willy Tarreau5794fb02018-11-25 18:43:29 +01002875 /* process all initcalls in order of potential dependency */
2876 RUN_INITCALLS(STG_PREPARE);
2877 RUN_INITCALLS(STG_LOCK);
2878 RUN_INITCALLS(STG_ALLOC);
2879 RUN_INITCALLS(STG_POOL);
2880 RUN_INITCALLS(STG_REGISTER);
2881 RUN_INITCALLS(STG_INIT);
2882
Emeric Bruncf20bf12010-10-22 16:06:11 +02002883 init(argc, argv);
Willy Tarreau24f4efa2010-08-27 17:56:48 +02002884 signal_register_fct(SIGQUIT, dump, SIGQUIT);
2885 signal_register_fct(SIGUSR1, sig_soft_stop, SIGUSR1);
2886 signal_register_fct(SIGHUP, sig_dump_state, SIGHUP);
William Lallemand73b85e72017-06-01 17:38:51 +02002887 signal_register_fct(SIGUSR2, NULL, 0);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002888
Willy Tarreaue437c442010-03-17 18:02:46 +01002889 /* Always catch SIGPIPE even on platforms which define MSG_NOSIGNAL.
2890 * Some recent FreeBSD setups report broken pipes, and MSG_NOSIGNAL
2891 * was defined there, so let's stay on the safe side.
Willy Tarreaubaaee002006-06-26 02:48:02 +02002892 */
Willy Tarreau24f4efa2010-08-27 17:56:48 +02002893 signal_register_fct(SIGPIPE, NULL, 0);
Willy Tarreaubaaee002006-06-26 02:48:02 +02002894
Willy Tarreaudc23a922011-02-16 11:10:36 +01002895 /* ulimits */
2896 if (!global.rlimit_nofile)
2897 global.rlimit_nofile = global.maxsock;
2898
2899 if (global.rlimit_nofile) {
Willy Tarreaue5cfdac2019-03-01 10:32:05 +01002900 limit.rlim_cur = global.rlimit_nofile;
2901 limit.rlim_max = MAX(rlim_fd_max_at_boot, limit.rlim_cur);
2902
Willy Tarreaudc23a922011-02-16 11:10:36 +01002903 if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
Willy Tarreauef635472016-06-21 11:48:18 +02002904 getrlimit(RLIMIT_NOFILE, &limit);
William Dauchy0fec3ab2019-10-27 20:08:11 +01002905 if (global.tune.options & GTUNE_STRICT_LIMITS) {
2906 ha_alert("[%s.main()] Cannot raise FD limit to %d, limit is %d.\n",
2907 argv[0], global.rlimit_nofile, (int)limit.rlim_cur);
Jerome Magnin50f757c2021-01-12 20:19:38 +01002908 exit(1);
William Dauchy0fec3ab2019-10-27 20:08:11 +01002909 }
2910 else {
2911 /* try to set it to the max possible at least */
2912 limit.rlim_cur = limit.rlim_max;
2913 if (setrlimit(RLIMIT_NOFILE, &limit) != -1)
2914 getrlimit(RLIMIT_NOFILE, &limit);
Willy Tarreau164dd0b2016-06-21 11:51:59 +02002915
William Dauchya5194602020-03-28 19:29:58 +01002916 ha_warning("[%s.main()] Cannot raise FD limit to %d, limit is %d.\n",
William Dauchy0fec3ab2019-10-27 20:08:11 +01002917 argv[0], global.rlimit_nofile, (int)limit.rlim_cur);
2918 global.rlimit_nofile = limit.rlim_cur;
2919 }
Willy Tarreaudc23a922011-02-16 11:10:36 +01002920 }
2921 }
2922
2923 if (global.rlimit_memmax) {
2924 limit.rlim_cur = limit.rlim_max =
Willy Tarreau70060452015-12-14 12:46:07 +01002925 global.rlimit_memmax * 1048576ULL;
Willy Tarreaudc23a922011-02-16 11:10:36 +01002926#ifdef RLIMIT_AS
2927 if (setrlimit(RLIMIT_AS, &limit) == -1) {
William Dauchy0fec3ab2019-10-27 20:08:11 +01002928 if (global.tune.options & GTUNE_STRICT_LIMITS) {
2929 ha_alert("[%s.main()] Cannot fix MEM limit to %d megs.\n",
2930 argv[0], global.rlimit_memmax);
Jerome Magnin50f757c2021-01-12 20:19:38 +01002931 exit(1);
William Dauchy0fec3ab2019-10-27 20:08:11 +01002932 }
2933 else
William Dauchya5194602020-03-28 19:29:58 +01002934 ha_warning("[%s.main()] Cannot fix MEM limit to %d megs.\n",
William Dauchy0fec3ab2019-10-27 20:08:11 +01002935 argv[0], global.rlimit_memmax);
Willy Tarreaudc23a922011-02-16 11:10:36 +01002936 }
2937#else
2938 if (setrlimit(RLIMIT_DATA, &limit) == -1) {
William Dauchy0fec3ab2019-10-27 20:08:11 +01002939 if (global.tune.options & GTUNE_STRICT_LIMITS) {
2940 ha_alert("[%s.main()] Cannot fix MEM limit to %d megs.\n",
2941 argv[0], global.rlimit_memmax);
Jerome Magnin50f757c2021-01-12 20:19:38 +01002942 exit(1);
William Dauchy0fec3ab2019-10-27 20:08:11 +01002943 }
2944 else
William Dauchya5194602020-03-28 19:29:58 +01002945 ha_warning("[%s.main()] Cannot fix MEM limit to %d megs.\n",
William Dauchy0fec3ab2019-10-27 20:08:11 +01002946 argv[0], global.rlimit_memmax);
Willy Tarreaudc23a922011-02-16 11:10:36 +01002947 }
2948#endif
2949 }
2950
Olivier Houchardf73629d2017-04-05 22:33:04 +02002951 if (old_unixsocket) {
William Lallemand85b0bd92017-06-01 17:38:53 +02002952 if (strcmp("/dev/null", old_unixsocket) != 0) {
Willy Tarreau42961742020-08-28 18:42:45 +02002953 if (sock_get_old_sockets(old_unixsocket) != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002954 ha_alert("Failed to get the sockets from the old process!\n");
William Lallemand85b0bd92017-06-01 17:38:53 +02002955 if (!(global.mode & MODE_MWORKER))
2956 exit(1);
2957 }
Olivier Houchardf73629d2017-04-05 22:33:04 +02002958 }
2959 }
William Lallemand85b0bd92017-06-01 17:38:53 +02002960 get_cur_unixsocket();
2961
Willy Tarreaubaaee002006-06-26 02:48:02 +02002962 /* We will loop at most 100 times with 10 ms delay each time.
2963 * That's at most 1 second. We only send a signal to old pids
2964 * if we cannot grab at least one port.
2965 */
2966 retry = MAX_START_RETRIES;
2967 err = ERR_NONE;
2968 while (retry >= 0) {
2969 struct timeval w;
Willy Tarreaue91bff22020-09-02 11:11:43 +02002970 err = protocol_bind_all(retry == 0 || nb_oldpids == 0);
Willy Tarreaue13e9252007-12-20 23:05:50 +01002971 /* exit the loop on no error or fatal error */
2972 if ((err & (ERR_RETRYABLE|ERR_FATAL)) != ERR_RETRYABLE)
Willy Tarreaubaaee002006-06-26 02:48:02 +02002973 break;
Willy Tarreaubb545b42010-08-25 12:58:59 +02002974 if (nb_oldpids == 0 || retry == 0)
Willy Tarreaubaaee002006-06-26 02:48:02 +02002975 break;
2976
2977 /* FIXME-20060514: Solaris and OpenBSD do not support shutdown() on
2978 * listening sockets. So on those platforms, it would be wiser to
2979 * simply send SIGUSR1, which will not be undoable.
2980 */
Willy Tarreaubb545b42010-08-25 12:58:59 +02002981 if (tell_old_pids(SIGTTOU) == 0) {
2982 /* no need to wait if we can't contact old pids */
2983 retry = 0;
2984 continue;
2985 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02002986 /* give some time to old processes to stop listening */
2987 w.tv_sec = 0;
2988 w.tv_usec = 10*1000;
2989 select(0, NULL, NULL, NULL, &w);
2990 retry--;
2991 }
2992
Willy Tarreaue91bff22020-09-02 11:11:43 +02002993 /* Note: protocol_bind_all() sends an alert when it fails. */
Willy Tarreau0a3b9d92009-02-04 17:05:23 +01002994 if ((err & ~ERR_WARN) != ERR_NONE) {
Willy Tarreaue91bff22020-09-02 11:11:43 +02002995 ha_alert("[%s.main()] Some protocols failed to start their listeners! Exiting.\n", argv[0]);
Willy Tarreauf68da462009-06-09 14:36:00 +02002996 if (retry != MAX_START_RETRIES && nb_oldpids) {
2997 protocol_unbind_all(); /* cleanup everything we can */
Willy Tarreaubaaee002006-06-26 02:48:02 +02002998 tell_old_pids(SIGTTIN);
Willy Tarreauf68da462009-06-09 14:36:00 +02002999 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02003000 exit(1);
3001 }
3002
William Lallemand944e6192018-11-21 15:48:31 +01003003 if (!(global.mode & MODE_MWORKER_WAIT) && listeners == 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003004 ha_alert("[%s.main()] No enabled listener found (check for 'bind' directives) ! Exiting.\n", argv[0]);
Willy Tarreaubaaee002006-06-26 02:48:02 +02003005 /* Note: we don't have to send anything to the old pids because we
3006 * never stopped them. */
3007 exit(1);
3008 }
3009
Willy Tarreaue91bff22020-09-02 11:11:43 +02003010 /* Ok, all listeners should now be bound, close any leftover sockets
Olivier Houchardf73629d2017-04-05 22:33:04 +02003011 * the previous process gave us, we don't need them anymore
3012 */
3013 while (xfer_sock_list != NULL) {
3014 struct xfer_sock_list *tmpxfer = xfer_sock_list->next;
3015 close(xfer_sock_list->fd);
3016 free(xfer_sock_list->iface);
3017 free(xfer_sock_list->namespace);
3018 free(xfer_sock_list);
3019 xfer_sock_list = tmpxfer;
3020 }
Willy Tarreaudd815982007-10-16 12:25:14 +02003021
Willy Tarreaubaaee002006-06-26 02:48:02 +02003022 /* prepare pause/play signals */
Willy Tarreau24f4efa2010-08-27 17:56:48 +02003023 signal_register_fct(SIGTTOU, sig_pause, SIGTTOU);
3024 signal_register_fct(SIGTTIN, sig_listen, SIGTTIN);
Willy Tarreaubaaee002006-06-26 02:48:02 +02003025
Willy Tarreaubaaee002006-06-26 02:48:02 +02003026 /* MODE_QUIET can inhibit alerts and warnings below this line */
3027
PiBa-NL149a81a2017-12-25 21:03:31 +01003028 if (getenv("HAPROXY_MWORKER_REEXEC") != NULL) {
3029 /* either stdin/out/err are already closed or should stay as they are. */
3030 if ((global.mode & MODE_DAEMON)) {
3031 /* daemon mode re-executing, stdin/stdout/stderr are already closed so keep quiet */
3032 global.mode &= ~MODE_VERBOSE;
3033 global.mode |= MODE_QUIET; /* ensure that we won't say anything from now */
3034 }
3035 } else {
3036 if ((global.mode & MODE_QUIET) && !(global.mode & MODE_VERBOSE)) {
3037 /* detach from the tty */
William Lallemande1340412017-12-28 16:09:36 +01003038 stdio_quiet(-1);
PiBa-NL149a81a2017-12-25 21:03:31 +01003039 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02003040 }
3041
3042 /* open log & pid files before the chroot */
William Lallemand80293002017-11-06 11:00:03 +01003043 if ((global.mode & MODE_DAEMON || global.mode & MODE_MWORKER) && global.pidfile != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02003044 unlink(global.pidfile);
3045 pidfd = open(global.pidfile, O_CREAT | O_WRONLY | O_TRUNC, 0644);
3046 if (pidfd < 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003047 ha_alert("[%s.main()] Cannot create pidfile %s\n", argv[0], global.pidfile);
Willy Tarreaubaaee002006-06-26 02:48:02 +02003048 if (nb_oldpids)
3049 tell_old_pids(SIGTTIN);
Willy Tarreaudd815982007-10-16 12:25:14 +02003050 protocol_unbind_all();
Willy Tarreaubaaee002006-06-26 02:48:02 +02003051 exit(1);
3052 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02003053 }
3054
Willy Tarreaub38651a2007-03-24 17:24:39 +01003055 if ((global.last_checks & LSTCHK_NETADM) && global.uid) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003056 ha_alert("[%s.main()] Some configuration options require full privileges, so global.uid cannot be changed.\n"
3057 "", argv[0]);
Willy Tarreaudd815982007-10-16 12:25:14 +02003058 protocol_unbind_all();
Willy Tarreaub38651a2007-03-24 17:24:39 +01003059 exit(1);
3060 }
3061
Jackie Tapia749f74c2020-07-22 18:59:40 -05003062 /* If the user is not root, we'll still let them try the configuration
3063 * but we inform them that unexpected behaviour may occur.
Willy Tarreau4e30ed72009-02-04 18:02:48 +01003064 */
3065 if ((global.last_checks & LSTCHK_NETADM) && getuid())
Christopher Faulet767a84b2017-11-24 16:50:31 +01003066 ha_warning("[%s.main()] Some options which require full privileges"
3067 " might not work well.\n"
3068 "", argv[0]);
Willy Tarreau4e30ed72009-02-04 18:02:48 +01003069
William Lallemand095ba4c2017-06-01 17:38:50 +02003070 if ((global.mode & (MODE_MWORKER|MODE_DAEMON)) == 0) {
3071
3072 /* chroot if needed */
3073 if (global.chroot != NULL) {
3074 if (chroot(global.chroot) == -1 || chdir("/") == -1) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003075 ha_alert("[%s.main()] Cannot chroot(%s).\n", argv[0], global.chroot);
William Lallemand095ba4c2017-06-01 17:38:50 +02003076 if (nb_oldpids)
3077 tell_old_pids(SIGTTIN);
3078 protocol_unbind_all();
3079 exit(1);
3080 }
Willy Tarreauf223cc02007-10-15 18:57:08 +02003081 }
Willy Tarreauf223cc02007-10-15 18:57:08 +02003082 }
3083
William Lallemand944e6192018-11-21 15:48:31 +01003084 if (nb_oldpids && !(global.mode & MODE_MWORKER_WAIT))
Willy Tarreaubb545b42010-08-25 12:58:59 +02003085 nb_oldpids = tell_old_pids(oldpids_sig);
Willy Tarreaubaaee002006-06-26 02:48:02 +02003086
William Lallemand27edc4b2019-05-07 17:49:33 +02003087 /* send a SIGTERM to workers who have a too high reloads number */
3088 if ((global.mode & MODE_MWORKER) && !(global.mode & MODE_MWORKER_WAIT))
3089 mworker_kill_max_reloads(SIGTERM);
3090
Willy Tarreaubaaee002006-06-26 02:48:02 +02003091 /* Note that any error at this stage will be fatal because we will not
3092 * be able to restart the old pids.
3093 */
3094
William Dauchyf9af9d72019-11-17 15:47:16 +01003095 if ((global.mode & (MODE_MWORKER | MODE_DAEMON)) == 0)
3096 set_identity(argv[0]);
Willy Tarreau636848a2019-04-15 19:38:50 +02003097
Willy Tarreaubaaee002006-06-26 02:48:02 +02003098 /* check ulimits */
3099 limit.rlim_cur = limit.rlim_max = 0;
3100 getrlimit(RLIMIT_NOFILE, &limit);
3101 if (limit.rlim_cur < global.maxsock) {
William Dauchy0fec3ab2019-10-27 20:08:11 +01003102 if (global.tune.options & GTUNE_STRICT_LIMITS) {
3103 ha_alert("[%s.main()] FD limit (%d) too low for maxconn=%d/maxsock=%d. "
3104 "Please raise 'ulimit-n' to %d or more to avoid any trouble.\n",
3105 argv[0], (int)limit.rlim_cur, global.maxconn, global.maxsock,
3106 global.maxsock);
Jerome Magnin50f757c2021-01-12 20:19:38 +01003107 exit(1);
William Dauchy0fec3ab2019-10-27 20:08:11 +01003108 }
3109 else
3110 ha_alert("[%s.main()] FD limit (%d) too low for maxconn=%d/maxsock=%d. "
William Dauchya5194602020-03-28 19:29:58 +01003111 "Please raise 'ulimit-n' to %d or more to avoid any trouble.\n",
William Dauchy0fec3ab2019-10-27 20:08:11 +01003112 argv[0], (int)limit.rlim_cur, global.maxconn, global.maxsock,
3113 global.maxsock);
Willy Tarreaubaaee002006-06-26 02:48:02 +02003114 }
3115
William Lallemand944e6192018-11-21 15:48:31 +01003116 if (global.mode & (MODE_DAEMON | MODE_MWORKER | MODE_MWORKER_WAIT)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02003117 int ret = 0;
Willy Tarreaud67ff342021-06-15 07:58:09 +02003118 int in_parent = 0;
William Lallemande1340412017-12-28 16:09:36 +01003119 int devnullfd = -1;
Willy Tarreaubaaee002006-06-26 02:48:02 +02003120
William Lallemand095ba4c2017-06-01 17:38:50 +02003121 /*
3122 * if daemon + mworker: must fork here to let a master
3123 * process live in background before forking children
3124 */
William Lallemand73b85e72017-06-01 17:38:51 +02003125
3126 if ((getenv("HAPROXY_MWORKER_REEXEC") == NULL)
3127 && (global.mode & MODE_MWORKER)
3128 && (global.mode & MODE_DAEMON)) {
William Lallemand095ba4c2017-06-01 17:38:50 +02003129 ret = fork();
3130 if (ret < 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01003131 ha_alert("[%s.main()] Cannot fork.\n", argv[0]);
William Lallemand095ba4c2017-06-01 17:38:50 +02003132 protocol_unbind_all();
3133 exit(1); /* there has been an error */
William Lallemandbfd8eb52018-07-04 15:31:23 +02003134 } else if (ret > 0) { /* parent leave to daemonize */
William Lallemand095ba4c2017-06-01 17:38:50 +02003135 exit(0);
William Lallemandbfd8eb52018-07-04 15:31:23 +02003136 } else /* change the process group ID in the child (master process) */
3137 setsid();
William Lallemand095ba4c2017-06-01 17:38:50 +02003138 }
William Lallemande20b6a62017-06-01 17:38:55 +02003139
William Lallemande20b6a62017-06-01 17:38:55 +02003140
William Lallemanddeed7802017-11-06 11:00:04 +01003141 /* if in master-worker mode, write the PID of the father */
3142 if (global.mode & MODE_MWORKER) {
3143 char pidstr[100];
Willy Tarreau76a80c72019-06-22 07:41:38 +02003144 snprintf(pidstr, sizeof(pidstr), "%d\n", (int)getpid());
Willy Tarreau46ec48b2018-01-23 19:20:19 +01003145 if (pidfd >= 0)
Willy Tarreau2e8ab6b2020-03-14 11:03:20 +01003146 DISGUISE(write(pidfd, pidstr, strlen(pidstr)));
William Lallemanddeed7802017-11-06 11:00:04 +01003147 }
3148
Willy Tarreaubaaee002006-06-26 02:48:02 +02003149 /* the father launches the required number of processes */
William Lallemand944e6192018-11-21 15:48:31 +01003150 if (!(global.mode & MODE_MWORKER_WAIT)) {
William Lallemand9a1ee7a2019-04-01 11:30:02 +02003151 if (global.mode & MODE_MWORKER)
3152 mworker_ext_launch_all();
Willy Tarreaud67ff342021-06-15 07:58:09 +02003153
3154 ret = fork();
3155 if (ret < 0) {
3156 ha_alert("[%s.main()] Cannot fork.\n", argv[0]);
3157 protocol_unbind_all();
3158 exit(1); /* there has been an error */
3159 }
3160 else if (ret == 0) { /* child breaks here */
3161 ha_random_jump96(relative_pid);
3162 }
3163 else { /* parent here */
3164 in_parent = 1;
3165
William Lallemand944e6192018-11-21 15:48:31 +01003166 if (pidfd >= 0 && !(global.mode & MODE_MWORKER)) {
3167 char pidstr[100];
3168 snprintf(pidstr, sizeof(pidstr), "%d\n", ret);
Willy Tarreau2e8ab6b2020-03-14 11:03:20 +01003169 DISGUISE(write(pidfd, pidstr, strlen(pidstr)));
William Lallemand944e6192018-11-21 15:48:31 +01003170 }
3171 if (global.mode & MODE_MWORKER) {
3172 struct mworker_proc *child;
William Lallemandce83b4a2018-10-26 14:47:30 +02003173
William Lallemand220567e2018-11-21 18:04:53 +01003174 ha_notice("New worker #%d (%d) forked\n", relative_pid, ret);
William Lallemand944e6192018-11-21 15:48:31 +01003175 /* find the right mworker_proc */
3176 list_for_each_entry(child, &proc_list, list) {
3177 if (child->relative_pid == relative_pid &&
William Lallemand8f7069a2019-04-12 16:09:23 +02003178 child->reloads == 0 && child->options & PROC_O_TYPE_WORKER) {
William Lallemand944e6192018-11-21 15:48:31 +01003179 child->timestamp = now.tv_sec;
3180 child->pid = ret;
William Lallemand1dc69632019-06-12 19:11:33 +02003181 child->version = strdup(haproxy_version);
William Lallemand944e6192018-11-21 15:48:31 +01003182 break;
3183 }
William Lallemandce83b4a2018-10-26 14:47:30 +02003184 }
3185 }
William Lallemand944e6192018-11-21 15:48:31 +01003186 }
Willy Tarreaud67ff342021-06-15 07:58:09 +02003187
William Lallemand944e6192018-11-21 15:48:31 +01003188 } else {
3189 /* wait mode */
Willy Tarreaud67ff342021-06-15 07:58:09 +02003190 in_parent = 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +02003191 }
Willy Tarreaufc6c0322012-11-16 16:12:27 +01003192
3193#ifdef USE_CPU_AFFINITY
Willy Tarreau44ea6312021-06-15 08:57:56 +02003194 if (!in_parent && ha_cpuset_count(&cpu_map.proc)) { /* only do this if the process has a CPU map */
Olivier Houchard97148f62017-08-16 17:29:11 +02003195
Amaury Denoyelle982fb532021-04-21 18:39:58 +02003196#ifdef __FreeBSD__
Willy Tarreau44ea6312021-06-15 08:57:56 +02003197 struct hap_cpuset *set = &cpu_map.proc;
Amaury Denoyelle982fb532021-04-21 18:39:58 +02003198 ret = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(set->cpuset), &set->cpuset);
David Carlier2d0493a2020-12-02 21:14:51 +00003199#elif defined(__linux__) || defined(__DragonFly__)
Willy Tarreau44ea6312021-06-15 08:57:56 +02003200 struct hap_cpuset *set = &cpu_map.proc;
Amaury Denoyelle982fb532021-04-21 18:39:58 +02003201 sched_setaffinity(0, sizeof(set->cpuset), &set->cpuset);
Willy Tarreaufc6c0322012-11-16 16:12:27 +01003202#endif
Amaury Denoyelle982fb532021-04-21 18:39:58 +02003203 }
Pieter Baauwcaa6a1b2015-09-17 21:26:40 +02003204#endif
Willy Tarreaubaaee002006-06-26 02:48:02 +02003205 /* close the pidfile both in children and father */
Willy Tarreau269ab312012-09-05 08:02:48 +02003206 if (pidfd >= 0) {
3207 //lseek(pidfd, 0, SEEK_SET); /* debug: emulate eglibc bug */
3208 close(pidfd);
3209 }
Willy Tarreaud137dd32010-08-25 12:49:05 +02003210
3211 /* We won't ever use this anymore */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003212 ha_free(&global.pidfile);
Willy Tarreaubaaee002006-06-26 02:48:02 +02003213
Willy Tarreaud67ff342021-06-15 07:58:09 +02003214 if (in_parent) {
William Lallemand944e6192018-11-21 15:48:31 +01003215 if (global.mode & (MODE_MWORKER|MODE_MWORKER_WAIT)) {
PiBa-NLbaf6ea42017-11-28 23:26:08 +01003216
3217 if ((!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) &&
3218 (global.mode & MODE_DAEMON)) {
3219 /* detach from the tty, this is required to properly daemonize. */
William Lallemande1340412017-12-28 16:09:36 +01003220 if ((getenv("HAPROXY_MWORKER_REEXEC") == NULL))
3221 stdio_quiet(-1);
3222
PiBa-NLbaf6ea42017-11-28 23:26:08 +01003223 global.mode &= ~MODE_VERBOSE;
3224 global.mode |= MODE_QUIET; /* ensure that we won't say anything from now */
PiBa-NLbaf6ea42017-11-28 23:26:08 +01003225 }
3226
William Lallemandb3f2be32018-09-11 10:06:18 +02003227 mworker_loop();
William Lallemand1499b9b2017-06-07 15:04:47 +02003228 /* should never get there */
3229 exit(EXIT_FAILURE);
Willy Tarreauedaff0a2015-05-01 17:01:08 +02003230 }
William Lallemandcf4e4962017-06-08 19:05:48 +02003231#if defined(USE_OPENSSL) && !defined(OPENSSL_NO_DH)
Grant Zhang872f9c22017-01-21 01:10:18 +00003232 ssl_free_dh();
3233#endif
William Lallemand1499b9b2017-06-07 15:04:47 +02003234 exit(0); /* parent must leave */
Willy Tarreauedaff0a2015-05-01 17:01:08 +02003235 }
3236
William Lallemandcb11fd22017-06-01 17:38:52 +02003237 /* child must never use the atexit function */
3238 atexit_flag = 0;
3239
William Lallemandbc193052018-09-11 10:06:26 +02003240 /* close useless master sockets */
3241 if (global.mode & MODE_MWORKER) {
3242 struct mworker_proc *child, *it;
3243 master = 0;
3244
William Lallemand309dc9a2018-10-26 14:47:45 +02003245 mworker_cli_proxy_stop();
3246
William Lallemandbc193052018-09-11 10:06:26 +02003247 /* free proc struct of other processes */
3248 list_for_each_entry_safe(child, it, &proc_list, list) {
William Lallemandce83b4a2018-10-26 14:47:30 +02003249 /* close the FD of the master side for all
3250 * workers, we don't need to close the worker
3251 * side of other workers since it's done with
3252 * the bind_proc */
Tim Duesterhus742e0f92018-11-25 20:03:39 +01003253 if (child->ipc_fd[0] >= 0)
3254 close(child->ipc_fd[0]);
William Lallemandce83b4a2018-10-26 14:47:30 +02003255 if (child->relative_pid == relative_pid &&
3256 child->reloads == 0) {
3257 /* keep this struct if this is our pid */
3258 proc_self = child;
William Lallemandbc193052018-09-11 10:06:26 +02003259 continue;
William Lallemandce83b4a2018-10-26 14:47:30 +02003260 }
Willy Tarreau2b718102021-04-21 07:32:39 +02003261 LIST_DELETE(&child->list);
Tim Duesterhus9b7a9762019-05-16 20:23:22 +02003262 mworker_free_child(child);
3263 child = NULL;
William Lallemandbc193052018-09-11 10:06:26 +02003264 }
3265 }
Willy Tarreau1605c7a2018-01-23 19:01:49 +01003266
William Lallemande1340412017-12-28 16:09:36 +01003267 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) {
3268 devnullfd = open("/dev/null", O_RDWR, 0);
3269 if (devnullfd < 0) {
3270 ha_alert("Cannot open /dev/null\n");
3271 exit(EXIT_FAILURE);
3272 }
3273 }
3274
William Lallemand095ba4c2017-06-01 17:38:50 +02003275 /* Must chroot and setgid/setuid in the children */
3276 /* chroot if needed */
3277 if (global.chroot != NULL) {
3278 if (chroot(global.chroot) == -1 || chdir("/") == -1) {
Willy Tarreaue34cf282021-06-15 08:59:19 +02003279 ha_alert("[%s.main()] Cannot chroot(%s).\n", argv[0], global.chroot);
William Lallemand095ba4c2017-06-01 17:38:50 +02003280 if (nb_oldpids)
3281 tell_old_pids(SIGTTIN);
3282 protocol_unbind_all();
3283 exit(1);
3284 }
3285 }
3286
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003287 ha_free(&global.chroot);
William Dauchyf9af9d72019-11-17 15:47:16 +01003288 set_identity(argv[0]);
William Lallemand095ba4c2017-06-01 17:38:50 +02003289
William Lallemand7f80eb22017-05-26 18:19:55 +02003290 /* pass through every cli socket, and check if it's bound to
3291 * the current process and if it exposes listeners sockets.
3292 * Caution: the GTUNE_SOCKET_TRANSFER is now set after the fork.
3293 * */
3294
Willy Tarreau4975d142021-03-13 11:00:33 +01003295 if (global.cli_fe) {
William Lallemand7f80eb22017-05-26 18:19:55 +02003296 struct bind_conf *bind_conf;
3297
Willy Tarreau4975d142021-03-13 11:00:33 +01003298 list_for_each_entry(bind_conf, &global.cli_fe->conf.bind, by_fe) {
William Lallemand7f80eb22017-05-26 18:19:55 +02003299 if (bind_conf->level & ACCESS_FD_LISTENERS) {
Willy Tarreau72faef32021-06-15 08:36:30 +02003300 global.tune.options |= GTUNE_SOCKET_TRANSFER;
3301 break;
William Lallemand7f80eb22017-05-26 18:19:55 +02003302 }
3303 }
Willy Tarreauf83d3fe2015-05-01 19:13:41 +02003304 }
3305
William Lallemand2e8fad92018-11-13 16:18:23 +01003306 /*
3307 * This is only done in daemon mode because we might want the
3308 * logs on stdout in mworker mode. If we're NOT in QUIET mode,
3309 * we should now close the 3 first FDs to ensure that we can
3310 * detach from the TTY. We MUST NOT do it in other cases since
3311 * it would have already be done, and 0-2 would have been
3312 * affected to listening sockets
Willy Tarreaubaaee002006-06-26 02:48:02 +02003313 */
William Lallemand2e8fad92018-11-13 16:18:23 +01003314 if ((global.mode & MODE_DAEMON) &&
3315 (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02003316 /* detach from the tty */
William Lallemande1340412017-12-28 16:09:36 +01003317 stdio_quiet(devnullfd);
Willy Tarreau106cb762008-11-16 07:40:34 +01003318 global.mode &= ~MODE_VERBOSE;
Willy Tarreaubaaee002006-06-26 02:48:02 +02003319 global.mode |= MODE_QUIET; /* ensure that we won't say anything from now */
3320 }
3321 pid = getpid(); /* update child's pid */
William Lallemandbfd8eb52018-07-04 15:31:23 +02003322 if (!(global.mode & MODE_MWORKER)) /* in mworker mode we don't want a new pgid for the children */
3323 setsid();
Willy Tarreau2ff76222007-04-09 19:29:56 +02003324 fork_poller();
Willy Tarreaubaaee002006-06-26 02:48:02 +02003325 }
3326
William Dauchye039f262019-11-17 15:47:15 +01003327 /* try our best to re-enable core dumps depending on system capabilities.
3328 * What is addressed here :
3329 * - remove file size limits
3330 * - remove core size limits
3331 * - mark the process dumpable again if it lost it due to user/group
3332 */
3333 if (global.tune.options & GTUNE_SET_DUMPABLE) {
3334 limit.rlim_cur = limit.rlim_max = RLIM_INFINITY;
3335
3336#if defined(RLIMIT_FSIZE)
3337 if (setrlimit(RLIMIT_FSIZE, &limit) == -1) {
3338 if (global.tune.options & GTUNE_STRICT_LIMITS) {
3339 ha_alert("[%s.main()] Failed to set the raise the maximum "
3340 "file size.\n", argv[0]);
Jerome Magnin50f757c2021-01-12 20:19:38 +01003341 exit(1);
William Dauchye039f262019-11-17 15:47:15 +01003342 }
3343 else
3344 ha_warning("[%s.main()] Failed to set the raise the maximum "
William Dauchya5194602020-03-28 19:29:58 +01003345 "file size.\n", argv[0]);
William Dauchye039f262019-11-17 15:47:15 +01003346 }
3347#endif
3348
3349#if defined(RLIMIT_CORE)
3350 if (setrlimit(RLIMIT_CORE, &limit) == -1) {
3351 if (global.tune.options & GTUNE_STRICT_LIMITS) {
3352 ha_alert("[%s.main()] Failed to set the raise the core "
3353 "dump size.\n", argv[0]);
Jerome Magnin50f757c2021-01-12 20:19:38 +01003354 exit(1);
William Dauchye039f262019-11-17 15:47:15 +01003355 }
3356 else
3357 ha_warning("[%s.main()] Failed to set the raise the core "
William Dauchya5194602020-03-28 19:29:58 +01003358 "dump size.\n", argv[0]);
William Dauchye039f262019-11-17 15:47:15 +01003359 }
3360#endif
3361
3362#if defined(USE_PRCTL)
3363 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1)
3364 ha_warning("[%s.main()] Failed to set the dumpable flag, "
3365 "no core will be dumped.\n", argv[0]);
3366#endif
3367 }
3368
Christopher Faulete3a5e352017-10-24 13:53:54 +02003369 global.mode &= ~MODE_STARTING;
Amaury Denoyelle6af81f82021-05-27 15:45:28 +02003370 reset_usermsgs_ctx();
3371
Willy Tarreau4f60f162007-04-08 16:39:58 +02003372 /*
3373 * That's it : the central polling loop. Run until we stop.
3374 */
Christopher Faulet1d17c102017-08-29 15:38:48 +02003375#ifdef USE_THREAD
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003376 {
William Lallemand1aab50b2018-06-07 09:46:01 +02003377 sigset_t blocked_sig, old_sig;
Willy Tarreauc40efc12019-05-03 09:22:44 +02003378 int i;
3379
William Lallemand1aab50b2018-06-07 09:46:01 +02003380 /* ensure the signals will be blocked in every thread */
3381 sigfillset(&blocked_sig);
3382 sigdelset(&blocked_sig, SIGPROF);
3383 sigdelset(&blocked_sig, SIGBUS);
3384 sigdelset(&blocked_sig, SIGFPE);
3385 sigdelset(&blocked_sig, SIGILL);
3386 sigdelset(&blocked_sig, SIGSEGV);
3387 pthread_sigmask(SIG_SETMASK, &blocked_sig, &old_sig);
3388
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003389 /* Create nbthread-1 thread. The first thread is the current process */
David Carliera92c5ce2019-09-13 05:03:12 +01003390 ha_thread_info[0].pthread = pthread_self();
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003391 for (i = 1; i < global.nbthread; i++)
David Carliera92c5ce2019-09-13 05:03:12 +01003392 pthread_create(&ha_thread_info[i].pthread, NULL, &run_thread_poll_loop, (void *)(long)i);
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003393
Christopher Faulet62519022017-10-16 15:49:32 +02003394#ifdef USE_CPU_AFFINITY
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003395 /* Now the CPU affinity for all threads */
Amaury Denoyelleaf02c572021-04-15 16:29:58 +02003396
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003397 for (i = 0; i < global.nbthread; i++) {
Willy Tarreau44ea6312021-06-15 08:57:56 +02003398 if (ha_cpuset_count(&cpu_map.proc))
3399 ha_cpuset_and(&cpu_map.thread[i], &cpu_map.proc);
Christopher Faulet62519022017-10-16 15:49:32 +02003400
Willy Tarreau421f02e2018-01-20 18:19:22 +01003401 if (i < MAX_THREADS && /* only the first 32/64 threads may be pinned */
Amaury Denoyellefc6ac532021-04-27 10:46:36 +02003402 ha_cpuset_count(&cpu_map.thread[i])) {/* only do this if the thread has a THREAD map */
David Carlier5e4c8e22019-09-13 05:12:58 +01003403#if defined(__APPLE__)
3404 int j;
Amaury Denoyelle8f685c12021-04-27 16:45:29 +02003405 unsigned long set = cpu_map.thread[i].cpuset;
David Carlier5e4c8e22019-09-13 05:12:58 +01003406
Amaury Denoyelle8f685c12021-04-27 16:45:29 +02003407 while ((j = ffsl(set)) > 0) {
David Carlier5e4c8e22019-09-13 05:12:58 +01003408 thread_affinity_policy_data_t cpu_set = { j - 1 };
3409 thread_port_t mthread = pthread_mach_thread_np(ha_thread_info[i].pthread);
3410 thread_policy_set(mthread, THREAD_AFFINITY_POLICY, (thread_policy_t)&cpu_set, 1);
Amaury Denoyelle8f685c12021-04-27 16:45:29 +02003411 set &= ~(1UL << (j - 1));
David Carlier5e4c8e22019-09-13 05:12:58 +01003412 }
3413#else
Amaury Denoyellefc6ac532021-04-27 10:46:36 +02003414 struct hap_cpuset *set = &cpu_map.thread[i];
David Carliera92c5ce2019-09-13 05:03:12 +01003415 pthread_setaffinity_np(ha_thread_info[i].pthread,
Amaury Denoyelle982fb532021-04-21 18:39:58 +02003416 sizeof(set->cpuset), &set->cpuset);
David Carlier5e4c8e22019-09-13 05:12:58 +01003417#endif
Olivier Houchard829aa242017-12-01 18:19:43 +01003418 }
Christopher Faulet1d17c102017-08-29 15:38:48 +02003419 }
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003420#endif /* !USE_CPU_AFFINITY */
3421
William Lallemand1aab50b2018-06-07 09:46:01 +02003422 /* when multithreading we need to let only the thread 0 handle the signals */
William Lallemandd3801c12018-09-11 10:06:23 +02003423 haproxy_unblock_signals();
William Lallemand1aab50b2018-06-07 09:46:01 +02003424
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003425 /* Finally, start the poll loop for the first thread */
Willy Tarreaub4f7cc32019-05-03 09:27:30 +02003426 run_thread_poll_loop(0);
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003427
3428 /* Wait the end of other threads */
3429 for (i = 1; i < global.nbthread; i++)
David Carliera92c5ce2019-09-13 05:03:12 +01003430 pthread_join(ha_thread_info[i].pthread, NULL);
Christopher Faulet1d17c102017-08-29 15:38:48 +02003431
Christopher Fauletb79a94c2017-05-30 15:34:30 +02003432#if defined(DEBUG_THREAD) || defined(DEBUG_FULL)
3433 show_lock_stats();
3434#endif
Christopher Faulet1d17c102017-08-29 15:38:48 +02003435 }
Christopher Fauletcd7879a2017-10-27 13:53:47 +02003436#else /* ! USE_THREAD */
William Lallemandd3801c12018-09-11 10:06:23 +02003437 haproxy_unblock_signals();
Willy Tarreaub4f7cc32019-05-03 09:27:30 +02003438 run_thread_poll_loop(0);
Christopher Faulet62519022017-10-16 15:49:32 +02003439#endif
Christopher Faulet1d17c102017-08-29 15:38:48 +02003440
Tim Duesterhus0a3b43d2020-06-14 00:37:42 +02003441 deinit_and_exit(0);
Willy Tarreaubaaee002006-06-26 02:48:02 +02003442}
3443
Willy Tarreaubaaee002006-06-26 02:48:02 +02003444/*
3445 * Local variables:
3446 * c-indent-level: 8
3447 * c-basic-offset: 8
3448 * End:
3449 */