3 * $Id: main.cc,v 1.439 2006/12/21 00:34:51 hno Exp $
5 * DEBUG: section 1 Startup and Main Loop
6 * AUTHOR: Harvest Derived
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
37 #include "AccessLogEntry.h"
38 #include "authenticate.h"
39 #include "CacheManager.h"
40 #include "ConfigParser.h"
41 #include "errorpage.h"
43 #include "EventLoop.h"
44 #include "ExternalACL.h"
47 #include "HttpReply.h"
53 #include "StoreFileSystem.h"
54 #include "DiskIO/DiskIOModule.h"
57 #include "comm_epoll.h"
60 #include "comm_kqueue.h"
63 #include "comm_poll.h"
66 #include "comm_select.h"
69 #include "comm_select.h"
71 #include "SquidTime.h"
78 #include "squid_windows.h"
81 static int opt_install_service
= FALSE
;
82 static int opt_remove_service
= FALSE
;
83 static int opt_signal_service
= FALSE
;
84 static int opt_command_line
= FALSE
;
85 extern void WIN32_svcstatusupdate(DWORD
, DWORD
);
86 void WINAPI
WIN32_svcHandler(DWORD
);
90 /* for error reporting from xmalloc and friends */
91 SQUIDCEXTERN
void (*failure_notify
) (const char *);
93 static int opt_parse_cfg_only
= 0;
94 static char *opt_syslog_facility
= NULL
;
95 static int icpPortNumOverride
= 1; /* Want to detect "-u 0" */
96 static int configured_once
= 0;
98 static int malloc_debug_level
= 0;
100 static volatile int do_reconfigure
= 0;
101 static volatile int do_rotate
= 0;
102 static volatile int do_shutdown
= 0;
103 static volatile int shutdown_status
= 0;
105 static void mainRotate(void);
106 static void mainReconfigure(void);
107 static void mainInitialize(void);
108 static void usage(void);
109 static void mainParseOptions(int, char **);
110 static void sendSignal(void);
111 static void serverConnectionsOpen(void);
112 static void watch_child(char **);
113 static void setEffectiveUser(void);
115 extern void log_trace_done();
116 extern void log_trace_init(char *);
118 static void SquidShutdown(void);
119 static void mainSetCwd(void);
120 static int checkRunningPid(void);
122 static CacheManager manager
;
124 #ifndef _SQUID_MSWIN_
125 static const char *squid_start_script
= "squid_start";
129 #include "test_access.c"
132 /* temporary thunk across to the unrefactored store interface */
134 class StoreRootEngine
: public AsyncEngine
138 int checkEvents(int timeout
)
140 Store::Root().callback();
145 class SignalDispatcher
: public CompletionDispatcher
149 SignalDispatcher(EventLoop
&loop
) : loop(loop
), events_dispatched(false) {}
151 void addEventLoop(EventLoop
* loop
);
152 virtual bool dispatch();
155 static void StopEventLoop(void * data
)
157 static_cast<SignalDispatcher
*>(data
)->loop
.stop();
161 bool events_dispatched
;
165 SignalDispatcher::dispatch()
167 PROF_start(SignalDispatcher_dispatch
);
168 if (do_reconfigure
) {
171 } else if (do_rotate
) {
174 } else if (do_shutdown
) {
175 time_t wait
= do_shutdown
> 0 ? (int) Config
.shutdownLifetime
: 0;
176 debug(1, 1) ("Preparing for shutdown after %d requests\n",
177 statCounter
.client_http
.requests
);
178 debug(1, 1) ("Waiting %d seconds for active connections to finish\n",
182 #if USE_WIN32_SERVICE
184 WIN32_svcstatusupdate(SERVICE_STOP_PENDING
, (wait
+ 1) * 1000);
187 serverConnectionsClose();
188 eventAdd("SquidShutdown", StopEventLoop
, this, (double) (wait
+ 1), 1, false);
191 bool result
= events_dispatched
;
192 events_dispatched
= false;
193 PROF_stop(SignalDispatcher_dispatch
);
201 #if USE_WIN32_SERVICE
202 "Usage: %s [-cdhirvzCDFNRVYX] [-s | -l facility] [-f config-file] [-[au] port] [-k signal] [-n name] [-O CommandLine]\n"
204 "Usage: %s [-cdhvzCDFNRVYX] [-s | -l facility] [-f config-file] [-[au] port] [-k signal]\n"
206 " -a port Specify HTTP port number (default: %d).\n"
207 " -d level Write debugging to stderr also.\n"
208 " -f file Use given config-file instead of\n"
210 " -h Print help message.\n"
211 #if USE_WIN32_SERVICE
212 " -i Installs as a Windows Service (see -n option).\n"
214 " -k reconfigure|rotate|shutdown|interrupt|kill|debug|check|parse\n"
215 " Parse configuration file, then send signal to \n"
216 " running copy (except -k parse) and exit.\n"
217 #if USE_WIN32_SERVICE
218 " -n name Specify Windows Service name to use for service operations\n"
219 " default is: " _WIN_SQUID_DEFAULT_SERVICE_NAME
".\n"
220 " -r Removes a Windows Service (see -n option).\n"
222 " -s | -l facility\n"
223 " Enable logging to syslog.\n"
224 " -u port Specify ICP port number (default: %d), disable with 0.\n"
225 " -v Print version.\n"
226 " -z Create swap directories\n"
227 " -C Do not catch fatal signals.\n"
228 " -D Disable initial DNS tests.\n"
229 " -F Don't serve any requests until store is rebuilt.\n"
230 " -N No daemon mode.\n"
231 #if USE_WIN32_SERVICE
233 " Set Windows Service Command line options in Registry.\n"
235 " -R Do not set REUSEADDR on port.\n"
236 " -S Double-check swap during rebuild.\n"
237 " -V Virtual host httpd-accelerator.\n"
238 " -X Force full debugging.\n"
239 " -Y Only return UDP_HIT or UDP_MISS_NOFETCH during fast reload.\n",
240 appname
, CACHE_HTTP_PORT
, DefaultConfigFile
, CACHE_ICP_PORT
);
245 mainParseOptions(int argc
, char *argv
[])
250 #if USE_WIN32_SERVICE
252 while ((c
= getopt(argc
, argv
, "CDFNO:RSVYXa:d:f:hik:m::n:rsl:u:vz?")) != -1)
255 while ((c
= getopt(argc
, argv
, "CDFNRSYXa:d:f:hk:m::sl:u:vz?")) != -1)
264 opt_catch_signals
= 0;
272 opt_foreground_rebuild
= 1;
278 #if USE_WIN32_SERVICE
281 opt_command_line
= 1;
282 WIN32_Command_Line
= xstrdup(optarg
);
291 opt_store_doublecheck
= 1;
295 /* force full debugging */
296 sigusr2_handle(SIGUSR2
);
301 opt_reload_hit_only
= 1;
305 #if USE_WIN32_SERVICE
308 opt_install_service
= TRUE
;
315 add_http_port(optarg
);
320 opt_debug_stderr
= atoi(optarg
);
327 ConfigFile
= xstrdup(optarg
);
337 if ((int) strlen(optarg
) < 1)
340 if (!strncmp(optarg
, "reconfigure", strlen(optarg
)))
341 opt_send_signal
= SIGHUP
;
342 else if (!strncmp(optarg
, "rotate", strlen(optarg
)))
343 #ifdef _SQUID_LINUX_THREADS_
345 opt_send_signal
= SIGQUIT
;
349 opt_send_signal
= SIGUSR1
;
353 else if (!strncmp(optarg
, "debug", strlen(optarg
)))
354 #ifdef _SQUID_LINUX_THREADS_
356 opt_send_signal
= SIGTRAP
;
360 opt_send_signal
= SIGUSR2
;
364 else if (!strncmp(optarg
, "shutdown", strlen(optarg
)))
365 opt_send_signal
= SIGTERM
;
366 else if (!strncmp(optarg
, "interrupt", strlen(optarg
)))
367 opt_send_signal
= SIGINT
;
368 else if (!strncmp(optarg
, "kill", strlen(optarg
)))
369 opt_send_signal
= SIGKILL
;
373 else if (!strncmp(optarg
, "restart", strlen(optarg
)))
374 opt_send_signal
= SIGTTIN
; /* exit and restart by parent */
378 else if (!strncmp(optarg
, "check", strlen(optarg
)))
379 opt_send_signal
= 0; /* SIGNULL */
380 else if (!strncmp(optarg
, "parse", strlen(optarg
)))
381 opt_parse_cfg_only
= 1; /* parse cfg file only */
390 malloc_debug_level
= atoi(optarg
);
393 fatal("Need to add -DMALLOC_DBG when compiling to use -mX option");
398 xmalloc_trace
= !xmalloc_trace
;
401 fatal("Need to configure --enable-xmalloc-debug-trace to use -m option");
409 #if USE_WIN32_SERVICE
412 xfree(WIN32_Service_name
);
414 WIN32_Service_name
= xstrdup(optarg
);
416 opt_signal_service
= TRUE
;
421 opt_remove_service
= TRUE
;
428 opt_syslog_facility
= xstrdup(optarg
);
433 _db_set_syslog(opt_syslog_facility
);
439 fatal("Logging to syslog not available on this platform");
445 icpPortNumOverride
= atoi(optarg
);
447 if (icpPortNumOverride
< 0)
448 icpPortNumOverride
= 0;
453 printf("Squid Cache: Version %s\nconfigure options: %s\n", version_string
, SQUID_CONFIGURE_OPTIONS
);
455 #if USE_WIN32_SERVICE
457 printf("Compiled as Windows System Service.\n");
466 opt_debug_stderr
= 1;
468 opt_create_swap_dirs
= 1;
488 #ifndef _SQUID_MSWIN_
491 signal(sig
, rotate_logs
);
501 #ifndef _SQUID_MSWIN_
504 signal(sig
, reconfigure
);
512 do_shutdown
= sig
== SIGINT
? -1 : 1;
519 #ifndef _SQUID_MSWIN_
520 #ifdef KILL_PARENT_OPT
523 debugs(1, 1, "Killing RunCache, pid " << getppid());
525 if (kill(getppid(), sig
) < 0)
526 debugs(1, 1, "kill " << getppid() << ": " << xstrerror());
530 #if SA_RESETHAND == 0
531 signal(SIGTERM
, SIG_DFL
);
533 signal(SIGINT
, SIG_DFL
);
540 serverConnectionsOpen(void)
542 clientOpenListenSockets();
543 icpConnectionsOpen();
550 snmpConnectionOpen();
554 wccpConnectionOpen();
559 wccp2ConnectionOpen();
575 serverConnectionsClose(void)
577 assert(shutting_down
|| reconfiguring
);
578 clientHttpConnectionsClose();
579 icpConnectionShutdown();
582 htcpSocketShutdown();
588 snmpConnectionShutdown();
592 wccpConnectionClose();
596 wccp2ConnectionClose();
603 mainReconfigure(void)
605 debug(1, 1) ("Reconfiguring Squid Cache (version %s)...\n", version_string
);
607 /* Already called serverConnectionsClose and ipcacheShutdownServers() */
608 serverConnectionsClose();
609 icpConnectionClose();
616 snmpConnectionClose();
627 authenticateShutdown();
628 externalAclShutdown();
629 storeDirCloseSwapLogs();
635 enter_suid(); /* root to read config file */
636 parseConfigFile(ConfigFile
, manager
);
638 _db_init(Config
.Log
.log
, Config
.debugOptions
);
639 ipcache_restart(); /* clear stuck entries */
640 authenticateUserCacheRestart(); /* clear stuck ACL entries */
641 fqdncache_restart(); /* sigh, fqdncache too */
643 errorInitialize(); /* reload error pages */
657 authenticateInit(&Config
.authConfiguration
);
668 serverConnectionsOpen();
670 if (theOutIcpConnection
>= 0) {
672 neighborsRegisterWithCacheManager(manager
);
675 storeDirOpenSwapLogs();
677 mimeInit(Config
.mimeTablePathname
);
679 if (Config
.onoff
.announce
) {
680 if (!eventFind(start_announce
, NULL
))
681 eventAdd("start_announce", start_announce
, NULL
, 3600.0, 1);
683 if (eventFind(start_announce
, NULL
))
684 eventDelete(start_announce
, NULL
);
687 writePidFile(); /* write PID file */
689 debug(1, 1) ("Ready to serve requests.\n");
704 authenticateShutdown();
705 externalAclShutdown();
706 _db_rotate_log(); /* cache.log */
707 storeDirWriteCleanLogs(1);
708 storeLogRotate(); /* store.log */
709 accessLogRotate(); /* access.log */
710 useragentRotateLog(); /* useragent.log */
711 refererRotateLog(); /* referer.log */
724 authenticateInit(&Config
.authConfiguration
);
729 setEffectiveUser(void)
731 leave_suid(); /* Run as non privilegied user */
737 if (geteuid() == 0) {
738 debug(0, 0) ("Squid is not safe to run as root! If you must\n");
739 debug(0, 0) ("start Squid as root, then you must configure\n");
740 debug(0, 0) ("it to run as a non-priveledged user with the\n");
741 debug(0, 0) ("'cache_effective_user' option in the config file.\n");
742 fatal("Don't run Squid as root, set 'cache_effective_user'!");
749 char pathbuf
[MAXPATHLEN
];
751 if (Config
.coredump_dir
) {
752 if (0 == strcmp("none", Config
.coredump_dir
)) {
754 } else if (chdir(Config
.coredump_dir
) == 0) {
755 debug(0, 1) ("Set Current Directory to %s\n", Config
.coredump_dir
);
758 debug(50, 0) ("chdir: %s: %s\n", Config
.coredump_dir
, xstrerror());
762 /* If we don't have coredump_dir or couldn't cd there, report current dir */
763 if (getcwd(pathbuf
, MAXPATHLEN
)) {
764 debug(0, 1) ("Current Directory is %s\n", pathbuf
);
766 debug(50, 0) ("WARNING: Can't find current directory, getcwd: %s\n", xstrerror());
771 #include "DelayPools.h"
777 /* chroot if configured to run inside chroot */
779 if (Config
.chroot_dir
&& chroot(Config
.chroot_dir
)) {
780 fatal("failed to chroot");
783 if (opt_catch_signals
) {
784 squid_signal(SIGSEGV
, death
, SA_NODEFER
| SA_RESETHAND
);
785 squid_signal(SIGBUS
, death
, SA_NODEFER
| SA_RESETHAND
);
788 squid_signal(SIGPIPE
, SIG_IGN
, SA_RESTART
);
789 squid_signal(SIGCHLD
, sig_child
, SA_NODEFER
| SA_RESTART
);
793 if (icpPortNumOverride
!= 1)
794 Config
.Port
.icp
= (u_short
) icpPortNumOverride
;
796 _db_init(Config
.Log
.log
, Config
.debugOptions
);
798 fd_open(fileno(debug_log
), FD_LOG
, Config
.Log
.log
);
802 log_trace_init("/tmp/squid.alloc");
806 debug(1, 0) ("Starting Squid Cache version %s for %s...\n",
812 if (WIN32_run_mode
== _WIN_SQUID_RUN_MODE_SERVICE
) {
813 debug(1, 0) ("Running as %s Windows System Service on %s\n", WIN32_Service_name
, WIN32_OS_string
);
814 debug(1, 0) ("Service command line is: %s\n", WIN32_Service_Command_Line
);
816 debug(1, 0) ("Running on %s\n",WIN32_OS_string
);
820 debugs(1, 1, "Process ID " << getpid());
822 debug(1, 1) ("With %d file descriptors available\n", Squid_MaxFD
);
826 debug(1, 1) ("With %d CRT stdio descriptors available\n", _getmaxstdio());
828 if (WIN32_Socks_initialized
)
829 debug(1, 1)("Windows sockets initialized\n");
833 if (!configured_once
)
834 disk_init(); /* disk_init must go before ipcache_init() */
854 authenticateInit(&Config
.authConfiguration
);
862 httpHeaderInitModule(); /* must go before any header processing (e.g. the one in errorInitialize) */
864 httpReplyInitModule(); /* must go before accepting replies */
882 malloc_debug(0, malloc_debug_level
);
886 if (!configured_once
) {
895 /* after this point we want to see the mallinfo() output */
897 mimeInit(Config
.mimeTablePathname
);
904 FwdState::initModule();
905 /* register the modules in the cache manager menus */
906 accessLogRegisterWithCacheManager(manager
);
907 asnRegisterWithCacheManager(manager
);
908 authenticateRegisterWithCacheManager(&Config
.authConfiguration
, manager
);
911 carpRegisterWithCacheManager(manager
);
914 cbdataRegisterWithCacheManager(manager
);
915 /* These use separate calls so that the comm loops can eventually
920 commEPollRegisterWithCacheManager(manager
);
924 commKQueueRegisterWithCacheManager(manager
);
928 commPollRegisterWithCacheManager(manager
);
932 commSelectRegisterWithCacheManager(manager
);
935 clientdbRegisterWithCacheManager(manager
);
938 DelayPools::RegisterWithCacheManager(manager
);
941 DiskIOModule::RegisterAllModulesWithCacheManager(manager
);
944 dnsRegisterWithCacheManager(manager
);
948 externalAclRegisterWithCacheManager(manager
);
949 fqdncacheRegisterWithCacheManager(manager
);
950 FwdState::RegisterWithCacheManager(manager
);
951 httpHeaderRegisterWithCacheManager(manager
);
954 idnsRegisterWithCacheManager(manager
);
957 ipcacheRegisterWithCacheManager(manager
);
958 Mem::RegisterWithCacheManager(manager
);
959 netdbRegisterWitHCacheManager(manager
);
960 PconnModule::GetInstance()->registerWithCacheManager(manager
);
961 redirectRegisterWithCacheManager(manager
);
962 refreshRegisterWithCacheManager(manager
);
963 statRegisterWithCacheManager(manager
);
964 storeDigestRegisterWithCacheManager(manager
);
965 StoreFileSystem::RegisterAllFsWithCacheManager(manager
);
966 storeRegisterWithCacheManager(manager
);
969 StringRegistry::Instance().registerWithCacheManager(manager
);
974 xprofRegisterWithCacheManager(manager
);
989 serverConnectionsOpen();
991 if (theOutIcpConnection
>= 0) {
993 neighborsRegisterWithCacheManager(manager
);
996 if (Config
.chroot_dir
)
999 if (!configured_once
)
1000 writePidFile(); /* write PID file */
1002 #ifdef _SQUID_LINUX_THREADS_
1004 squid_signal(SIGQUIT
, rotate_logs
, SA_RESTART
);
1006 squid_signal(SIGTRAP
, sigusr2_handle
, SA_RESTART
);
1010 squid_signal(SIGUSR1
, rotate_logs
, SA_RESTART
);
1012 squid_signal(SIGUSR2
, sigusr2_handle
, SA_RESTART
);
1016 squid_signal(SIGHUP
, reconfigure
, SA_RESTART
);
1018 squid_signal(SIGTERM
, shut_down
, SA_NODEFER
| SA_RESETHAND
| SA_RESTART
);
1020 squid_signal(SIGINT
, shut_down
, SA_NODEFER
| SA_RESETHAND
| SA_RESTART
);
1024 squid_signal(SIGTTIN
, shut_down
, SA_NODEFER
| SA_RESETHAND
| SA_RESTART
);
1030 debug(1, 1) ("Ready to serve requests.\n");
1032 if (!configured_once
) {
1033 eventAdd("storeMaintain", Store::Maintain
, NULL
, 1.0, 1);
1035 if (Config
.onoff
.announce
)
1036 eventAdd("start_announce", start_announce
, NULL
, 3600.0, 1);
1038 eventAdd("ipcache_purgelru", ipcache_purgelru
, NULL
, 10.0, 1);
1040 eventAdd("fqdncache_purgelru", fqdncache_purgelru
, NULL
, 15.0, 1);
1044 eventAdd("cpuProfiling", xprof_event
, NULL
, 1.0, 1);
1048 eventAdd("memPoolCleanIdlePools", Mem::CleanIdlePools
, NULL
, 15.0, 1);
1050 eventAdd("commCheckHalfClosed", commCheckHalfClosed
, NULL
, 1.0, false);
1053 configured_once
= 1;
1056 #if USE_WIN32_SERVICE
1057 /* When USE_WIN32_SERVICE is defined, the main function is placed in win32.cc */
1058 extern "C" void WINAPI
1059 SquidWinSvcMain(int argc
, char **argv
)
1061 SquidMain(argc
, argv
);
1065 SquidMain(int argc
, char **argv
)
1068 main(int argc
, char **argv
)
1072 #ifdef _SQUID_WIN32_
1079 sbrk_start
= sbrk(0);
1082 Debug::parseOptions("ALL,1");
1085 #if defined(SQUID_MAXFD_LIMIT)
1087 if (SQUID_MAXFD_LIMIT
< Squid_MaxFD
)
1088 Squid_MaxFD
= SQUID_MAXFD_LIMIT
;
1092 #ifdef _SQUID_WIN32_
1094 if ((WIN32_init_err
= WIN32_Subsystem_Init(&argc
, &argv
)))
1095 return WIN32_init_err
;
1099 /* call mallopt() before anything else */
1102 /* Round up all sizes to a multiple of this */
1103 mallopt(M_GRAIN
, 16);
1107 /* biggest size that is considered a small block */
1108 mallopt(M_MXFAST
, 256);
1112 /* allocate this many small blocks at once */
1113 mallopt(M_NLBLKS
, 32);
1116 #endif /* HAVE_MALLOPT */
1119 * The plan here is to set the umask to 007 (deny others for
1120 * read,write,execute), but only if the umask is not already
1121 * set. Unfortunately, there is no way to get the current
1122 * umask value without setting it.
1124 oldmask
= umask(S_IRWXO
);
1129 memset(&local_addr
, '\0', sizeof(struct IN_ADDR
));
1131 safe_inet_addr(localhost
, &local_addr
);
1133 memset(&any_addr
, '\0', sizeof(struct IN_ADDR
));
1135 safe_inet_addr("0.0.0.0", &any_addr
);
1137 memset(&no_addr
, '\0', sizeof(struct IN_ADDR
));
1139 safe_inet_addr("255.255.255.255", &no_addr
);
1141 squid_srandom(time(NULL
));
1145 squid_start
= current_time
;
1147 failure_notify
= fatal_dump
;
1149 #if USE_WIN32_SERVICE
1151 WIN32_svcstatusupdate(SERVICE_START_PENDING
, 10000);
1155 mainParseOptions(argc
, argv
);
1157 #if USE_WIN32_SERVICE
1159 if (opt_install_service
)
1161 WIN32_InstallService();
1165 if (opt_remove_service
)
1167 WIN32_RemoveService();
1171 if (opt_command_line
)
1173 WIN32_SetServiceCommandLine();
1179 /* parse configuration file
1180 * note: in "normal" case this used to be called from mainInitialize() */
1185 ConfigFile
= xstrdup(DefaultConfigFile
);
1187 assert(!configured_once
);
1191 storeFsInit(); /* required for config parsing */
1193 /* May not be needed for parsing, have not audited for such */
1194 DiskIOModule::SetupAllModules();
1196 /* Shouldn't be needed for config parsing, but have not audited for such */
1197 StoreFileSystem::SetupAllFs();
1199 /* we may want the parsing process to set this up in the future */
1200 Store::Root(new StoreController
);
1202 parse_err
= parseConfigFile(ConfigFile
, manager
);
1204 if (opt_parse_cfg_only
)
1208 if (-1 == opt_send_signal
)
1209 if (checkRunningPid())
1226 /* send signal to running copy and exit */
1227 if (opt_send_signal
!= -1)
1229 /* chroot if configured to run inside chroot */
1231 if (Config
.chroot_dir
) {
1232 if (chroot(Config
.chroot_dir
))
1233 fatal("failed to chroot");
1244 if (opt_create_swap_dirs
)
1246 /* chroot if configured to run inside chroot */
1248 if (Config
.chroot_dir
&& chroot(Config
.chroot_dir
)) {
1249 fatal("failed to chroot");
1253 debug(0, 0) ("Creating Swap Directories\n");
1254 Store::Root().create();
1264 /* init comm module */
1271 /* we have to init fdstat here. */
1272 fd_open(0, FD_LOG
, "stdin");
1273 fd_open(1, FD_LOG
, "stdout");
1274 fd_open(2, FD_LOG
, "stderr");
1277 #if USE_WIN32_SERVICE
1279 WIN32_svcstatusupdate(SERVICE_START_PENDING
, 10000);
1285 #if USE_WIN32_SERVICE
1287 WIN32_svcstatusupdate(SERVICE_RUNNING
, 0);
1294 SignalDispatcher
signal_dispatcher(mainLoop
);
1296 mainLoop
.registerDispatcher(&signal_dispatcher
);
1298 /* TODO: stop requiring the singleton here */
1299 mainLoop
.registerDispatcher(EventDispatcher::GetInstance());
1301 /* TODO: stop requiring the singleton here */
1302 mainLoop
.registerEngine(EventScheduler::GetInstance());
1304 StoreRootEngine store_engine
;
1306 mainLoop
.registerEngine(&store_engine
);
1308 CommDispatcher comm_dispatcher
;
1310 mainLoop
.registerDispatcher(&comm_dispatcher
);
1312 CommSelectEngine comm_engine
;
1314 mainLoop
.registerEngine(&comm_engine
);
1316 mainLoop
.setPrimaryEngine(&comm_engine
);
1318 /* use the standard time service */
1319 TimeEngine time_engine
;
1321 mainLoop
.setTimeService(&time_engine
);
1325 if (mainLoop
.errcount
== 10)
1326 fatal_dump("Event loop exited with failure.");
1328 /* shutdown squid now */
1341 if (strcmp(Config
.pidFilename
, "none") == 0) {
1342 debug(0, 1) ("No pid_filename specified. Trusting you know what you are doing.\n");
1345 pid
= readPidFile();
1348 #if USE_WIN32_SERVICE
1350 if (opt_signal_service
) {
1351 WIN32_sendSignal(opt_send_signal
);
1354 #ifdef _SQUID_MSWIN_
1356 fprintf(stderr
, "%s: ERROR: Could not send ", appname
);
1357 fprintf(stderr
, "signal to Squid Service:\n");
1358 fprintf(stderr
, "missing -n command line switch.\n");
1367 if (kill(pid
, opt_send_signal
) &&
1368 /* ignore permissions if just running check */
1369 !(opt_send_signal
== 0 && errno
== EPERM
)) {
1370 fprintf(stderr
, "%s: ERROR: Could not send ", appname
);
1371 fprintf(stderr
, "signal %d to process %d: %s\n",
1372 opt_send_signal
, (int) pid
, xstrerror());
1376 fprintf(stderr
, "%s: ERROR: No running copy\n", appname
);
1380 /* signal successfully sent */
1384 #ifndef _SQUID_MSWIN_
1386 * This function is run when Squid is in daemon mode, just
1387 * before the parent forks and starts up the child process.
1388 * It can be used for admin-specific tasks, such as notifying
1389 * someone that Squid is (re)started.
1392 mainStartScript(const char *prog
)
1394 char script
[SQUID_MAXPATHLEN
];
1399 xstrncpy(script
, prog
, MAXPATHLEN
);
1401 if ((t
= strrchr(script
, '/'))) {
1403 sl
= strlen(script
);
1406 xstrncpy(&script
[sl
], squid_start_script
, MAXPATHLEN
- sl
);
1408 if ((cpid
= fork()) == 0) {
1410 execl(script
, squid_start_script
, (char *)NULL
);
1416 rpid
= wait3(&status
, 0, NULL
);
1420 rpid
= waitpid(-1, &status
, 0);
1423 } while (rpid
!= cpid
);
1427 #endif /* _SQUID_MSWIN_ */
1430 checkRunningPid(void)
1437 pid
= readPidFile();
1442 if (kill(pid
, 0) < 0)
1445 debugs(0, 0, "Squid is already running! Process ID " << pid
);
1451 watch_child(char *argv
[])
1453 #ifndef _SQUID_MSWIN_
1474 if (*(argv
[0]) == '(')
1477 openlog(appname
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, LOG_LOCAL4
);
1479 if ((pid
= fork()) < 0)
1480 syslog(LOG_ALERT
, "fork failed: %s", xstrerror());
1485 syslog(LOG_ALERT
, "setsid failed: %s", xstrerror());
1491 if ((i
= open("/dev/tty", O_RDWR
| O_TEXT
)) >= 0) {
1492 ioctl(i
, TIOCNOTTY
, NULL
);
1499 * RBCOLLINS - if cygwin stackdumps when squid is run without
1500 * -N, check the cygwin1.dll version, it needs to be AT LEAST
1501 * 1.1.3. execvp had a bit overflow error in a loop..
1503 /* Connect stdio to /dev/null in daemon mode */
1504 nullfd
= open(_PATH_DEVNULL
, O_RDWR
| O_TEXT
);
1507 fatalf(_PATH_DEVNULL
" %s\n", xstrerror());
1511 if (opt_debug_stderr
< 0) {
1517 mainStartScript(argv
[0]);
1519 if ((pid
= fork()) == 0) {
1521 openlog(appname
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, LOG_LOCAL4
);
1522 prog
= xstrdup(argv
[0]);
1523 argv
[0] = xstrdup("(squid)");
1525 syslog(LOG_ALERT
, "execvp failed: %s", xstrerror());
1529 openlog(appname
, LOG_PID
| LOG_NDELAY
| LOG_CONS
, LOG_LOCAL4
);
1531 syslog(LOG_NOTICE
, "Squid Parent: child process %d started", pid
);
1535 squid_signal(SIGINT
, SIG_IGN
, SA_RESTART
);
1539 pid
= wait3(&status
, 0, NULL
);
1543 pid
= waitpid(-1, &status
, 0);
1549 if (WIFEXITED(status
)) {
1551 "Squid Parent: child process %d exited with status %d",
1552 pid
, WEXITSTATUS(status
));
1553 } else if (WIFSIGNALED(status
)) {
1555 "Squid Parent: child process %d exited due to signal %d",
1556 pid
, WTERMSIG(status
));
1558 syslog(LOG_NOTICE
, "Squid Parent: child process %d exited", pid
);
1561 if (stop
- start
< 10)
1566 if (failcount
== 5) {
1567 syslog(LOG_ALERT
, "Exiting due to repeated, frequent failures");
1571 if (WIFEXITED(status
))
1572 if (WEXITSTATUS(status
) == 0)
1575 if (WIFSIGNALED(status
)) {
1576 switch (WTERMSIG(status
)) {
1587 squid_signal(SIGINT
, SIG_DFL
, SA_RESTART
);
1592 #endif /* _SQUID_MSWIN_ */
1599 #if USE_WIN32_SERVICE
1600 WIN32_svcstatusupdate(SERVICE_STOP_PENDING
, 10000);
1603 debug(1, 1) ("Shutting down...\n");
1613 externalAclShutdown();
1614 icpConnectionClose();
1621 snmpConnectionClose();
1625 wccpConnectionClose();
1629 wccp2ConnectionClose();
1632 releaseServerSockets();
1633 commCloseAllSockets();
1636 DelayPools::FreePools();
1639 authenticateShutdown();
1644 #if USE_WIN32_SERVICE
1646 WIN32_svcstatusupdate(SERVICE_STOP_PENDING
, 10000);
1649 Store::Root().sync(); /* Flush pending object writes/unlinks */
1650 storeDirWriteCleanLogs(0);
1653 Store::Root().sync(); /* Flush log writes */
1656 useragentLogClose();
1663 Store::Root().sync(); /* Flush log close */
1664 StoreFileSystem::FreeAllFs();
1665 DiskIOModule::FreeAllModules();
1666 #if LEAK_CHECK_MODE && 0 /* doesn't work at the moment */
1670 /*stmemFreeMemory(); */
1672 ipcacheFreeMemory();
1673 fqdncacheFreeMemory();
1675 clientdbFreeMemory();
1676 httpHeaderCleanModule();
1684 if (opt_no_daemon
) {
1699 xmalloc_find_leaks();
1701 debug(1, 0) ("Memory used after shutdown: %d\n", xmalloc_total
);
1710 if (Config
.pidFilename
&& strcmp(Config
.pidFilename
, "none") != 0) {
1712 safeunlink(Config
.pidFilename
, 0);
1716 debug(1, 1) ("Squid Cache (Version %s): Exiting normally.\n",
1721 * We used to fclose(debug_log) here if it was set, but then
1722 * we forgot to set it to NULL. That caused some coredumps
1723 * because exit() ends up calling a bunch of destructors and
1724 * such. So rather than forcing the debug_log to close, we'll
1725 * leave it open so that those destructors can write some
1726 * debugging if necessary. The file will be closed anyway when
1727 * the process truly exits.
1730 exit(shutdown_status
);