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