]> git.ipfire.org Git - thirdparty/squid.git/blob - src/main.cc
Migrated RegisteredRunners to a multi-action interface.
[thirdparty/squid.git] / src / main.cc
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
158 static int opt_install_service = FALSE;
159 static int opt_remove_service = FALSE;
160 static int opt_command_line = FALSE;
161 void WIN32_svcstatusupdate(DWORD, DWORD);
162 void WINAPI WIN32_svcHandler(DWORD);
163 #endif
164
165 static int opt_signal_service = FALSE;
166 static char *opt_syslog_facility = NULL;
167 static int icpPortNumOverride = 1; /* Want to detect "-u 0" */
168 static int configured_once = 0;
169 #if MALLOC_DBG
170 static int malloc_debug_level = 0;
171 #endif
172 static volatile int do_reconfigure = 0;
173 static volatile int do_rotate = 0;
174 static volatile int do_shutdown = 0;
175 static volatile int shutdown_status = 0;
176
177 static int RotateSignal = -1;
178 static int ReconfigureSignal = -1;
179 static int ShutdownSignal = -1;
180
181 static void mainRotate(void);
182 static void mainReconfigureStart(void);
183 static void mainReconfigureFinish(void*);
184 static void mainInitialize(void);
185 static void usage(void);
186 static void mainParseOptions(int argc, char *argv[]);
187 static void sendSignal(void);
188 static void serverConnectionsOpen(void);
189 static void serverConnectionsClose(void);
190 static void watch_child(char **);
191 static void setEffectiveUser(void);
192 #if MEM_GEN_TRACE
193 void log_trace_done();
194 void log_trace_init(char *);
195 #endif
196 static void SquidShutdown(void);
197 static void mainSetCwd(void);
198 static int checkRunningPid(void);
199
200 #if !_SQUID_WINDOWS_
201 static 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
210 class StoreRootEngine : public AsyncEngine
211 {
212
213 public:
214 int checkEvents(int timeout) {
215 Store::Root().callback();
216 return EVENT_IDLE;
217 };
218 };
219
220 class SignalEngine: public AsyncEngine
221 {
222
223 public:
224 virtual int checkEvents(int timeout);
225
226 private:
227 static void StopEventLoop(void *) {
228 if (EventLoop::Running)
229 EventLoop::Running->stop();
230 }
231
232 void doShutdown(time_t wait);
233 };
234
235 int
236 SignalEngine::checkEvents(int timeout)
237 {
238 PROF_start(SignalEngine_checkEvents);
239
240 if (do_reconfigure) {
241 mainReconfigureStart();
242 do_reconfigure = 0;
243 } else if (do_rotate) {
244 mainRotate();
245 do_rotate = 0;
246 } else if (do_shutdown) {
247 doShutdown(do_shutdown > 0 ? (int) Config.shutdownLifetime : 0);
248 do_shutdown = 0;
249 }
250 BroadcastSignalIfAny(DebugSignal);
251 BroadcastSignalIfAny(RotateSignal);
252 BroadcastSignalIfAny(ReconfigureSignal);
253 BroadcastSignalIfAny(ShutdownSignal);
254
255 PROF_stop(SignalEngine_checkEvents);
256 return EVENT_IDLE;
257 }
258
259 void
260 SignalEngine::doShutdown(time_t wait)
261 {
262 debugs(1, DBG_IMPORTANT, "Preparing for shutdown after " << statCounter.client_http.requests << " requests");
263 debugs(1, DBG_IMPORTANT, "Waiting " << wait << " seconds for active connections to finish");
264
265 shutting_down = 1;
266
267 #if USE_WIN32_SERVICE
268 WIN32_svcstatusupdate(SERVICE_STOP_PENDING, (wait + 1) * 1000);
269 #endif
270
271 /* run the closure code which can be shared with reconfigure */
272 serverConnectionsClose();
273 #if USE_AUTH
274 /* detach the auth components (only do this on full shutdown) */
275 Auth::Scheme::FreeAll();
276 #endif
277
278 RunRegisteredHere(RegisteredRunner::startShutdown);
279 eventAdd("SquidShutdown", &StopEventLoop, this, (double) (wait + 1), 1, false);
280 }
281
282 static void
283 usage(void)
284 {
285 fprintf(stderr,
286 "Usage: %s [-cdhvzCFNRVYX] [-n name] [-s | -l facility] [-f config-file] [-[au] port] [-k signal]"
287 #if USE_WIN32_SERVICE
288 "[-ir] [-O CommandLine]"
289 #endif
290 "\n"
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 " -n name Specify service name to use for service operations\n"
303 " default is: " APP_SHORTNAME ".\n"
304 #if USE_WIN32_SERVICE
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 */
334 static void
335 mainParseOptions(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::n: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 case 'n':
514 /** \par n
515 * Set global option opt_signal_service (to true).
516 * Stores the additional parameter given in global service_name */
517 // XXX: verify that the new name has ONLY alphanumeric characters
518 xfree(service_name);
519 service_name = xstrdup(optarg);
520 opt_signal_service = true;
521 break;
522
523 #if USE_WIN32_SERVICE
524
525 case 'r':
526 /** \par r
527 * Set global option opt_remove_service (to TRUE) */
528 opt_remove_service = TRUE;
529
530 break;
531
532 #endif
533
534 case 'l':
535 /** \par l
536 * Stores the syslog facility name in global opt_syslog_facility
537 * then performs actions for -s option. */
538 xfree(opt_syslog_facility); // ignore any previous options sent
539 opt_syslog_facility = xstrdup(optarg);
540
541 case 's':
542 /** \par s
543 * Initialize the syslog for output */
544 #if HAVE_SYSLOG
545
546 _db_set_syslog(opt_syslog_facility);
547
548 break;
549
550 #else
551
552 fatal("Logging to syslog not available on this platform");
553
554 /* NOTREACHED */
555 #endif
556
557 case 'u':
558 /** \par u
559 * Store the ICP port number given in global option icpPortNumOverride
560 * ensuring its a positive number. */
561 icpPortNumOverride = atoi(optarg);
562
563 if (icpPortNumOverride < 0)
564 icpPortNumOverride = 0;
565
566 break;
567
568 case 'v':
569 /** \par v
570 * Display squid version and build information. Then exit. */
571 printf("Squid Cache: Version %s\n" ,version_string);
572 printf("Service Name: %s\n", service_name);
573 if (strlen(SQUID_BUILD_INFO))
574 printf("%s\n",SQUID_BUILD_INFO);
575 printf( "configure options: %s\n", SQUID_CONFIGURE_OPTIONS);
576
577 #if USE_WIN32_SERVICE
578
579 printf("Compiled as Windows System Service.\n");
580
581 #endif
582
583 exit(0);
584
585 /* NOTREACHED */
586
587 case 'z':
588 /** \par z
589 * Set global option Debug::log_stderr and opt_create_swap_dirs */
590 Debug::log_stderr = 1;
591 opt_create_swap_dirs = 1;
592 break;
593
594 case 'h':
595
596 case '?':
597
598 default:
599 /** \par h,?, or unknown
600 * \copydoc usage() */
601 usage();
602
603 break;
604 }
605
606 }
607 }
608
609 /* ARGSUSED */
610 void
611 rotate_logs(int sig)
612 {
613 do_rotate = 1;
614 RotateSignal = sig;
615 #if !_SQUID_WINDOWS_
616 #if !HAVE_SIGACTION
617
618 signal(sig, rotate_logs);
619 #endif
620 #endif
621 }
622
623 /* ARGSUSED */
624 void
625 reconfigure(int sig)
626 {
627 do_reconfigure = 1;
628 ReconfigureSignal = sig;
629 #if !_SQUID_WINDOWS_
630 #if !HAVE_SIGACTION
631
632 signal(sig, reconfigure);
633 #endif
634 #endif
635 }
636
637 void
638 shut_down(int sig)
639 {
640 do_shutdown = sig == SIGINT ? -1 : 1;
641 ShutdownSignal = sig;
642 #ifdef SIGTTIN
643
644 if (SIGTTIN == sig)
645 shutdown_status = 1;
646
647 #endif
648
649 const pid_t ppid = getppid();
650
651 if (!IamMasterProcess() && ppid > 1) {
652 // notify master that we are shutting down
653 if (kill(ppid, SIGUSR1) < 0)
654 debugs(1, DBG_IMPORTANT, "Failed to send SIGUSR1 to master process,"
655 " pid " << ppid << ": " << xstrerror());
656 }
657
658 #if !_SQUID_WINDOWS_
659 #if KILL_PARENT_OPT
660
661 if (!IamMasterProcess() && ppid > 1) {
662 debugs(1, DBG_IMPORTANT, "Killing master process, pid " << ppid);
663
664 if (kill(ppid, sig) < 0)
665 debugs(1, DBG_IMPORTANT, "kill " << ppid << ": " << xstrerror());
666 }
667
668 #endif /* KILL_PARENT_OPT */
669 #if SA_RESETHAND == 0
670 signal(SIGTERM, SIG_DFL);
671
672 signal(SIGINT, SIG_DFL);
673
674 #endif
675 #endif
676 }
677
678 static void
679 serverConnectionsOpen(void)
680 {
681 if (IamPrimaryProcess()) {
682 #if USE_WCCP
683 wccpConnectionOpen();
684 #endif
685
686 #if USE_WCCPv2
687
688 wccp2ConnectionOpen();
689 #endif
690 }
691 // start various proxying services if we are responsible for them
692 if (IamWorkerProcess()) {
693 clientOpenListenSockets();
694 icpOpenPorts();
695 #if USE_HTCP
696 htcpOpenPorts();
697 #endif
698 #if SQUID_SNMP
699 snmpOpenPorts();
700 #endif
701
702 icmpEngine.Open();
703 netdbInit();
704 asnInit();
705 ACL::Initialize();
706 peerSelectInit();
707
708 carpInit();
709 #if USE_AUTH
710 peerUserHashInit();
711 #endif
712 peerSourceHashInit();
713 }
714 }
715
716 static void
717 serverConnectionsClose(void)
718 {
719 assert(shutting_down || reconfiguring);
720
721 if (IamPrimaryProcess()) {
722 #if USE_WCCP
723
724 wccpConnectionClose();
725 #endif
726 #if USE_WCCPv2
727
728 wccp2ConnectionClose();
729 #endif
730 }
731 if (IamWorkerProcess()) {
732 clientHttpConnectionsClose();
733 icpConnectionShutdown();
734 #if USE_HTCP
735 htcpSocketShutdown();
736 #endif
737
738 icmpEngine.Close();
739 #if SQUID_SNMP
740 snmpClosePorts();
741 #endif
742
743 asnFreeMemory();
744 }
745 }
746
747 static void
748 mainReconfigureStart(void)
749 {
750 debugs(1, DBG_IMPORTANT, "Reconfiguring Squid Cache (version " << version_string << ")...");
751 reconfiguring = 1;
752
753 // Initiate asynchronous closing sequence
754 serverConnectionsClose();
755 icpClosePorts();
756 #if USE_HTCP
757 htcpClosePorts();
758 #endif
759 dnsShutdown();
760 #if USE_SSL_CRTD
761 Ssl::Helper::GetInstance()->Shutdown();
762 #endif
763 #if USE_SSL
764 if (Ssl::CertValidationHelper::GetInstance())
765 Ssl::CertValidationHelper::GetInstance()->Shutdown();
766 Ssl::TheGlobalContextStorage.reconfigureStart();
767 #endif
768 redirectShutdown();
769 #if USE_AUTH
770 authenticateReset();
771 #endif
772 externalAclShutdown();
773 storeDirCloseSwapLogs();
774 storeLogClose();
775 accessLogClose();
776 #if ICAP_CLIENT
777 icapLogClose();
778 #endif
779
780 eventAdd("mainReconfigureFinish", &mainReconfigureFinish, NULL, 0, 1,
781 false);
782 }
783
784 static void
785 mainReconfigureFinish(void *)
786 {
787 debugs(1, 3, "finishing reconfiguring");
788
789 errorClean();
790 enter_suid(); /* root to read config file */
791
792 // we may have disabled the need for PURGE
793 if (Config2.onoff.enable_purge)
794 Config2.onoff.enable_purge = 2;
795
796 // parse the config returns a count of errors encountered.
797 const int oldWorkers = Config.workers;
798 if ( parseConfigFile(ConfigFile) != 0) {
799 // for now any errors are a fatal condition...
800 self_destruct();
801 }
802 if (oldWorkers != Config.workers) {
803 debugs(1, DBG_CRITICAL, "WARNING: Changing 'workers' (from " <<
804 oldWorkers << " to " << Config.workers <<
805 ") requires a full restart. It has been ignored by reconfigure.");
806 Config.workers = oldWorkers;
807 }
808
809 RunRegisteredHere(RegisteredRunner::syncConfig);
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
900 static void
901 mainRotate(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
925 static void
926 setEffectiveUser(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
945 static bool
946 mainChangeDir(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.
957 static void
958 mainSetCwd(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
987 static void
988 mainInitialize(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 debugs(1, DBG_CRITICAL, "Service Name: " << service_name);
1018
1019 #if _SQUID_WINDOWS_
1020 if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) {
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 (!configured_once)
1063 Ssl::initialize_session_cache();
1064
1065 if (Ssl::CertValidationHelper::GetInstance())
1066 Ssl::CertValidationHelper::GetInstance()->Init();
1067 #endif
1068
1069 redirectInit();
1070 #if USE_AUTH
1071 authenticateInit(&Auth::TheConfig);
1072 #endif
1073 externalAclInit();
1074
1075 httpHeaderInitModule(); /* must go before any header processing (e.g. the one in errorInitialize) */
1076
1077 httpReplyInitModule(); /* must go before accepting replies */
1078
1079 errorInitialize();
1080
1081 accessLogInit();
1082
1083 #if ICAP_CLIENT
1084 icapLogOpen();
1085 #endif
1086
1087 #if USE_IDENT
1088 Ident::Init();
1089 #endif
1090
1091 #if SQUID_SNMP
1092
1093 snmpInit();
1094
1095 #endif
1096 #if MALLOC_DBG
1097
1098 malloc_debug(0, malloc_debug_level);
1099
1100 #endif
1101
1102 if (!configured_once) {
1103 if (unlinkdNeeded())
1104 unlinkdInit();
1105
1106 urlInitialize();
1107 statInit();
1108 storeInit();
1109 mainSetCwd();
1110 /* after this point we want to see the mallinfo() output */
1111 do_mallinfo = 1;
1112 mimeInit(Config.mimeTablePathname);
1113 refreshInit();
1114 #if USE_DELAY_POOLS
1115 DelayPools::Init();
1116 #endif
1117
1118 FwdState::initModule();
1119 /* register the modules in the cache manager menus */
1120
1121 cbdataRegisterWithCacheManager();
1122 /* These use separate calls so that the comm loops can eventually
1123 * coexist.
1124 */
1125
1126 eventInit();
1127
1128 // TODO: pconn is a good candidate for new-style registration
1129 // PconnModule::GetInstance()->registerWithCacheManager();
1130 // moved to PconnModule::PconnModule()
1131 }
1132
1133 if (IamPrimaryProcess()) {
1134 #if USE_WCCP
1135 wccpInit();
1136
1137 #endif
1138 #if USE_WCCPv2
1139
1140 wccp2Init();
1141
1142 #endif
1143 }
1144
1145 serverConnectionsOpen();
1146
1147 neighbors_init();
1148
1149 // neighborsRegisterWithCacheManager(); //moved to neighbors_init()
1150
1151 if (Config.chroot_dir)
1152 no_suid();
1153
1154 if (!configured_once)
1155 writePidFile(); /* write PID file */
1156
1157 #if defined(_SQUID_LINUX_THREADS_)
1158
1159 squid_signal(SIGQUIT, rotate_logs, SA_RESTART);
1160
1161 squid_signal(SIGTRAP, sigusr2_handle, SA_RESTART);
1162
1163 #else
1164
1165 squid_signal(SIGUSR1, rotate_logs, SA_RESTART);
1166
1167 squid_signal(SIGUSR2, sigusr2_handle, SA_RESTART);
1168
1169 #endif
1170
1171 squid_signal(SIGHUP, reconfigure, SA_RESTART);
1172
1173 squid_signal(SIGTERM, shut_down, SA_NODEFER | SA_RESETHAND | SA_RESTART);
1174
1175 squid_signal(SIGINT, shut_down, SA_NODEFER | SA_RESETHAND | SA_RESTART);
1176
1177 #ifdef SIGTTIN
1178
1179 squid_signal(SIGTTIN, shut_down, SA_NODEFER | SA_RESETHAND | SA_RESTART);
1180
1181 #endif
1182
1183 memCheckInit();
1184
1185 #if USE_LOADABLE_MODULES
1186 LoadableModulesConfigure(Config.loadable_module_names);
1187 #endif
1188
1189 #if USE_ADAPTATION
1190 bool enableAdaptation = false;
1191
1192 // We can remove this dependency on specific adaptation mechanisms
1193 // if we create a generic Registry of such mechanisms. Should we?
1194 #if ICAP_CLIENT
1195 Adaptation::Icap::TheConfig.finalize();
1196 enableAdaptation = Adaptation::Icap::TheConfig.onoff || enableAdaptation;
1197 #endif
1198 #if USE_ECAP
1199 Adaptation::Ecap::TheConfig.finalize(); // must be after we load modules
1200 enableAdaptation = Adaptation::Ecap::TheConfig.onoff || enableAdaptation;
1201 #endif
1202 // must be the last adaptation-related finalize
1203 Adaptation::Config::Finalize(enableAdaptation);
1204 #endif
1205
1206 #if USE_SQUID_ESI
1207 Esi::Init();
1208 #endif
1209
1210 #if USE_DELAY_POOLS
1211 Config.ClientDelay.finalize();
1212 #endif
1213
1214 if (!configured_once) {
1215 eventAdd("storeMaintain", Store::Maintain, NULL, 1.0, 1);
1216
1217 if (Config.onoff.announce)
1218 eventAdd("start_announce", start_announce, NULL, 3600.0, 1);
1219
1220 eventAdd("ipcache_purgelru", ipcache_purgelru, NULL, 10.0, 1);
1221
1222 eventAdd("fqdncache_purgelru", fqdncache_purgelru, NULL, 15.0, 1);
1223
1224 #if USE_XPROF_STATS
1225
1226 eventAdd("cpuProfiling", xprof_event, NULL, 1.0, 1);
1227
1228 #endif
1229
1230 eventAdd("memPoolCleanIdlePools", Mem::CleanIdlePools, NULL, 15.0, 1);
1231 }
1232
1233 configured_once = 1;
1234 }
1235
1236 /// unsafe main routine -- may throw
1237 int SquidMain(int argc, char **argv);
1238 /// unsafe main routine wrapper to catch exceptions
1239 static int SquidMainSafe(int argc, char **argv);
1240
1241 #if USE_WIN32_SERVICE
1242 /* When USE_WIN32_SERVICE is defined, the main function is placed in win32.cc */
1243 extern "C" void WINAPI
1244 SquidWinSvcMain(int argc, char **argv)
1245 {
1246 SquidMainSafe(argc, argv);
1247 }
1248 #else
1249 int
1250 main(int argc, char **argv)
1251 {
1252 return SquidMainSafe(argc, argv);
1253 }
1254 #endif
1255
1256 static int
1257 SquidMainSafe(int argc, char **argv)
1258 {
1259 try {
1260 return SquidMain(argc, argv);
1261 } catch (const std::exception &e) {
1262 debugs(1, DBG_CRITICAL, "FATAL: dying from an unhandled exception: " <<
1263 e.what());
1264 throw;
1265 } catch (...) {
1266 debugs(1, DBG_CRITICAL, "FATAL: dying from an unhandled exception.");
1267 throw;
1268 }
1269 return -1; // not reached
1270 }
1271
1272 /// computes name and ID for the current kid process
1273 static void
1274 ConfigureCurrentKid(const char *processName)
1275 {
1276 // kids are marked with parenthesis around their process names
1277 if (processName && processName[0] == '(') {
1278 if (const char *idStart = strrchr(processName, '-')) {
1279 KidIdentifier = atoi(idStart + 1);
1280 const size_t nameLen = idStart - (processName + 1);
1281 assert(nameLen < sizeof(TheKidName));
1282 xstrncpy(TheKidName, processName + 1, nameLen + 1);
1283 if (!strcmp(TheKidName, "squid-coord"))
1284 TheProcessKind = pkCoordinator;
1285 else if (!strcmp(TheKidName, "squid"))
1286 TheProcessKind = pkWorker;
1287 else if (!strcmp(TheKidName, "squid-disk"))
1288 TheProcessKind = pkDisker;
1289 else
1290 TheProcessKind = pkOther; // including coordinator
1291 }
1292 } else {
1293 xstrncpy(TheKidName, APP_SHORTNAME, sizeof(TheKidName));
1294 KidIdentifier = 0;
1295 }
1296 }
1297
1298 int
1299 SquidMain(int argc, char **argv)
1300 {
1301 ConfigureCurrentKid(argv[0]);
1302
1303 #if HAVE_SBRK
1304 sbrk_start = sbrk(0);
1305 #endif
1306
1307 Debug::parseOptions(NULL);
1308 debug_log = stderr;
1309
1310 #if defined(SQUID_MAXFD_LIMIT)
1311
1312 if (SQUID_MAXFD_LIMIT < Squid_MaxFD)
1313 Squid_MaxFD = SQUID_MAXFD_LIMIT;
1314
1315 #endif
1316
1317 /* NOP under non-windows */
1318 int WIN32_init_err=0;
1319 if ((WIN32_init_err = WIN32_Subsystem_Init(&argc, &argv)))
1320 return WIN32_init_err;
1321
1322 /* call mallopt() before anything else */
1323 #if HAVE_MALLOPT
1324 #ifdef M_GRAIN
1325 /* Round up all sizes to a multiple of this */
1326 mallopt(M_GRAIN, 16);
1327
1328 #endif
1329 #ifdef M_MXFAST
1330 /* biggest size that is considered a small block */
1331 mallopt(M_MXFAST, 256);
1332
1333 #endif
1334 #ifdef M_NBLKS
1335 /* allocate this many small blocks at once */
1336 mallopt(M_NLBLKS, 32);
1337
1338 #endif
1339 #endif /* HAVE_MALLOPT */
1340
1341 squid_srandom(time(NULL));
1342
1343 getCurrentTime();
1344
1345 squid_start = current_time;
1346
1347 failure_notify = fatal_dump;
1348
1349 #if USE_WIN32_SERVICE
1350
1351 WIN32_svcstatusupdate(SERVICE_START_PENDING, 10000);
1352
1353 #endif
1354
1355 mainParseOptions(argc, argv);
1356
1357 if (opt_parse_cfg_only) {
1358 Debug::parseOptions("ALL,1");
1359 }
1360
1361 #if USE_WIN32_SERVICE
1362
1363 if (opt_install_service) {
1364 WIN32_InstallService();
1365 return 0;
1366 }
1367
1368 if (opt_remove_service) {
1369 WIN32_RemoveService();
1370 return 0;
1371 }
1372
1373 if (opt_command_line) {
1374 WIN32_SetServiceCommandLine();
1375 return 0;
1376 }
1377
1378 #endif
1379
1380 /* parse configuration file
1381 * note: in "normal" case this used to be called from mainInitialize() */
1382 {
1383 int parse_err;
1384
1385 if (!ConfigFile)
1386 ConfigFile = xstrdup(DefaultConfigFile);
1387
1388 assert(!configured_once);
1389
1390 Mem::Init();
1391
1392 storeFsInit(); /* required for config parsing */
1393
1394 /* TODO: call the FS::Clean() in shutdown to do Fs cleanups */
1395 Fs::Init();
1396
1397 /* May not be needed for parsing, have not audited for such */
1398 DiskIOModule::SetupAllModules();
1399
1400 /* Shouldn't be needed for config parsing, but have not audited for such */
1401 StoreFileSystem::SetupAllFs();
1402
1403 /* we may want the parsing process to set this up in the future */
1404 Store::Root(new StoreController);
1405 Auth::Init(); /* required for config parsing. NOP if !USE_AUTH */
1406 Ip::ProbeTransport(); // determine IPv4 or IPv6 capabilities before parsing.
1407
1408 Format::Token::Init(); // XXX: temporary. Use a runners registry of pre-parse runners instead.
1409
1410 parse_err = parseConfigFile(ConfigFile);
1411
1412 Mem::Report();
1413
1414 if (opt_parse_cfg_only || parse_err > 0)
1415 return parse_err;
1416 }
1417 setUmask(Config.umask);
1418 if (-1 == opt_send_signal)
1419 if (checkRunningPid())
1420 exit(0);
1421
1422 #if TEST_ACCESS
1423
1424 comm_init();
1425
1426 mainInitialize();
1427
1428 test_access();
1429
1430 return 0;
1431
1432 #endif
1433
1434 /* send signal to running copy and exit */
1435 if (opt_send_signal != -1) {
1436 /* chroot if configured to run inside chroot */
1437 mainSetCwd();
1438 if (Config.chroot_dir) {
1439 no_suid();
1440 } else {
1441 leave_suid();
1442 }
1443
1444 sendSignal();
1445 /* NOTREACHED */
1446 }
1447
1448 debugs(1,2, HERE << "Doing post-config initialization\n");
1449 leave_suid();
1450 RunRegisteredHere(RegisteredRunner::finalizeConfig);
1451 RunRegisteredHere(RegisteredRunner::claimMemoryNeeds);
1452 RunRegisteredHere(RegisteredRunner::useConfig);
1453 enter_suid();
1454
1455 if (!opt_no_daemon && Config.workers > 0)
1456 watch_child(argv);
1457
1458 if (opt_create_swap_dirs) {
1459 /* chroot if configured to run inside chroot */
1460 mainSetCwd();
1461
1462 setEffectiveUser();
1463 debugs(0, DBG_CRITICAL, "Creating missing swap directories");
1464 Store::Root().create();
1465
1466 return 0;
1467 }
1468
1469 if (IamPrimaryProcess())
1470 CpuAffinityCheck();
1471 CpuAffinityInit();
1472
1473 setMaxFD();
1474
1475 /* init comm module */
1476 comm_init();
1477
1478 if (opt_no_daemon) {
1479 /* we have to init fdstat here. */
1480 fd_open(0, FD_LOG, "stdin");
1481 fd_open(1, FD_LOG, "stdout");
1482 fd_open(2, FD_LOG, "stderr");
1483 }
1484
1485 #if USE_WIN32_SERVICE
1486
1487 WIN32_svcstatusupdate(SERVICE_START_PENDING, 10000);
1488
1489 #endif
1490
1491 mainInitialize();
1492
1493 #if USE_WIN32_SERVICE
1494
1495 WIN32_svcstatusupdate(SERVICE_RUNNING, 0);
1496
1497 #endif
1498
1499 /* main loop */
1500 EventLoop mainLoop;
1501
1502 SignalEngine signalEngine;
1503
1504 mainLoop.registerEngine(&signalEngine);
1505
1506 /* TODO: stop requiring the singleton here */
1507 mainLoop.registerEngine(EventScheduler::GetInstance());
1508
1509 StoreRootEngine store_engine;
1510
1511 mainLoop.registerEngine(&store_engine);
1512
1513 CommSelectEngine comm_engine;
1514
1515 mainLoop.registerEngine(&comm_engine);
1516
1517 mainLoop.setPrimaryEngine(&comm_engine);
1518
1519 /* use the standard time service */
1520 TimeEngine time_engine;
1521
1522 mainLoop.setTimeService(&time_engine);
1523
1524 if (IamCoordinatorProcess())
1525 AsyncJob::Start(Ipc::Coordinator::Instance());
1526 else if (UsingSmp() && (IamWorkerProcess() || IamDiskProcess()))
1527 AsyncJob::Start(new Ipc::Strand);
1528
1529 /* at this point we are finished the synchronous startup. */
1530 starting_up = 0;
1531
1532 mainLoop.run();
1533
1534 if (mainLoop.errcount == 10)
1535 fatal_dump("Event loop exited with failure.");
1536
1537 /* shutdown squid now */
1538 SquidShutdown();
1539
1540 /* NOTREACHED */
1541 return 0;
1542 }
1543
1544 static void
1545 sendSignal(void)
1546 {
1547 pid_t pid;
1548 debug_log = stderr;
1549
1550 if (strcmp(Config.pidFilename, "none") == 0) {
1551 debugs(0, DBG_IMPORTANT, "No pid_filename specified. Trusting you know what you are doing.");
1552 }
1553
1554 pid = readPidFile();
1555
1556 if (pid > 1) {
1557 #if USE_WIN32_SERVICE
1558 if (opt_signal_service) {
1559 WIN32_sendSignal(opt_send_signal);
1560 exit(0);
1561 } else {
1562 fprintf(stderr, "%s: ERROR: Could not send ", APP_SHORTNAME);
1563 fprintf(stderr, "signal to Squid Service:\n");
1564 fprintf(stderr, "missing -n command line switch.\n");
1565 exit(1);
1566 }
1567 /* NOTREACHED */
1568 #endif
1569
1570 if (kill(pid, opt_send_signal) &&
1571 /* ignore permissions if just running check */
1572 !(opt_send_signal == 0 && errno == EPERM)) {
1573 fprintf(stderr, "%s: ERROR: Could not send ", APP_SHORTNAME);
1574 fprintf(stderr, "signal %d to process %d: %s\n",
1575 opt_send_signal, (int) pid, xstrerror());
1576 exit(1);
1577 }
1578 } else {
1579 if (opt_send_signal != SIGTERM) {
1580 fprintf(stderr, "%s: ERROR: No running copy\n", APP_SHORTNAME);
1581 exit(1);
1582 } else {
1583 fprintf(stderr, "%s: No running copy\n", APP_SHORTNAME);
1584 exit(0);
1585 }
1586 }
1587
1588 /* signal successfully sent */
1589 exit(0);
1590 }
1591
1592 #if !_SQUID_WINDOWS_
1593 /*
1594 * This function is run when Squid is in daemon mode, just
1595 * before the parent forks and starts up the child process.
1596 * It can be used for admin-specific tasks, such as notifying
1597 * someone that Squid is (re)started.
1598 */
1599 static void
1600 mainStartScript(const char *prog)
1601 {
1602 char script[MAXPATHLEN];
1603 char *t;
1604 size_t sl = 0;
1605 pid_t cpid;
1606 pid_t rpid;
1607 xstrncpy(script, prog, MAXPATHLEN);
1608
1609 if ((t = strrchr(script, '/'))) {
1610 *(++t) = '\0';
1611 sl = strlen(script);
1612 }
1613
1614 xstrncpy(&script[sl], squid_start_script, MAXPATHLEN - sl);
1615
1616 if ((cpid = fork()) == 0) {
1617 /* child */
1618 execl(script, squid_start_script, (char *)NULL);
1619 _exit(-1);
1620 } else {
1621 do {
1622 #if _SQUID_NEXT_
1623 union wait status;
1624 rpid = wait4(cpid, &status, 0, NULL);
1625 #else
1626
1627 int status;
1628 rpid = waitpid(cpid, &status, 0);
1629 #endif
1630
1631 } while (rpid != cpid);
1632 }
1633 }
1634
1635 #endif /* _SQUID_WINDOWS_ */
1636
1637 static int
1638 checkRunningPid(void)
1639 {
1640 // master process must start alone, but its kids processes may co-exist
1641 if (!IamMasterProcess())
1642 return 0;
1643
1644 pid_t pid;
1645
1646 if (!debug_log)
1647 debug_log = stderr;
1648
1649 pid = readPidFile();
1650
1651 if (pid < 2)
1652 return 0;
1653
1654 if (kill(pid, 0) < 0)
1655 return 0;
1656
1657 debugs(0, DBG_CRITICAL, "Squid is already running! Process ID " << pid);
1658
1659 return 1;
1660 }
1661
1662 static void
1663 watch_child(char *argv[])
1664 {
1665 #if !_SQUID_WINDOWS_
1666 char *prog;
1667 #if _SQUID_NEXT_
1668
1669 union wait status;
1670 #else
1671
1672 int status;
1673 #endif
1674
1675 pid_t pid;
1676 #ifdef TIOCNOTTY
1677
1678 int i;
1679 #endif
1680
1681 int nullfd;
1682
1683 if (!IamMasterProcess())
1684 return;
1685
1686 openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
1687
1688 if ((pid = fork()) < 0)
1689 syslog(LOG_ALERT, "fork failed: %s", xstrerror());
1690 else if (pid > 0)
1691 exit(0);
1692
1693 if (setsid() < 0)
1694 syslog(LOG_ALERT, "setsid failed: %s", xstrerror());
1695
1696 closelog();
1697
1698 #ifdef TIOCNOTTY
1699
1700 if ((i = open("/dev/tty", O_RDWR | O_TEXT)) >= 0) {
1701 ioctl(i, TIOCNOTTY, NULL);
1702 close(i);
1703 }
1704
1705 #endif
1706
1707 /*
1708 * RBCOLLINS - if cygwin stackdumps when squid is run without
1709 * -N, check the cygwin1.dll version, it needs to be AT LEAST
1710 * 1.1.3. execvp had a bit overflow error in a loop..
1711 */
1712 /* Connect stdio to /dev/null in daemon mode */
1713 nullfd = open(_PATH_DEVNULL, O_RDWR | O_TEXT);
1714
1715 if (nullfd < 0)
1716 fatalf(_PATH_DEVNULL " %s\n", xstrerror());
1717
1718 dup2(nullfd, 0);
1719
1720 if (Debug::log_stderr < 0) {
1721 dup2(nullfd, 1);
1722 dup2(nullfd, 2);
1723 }
1724
1725 // handle shutdown notifications from kids
1726 squid_signal(SIGUSR1, sig_shutdown, SA_RESTART);
1727
1728 if (Config.workers > 128) {
1729 syslog(LOG_ALERT, "Suspiciously high workers value: %d",
1730 Config.workers);
1731 // but we keep going in hope that user knows best
1732 }
1733 TheKids.init();
1734
1735 syslog(LOG_NOTICE, "Squid Parent: will start %d kids", (int)TheKids.count());
1736
1737 // keep [re]starting kids until it is time to quit
1738 for (;;) {
1739 mainStartScript(argv[0]);
1740
1741 // start each kid that needs to be [re]started; once
1742 for (int i = TheKids.count() - 1; i >= 0; --i) {
1743 Kid& kid = TheKids.get(i);
1744 if (!kid.shouldRestart())
1745 continue;
1746
1747 if ((pid = fork()) == 0) {
1748 /* child */
1749 openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
1750 prog = argv[0];
1751 argv[0] = const_cast<char*>(kid.name().termedBuf());
1752 execvp(prog, argv);
1753 syslog(LOG_ALERT, "execvp failed: %s", xstrerror());
1754 }
1755
1756 kid.start(pid);
1757 syslog(LOG_NOTICE, "Squid Parent: %s process %d started",
1758 kid.name().termedBuf(), pid);
1759 }
1760
1761 /* parent */
1762 openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
1763
1764 squid_signal(SIGINT, SIG_IGN, SA_RESTART);
1765
1766 #if _SQUID_NEXT_
1767
1768 pid = wait3(&status, 0, NULL);
1769
1770 #else
1771
1772 pid = waitpid(-1, &status, 0);
1773
1774 #endif
1775 // Loop to collect all stopped kids before we go to sleep below.
1776 do {
1777 Kid* kid = TheKids.find(pid);
1778 if (kid) {
1779 kid->stop(status);
1780 if (kid->calledExit()) {
1781 syslog(LOG_NOTICE,
1782 "Squid Parent: %s process %d exited with status %d",
1783 kid->name().termedBuf(),
1784 kid->getPid(), kid->exitStatus());
1785 } else if (kid->signaled()) {
1786 syslog(LOG_NOTICE,
1787 "Squid Parent: %s process %d exited due to signal %d with status %d",
1788 kid->name().termedBuf(),
1789 kid->getPid(), kid->termSignal(), kid->exitStatus());
1790 } else {
1791 syslog(LOG_NOTICE, "Squid Parent: %s process %d exited",
1792 kid->name().termedBuf(), kid->getPid());
1793 }
1794 if (kid->hopeless()) {
1795 syslog(LOG_NOTICE, "Squid Parent: %s process %d will not"
1796 " be restarted due to repeated, frequent failures",
1797 kid->name().termedBuf(), kid->getPid());
1798 }
1799 } else {
1800 syslog(LOG_NOTICE, "Squid Parent: unknown child process %d exited", pid);
1801 }
1802 #if _SQUID_NEXT_
1803 } while ((pid = wait3(&status, WNOHANG, NULL)) > 0);
1804 #else
1805 }
1806 while ((pid = waitpid(-1, &status, WNOHANG)) > 0);
1807 #endif
1808
1809 if (!TheKids.someRunning() && !TheKids.shouldRestartSome()) {
1810 leave_suid();
1811 // XXX: Master process has no main loop and, hence, should not call
1812 // RegisteredRunner::startShutdown which promises a loop iteration.
1813 RunRegisteredHere(RegisteredRunner::finishShutdown);
1814 enter_suid();
1815
1816 if (TheKids.someSignaled(SIGINT) || TheKids.someSignaled(SIGTERM)) {
1817 syslog(LOG_ALERT, "Exiting due to unexpected forced shutdown");
1818 exit(1);
1819 }
1820
1821 if (TheKids.allHopeless()) {
1822 syslog(LOG_ALERT, "Exiting due to repeated, frequent failures");
1823 exit(1);
1824 }
1825
1826 exit(0);
1827 }
1828
1829 squid_signal(SIGINT, SIG_DFL, SA_RESTART);
1830 sleep(3);
1831 }
1832
1833 /* NOTREACHED */
1834 #endif /* _SQUID_WINDOWS_ */
1835
1836 }
1837
1838 static void
1839 SquidShutdown()
1840 {
1841 /* XXX: This function is called after the main loop has quit, which
1842 * means that no AsyncCalls would be called, including close handlers.
1843 * TODO: We need to close/shut/free everything that needs calls before
1844 * exiting the loop.
1845 */
1846
1847 #if USE_WIN32_SERVICE
1848 WIN32_svcstatusupdate(SERVICE_STOP_PENDING, 10000);
1849 #endif
1850
1851 debugs(1, DBG_IMPORTANT, "Shutting down...");
1852 dnsShutdown();
1853 #if USE_SSL_CRTD
1854 Ssl::Helper::GetInstance()->Shutdown();
1855 #endif
1856 #if USE_SSL
1857 if (Ssl::CertValidationHelper::GetInstance())
1858 Ssl::CertValidationHelper::GetInstance()->Shutdown();
1859 #endif
1860 redirectShutdown();
1861 externalAclShutdown();
1862 icpClosePorts();
1863 #if USE_HTCP
1864 htcpClosePorts();
1865 #endif
1866 #if SQUID_SNMP
1867 snmpClosePorts();
1868 #endif
1869 #if USE_WCCP
1870
1871 wccpConnectionClose();
1872 #endif
1873 #if USE_WCCPv2
1874
1875 wccp2ConnectionClose();
1876 #endif
1877
1878 releaseServerSockets();
1879 commCloseAllSockets();
1880
1881 #if USE_SQUID_ESI
1882 Esi::Clean();
1883 #endif
1884
1885 #if USE_DELAY_POOLS
1886 DelayPools::FreePools();
1887 #endif
1888 #if USE_AUTH
1889 authenticateReset();
1890 #endif
1891 #if USE_WIN32_SERVICE
1892
1893 WIN32_svcstatusupdate(SERVICE_STOP_PENDING, 10000);
1894 #endif
1895
1896 Store::Root().sync(); /* Flush pending object writes/unlinks */
1897
1898 unlinkdClose(); /* after sync/flush. NOP if !USE_UNLINKD */
1899
1900 storeDirWriteCleanLogs(0);
1901 PrintRusage();
1902 dumpMallocStats();
1903 Store::Root().sync(); /* Flush log writes */
1904 storeLogClose();
1905 accessLogClose();
1906 Store::Root().sync(); /* Flush log close */
1907 StoreFileSystem::FreeAllFs();
1908 DiskIOModule::FreeAllModules();
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 RunRegisteredHere(RegisteredRunner::finishShutdown);
1944
1945 #if XMALLOC_TRACE
1946
1947 xmalloc_find_leaks();
1948
1949 debugs(1, DBG_CRITICAL, "Memory used after shutdown: " << xmalloc_total);
1950
1951 #endif
1952 #if MEM_GEN_TRACE
1953
1954 log_trace_done();
1955
1956 #endif
1957
1958 if (IamPrimaryProcess()) {
1959 if (Config.pidFilename && strcmp(Config.pidFilename, "none") != 0) {
1960 enter_suid();
1961 safeunlink(Config.pidFilename, 0);
1962 leave_suid();
1963 }
1964 }
1965
1966 debugs(1, DBG_IMPORTANT, "Squid Cache (Version " << version_string << "): Exiting normally.");
1967
1968 /*
1969 * DPW 2006-10-23
1970 * We used to fclose(debug_log) here if it was set, but then
1971 * we forgot to set it to NULL. That caused some coredumps
1972 * because exit() ends up calling a bunch of destructors and
1973 * such. So rather than forcing the debug_log to close, we'll
1974 * leave it open so that those destructors can write some
1975 * debugging if necessary. The file will be closed anyway when
1976 * the process truly exits.
1977 */
1978
1979 exit(shutdown_status);
1980 }
1981