96#if USE_LOADABLE_MODULES
139static int malloc_debug_level = 0;
157static void usage(
void);
172#include "test_access.c"
234 const char *avoiding =
"delaying";
235 const char *currentEvent =
"none";
237 currentEvent =
"shutdown";
238 avoiding =
"canceling";
241 if (strcmp(currentEvent, description) == 0)
246 currentEvent =
"startup";
248 currentEvent =
"reconfiguration";
256 " request during " << currentEvent);
267 debugs(1,
Important(3),
"Waiting " << wait <<
" seconds for active connections to finish");
310 while (
pid > 0 || (
pid < 0 && errno == EINTR));
319 "Usage: %s [-cdzCFNRVYX] [-n name] [-s | -l facility] [-f config-file] [-[au] port] [-k signal]"
321 "[-ir] [-O CommandLine]"
324 " -h | --help Print help message.\n"
325 " -v | --version Print version details.\n"
327 " -a port Specify HTTP port number (default: %d).\n"
328 " -d level Write debugging to stderr also.\n"
329 " -f file Use given config-file instead of\n"
332 " -i Installs as a Windows Service (see -n option).\n"
334 " -k reconfigure|rotate|shutdown|"
338 "interrupt|kill|debug|check|parse\n"
339 " Parse configuration file, then send signal to \n"
340 " running copy (except -k parse) and exit.\n"
341 " -n name Specify service name to use for service operations\n"
344 " -r Removes a Windows Service (see -n option).\n"
346 " -s | -l facility\n"
347 " Enable logging to syslog.\n"
348 " -u port Specify ICP port number (default: %d), disable with 0.\n"
349 " -z Create missing swap directories and then exit.\n"
350 " -C Do not catch fatal signals.\n"
351 " -D OBSOLETE. Scheduled for removal.\n"
352 " -F Don't serve any requests until store is rebuilt.\n"
353 " -N Master process runs in foreground and is a worker. No kids.\n"
355 " Master process runs in foreground and creates worker kids.\n"
357 " Play a given SMP kid process role, with a given ID. Do not use\n"
358 " this option. It is meant for the master process use only.\n"
361 " Set Windows Service Command line options in Registry.\n"
363 " -R Do not set REUSEADDR on port.\n"
364 " -S Double-check swap during rebuild.\n"
365 " -X Force full debugging.\n"
366 " Add -d9 to also write full debugging to stderr.\n"
367 " -Y Only return UDP_HIT or UDP_MISS_NOFETCH during fast reload.\n",
388 "CDFNRSYXa:d:f:hk:m::n:sl:u:vz?";
393 {
"kid", required_argument,
nullptr,
optKid},
394 {
"help", no_argument,
nullptr,
'h'},
395 {
"version", no_argument,
nullptr,
'v'},
396 {
nullptr, 0,
nullptr, 0}
435 WIN32_Command_Line =
xstrdup(optValue);
504 if (!optValue || strlen(optValue) < 1)
507 else if (!strncmp(optValue,
"reconfigure", strlen(optValue)))
510 else if (!strncmp(optValue,
"rotate", strlen(optValue)))
512#if defined(_SQUID_LINUX_THREADS_)
518 else if (!strncmp(optValue,
"debug", strlen(optValue)))
520#if defined(_SQUID_LINUX_THREADS_)
526 else if (!strncmp(optValue,
"shutdown", strlen(optValue)))
529 else if (!strncmp(optValue,
"interrupt", strlen(optValue)))
532 else if (!strncmp(optValue,
"kill", strlen(optValue)))
539 else if (!strncmp(optValue,
"restart", strlen(optValue)))
545 else if (!strncmp(optValue,
"check", strlen(optValue)))
548 else if (!strncmp(optValue,
"parse", strlen(optValue)))
566 malloc_debug_level =
xatoi(optValue);
568 fatal(
"Need to add -DMALLOC_DBG when compiling to use -mX option");
578 if (optValue && *optValue !=
'\0') {
579 const SBuf t(optValue);
583 fatalf(
"Expected alphanumeric service name for the -n option but got: %s", optValue);
585 fatalf(
"Garbage after alphanumeric service name in the -n option value: %s", optValue);
590 fatal(
"A service name is required for the -n option");
640#if OPENSSL_VERSION_MAJOR < 3
641 printf(
"For legal restrictions on distribution see https://www.openssl.org/source/license.html\n\n");
648 printf(
"Compiled as Windows System Service.\n");
756#if !defined(_SQUID_WINDOWS_) && !defined(HAVE_SIGACTION)
766#if !defined(_SQUID_WINDOWS_) && !defined(HAVE_SIGACTION)
840 out <<
Debug::Extra <<
"advice: Run 'squid -k parse' and check for ERRORs.";
847 debugs(1, 3,
"finishing reconfiguring");
868 ") requires a full restart. It has been ignored by reconfigure.");
887#if USE_LOADABLE_MODULES
892 bool enableAdaptation =
false;
980 if (geteuid() == 0) {
985 fatal(
"Don't run Squid as root, set 'cache_effective_user'!");
1060 if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) {
1075 debugs(1,
DBG_IMPORTANT,
"With " << _getmaxstdio() <<
" CRT stdio descriptors available");
1077 if (WIN32_Socks_initialized)
1080 if (WIN32_OS_version > _WIN_OS_WINNT) {
1122 malloc_debug(0, malloc_debug_level);
1163#if defined(_SQUID_LINUX_THREADS_)
1187#if USE_LOADABLE_MODULES
1192 bool enableAdaptation =
false;
1227 static bool terminating =
false;
1243#if USE_WIN32_SERVICE
1245extern "C" void WINAPI
1255#if USE_WIN32_SERVICE
1256 SetErrorMode(SEM_NOGPFAULTERRORBOX);
1257 if ((argc == 2) && strstr(argv[1], _WIN_SQUID_SERVICE_OPTION))
1260 WIN32_run_mode = _WIN_SQUID_RUN_MODE_INTERACTIVE;
1281 return EXIT_FAILURE;
1288 const char *kidParams =
nullptr;
1290 SBuf processName(kidParams);
1342 if (skipCwdAdjusting) {
1385#if HAVE_DISKIO_MODULE_IPCIO
1389#if HAVE_AUTH_MODULE_NTLM
1431#if defined(SQUID_MAXFD_LIMIT)
1439 int WIN32_init_err=0;
1441 return WIN32_init_err;
1447 mallopt(M_GRAIN, 16);
1452 mallopt(M_MXFAST, 256);
1457 mallopt(M_NLBLKS, 32);
1468#if USE_WIN32_SERVICE
1481 debugs(1,
DBG_CRITICAL,
"WARNING: --foreground command-line option has no effect with -N.");
1484#if USE_WIN32_SERVICE
1535 return EXIT_FAILURE;
1538 return EXIT_FAILURE;
1543 return EXIT_SUCCESS;
1567 debugs(1,2,
"Doing post-config initialization");
1598#if USE_WIN32_SERVICE
1606#if USE_WIN32_SERVICE
1648 fatal_dump(
"Event loop exited with failure.");
1660#if USE_WIN32_SERVICE
1665 throw TexcHere(
"missing -n command line switch");
1672 const auto savedErrno = errno;
1674 " to Squid instance with PID ",
pid,
": ",
xstrerr(savedErrno)));
1697 if ((t = strrchr(script,
'/'))) {
1699 sl = strlen(script);
1704 if ((cpid = fork()) == 0) {
1712 }
while (rpid != cpid);
1722 debugs(1, 2,
"received shutdown command");
1732 debugs(1, 2,
"received reconfiguration command");
1784 assert(nextCheckDelay >= 0);
1785 (void)alarm(
static_cast<unsigned int>(nextCheckDelay));
1787 debugs(1, 2,
"will recheck hopeless kids in " << nextCheckDelay <<
" seconds");
1802 if ((
pid = fork()) < 0) {
1805 }
else if (
pid > 0) {
1820 syslog(LOG_ALERT,
"Exiting due to unexpected forced shutdown");
1825 syslog(LOG_ALERT,
"Exiting due to repeated, frequent failures");
1847 throw TexcHere(
"hopeless_kid_revival_delay must be positive");
1851 openlog(
APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
1860 if ((
const auto i =
xopen(
"/dev/tty", O_RDWR |
O_TEXT)) >= 0) {
1861 ioctl(i, TIOCNOTTY,
nullptr);
1873 const auto nullfd =
xopen(_PATH_DEVNULL, O_RDWR |
O_TEXT);
1892#if defined(_SQUID_LINUX_THREADS_)
1910 syslog(LOG_ALERT,
"Suspiciously high workers value: %d",
1918 syslog(LOG_NOTICE,
"Squid Parent: will start %d kids", (
int)
TheKids.
count());
1922 bool mainStartScriptCalled =
false;
1929 if (!mainStartScriptCalled) {
1931 mainStartScriptCalled =
true;
1936 auto kidCommand = masterCommand;
1939 kidCommand.pushFrontOption(
"--kid", kid.
gist().
c_str());
1941 if ((
pid = fork()) == 0) {
1943 openlog(
APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
1944 (void)execvp(masterCommand.
arg0(), kidCommand.argv());
1946 syslog(LOG_ALERT,
"execvp failed: %s",
xstrerr(xerrno));
1950 syslog(LOG_NOTICE,
"Squid Parent: %s process %d started",
1955 openlog(
APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
1976 syslog(LOG_NOTICE,
"Squid Parent: unknown child process %d exited",
pid);
2005#if USE_WIN32_SERVICE
2028#if USE_WIN32_SERVICE
void accessLogClose(void)
void accessLogRotate(void)
void CpuAffinityInit()
set CPU affinity for this process on startup
void CpuAffinityCheck()
check CPU affinity configuration and print warnings if needed
void CpuAffinityReconfigure()
reconfigure CPU affinity for this process
void storeDirOpenSwapLogs()
int storeDirWriteCleanLogs(int reopen)
void storeDirCloseSwapLogs()
int TheProcessKind
ProcessKind for the current process.
@ pkWorker
general-purpose worker bee
@ pkCoordinator
manages all other kids
@ pkDisker
cache_dir manager
@ pkOther
we do not know or do not care
SBuf TheKidName
current Squid process name (e.g., "squid-coord")
Kids TheKids
All kids being maintained.
void LoadableModulesConfigure(const SBufList &names)
dynamically load named libraries, in the listed order
int xatoi(const char *token)
#define RunRegisteredHere(m)
convenience macro to describe/debug the caller and the method being called
#define CallRunnerRegistratorIn(Namespace, ClassName)
#define CallRunnerRegistrator(ClassName)
#define SQUIDSBUFPRINT(s)
class SquidConfig2 Config2
std::ostream & CurrentExceptionExtra(std::ostream &os)
std::ostream & CurrentException(std::ostream &os)
prints active (i.e., thrown but not yet handled) exception
#define TexcHere(msg)
legacy convenience macro; it is not difficult to type Here() now
void authenticateInit(Auth::ConfigVector *config)
void authenticateReset(void)
void authenticateRotate(void)
#define USE_WIN32_SERVICE
#define SQUID_CONFIGURE_OPTIONS
void add_http_port(char *portspec)
static void Finalize(bool enable)
static void Init()
initializes down-cased protocol scheme names array
static void Start(const Pointer &job)
static void RegisterWithCacheManager()
reacts to RegisteredRunner events relevant to this module
optimized set of C chars, with quick membership test and merge support
static const CharacterSet DIGIT
static const CharacterSet ALPHA
void finalize()
checks pools configuration
initializes shared queue used by CollapsedForwarding
Manages arguments passed to a program (i.e., main(argc, argv) parameters).
bool hasOption(const int optId, const char **optValue=nullptr) const
void forEachOption(Visitor) const
calls Visitor for each of the configured command line option
void resetArg0(const char *programName)
replaces argv[0] with the new value
const char * arg0() const
static void ResetStderrLevel(int maxLevel)
static bool StderrEnabled()
static void parseOptions(char const *)
static void PrepareToDie()
static void ForgetSaved()
silently erases saved early debugs() messages (if any)
static std::ostream & Extra(std::ostream &)
static void NameThisKid(int kidIdentifier)
static void SettleSyslog()
static void UseCacheLog()
static void BanCacheLogUse()
static void ConfigureSyslog(const char *facility)
enables logging to syslog (using the specified facility, when not nil)
static void EnsureDefaultStderrLevel(int maxDefault)
static void SettleStderr()
static void FreeAllModules()
static void SetupAllModules()
static EventLoop * Running
void setTimeService(Time::Engine *)
void registerEngine(AsyncEngine *engine)
void setPrimaryEngine(AsyncEngine *engine)
static EventScheduler * GetInstance()
void Close() override
Shutdown pinger helper and control channel.
int Open() override
Start pinger helper and initiate control channel.
static Coordinator * Instance()
Receives coordination messages on behalf of its process or thread.
void start(pid_t cpid)
called when this kid got started, records PID
SBuf processName() const
returns kid name
bool shouldRestart() const
returns true if master should restart this kid
void forgetAllFailures()
forgets all failures in all kids
bool someSignaled(const int sgnl) const
whether some kids died from a given signal
size_t count() const
returns the number of kids
Kid * find(pid_t pid)
returns kid by pid
bool shouldRestartSome() const
whether some kids should be restarted by master
void init()
initialize all kid records based on Config
bool someRunning() const
whether some kids are running
Kid & get(size_t i)
returns the kid by index, useful for kids iteration
time_t forgetOldFailures()
bool allHopeless() const
whether all kids are hopeless
launches PeerPoolMgrs for peers configured with standby.limit
reacts to RegisteredRunner events relevant to this module
reacts to RegisteredRunner events relevant to this module
virtual void syncConfig()
virtual void bootstrapConfig()
virtual void claimMemoryNeeds()
virtual void startShutdown()
virtual void finalizeConfig()
virtual void endingShutdown()
virtual void finishShutdown()
Meant for cleanup of services needed by the already destroyed objects.
virtual void startReconfigure()
static void RegisterWithCacheManager(void)
SBuf buf()
bytes written so far
size_type length() const
Returns the number of bytes stored in SBuf.
int cmp(const SBuf &S, const size_type n) const
shorthand version for compare()
SBuf & assign(const SBuf &S)
initializes shared memory pages
initializes shared memory segments used by MemStore
void doShutdown(time_t wait)
int checkEvents(int timeout) override
static void FinalShutdownRunners(void *)
void handleStoppedChild()
static void StopEventLoop(void *)
struct SquidConfig2::@102 onoff
ClientDelayConfig ClientDelay
time_t hopelessKidRevivalDelay
hopeless_kid_revival_delay
SBufList loadable_module_names
struct SquidConfig::@78 Port
static void Shutdown()
Shutdown helper structure.
static void Init()
Init helper structure.
static void Reconfigure()
void reconfigureStart()
When reconfigring should be called this method.
static void Init()
Init helper structure.
static void Reconfigure()
static void Shutdown()
Shutdown helper structure.
struct StatCounters::@104 client_http
int checkEvents(int) override
void sync() override
prepare for shutdown
void create() override
create system resources needed for this store to operate in the future
int callback() override
called once every main loop iteration; TODO: Move to UFS code.
event class for doing synthetic time etc
initializes shared memory segment used by Transients
void clientOpenListenSockets(void)
void clientConnectionsClose()
void fd_open(const int fd, unsigned int, const char *description)
void commCloseAllSockets(void)
void(* failure_notify)(const char *)
#define SQUID_MAXFD_LIMIT
#define debugs(SECTION, LEVEL, CONTENT)
void eventAdd(const char *name, EVH *func, void *arg, double when, int weight, bool cbdata)
void externalAclInit(void)
void externalAclShutdown(void)
void fatal(const char *message)
void fatal_dump(const char *message)
void fatalf(const char *fmt,...)
int opt_store_doublecheck
struct timeval squid_start
const char * version_string
int opt_foreground_rebuild
void errorInitialize(void)
void fqdncache_init(void)
void fqdncache_purgelru(void *)
void fqdncache_restart(void)
void ipcache_restart(void)
void ipcache_purgelru(void *)
void icpConnectionShutdown(void)
static void setEffectiveUser(void)
static void master_shutdown(int sig)
Shutdown signal handler for master process.
static void StartUsingConfig()
static void watch_child(const CommandLine &)
void WINAPI WIN32_svcHandler(DWORD)
static volatile int do_reconfigure
static void mainReconfigureStart(void)
static void ConfigureDebugging()
Start directing debugs() messages to the configured cache.log.
static int opt_signal_service
int SquidMain(int argc, char **argv)
unsafe main routine – may throw
static void masterReviveKids()
Reacts to the kid revival alarm.
static int opt_command_line
static int ReviveKidsSignal
static volatile int do_handle_stopped_child
static void RegisterModules()
register all known modules for handling future RegisteredRunner events
static void GoIntoBackground()
makes the caller a daemon process running in the background
static struct option squidOptions[]
static volatile int do_revive_kids
static void mainSetCwd(void)
set the working directory.
static SBuf ConfigurationFailureMessage()
error message to log when Configuration::Parse() fails
static void ConfigureCurrentKid(const CommandLine &cmdLine)
computes name and ID for the current kid process
static volatile int do_shutdown
void rotate_logs(int sig)
static void RunConfigUsers()
static int configured_once
static void mainHandleCommandLineOption(const int optId, const char *optValue)
static int opt_remove_service
static void master_revive_kids(int sig)
static void SquidShutdown(void)
void WINAPI SquidWinSvcMain(int argc, char **argv)
static void masterShutdownStart()
Initiates shutdown sequence. Shutdown ends when the last running kids stops.
static bool mainChangeDir(const char *dir)
changes working directory, providing error reporting
static void OnTerminate()
static int SquidMainSafe(int argc, char **argv)
unsafe main routine wrapper to catch exceptions
static int ReconfigureSignal
static int ShutdownSignal
static void mainReconfigureFinish(void *)
void WIN32_svcstatusupdate(DWORD, DWORD)
static void sendSignal(void)
static const char * squid_start_script
static int icpPortNumOverride
static void serverConnectionsOpen(void)
static const char * shortOpStr
static void masterCheckAndBroadcastSignals()
static volatile int shutdown_status
static void masterMaintainKidRevivalSchedule()
static void mainStartScript(const char *prog)
static int opt_install_service
void reconfigure(int sig)
static void masterReconfigureFinish()
Ends reconfiguration sequence started by masterReconfigureStart().
static void mainRotate(void)
static void masterReconfigureStart()
Initiates reconfiguration sequence. See also: masterReconfigureFinish().
static bool AvoidSignalAction(const char *description, volatile int &signalVar)
static volatile int do_rotate
static void serverConnectionsClose(void)
static bool masterSignaled()
static void mainInitialize(void)
static char * opt_syslog_facility
void memClean(void)
Main cleanup handler.
void mimeInit(char *filename)
void Init(void)
prepares to parse ACLs configuration
void Init(void)
Initialize Auth subsystem.
void Parse()
interprets (and partially applies) squid.conf or equivalent configuration
void WriteOurPid()
creates a PID file; throws on error
void ThrowIfAlreadyRunning()
void ProbeTransport(void)
Probe to discover IPv6 capabilities.
void CleanIdlePools(void *unused)
void OpenLogs()
opens logs enabled in the current configuration
void CloseLogs()
closes logs opened by OpenLogs()
void RotateLogs()
rotates logs opened by OpenLogs()
GlobalContextStorage & TheGlobalContextStorage()
Global cache for store all SSL server certificates.
Controller & Root()
safely access controller singleton
void Maintain(void *unused)
void neighbors_init(void)
void peerSelectInit(void)
void redirectReconfigure()
void redirectShutdown(void)
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
void _db_rotate_log(void)
void storeLogRotate(void)
time_t getCurrentTime() STUB_RETVAL(0) int tvSubUsec(struct timeval
struct timeval current_time
the current UNIX time in timeval {seconds, microseconds} format
int xopen(const char *filename, int oflag, int pmode=0)
POSIX open(2) equivalent.
void WIN32_SetServiceCommandLine()
int WIN32_StartService(int argc, char **argv)
int WIN32_Subsystem_Init(int *argc, char ***argv)
void WIN32_RemoveService()
void WIN32_InstallService()
DWORD WIN32_IpAddrChangeMonitorInit()
void WIN32_sendSignal(int WIN32_signal)
const char * xstrerr(int error)
char * xstrncpy(char *dst, const char *src, size_t n)