]> git.ipfire.org Git - thirdparty/squid.git/blame - src/main.cc
Fixed Parser::Tokenizer::prefix() to return false on all empty prefixes.
[thirdparty/squid.git] / src / main.cc
CommitLineData
30a4f2a8 1/*
b510f3a1 2 * DEBUG: section 01 Startup and Main Loop
30a4f2a8 3 * AUTHOR: Harvest Derived
4 *
2b6662ba 5 * SQUID Web Proxy Cache http://www.squid-cache.org/
e25c139f 6 * ----------------------------------------------------------
30a4f2a8 7 *
2b6662ba 8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
30a4f2a8 16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
26ac0430 21 *
30a4f2a8 22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26ac0430 26 *
30a4f2a8 27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
cbdec147 29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
e25c139f 30 *
30a4f2a8 31 */
44a47c6e 32
582c2af2 33#include "squid.h"
450e0c10 34#include "AccessLogEntry.h"
582c2af2
FC
35#include "acl/Acl.h"
36#include "acl/Asn.h"
89736861 37#include "AuthReg.h"
6d57128b 38#include "base/RunnersRegistry.h"
e0d28505 39#include "base/Subscription.h"
3d93a84d 40#include "base/TextException.h"
fc54b8d2
FC
41#include "cache_cf.h"
42#include "carp.h"
43#include "client_db.h"
44#include "client_side.h"
d841c88d 45#include "comm.h"
62ee09ca 46#include "ConfigParser.h"
96c2bb61 47#include "CpuAffinity.h"
fc54b8d2 48#include "disk.h"
582c2af2 49#include "DiskIO/DiskIOModule.h"
aa839030 50#include "errorpage.h"
a553a5a3 51#include "event.h"
52#include "EventLoop.h"
62ee09ca 53#include "ExternalACL.h"
fc54b8d2 54#include "fd.h"
31971e6a 55#include "format/Token.h"
fc54b8d2 56#include "fqdncache.h"
602d9612 57#include "fs/Module.h"
eb13c21e 58#include "FwdState.h"
af69c635 59#include "globals.h"
582c2af2 60#include "htcp.h"
fc54b8d2 61#include "HttpHeader.h"
582c2af2
FC
62#include "HttpReply.h"
63#include "icmp/IcmpSquid.h"
64#include "icmp/net_db.h"
e6ccf245 65#include "ICP.h"
4daaf3cb 66#include "ident/Ident.h"
602d9612 67#include "ip/tools.h"
10cefb7b 68#include "ipc/Coordinator.h"
582c2af2 69#include "ipc/Kids.h"
10cefb7b 70#include "ipc/Strand.h"
602d9612 71#include "ipcache.h"
582c2af2
FC
72#include "Mem.h"
73#include "MemPool.h"
b65ce00c 74#include "mime.h"
fc54b8d2 75#include "neighbors.h"
d5f21615 76#include "parser/Tokenizer.h"
582c2af2 77#include "pconn.h"
fc54b8d2
FC
78#include "peer_sourcehash.h"
79#include "peer_userhash.h"
602d9612 80#include "PeerSelectState.h"
582c2af2 81#include "profiler/Profiler.h"
c548327a 82#include "redirect.h"
fc54b8d2 83#include "refresh.h"
bc94e5ca 84#include "send-announce.h"
4d5904f7 85#include "SquidConfig.h"
582c2af2 86#include "SquidDns.h"
985c86bc 87#include "SquidTime.h"
fc54b8d2 88#include "stat.h"
e4f1fdae 89#include "StatCounters.h"
582c2af2 90#include "Store.h"
602d9612
A
91#include "store_log.h"
92#include "StoreFileSystem.h"
c8f4eac4 93#include "SwapDir.h"
602d9612 94#include "tools.h"
b6b42084 95#include "unlinkd.h"
fc54b8d2
FC
96#include "URL.h"
97#include "wccp.h"
98#include "wccp2.h"
cf3edd6f 99#include "WinSvc.h"
44a47c6e 100
582c2af2
FC
101#if USE_ADAPTATION
102#include "adaptation/Config.h"
103#endif
104#if USE_ECAP
105#include "adaptation/ecap/Config.h"
106#endif
107#if ICAP_CLIENT
108#include "adaptation/icap/Config.h"
109#include "adaptation/icap/icap_log.h"
110#endif
111#if USE_AUTH
112#include "auth/Gadgets.h"
113#endif
114#if USE_DELAY_POOLS
115#include "ClientDelayConfig.h"
116#endif
117#if USE_DELAY_POOLS
118#include "DelayPools.h"
119#endif
57afc994
AR
120#if USE_LOADABLE_MODULES
121#include "LoadableModules.h"
122#endif
95d2589c 123#if USE_SSL_CRTD
95d2589c
CT
124#include "ssl/certificate_db.h"
125#endif
cb4f4424 126#if USE_OPENSSL
95d2589c 127#include "ssl/context_storage.h"
602d9612 128#include "ssl/helper.h"
95d2589c 129#endif
b958cb0f 130#if ICAP_CLIENT
26cc52cb 131#include "adaptation/icap/Config.h"
b958cb0f 132#endif
6e5db507 133#if USE_ECAP
1f3c65fc 134#include "adaptation/ecap/Config.h"
6e5db507 135#endif
b958cb0f
AR
136#if USE_ADAPTATION
137#include "adaptation/Config.h"
138#endif
79039294
AR
139#if USE_SQUID_ESI
140#include "esi/Module.h"
141#endif
9c0a2256
FC
142#if SQUID_SNMP
143#include "snmp_core.h"
144#endif
7b5b7ba8 145
1a30fdf5 146#include <cerrno>
25f98340
AJ
147#if HAVE_PATHS_H
148#include <paths.h>
149#endif
582c2af2
FC
150#if HAVE_SYS_WAIT_H
151#include <sys/wait.h>
152#endif
1a774556 153
25f98340 154#if USE_WIN32_SERVICE
1a774556 155#include <process.h>
156
157static int opt_install_service = FALSE;
158static int opt_remove_service = FALSE;
1a774556 159static int opt_command_line = FALSE;
82afb125 160void WIN32_svcstatusupdate(DWORD, DWORD);
1a774556 161void WINAPI WIN32_svcHandler(DWORD);
1a774556 162#endif
163
cf2155f2 164static int opt_signal_service = FALSE;
5e6d4736 165static char *opt_syslog_facility = NULL;
30a4f2a8 166static int icpPortNumOverride = 1; /* Want to detect "-u 0" */
e13ee7ad 167static int configured_once = 0;
30a4f2a8 168#if MALLOC_DBG
4d64d74a 169static int malloc_debug_level = 0;
30a4f2a8 170#endif
5cd39a10 171static volatile int do_reconfigure = 0;
172static volatile int do_rotate = 0;
2681d383 173static volatile int do_shutdown = 0;
ae1feb30 174static volatile int shutdown_status = 0;
4d7add01 175
a2c48c98
AR
176static int RotateSignal = -1;
177static int ReconfigureSignal = -1;
178static int ShutdownSignal = -1;
179
5cd39a10 180static void mainRotate(void);
d71e4674
AR
181static void mainReconfigureStart(void);
182static void mainReconfigureFinish(void*);
f5b8bbc4 183static void mainInitialize(void);
f5b8bbc4 184static void usage(void);
63be0a78 185static void mainParseOptions(int argc, char *argv[]);
f5b8bbc4 186static void sendSignal(void);
187static void serverConnectionsOpen(void);
d71e4674 188static void serverConnectionsClose(void);
bbe199dc 189static void watch_child(char **);
85407535 190static void setEffectiveUser(void);
8ff3fa2e 191static void SquidShutdown(void);
b6a2f15e 192static void mainSetCwd(void);
efd900cb 193static int checkRunningPid(void);
85407535 194
7aa9bb3e 195#if !_SQUID_WINDOWS_
e18d7fdc 196static const char *squid_start_script = "squid_start";
b293c4d8 197#endif
e18d7fdc 198
9bc73deb 199#if TEST_ACCESS
200#include "test_access.c"
201#endif
202
63be0a78 203/** temporary thunk across to the unrefactored store interface */
8ff3fa2e 204
205class StoreRootEngine : public AsyncEngine
206{
207
208public:
26ac0430 209 int checkEvents(int timeout) {
8ff3fa2e 210 Store::Root().callback();
211 return EVENT_IDLE;
212 };
213};
214
9688b0ae 215class SignalEngine: public AsyncEngine
a553a5a3 216{
217
218public:
9688b0ae 219 virtual int checkEvents(int timeout);
a553a5a3 220
221private:
0a720258
AR
222 static void StopEventLoop(void *) {
223 if (EventLoop::Running)
224 EventLoop::Running->stop();
a553a5a3 225 }
226
9688b0ae 227 void doShutdown(time_t wait);
a553a5a3 228};
229
9688b0ae 230int
231SignalEngine::checkEvents(int timeout)
a553a5a3 232{
9688b0ae 233 PROF_start(SignalEngine_checkEvents);
fc68f6b1 234
a553a5a3 235 if (do_reconfigure) {
d71e4674 236 mainReconfigureStart();
a553a5a3 237 do_reconfigure = 0;
a553a5a3 238 } else if (do_rotate) {
239 mainRotate();
240 do_rotate = 0;
241 } else if (do_shutdown) {
9688b0ae 242 doShutdown(do_shutdown > 0 ? (int) Config.shutdownLifetime : 0);
a553a5a3 243 do_shutdown = 0;
26ac0430 244 }
a2c48c98
AR
245 BroadcastSignalIfAny(DebugSignal);
246 BroadcastSignalIfAny(RotateSignal);
247 BroadcastSignalIfAny(ReconfigureSignal);
248 BroadcastSignalIfAny(ShutdownSignal);
a553a5a3 249
9688b0ae 250 PROF_stop(SignalEngine_checkEvents);
251 return EVENT_IDLE;
252}
a553a5a3 253
9688b0ae 254void
255SignalEngine::doShutdown(time_t wait)
256{
e0236918
FC
257 debugs(1, DBG_IMPORTANT, "Preparing for shutdown after " << statCounter.client_http.requests << " requests");
258 debugs(1, DBG_IMPORTANT, "Waiting " << wait << " seconds for active connections to finish");
8ff3fa2e 259
9688b0ae 260 shutting_down = 1;
261
262#if USE_WIN32_SERVICE
263 WIN32_svcstatusupdate(SERVICE_STOP_PENDING, (wait + 1) * 1000);
264#endif
265
0bcb6908 266 /* run the closure code which can be shared with reconfigure */
9688b0ae 267 serverConnectionsClose();
2f1431ea 268#if USE_AUTH
0bcb6908 269 /* detach the auth components (only do this on full shutdown) */
c6cf8dee 270 Auth::Scheme::FreeAll();
2f1431ea 271#endif
21b7990f
AR
272
273 RunRegisteredHere(RegisteredRunner::startShutdown);
9688b0ae 274 eventAdd("SquidShutdown", &StopEventLoop, this, (double) (wait + 1), 1, false);
a553a5a3 275}
276
b8d8561b 277static void
0673c0ba 278usage(void)
ccff9601 279{
0ee4272b 280 fprintf(stderr,
cf2155f2 281 "Usage: %s [-cdhvzCFNRVYX] [-n name] [-s | -l facility] [-f config-file] [-[au] port] [-k signal]"
0e657244 282#if USE_WIN32_SERVICE
cf2155f2 283 "[-ir] [-O CommandLine]"
0e657244 284#endif
cf2155f2 285 "\n"
62e76326 286 " -a port Specify HTTP port number (default: %d).\n"
287 " -d level Write debugging to stderr also.\n"
288 " -f file Use given config-file instead of\n"
289 " %s\n"
290 " -h Print help message.\n"
0e657244 291#if USE_WIN32_SERVICE
292 " -i Installs as a Windows Service (see -n option).\n"
293#endif
98fcbb0e
AJ
294 " -k reconfigure|rotate|shutdown|"
295#ifdef SIGTTIN
296 "restart|"
297#endif
298 "interrupt|kill|debug|check|parse\n"
62e76326 299 " Parse configuration file, then send signal to \n"
300 " running copy (except -k parse) and exit.\n"
cf2155f2
AJ
301 " -n name Specify service name to use for service operations\n"
302 " default is: " APP_SHORTNAME ".\n"
0e657244 303#if USE_WIN32_SERVICE
0e657244 304 " -r Removes a Windows Service (see -n option).\n"
305#endif
5e6d4736 306 " -s | -l facility\n"
307 " Enable logging to syslog.\n"
62e76326 308 " -u port Specify ICP port number (default: %d), disable with 0.\n"
309 " -v Print version.\n"
04632397 310 " -z Create missing swap directories and then exit.\n"
62e76326 311 " -C Do not catch fatal signals.\n"
8eb28163 312 " -D OBSOLETE. Scheduled for removal.\n"
62e76326 313 " -F Don't serve any requests until store is rebuilt.\n"
314 " -N No daemon mode.\n"
0e657244 315#if USE_WIN32_SERVICE
316 " -O options\n"
317 " Set Windows Service Command line options in Registry.\n"
318#endif
62e76326 319 " -R Do not set REUSEADDR on port.\n"
320 " -S Double-check swap during rebuild.\n"
62e76326 321 " -X Force full debugging.\n"
322 " -Y Only return UDP_HIT or UDP_MISS_NOFETCH during fast reload.\n",
7dbca7a4 323 APP_SHORTNAME, CACHE_HTTP_PORT, DefaultConfigFile, CACHE_ICP_PORT);
77ffc99f 324 exit(1);
ccff9601 325}
326
63be0a78 327/**
328 * Parse the parameters received via command line interface.
329 *
d85b8894
AJ
330 \param argc Number of options received on command line
331 \param argv List of parameters received on command line
63be0a78 332 */
b8d8561b 333static void
334mainParseOptions(int argc, char *argv[])
090089c4 335{
090089c4 336 extern char *optarg;
4d64d74a 337 int c;
090089c4 338
0e657244 339#if USE_WIN32_SERVICE
5e6d4736 340 while ((c = getopt(argc, argv, "CDFNO:RSVYXa:d:f:hik:m::n:rsl:u:vz?")) != -1)
0e657244 341#else
cf2155f2 342 while ((c = getopt(argc, argv, "CDFNRSYXa:d:f:hk:m::n:sl:u:vz?")) != -1)
0e657244 343#endif
9b7292ce 344 {
345
26ac0430 346 switch (c) {
62e76326 347
348 case 'C':
63be0a78 349 /** \par C
350 * Unset/disabel global option for catchign signals. opt_catch_signals */
62e76326 351 opt_catch_signals = 0;
352 break;
353
354 case 'D':
63be0a78 355 /** \par D
8eb28163
AJ
356 * OBSOLETE: WAS: override to prevent optional startup DNS tests. */
357 debugs(1,DBG_CRITICAL, "WARNING: -D command-line option is obsolete.");
62e76326 358 break;
359
360 case 'F':
63be0a78 361 /** \par F
362 * Set global option for foreground rebuild. opt_foreground_rebuild */
62e76326 363 opt_foreground_rebuild = 1;
364 break;
365
366 case 'N':
63be0a78 367 /** \par N
368 * Set global option for 'no_daemon' mode. opt_no_daemon */
62e76326 369 opt_no_daemon = 1;
370 break;
63be0a78 371
0e657244 372#if USE_WIN32_SERVICE
373
374 case 'O':
63be0a78 375 /** \par O
376 * Set global option. opt_command_lin and WIN32_Command_Line */
0e657244 377 opt_command_line = 1;
378 WIN32_Command_Line = xstrdup(optarg);
379 break;
380#endif
62e76326 381
382 case 'R':
63be0a78 383 /** \par R
384 * Unset/disable global option opt_reuseaddr */
62e76326 385 opt_reuseaddr = 0;
386 break;
387
388 case 'S':
63be0a78 389 /** \par S
390 * Set global option opt_store_doublecheck */
62e76326 391 opt_store_doublecheck = 1;
392 break;
393
62e76326 394 case 'X':
63be0a78 395 /** \par X
396 * Force full debugging */
62493678
AJ
397 Debug::parseOptions("rotate=0 ALL,9");
398 Debug::override_X = 1;
62e76326 399 sigusr2_handle(SIGUSR2);
62e76326 400 break;
401
402 case 'Y':
63be0a78 403 /** \par Y
404 * Set global option opt_reload_hit_only */
62e76326 405 opt_reload_hit_only = 1;
62e76326 406 break;
407
0e657244 408#if USE_WIN32_SERVICE
409
410 case 'i':
63be0a78 411 /** \par i
412 * Set global option opt_install_service (to TRUE) */
0e657244 413 opt_install_service = TRUE;
0e657244 414 break;
0e657244 415#endif
416
62e76326 417 case 'a':
63be0a78 418 /** \par a
419 * Add optional HTTP port as given following the option */
62e76326 420 add_http_port(optarg);
62e76326 421 break;
422
423 case 'd':
63be0a78 424 /** \par d
62493678
AJ
425 * Set global option Debug::log_stderr to the number given follwoign the option */
426 Debug::log_stderr = atoi(optarg);
62e76326 427 break;
428
429 case 'f':
63be0a78 430 /** \par f
431 * Load the file given instead of the default squid.conf. */
62e76326 432 xfree(ConfigFile);
62e76326 433 ConfigFile = xstrdup(optarg);
62e76326 434 break;
435
436 case 'k':
63be0a78 437 /** \par k
438 * Run the administrative action given following the option */
fc68f6b1 439
63be0a78 440 /** \li When its an unknown option display the usage help. */
62e76326 441 if ((int) strlen(optarg) < 1)
442 usage();
443
444 if (!strncmp(optarg, "reconfigure", strlen(optarg)))
63be0a78 445 /** \li On reconfigure send SIGHUP. */
62e76326 446 opt_send_signal = SIGHUP;
447 else if (!strncmp(optarg, "rotate", strlen(optarg)))
63be0a78 448 /** \li On rotate send SIGQUIT or SIGUSR1. */
605f2c3e 449#if defined(_SQUID_LINUX_THREADS_)
62e76326 450 opt_send_signal = SIGQUIT;
e3175d1f 451#else
62e76326 452 opt_send_signal = SIGUSR1;
e3175d1f 453#endif
62e76326 454
455 else if (!strncmp(optarg, "debug", strlen(optarg)))
63be0a78 456 /** \li On debug send SIGTRAP or SIGUSR2. */
605f2c3e 457#if defined(_SQUID_LINUX_THREADS_)
62e76326 458 opt_send_signal = SIGTRAP;
e3175d1f 459#else
62e76326 460 opt_send_signal = SIGUSR2;
62e76326 461#endif
462
463 else if (!strncmp(optarg, "shutdown", strlen(optarg)))
63be0a78 464 /** \li On shutdown send SIGTERM. */
62e76326 465 opt_send_signal = SIGTERM;
466 else if (!strncmp(optarg, "interrupt", strlen(optarg)))
63be0a78 467 /** \li On interrupt send SIGINT. */
62e76326 468 opt_send_signal = SIGINT;
469 else if (!strncmp(optarg, "kill", strlen(optarg)))
63be0a78 470 /** \li On kill send SIGKILL. */
62e76326 471 opt_send_signal = SIGKILL;
ae1feb30 472
473#ifdef SIGTTIN
474
475 else if (!strncmp(optarg, "restart", strlen(optarg)))
63be0a78 476 /** \li On restart send SIGTTIN. (exit and restart by parent) */
477 opt_send_signal = SIGTTIN;
ae1feb30 478
479#endif
480
62e76326 481 else if (!strncmp(optarg, "check", strlen(optarg)))
63be0a78 482 /** \li On check send 0 / SIGNULL. */
62e76326 483 opt_send_signal = 0; /* SIGNULL */
484 else if (!strncmp(optarg, "parse", strlen(optarg)))
63be0a78 485 /** \li On parse set global flag to re-parse the config file only. */
486 opt_parse_cfg_only = 1;
62e76326 487 else
488 usage();
489
490 break;
491
492 case 'm':
63be0a78 493 /** \par m
494 * Set global malloc_debug_level to the value given following the option.
495 * if none is given it toggles the xmalloc_trace option on/off */
62e76326 496 if (optarg) {
30a4f2a8 497#if MALLOC_DBG
fc68f6b1 498 malloc_debug_level = atoi(optarg);
30a4f2a8 499#else
fc68f6b1 500 fatal("Need to add -DMALLOC_DBG when compiling to use -mX option");
33ab18e8 501#endif
62e76326 502
e2849af8 503 }
d9e7ee1f 504 break;
d9e7ee1f 505
0e657244 506 case 'n':
63be0a78 507 /** \par n
cf2155f2
AJ
508 * Set global option opt_signal_service (to true).
509 * Stores the additional parameter given in global service_name */
eeae1733 510 if (optarg && *optarg != '\0') {
d5f21615
AJ
511 const SBuf t(optarg);
512 ::Parser::Tokenizer tok(t);
513 const CharacterSet chr = CharacterSet::ALPHA+CharacterSet::DIGIT;
514 if (!tok.prefix(service_name, chr) || !tok.atEnd())
515 fatalf("Expected alphanumeric service name for the -n option but got: " SQUIDSBUFPH, SQUIDSBUFPRINT(service_name));
516 if (service_name.length() > 32)
517 fatalf("Service name (-n option) must be limited to 32 characters but got %u", service_name.length());
518 opt_signal_service = true;
519 } else {
520 fatal("A service name is required for the -n option");
521 }
0e657244 522 break;
523
cf2155f2
AJ
524#if USE_WIN32_SERVICE
525
0e657244 526 case 'r':
63be0a78 527 /** \par r
528 * Set global option opt_remove_service (to TRUE) */
0e657244 529 opt_remove_service = TRUE;
530
531 break;
532
533#endif
534
5e6d4736 535 case 'l':
63be0a78 536 /** \par l
537 * Stores the syslog facility name in global opt_syslog_facility
538 * then performs actions for -s option. */
5c6dae44 539 xfree(opt_syslog_facility); // ignore any previous options sent
5e6d4736 540 opt_syslog_facility = xstrdup(optarg);
541
62e76326 542 case 's':
63be0a78 543 /** \par s
544 * Initialize the syslog for output */
c307aec3 545#if HAVE_SYSLOG
62e76326 546
5e6d4736 547 _db_set_syslog(opt_syslog_facility);
0e657244 548
62e76326 549 break;
0e657244 550
c307aec3 551#else
62e76326 552
553 fatal("Logging to syslog not available on this platform");
0e657244 554
62e76326 555 /* NOTREACHED */
556#endif
557
558 case 'u':
63be0a78 559 /** \par u
560 * Store the ICP port number given in global option icpPortNumOverride
561 * ensuring its a positive number. */
62e76326 562 icpPortNumOverride = atoi(optarg);
563
564 if (icpPortNumOverride < 0)
565 icpPortNumOverride = 0;
566
567 break;
568
569 case 'v':
63be0a78 570 /** \par v
571 * Display squid version and build information. Then exit. */
4fe75473 572 printf("Squid Cache: Version %s\n" ,version_string);
d5f21615 573 printf("Service Name: " SQUIDSBUFPH "\n", SQUIDSBUFPRINT(service_name));
4fe75473
FC
574 if (strlen(SQUID_BUILD_INFO))
575 printf("%s\n",SQUID_BUILD_INFO);
576 printf( "configure options: %s\n", SQUID_CONFIGURE_OPTIONS);
62e76326 577
1a774556 578#if USE_WIN32_SERVICE
579
580 printf("Compiled as Windows System Service.\n");
581
582#endif
583
62e76326 584 exit(0);
585
586 /* NOTREACHED */
587
588 case 'z':
63be0a78 589 /** \par z
62493678
AJ
590 * Set global option Debug::log_stderr and opt_create_swap_dirs */
591 Debug::log_stderr = 1;
62e76326 592 opt_create_swap_dirs = 1;
62e76326 593 break;
594
63be0a78 595 case 'h':
596
62e76326 597 case '?':
598
599 default:
63be0a78 600 /** \par h,?, or unknown
601 * \copydoc usage() */
62e76326 602 usage();
603
604 break;
605 }
9b7292ce 606
090089c4 607 }
4d64d74a 608}
090089c4 609
7a2f978b 610/* ARGSUSED */
b293c4d8 611void
9b7292ce 612rotate_logs(int sig)
613{
5cd39a10 614 do_rotate = 1;
a2c48c98 615 RotateSignal = sig;
7aa9bb3e 616#if !_SQUID_WINDOWS_
30a4f2a8 617#if !HAVE_SIGACTION
62e76326 618
30a4f2a8 619 signal(sig, rotate_logs);
620#endif
a50bfe93 621#endif
30a4f2a8 622}
623
7a2f978b 624/* ARGSUSED */
b293c4d8 625void
9b7292ce 626reconfigure(int sig)
627{
5cd39a10 628 do_reconfigure = 1;
a2c48c98 629 ReconfigureSignal = sig;
7aa9bb3e 630#if !_SQUID_WINDOWS_
30a4f2a8 631#if !HAVE_SIGACTION
62e76326 632
30a4f2a8 633 signal(sig, reconfigure);
634#endif
a50bfe93 635#endif
30a4f2a8 636}
637
b8d8561b 638void
9b7292ce 639shut_down(int sig)
640{
2681d383 641 do_shutdown = sig == SIGINT ? -1 : 1;
a2c48c98 642 ShutdownSignal = sig;
ae1feb30 643#ifdef SIGTTIN
644
645 if (SIGTTIN == sig)
646 shutdown_status = 1;
647
648#endif
ca4b9ee6
DK
649
650 const pid_t ppid = getppid();
651
bd9fe5b4 652 if (!IamMasterProcess() && ppid > 1) {
ca4b9ee6
DK
653 // notify master that we are shutting down
654 if (kill(ppid, SIGUSR1) < 0)
655 debugs(1, DBG_IMPORTANT, "Failed to send SIGUSR1 to master process,"
656 " pid " << ppid << ": " << xstrerror());
657 }
658
7aa9bb3e 659#if !_SQUID_WINDOWS_
a67d2b2e 660#if KILL_PARENT_OPT
62e76326 661
bd9fe5b4 662 if (!IamMasterProcess() && ppid > 1) {
ca4b9ee6 663 debugs(1, DBG_IMPORTANT, "Killing master process, pid " << ppid);
62e76326 664
ca4b9ee6
DK
665 if (kill(ppid, sig) < 0)
666 debugs(1, DBG_IMPORTANT, "kill " << ppid << ": " << xstrerror());
88738790 667 }
62e76326 668
0f658b5b 669#endif /* KILL_PARENT_OPT */
6e40f263 670#if SA_RESETHAND == 0
671 signal(SIGTERM, SIG_DFL);
62e76326 672
6e40f263 673 signal(SIGINT, SIG_DFL);
62e76326 674
a50bfe93 675#endif
6e40f263 676#endif
30a4f2a8 677}
678
24382924 679static void
9b7292ce 680serverConnectionsOpen(void)
681{
7de94c8c
AR
682 if (IamPrimaryProcess()) {
683#if USE_WCCP
5667a628 684 wccpConnectionOpen();
7de94c8c 685#endif
45aae82b 686
7de94c8c
AR
687#if USE_WCCPv2
688
5667a628 689 wccp2ConnectionOpen();
7de94c8c
AR
690#endif
691 }
095ec2b1
AR
692 // start various proxying services if we are responsible for them
693 if (IamWorkerProcess()) {
5667a628 694 clientOpenListenSockets();
65d448bc 695 icpOpenPorts();
ace287ee 696#if USE_HTCP
65d448bc 697 htcpOpenPorts();
ace287ee 698#endif
a67d2b2e 699#if SQUID_SNMP
65d448bc 700 snmpOpenPorts();
320e9f36 701#endif
0b0cfcf2 702
5667a628
AR
703 icmpEngine.Open();
704 netdbInit();
705 asnInit();
706 ACL::Initialize();
707 peerSelectInit();
708
709 carpInit();
2f1431ea 710#if USE_AUTH
5667a628 711 peerUserHashInit();
2f1431ea 712#endif
5667a628 713 peerSourceHashInit();
7de94c8c 714 }
5f3f8d0e 715}
716
d71e4674 717static void
9b7292ce 718serverConnectionsClose(void)
719{
0a5a8601 720 assert(shutting_down || reconfiguring);
7de94c8c
AR
721
722 if (IamPrimaryProcess()) {
723#if USE_WCCP
724
5667a628 725 wccpConnectionClose();
7de94c8c
AR
726#endif
727#if USE_WCCPv2
728
5667a628 729 wccp2ConnectionClose();
7de94c8c
AR
730#endif
731 }
095ec2b1 732 if (IamWorkerProcess()) {
434a79b0 733 clientConnectionsClose();
5667a628 734 icpConnectionShutdown();
72549e05 735#if USE_HTCP
5667a628 736 htcpSocketShutdown();
72549e05 737#endif
62e76326 738
5667a628 739 icmpEngine.Close();
a67d2b2e 740#if SQUID_SNMP
65d448bc 741 snmpClosePorts();
320e9f36 742#endif
62e76326 743
5667a628 744 asnFreeMemory();
7de94c8c 745 }
5f3f8d0e 746}
747
b8d8561b 748static void
d71e4674 749mainReconfigureStart(void)
9b7292ce 750{
e0236918 751 debugs(1, DBG_IMPORTANT, "Reconfiguring Squid Cache (version " << version_string << ")...");
5cd39a10 752 reconfiguring = 1;
d71e4674
AR
753
754 // Initiate asynchronous closing sequence
15df8349 755 serverConnectionsClose();
65d448bc 756 icpClosePorts();
72549e05 757#if USE_HTCP
65d448bc 758 htcpClosePorts();
72549e05 759#endif
74addf6c 760 dnsShutdown();
95d2589c
CT
761#if USE_SSL_CRTD
762 Ssl::Helper::GetInstance()->Shutdown();
763#endif
cb4f4424 764#if USE_OPENSSL
f54e3d4c
AR
765 if (Ssl::CertValidationHelper::GetInstance())
766 Ssl::CertValidationHelper::GetInstance()->Shutdown();
95d2589c
CT
767 Ssl::TheGlobalContextStorage.reconfigureStart();
768#endif
74addf6c 769 redirectShutdown();
2f1431ea 770#if USE_AUTH
0bcb6908 771 authenticateReset();
2f1431ea 772#endif
d9572179 773 externalAclShutdown();
2db68ce5 774 storeDirCloseSwapLogs();
2e923080 775 storeLogClose();
776 accessLogClose();
3ff65596
AR
777#if ICAP_CLIENT
778 icapLogClose();
779#endif
d71e4674
AR
780
781 eventAdd("mainReconfigureFinish", &mainReconfigureFinish, NULL, 0, 1,
26ac0430 782 false);
d71e4674
AR
783}
784
785static void
26ac0430
AJ
786mainReconfigureFinish(void *)
787{
d71e4674
AR
788 debugs(1, 3, "finishing reconfiguring");
789
c68e9c6b 790 errorClean();
3aa4adbc 791 enter_suid(); /* root to read config file */
936b23cd
AJ
792
793 // we may have disabled the need for PURGE
e1381638 794 if (Config2.onoff.enable_purge)
936b23cd
AJ
795 Config2.onoff.enable_purge = 2;
796
18631119 797 // parse the config returns a count of errors encountered.
13aeac35 798 const int oldWorkers = Config.workers;
18631119
AJ
799 if ( parseConfigFile(ConfigFile) != 0) {
800 // for now any errors are a fatal condition...
801 self_destruct();
802 }
13aeac35
AR
803 if (oldWorkers != Config.workers) {
804 debugs(1, DBG_CRITICAL, "WARNING: Changing 'workers' (from " <<
5667a628 805 oldWorkers << " to " << Config.workers <<
0b68976e 806 ") requires a full restart. It has been ignored by reconfigure.");
13aeac35 807 Config.workers = oldWorkers;
a2c48c98 808 }
936b23cd 809
21b7990f
AR
810 RunRegisteredHere(RegisteredRunner::syncConfig);
811
96c2bb61
AR
812 if (IamPrimaryProcess())
813 CpuAffinityCheck();
814 CpuAffinityReconfigure();
815
c642c141 816 setUmask(Config.umask);
97244680 817 Mem::Report();
3aa4adbc 818 setEffectiveUser();
62493678 819 _db_init(Debug::cache_log, Debug::debugOptions);
429fdbec 820 ipcache_restart(); /* clear stuck entries */
821 fqdncache_restart(); /* sigh, fqdncache too */
0e70aa1e 822 parseEtcHosts();
53ad48e6 823 errorInitialize(); /* reload error pages */
2e923080 824 accessLogInit();
76fc7e57
AJ
825
826#if USE_LOADABLE_MODULES
827 LoadableModulesConfigure(Config.loadable_module_names);
828#endif
829
830#if USE_ADAPTATION
831 bool enableAdaptation = false;
832#if ICAP_CLIENT
833 Adaptation::Icap::TheConfig.finalize();
834 enableAdaptation = Adaptation::Icap::TheConfig.onoff || enableAdaptation;
835#endif
836#if USE_ECAP
837 Adaptation::Ecap::TheConfig.finalize(); // must be after we load modules
838 enableAdaptation = Adaptation::Ecap::TheConfig.onoff || enableAdaptation;
839#endif
840 Adaptation::Config::Finalize(enableAdaptation);
841#endif
d090e020 842
3ff65596
AR
843#if ICAP_CLIENT
844 icapLogOpen();
845#endif
2e923080 846 storeLogOpen();
74addf6c 847 dnsInit();
95d2589c
CT
848#if USE_SSL_CRTD
849 Ssl::Helper::GetInstance()->Init();
850#endif
cb4f4424 851#if USE_OPENSSL
2cef0ca6
AR
852 if (Ssl::CertValidationHelper::GetInstance())
853 Ssl::CertValidationHelper::GetInstance()->Init();
854#endif
62e76326 855
74addf6c 856 redirectInit();
2f1431ea 857#if USE_AUTH
5817ee13 858 authenticateInit(&Auth::TheConfig);
2f1431ea 859#endif
d9572179 860 externalAclInit();
7de94c8c
AR
861
862 if (IamPrimaryProcess()) {
1f38f50a 863#if USE_WCCP
62e76326 864
5667a628 865 wccpInit();
1f38f50a 866#endif
0b0cfcf2 867#if USE_WCCPv2
868
5667a628 869 wccp2Init();
0b0cfcf2 870#endif
7de94c8c 871 }
62e76326 872
0ffd22bc 873 serverConnectionsOpen();
9c2e9b50 874
3ee2b4f8 875 neighbors_init();
9c2e9b50 876
2db68ce5 877 storeDirOpenSwapLogs();
9c2e9b50 878
9c021a38 879 mimeInit(Config.mimeTablePathname);
9c2e9b50 880
c521ad17
DK
881 if (unlinkdNeeded())
882 unlinkdInit();
c521ad17 883
9a0a18de 884#if USE_DELAY_POOLS
b4cd430a
CT
885 Config.ClientDelay.finalize();
886#endif
887
926375e6 888 if (Config.onoff.announce) {
889 if (!eventFind(start_announce, NULL))
890 eventAdd("start_announce", start_announce, NULL, 3600.0, 1);
891 } else {
892 if (eventFind(start_announce, NULL))
893 eventDelete(start_announce, NULL);
894 }
895
b8890359 896 writePidFile(); /* write PID file */
9c2e9b50 897
5cd39a10 898 reconfiguring = 0;
899}
900
901static void
9b7292ce 902mainRotate(void)
903{
cc192b50 904 icmpEngine.Close();
e40aa8da 905 redirectShutdown();
2f1431ea 906#if USE_AUTH
0bcb6908 907 authenticateRotate();
2f1431ea 908#endif
d9572179 909 externalAclShutdown();
0a6dd8fb 910
5cd39a10 911 _db_rotate_log(); /* cache.log */
912 storeDirWriteCleanLogs(1);
913 storeLogRotate(); /* store.log */
914 accessLogRotate(); /* access.log */
3ff65596
AR
915#if ICAP_CLIENT
916 icapLogRotate(); /*icap.log*/
917#endif
cc192b50 918 icmpEngine.Open();
e40aa8da 919 redirectInit();
2f1431ea 920#if USE_AUTH
5817ee13 921 authenticateInit(&Auth::TheConfig);
2f1431ea 922#endif
d9572179 923 externalAclInit();
5f3f8d0e 924}
925
067bea91 926static void
9b7292ce 927setEffectiveUser(void)
928{
fc68f6b1 929 keepCapabilities();
85407535 930 leave_suid(); /* Run as non privilegied user */
1191b93b 931#if _SQUID_OS2_
62e76326 932
cd377065 933 return;
934#endif
62e76326 935
85407535 936 if (geteuid() == 0) {
fa84c01d
FC
937 debugs(0, DBG_CRITICAL, "Squid is not safe to run as root! If you must");
938 debugs(0, DBG_CRITICAL, "start Squid as root, then you must configure");
939 debugs(0, DBG_CRITICAL, "it to run as a non-priveledged user with the");
940 debugs(0, DBG_CRITICAL, "'cache_effective_user' option in the config file.");
62e76326 941 fatal("Don't run Squid as root, set 'cache_effective_user'!");
85407535 942 }
943}
944
dd0cbc64
AR
945/// changes working directory, providing error reporting
946static bool
947mainChangeDir(const char *dir)
948{
949 if (chdir(dir) == 0)
950 return true;
951
952 debugs(50, DBG_CRITICAL, "cannot change current directory to " << dir <<
953 ": " << xstrerror());
954 return false;
955}
956
133906f5 957/// set the working directory.
b6a2f15e 958static void
9b7292ce 959mainSetCwd(void)
960{
133906f5 961 static bool chrooted = false;
133906f5
AJ
962 if (Config.chroot_dir && !chrooted) {
963 chrooted = true;
62e76326 964
dd0cbc64
AR
965 if (chroot(Config.chroot_dir) != 0)
966 fatalf("chroot to %s failed: %s", Config.chroot_dir, xstrerror());
133906f5 967
dd0cbc64
AR
968 if (!mainChangeDir("/"))
969 fatalf("chdir to / after chroot to %s failed", Config.chroot_dir);
133906f5
AJ
970 }
971
dd0cbc64
AR
972 if (Config.coredump_dir && strcmp("none", Config.coredump_dir) != 0) {
973 if (mainChangeDir(Config.coredump_dir)) {
e0236918 974 debugs(0, DBG_IMPORTANT, "Set Current Directory to " << Config.coredump_dir);
62e76326 975 return;
62e76326 976 }
b6a2f15e 977 }
62e76326 978
02e8115e 979 /* If we don't have coredump_dir or couldn't cd there, report current dir */
dd0cbc64 980 char pathbuf[MAXPATHLEN];
4a504376 981 if (getcwd(pathbuf, MAXPATHLEN)) {
e0236918 982 debugs(0, DBG_IMPORTANT, "Current Directory is " << pathbuf);
4a504376 983 } else {
fa84c01d 984 debugs(50, DBG_CRITICAL, "WARNING: Can't find current directory, getcwd: " << xstrerror());
4a504376 985 }
b6a2f15e 986}
987
b8d8561b 988static void
9b7292ce 989mainInitialize(void)
990{
efd900cb 991 /* chroot if configured to run inside chroot */
133906f5 992 mainSetCwd();
62e76326 993
1758c627 994 if (opt_catch_signals) {
62e76326 995 squid_signal(SIGSEGV, death, SA_NODEFER | SA_RESETHAND);
996 squid_signal(SIGBUS, death, SA_NODEFER | SA_RESETHAND);
44f99671 997 }
62e76326 998
30a4f2a8 999 squid_signal(SIGPIPE, SIG_IGN, SA_RESTART);
1000 squid_signal(SIGCHLD, sig_child, SA_NODEFER | SA_RESTART);
44f99671 1001
85407535 1002 setEffectiveUser();
62e76326 1003
30a4f2a8 1004 if (icpPortNumOverride != 1)
f45dd259 1005 Config.Port.icp = (unsigned short) icpPortNumOverride;
30a4f2a8 1006
62493678 1007 _db_init(Debug::cache_log, Debug::debugOptions);
62e76326 1008
62493678 1009 fd_open(fileno(debug_log), FD_LOG, Debug::cache_log);
62e76326 1010
fa84c01d 1011 debugs(1, DBG_CRITICAL, "Starting Squid Cache version " << version_string << " for " << CONFIG_HOST_TYPE << "...");
cf2155f2 1012 debugs(1, DBG_CRITICAL, "Service Name: " << service_name);
62e76326 1013
be266cb2 1014#if _SQUID_WINDOWS_
b293c4d8 1015 if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) {
fa84c01d 1016 debugs(1, DBG_CRITICAL, "Service command line is: " << WIN32_Service_Command_Line);
b293c4d8 1017 } else
fa84c01d 1018 debugs(1, DBG_CRITICAL, "Running on " << WIN32_OS_string);
b293c4d8 1019#endif
1020
e0236918 1021 debugs(1, DBG_IMPORTANT, "Process ID " << getpid());
095ec2b1 1022
e0236918 1023 debugs(1, DBG_IMPORTANT, "Process Roles:" << ProcessRoles());
095ec2b1 1024
f3f0f563 1025 setSystemLimits();
e0236918 1026 debugs(1, DBG_IMPORTANT, "With " << Squid_MaxFD << " file descriptors available");
5f3f8d0e 1027
7aa9bb3e 1028#if _SQUID_WINDOWS_
6c1962dd 1029
e0236918 1030 debugs(1, DBG_IMPORTANT, "With " << _getmaxstdio() << " CRT stdio descriptors available");
6c1962dd 1031
1032 if (WIN32_Socks_initialized)
e0236918 1033 debugs(1, DBG_IMPORTANT, "Windows sockets initialized");
6c1962dd 1034
babd1fd5 1035 if (WIN32_OS_version > _WIN_OS_WINNT) {
26ac0430 1036 WIN32_IpAddrChangeMonitorInit();
babd1fd5 1037 }
1038
6c1962dd 1039#endif
1040
9f75c559 1041 if (!configured_once)
62e76326 1042 disk_init(); /* disk_init must go before ipcache_init() */
1043
5f3f8d0e 1044 ipcache_init();
62e76326 1045
f88bb09c 1046 fqdncache_init();
62e76326 1047
0e70aa1e 1048 parseEtcHosts();
62e76326 1049
74addf6c 1050 dnsInit();
62e76326 1051
586089cd
CT
1052#if USE_SSL_CRTD
1053 Ssl::Helper::GetInstance()->Init();
1054#endif
1055
cb4f4424 1056#if USE_OPENSSL
10a69fc0
CT
1057 if (!configured_once)
1058 Ssl::initialize_session_cache();
1059
2cef0ca6
AR
1060 if (Ssl::CertValidationHelper::GetInstance())
1061 Ssl::CertValidationHelper::GetInstance()->Init();
1062#endif
1063
74addf6c 1064 redirectInit();
2f1431ea 1065#if USE_AUTH
5817ee13 1066 authenticateInit(&Auth::TheConfig);
2f1431ea 1067#endif
d9572179 1068 externalAclInit();
62e76326 1069
2ac76861 1070 httpHeaderInitModule(); /* must go before any header processing (e.g. the one in errorInitialize) */
62e76326 1071
2246b732 1072 httpReplyInitModule(); /* must go before accepting replies */
62e76326 1073
9b312a19 1074 errorInitialize();
62e76326 1075
7a2f978b 1076 accessLogInit();
62e76326 1077
e1381638 1078#if ICAP_CLIENT
3ff65596
AR
1079 icapLogOpen();
1080#endif
1081
3898f57f 1082#if USE_IDENT
4daaf3cb 1083 Ident::Init();
3898f57f 1084#endif
4daaf3cb 1085
59ad6d31 1086#if SQUID_SNMP
62e76326 1087
5e14bf6d 1088 snmpInit();
62e76326 1089
5e14bf6d 1090#endif
30a4f2a8 1091#if MALLOC_DBG
62e76326 1092
5f3f8d0e 1093 malloc_debug(0, malloc_debug_level);
62e76326 1094
5f3f8d0e 1095#endif
1096
dbe4fd8e 1097 if (!configured_once) {
c521ad17
DK
1098 if (unlinkdNeeded())
1099 unlinkdInit();
62e76326 1100
1101 urlInitialize();
62e76326 1102 statInit();
1103 storeInit();
1104 mainSetCwd();
62e76326 1105 mimeInit(Config.mimeTablePathname);
62e76326 1106 refreshInit();
9a0a18de 1107#if USE_DELAY_POOLS
62e76326 1108 DelayPools::Init();
0d7e5d78 1109#endif
62e76326 1110
b6b6f466 1111 FwdState::initModule();
62ee09ca 1112 /* register the modules in the cache manager menus */
62ee09ca 1113
a08f1b5a 1114 cbdataRegisterWithCacheManager();
62ee09ca 1115 /* These use separate calls so that the comm loops can eventually
1116 * coexist.
1117 */
62ee09ca 1118
15b3c0d7 1119 eventInit();
610ee341 1120
26ac0430 1121 // TODO: pconn is a good candidate for new-style registration
6852be71 1122 // PconnModule::GetInstance()->registerWithCacheManager();
26ac0430 1123 // moved to PconnModule::PconnModule()
5f3f8d0e 1124 }
62e76326 1125
7de94c8c 1126 if (IamPrimaryProcess()) {
1f38f50a 1127#if USE_WCCP
5667a628 1128 wccpInit();
62e76326 1129
0b0cfcf2 1130#endif
1131#if USE_WCCPv2
1132
5667a628 1133 wccp2Init();
0b0cfcf2 1134
1f38f50a 1135#endif
7de94c8c 1136 }
62e76326 1137
2285407f 1138 serverConnectionsOpen();
62e76326 1139
3ee2b4f8 1140 neighbors_init();
fc68f6b1 1141
5f5e883f 1142 // neighborsRegisterWithCacheManager(); //moved to neighbors_init()
62e76326 1143
efd900cb 1144 if (Config.chroot_dir)
62e76326 1145 no_suid();
1146
dbe4fd8e 1147 if (!configured_once)
62e76326 1148 writePidFile(); /* write PID file */
0a5b9b32 1149
605f2c3e 1150#if defined(_SQUID_LINUX_THREADS_)
62e76326 1151
e3175d1f 1152 squid_signal(SIGQUIT, rotate_logs, SA_RESTART);
62e76326 1153
e3175d1f 1154 squid_signal(SIGTRAP, sigusr2_handle, SA_RESTART);
62e76326 1155
e3175d1f 1156#else
62e76326 1157
30a4f2a8 1158 squid_signal(SIGUSR1, rotate_logs, SA_RESTART);
62e76326 1159
30a4f2a8 1160 squid_signal(SIGUSR2, sigusr2_handle, SA_RESTART);
62e76326 1161
9fc0b4b8 1162#endif
62e76326 1163
30a4f2a8 1164 squid_signal(SIGHUP, reconfigure, SA_RESTART);
62e76326 1165
30a4f2a8 1166 squid_signal(SIGTERM, shut_down, SA_NODEFER | SA_RESETHAND | SA_RESTART);
62e76326 1167
30a4f2a8 1168 squid_signal(SIGINT, shut_down, SA_NODEFER | SA_RESETHAND | SA_RESTART);
62e76326 1169
ae1feb30 1170#ifdef SIGTTIN
1171
1172 squid_signal(SIGTTIN, shut_down, SA_NODEFER | SA_RESETHAND | SA_RESTART);
1173
1174#endif
1175
58a39dc9 1176 memCheckInit();
62e76326 1177
57afc994
AR
1178#if USE_LOADABLE_MODULES
1179 LoadableModulesConfigure(Config.loadable_module_names);
1180#endif
1181
8f361c50
AR
1182#if USE_ADAPTATION
1183 bool enableAdaptation = false;
1184
1185 // We can remove this dependency on specific adaptation mechanisms
1186 // if we create a generic Registry of such mechanisms. Should we?
b958cb0f 1187#if ICAP_CLIENT
26cc52cb
AR
1188 Adaptation::Icap::TheConfig.finalize();
1189 enableAdaptation = Adaptation::Icap::TheConfig.onoff || enableAdaptation;
6e5db507
AR
1190#endif
1191#if USE_ECAP
574b508c
AR
1192 Adaptation::Ecap::TheConfig.finalize(); // must be after we load modules
1193 enableAdaptation = Adaptation::Ecap::TheConfig.onoff || enableAdaptation;
b958cb0f 1194#endif
8f361c50
AR
1195 // must be the last adaptation-related finalize
1196 Adaptation::Config::Finalize(enableAdaptation);
b958cb0f
AR
1197#endif
1198
79039294
AR
1199#if USE_SQUID_ESI
1200 Esi::Init();
1201#endif
b958cb0f 1202
9a0a18de 1203#if USE_DELAY_POOLS
b4cd430a
CT
1204 Config.ClientDelay.finalize();
1205#endif
1206
dbe4fd8e 1207 if (!configured_once) {
c8f4eac4 1208 eventAdd("storeMaintain", Store::Maintain, NULL, 1.0, 1);
62e76326 1209
1210 if (Config.onoff.announce)
1211 eventAdd("start_announce", start_announce, NULL, 3600.0, 1);
1212
1213 eventAdd("ipcache_purgelru", ipcache_purgelru, NULL, 10.0, 1);
1214
1215 eventAdd("fqdncache_purgelru", fqdncache_purgelru, NULL, 15.0, 1);
1216
88bfe092 1217#if USE_XPROF_STATS
62e76326 1218
1219 eventAdd("cpuProfiling", xprof_event, NULL, 1.0, 1);
1220
88bfe092 1221#endif
62e76326 1222
1223 eventAdd("memPoolCleanIdlePools", Mem::CleanIdlePools, NULL, 15.0, 1);
4d7add01 1224 }
62e76326 1225
dbe4fd8e 1226 configured_once = 1;
4d64d74a 1227}
1228
c842329d 1229/// unsafe main routine -- may throw
f3f3e961 1230int SquidMain(int argc, char **argv);
c842329d 1231/// unsafe main routine wrapper to catch exceptions
6e5db507
AR
1232static int SquidMainSafe(int argc, char **argv);
1233
6c1962dd 1234#if USE_WIN32_SERVICE
1235/* When USE_WIN32_SERVICE is defined, the main function is placed in win32.cc */
1236extern "C" void WINAPI
e1381638 1237SquidWinSvcMain(int argc, char **argv)
18631119
AJ
1238{
1239 SquidMainSafe(argc, argv);
1240}
6c1962dd 1241#else
b8d8561b 1242int
1243main(int argc, char **argv)
6e5db507 1244{
18631119 1245 return SquidMainSafe(argc, argv);
6e5db507 1246}
18631119 1247#endif
6e5db507
AR
1248
1249static int
1250SquidMainSafe(int argc, char **argv)
1251{
1252 try {
1253 return SquidMain(argc, argv);
26ac0430 1254 } catch (const std::exception &e) {
51618c6a 1255 debugs(1, DBG_CRITICAL, "FATAL: dying from an unhandled exception: " <<
9199139f 1256 e.what());
26ac0430
AJ
1257 throw;
1258 } catch (...) {
51618c6a 1259 debugs(1, DBG_CRITICAL, "FATAL: dying from an unhandled exception.");
26ac0430
AJ
1260 throw;
1261 }
1262 return -1; // not reached
6e5db507
AR
1263}
1264
d4a3e179
AR
1265/// computes name and ID for the current kid process
1266static void
1267ConfigureCurrentKid(const char *processName)
1268{
5667a628 1269 // kids are marked with parenthesis around their process names
d4a3e179
AR
1270 if (processName && processName[0] == '(') {
1271 if (const char *idStart = strrchr(processName, '-')) {
1272 KidIdentifier = atoi(idStart + 1);
9de6c973
AR
1273 const size_t nameLen = idStart - (processName + 1);
1274 assert(nameLen < sizeof(TheKidName));
1275 xstrncpy(TheKidName, processName + 1, nameLen + 1);
095ec2b1
AR
1276 if (!strcmp(TheKidName, "squid-coord"))
1277 TheProcessKind = pkCoordinator;
9199139f 1278 else if (!strcmp(TheKidName, "squid"))
095ec2b1 1279 TheProcessKind = pkWorker;
9199139f 1280 else if (!strcmp(TheKidName, "squid-disk"))
095ec2b1
AR
1281 TheProcessKind = pkDisker;
1282 else
1283 TheProcessKind = pkOther; // including coordinator
d4a3e179 1284 }
2664c457 1285 } else {
9de6c973 1286 xstrncpy(TheKidName, APP_SHORTNAME, sizeof(TheKidName));
2664c457 1287 KidIdentifier = 0;
d4a3e179 1288 }
d4a3e179
AR
1289}
1290
f3f3e961 1291int
6e5db507 1292SquidMain(int argc, char **argv)
9b7292ce 1293{
d4a3e179 1294 ConfigureCurrentKid(argv[0]);
007d775d 1295
fb6a61d1 1296 Debug::parseOptions(NULL);
9b7292ce 1297 debug_log = stderr;
62e76326 1298
b9269882 1299#if defined(SQUID_MAXFD_LIMIT)
1300
1301 if (SQUID_MAXFD_LIMIT < Squid_MaxFD)
1302 Squid_MaxFD = SQUID_MAXFD_LIMIT;
1303
1304#endif
399e85ea 1305
cf3edd6f
FC
1306 /* NOP under non-windows */
1307 int WIN32_init_err=0;
a0aa9e74 1308 if ((WIN32_init_err = WIN32_Subsystem_Init(&argc, &argv)))
1309 return WIN32_init_err;
0e6d05ef 1310
9b7292ce 1311 /* call mallopt() before anything else */
0b29fe44 1312#if HAVE_MALLOPT
7328e889 1313#ifdef M_GRAIN
9b7292ce 1314 /* Round up all sizes to a multiple of this */
1315 mallopt(M_GRAIN, 16);
62e76326 1316
7328e889 1317#endif
1318#ifdef M_MXFAST
9b7292ce 1319 /* biggest size that is considered a small block */
1320 mallopt(M_MXFAST, 256);
62e76326 1321
7328e889 1322#endif
1323#ifdef M_NBLKS
9b7292ce 1324 /* allocate this many small blocks at once */
1325 mallopt(M_NLBLKS, 32);
62e76326 1326
7328e889 1327#endif
1328#endif /* HAVE_MALLOPT */
1329
9b7292ce 1330 squid_srandom(time(NULL));
4d64d74a 1331
9b7292ce 1332 getCurrentTime();
62e76326 1333
9b7292ce 1334 squid_start = current_time;
62e76326 1335
9b7292ce 1336 failure_notify = fatal_dump;
4d64d74a 1337
6c1962dd 1338#if USE_WIN32_SERVICE
1339
9b7292ce 1340 WIN32_svcstatusupdate(SERVICE_START_PENDING, 10000);
6c1962dd 1341
1342#endif
1343
9b7292ce 1344 mainParseOptions(argc, argv);
4d64d74a 1345
9aae6be3 1346 if (opt_parse_cfg_only) {
26ac0430 1347 Debug::parseOptions("ALL,1");
9aae6be3 1348 }
1349
6c1962dd 1350#if USE_WIN32_SERVICE
1351
26ac0430 1352 if (opt_install_service) {
9b7292ce 1353 WIN32_InstallService();
a0aa9e74 1354 return 0;
9b7292ce 1355 }
6c1962dd 1356
26ac0430 1357 if (opt_remove_service) {
9b7292ce 1358 WIN32_RemoveService();
a0aa9e74 1359 return 0;
9b7292ce 1360 }
6c1962dd 1361
26ac0430 1362 if (opt_command_line) {
9b7292ce 1363 WIN32_SetServiceCommandLine();
a0aa9e74 1364 return 0;
9b7292ce 1365 }
6c1962dd 1366
1367#endif
1368
9b7292ce 1369 /* parse configuration file
1370 * note: in "normal" case this used to be called from mainInitialize() */
1371 {
1372 int parse_err;
62e76326 1373
9b7292ce 1374 if (!ConfigFile)
1375 ConfigFile = xstrdup(DefaultConfigFile);
62e76326 1376
9b7292ce 1377 assert(!configured_once);
62e76326 1378
9b7292ce 1379 Mem::Init();
62e76326 1380
9b7292ce 1381 storeFsInit(); /* required for config parsing */
62e76326 1382
7b5b7ba8 1383 /* TODO: call the FS::Clean() in shutdown to do Fs cleanups */
af6a12ee 1384 Fs::Init();
7b5b7ba8 1385
b9ae18aa 1386 /* May not be needed for parsing, have not audited for such */
1387 DiskIOModule::SetupAllModules();
1388
59b2d47f 1389 /* Shouldn't be needed for config parsing, but have not audited for such */
1390 StoreFileSystem::SetupAllFs();
1391
c8f4eac4 1392 /* we may want the parsing process to set this up in the future */
1393 Store::Root(new StoreController);
89736861 1394 Auth::Init(); /* required for config parsing. NOP if !USE_AUTH */
055421ee
AJ
1395 Ip::ProbeTransport(); // determine IPv4 or IPv6 capabilities before parsing.
1396
31971e6a
AJ
1397 Format::Token::Init(); // XXX: temporary. Use a runners registry of pre-parse runners instead.
1398
dd9b1081 1399 parse_err = parseConfigFile(ConfigFile);
62e76326 1400
97244680 1401 Mem::Report();
26ac0430 1402
18631119 1403 if (opt_parse_cfg_only || parse_err > 0)
9b7292ce 1404 return parse_err;
9b7292ce 1405 }
c642c141 1406 setUmask(Config.umask);
9b7292ce 1407 if (-1 == opt_send_signal)
1408 if (checkRunningPid())
205d7c3b 1409 exit(0);
e13ee7ad 1410
9bc73deb 1411#if TEST_ACCESS
62e76326 1412
95564b0d 1413 comm_init();
62e76326 1414
9b7292ce 1415 mainInitialize();
62e76326 1416
9b7292ce 1417 test_access();
62e76326 1418
9b7292ce 1419 return 0;
62e76326 1420
9bc73deb 1421#endif
1422
9b7292ce 1423 /* send signal to running copy and exit */
26ac0430 1424 if (opt_send_signal != -1) {
9b7292ce 1425 /* chroot if configured to run inside chroot */
133906f5 1426 mainSetCwd();
a572d8be 1427 if (Config.chroot_dir) {
a572d8be 1428 no_suid();
1429 } else {
1430 leave_suid();
9b7292ce 1431 }
62e76326 1432
9b7292ce 1433 sendSignal();
1434 /* NOTREACHED */
1435 }
62e76326 1436
6d57128b 1437 debugs(1,2, HERE << "Doing post-config initialization\n");
520e0073 1438 leave_suid();
21b7990f
AR
1439 RunRegisteredHere(RegisteredRunner::finalizeConfig);
1440 RunRegisteredHere(RegisteredRunner::claimMemoryNeeds);
1441 RunRegisteredHere(RegisteredRunner::useConfig);
520e0073 1442 enter_suid();
9487bae9 1443
2ae5c85f
AJ
1444 if (!opt_no_daemon && Config.workers > 0)
1445 watch_child(argv);
1446
26ac0430 1447 if (opt_create_swap_dirs) {
9b7292ce 1448 /* chroot if configured to run inside chroot */
133906f5 1449 mainSetCwd();
62e76326 1450
9b7292ce 1451 setEffectiveUser();
04632397 1452 debugs(0, DBG_CRITICAL, "Creating missing swap directories");
c8f4eac4 1453 Store::Root().create();
6c1962dd 1454
9b7292ce 1455 return 0;
9b7292ce 1456 }
62e76326 1457
96c2bb61
AR
1458 if (IamPrimaryProcess())
1459 CpuAffinityCheck();
1460 CpuAffinityInit();
1461
95564b0d 1462 setMaxFD();
1463
1464 /* init comm module */
1465 comm_init();
62e76326 1466
26ac0430 1467 if (opt_no_daemon) {
9b7292ce 1468 /* we have to init fdstat here. */
1469 fd_open(0, FD_LOG, "stdin");
1470 fd_open(1, FD_LOG, "stdout");
1471 fd_open(2, FD_LOG, "stderr");
1472 }
62e76326 1473
6c1962dd 1474#if USE_WIN32_SERVICE
1475
9b7292ce 1476 WIN32_svcstatusupdate(SERVICE_START_PENDING, 10000);
6c1962dd 1477
1478#endif
1479
9b7292ce 1480 mainInitialize();
4d64d74a 1481
6c1962dd 1482#if USE_WIN32_SERVICE
1483
9b7292ce 1484 WIN32_svcstatusupdate(SERVICE_RUNNING, 0);
6c1962dd 1485
1486#endif
1487
9b7292ce 1488 /* main loop */
a553a5a3 1489 EventLoop mainLoop;
62e76326 1490
0a720258 1491 SignalEngine signalEngine;
6c1962dd 1492
9688b0ae 1493 mainLoop.registerEngine(&signalEngine);
62e76326 1494
8ff3fa2e 1495 /* TODO: stop requiring the singleton here */
1496 mainLoop.registerEngine(EventScheduler::GetInstance());
62e76326 1497
8ff3fa2e 1498 StoreRootEngine store_engine;
615f9581 1499
8ff3fa2e 1500 mainLoop.registerEngine(&store_engine);
a774fd3f 1501
8ff3fa2e 1502 CommSelectEngine comm_engine;
1503
8ff3fa2e 1504 mainLoop.registerEngine(&comm_engine);
1505
bef81ea5 1506 mainLoop.setPrimaryEngine(&comm_engine);
1507
8ff3fa2e 1508 /* use the standard time service */
1509 TimeEngine time_engine;
1510
1511 mainLoop.setTimeService(&time_engine);
1512
7de94c8c 1513 if (IamCoordinatorProcess())
4299f876 1514 AsyncJob::Start(Ipc::Coordinator::Instance());
095ec2b1 1515 else if (UsingSmp() && (IamWorkerProcess() || IamDiskProcess()))
4299f876 1516 AsyncJob::Start(new Ipc::Strand);
10cefb7b 1517
48d54e4d
AJ
1518 /* at this point we are finished the synchronous startup. */
1519 starting_up = 0;
1520
8ff3fa2e 1521 mainLoop.run();
1522
1523 if (mainLoop.errcount == 10)
1524 fatal_dump("Event loop exited with failure.");
1525
1526 /* shutdown squid now */
1527 SquidShutdown();
62e76326 1528
9b7292ce 1529 /* NOTREACHED */
9b7292ce 1530 return 0;
090089c4 1531}
7690e8eb 1532
b8d8561b 1533static void
0673c0ba 1534sendSignal(void)
7690e8eb 1535{
ff8d0ea6 1536 pid_t pid;
fedac7e5 1537 debug_log = stderr;
258ac4d7 1538
1539 if (strcmp(Config.pidFilename, "none") == 0) {
e0236918 1540 debugs(0, DBG_IMPORTANT, "No pid_filename specified. Trusting you know what you are doing.");
258ac4d7 1541 }
1542
fedac7e5 1543 pid = readPidFile();
62e76326 1544
fedac7e5 1545 if (pid > 1) {
6c1962dd 1546#if USE_WIN32_SERVICE
6c1962dd 1547 if (opt_signal_service) {
1548 WIN32_sendSignal(opt_send_signal);
1549 exit(0);
cf3edd6f 1550 } else {
7dbca7a4 1551 fprintf(stderr, "%s: ERROR: Could not send ", APP_SHORTNAME);
6c1962dd 1552 fprintf(stderr, "signal to Squid Service:\n");
1553 fprintf(stderr, "missing -n command line switch.\n");
1554 exit(1);
1555 }
6c1962dd 1556 /* NOTREACHED */
6c1962dd 1557#endif
1558
62e76326 1559 if (kill(pid, opt_send_signal) &&
1560 /* ignore permissions if just running check */
1561 !(opt_send_signal == 0 && errno == EPERM)) {
7dbca7a4 1562 fprintf(stderr, "%s: ERROR: Could not send ", APP_SHORTNAME);
62e76326 1563 fprintf(stderr, "signal %d to process %d: %s\n",
1564 opt_send_signal, (int) pid, xstrerror());
1565 exit(1);
1566 }
fedac7e5 1567 } else {
205d7c3b 1568 if (opt_send_signal != SIGTERM) {
e08d498f 1569 fprintf(stderr, "%s: ERROR: No running copy\n", APP_SHORTNAME);
205d7c3b
AJ
1570 exit(1);
1571 } else {
e08d498f 1572 fprintf(stderr, "%s: No running copy\n", APP_SHORTNAME);
205d7c3b
AJ
1573 exit(0);
1574 }
7690e8eb 1575 }
62e76326 1576
fedac7e5 1577 /* signal successfully sent */
1578 exit(0);
1579}
f95b8144 1580
7aa9bb3e 1581#if !_SQUID_WINDOWS_
e18d7fdc 1582/*
1583 * This function is run when Squid is in daemon mode, just
1584 * before the parent forks and starts up the child process.
1585 * It can be used for admin-specific tasks, such as notifying
1586 * someone that Squid is (re)started.
1587 */
1588static void
1589mainStartScript(const char *prog)
1590{
ef364f64 1591 char script[MAXPATHLEN];
e18d7fdc 1592 char *t;
1593 size_t sl = 0;
1594 pid_t cpid;
1595 pid_t rpid;
1596 xstrncpy(script, prog, MAXPATHLEN);
62e76326 1597
e18d7fdc 1598 if ((t = strrchr(script, '/'))) {
62e76326 1599 *(++t) = '\0';
1600 sl = strlen(script);
e18d7fdc 1601 }
62e76326 1602
e18d7fdc 1603 xstrncpy(&script[sl], squid_start_script, MAXPATHLEN - sl);
62e76326 1604
e18d7fdc 1605 if ((cpid = fork()) == 0) {
62e76326 1606 /* child */
f75662c9 1607 execl(script, squid_start_script, (char *)NULL);
482aa790 1608 _exit(-1);
e18d7fdc 1609 } else {
62e76326 1610 do {
1191b93b 1611#if _SQUID_NEXT_
62e76326 1612 union wait status;
007d775d 1613 rpid = wait4(cpid, &status, 0, NULL);
e18d7fdc 1614#else
62e76326 1615
1616 int status;
007d775d 1617 rpid = waitpid(cpid, &status, 0);
e18d7fdc 1618#endif
62e76326 1619
1620 } while (rpid != cpid);
e18d7fdc 1621 }
1622}
1623
7aa9bb3e 1624#endif /* _SQUID_WINDOWS_ */
a50bfe93 1625
efd900cb 1626static int
1627checkRunningPid(void)
1628{
b81949b9 1629 // master process must start alone, but its kids processes may co-exist
7de94c8c 1630 if (!IamMasterProcess())
b81949b9
AR
1631 return 0;
1632
efd900cb 1633 pid_t pid;
e0077312 1634
1635 if (!debug_log)
1636 debug_log = stderr;
1637
efd900cb 1638 pid = readPidFile();
62e76326 1639
efd900cb 1640 if (pid < 2)
62e76326 1641 return 0;
1642
efd900cb 1643 if (kill(pid, 0) < 0)
62e76326 1644 return 0;
1645
fa84c01d 1646 debugs(0, DBG_CRITICAL, "Squid is already running! Process ID " << pid);
62e76326 1647
efd900cb 1648 return 1;
1649}
1650
f95b8144 1651static void
bbe199dc 1652watch_child(char *argv[])
f95b8144 1653{
7aa9bb3e 1654#if !_SQUID_WINDOWS_
f95b8144 1655 char *prog;
1191b93b 1656#if _SQUID_NEXT_
62e76326 1657
f95b8144 1658 union wait status;
1659#else
62e76326 1660
f95b8144 1661 int status;
1662#endif
62e76326 1663
e3a3b845 1664 pid_t pid;
c99c5397 1665#ifdef TIOCNOTTY
1666
54f742e7 1667 int i;
c99c5397 1668#endif
1669
742724a4 1670 int nullfd;
62e76326 1671
7de94c8c 1672 if (!IamMasterProcess())
62e76326 1673 return;
1674
7dbca7a4 1675 openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
62e76326 1676
54f742e7 1677 if ((pid = fork()) < 0)
62e76326 1678 syslog(LOG_ALERT, "fork failed: %s", xstrerror());
54f742e7 1679 else if (pid > 0)
62e76326 1680 exit(0);
1681
54f742e7 1682 if (setsid() < 0)
62e76326 1683 syslog(LOG_ALERT, "setsid failed: %s", xstrerror());
1684
efd900cb 1685 closelog();
62e76326 1686
54f742e7 1687#ifdef TIOCNOTTY
62e76326 1688
c4aefe96 1689 if ((i = open("/dev/tty", O_RDWR | O_TEXT)) >= 0) {
62e76326 1690 ioctl(i, TIOCNOTTY, NULL);
1691 close(i);
54f742e7 1692 }
62e76326 1693
54f742e7 1694#endif
b05490a8 1695
7f6ffd15 1696 /*
1697 * RBCOLLINS - if cygwin stackdumps when squid is run without
1698 * -N, check the cygwin1.dll version, it needs to be AT LEAST
1699 * 1.1.3. execvp had a bit overflow error in a loop..
1700 */
742724a4 1701 /* Connect stdio to /dev/null in daemon mode */
4da086c4 1702 nullfd = open(_PATH_DEVNULL, O_RDWR | O_TEXT);
62e76326 1703
e4a1325e 1704 if (nullfd < 0)
4da086c4 1705 fatalf(_PATH_DEVNULL " %s\n", xstrerror());
e4a1325e 1706
742724a4 1707 dup2(nullfd, 0);
62e76326 1708
62493678 1709 if (Debug::log_stderr < 0) {
62e76326 1710 dup2(nullfd, 1);
1711 dup2(nullfd, 2);
742724a4 1712 }
62e76326 1713
ca4b9ee6
DK
1714 // handle shutdown notifications from kids
1715 squid_signal(SIGUSR1, sig_shutdown, SA_RESTART);
1716
13aeac35
AR
1717 if (Config.workers > 128) {
1718 syslog(LOG_ALERT, "Suspiciously high workers value: %d",
5667a628 1719 Config.workers);
007d775d 1720 // but we keep going in hope that user knows best
5667a628 1721 }
095ec2b1
AR
1722 TheKids.init();
1723
a2515f86 1724 syslog(LOG_NOTICE, "Squid Parent: will start %d kids", (int)TheKids.count());
007d775d
AR
1725
1726 // keep [re]starting kids until it is time to quit
f95b8144 1727 for (;;) {
62e76326 1728 mainStartScript(argv[0]);
1729
007d775d 1730 // start each kid that needs to be [re]started; once
10cefb7b 1731 for (int i = TheKids.count() - 1; i >= 0; --i) {
007d775d 1732 Kid& kid = TheKids.get(i);
ca4b9ee6 1733 if (!kid.shouldRestart())
007d775d
AR
1734 continue;
1735
1736 if ((pid = fork()) == 0) {
1737 /* child */
1738 openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
bc91a636 1739 prog = argv[0];
007d775d
AR
1740 argv[0] = const_cast<char*>(kid.name().termedBuf());
1741 execvp(prog, argv);
1742 syslog(LOG_ALERT, "execvp failed: %s", xstrerror());
1743 }
1744
1745 kid.start(pid);
095ec2b1 1746 syslog(LOG_NOTICE, "Squid Parent: %s process %d started",
9199139f 1747 kid.name().termedBuf(), pid);
62e76326 1748 }
1749
1750 /* parent */
7dbca7a4 1751 openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
62e76326 1752
62e76326 1753 squid_signal(SIGINT, SIG_IGN, SA_RESTART);
1754
1191b93b 1755#if _SQUID_NEXT_
62e76326 1756
1757 pid = wait3(&status, 0, NULL);
1758
f95b8144 1759#else
62e76326 1760
1761 pid = waitpid(-1, &status, 0);
1762
007d775d 1763#endif
86b91dcd 1764 // Loop to collect all stopped kids before we go to sleep below.
5667a628 1765 do {
007d775d
AR
1766 Kid* kid = TheKids.find(pid);
1767 if (kid) {
1768 kid->stop(status);
1769 if (kid->calledExit()) {
1770 syslog(LOG_NOTICE,
095ec2b1
AR
1771 "Squid Parent: %s process %d exited with status %d",
1772 kid->name().termedBuf(),
5667a628 1773 kid->getPid(), kid->exitStatus());
007d775d
AR
1774 } else if (kid->signaled()) {
1775 syslog(LOG_NOTICE,
095ec2b1
AR
1776 "Squid Parent: %s process %d exited due to signal %d with status %d",
1777 kid->name().termedBuf(),
5667a628 1778 kid->getPid(), kid->termSignal(), kid->exitStatus());
007d775d 1779 } else {
095ec2b1
AR
1780 syslog(LOG_NOTICE, "Squid Parent: %s process %d exited",
1781 kid->name().termedBuf(), kid->getPid());
007d775d 1782 }
ca4b9ee6 1783 if (kid->hopeless()) {
1a98557c 1784 syslog(LOG_NOTICE, "Squid Parent: %s process %d will not"
ca4b9ee6 1785 " be restarted due to repeated, frequent failures",
1a98557c 1786 kid->name().termedBuf(), kid->getPid());
ca4b9ee6 1787 }
007d775d
AR
1788 } else {
1789 syslog(LOG_NOTICE, "Squid Parent: unknown child process %d exited", pid);
1790 }
1191b93b 1791#if _SQUID_NEXT_
007d775d
AR
1792 } while ((pid = wait3(&status, WNOHANG, NULL)) > 0);
1793#else
5667a628
AR
1794 }
1795 while ((pid = waitpid(-1, &status, WNOHANG)) > 0);
62e76326 1796#endif
1797
ca4b9ee6 1798 if (!TheKids.someRunning() && !TheKids.shouldRestartSome()) {
520e0073 1799 leave_suid();
21b7990f
AR
1800 // XXX: Master process has no main loop and, hence, should not call
1801 // RegisteredRunner::startShutdown which promises a loop iteration.
1802 RunRegisteredHere(RegisteredRunner::finishShutdown);
520e0073 1803 enter_suid();
c011f9bc 1804
ca4b9ee6
DK
1805 if (TheKids.someSignaled(SIGINT) || TheKids.someSignaled(SIGTERM)) {
1806 syslog(LOG_ALERT, "Exiting due to unexpected forced shutdown");
1807 exit(1);
1808 }
62e76326 1809
ca4b9ee6
DK
1810 if (TheKids.allHopeless()) {
1811 syslog(LOG_ALERT, "Exiting due to repeated, frequent failures");
1812 exit(1);
1813 }
62e76326 1814
007d775d
AR
1815 exit(0);
1816 }
06a0fbd3 1817
62e76326 1818 squid_signal(SIGINT, SIG_DFL, SA_RESTART);
1819 sleep(3);
f95b8144 1820 }
62e76326 1821
bbe199dc 1822 /* NOTREACHED */
7aa9bb3e 1823#endif /* _SQUID_WINDOWS_ */
a572d8be 1824
f95b8144 1825}
fff6ad65 1826
9ec1a1dc 1827static void
8ff3fa2e 1828SquidShutdown()
fff6ad65 1829{
d71e4674
AR
1830 /* XXX: This function is called after the main loop has quit, which
1831 * means that no AsyncCalls would be called, including close handlers.
1832 * TODO: We need to close/shut/free everything that needs calls before
1833 * exiting the loop.
26ac0430 1834 */
d71e4674 1835
6c1962dd 1836#if USE_WIN32_SERVICE
1837 WIN32_svcstatusupdate(SERVICE_STOP_PENDING, 10000);
1838#endif
1839
e0236918 1840 debugs(1, DBG_IMPORTANT, "Shutting down...");
95a83c22 1841 dnsShutdown();
95d2589c
CT
1842#if USE_SSL_CRTD
1843 Ssl::Helper::GetInstance()->Shutdown();
2cef0ca6 1844#endif
cb4f4424 1845#if USE_OPENSSL
f54e3d4c
AR
1846 if (Ssl::CertValidationHelper::GetInstance())
1847 Ssl::CertValidationHelper::GetInstance()->Shutdown();
95d2589c 1848#endif
95a83c22 1849 redirectShutdown();
1850 externalAclShutdown();
65d448bc 1851 icpClosePorts();
d723bf6b 1852#if USE_HTCP
65d448bc 1853 htcpClosePorts();
d723bf6b 1854#endif
59ad6d31 1855#if SQUID_SNMP
65d448bc 1856 snmpClosePorts();
320e9f36 1857#endif
eb824054 1858#if USE_WCCP
62e76326 1859
320e9f36 1860 wccpConnectionClose();
d723bf6b 1861#endif
0b0cfcf2 1862#if USE_WCCPv2
1863
1864 wccp2ConnectionClose();
1865#endif
62e76326 1866
fff6ad65 1867 releaseServerSockets();
d723bf6b 1868 commCloseAllSockets();
79039294
AR
1869
1870#if USE_SQUID_ESI
1871 Esi::Clean();
1872#endif
1873
9a0a18de 1874#if USE_DELAY_POOLS
b67e2c8c 1875 DelayPools::FreePools();
515ec4dc 1876#endif
2f1431ea 1877#if USE_AUTH
0bcb6908 1878 authenticateReset();
2f1431ea 1879#endif
6c1962dd 1880#if USE_WIN32_SERVICE
1881
1882 WIN32_svcstatusupdate(SERVICE_STOP_PENDING, 10000);
1883#endif
62e76326 1884
c8f4eac4 1885 Store::Root().sync(); /* Flush pending object writes/unlinks */
4d075ba0 1886
b6b42084 1887 unlinkdClose(); /* after sync/flush. NOP if !USE_UNLINKD */
fc68f6b1 1888
fff6ad65 1889 storeDirWriteCleanLogs(0);
1890 PrintRusage();
1891 dumpMallocStats();
c8f4eac4 1892 Store::Root().sync(); /* Flush log writes */
fff6ad65 1893 storeLogClose();
1894 accessLogClose();
c8f4eac4 1895 Store::Root().sync(); /* Flush log close */
59b2d47f 1896 StoreFileSystem::FreeAllFs();
b9ae18aa 1897 DiskIOModule::FreeAllModules();
afec404b 1898#if LEAK_CHECK_MODE && 0 /* doesn't work at the moment */
62e76326 1899
fff6ad65 1900 configFreeMemory();
1901 storeFreeMemory();
33ab18e8 1902 /*stmemFreeMemory(); */
fff6ad65 1903 netdbFreeMemory();
1904 ipcacheFreeMemory();
1905 fqdncacheFreeMemory();
1906 asnFreeMemory();
26a369ba 1907 clientdbFreeMemory();
7021844c 1908 httpHeaderCleanModule();
d2db411c 1909 statFreeMemory();
f1fc2a8d 1910 eventFreeMemory();
c68e9c6b 1911 mimeFreeMemory();
1912 errorClean();
33ab18e8 1913#endif
57fc379e
CT
1914 // clear StoreController
1915 Store::Root(NULL);
1916
fff6ad65 1917 fdDumpOpen();
62e76326 1918
236d1779 1919 comm_exit();
62e76326 1920
21b7990f 1921 RunRegisteredHere(RegisteredRunner::finishShutdown);
62e76326 1922
553d498c
AJ
1923 memClean();
1924
7de94c8c 1925 if (IamPrimaryProcess()) {
a2c48c98
AR
1926 if (Config.pidFilename && strcmp(Config.pidFilename, "none") != 0) {
1927 enter_suid();
1928 safeunlink(Config.pidFilename, 0);
1929 leave_suid();
1930 }
ab50ee9e 1931 }
62e76326 1932
e0236918 1933 debugs(1, DBG_IMPORTANT, "Squid Cache (Version " << version_string << "): Exiting normally.");
62e76326 1934
0cfa98cb 1935 /*
1936 * DPW 2006-10-23
1937 * We used to fclose(debug_log) here if it was set, but then
1938 * we forgot to set it to NULL. That caused some coredumps
1939 * because exit() ends up calling a bunch of destructors and
1940 * such. So rather than forcing the debug_log to close, we'll
1941 * leave it open so that those destructors can write some
1942 * debugging if necessary. The file will be closed anyway when
1943 * the process truly exits.
1944 */
62e76326 1945
ae1feb30 1946 exit(shutdown_status);
fff6ad65 1947}
bef81ea5 1948