]> git.ipfire.org Git - thirdparty/squid.git/blame - src/cache_manager.cc
SourceLayout: Move time related tools to time/libtime.la (#1001)
[thirdparty/squid.git] / src / cache_manager.cc
CommitLineData
22f3fd98 1/*
bf95c10a 2 * Copyright (C) 1996-2022 The Squid Software Foundation and contributors
e25c139f 3 *
bbc27441
AJ
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.
22f3fd98 7 */
8
bbc27441
AJ
9/* DEBUG: section 16 Cache Manager Objects */
10
f7f3304a 11#include "squid.h"
7e6eabbc 12#include "AccessLogEntry.h"
8822ebee 13#include "base/TextException.h"
62ee09ca 14#include "CacheManager.h"
5c336a3b 15#include "comm/Connection.h"
675b8408 16#include "debug/Stream.h"
26e65059 17#include "error/ExceptionErrorDetail.h"
53521734 18#include "errorpage.h"
8822ebee 19#include "fde.h"
528b2c61 20#include "HttpReply.h"
21#include "HttpRequest.h"
8822ebee 22#include "mgr/Action.h"
602d9612
A
23#include "mgr/ActionCreator.h"
24#include "mgr/ActionPasswordList.h"
8822ebee
AR
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"
b8151fa1 30#include "mgr/QueryParams.h"
26e65059 31#include "parser/Tokenizer.h"
592b8687 32#include "protos.h"
26e65059 33#include "sbuf/Stream.h"
2582f64a 34#include "sbuf/StringConvert.h"
4d5904f7 35#include "SquidConfig.h"
8822ebee 36#include "Store.h"
602d9612 37#include "tools.h"
d295d770 38#include "wordlist.h"
5bed43d6 39
8822ebee 40#include <algorithm>
22f3fd98 41
63be0a78 42/// \ingroup CacheManagerInternal
22f3fd98 43#define MGR_PASSWD_SZ 128
44
8822ebee
AR
45/// creates Action using supplied Action::Create method and command
46class ClassActionCreator: public Mgr::ActionCreator
47{
48public:
49 typedef Mgr::Action::Pointer Handler(const Mgr::Command::Pointer &cmd);
c83f0bd5 50
8822ebee
AR
51public:
52 ClassActionCreator(Handler *aHandler): handler(aHandler) {}
53
d9fc6862 54 virtual Mgr::Action::Pointer create(const Mgr::Command::Pointer &cmd) const {
8822ebee
AR
55 return handler(cmd);
56 }
57
58private:
59 Handler *handler;
60};
61
8822ebee
AR
62/// Registers new profiles, ignoring attempts to register a duplicate
63void
64CacheManager::registerProfile(const Mgr::ActionProfile::Pointer &profile)
62ee09ca 65{
8822ebee 66 Must(profile != NULL);
e3c2ea01 67 if (!CacheManager::findAction(profile->name)) {
8822ebee 68 menu_.push_back(profile);
bf95c10a 69 debugs(16, 3, "registered profile: " << *profile);
8822ebee 70 } else {
bf95c10a 71 debugs(16, 2, "skipped duplicate profile: " << *profile);
8822ebee 72 }
62ee09ca 73}
22f3fd98 74
50847dca
AJ
75/**
76 \ingroup CacheManagerAPI
77 * Registers a C-style action, which is implemented as a pointer to a function
78 * taking as argument a pointer to a StoreEntry and returning void.
79 * Implemented via CacheManagerActionLegacy.
80 */
22f3fd98 81void
8822ebee 82CacheManager::registerProfile(char const * action, char const * desc, OBJH * handler, int pw_req_flag, int atomic)
22f3fd98 83{
bf95c10a 84 debugs(16, 3, "registering legacy " << action);
8822ebee 85 const Mgr::ActionProfile::Pointer profile = new Mgr::ActionProfile(action,
d9fc6862 86 desc, pw_req_flag, atomic, new Mgr::FunActionCreator(handler));
8822ebee 87 registerProfile(profile);
1d8395bd 88}
62e76326 89
d154d3ec 90/**
e0d28505 91 * \ingroup CacheManagerAPI
a750e510 92 * Registers a C++-style action, via a pointer to a subclass of
d154d3ec
FC
93 * a CacheManagerAction object, whose run() method will be invoked when
94 * CacheManager identifies that the user has requested the action.
95 */
1d8395bd 96void
8822ebee 97CacheManager::registerProfile(char const * action, char const * desc,
d9fc6862
A
98 ClassActionCreator::Handler *handler,
99 int pw_req_flag, int atomic)
1d8395bd 100{
8822ebee 101 const Mgr::ActionProfile::Pointer profile = new Mgr::ActionProfile(action,
d9fc6862 102 desc, pw_req_flag, atomic, new ClassActionCreator(handler));
8822ebee 103 registerProfile(profile);
62ee09ca 104}
105
d154d3ec
FC
106/**
107 \ingroup CacheManagerInternal
108 * Locates an action in the actions registry ActionsList.
109\retval NULL if Action not found
110\retval CacheManagerAction* if the action was found
111 */
8822ebee
AR
112Mgr::ActionProfile::Pointer
113CacheManager::findAction(char const * action) const
22f3fd98 114{
8822ebee
AR
115 Must(action != NULL);
116 Menu::const_iterator a;
03c4599f
K
117
118 debugs(16, 5, "CacheManager::findAction: looking for action " << action);
8822ebee
AR
119 for (a = menu_.begin(); a != menu_.end(); ++a) {
120 if (0 == strcmp((*a)->name, action)) {
03c4599f
K
121 debugs(16, 6, " found");
122 return *a;
123 }
22f3fd98 124 }
62e76326 125
03c4599f 126 debugs(16, 6, "Action not found.");
8822ebee
AR
127 return Mgr::ActionProfilePointer();
128}
129
130Mgr::Action::Pointer
131CacheManager::createNamedAction(const char *actionName)
132{
133 Must(actionName);
134
135 Mgr::Command::Pointer cmd = new Mgr::Command;
136 cmd->profile = findAction(actionName);
137 cmd->params.actionName = actionName;
138
139 Must(cmd->profile != NULL);
140 return cmd->profile->creator->create(cmd);
141}
142
143Mgr::Action::Pointer
144CacheManager::createRequestedAction(const Mgr::ActionParams &params)
145{
146 Mgr::Command::Pointer cmd = new Mgr::Command;
147 cmd->params = params;
148 cmd->profile = findAction(params.actionName.termedBuf());
149 Must(cmd->profile != NULL);
150 return cmd->profile->creator->create(cmd);
22f3fd98 151}
152
26e65059
AJ
153static const CharacterSet &
154MgrFieldChars(const AnyP::ProtocolType &protocol)
155{
156 // Deprecated cache_object:// scheme used '@' to delimit passwords
157 if (protocol == AnyP::PROTO_CACHE_OBJECT) {
158 static const CharacterSet fieldChars = CharacterSet("cache-object-field", "@?#").complement();
159 return fieldChars;
160 }
161
162 static const CharacterSet actionChars = CharacterSet("mgr-field", "?#").complement();
163 return actionChars;
164}
165
832c08ab 166/**
832c08ab
FC
167 * define whether the URL is a cache-manager URL and parse the action
168 * requested by the user. Checks via CacheManager::ActionProtection() that the
169 * item is accessible by the user.
26e65059
AJ
170 *
171 * Syntax:
172 *
173 * scheme "://" authority [ '/squid-internal-mgr' ] path-absolute [ '@' unreserved ] '?' query-string
174 *
175 * see RFC 3986 for definitions of scheme, authority, path-absolute, query-string
176 *
177 * \returns Mgr::Command object with action to perform and parameters it might use
832c08ab 178 */
8822ebee 179Mgr::Command::Pointer
26e65059 180CacheManager::ParseUrl(const AnyP::Uri &uri)
22f3fd98 181{
26e65059 182 Parser::Tokenizer tok(uri.path());
8822ebee 183
26e65059
AJ
184 static const SBuf internalMagicPrefix("/squid-internal-mgr/");
185 if (!tok.skip(internalMagicPrefix) && !tok.skip('/'))
186 throw TextException("invalid URL path", Here());
62e76326 187
26e65059
AJ
188 Mgr::Command::Pointer cmd = new Mgr::Command();
189 cmd->params.httpUri = SBufToString(uri.absolute());
5366b99b 190
26e65059
AJ
191 const auto &fieldChars = MgrFieldChars(uri.getScheme());
192
193 SBuf action;
194 if (!tok.prefix(action, fieldChars)) {
195 if (uri.getScheme() == AnyP::PROTO_CACHE_OBJECT) {
196 static const SBuf menuReport("menu");
197 action = menuReport;
198 } else {
199 static const SBuf indexReport("index");
200 action = indexReport;
201 }
22f3fd98 202 }
26e65059
AJ
203 cmd->params.actionName = SBufToString(action);
204
205 const auto profile = findAction(action.c_str());
206 if (!profile)
207 throw TextException(ToSBuf("action '", action, "' not found"), Here());
62e76326 208
8822ebee 209 const char *prot = ActionProtection(profile);
26e65059
AJ
210 if (!strcmp(prot, "disabled") || !strcmp(prot, "hidden"))
211 throw TextException(ToSBuf("action '", action, "' is ", prot), Here());
212 cmd->profile = profile;
213
214 SBuf passwd;
215 if (uri.getScheme() == AnyP::PROTO_CACHE_OBJECT && tok.skip('@')) {
216 (void)tok.prefix(passwd, fieldChars);
217 cmd->params.password = SBufToString(passwd);
8822ebee 218 }
62e76326 219
26e65059
AJ
220 // TODO: fix when AnyP::Uri::parse() separates path?query#fragment
221 SBuf params;
222 if (tok.skip('?')) {
223 params = tok.remaining();
224 Mgr::QueryParams::Parse(tok, cmd->params.queryParams);
225 }
226
227 if (!tok.skip('#') && !tok.atEnd())
228 throw TextException("invalid characters in URL", Here());
229 // else ignore #fragment (if any)
230
231 debugs(16, 3, "MGR request: host=" << uri.host() << ", action=" << action <<
232 ", password=" << passwd << ", params=" << params);
233
8822ebee 234 return cmd;
22f3fd98 235}
236
63be0a78 237/// \ingroup CacheManagerInternal
832c08ab
FC
238/*
239 \ingroup CacheManagerInternal
240 * Decodes the headers needed to perform user authentication and fills
241 * the details into the cachemgrStateData argument
242 */
c83f0bd5 243void
8822ebee 244CacheManager::ParseHeaders(const HttpRequest * request, Mgr::ActionParams &params)
63259c34 245{
8822ebee
AR
246 assert(request);
247
248 params.httpMethod = request->method.id();
249 params.httpFlags = request->flags;
250
9da6b594
AJ
251#if HAVE_AUTH_MODULE_BASIC
252 // TODO: use the authentication system decode to retrieve these details properly.
253
254 /* base 64 _decoded_ user:passwd pair */
2582f64a 255 const auto basic_cookie(request->header.getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
62e76326 256
2582f64a 257 if (basic_cookie.isEmpty())
62e76326 258 return;
259
2582f64a
AJ
260 const auto colonPos = basic_cookie.find(':');
261 if (colonPos == SBuf::npos) {
d816f28d 262 debugs(16, DBG_IMPORTANT, "ERROR: CacheManager::ParseHeaders: unknown basic_cookie format '" << basic_cookie << "'");
62e76326 263 return;
63259c34 264 }
62e76326 265
63259c34 266 /* found user:password pair, reset old values */
2582f64a
AJ
267 params.userName = SBufToString(basic_cookie.substr(0, colonPos));
268 params.password = SBufToString(basic_cookie.substr(colonPos+1));
62e76326 269
9da6b594 270 /* warning: this prints decoded password which maybe not be what you want to do @?@ @?@ */
8822ebee 271 debugs(16, 9, "CacheManager::ParseHeaders: got user: '" <<
d9fc6862 272 params.userName << "' passwd: '" << params.password << "'");
9da6b594 273#endif
63259c34 274}
275
63be0a78 276/**
277 \ingroup CacheManagerInternal
278 *
f53969cc
SM
279 \retval 0 if mgr->password is good or "none"
280 \retval 1 if mgr->password is "disable"
281 \retval !0 if mgr->password does not match configured password
22f3fd98 282 */
c83f0bd5 283int
8822ebee 284CacheManager::CheckPassword(const Mgr::Command &cmd)
22f3fd98 285{
8822ebee
AR
286 assert(cmd.profile != NULL);
287 const char *action = cmd.profile->name;
288 char *pwd = PasswdGet(Config.passwd_list, action);
03c4599f 289
8822ebee 290 debugs(16, 4, "CacheManager::CheckPassword for action " << action);
62e76326 291
22f3fd98 292 if (pwd == NULL)
8822ebee 293 return cmd.profile->isPwReq;
62e76326 294
22f3fd98 295 if (strcmp(pwd, "disable") == 0)
62e76326 296 return 1;
297
22f3fd98 298 if (strcmp(pwd, "none") == 0)
62e76326 299 return 0;
300
8822ebee 301 if (!cmd.params.password.size())
62e76326 302 return 1;
303
8822ebee 304 return cmd.params.password != pwd;
22f3fd98 305}
306
832c08ab
FC
307/**
308 \ingroup CacheManagerAPI
309 * Main entry point in the Cache Manager's activity. Gets called as part
310 * of the forward chain if the right URL is detected there. Initiates
311 * all needed internal work and renders the response.
312 */
22f3fd98 313void
7e6eabbc 314CacheManager::start(const Comm::ConnectionPointer &client, HttpRequest *request, StoreEntry *entry, const AccessLogEntry::Pointer &ale)
22f3fd98 315{
26e65059 316 debugs(16, 3, "request-url= '" << request->url << "', entry-url='" << entry->url() << "'");
62e76326 317
26e65059
AJ
318 Mgr::Command::Pointer cmd;
319 try {
320 cmd = ParseUrl(request->url);
321
322 } catch (...) {
323 debugs(16, 2, "request URL error: " << CurrentException);
7e6eabbc 324 const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request, ale);
3900307b 325 err->url = xstrdup(entry->url());
26e65059 326 err->detailError(new ExceptionErrorDetail(Here().id()));
62e76326 327 errorAppendEntry(entry, err);
328 entry->expires = squid_curtime;
329 return;
22f3fd98 330 }
62e76326 331
8822ebee 332 const char *actionName = cmd->profile->name;
34266cde 333
22f3fd98 334 entry->expires = squid_curtime;
34266cde 335
a750e510 336 debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");
34266cde 337
63259c34 338 /* get additional info from request headers */
8822ebee
AR
339 ParseHeaders(request, cmd->params);
340
341 const char *userName = cmd->params.userName.size() ?
d9fc6862 342 cmd->params.userName.termedBuf() : "unknown";
34266cde 343
22f3fd98 344 /* Check password */
62e76326 345
8822ebee 346 if (CheckPassword(*cmd) != 0) {
62e76326 347 /* build error message */
7e6eabbc 348 ErrorState errState(ERR_CACHE_MGR_ACCESS_DENIED, Http::scUnauthorized, request, ale);
62e76326 349 /* warn if user specified incorrect password */
350
8822ebee 351 if (cmd->params.password.size()) {
26ac0430 352 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
8822ebee 353 userName << "@" <<
5c336a3b 354 client << ": incorrect password for '" <<
8822ebee
AR
355 actionName << "'" );
356 } else {
26ac0430 357 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
8822ebee 358 userName << "@" <<
5c336a3b 359 client << ": password needed for '" <<
8822ebee
AR
360 actionName << "'" );
361 }
62e76326 362
913524f0 363 HttpReply *rep = errState.BuildHttpReply();
62e76326 364
9da6b594 365#if HAVE_AUTH_MODULE_BASIC
62e76326 366 /*
8822ebee
AR
367 * add Authenticate header using action name as a realm because
368 * password depends on the action
62e76326 369 */
8822ebee 370 rep->header.putAuth("Basic", actionName);
9da6b594 371#endif
3865965d 372 // Allow cachemgr and other XHR scripts access to our version string
789217a2
FC
373 if (request->header.has(Http::HdrType::ORIGIN)) {
374 rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
3865965d
AJ
375#if HAVE_AUTH_MODULE_BASIC
376 rep->header.putExt("Access-Control-Allow-Credentials","true");
377#endif
378 rep->header.putExt("Access-Control-Expose-Headers","Server");
379 }
62e76326 380
381 /* store the reply */
db237875 382 entry->replaceHttpReply(rep);
62e76326 383
384 entry->expires = squid_curtime;
385
386 entry->complete();
387
62e76326 388 return;
22f3fd98 389 }
62e76326 390
789217a2
FC
391 if (request->header.has(Http::HdrType::ORIGIN)) {
392 cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
3865965d
AJ
393 }
394
0be039f4 395 debugs(16, 2, "CacheManager: " <<
8822ebee 396 userName << "@" <<
5c336a3b 397 client << " requesting '" <<
8822ebee 398 actionName << "'" );
62e76326 399
b073fc4b
AJ
400 // special case: /squid-internal-mgr/ index page
401 if (!strcmp(cmd->profile->name, "index")) {
7e6eabbc 402 ErrorState err(MGR_INDEX, Http::scOkay, request, ale);
b073fc4b
AJ
403 err.url = xstrdup(entry->url());
404 HttpReply *rep = err.BuildHttpReply();
405 if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
9b769c67 406 rep->sline.set(Http::ProtocolVersion(1,1), Http::scNotFound);
b073fc4b 407 // Allow cachemgr and other XHR scripts access to our version string
789217a2
FC
408 if (request->header.has(Http::HdrType::ORIGIN)) {
409 rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
b073fc4b
AJ
410#if HAVE_AUTH_MODULE_BASIC
411 rep->header.putExt("Access-Control-Allow-Credentials","true");
412#endif
413 rep->header.putExt("Access-Control-Expose-Headers","Server");
414 }
415 entry->replaceHttpReply(rep);
416 entry->complete();
417 return;
418 }
419
8822ebee 420 if (UsingSmp() && IamWorkerProcess()) {
1b76e6c1 421 // is client the right connection to pass here?
7e6eabbc 422 AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry, ale));
8822ebee 423 return;
cb69b4c7 424 }
62e76326 425
8822ebee
AR
426 Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
427 Must(action != NULL);
428 action->run(entry, true);
22f3fd98 429}
430
832c08ab
FC
431/*
432 \ingroup CacheManagerInternal
433 * Renders the protection level text for an action.
434 * Also doubles as a check for the protection level.
832c08ab 435 */
c83f0bd5 436const char *
8822ebee 437CacheManager::ActionProtection(const Mgr::ActionProfile::Pointer &profile)
7395afb8 438{
8822ebee
AR
439 assert(profile != NULL);
440 const char *pwd = PasswdGet(Config.passwd_list, profile->name);
62e76326 441
7395afb8 442 if (!pwd)
8822ebee 443 return profile->isPwReq ? "hidden" : "public";
62e76326 444
7395afb8 445 if (!strcmp(pwd, "disable"))
62e76326 446 return "disabled";
447
7395afb8 448 if (strcmp(pwd, "none") == 0)
62e76326 449 return "public";
450
7395afb8 451 return "protected";
452}
453
832c08ab 454/*
ee82937c 455 * \ingroup CacheManagerInternal
832c08ab
FC
456 * gets from the global Config the password the user would need to supply
457 * for the action she queried
458 */
c83f0bd5 459char *
613924ee 460CacheManager::PasswdGet(Mgr::ActionPasswordList * a, const char *action)
22f3fd98 461{
a5f27c62
AJ
462 while (a) {
463 for (auto &w : a->actions) {
464 if (w.cmp(action) == 0)
62e76326 465 return a->passwd;
466
a5f27c62
AJ
467 static const SBuf allAction("all");
468 if (w == allAction)
62e76326 469 return a->passwd;
470 }
471
472 a = a->next;
22f3fd98 473 }
62e76326 474
22f3fd98 475 return NULL;
476}
c83f0bd5 477
c83f0bd5 478CacheManager*
26ac0430
AJ
479CacheManager::GetInstance()
480{
f0ffd7c3 481 static CacheManager *instance = nullptr;
7658a296
AJ
482 if (!instance) {
483 debugs(16, 6, "starting cachemanager up");
26ac0430 484 instance = new CacheManager;
8822ebee 485 Mgr::RegisterBasics();
26ac0430
AJ
486 }
487 return instance;
c83f0bd5 488}
53521734 489