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