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