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