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