cache_manager.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2021 The Squid Software Foundation and contributors
3  *
4  * Squid software is distributed under GPLv2+ license and includes
5  * contributions from numerous individuals and organizations.
6  * Please see the COPYING and CONTRIBUTORS files for details.
7  */
8 
9 /* DEBUG: section 16 Cache Manager Objects */
10 
11 #include "squid.h"
12 #include "AccessLogEntry.h"
13 #include "base/TextException.h"
14 #include "CacheManager.h"
15 #include "comm/Connection.h"
16 #include "Debug.h"
18 #include "errorpage.h"
19 #include "fde.h"
20 #include "HttpReply.h"
21 #include "HttpRequest.h"
22 #include "mgr/Action.h"
23 #include "mgr/ActionCreator.h"
24 #include "mgr/ActionPasswordList.h"
25 #include "mgr/ActionProfile.h"
26 #include "mgr/BasicActions.h"
27 #include "mgr/Command.h"
28 #include "mgr/Forwarder.h"
29 #include "mgr/FunAction.h"
30 #include "mgr/QueryParams.h"
31 #include "parser/Tokenizer.h"
32 #include "protos.h"
33 #include "sbuf/Stream.h"
34 #include "sbuf/StringConvert.h"
35 #include "SquidConfig.h"
36 #include "SquidTime.h"
37 #include "Store.h"
38 #include "tools.h"
39 #include "wordlist.h"
40 
41 #include <algorithm>
42 
44 #define MGR_PASSWD_SZ 128
45 
48 {
49 public:
51 
52 public:
53  ClassActionCreator(Handler *aHandler): handler(aHandler) {}
54 
56  return handler(cmd);
57  }
58 
59 private:
61 };
62 
64 void
66 {
67  Must(profile != NULL);
68  if (!CacheManager::findAction(profile->name)) {
69  menu_.push_back(profile);
70  debugs(16, 3, HERE << "registered profile: " << *profile);
71  } else {
72  debugs(16, 2, HERE << "skipped duplicate profile: " << *profile);
73  }
74 }
75 
82 void
83 CacheManager::registerProfile(char const * action, char const * desc, OBJH * handler, int pw_req_flag, int atomic)
84 {
85  debugs(16, 3, HERE << "registering legacy " << action);
87  desc, pw_req_flag, atomic, new Mgr::FunActionCreator(handler));
88  registerProfile(profile);
89 }
90 
97 void
98 CacheManager::registerProfile(char const * action, char const * desc,
100  int pw_req_flag, int atomic)
101 {
103  desc, pw_req_flag, atomic, new ClassActionCreator(handler));
104  registerProfile(profile);
105 }
106 
114 CacheManager::findAction(char const * action) const
115 {
116  Must(action != NULL);
117  Menu::const_iterator a;
118 
119  debugs(16, 5, "CacheManager::findAction: looking for action " << action);
120  for (a = menu_.begin(); a != menu_.end(); ++a) {
121  if (0 == strcmp((*a)->name, action)) {
122  debugs(16, 6, " found");
123  return *a;
124  }
125  }
126 
127  debugs(16, 6, "Action not found.");
128  return Mgr::ActionProfilePointer();
129 }
130 
132 CacheManager::createNamedAction(const char *actionName)
133 {
134  Must(actionName);
135 
137  cmd->profile = findAction(actionName);
138  cmd->params.actionName = actionName;
139 
140  Must(cmd->profile != NULL);
141  return cmd->profile->creator->create(cmd);
142 }
143 
146 {
148  cmd->params = params;
149  cmd->profile = findAction(params.actionName.termedBuf());
150  Must(cmd->profile != NULL);
151  return cmd->profile->creator->create(cmd);
152 }
153 
154 static const CharacterSet &
156 {
157  // Deprecated cache_object:// scheme used '@' to delimit passwords
158  if (protocol == AnyP::PROTO_CACHE_OBJECT) {
159  static const CharacterSet fieldChars = CharacterSet("cache-object-field", "@?#").complement();
160  return fieldChars;
161  }
162 
163  static const CharacterSet actionChars = CharacterSet("mgr-field", "?#").complement();
164  return actionChars;
165 }
166 
182 {
183  Parser::Tokenizer tok(uri.path());
184 
185  static const SBuf internalMagicPrefix("/squid-internal-mgr/");
186  if (!tok.skip(internalMagicPrefix) && !tok.skip('/'))
187  throw TextException("invalid URL path", Here());
188 
190  cmd->params.httpUri = SBufToString(uri.absolute());
191 
192  const auto &fieldChars = MgrFieldChars(uri.getScheme());
193 
194  SBuf action;
195  if (!tok.prefix(action, fieldChars)) {
196  if (uri.getScheme() == AnyP::PROTO_CACHE_OBJECT) {
197  static const SBuf menuReport("menu");
198  action = menuReport;
199  } else {
200  static const SBuf indexReport("index");
201  action = indexReport;
202  }
203  }
204  cmd->params.actionName = SBufToString(action);
205 
206  const auto profile = findAction(action.c_str());
207  if (!profile)
208  throw TextException(ToSBuf("action '", action, "' not found"), Here());
209 
210  const char *prot = ActionProtection(profile);
211  if (!strcmp(prot, "disabled") || !strcmp(prot, "hidden"))
212  throw TextException(ToSBuf("action '", action, "' is ", prot), Here());
213  cmd->profile = profile;
214 
215  SBuf passwd;
216  if (uri.getScheme() == AnyP::PROTO_CACHE_OBJECT && tok.skip('@')) {
217  (void)tok.prefix(passwd, fieldChars);
218  cmd->params.password = SBufToString(passwd);
219  }
220 
221  // TODO: fix when AnyP::Uri::parse() separates path?query#fragment
222  SBuf params;
223  if (tok.skip('?')) {
224  params = tok.remaining();
225  Mgr::QueryParams::Parse(tok, cmd->params.queryParams);
226  }
227 
228  if (!tok.skip('#') && !tok.atEnd())
229  throw TextException("invalid characters in URL", Here());
230  // else ignore #fragment (if any)
231 
232  debugs(16, 3, "MGR request: host=" << uri.host() << ", action=" << action <<
233  ", password=" << passwd << ", params=" << params);
234 
235  return cmd;
236 }
237 
239 /*
240  \ingroup CacheManagerInternal
241  * Decodes the headers needed to perform user authentication and fills
242  * the details into the cachemgrStateData argument
243  */
244 void
246 {
247  assert(request);
248 
249  params.httpMethod = request->method.id();
250  params.httpFlags = request->flags;
251 
252 #if HAVE_AUTH_MODULE_BASIC
253  // TODO: use the authentication system decode to retrieve these details properly.
254 
255  /* base 64 _decoded_ user:passwd pair */
256  const auto basic_cookie(request->header.getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
257 
258  if (basic_cookie.isEmpty())
259  return;
260 
261  const auto colonPos = basic_cookie.find(':');
262  if (colonPos == SBuf::npos) {
263  debugs(16, DBG_IMPORTANT, "CacheManager::ParseHeaders: unknown basic_cookie format '" << basic_cookie << "'");
264  return;
265  }
266 
267  /* found user:password pair, reset old values */
268  params.userName = SBufToString(basic_cookie.substr(0, colonPos));
269  params.password = SBufToString(basic_cookie.substr(colonPos+1));
270 
271  /* warning: this prints decoded password which maybe not be what you want to do @?@ @?@ */
272  debugs(16, 9, "CacheManager::ParseHeaders: got user: '" <<
273  params.userName << "' passwd: '" << params.password << "'");
274 #endif
275 }
276 
284 int
286 {
287  assert(cmd.profile != NULL);
288  const char *action = cmd.profile->name;
289  char *pwd = PasswdGet(Config.passwd_list, action);
290 
291  debugs(16, 4, "CacheManager::CheckPassword for action " << action);
292 
293  if (pwd == NULL)
294  return cmd.profile->isPwReq;
295 
296  if (strcmp(pwd, "disable") == 0)
297  return 1;
298 
299  if (strcmp(pwd, "none") == 0)
300  return 0;
301 
302  if (!cmd.params.password.size())
303  return 1;
304 
305  return cmd.params.password != pwd;
306 }
307 
314 void
316 {
317  debugs(16, 3, "request-url= '" << request->url << "', entry-url='" << entry->url() << "'");
318 
320  try {
321  cmd = ParseUrl(request->url);
322 
323  } catch (...) {
324  debugs(16, 2, "request URL error: " << CurrentException);
325  const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request, ale);
326  err->url = xstrdup(entry->url());
327  err->detailError(new ExceptionErrorDetail(Here().id()));
328  errorAppendEntry(entry, err);
329  entry->expires = squid_curtime;
330  return;
331  }
332 
333  const char *actionName = cmd->profile->name;
334 
335  entry->expires = squid_curtime;
336 
337  debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");
338 
339  /* get additional info from request headers */
340  ParseHeaders(request, cmd->params);
341 
342  const char *userName = cmd->params.userName.size() ?
343  cmd->params.userName.termedBuf() : "unknown";
344 
345  /* Check password */
346 
347  if (CheckPassword(*cmd) != 0) {
348  /* build error message */
350  /* warn if user specified incorrect password */
351 
352  if (cmd->params.password.size()) {
353  debugs(16, DBG_IMPORTANT, "CacheManager: " <<
354  userName << "@" <<
355  client << ": incorrect password for '" <<
356  actionName << "'" );
357  } else {
358  debugs(16, DBG_IMPORTANT, "CacheManager: " <<
359  userName << "@" <<
360  client << ": password needed for '" <<
361  actionName << "'" );
362  }
363 
364  HttpReply *rep = errState.BuildHttpReply();
365 
366 #if HAVE_AUTH_MODULE_BASIC
367  /*
368  * add Authenticate header using action name as a realm because
369  * password depends on the action
370  */
371  rep->header.putAuth("Basic", actionName);
372 #endif
373  // Allow cachemgr and other XHR scripts access to our version string
374  if (request->header.has(Http::HdrType::ORIGIN)) {
375  rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
376 #if HAVE_AUTH_MODULE_BASIC
377  rep->header.putExt("Access-Control-Allow-Credentials","true");
378 #endif
379  rep->header.putExt("Access-Control-Expose-Headers","Server");
380  }
381 
382  /* store the reply */
383  entry->replaceHttpReply(rep);
384 
385  entry->expires = squid_curtime;
386 
387  entry->complete();
388 
389  return;
390  }
391 
392  if (request->header.has(Http::HdrType::ORIGIN)) {
393  cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
394  }
395 
396  debugs(16, 2, "CacheManager: " <<
397  userName << "@" <<
398  client << " requesting '" <<
399  actionName << "'" );
400 
401  // special case: /squid-internal-mgr/ index page
402  if (!strcmp(cmd->profile->name, "index")) {
404  err.url = xstrdup(entry->url());
405  HttpReply *rep = err.BuildHttpReply();
406  if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
408  // Allow cachemgr and other XHR scripts access to our version string
409  if (request->header.has(Http::HdrType::ORIGIN)) {
410  rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
411 #if HAVE_AUTH_MODULE_BASIC
412  rep->header.putExt("Access-Control-Allow-Credentials","true");
413 #endif
414  rep->header.putExt("Access-Control-Expose-Headers","Server");
415  }
416  entry->replaceHttpReply(rep);
417  entry->complete();
418  return;
419  }
420 
421  if (UsingSmp() && IamWorkerProcess()) {
422  // is client the right connection to pass here?
423  AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry, ale));
424  return;
425  }
426 
427  Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
428  Must(action != NULL);
429  action->run(entry, true);
430 }
431 
432 /*
433  \ingroup CacheManagerInternal
434  * Renders the protection level text for an action.
435  * Also doubles as a check for the protection level.
436  */
437 const char *
439 {
440  assert(profile != NULL);
441  const char *pwd = PasswdGet(Config.passwd_list, profile->name);
442 
443  if (!pwd)
444  return profile->isPwReq ? "hidden" : "public";
445 
446  if (!strcmp(pwd, "disable"))
447  return "disabled";
448 
449  if (strcmp(pwd, "none") == 0)
450  return "public";
451 
452  return "protected";
453 }
454 
455 /*
456  * \ingroup CacheManagerInternal
457  * gets from the global Config the password the user would need to supply
458  * for the action she queried
459  */
460 char *
462 {
463  while (a) {
464  for (auto &w : a->actions) {
465  if (w.cmp(action) == 0)
466  return a->passwd;
467 
468  static const SBuf allAction("all");
469  if (w == allAction)
470  return a->passwd;
471  }
472 
473  a = a->next;
474  }
475 
476  return NULL;
477 }
478 
481 {
482  static CacheManager *instance = nullptr;
483  if (!instance) {
484  debugs(16, 6, "starting cachemanager up");
485  instance = new CacheManager;
487  }
488  return instance;
489 }
490 
char method[16]
Definition: tcp-banger2.c:115
static bool action(int fd, size_t metasize, const char *fn, const char *url, const SquidMetaList &meta)
Definition: purge.cc:311
@ ERR_INVALID_URL
Definition: forward.h:45
@ ERR_CACHE_MGR_ACCESS_DENIED
Definition: forward.h:20
#define Here()
source code location of the caller
Definition: Here.h:15
@ scUnauthorized
Definition: StatusCode.h:45
hard-coded Cache Manager action configuration, including Action creator
Definition: ActionProfile.h:22
Definition: Uri.h:31
Command
what kind of I/O the disker needs to do or have done
Definition: IpcIoFile.h:33
ActionParams params
user-supplied action arguments
Definition: Command.h:28
HttpHeader header
Definition: Message.h:75
void errorAppendEntry(StoreEntry *entry, ErrorState *err)
Definition: errorpage.cc:720
CacheManager()
use Instance() instead
Definition: CacheManager.h:53
combined hard-coded action profile with user-supplied action parameters
Definition: Command.h:22
const char * url() const
Definition: store.cc:1583
static void handler(int signo)
Definition: purge.cc:854
String password
user password; used for acceptance check and cleared
Definition: ActionParams.h:41
RefCount< ActionProfile > ActionProfilePointer
Definition: forward.h:32
HttpReply * BuildHttpReply(void)
Definition: errorpage.cc:1280
Definition: SBuf.h:87
CharacterSet complement(const char *complementLabel=nullptr) const
Definition: CharacterSet.cc:74
#define xstrdup
ActionPasswordList * next
const char * content() const
Definition: HttpBody.h:44
Http::StatusLine sline
Definition: HttpReply.h:56
time_t expires
Definition: Store.h:227
bool IamWorkerProcess()
whether the current process handles HTTP transactions and such
Definition: stub_tools.cc:47
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition: store.cc:1722
static CacheManager * GetInstance()
#define DBG_IMPORTANT
Definition: Debug.h:41
int CheckPassword(const Mgr::Command &cmd)
ActionProfilePointer profile
hard-coded action specification
Definition: Command.h:27
const char * ActionProtection(const Mgr::ActionProfilePointer &profile)
AnyP::UriScheme const & getScheme() const
Definition: Uri.h:67
Mgr::Action::Pointer Handler(const Mgr::Command::Pointer &cmd)
HttpBody body
Definition: HttpReply.h:58
ProtocolType
Definition: ProtocolType.h:23
HttpRequestMethod httpMethod
HTTP request method.
Definition: ActionParams.h:34
RequestFlags httpFlags
HTTP request flags.
Definition: ActionParams.h:35
Mgr::ActionPasswordList * passwd_list
Definition: SquidConfig.h:266
void OBJH(StoreEntry *)
Definition: forward.h:44
#define NULL
Definition: types.h:166
char * PasswdGet(Mgr::ActionPasswordList *, const char *)
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Debug.h:123
void start(const Comm::ConnectionPointer &client, HttpRequest *request, StoreEntry *entry, const AccessLogEntryPointer &ale)
void RegisterBasics()
Registers profiles for the actions above; TODO: move elsewhere?
void putAuth(const char *auth_scheme, const char *realm)
Definition: HttpHeader.cc:1060
std::ostream & HERE(std::ostream &s)
Definition: Debug.h:152
void putExt(const char *name, const char *value)
Definition: HttpHeader.cc:1140
#define assert(EX)
Definition: assert.h:19
char const * termedBuf() const
Definition: SquidString.h:92
Mgr::Action::Pointer createRequestedAction(const Mgr::ActionParams &)
Mgr::Action::Pointer createNamedAction(const char *actionName)
void ParseHeaders(const HttpRequest *request, Mgr::ActionParams &params)
std::ostream & CurrentException(std::ostream &os)
prints active (i.e., thrown but not yet handled) exception
creates Action using supplied Action::Create method and command
time_t squid_curtime
Definition: stub_time.cc:17
@ MGR_INDEX
Definition: forward.h:86
static const size_type npos
Definition: SBuf.h:92
static void Parse(Parser::Tokenizer &, QueryParams &)
parses the query string parameters
Definition: QueryParams.cc:112
@ PROTO_CACHE_OBJECT
Definition: ProtocolType.h:32
void complete()
Definition: store.cc:1045
Mgr::CommandPointer ParseUrl(const AnyP::Uri &)
SBuf & absolute() const
Definition: Uri.cc:583
void path(const char *p)
Definition: Uri.h:99
@ scNotFound
Definition: StatusCode.h:48
ClassActionCreator(Handler *aHandler)
char * url
Definition: errorpage.h:176
Definition: parse.c:160
Cache Manager Action parameters extracted from the user request.
Definition: ActionParams.h:24
an std::runtime_error with thrower location info
Definition: TextException.h:20
void set(const AnyP::ProtocolVersion &newVersion, Http::StatusCode newStatus, const char *newReason=NULL)
Definition: StatusLine.cc:35
list of cachemgr password authorization definitions. Currently a POD.
size_type size() const
Definition: SquidString.h:73
char * url
Definition: tcp-banger2.c:114
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
Definition: Stream.h:124
creates FunAction using ActionCreator API
Definition: FunAction.h:45
#define Must(condition)
Like assert() but throws an exception instead of aborting the process.
Definition: TextException.h:73
String actionName
action name (and credentials realm)
Definition: ActionParams.h:39
void registerProfile(char const *action, char const *desc, OBJH *handler, int pw_req_flag, int atomic)
static CacheManager * instance
optimized set of C chars, with quick membership test and merge support
Definition: CharacterSet.h:18
Mgr::ActionProfilePointer findAction(char const *action) const
String SBufToString(const SBuf &s)
Definition: StringConvert.h:26
virtual Mgr::Action::Pointer create(const Mgr::Command::Pointer &cmd) const
returns a pointer to the new Action object for cmd; never nil
@ scOkay
Definition: StatusCode.h:26
bool UsingSmp()
Whether there should be more than one worker process running.
Definition: tools.cc:663
void host(const char *src)
Definition: Uri.cc:98
struct _request * request(char *urlin)
Definition: tcp-banger2.c:291
static const CharacterSet & MgrFieldChars(const AnyP::ProtocolType &protocol)
String userName
user login name; currently only used for logging
Definition: ActionParams.h:40
class SquidConfig Config
Definition: SquidConfig.cc:12
static void Start(const Pointer &job)
Definition: AsyncJob.cc:24
AnyP::ProtocolVersion ProtocolVersion(unsigned int aMajor, unsigned int aMinor)
HTTP version label information.

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors