]> git.ipfire.org Git - thirdparty/squid.git/blame - src/cache_manager.cc
CI: Remove unnecessary test-functionality test wrappers (#1393)
[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
832c08ab 155/**
7902bd5b
EB
156 * Parses the action requested by the user and checks via
157 * CacheManager::ActionProtection() that the item is accessible by the user.
26e65059
AJ
158 *
159 * Syntax:
160 *
7902bd5b 161 * [ scheme "://" authority ] '/squid-internal-mgr' path-absolute [ "?" query ] [ "#" fragment ]
26e65059 162 *
7902bd5b 163 * see RFC 3986 for definitions of scheme, authority, path-absolute, query
26e65059
AJ
164 *
165 * \returns Mgr::Command object with action to perform and parameters it might use
832c08ab 166 */
8822ebee 167Mgr::Command::Pointer
26e65059 168CacheManager::ParseUrl(const AnyP::Uri &uri)
22f3fd98 169{
26e65059 170 Parser::Tokenizer tok(uri.path());
8822ebee 171
26e65059 172 static const SBuf internalMagicPrefix("/squid-internal-mgr/");
7902bd5b 173 Assure(tok.skip(internalMagicPrefix));
62e76326 174
26e65059
AJ
175 Mgr::Command::Pointer cmd = new Mgr::Command();
176 cmd->params.httpUri = SBufToString(uri.absolute());
5366b99b 177
7902bd5b 178 static const auto fieldChars = CharacterSet("mgr-field", "?#").complement();
26e65059
AJ
179
180 SBuf action;
181 if (!tok.prefix(action, fieldChars)) {
7902bd5b
EB
182 static const SBuf indexReport("index");
183 action = indexReport;
22f3fd98 184 }
26e65059
AJ
185 cmd->params.actionName = SBufToString(action);
186
187 const auto profile = findAction(action.c_str());
188 if (!profile)
189 throw TextException(ToSBuf("action '", action, "' not found"), Here());
62e76326 190
8822ebee 191 const char *prot = ActionProtection(profile);
26e65059
AJ
192 if (!strcmp(prot, "disabled") || !strcmp(prot, "hidden"))
193 throw TextException(ToSBuf("action '", action, "' is ", prot), Here());
194 cmd->profile = profile;
195
26e65059
AJ
196 // TODO: fix when AnyP::Uri::parse() separates path?query#fragment
197 SBuf params;
198 if (tok.skip('?')) {
199 params = tok.remaining();
200 Mgr::QueryParams::Parse(tok, cmd->params.queryParams);
201 }
202
203 if (!tok.skip('#') && !tok.atEnd())
204 throw TextException("invalid characters in URL", Here());
205 // else ignore #fragment (if any)
206
7902bd5b 207 debugs(16, 3, "MGR request: host=" << uri.host() << ", action=" << action << ", params=" << params);
26e65059 208
8822ebee 209 return cmd;
22f3fd98 210}
211
63be0a78 212/// \ingroup CacheManagerInternal
832c08ab
FC
213/*
214 \ingroup CacheManagerInternal
215 * Decodes the headers needed to perform user authentication and fills
216 * the details into the cachemgrStateData argument
217 */
c83f0bd5 218void
8822ebee 219CacheManager::ParseHeaders(const HttpRequest * request, Mgr::ActionParams &params)
63259c34 220{
8822ebee
AR
221 assert(request);
222
223 params.httpMethod = request->method.id();
224 params.httpFlags = request->flags;
225
9da6b594
AJ
226#if HAVE_AUTH_MODULE_BASIC
227 // TODO: use the authentication system decode to retrieve these details properly.
228
229 /* base 64 _decoded_ user:passwd pair */
2582f64a 230 const auto basic_cookie(request->header.getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
62e76326 231
2582f64a 232 if (basic_cookie.isEmpty())
62e76326 233 return;
234
2582f64a
AJ
235 const auto colonPos = basic_cookie.find(':');
236 if (colonPos == SBuf::npos) {
d816f28d 237 debugs(16, DBG_IMPORTANT, "ERROR: CacheManager::ParseHeaders: unknown basic_cookie format '" << basic_cookie << "'");
62e76326 238 return;
63259c34 239 }
62e76326 240
63259c34 241 /* found user:password pair, reset old values */
2582f64a
AJ
242 params.userName = SBufToString(basic_cookie.substr(0, colonPos));
243 params.password = SBufToString(basic_cookie.substr(colonPos+1));
62e76326 244
9da6b594 245 /* warning: this prints decoded password which maybe not be what you want to do @?@ @?@ */
8822ebee 246 debugs(16, 9, "CacheManager::ParseHeaders: got user: '" <<
d9fc6862 247 params.userName << "' passwd: '" << params.password << "'");
9da6b594 248#endif
63259c34 249}
250
63be0a78 251/**
252 \ingroup CacheManagerInternal
253 *
f53969cc
SM
254 \retval 0 if mgr->password is good or "none"
255 \retval 1 if mgr->password is "disable"
256 \retval !0 if mgr->password does not match configured password
22f3fd98 257 */
c83f0bd5 258int
8822ebee 259CacheManager::CheckPassword(const Mgr::Command &cmd)
22f3fd98 260{
aee3523a 261 assert(cmd.profile != nullptr);
8822ebee
AR
262 const char *action = cmd.profile->name;
263 char *pwd = PasswdGet(Config.passwd_list, action);
03c4599f 264
8822ebee 265 debugs(16, 4, "CacheManager::CheckPassword for action " << action);
62e76326 266
aee3523a 267 if (pwd == nullptr)
8822ebee 268 return cmd.profile->isPwReq;
62e76326 269
22f3fd98 270 if (strcmp(pwd, "disable") == 0)
62e76326 271 return 1;
272
22f3fd98 273 if (strcmp(pwd, "none") == 0)
62e76326 274 return 0;
275
8822ebee 276 if (!cmd.params.password.size())
62e76326 277 return 1;
278
8822ebee 279 return cmd.params.password != pwd;
22f3fd98 280}
281
832c08ab
FC
282/**
283 \ingroup CacheManagerAPI
284 * Main entry point in the Cache Manager's activity. Gets called as part
285 * of the forward chain if the right URL is detected there. Initiates
286 * all needed internal work and renders the response.
287 */
22f3fd98 288void
7e6eabbc 289CacheManager::start(const Comm::ConnectionPointer &client, HttpRequest *request, StoreEntry *entry, const AccessLogEntry::Pointer &ale)
22f3fd98 290{
26e65059 291 debugs(16, 3, "request-url= '" << request->url << "', entry-url='" << entry->url() << "'");
62e76326 292
26e65059
AJ
293 Mgr::Command::Pointer cmd;
294 try {
295 cmd = ParseUrl(request->url);
296
297 } catch (...) {
298 debugs(16, 2, "request URL error: " << CurrentException);
7e6eabbc 299 const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request, ale);
3900307b 300 err->url = xstrdup(entry->url());
26e65059 301 err->detailError(new ExceptionErrorDetail(Here().id()));
62e76326 302 errorAppendEntry(entry, err);
303 entry->expires = squid_curtime;
304 return;
22f3fd98 305 }
62e76326 306
8822ebee 307 const char *actionName = cmd->profile->name;
34266cde 308
22f3fd98 309 entry->expires = squid_curtime;
34266cde 310
a750e510 311 debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");
34266cde 312
63259c34 313 /* get additional info from request headers */
8822ebee
AR
314 ParseHeaders(request, cmd->params);
315
316 const char *userName = cmd->params.userName.size() ?
d9fc6862 317 cmd->params.userName.termedBuf() : "unknown";
34266cde 318
22f3fd98 319 /* Check password */
62e76326 320
8822ebee 321 if (CheckPassword(*cmd) != 0) {
62e76326 322 /* build error message */
7e6eabbc 323 ErrorState errState(ERR_CACHE_MGR_ACCESS_DENIED, Http::scUnauthorized, request, ale);
62e76326 324 /* warn if user specified incorrect password */
325
8822ebee 326 if (cmd->params.password.size()) {
26ac0430 327 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
8822ebee 328 userName << "@" <<
5c336a3b 329 client << ": incorrect password for '" <<
8822ebee
AR
330 actionName << "'" );
331 } else {
26ac0430 332 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
8822ebee 333 userName << "@" <<
5c336a3b 334 client << ": password needed for '" <<
8822ebee
AR
335 actionName << "'" );
336 }
62e76326 337
913524f0 338 HttpReply *rep = errState.BuildHttpReply();
62e76326 339
9da6b594 340#if HAVE_AUTH_MODULE_BASIC
62e76326 341 /*
8822ebee
AR
342 * add Authenticate header using action name as a realm because
343 * password depends on the action
62e76326 344 */
8822ebee 345 rep->header.putAuth("Basic", actionName);
9da6b594 346#endif
92a5adb7
AR
347
348 const auto originOrNil = request->header.getStr(Http::HdrType::ORIGIN);
349 PutCommonResponseHeaders(*rep, originOrNil);
62e76326 350
351 /* store the reply */
db237875 352 entry->replaceHttpReply(rep);
62e76326 353
354 entry->expires = squid_curtime;
355
356 entry->complete();
357
62e76326 358 return;
22f3fd98 359 }
62e76326 360
789217a2
FC
361 if (request->header.has(Http::HdrType::ORIGIN)) {
362 cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
3865965d
AJ
363 }
364
0be039f4 365 debugs(16, 2, "CacheManager: " <<
8822ebee 366 userName << "@" <<
5c336a3b 367 client << " requesting '" <<
8822ebee 368 actionName << "'" );
62e76326 369
b073fc4b
AJ
370 // special case: /squid-internal-mgr/ index page
371 if (!strcmp(cmd->profile->name, "index")) {
7e6eabbc 372 ErrorState err(MGR_INDEX, Http::scOkay, request, ale);
b073fc4b
AJ
373 err.url = xstrdup(entry->url());
374 HttpReply *rep = err.BuildHttpReply();
375 if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
9b769c67 376 rep->sline.set(Http::ProtocolVersion(1,1), Http::scNotFound);
92a5adb7
AR
377
378 const auto originOrNil = request->header.getStr(Http::HdrType::ORIGIN);
379 PutCommonResponseHeaders(*rep, originOrNil);
380
b073fc4b
AJ
381 entry->replaceHttpReply(rep);
382 entry->complete();
383 return;
384 }
385
8822ebee 386 if (UsingSmp() && IamWorkerProcess()) {
1b76e6c1 387 // is client the right connection to pass here?
7e6eabbc 388 AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry, ale));
8822ebee 389 return;
cb69b4c7 390 }
62e76326 391
8822ebee 392 Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
aee3523a 393 Must(action != nullptr);
8822ebee 394 action->run(entry, true);
22f3fd98 395}
396
832c08ab
FC
397/*
398 \ingroup CacheManagerInternal
399 * Renders the protection level text for an action.
400 * Also doubles as a check for the protection level.
832c08ab 401 */
c83f0bd5 402const char *
8822ebee 403CacheManager::ActionProtection(const Mgr::ActionProfile::Pointer &profile)
7395afb8 404{
aee3523a 405 assert(profile != nullptr);
8822ebee 406 const char *pwd = PasswdGet(Config.passwd_list, profile->name);
62e76326 407
7395afb8 408 if (!pwd)
8822ebee 409 return profile->isPwReq ? "hidden" : "public";
62e76326 410
7395afb8 411 if (!strcmp(pwd, "disable"))
62e76326 412 return "disabled";
413
7395afb8 414 if (strcmp(pwd, "none") == 0)
62e76326 415 return "public";
416
7395afb8 417 return "protected";
418}
419
832c08ab 420/*
ee82937c 421 * \ingroup CacheManagerInternal
832c08ab
FC
422 * gets from the global Config the password the user would need to supply
423 * for the action she queried
424 */
c83f0bd5 425char *
613924ee 426CacheManager::PasswdGet(Mgr::ActionPasswordList * a, const char *action)
22f3fd98 427{
a5f27c62
AJ
428 while (a) {
429 for (auto &w : a->actions) {
430 if (w.cmp(action) == 0)
62e76326 431 return a->passwd;
432
a5f27c62
AJ
433 static const SBuf allAction("all");
434 if (w == allAction)
62e76326 435 return a->passwd;
436 }
437
438 a = a->next;
22f3fd98 439 }
62e76326 440
aee3523a 441 return nullptr;
22f3fd98 442}
c83f0bd5 443
92a5adb7
AR
444void
445CacheManager::PutCommonResponseHeaders(HttpReply &response, const char *httpOrigin)
446{
447 // Allow cachemgr and other XHR scripts access to our version string
448 if (httpOrigin) {
449 response.header.putExt("Access-Control-Allow-Origin", httpOrigin);
450#if HAVE_AUTH_MODULE_BASIC
451 response.header.putExt("Access-Control-Allow-Credentials", "true");
452#endif
453 response.header.putExt("Access-Control-Expose-Headers", "Server");
454 }
455
456 std::unique_ptr<HttpHdrCc> cc(new HttpHdrCc());
457 // this is honored by more caches but allows pointless revalidation;
458 // revalidation will always fail because we do not support it (yet?)
459 cc->noCache(String());
460 // this is honored by fewer caches but prohibits pointless revalidation
461 cc->noStore(true);
462 response.putCc(cc.release());
463}
464
c83f0bd5 465CacheManager*
26ac0430
AJ
466CacheManager::GetInstance()
467{
f0ffd7c3 468 static CacheManager *instance = nullptr;
7658a296
AJ
469 if (!instance) {
470 debugs(16, 6, "starting cachemanager up");
26ac0430 471 instance = new CacheManager;
8822ebee 472 Mgr::RegisterBasics();
26ac0430
AJ
473 }
474 return instance;
c83f0bd5 475}
53521734 476