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

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors