main.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2021 The Squid Software Foundation and contributors
3  *
4  * Squid software is distributed under GPLv2+ license and includes
5  * contributions from numerous individuals and organizations.
6  * Please see the COPYING and CONTRIBUTORS files for details.
7  */
8 
9 /* DEBUG: section 01 Startup and Main Loop */
10 
11 #include "squid.h"
12 #include "AccessLogEntry.h"
13 //#include "acl/Acl.h"
14 #include "acl/Asn.h"
15 #include "acl/forward.h"
16 #include "anyp/UriScheme.h"
17 #include "auth/Config.h"
18 #include "auth/Gadgets.h"
19 #include "AuthReg.h"
20 #include "base/RunnersRegistry.h"
21 #include "base/Subscription.h"
22 #include "base/TextException.h"
23 #include "cache_cf.h"
24 #include "CachePeer.h"
25 #include "carp.h"
26 #include "client_db.h"
27 #include "client_side.h"
28 #include "comm.h"
29 #include "CommandLine.h"
30 #include "ConfigParser.h"
31 #include "CpuAffinity.h"
32 #include "DebugMessages.h"
33 #include "DiskIO/DiskIOModule.h"
34 #include "dns/forward.h"
35 #include "errorpage.h"
36 #include "event.h"
37 #include "EventLoop.h"
38 #include "ExternalACL.h"
39 #include "fd.h"
40 #include "format/Token.h"
41 #include "fqdncache.h"
42 #include "fs/Module.h"
43 #include "fs_io.h"
44 #include "FwdState.h"
45 #include "globals.h"
46 #include "htcp.h"
47 #include "http/Stream.h"
48 #include "HttpHeader.h"
49 #include "HttpReply.h"
50 #include "icmp/IcmpSquid.h"
51 #include "icmp/net_db.h"
52 #include "ICP.h"
53 #include "ident/Ident.h"
54 #include "Instance.h"
55 #include "ip/tools.h"
56 #include "ipc/Coordinator.h"
57 #include "ipc/Kids.h"
58 #include "ipc/Strand.h"
59 #include "ipcache.h"
60 #include "mime.h"
61 #include "neighbors.h"
62 #include "parser/Tokenizer.h"
63 #include "Parsing.h"
64 #include "pconn.h"
65 #include "peer_sourcehash.h"
66 #include "peer_userhash.h"
67 #include "PeerSelectState.h"
68 #include "protos.h"
69 #include "redirect.h"
70 #include "refresh.h"
71 #include "sbuf/Stream.h"
72 #include "SBufStatsAction.h"
73 #include "send-announce.h"
74 #include "SquidConfig.h"
75 #include "SquidTime.h"
76 #include "stat.h"
77 #include "StatCounters.h"
78 #include "Store.h"
79 #include "store/Disks.h"
80 #include "store_log.h"
81 #include "StoreFileSystem.h"
82 #include "tools.h"
83 #include "unlinkd.h"
84 #include "wccp.h"
85 #include "wccp2.h"
86 #include "WinSvc.h"
87 
88 #if USE_ADAPTATION
89 #include "adaptation/Config.h"
90 #endif
91 #if USE_ECAP
92 #include "adaptation/ecap/Config.h"
93 #endif
94 #if ICAP_CLIENT
95 #include "adaptation/icap/Config.h"
97 #endif
98 #if USE_DELAY_POOLS
99 #include "ClientDelayConfig.h"
100 #endif
101 #if USE_DELAY_POOLS
102 #include "DelayPools.h"
103 #endif
104 #if USE_LOADABLE_MODULES
105 #include "LoadableModules.h"
106 #endif
107 #if USE_OPENSSL
108 #include "ssl/context_storage.h"
109 #include "ssl/helper.h"
110 #endif
111 #if ICAP_CLIENT
112 #include "adaptation/icap/Config.h"
113 #endif
114 #if USE_ECAP
115 #include "adaptation/ecap/Config.h"
116 #endif
117 #if USE_ADAPTATION
118 #include "adaptation/Config.h"
119 #endif
120 #if USE_SQUID_ESI
121 #include "esi/Module.h"
122 #endif
123 #if SQUID_SNMP
124 #include "snmp_core.h"
125 #endif
126 
127 #include <cerrno>
128 #if HAVE_GETOPT_H
129 #include <getopt.h>
130 #endif
131 #if HAVE_PATHS_H
132 #include <paths.h>
133 #endif
134 #if HAVE_SYS_WAIT_H
135 #include <sys/wait.h>
136 #endif
137 
138 #if USE_WIN32_SERVICE
139 #include <process.h>
140 
143 static int opt_command_line = FALSE;
144 void WIN32_svcstatusupdate(DWORD, DWORD);
145 void WINAPI WIN32_svcHandler(DWORD);
146 #endif
147 
149 static char *opt_syslog_facility = NULL;
150 static int icpPortNumOverride = 1; /* Want to detect "-u 0" */
151 static int configured_once = 0;
152 #if MALLOC_DBG
153 static int malloc_debug_level = 0;
154 #endif
155 static volatile int do_reconfigure = 0;
156 static volatile int do_rotate = 0;
157 static volatile int do_shutdown = 0;
158 static volatile int do_revive_kids = 0;
159 static volatile int shutdown_status = EXIT_SUCCESS;
160 static volatile int do_handle_stopped_child = 0;
161 
162 static int RotateSignal = -1;
163 static int ReconfigureSignal = -1;
164 static int ShutdownSignal = -1;
165 static int ReviveKidsSignal = -1;
166 
167 static void mainRotate(void);
168 static void mainReconfigureStart(void);
169 static void mainReconfigureFinish(void*);
170 static void mainInitialize(void);
171 static void usage(void);
172 static void mainHandleCommandLineOption(const int optId, const char *optValue);
173 static void sendSignal(void);
174 static void serverConnectionsOpen(void);
175 static void serverConnectionsClose(void);
176 static void watch_child(const CommandLine &);
177 static void setEffectiveUser(void);
178 static void SquidShutdown(void);
179 static void mainSetCwd(void);
180 
181 #if !_SQUID_WINDOWS_
182 static const char *squid_start_script = "squid_start";
183 #endif
184 
185 #if TEST_ACCESS
186 #include "test_access.c"
187 #endif
188 
192 {
193 
194 public:
195  int checkEvents(int) {
196  Store::Root().callback();
197  return EVENT_IDLE;
198  };
199 };
200 
202 {
203 
204 public:
205 #if KILL_PARENT_OPT
206  SignalEngine(): parentKillNotified(false) {
207  parentPid = getppid();
208  }
209 #endif
210 
211  virtual int checkEvents(int timeout);
212 
213 private:
214  static void StopEventLoop(void *) {
215  if (EventLoop::Running)
217  }
218 
219  static void FinalShutdownRunners(void *) {
221 
222  // XXX: this should be a Runner.
223 #if USE_AUTH
224  /* detach the auth components (only do this on full shutdown) */
226 #endif
227 
228  eventAdd("SquidTerminate", &StopEventLoop, NULL, 0, 1, false);
229  }
230 
231  void doShutdown(time_t wait);
232  void handleStoppedChild();
233 
234 #if KILL_PARENT_OPT
235  bool parentKillNotified;
236  pid_t parentPid;
237 #endif
238 };
239 
240 int
242 {
243  if (do_reconfigure)
245  else if (do_rotate)
246  mainRotate();
247  else if (do_shutdown)
251  return EVENT_IDLE;
252 }
253 
256 static bool
257 AvoidSignalAction(const char *description, volatile int &signalVar)
258 {
259  const char *avoiding = "delaying";
260  const char *currentEvent = "none";
261  if (shutting_down) {
262  currentEvent = "shutdown";
263  avoiding = "canceling";
264  // do not avoid repeated shutdown signals
265  // which just means the user wants to skip/abort shutdown timeouts
266  if (strcmp(currentEvent, description) == 0)
267  return false;
268  signalVar = 0;
269  }
270  else if (!configured_once)
271  currentEvent = "startup";
272  else if (reconfiguring)
273  currentEvent = "reconfiguration";
274  else {
275  signalVar = 0;
276  return false; // do not avoid (i.e., execute immediately)
277  // the caller may produce a signal-specific debugging message
278  }
279 
280  debugs(1, DBG_IMPORTANT, avoiding << ' ' << description <<
281  " request during " << currentEvent);
282  return true;
283 }
284 
285 void
287 {
288  if (AvoidSignalAction("shutdown", do_shutdown))
289  return;
290 
291  debugs(1, Important(2), "Preparing for shutdown after " << statCounter.client_http.requests << " requests");
292  debugs(1, Important(3), "Waiting " << wait << " seconds for active connections to finish");
293 
294 #if KILL_PARENT_OPT
295  if (!IamMasterProcess() && !parentKillNotified && ShutdownSignal > 0 && parentPid > 1) {
296  debugs(1, DBG_IMPORTANT, "Killing master process, pid " << parentPid);
297  if (kill(parentPid, ShutdownSignal) < 0) {
298  int xerrno = errno;
299  debugs(1, DBG_IMPORTANT, "kill " << parentPid << ": " << xstrerr(xerrno));
300  }
301  parentKillNotified = true;
302  }
303 #endif
304 
305  if (shutting_down) {
306 #if !KILL_PARENT_OPT
307  // Already a shutdown signal has received and shutdown is in progress.
308  // Shutdown as soon as possible.
309  wait = 0;
310 #endif
311  } else {
312  shutting_down = 1;
313 
314  /* run the closure code which can be shared with reconfigure */
316 
318  }
319 
320 #if USE_WIN32_SERVICE
321  WIN32_svcstatusupdate(SERVICE_STOP_PENDING, (wait + 1) * 1000);
322 #endif
323 
324  eventAdd("SquidShutdown", &FinalShutdownRunners, this, (double) (wait + 1), 1, false);
325 }
326 
327 void
329 {
330  // no AvoidSignalAction() call: This code can run at any time because it
331  // does not depend on Squid state. It does not need debugging because it
332  // handles an "internal" signal, not an external/admin command.
334 #if !_SQUID_WINDOWS_
335  PidStatus status;
336  pid_t pid;
337 
338  do {
339  pid = WaitForAnyPid(status, WNOHANG);
340 
341 #if HAVE_SIGACTION
342 
343  } while (pid > 0);
344 
345 #else
346 
347  }
348  while (pid > 0 || (pid < 0 && errno == EINTR));
349 #endif
350 #endif
351 }
352 
353 static void
354 usage(void)
355 {
356  fprintf(stderr,
357  "Usage: %s [-cdzCFNRVYX] [-n name] [-s | -l facility] [-f config-file] [-[au] port] [-k signal]"
358 #if USE_WIN32_SERVICE
359  "[-ir] [-O CommandLine]"
360 #endif
361  "\n"
362  " -h | --help Print help message.\n"
363  " -v | --version Print version details.\n"
364  "\n"
365  " -a port Specify HTTP port number (default: %d).\n"
366  " -d level Write debugging to stderr also.\n"
367  " -f file Use given config-file instead of\n"
368  " %s\n"
369 #if USE_WIN32_SERVICE
370  " -i Installs as a Windows Service (see -n option).\n"
371 #endif
372  " -k reconfigure|rotate|shutdown|"
373 #ifdef SIGTTIN
374  "restart|"
375 #endif
376  "interrupt|kill|debug|check|parse\n"
377  " Parse configuration file, then send signal to \n"
378  " running copy (except -k parse) and exit.\n"
379  " -n name Specify service name to use for service operations\n"
380  " default is: " APP_SHORTNAME ".\n"
381 #if USE_WIN32_SERVICE
382  " -r Removes a Windows Service (see -n option).\n"
383 #endif
384  " -s | -l facility\n"
385  " Enable logging to syslog.\n"
386  " -u port Specify ICP port number (default: %d), disable with 0.\n"
387  " -z Create missing swap directories and then exit.\n"
388  " -C Do not catch fatal signals.\n"
389  " -D OBSOLETE. Scheduled for removal.\n"
390  " -F Don't serve any requests until store is rebuilt.\n"
391  " -N Master process runs in foreground and is a worker. No kids.\n"
392  " --foreground\n"
393  " Master process runs in foreground and creates worker kids.\n"
394  " --kid role-ID\n"
395  " Play a given SMP kid process role, with a given ID. Do not use\n"
396  " this option. It is meant for the master process use only.\n"
397 #if USE_WIN32_SERVICE
398  " -O options\n"
399  " Set Windows Service Command line options in Registry.\n"
400 #endif
401  " -R Do not set REUSEADDR on port.\n"
402  " -S Double-check swap during rebuild.\n"
403  " -X Force full debugging.\n"
404  " -Y Only return UDP_HIT or UDP_MISS_NOFETCH during fast reload.\n",
405  APP_SHORTNAME, CACHE_HTTP_PORT, DEFAULT_CONFIG_FILE, CACHE_ICP_PORT);
406  exit(EXIT_FAILURE);
407 }
408 
410 enum {
411  // The absolute values do not matter except that the following values should
412  // not be used: Values below 2 are for special getopt_long(3) use cases, and
413  // values in the [33,126] range are reserved for short options (-x).
415  optKid
416 };
417 
418 // short options
419 // TODO: consider prefixing with ':' for better logging
420 // (distinguish missing required argument cases)
421 static const char *shortOpStr =
422 #if USE_WIN32_SERVICE
423  "O:Vir"
424 #endif
425  "CDFNRSYXa:d:f:hk:m::n:sl:u:vz?";
426 
427 // long options
428 static struct option squidOptions[] = {
429  {"foreground", no_argument, 0, optForeground},
430  {"kid", required_argument, 0, optKid},
431  {"help", no_argument, 0, 'h'},
432  {"version", no_argument, 0, 'v'},
433  {0, 0, 0, 0}
434 };
435 
436 // handle a command line parameter
437 static void
438 mainHandleCommandLineOption(const int optId, const char *optValue)
439 {
440  switch (optId) {
441 
442  case 'C':
445  opt_catch_signals = 0;
446  break;
447 
448  case 'D':
451  debugs(1,DBG_CRITICAL, "WARNING: -D command-line option is obsolete.");
452  break;
453 
454  case 'F':
458  break;
459 
460  case 'N':
463  opt_no_daemon = 1;
464  break;
465 
466 #if USE_WIN32_SERVICE
467 
468  case 'O':
471  opt_command_line = 1;
472  WIN32_Command_Line = xstrdup(optValue);
473  break;
474 #endif
475 
476  case 'R':
479  opt_reuseaddr = 0;
480  break;
481 
482  case 'S':
486  break;
487 
488  case 'X':
491  Debug::parseOptions("rotate=0 ALL,9");
492  Debug::override_X = 1;
493  sigusr2_handle(SIGUSR2);
494  break;
495 
496  case 'Y':
500  break;
501 
502 #if USE_WIN32_SERVICE
503 
504  case 'i':
508  break;
509 #endif
510 
511  case 'a':
512  {
515  char *port = xstrdup(optValue);
516  // use a copy to avoid optValue modification
518  xfree(port);
519  break;
520  }
521 
522  case 'd':
525  Debug::log_stderr = xatoi(optValue);
526  break;
527 
528  case 'f':
531  xfree(ConfigFile);
532  ConfigFile = xstrdup(optValue);
533  break;
534 
535  case 'k':
540  if (!optValue || strlen(optValue) < 1)
541  usage();
542 
543  else if (!strncmp(optValue, "reconfigure", strlen(optValue)))
545  opt_send_signal = SIGHUP;
546  else if (!strncmp(optValue, "rotate", strlen(optValue)))
548 #if defined(_SQUID_LINUX_THREADS_)
549  opt_send_signal = SIGQUIT;
550 #else
551  opt_send_signal = SIGUSR1;
552 #endif
553 
554  else if (!strncmp(optValue, "debug", strlen(optValue)))
556 #if defined(_SQUID_LINUX_THREADS_)
557  opt_send_signal = SIGTRAP;
558 #else
559  opt_send_signal = SIGUSR2;
560 #endif
561 
562  else if (!strncmp(optValue, "shutdown", strlen(optValue)))
564  opt_send_signal = SIGTERM;
565  else if (!strncmp(optValue, "interrupt", strlen(optValue)))
567  opt_send_signal = SIGINT;
568  else if (!strncmp(optValue, "kill", strlen(optValue)))
570  opt_send_signal = SIGKILL;
571 
572 #ifdef SIGTTIN
573 
574  else if (!strncmp(optValue, "restart", strlen(optValue)))
576  opt_send_signal = SIGTTIN;
577 
578 #endif
579 
580  else if (!strncmp(optValue, "check", strlen(optValue)))
582  opt_send_signal = 0; /* SIGNULL */
583  else if (!strncmp(optValue, "parse", strlen(optValue)))
585  opt_parse_cfg_only = 1;
586  else
587  usage();
588 
589  break;
590 
591  case 'm':
595  if (optValue) {
596 #if MALLOC_DBG
597  malloc_debug_level = xatoi(optValue);
598 #else
599  fatal("Need to add -DMALLOC_DBG when compiling to use -mX option");
600 #endif
601 
602  }
603  break;
604 
605  case 'n':
609  if (optValue && *optValue != '\0') {
610  const SBuf t(optValue);
613  if (!tok.prefix(service_name, chr))
614  fatalf("Expected alphanumeric service name for the -n option but got: %s", optValue);
615  if (!tok.atEnd())
616  fatalf("Garbage after alphanumeric service name in the -n option value: %s", optValue);
617  if (service_name.length() > 32)
618  fatalf("Service name (-n option) must be limited to 32 characters but got %u", service_name.length());
619  opt_signal_service = true;
620  } else {
621  fatal("A service name is required for the -n option");
622  }
623  break;
624 
625 #if USE_WIN32_SERVICE
626 
627  case 'r':
631 
632  break;
633 
634 #endif
635 
636  case 'l':
640  xfree(opt_syslog_facility); // ignore any previous options sent
641  opt_syslog_facility = xstrdup(optValue);
643  break;
644 
645  case 's':
649  break;
650 
651  case 'u':
655  icpPortNumOverride = atoi(optValue);
656 
657  if (icpPortNumOverride < 0)
658  icpPortNumOverride = 0;
659 
660  break;
661 
662  case 'v':
665  printf("Squid Cache: Version %s\n",version_string);
666  printf("Service Name: " SQUIDSBUFPH "\n", SQUIDSBUFPRINT(service_name));
667  if (strlen(SQUID_BUILD_INFO))
668  printf("%s\n",SQUID_BUILD_INFO);
669 #if USE_OPENSSL
670  printf("\nThis binary uses %s. ", OpenSSL_version(OPENSSL_VERSION));
671  printf("For legal restrictions on distribution see https://www.openssl.org/source/license.html\n\n");
672 #endif
673  printf( "configure options: %s\n", SQUID_CONFIGURE_OPTIONS);
674 
675 #if USE_WIN32_SERVICE
676 
677  printf("Compiled as Windows System Service.\n");
678 
679 #endif
680 
681  exit(EXIT_SUCCESS);
682 
683  /* NOTREACHED */
684 
685  case 'z':
688  Debug::log_stderr = 1;
690  break;
691 
692  case optForeground:
695  opt_foreground = 1;
696  break;
697 
698  case optKid:
699  // already processed in ConfigureCurrentKid()
700  break;
701 
702  case 'h':
703 
704  case '?':
705 
706  default:
709  usage();
710 
711  break;
712  }
713 }
714 
715 /* ARGSUSED */
716 void
717 rotate_logs(int sig)
718 {
719  do_rotate = 1;
720  RotateSignal = sig;
721 #if !_SQUID_WINDOWS_
722 #if !HAVE_SIGACTION
723 
724  signal(sig, rotate_logs);
725 #endif
726 #endif
727 }
728 
729 /* ARGSUSED */
730 void
731 reconfigure(int sig)
732 {
733  do_reconfigure = 1;
734  ReconfigureSignal = sig;
735 #if !_SQUID_WINDOWS_
736 #if !HAVE_SIGACTION
737 
738  signal(sig, reconfigure);
739 #endif
740 #endif
741 }
742 
743 static void
745 {
746  ReviveKidsSignal = sig;
747  do_revive_kids = true;
748 
749 #if !_SQUID_WINDOWS_
750 #if !HAVE_SIGACTION
751  signal(sig, master_revive_kids);
752 #endif
753 #endif
754 }
755 
757 static void
759 {
760  do_shutdown = 1;
761  ShutdownSignal = sig;
762 
763 #if !_SQUID_WINDOWS_
764 #if !HAVE_SIGACTION
765  signal(sig, master_shutdown);
766 #endif
767 #endif
768 
769 }
770 
771 void
772 shut_down(int sig)
773 {
774  do_shutdown = sig == SIGINT ? -1 : 1;
775  ShutdownSignal = sig;
776 #if defined(SIGTTIN)
777  if (SIGTTIN == sig)
778  shutdown_status = EXIT_FAILURE;
779 #endif
780 
781 #if !defined(_SQUID_WINDOWS_) && !defined(HAVE_SIGACTION)
782  signal(sig, shut_down);
783 #endif
784 }
785 
786 void
787 sig_child(int sig)
788 {
790 
791 #if !defined(_SQUID_WINDOWS_) && !defined(HAVE_SIGACTION)
792  signal(sig, sig_child);
793 #else
794  (void)sig;
795 #endif
796 }
797 
798 static void
800 {
801  if (IamPrimaryProcess()) {
802 #if USE_WCCP
804 #endif
805 
806 #if USE_WCCPv2
807 
809 #endif
810  }
811  // start various proxying services if we are responsible for them
812  if (IamWorkerProcess()) {
814  icpOpenPorts();
815 #if USE_HTCP
816  htcpOpenPorts();
817 #endif
818 #if SQUID_SNMP
819  snmpOpenPorts();
820 #endif
821 
822  icmpEngine.Open();
823  netdbInit();
824  asnInit();
825  ACL::Initialize();
826  peerSelectInit();
827 
828  carpInit();
829 #if USE_AUTH
831 #endif
833  }
834 }
835 
836 static void
838 {
840 
841  if (IamPrimaryProcess()) {
842 #if USE_WCCP
843 
845 #endif
846 #if USE_WCCPv2
847 
849 #endif
850  }
851  if (IamWorkerProcess()) {
854 #if USE_HTCP
856 #endif
857 
858  icmpEngine.Close();
859 #if SQUID_SNMP
860  snmpClosePorts();
861 #endif
862 
863  asnFreeMemory();
864  }
865 }
866 
867 static void
869 {
870  if (AvoidSignalAction("reconfiguration", do_reconfigure))
871  return;
872 
873  debugs(1, DBG_IMPORTANT, "Reconfiguring Squid Cache (version " << version_string << ")...");
874  reconfiguring = 1;
875 
877 
878  // Initiate asynchronous closing sequence
880  icpClosePorts();
881 #if USE_HTCP
882  htcpClosePorts();
883 #endif
884 #if USE_OPENSSL
886 #endif
887 #if USE_AUTH
889 #endif
892  storeLogClose();
893  accessLogClose();
894 #if ICAP_CLIENT
895  icapLogClose();
896 #endif
898 
899  eventAdd("mainReconfigureFinish", &mainReconfigureFinish, NULL, 0, 1,
900  false);
901 }
902 
903 static void
905 {
906  debugs(1, 3, "finishing reconfiguring");
907 
908  errorClean();
909  enter_suid(); /* root to read config file */
910 
911  // we may have disabled the need for PURGE
914 
915  // parse the config returns a count of errors encountered.
916  const int oldWorkers = Config.workers;
917  try {
918  if (parseConfigFile(ConfigFile) != 0) {
919  // for now any errors are a fatal condition...
920  self_destruct();
921  }
922  } catch (...) {
923  // for now any errors are a fatal condition...
924  debugs(1, DBG_CRITICAL, "FATAL: Unhandled exception parsing config file. " <<
925  " Run squid -k parse and check for errors.");
926  self_destruct();
927  }
928 
929  if (oldWorkers != Config.workers) {
930  debugs(1, DBG_CRITICAL, "WARNING: Changing 'workers' (from " <<
931  oldWorkers << " to " << Config.workers <<
932  ") requires a full restart. It has been ignored by reconfigure.");
933  Config.workers = oldWorkers;
934  }
935 
937 
938  if (IamPrimaryProcess())
941 
943  Mem::Report();
946  ipcache_restart(); /* clear stuck entries */
947  fqdncache_restart(); /* sigh, fqdncache too */
948  parseEtcHosts();
949  errorInitialize(); /* reload error pages */
950  accessLogInit();
951 
952 #if USE_LOADABLE_MODULES
954 #endif
955 
956 #if USE_ADAPTATION
957  bool enableAdaptation = false;
958 #if ICAP_CLIENT
960  enableAdaptation = Adaptation::Icap::TheConfig.onoff || enableAdaptation;
961 #endif
962 #if USE_ECAP
963  Adaptation::Ecap::TheConfig.finalize(); // must be after we load modules
964  enableAdaptation = Adaptation::Ecap::TheConfig.onoff || enableAdaptation;
965 #endif
966  Adaptation::Config::Finalize(enableAdaptation);
967 #endif
968 
970 #if ICAP_CLIENT
971  icapLogOpen();
972 #endif
973  storeLogOpen();
974  Dns::Init();
975 #if USE_SSL_CRTD
977 #endif
978 #if USE_OPENSSL
980 #endif
981 
983 #if USE_AUTH
985 #endif
986  externalAclInit();
987 
988  if (IamPrimaryProcess()) {
989 #if USE_WCCP
990 
991  wccpInit();
992 #endif
993 #if USE_WCCPv2
994 
995  wccp2Init();
996 #endif
997  }
998 
1000 
1001  neighbors_init();
1002 
1004 
1006 
1007  if (unlinkdNeeded())
1008  unlinkdInit();
1009 
1010 #if USE_DELAY_POOLS
1012 #endif
1013 
1014  if (Config.onoff.announce) {
1015  if (!eventFind(start_announce, NULL))
1016  eventAdd("start_announce", start_announce, NULL, 3600.0, 1);
1017  } else {
1020  }
1021 
1022  reconfiguring = 0;
1023 }
1024 
1025 static void
1027 {
1028  if (AvoidSignalAction("log rotation", do_rotate))
1029  return;
1030 
1031  icmpEngine.Close();
1032  redirectShutdown();
1033 #if USE_AUTH
1035 #endif
1037 
1038  _db_rotate_log(); /* cache.log */
1040  storeLogRotate(); /* store.log */
1041  accessLogRotate(); /* access.log */
1043 #if ICAP_CLIENT
1044  icapLogRotate(); /*icap.log*/
1045 #endif
1046  icmpEngine.Open();
1047  redirectInit();
1048 #if USE_AUTH
1050 #endif
1051  externalAclInit();
1052 }
1053 
1054 static void
1056 {
1057  keepCapabilities();
1058  leave_suid(); /* Run as non privilegied user */
1059 #if _SQUID_OS2_
1060 
1061  return;
1062 #endif
1063 
1064  if (geteuid() == 0) {
1065  debugs(0, DBG_CRITICAL, "Squid is not safe to run as root! If you must");
1066  debugs(0, DBG_CRITICAL, "start Squid as root, then you must configure");
1067  debugs(0, DBG_CRITICAL, "it to run as a non-priveledged user with the");
1068  debugs(0, DBG_CRITICAL, "'cache_effective_user' option in the config file.");
1069  fatal("Don't run Squid as root, set 'cache_effective_user'!");
1070  }
1071 }
1072 
1074 static bool
1075 mainChangeDir(const char *dir)
1076 {
1077  if (chdir(dir) == 0)
1078  return true;
1079 
1080  int xerrno = errno;
1081  debugs(50, DBG_CRITICAL, "ERROR: cannot change current directory to " << dir <<
1082  ": " << xstrerr(xerrno));
1083  return false;
1084 }
1085 
1088 bool Chrooted = false;
1089 
1091 static void
1093 {
1094  if (Config.chroot_dir && !Chrooted) {
1095  Chrooted = true;
1096 
1097  if (chroot(Config.chroot_dir) != 0) {
1098  int xerrno = errno;
1099  fatalf("chroot to %s failed: %s", Config.chroot_dir, xstrerr(xerrno));
1100  }
1101 
1102  if (!mainChangeDir("/"))
1103  fatalf("chdir to / after chroot to %s failed", Config.chroot_dir);
1104  }
1105 
1106  if (Config.coredump_dir && strcmp("none", Config.coredump_dir) != 0) {
1108  debugs(0, Important(4), "Set Current Directory to " << Config.coredump_dir);
1109  return;
1110  }
1111  }
1112 
1113  /* If we don't have coredump_dir or couldn't cd there, report current dir */
1114  char pathbuf[MAXPATHLEN];
1115  if (getcwd(pathbuf, MAXPATHLEN)) {
1116  debugs(0, DBG_IMPORTANT, "Current Directory is " << pathbuf);
1117  } else {
1118  int xerrno = errno;
1119  debugs(50, DBG_CRITICAL, "WARNING: Can't find current directory, getcwd: " << xstrerr(xerrno));
1120  }
1121 }
1122 
1123 static void
1125 {
1126  if (opt_catch_signals) {
1129  }
1130 
1131  squid_signal(SIGPIPE, SIG_IGN, SA_RESTART);
1134 
1135  setEffectiveUser();
1136 
1137  if (icpPortNumOverride != 1)
1138  Config.Port.icp = (unsigned short) icpPortNumOverride;
1139 
1140  debugs(1, DBG_CRITICAL, "Starting Squid Cache version " << version_string << " for " << CONFIG_HOST_TYPE << "...");
1141  debugs(1, Critical(5), "Service Name: " << service_name);
1142 
1143 #if _SQUID_WINDOWS_
1144  if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) {
1145  debugs(1, DBG_CRITICAL, "Service command line is: " << WIN32_Service_Command_Line);
1146  } else
1147  debugs(1, DBG_CRITICAL, "Running on " << WIN32_OS_string);
1148 #endif
1149 
1150  debugs(1, Important(6), "Process ID " << getpid());
1151 
1152  debugs(1, Important(7), "Process Roles:" << ProcessRoles());
1153 
1154  setSystemLimits();
1155  debugs(1, Important(8), "With " << Squid_MaxFD << " file descriptors available");
1156 
1157 #if _SQUID_WINDOWS_
1158 
1159  debugs(1, DBG_IMPORTANT, "With " << _getmaxstdio() << " CRT stdio descriptors available");
1160 
1161  if (WIN32_Socks_initialized)
1162  debugs(1, DBG_IMPORTANT, "Windows sockets initialized");
1163 
1164  if (WIN32_OS_version > _WIN_OS_WINNT) {
1166  }
1167 
1168 #endif
1169 
1170  ipcache_init();
1171 
1172  fqdncache_init();
1173 
1174  parseEtcHosts();
1175 
1176  Dns::Init();
1177 
1178 #if USE_SSL_CRTD
1180 #endif
1181 
1182 #if USE_OPENSSL
1184 #endif
1185 
1186  redirectInit();
1187 #if USE_AUTH
1189 #endif
1190  externalAclInit();
1191 
1192  httpHeaderInitModule(); /* must go before any header processing (e.g. the one in errorInitialize) */
1193 
1194  errorInitialize();
1195 
1196  accessLogInit();
1197 
1199 
1200 #if ICAP_CLIENT
1201  icapLogOpen();
1202 #endif
1203 
1204 #if USE_IDENT
1205  Ident::Init();
1206 #endif
1207 
1208 #if SQUID_SNMP
1209 
1210  snmpInit();
1211 
1212 #endif
1213 #if MALLOC_DBG
1214 
1215  malloc_debug(0, malloc_debug_level);
1216 
1217 #endif
1218 
1219  if (unlinkdNeeded())
1220  unlinkdInit();
1221 
1222  urlInitialize();
1223  statInit();
1224  storeInit();
1225  mainSetCwd();
1227  refreshInit();
1228 #if USE_DELAY_POOLS
1229  DelayPools::Init();
1230 #endif
1231 
1233  /* register the modules in the cache manager menus */
1234 
1237 
1238  /* These use separate calls so that the comm loops can eventually
1239  * coexist.
1240  */
1241 
1242  eventInit();
1243 
1244  // TODO: pconn is a good candidate for new-style registration
1245  // PconnModule::GetInstance()->registerWithCacheManager();
1246  // moved to PconnModule::PconnModule()
1247 
1248  if (IamPrimaryProcess()) {
1249 #if USE_WCCP
1250  wccpInit();
1251 
1252 #endif
1253 #if USE_WCCPv2
1254 
1255  wccp2Init();
1256 
1257 #endif
1258  }
1259 
1261 
1262  neighbors_init();
1263 
1264  // neighborsRegisterWithCacheManager(); //moved to neighbors_init()
1265 
1266  if (Config.chroot_dir)
1267  no_suid();
1268 
1269 #if defined(_SQUID_LINUX_THREADS_)
1270 
1271  squid_signal(SIGQUIT, rotate_logs, SA_RESTART);
1272 
1274 
1275 #else
1276 
1277  squid_signal(SIGUSR1, rotate_logs, SA_RESTART);
1278 
1280 
1281 #endif
1282 
1283  squid_signal(SIGTERM, shut_down, SA_RESTART);
1284 
1285  squid_signal(SIGINT, shut_down, SA_RESTART);
1286 
1287 #ifdef SIGTTIN
1288 
1289  squid_signal(SIGTTIN, shut_down, SA_RESTART);
1290 
1291 #endif
1292 
1293  memCheckInit();
1294 
1295 #if USE_LOADABLE_MODULES
1297 #endif
1298 
1299 #if USE_ADAPTATION
1300  bool enableAdaptation = false;
1301 
1302  // We can remove this dependency on specific adaptation mechanisms
1303  // if we create a generic Registry of such mechanisms. Should we?
1304 #if ICAP_CLIENT
1306  enableAdaptation = Adaptation::Icap::TheConfig.onoff || enableAdaptation;
1307 #endif
1308 #if USE_ECAP
1309  Adaptation::Ecap::TheConfig.finalize(); // must be after we load modules
1310  enableAdaptation = Adaptation::Ecap::TheConfig.onoff || enableAdaptation;
1311 #endif
1312  // must be the last adaptation-related finalize
1313  Adaptation::Config::Finalize(enableAdaptation);
1314 #endif
1315 
1316 #if USE_SQUID_ESI
1317  Esi::Init();
1318 #endif
1319 
1320 #if USE_DELAY_POOLS
1322 #endif
1323 
1324  eventAdd("storeMaintain", Store::Maintain, nullptr, 1.0, 1);
1325 
1326  if (Config.onoff.announce)
1327  eventAdd("start_announce", start_announce, nullptr, 3600.0, 1);
1328 
1329  eventAdd("ipcache_purgelru", ipcache_purgelru, nullptr, 10.0, 1);
1330 
1331  eventAdd("fqdncache_purgelru", fqdncache_purgelru, nullptr, 15.0, 1);
1332 
1333  eventAdd("memPoolCleanIdlePools", Mem::CleanIdlePools, nullptr, 15.0, 1);
1334 
1335  configured_once = 1;
1336 }
1337 
1338 static void
1340 {
1341  // ignore recursive calls to avoid termination loops
1342  static bool terminating = false;
1343  if (terminating)
1344  return;
1345  terminating = true;
1346 
1347  debugs(1, DBG_CRITICAL, "FATAL: Dying from an exception handling failure; exception: " << CurrentException);
1348  abort();
1349 }
1350 
1352 int SquidMain(int argc, char **argv);
1354 static int SquidMainSafe(int argc, char **argv);
1355 
1356 #if USE_WIN32_SERVICE
1357 /* Entry point for Windows services */
1358 extern "C" void WINAPI
1359 SquidWinSvcMain(int argc, char **argv)
1360 {
1361  SquidMainSafe(argc, argv);
1362 }
1363 #endif
1364 
1365 int
1366 main(int argc, char **argv)
1367 {
1368 #if USE_WIN32_SERVICE
1369  SetErrorMode(SEM_NOGPFAULTERRORBOX);
1370  if ((argc == 2) && strstr(argv[1], _WIN_SQUID_SERVICE_OPTION))
1371  return WIN32_StartService(argc, argv);
1372  else {
1373  WIN32_run_mode = _WIN_SQUID_RUN_MODE_INTERACTIVE;
1374  opt_no_daemon = 1;
1375  }
1376 #endif
1377 
1378  return SquidMainSafe(argc, argv);
1379 }
1380 
1381 static int
1382 SquidMainSafe(int argc, char **argv)
1383 {
1384  (void)std::set_terminate(&OnTerminate);
1385  // XXX: This top-level catch works great for startup, but, during runtime,
1386  // it erases valuable stack info. TODO: Let stack-preserving OnTerminate()
1387  // handle FATAL runtime errors by splitting main code into protected
1388  // startup, unprotected runtime, and protected termination sections!
1389  try {
1390  return SquidMain(argc, argv);
1391  } catch (...) {
1392  debugs(1, DBG_CRITICAL, "FATAL: " << CurrentException);
1393  }
1394  return EXIT_FAILURE;
1395 }
1396 
1398 static void
1400 {
1401  const char *kidParams = nullptr;
1402  if (cmdLine.hasOption(optKid, &kidParams)) {
1403  SBuf processName(kidParams);
1404  SBuf kidId;
1405  Parser::Tokenizer tok(processName);
1406  tok.suffix(kidId, CharacterSet::DIGIT);
1407  KidIdentifier = xatoi(kidId.c_str());
1408  tok.skipSuffix(SBuf("-"));
1409  TheKidName = tok.remaining();
1410  if (TheKidName.cmp("squid-coord") == 0)
1412  else if (TheKidName.cmp("squid") == 0)
1414  else if (TheKidName.cmp("squid-disk") == 0)
1416  else
1417  TheProcessKind = pkOther; // including coordinator
1418  } else {
1420  KidIdentifier = 0;
1421  }
1422 }
1423 
1426 static void
1428 {
1429  if (opt_no_daemon) {
1430  fd_open(0, FD_LOG, "stdin");
1431  fd_open(1, FD_LOG, "stdout");
1432  fd_open(2, FD_LOG, "stderr");
1433  }
1434  // we should not create cache.log outside chroot environment, if any
1435  // XXX: With Config.chroot_dir set, SMP master process never calls db_init().
1436  if (!Config.chroot_dir || Chrooted)
1438 }
1439 
1440 static void
1442 {
1445 }
1446 
1447 static void
1449 {
1450  setMaxFD();
1451  fde::Init();
1452  const auto skipCwdAdjusting = IamMasterProcess() && InDaemonMode();
1453  if (skipCwdAdjusting) {
1455  RunConfigUsers();
1456  } else if (Config.chroot_dir) {
1457  RunConfigUsers();
1458  enter_suid();
1459  // TODO: don't we need to RunConfigUsers() in the configured
1460  // chroot environment?
1461  mainSetCwd();
1462  leave_suid();
1464  } else {
1466  RunConfigUsers();
1467  enter_suid();
1468  // TODO: since RunConfigUsers() may use a relative path, we
1469  // need to change the process root first
1470  mainSetCwd();
1471  leave_suid();
1472  }
1473 }
1474 
1475 int
1476 SquidMain(int argc, char **argv)
1477 {
1478  const CommandLine cmdLine(argc, argv, shortOpStr, squidOptions);
1479 
1480  ConfigureCurrentKid(cmdLine);
1481 
1483 
1484 #if defined(SQUID_MAXFD_LIMIT)
1485 
1488 
1489 #endif
1490 
1491  /* NOP under non-windows */
1492  int WIN32_init_err=0;
1493  if ((WIN32_init_err = WIN32_Subsystem_Init(&argc, &argv)))
1494  return WIN32_init_err;
1495 
1496  /* call mallopt() before anything else */
1497 #if HAVE_MALLOPT
1498 #ifdef M_GRAIN
1499  /* Round up all sizes to a multiple of this */
1500  mallopt(M_GRAIN, 16);
1501 
1502 #endif
1503 #ifdef M_MXFAST
1504  /* biggest size that is considered a small block */
1505  mallopt(M_MXFAST, 256);
1506 
1507 #endif
1508 #ifdef M_NBLKS
1509  /* allocate this many small blocks at once */
1510  mallopt(M_NLBLKS, 32);
1511 
1512 #endif
1513 #endif /* HAVE_MALLOPT */
1514 
1515  getCurrentTime();
1516 
1518 
1520 
1521 #if USE_WIN32_SERVICE
1522 
1523  WIN32_svcstatusupdate(SERVICE_START_PENDING, 10000);
1524 
1525 #endif
1526 
1528 
1529  if (opt_foreground && opt_no_daemon) {
1530  debugs(1, DBG_CRITICAL, "WARNING: --foreground command-line option has no effect with -N.");
1531  }
1532 
1533  if (opt_parse_cfg_only) {
1534  Debug::parseOptions("ALL,1");
1535  }
1536 
1537 #if USE_WIN32_SERVICE
1538 
1539  if (opt_install_service) {
1541  return 0;
1542  }
1543 
1544  if (opt_remove_service) {
1546  return 0;
1547  }
1548 
1549  if (opt_command_line) {
1551  return 0;
1552  }
1553 
1554 #endif
1555 
1556  /* parse configuration file
1557  * note: in "normal" case this used to be called from mainInitialize() */
1558  {
1559  int parse_err;
1560 
1561  if (!ConfigFile)
1562  ConfigFile = xstrdup(DEFAULT_CONFIG_FILE);
1563 
1565 
1566  Mem::Init();
1567 
1569 
1570  storeFsInit(); /* required for config parsing */
1571 
1572  /* TODO: call the FS::Clean() in shutdown to do Fs cleanups */
1573  Fs::Init();
1574 
1575  /* May not be needed for parsing, have not audited for such */
1577 
1578  /* Shouldn't be needed for config parsing, but have not audited for such */
1580 
1581  /* we may want the parsing process to set this up in the future */
1582  Store::Init();
1583  Acl::Init();
1584  Auth::Init(); /* required for config parsing. NOP if !USE_AUTH */
1585  Ip::ProbeTransport(); // determine IPv4 or IPv6 capabilities before parsing.
1586 
1587  Format::Token::Init(); // XXX: temporary. Use a runners registry of pre-parse runners instead.
1588 
1589  try {
1590  parse_err = parseConfigFile(ConfigFile);
1591  } catch (...) {
1592  // for now any errors are a fatal condition...
1593  debugs(1, DBG_CRITICAL, "FATAL: Unhandled exception parsing config file." <<
1594  (opt_parse_cfg_only ? " Run squid -k parse and check for errors." : ""));
1595  parse_err = 1;
1596  }
1597 
1598  Mem::Report();
1599 
1600  if (opt_parse_cfg_only || parse_err > 0)
1601  return parse_err;
1602  }
1604 
1605  // Master optimization: Where possible, avoid pointless daemon fork() and/or
1606  // pointless wait for the exclusive PID file lock. This optional/weak check
1607  // is not applicable to kids because they always co-exist with their master.
1608  if (opt_send_signal == -1 && IamMasterProcess())
1610 
1611  /* send signal to running copy and exit */
1612  if (opt_send_signal != -1) {
1613  /* chroot if configured to run inside chroot */
1614  mainSetCwd();
1615  if (Config.chroot_dir) {
1616  no_suid();
1617  } else {
1618  leave_suid();
1619  }
1620 
1621  sendSignal();
1622  return 0;
1623  }
1624 
1625  debugs(1,2, "Doing post-config initialization");
1626  leave_suid();
1628 
1629  if (IamMasterProcess()) {
1630  if (InDaemonMode()) {
1631  watch_child(cmdLine);
1632  // NOTREACHED
1633  } else {
1635  }
1636  }
1637 
1638  StartUsingConfig();
1639  enter_suid();
1640 
1641  if (opt_create_swap_dirs) {
1642  setEffectiveUser();
1643  debugs(0, DBG_CRITICAL, "Creating missing swap directories");
1644  Store::Root().create();
1645 
1646  return 0;
1647  }
1648 
1649  if (IamPrimaryProcess())
1650  CpuAffinityCheck();
1651  CpuAffinityInit();
1652 
1653  /* init comm module */
1654  comm_init();
1655 
1656 #if USE_WIN32_SERVICE
1657 
1658  WIN32_svcstatusupdate(SERVICE_START_PENDING, 10000);
1659 
1660 #endif
1661 
1662  mainInitialize();
1663 
1664 #if USE_WIN32_SERVICE
1665 
1666  WIN32_svcstatusupdate(SERVICE_RUNNING, 0);
1667 
1668 #endif
1669 
1670  /* main loop */
1671  EventLoop mainLoop;
1672 
1673  SignalEngine signalEngine;
1674 
1675  mainLoop.registerEngine(&signalEngine);
1676 
1677  /* TODO: stop requiring the singleton here */
1679 
1680  StoreRootEngine store_engine;
1681 
1682  mainLoop.registerEngine(&store_engine);
1683 
1684  CommSelectEngine comm_engine;
1685 
1686  mainLoop.registerEngine(&comm_engine);
1687 
1688  mainLoop.setPrimaryEngine(&comm_engine);
1689 
1690  /* use the standard time service */
1691  TimeEngine time_engine;
1692 
1693  mainLoop.setTimeService(&time_engine);
1694 
1695  if (IamCoordinatorProcess())
1697  else if (UsingSmp() && (IamWorkerProcess() || IamDiskProcess()))
1699 
1700  /* at this point we are finished the synchronous startup. */
1701  starting_up = 0;
1702 
1703  mainLoop.run();
1704 
1705  if (mainLoop.errcount == 10)
1706  fatal_dump("Event loop exited with failure.");
1707 
1708  /* shutdown squid now */
1709  SquidShutdown();
1710 
1711  /* NOTREACHED */
1712  return 0;
1713 }
1714 
1715 static void
1717 {
1719 
1720 #if USE_WIN32_SERVICE
1721  // WIN32_sendSignal() does not need the PID value to signal,
1722  // but we must exit if there is no valid PID (TODO: Why?).
1723  (void)Instance::Other();
1724  if (!opt_signal_service)
1725  throw TexcHere("missing -n command line switch");
1727 #else
1728  const auto pid = Instance::Other();
1729  if (kill(pid, opt_send_signal) &&
1730  /* ignore permissions if just running check */
1731  !(opt_send_signal == 0 && errno == EPERM)) {
1732  const auto savedErrno = errno;
1733  throw TexcHere(ToSBuf("failed to send signal ", opt_send_signal,
1734  " to Squid instance with PID ", pid, ": ", xstrerr(savedErrno)));
1735  }
1736 #endif
1737  /* signal successfully sent */
1738 }
1739 
1740 #if !_SQUID_WINDOWS_
1741 /*
1742  * This function is run when Squid is in daemon mode, just
1743  * before the parent forks and starts up the child process.
1744  * It can be used for admin-specific tasks, such as notifying
1745  * someone that Squid is (re)started.
1746  */
1747 static void
1748 mainStartScript(const char *prog)
1749 {
1750  char script[MAXPATHLEN];
1751  char *t;
1752  size_t sl = 0;
1753  pid_t cpid;
1754  pid_t rpid;
1755  xstrncpy(script, prog, MAXPATHLEN);
1756 
1757  if ((t = strrchr(script, '/'))) {
1758  *(++t) = '\0';
1759  sl = strlen(script);
1760  }
1761 
1762  xstrncpy(&script[sl], squid_start_script, MAXPATHLEN - sl);
1763 
1764  if ((cpid = fork()) == 0) {
1765  /* child */
1766  execl(script, squid_start_script, (char *)NULL);
1767  _exit(-1);
1768  } else {
1769  do {
1770  PidStatus status;
1771  rpid = WaitForOnePid(cpid, status, 0);
1772  } while (rpid != cpid);
1773  }
1774 }
1775 
1777 static void
1779 {
1780  if (AvoidSignalAction("shutdown", do_shutdown))
1781  return;
1782  debugs(1, 2, "received shutdown command");
1783  shutting_down = 1;
1784 }
1785 
1787 static void
1789 {
1790  if (AvoidSignalAction("reconfiguration", do_reconfigure))
1791  return;
1792  debugs(1, 2, "received reconfiguration command");
1793  reconfiguring = 1;
1795  // TODO: hot-reconfiguration of the number of kids, kids revival delay,
1796  // PID file location, etc.
1797 }
1798 
1800 static void
1802 {
1803  reconfiguring = 0;
1804 }
1805 
1807 static void
1809 {
1810  if (AvoidSignalAction("kids revival", do_revive_kids))
1811  return;
1812  debugs(1, 2, "woke up after ~" << Config.hopelessKidRevivalDelay << "s");
1813  // nothing to do here -- actual revival happens elsewhere in the main loop
1814  // the alarm was needed just to wake us up so that we do a loop iteration
1815 }
1816 
1817 static void
1819 {
1820  if (do_shutdown)
1822  if (do_reconfigure)
1824  if (do_revive_kids)
1825  masterReviveKids();
1826 
1827  // emulate multi-step reconfiguration assumed by AvoidSignalAction()
1828  if (reconfiguring)
1830 
1835  ReviveKidsSignal = -1; // alarms are not broadcasted
1836 }
1837 
1840 static void
1842 {
1843  const auto nextCheckDelay = TheKids.forgetOldFailures();
1844  assert(nextCheckDelay >= 0);
1845  (void)alarm(static_cast<unsigned int>(nextCheckDelay)); // resets or cancels
1846  if (nextCheckDelay)
1847  debugs(1, 2, "will recheck hopeless kids in " << nextCheckDelay << " seconds");
1848 }
1849 
1850 static inline bool
1852 {
1853  return (DebugSignal > 0 || RotateSignal > 0 || ReconfigureSignal > 0 ||
1854  ShutdownSignal > 0 || ReviveKidsSignal > 0);
1855 }
1856 
1858 static void
1860 {
1861  pid_t pid;
1862  if ((pid = fork()) < 0) {
1863  int xerrno = errno;
1864  throw TexcHere(ToSBuf("failed to fork(2) the master process: ", xstrerr(xerrno)));
1865  } else if (pid > 0) {
1866  // parent
1867  exit(EXIT_SUCCESS);
1868  }
1869  // child, running as a background daemon
1870  Must(setsid() > 0); // ought to succeed after fork()
1871 }
1872 
1873 static void
1875 {
1876  if (TheKids.someSignaled(SIGINT) || TheKids.someSignaled(SIGTERM)) {
1877  syslog(LOG_ALERT, "Exiting due to unexpected forced shutdown");
1878  exit(EXIT_FAILURE);
1879  }
1880 
1881  if (TheKids.allHopeless()) {
1882  syslog(LOG_ALERT, "Exiting due to repeated, frequent failures");
1883  exit(EXIT_FAILURE);
1884  }
1885 
1886  exit(EXIT_SUCCESS);
1887 }
1888 
1889 #endif /* !_SQUID_WINDOWS_ */
1890 
1891 static void
1892 watch_child(const CommandLine &masterCommand)
1893 {
1894 #if !_SQUID_WINDOWS_
1895  pid_t pid;
1896 #ifdef TIOCNOTTY
1897 
1898  int i;
1899 #endif
1900 
1901  int nullfd;
1902 
1903  // TODO: zero values are not supported because they result in
1904  // misconfigured SMP Squid instances running forever, endlessly
1905  // restarting each dying kid.
1907  throw TexcHere("hopeless_kid_revival_delay must be positive");
1908 
1909  enter_suid();
1910 
1911  openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
1912 
1913  if (!opt_foreground)
1914  GoIntoBackground();
1915 
1916  closelog();
1917 
1918 #ifdef TIOCNOTTY
1919 
1920  if ((i = open("/dev/tty", O_RDWR | O_TEXT)) >= 0) {
1921  ioctl(i, TIOCNOTTY, NULL);
1922  close(i);
1923  }
1924 
1925 #endif
1926 
1927  /*
1928  * RBCOLLINS - if cygwin stackdumps when squid is run without
1929  * -N, check the cygwin1.dll version, it needs to be AT LEAST
1930  * 1.1.3. execvp had a bit overflow error in a loop..
1931  */
1932  /* Connect stdio to /dev/null in daemon mode */
1933  nullfd = open(_PATH_DEVNULL, O_RDWR | O_TEXT);
1934 
1935  if (nullfd < 0) {
1936  int xerrno = errno;
1937  fatalf(_PATH_DEVNULL " %s\n", xstrerr(xerrno));
1938  }
1939 
1940  dup2(nullfd, 0);
1941 
1942  if (Debug::log_stderr < 0) {
1943  dup2(nullfd, 1);
1944  dup2(nullfd, 2);
1945  }
1946 
1947  leave_suid();
1949  StartUsingConfig();
1950  enter_suid();
1951 
1952 #if defined(_SQUID_LINUX_THREADS_)
1953  squid_signal(SIGQUIT, rotate_logs, 0);
1954  squid_signal(SIGTRAP, sigusr2_handle, 0);
1955 #else
1956  squid_signal(SIGUSR1, rotate_logs, 0);
1957  squid_signal(SIGUSR2, sigusr2_handle, 0);
1958 #endif
1959 
1960  squid_signal(SIGHUP, reconfigure, 0);
1961 
1962  squid_signal(SIGTERM, master_shutdown, 0);
1963  squid_signal(SIGALRM, master_revive_kids, 0);
1964  squid_signal(SIGINT, master_shutdown, 0);
1965 #ifdef SIGTTIN
1966  squid_signal(SIGTTIN, master_shutdown, 0);
1967 #endif
1968 
1969  if (Config.workers > 128) {
1970  syslog(LOG_ALERT, "Suspiciously high workers value: %d",
1971  Config.workers);
1972  // but we keep going in hope that user knows best
1973  }
1974  TheKids.init();
1975 
1976  configured_once = 1;
1977 
1978  syslog(LOG_NOTICE, "Squid Parent: will start %d kids", (int)TheKids.count());
1979 
1980  // keep [re]starting kids until it is time to quit
1981  for (;;) {
1982  bool mainStartScriptCalled = false;
1983  // start each kid that needs to be [re]started; once
1984  for (int i = TheKids.count() - 1; i >= 0 && !shutting_down; --i) {
1985  Kid& kid = TheKids.get(i);
1986  if (!kid.shouldRestart())
1987  continue;
1988 
1989  if (!mainStartScriptCalled) {
1990  mainStartScript(masterCommand.arg0());
1991  mainStartScriptCalled = true;
1992  }
1993 
1994  // These are only needed by the forked child below, but let's keep
1995  // them out of that "no man's land" between fork() and execvp().
1996  auto kidCommand = masterCommand;
1997  kidCommand.resetArg0(kid.processName().c_str());
1998  assert(!kidCommand.hasOption(optKid));
1999  kidCommand.pushFrontOption("--kid", kid.gist().c_str());
2000 
2001  if ((pid = fork()) == 0) {
2002  /* child */
2003  openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
2004  (void)execvp(masterCommand.arg0(), kidCommand.argv());
2005  int xerrno = errno;
2006  syslog(LOG_ALERT, "execvp failed: %s", xstrerr(xerrno));
2007  }
2008 
2009  kid.start(pid);
2010  syslog(LOG_NOTICE, "Squid Parent: %s process %d started",
2011  kid.processName().c_str(), pid);
2012  }
2013 
2014  /* parent */
2015  openlog(APP_SHORTNAME, LOG_PID | LOG_NDELAY | LOG_CONS, LOG_LOCAL4);
2016 
2017  // If Squid received a signal while checking for dying kids (below) or
2018  // starting new kids (above), then do a fast check for a new dying kid
2019  // (WaitForAnyPid with the WNOHANG option) and continue to forward
2020  // signals to kids. Otherwise, wait for a kid to die or for a signal
2021  // to abort the blocking WaitForAnyPid() call.
2022  // With the WNOHANG option, we could check whether WaitForAnyPid() was
2023  // aborted by a dying kid or a signal, but it is not required: The
2024  // next do/while loop will check again for any dying kids.
2025  int waitFlag = 0;
2026  if (masterSignaled())
2027  waitFlag = WNOHANG;
2028  PidStatus status;
2029  pid = WaitForAnyPid(status, waitFlag);
2030  getCurrentTime();
2031 
2032  // check for a stopped kid
2033  if (Kid *kid = pid > 0 ? TheKids.find(pid) : nullptr)
2034  kid->stop(status);
2035  else if (pid > 0)
2036  syslog(LOG_NOTICE, "Squid Parent: unknown child process %d exited", pid);
2037 
2040 
2042  leave_suid();
2043  // XXX: Master process has no main loop and, hence, should not call
2044  // RegisteredRunner::startShutdown which promises a loop iteration.
2046  enter_suid();
2047  masterExit();
2048  }
2049  }
2050 
2051  /* NOTREACHED */
2052 #endif /* _SQUID_WINDOWS_ */
2053 
2054 }
2055 
2056 static void
2058 {
2059  /* XXX: This function is called after the main loop has quit, which
2060  * means that no AsyncCalls would be called, including close handlers.
2061  * TODO: We need to close/shut/free everything that needs calls before
2062  * exiting the loop.
2063  */
2064 
2065 #if USE_WIN32_SERVICE
2066  WIN32_svcstatusupdate(SERVICE_STOP_PENDING, 10000);
2067 #endif
2068 
2069  debugs(1, Important(9), "Shutting down...");
2070 #if USE_SSL_CRTD
2072 #endif
2073 #if USE_OPENSSL
2075 #endif
2076  redirectShutdown();
2078  icpClosePorts();
2079 #if USE_HTCP
2080  htcpClosePorts();
2081 #endif
2082 #if SQUID_SNMP
2083  snmpClosePorts();
2084 #endif
2085 #if USE_WCCP
2086 
2088 #endif
2089 #if USE_WCCPv2
2090 
2092 #endif
2093 
2096 
2097 #if USE_SQUID_ESI
2098  Esi::Clean();
2099 #endif
2100 
2101 #if USE_DELAY_POOLS
2103 #endif
2104 #if USE_AUTH
2106 #endif
2107 #if USE_WIN32_SERVICE
2108 
2109  WIN32_svcstatusupdate(SERVICE_STOP_PENDING, 10000);
2110 #endif
2111 #if ICAP_CLIENT
2113 #endif
2114 
2115  Store::Root().sync(); /* Flush pending object writes/unlinks */
2116 
2117  unlinkdClose(); /* after sync/flush. NOP if !USE_UNLINKD */
2118 
2120  PrintRusage();
2121  dumpMallocStats();
2122  Store::Root().sync(); /* Flush log writes */
2123  storeLogClose();
2124  accessLogClose();
2125  Store::Root().sync(); /* Flush log close */
2128 #if LEAK_CHECK_MODE && 0 /* doesn't work at the moment */
2129 
2130  configFreeMemory();
2131  storeFreeMemory();
2132  /*stmemFreeMemory(); */
2133  netdbFreeMemory();
2136  asnFreeMemory();
2138  statFreeMemory();
2139  eventFreeMemory();
2140  mimeFreeMemory();
2141  errorClean();
2142 #endif
2144 
2145  fdDumpOpen();
2146 
2147  comm_exit();
2148 
2150 
2151  memClean();
2152 
2153  debugs(1, Important(10), "Squid Cache (Version " << version_string << "): Exiting normally.");
2154 
2155  /*
2156  * DPW 2006-10-23
2157  * We used to fclose(debug_log) here if it was set, but then
2158  * we forgot to set it to NULL. That caused some coredumps
2159  * because exit() ends up calling a bunch of destructors and
2160  * such. So rather than forcing the debug_log to close, we'll
2161  * leave it open so that those destructors can write some
2162  * debugging if necessary. The file will be closed anyway when
2163  * the process truly exits.
2164  */
2165 
2166  exit(shutdown_status);
2167 }
2168 
static int ReviveKidsSignal
Definition: main.cc:165
void clientdbFreeMemory(void)
Definition: client_db.cc:351
static char * debugOptions
Definition: Debug.h:75
void fatal(const char *message)
Definition: fatal.cc:28
void comm_exit(void)
Definition: comm.cc:1160
const char * xstrerr(int error)
Definition: xstrerror.cc:83
static char * cache_log
Definition: Debug.h:76
void icapLogOpen()
Definition: icap_log.cc:23
int eventFind(EVH *func, void *arg)
Definition: event.cc:154
static void FreeAllModules()
struct timeval squid_start
void accessLogClose(void)
Definition: access_log.cc:203
void Maintain(void *unused)
Definition: store.cc:1147
void accessLogInit(void)
Definition: access_log.cc:365
static int configured_once
Definition: main.cc:151
void dumpMallocStats(void)
Definition: tools.cc:158
static void mainInitialize(void)
Definition: main.cc:1124
void externalAclShutdown(void)
int opt_send_signal
SBuf & assign(const SBuf &S)
Definition: SBuf.cc:83
void(* failure_notify)(const char *)
Definition: compat.cc:12
void setTimeService(TimeEngine *engine)
Definition: EventLoop.cc:162
virtual void Close()
Shutdown pinger helper and control channel.
Definition: IcmpSquid.cc:255
#define SA_NODEFER
void memClean(void)
Main cleanup handler.
Definition: old_api.cc:502
static void SquidShutdown(void)
Definition: main.cc:2057
void clientConnectionsClose()
void releaseServerSockets(void) STUB_NOP void dumpMallocStats(void) STUB void squid_getrusage(struct rusage *) STUB double rusage_cputime(struct rusage *) STUB_RETVAL(0) int rusage_maxrss(struct rusage *) STUB_RETVAL(0) int rusage_pagefaults(struct rusage *) STUB_RETVAL(0) void PrintRusage(void) STUB void death(int) STUB void BroadcastSignalIfAny(int &) STUB void sigusr2_handle(int) STUB void debug_trap(const char *) STUB void sig_child(int) STUB const char *getMyHostname(void) STUB_RETVAL(NULL) const char *uniqueHostname(void) STUB_RETVAL(NULL) void leave_suid(void) STUB_NOP void enter_suid(void) STUB void no_suid(void) STUB bool IamMasterProcess()
Definition: stub_tools.cc:18
#define FALSE
Definition: std-includes.h:56
void rotate_logs(int sig)
Definition: main.cc:717
void netdbFreeMemory(void)
Definition: net_db.cc:958
Config TheConfig
Definition: Config.cc:19
static EventLoop * Running
Definition: EventLoop.h:72
static void usage(void)
Definition: main.cc:354
virtual void create() override
create system resources needed for this store to operate in the future
Definition: Controller.cc:78
static void RunConfigUsers()
Definition: main.cc:1441
static bool masterSignaled()
Definition: main.cc:1851
void eventDelete(EVH *func, void *arg)
Definition: event.cc:130
static void sendSignal(void)
Definition: main.cc:1716
static void masterReconfigureFinish()
Ends reconfiguration sequence started by masterReconfigureStart().
Definition: main.cc:1801
virtual void sync() override
prepare for shutdown
Definition: Controller.cc:218
SBuf TheKidName
current Squid process name (e.g., "squid-coord")
Definition: Kids.cc:19
static void mainHandleCommandLineOption(const int optId, const char *optValue)
Definition: main.cc:438
int opt_store_doublecheck
static void StopEventLoop(void *)
Definition: main.cc:214
static int ReconfigureSignal
Definition: main.cc:163
void wccp2ConnectionOpen(void)
Definition: wccp2.cc:952
void run()
Definition: EventLoop.cc:76
void _db_rotate_log(void)
Definition: debug.cc:511
static void initModule()
Definition: FwdState.cc:1430
static void masterReviveKids()
Reacts to the kid revival alarm.
Definition: main.cc:1808
int TheProcessKind
ProcessKind for the current process.
Definition: Kid.cc:21
static const char * shortOpStr
Definition: main.cc:421
#define CACHE_HTTP_PORT
Definition: squid.h:16
int KidIdentifier
void storeInit(void)
Definition: store.cc:1272
static void watch_child(const CommandLine &)
Definition: main.cc:1892
unsigned short icp
Definition: SquidConfig.h:139
static volatile int do_shutdown
Definition: main.cc:157
SBuf gist() const
Definition: Kid.cc:172
#define O_TEXT
Definition: defines.h:140
SBuf ProcessRoles()
a string describing this process roles such as worker or coordinator
Definition: tools.cc:706
void Init(void)
Definition: Kid.h:18
IcmpSquid icmpEngine
Definition: IcmpSquid.cc:27
char * coredump_dir
Definition: SquidConfig.h:489
void FreeMemory()
undo Init()
Definition: Controller.cc:947
static void masterExit()
Definition: main.cc:1874
bool someSignaled(const int sgnl) const
whether some kids died from a given signal
Definition: Kids.cc:116
void handleStoppedChild()
Definition: main.cc:328
void WIN32_sendSignal(int WIN32_signal)
Definition: WinSvc.cc:799
static bool mainChangeDir(const char *dir)
changes working directory, providing error reporting
Definition: main.cc:1075
static volatile int do_handle_stopped_child
Definition: main.cc:160
void start(pid_t cpid)
called when this kid got started, records PID
Definition: Kid.cc:34
void OpenLogs()
opens logs enabled in the current configuration
Definition: KeyLog.cc:71
void storeLogClose(void)
Definition: store_log.cc:106
Definition: SBuf.h:87
void finalize()
checks pools configuration
void htcpOpenPorts(void)
Definition: htcp.cc:1443
#define OPENSSL_VERSION
Definition: openssl.h:133
static void serverConnectionsOpen(void)
Definition: main.cc:799
static void Shutdown()
Shutdown helper structure.
Definition: helper.cc:233
void death(int sig)
Definition: tools.cc:293
void Clean()
Definition: Module.cc:38
bool hasOption(const int optId, const char **optValue=nullptr) const
Definition: CommandLine.cc:71
#define xstrdup
@ FD_LOG
Definition: enums.h:14
void authenticateInit(Auth::ConfigVector *config)
Definition: Gadgets.cc:70
static void StartUsingConfig()
Definition: main.cc:1448
void start_announce(void *)
void snmpClosePorts(void)
Definition: snmp_core.cc:319
static bool AvoidSignalAction(const char *description, volatile int &signalVar)
Definition: main.cc:257
virtual int callback() override
called once every main loop iteration; TODO: Move to UFS code.
Definition: Controller.cc:229
SBuf service_name(APP_SHORTNAME)
time_t shutdownLifetime
Definition: SquidConfig.h:105
void forEachOption(Visitor) const
calls Visitor for each of the configured command line option
Definition: CommandLine.cc:89
bool shouldRestartSome() const
whether some kids should be restarted by master
Definition: Kids.cc:136
char * xstrncpy(char *dst, const char *src, size_t n)
Definition: xstring.cc:37
Auth::Config TheConfig
Definition: Config.cc:15
static int opt_signal_service
Definition: main.cc:148
bool IamWorkerProcess()
whether the current process handles HTTP transactions and such
Definition: stub_tools.cc:47
void LoadableModulesConfigure(const wordlist *names)
void ipcache_restart(void)
Definition: ipcache.cc:1103
#define SA_RESETHAND
#define DBG_CRITICAL
Definition: Debug.h:40
@ optForeground
Definition: main.cc:414
#define CACHE_ICP_PORT
Definition: squid.h:17
size_t count() const
returns the number of kids
Definition: Kids.cc:146
virtual void startReconfigure()
void authenticateRotate(void)
Definition: Gadgets.cc:85
virtual void syncConfig()
time_t getCurrentTime(void)
Get current time.
void WIN32_InstallService()
Definition: WinSvc.cc:719
void storeFsInit(void)
Definition: store.cc:1653
#define DBG_IMPORTANT
Definition: Debug.h:41
void fqdncache_init(void)
Definition: fqdncache.cc:699
static int SquidMainSafe(int argc, char **argv)
unsafe main routine wrapper to catch exceptions
Definition: main.cc:1382
static int port
Definition: ldap_backend.cc:69
void snmpInit(void)
Definition: snmp_core.cc:68
void self_destruct(void)
Definition: cache_cf.cc:275
virtual bool finalize()
Definition: Config.cc:184
static const CharacterSet ALPHA
Definition: CharacterSet.h:76
int WIN32_Subsystem_Init(int *argc, char ***argv)
Definition: WinSvc.cc:459
#define RunRegisteredHere(m)
convenience macro to describe/debug the caller and the method being called
int opt_no_daemon
static EventScheduler * GetInstance()
Definition: event.cc:303
time_t hopelessKidRevivalDelay
hopeless_kid_revival_delay
Definition: SquidConfig.h:107
#define TexcHere(msg)
legacy convenience macro; it is not difficult to type Here() now
Definition: TextException.h:58
Kid & get(size_t i)
returns the kid by index, useful for kids iteration
Definition: Kids.cc:60
static void mimeFreeMemory(void)
Definition: mime.cc:339
bool Chrooted
Definition: main.cc:1088
virtual bool finalize()
Definition: Config.cc:27
static void FreeAllFs()
static pid_t pid
Definition: IcmpSquid.cc:35
#define APP_SHORTNAME
Definition: version.h:22
static volatile int shutdown_status
Definition: main.cc:159
static void FreePools()
Definition: delay_pools.cc:555
static int RotateSignal
Definition: main.cc:162
void commCloseAllSockets(void)
Definition: comm.cc:1441
virtual int Open()
Start pinger helper and initiate control channel.
Definition: IcmpSquid.cc:190
bool allHopeless() const
whether all kids are hopeless
Definition: Kids.cc:67
static volatile int do_revive_kids
Definition: main.cc:158
void forgetAllFailures()
forgets all failures in all kids
Definition: Kids.cc:77
class SquidConfig2 Config2
Definition: SquidConfig.cc:14
void stop()
Definition: EventLoop.cc:168
const char * version_string
static void Reconfigure()
Definition: helper.cc:250
void netdbInit(void)
Definition: net_db.cc:884
void storeFreeMemory(void)
Definition: store.cc:1351
int DebugSignal
Definition: stub_tools.cc:16
int WIN32_StartService(int argc, char **argv)
Definition: WinSvc.cc:894
void WINAPI WIN32_svcHandler(DWORD)
Definition: WinSvc.cc:578
pid_t Other()
Definition: Instance.cc:128
static void RegisterWithCacheManager(void)
void leave_suid(void)
Definition: tools.cc:506
static void ConfigureDebugging()
Definition: main.cc:1427
void memCheckInit(void)
Definition: stub_libmem.cc:84
void comm_init(void)
Definition: comm.cc:1137
void _db_set_syslog(const char *)
Definition: debug.cc:460
void Init(void)
Definition: Ident.cc:307
void cbdataRegisterWithCacheManager(void)
Definition: cbdata.cc:209
static void master_revive_kids(int sig)
Definition: main.cc:744
void wccpInit(void)
Definition: wccp.cc:91
void sigusr2_handle(int sig)
Definition: tools.cc:380
static void Init()
Init helper structure.
Definition: helper.cc:77
void Init()
Definition: Module.cc:33
#define NULL
Definition: types.h:166
DWORD WIN32_IpAddrChangeMonitorInit()
Definition: WinSvc.cc:441
wordlist * loadable_module_names
Definition: SquidConfig.h:539
void WIN32_SetServiceCommandLine()
Definition: WinSvc.cc:704
void wccp2ConnectionClose(void)
Definition: wccp2.cc:1040
void RotateLogs()
rotates logs opened by OpenLogs()
Definition: KeyLog.cc:78
static void Init()
Init helper structure.
Definition: helper.cc:172
void StopUsingDebugLog()
start logging to stderr (instead of cache.log, if any)
Definition: debug.cc:84
#define SQUIDSBUFPRINT(s)
Definition: SBuf.h:32
#define OpenSSL_version
Definition: openssl.h:134
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Debug.h:123
static void SetupAllModules()
Definition: DiskIOModule.cc:45
void resetArg0(const char *programName)
replaces argv[0] with the new value
Definition: CommandLine.cc:115
void PrintRusage(void)
Definition: tools.cc:277
static void serverConnectionsClose(void)
Definition: main.cc:837
void unlinkdClose(void)
Definition: unlinkd.cc:132
bool IamDiskProcess() STUB_RETVAL_NOP(false) bool InDaemonMode() STUB_RETVAL_NOP(false) bool UsingSmp() STUB_RETVAL_NOP(false) bool IamCoordinatorProcess() STUB_RETVAL(false) bool IamPrimaryProcess() STUB_RETVAL(false) int NumberOfKids() STUB_RETVAL(0) void setMaxFD(void) STUB void setSystemLimits(void) STUB void squid_signal(int
whether the current process is dedicated to managing a cache_dir
pid_t WaitForOnePid(pid_t pid, PidStatus &status, int flags)
Definition: tools.cc:1147
void fdDumpOpen(void)
Definition: fd.cc:243
void mimeInit(char *filename)
Definition: mime.cc:231
void asnFreeMemory(void)
Definition: Asn.cc:210
static char * opt_syslog_facility
Definition: main.cc:149
static void Shutdown()
Shutdown helper structure.
Definition: helper.cc:108
static volatile int do_reconfigure
Definition: main.cc:155
static void mainRotate(void)
Definition: main.cc:1026
void snmpOpenPorts(void)
Definition: snmp_core.cc:256
struct SquidConfig::@98 Port
void eventFreeMemory(void)
Definition: event.cc:148
void WINAPI SquidWinSvcMain(int argc, char **argv)
Definition: main.cc:1359
static void Init()
initializes down-cased protocol scheme names array
Definition: UriScheme.cc:38
static void masterCheckAndBroadcastSignals()
Definition: main.cc:1818
void fqdncache_purgelru(void *)
Definition: fqdncache.cc:200
void htcpClosePorts(void)
Definition: htcp.cc:1647
Manages arguments passed to a program (i.e., main(argc, argv) parameters).
Definition: CommandLine.h:35
void CpuAffinityCheck()
check CPU affinity configuration and print warnings if needed
Definition: CpuAffinity.cc:49
void squid_signal(int sig, SIGHDLR *func, int flags)
Definition: tools.cc:840
void Report()
Definition: old_api.cc:468
static void Init()
Definition: delay_pools.cc:459
Kids TheKids
All kids being maintained.
Definition: Kids.cc:18
char * chroot_dir
Definition: SquidConfig.h:490
void WriteOurPid()
creates a PID file; throws on error
Definition: Instance.cc:178
int starting_up
void WIN32_svcstatusupdate(DWORD, DWORD)
Definition: WinSvc.cc:567
static void Init()
Definition: fde.cc:142
static void FinalShutdownRunners(void *)
Definition: main.cc:219
Config TheConfig
Definition: Config.cc:16
bool SIGHDLR int STUB void const char void ObjPackMethod STUB void const char *STUB void keepCapabilities(void) STUB pid_t WaitForOnePid(pid_t
struct SquidConfig2::@126 onoff
void httpHeaderInitModule(void)
Definition: HttpHeader.cc:118
int reconfiguring
int xatoi(const char *token)
Definition: Parsing.cc:44
void CpuAffinityInit()
set CPU affinity for this process on startup
Definition: CpuAffinity.cc:26
static void GoIntoBackground()
makes the caller a daemon process running in the background
Definition: main.cc:1859
void icapLogClose()
Definition: icap_log.cc:38
void icpConnectionShutdown(void)
Definition: icp_v2.cc:783
void clientOpenListenSockets(void)
virtual void endingShutdown()
#define assert(EX)
Definition: assert.h:19
static void mainStartScript(const char *prog)
Definition: main.cc:1748
static const char * squid_start_script
Definition: main.cc:182
int parseConfigFile(const char *file_name)
Definition: cache_cf.cc:633
int opt_create_swap_dirs
static void Init()
Initialize the format token registrations.
Definition: Token.cc:251
static void parseOptions(char const *)
Definition: debug.cc:468
void fatalf(const char *fmt,...)
Definition: fatal.cc:68
int errcount
Definition: EventLoop.h:68
std::ostream & CurrentException(std::ostream &os)
prints active (i.e., thrown but not yet handled) exception
static void Reconfigure()
Definition: helper.cc:119
void peerSelectInit(void)
Definition: peer_select.cc:919
int opt_reuseaddr
static const CharacterSet DIGIT
Definition: CharacterSet.h:84
static void mainReconfigureFinish(void *)
Definition: main.cc:904
void configFreeMemory(void)
Definition: cache_cf.cc:3985
#define SA_RESTART
pid_t WaitForAnyPid(PidStatus &status, int flags)
Definition: tools.h:111
const char * c_str()
Definition: SBuf.cc:516
void Init()
Definition: Module.cc:23
void fatal_dump(const char *message)
Definition: fatal.cc:78
size_type length() const
Returns the number of bytes stored in SBuf.
Definition: SBuf.h:408
static void mainSetCwd(void)
set the working directory.
Definition: main.cc:1092
int opt_foreground
virtual void useConfig()
void ipcacheFreeMemory(void)
Definition: ipcache.cc:1088
int Squid_MaxFD
#define SQUID_MAXFD_LIMIT
Definition: compat_shared.h:84
#define xfree
Receives coordination messages on behalf of its process or thread.
Definition: Strand.h:28
void storeDirCloseSwapLogs()
Definition: Disks.cc:681
void reconfigure(int sig)
Definition: main.cc:731
bool shouldRestart() const
returns true if master should restart this kid
Definition: Kid.cc:97
void storeLogRotate(void)
Definition: store_log.cc:97
void Init(Controller *root=nullptr)
initialize the storage module; a custom root is used by unit tests only
Definition: Controller.cc:941
void redirectReconfigure()
Definition: redirect.cc:435
bool IamMasterProcess()
whether the current process is the parent of all other Squid processes
Definition: tools.cc:635
virtual void finalizeConfig()
static void Initialize()
Definition: Acl.cc:404
int main(int argc, char **argv)
Definition: main.cc:1366
static void masterReconfigureStart()
Initiates reconfiguration sequence. See also: masterReconfigureFinish().
Definition: main.cc:1788
time_t forgetOldFailures()
Definition: Kids.cc:84
#define TRUE
Definition: std-includes.h:55
void BroadcastSignalIfAny(int &sig)
Definition: tools.cc:365
char * mimeTablePathname
Definition: SquidConfig.h:224
int storeDirWriteCleanLogs(int reopen)
Definition: Disks.cc:697
void refreshInit(void)
Definition: refresh.cc:737
void ipcache_init(void)
Definition: ipcache.cc:687
void htcpSocketShutdown(void)
Definition: htcp.cc:1618
int opt_reload_hit_only
GlobalContextStorage TheGlobalContextStorage
Global cache for store all SSL server certificates.
void urlInitialize(void)
Definition: Uri.cc:136
#define Important(id)
Definition: DebugMessages.h:91
@ pkOther
we do not know or do not care
Definition: Kid.h:103
static void mainReconfigureStart(void)
Definition: main.cc:868
static Coordinator * Instance()
Definition: Coordinator.cc:291
@ optKid
Definition: main.cc:415
void icpOpenPorts(void)
Definition: icp_v2.cc:700
void reconfigureStart()
When reconfigring should be called this method.
void setUmask(mode_t mask)
Definition: tools.cc:1036
static volatile int do_rotate
Definition: main.cc:156
struct timeval current_time
Definition: stub_time.cc:15
static int ShutdownSignal
Definition: main.cc:164
Definition: parse.c:160
struct SquidConfig::@111 onoff
int cmp(const SBuf &S, const size_type n) const
shorthand version for compare()
Definition: SBuf.h:268
char * ConfigFile
@ pkWorker
general-purpose worker bee
Definition: Kid.h:105
void fqdncacheFreeMemory(void)
Definition: fqdncache.cc:619
virtual void finishShutdown()
Meant for cleanup of services needed by the already destroyed objects.
int SquidMain(int argc, char **argv)
unsafe main routine – may throw
Definition: main.cc:1476
int PidStatus
Definition: tools.h:94
static void masterMaintainKidRevivalSchedule()
Definition: main.cc:1841
void authenticateReset(void)
Definition: Gadgets.cc:94
bool IamCoordinatorProcess()
whether the current process coordinates worker processes
Definition: tools.cc:669
void init()
initialize all kid records based on Config
Definition: Kids.cc:26
void wccp2Init(void) STUB void wccp2ConnectionOpen(void) STUB void wccp2ConnectionClose(void) STUB void dump_wccp2_method(StoreEntry *
void icpClosePorts(void)
Definition: icp_v2.cc:808
void Init()
Definition: old_api.cc:426
void accessLogRotate(void)
Definition: access_log.cc:183
void CloseLogs()
closes logs opened by OpenLogs()
Definition: KeyLog.cc:85
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
Definition: Stream.h:124
int opt_parse_cfg_only
void setPrimaryEngine(AsyncEngine *engine)
Definition: EventLoop.cc:149
Kid * find(pid_t pid)
returns kid by pid
Definition: Kids.cc:47
#define Must(condition)
Like assert() but throws an exception instead of aborting the process.
Definition: TextException.h:73
void asnInit(void)
Definition: Asn.cc:194
void fd_open(int fd, unsigned int type, const char *desc)
Definition: fd.cc:157
void enter_suid(void)
Definition: tools.cc:577
bool someRunning() const
whether some kids are running
Definition: Kids.cc:126
int checkEvents(int)
Definition: main.cc:195
virtual void claimMemoryNeeds()
void redirectInit(void)
Definition: redirect.cc:333
static int override_X
Definition: Debug.h:79
void setSystemLimits(void)
Definition: tools.cc:778
void doShutdown(time_t wait)
Definition: main.cc:286
static void ConfigureCurrentKid(const CommandLine &cmdLine)
computes name and ID for the current kid process
Definition: main.cc:1399
void CleanIdlePools(void *unused)
Definition: old_api.cc:400
void wccpConnectionOpen(void)
Definition: wccp.cc:109
static void masterShutdownStart()
Initiates shutdown sequence. Shutdown ends when the last running kids stops.
Definition: main.cc:1778
struct StatCounters::@128 client_http
void registerEngine(AsyncEngine *engine)
Definition: EventLoop.cc:70
int shutting_down
void setMaxFD(void)
Definition: tools.cc:729
void _db_init(const char *logfile, const char *options)
Definition: debug.cc:493
const char * arg0() const
Definition: CommandLine.h:58
optimized set of C chars, with quick membership test and merge support
Definition: CharacterSet.h:18
int opt_foreground_rebuild
void redirectShutdown(void)
Definition: redirect.cc:406
static int opt_remove_service
Definition: main.cc:142
void storeDirOpenSwapLogs()
Definition: Disks.cc:674
void fqdncache_restart(void)
Definition: fqdncache.cc:634
static void SetupAllFs()
void no_suid(void)
Definition: tools.cc:606
static void OnTerminate()
Definition: main.cc:1339
#define MAXPATHLEN
Definition: stdio.h:62
void peerUserHashInit(void)
int opt_catch_signals
SBuf processName() const
returns kid name
Definition: Kid.cc:164
static int log_stderr
Definition: Debug.h:80
bool UsingSmp()
Whether there should be more than one worker process running.
Definition: tools.cc:663
static int opt_command_line
Definition: main.cc:143
static void FreeAll()
Definition: Scheme.cc:60
void storeLogOpen(void)
Definition: store_log.cc:124
void ipcache_purgelru(void *)
Definition: ipcache.cc:351
void neighbors_init(void)
Definition: neighbors.cc:555
void eventInit(void)
Definition: event.cc:136
static void setEffectiveUser(void)
Definition: main.cc:1055
void unlinkdInit(void)
Definition: unlinkd.cc:192
void WIN32_RemoveService()
Definition: WinSvc.cc:648
void ProbeTransport(void)
Probe to discover IPv6 capabilities.
static int opt_install_service
Definition: main.cc:141
void errorClean(void)
Definition: errorpage.cc:316
void sig_child(int sig)
Definition: main.cc:787
@ pkCoordinator
manages all other kids
Definition: Kid.h:104
bool SIGHDLR int STUB void const char void ObjPackMethod STUB void parseEtcHosts(void) STUB int getMyPort(void) STUB_RETVAL(0) void setUmask(mode_t) STUB void strwordquote(MemBuf *
static struct option squidOptions[]
Definition: main.cc:428
void statFreeMemory(void)
Definition: stat.cc:1595
void peerSourceHashInit(void)
void Init(void)
prepares to parse ACLs configuration
Definition: AclRegs.cc:114
virtual void startShutdown()
void wccpConnectionClose(void)
Definition: wccp.cc:161
void freeService(void)
Definition: Config.cc:146
void ThrowIfAlreadyRunning()
Definition: Instance.cc:139
bool unlinkdNeeded(void)
Definition: unlinkd.cc:179
static void Finalize(bool enable)
Definition: Config.cc:230
void eventAdd(const char *name, EVH *func, void *arg, double when, int weight, bool cbdata)
Definition: event.cc:108
void icapLogRotate()
Definition: icap_log.cc:51
virtual int checkEvents(int timeout)
Definition: main.cc:241
void CpuAffinityReconfigure()
reconfigure CPU affinity for this process
Definition: CpuAffinity.cc:38
void errorInitialize(void)
Definition: errorpage.cc:254
#define SQUIDSBUFPH
Definition: SBuf.h:31
void Init(void)
Initialize Auth subsystem.
Definition: AuthReg.cc:34
static int icpPortNumOverride
Definition: main.cc:150
#define Critical(id)
Definition: DebugMessages.h:90
void carpInit(void)
Definition: carp.cc:44
class SquidConfig Config
Definition: SquidConfig.cc:12
@ pkDisker
cache_dir manager
Definition: Kid.h:106
void add_http_port(char *portspec)
Definition: cache_cf.cc:3781
bool IamPrimaryProcess()
Definition: tools.cc:675
void shut_down(int sig)
Definition: main.cc:772
StatCounters statCounter
Definition: StatCounters.cc:12
void externalAclInit(void)
static void Start(const Pointer &job)
Definition: AsyncJob.cc:24
static void master_shutdown(int sig)
Shutdown signal handler for master process.
Definition: main.cc:758
void statInit(void)
Definition: stat.cc:1269
ClientDelayConfig ClientDelay
Definition: SquidConfig.h:453
Controller & Root()
safely access controller singleton
Definition: Controller.cc:934
bool InDaemonMode()
Whether we are running in daemon mode.
Definition: tools.cc:657

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors