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

 

Introduction

Documentation

Support

Miscellaneous