Squid Web Cache master
Loading...
Searching...
No Matches
cache_manager.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 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/Stream.h"
18#include "errorpage.h"
19#include "fde.h"
20#include "HttpHdrCc.h"
21#include "HttpReply.h"
22#include "HttpRequest.h"
23#include "mgr/Action.h"
24#include "mgr/ActionCreator.h"
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"
31#include "mgr/QueryParams.h"
32#include "parser/Tokenizer.h"
33#include "protos.h"
34#include "sbuf/Stream.h"
35#include "sbuf/StringConvert.h"
36#include "SquidConfig.h"
37#include "Store.h"
38#include "tools.h"
39#include "wordlist.h"
40
41#include <algorithm>
42#include <memory>
43
45#define MGR_PASSWD_SZ 128
46
47void
49{
50 Must(profile != nullptr);
51 if (!CacheManager::findAction(profile->name)) {
52 menu_.push_back(profile);
53 debugs(16, 3, "registered profile: " << *profile);
54 } else {
55 debugs(16, 2, "skipped duplicate profile: " << *profile);
56 }
57}
58
66CacheManager::findAction(char const * action) const
67{
68 Must(action != nullptr);
69 Menu::const_iterator a;
70
71 debugs(16, 5, "CacheManager::findAction: looking for action " << action);
72 for (a = menu_.begin(); a != menu_.end(); ++a) {
73 if (0 == strcmp((*a)->name, action)) {
74 debugs(16, 6, " found");
75 return *a;
76 }
77 }
78
79 debugs(16, 6, "Action not found.");
81}
82
84CacheManager::createNamedAction(const char *actionName)
85{
86 Must(actionName);
87
89 cmd->profile = findAction(actionName);
90 cmd->params.actionName = actionName;
91
92 Must(cmd->profile != nullptr);
93 return cmd->profile->creator->create(cmd);
94}
95
98{
100 cmd->params = params;
101 cmd->profile = findAction(params.actionName.termedBuf());
102 Must(cmd->profile != nullptr);
103 return cmd->profile->creator->create(cmd);
104}
105
106const SBuf &
108{
109 static const SBuf prefix("/squid-internal-mgr/");
110 return prefix;
111}
112
127{
129
131
133 cmd->params.httpUri = SBufToString(uri.absolute());
134
135 static const auto fieldChars = CharacterSet("mgr-field", "?#").complement();
136
137 SBuf action;
138 if (!tok.prefix(action, fieldChars)) {
139 static const SBuf indexReport("index");
140 action = indexReport;
141 }
142 cmd->params.actionName = SBufToString(action);
143
144 const auto profile = findAction(action.c_str());
145 if (!profile)
146 throw TextException(ToSBuf("action '", action, "' not found"), Here());
147
148 const char *prot = ActionProtection(profile);
149 if (!strcmp(prot, "disabled") || !strcmp(prot, "hidden"))
150 throw TextException(ToSBuf("action '", action, "' is ", prot), Here());
151 cmd->profile = profile;
152
153 // TODO: fix when AnyP::Uri::parse() separates path?query#fragment
154 SBuf params;
155 if (tok.skip('?')) {
156 params = tok.remaining();
157 Mgr::QueryParams::Parse(tok, cmd->params.queryParams);
158 }
159
160 if (!tok.skip('#') && !tok.atEnd())
161 throw TextException("invalid characters in URL", Here());
162 // else ignore #fragment (if any)
163
164 debugs(16, 3, "MGR request: host=" << uri.host() << ", action=" << action << ", params=" << params);
165
166 return cmd;
167}
168
170/*
171 \ingroup CacheManagerInternal
172 * Decodes the headers needed to perform user authentication and fills
173 * the details into the cachemgrStateData argument
174 */
175void
177{
178 assert(request);
179
180 params.httpMethod = request->method.id();
181 params.httpFlags = request->flags;
182
183#if HAVE_AUTH_MODULE_BASIC
184 // TODO: use the authentication system decode to retrieve these details properly.
185
186 /* base 64 _decoded_ user:passwd pair */
187 const auto basic_cookie(request->header.getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
188
189 if (basic_cookie.isEmpty())
190 return;
191
192 const auto colonPos = basic_cookie.find(':');
193 if (colonPos == SBuf::npos) {
194 debugs(16, DBG_IMPORTANT, "ERROR: CacheManager::ParseHeaders: unknown basic_cookie format '" << basic_cookie << "'");
195 return;
196 }
197
198 /* found user:password pair, reset old values */
199 params.userName = SBufToString(basic_cookie.substr(0, colonPos));
200 params.password = SBufToString(basic_cookie.substr(colonPos+1));
201
202 /* warning: this prints decoded password which maybe not be what you want to do @?@ @?@ */
203 debugs(16, 9, "CacheManager::ParseHeaders: got user: '" <<
204 params.userName << "' passwd: '" << params.password << "'");
205#endif
206}
207
215int
217{
218 assert(cmd.profile != nullptr);
219 const char *action = cmd.profile->name;
220 char *pwd = PasswdGet(Config.passwd_list, action);
221
222 debugs(16, 4, "CacheManager::CheckPassword for action " << action);
223
224 if (pwd == nullptr)
225 return cmd.profile->isPwReq;
226
227 if (strcmp(pwd, "disable") == 0)
228 return 1;
229
230 if (strcmp(pwd, "none") == 0)
231 return 0;
232
233 if (!cmd.params.password.size())
234 return 1;
235
236 return cmd.params.password != pwd;
237}
238
245void
247{
248 debugs(16, 3, "request-url= '" << request->url << "', entry-url='" << entry->url() << "'");
249
251 try {
252 cmd = ParseUrl(request->url);
253
254 } catch (...) {
255 debugs(16, 2, "request URL error: " << CurrentException);
256 const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request, ale);
257 err->url = xstrdup(entry->url());
258 err->detailError(new ExceptionErrorDetail(Here().id()));
259 errorAppendEntry(entry, err);
260 return;
261 }
262
263 const char *actionName = cmd->profile->name;
264
265 entry->expires = squid_curtime;
266
267 debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");
268
269 /* get additional info from request headers */
270 ParseHeaders(request, cmd->params);
271
272 const char *userName = cmd->params.userName.size() ?
273 cmd->params.userName.termedBuf() : "unknown";
274
275 /* Check password */
276
277 if (CheckPassword(*cmd) != 0) {
278 /* build error message */
280 /* warn if user specified incorrect password */
281
282 if (cmd->params.password.size()) {
283 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
284 userName << "@" <<
285 client << ": incorrect password for '" <<
286 actionName << "'" );
287 } else {
288 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
289 userName << "@" <<
290 client << ": password needed for '" <<
291 actionName << "'" );
292 }
293
294 HttpReply *rep = errState.BuildHttpReply();
295
296#if HAVE_AUTH_MODULE_BASIC
297 /*
298 * add Authenticate header using action name as a realm because
299 * password depends on the action
300 */
301 rep->header.putAuth("Basic", actionName);
302#endif
303
304 const auto originOrNil = request->header.getStr(Http::HdrType::ORIGIN);
305 PutCommonResponseHeaders(*rep, originOrNil);
306
307 /* store the reply */
308 entry->replaceHttpReply(rep);
309
310 entry->expires = squid_curtime;
311
312 entry->complete();
313
314 return;
315 }
316
317 if (request->header.has(Http::HdrType::ORIGIN)) {
318 cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
319 }
320
321 debugs(16, 2, "CacheManager: " <<
322 userName << "@" <<
323 client << " requesting '" <<
324 actionName << "'" );
325
326 // special case: an index page
327 if (!strcmp(cmd->profile->name, "index")) {
328 ErrorState err(MGR_INDEX, Http::scOkay, request, ale);
329 err.url = xstrdup(entry->url());
330 HttpReply *rep = err.BuildHttpReply();
331 if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
333
334 const auto originOrNil = request->header.getStr(Http::HdrType::ORIGIN);
335 PutCommonResponseHeaders(*rep, originOrNil);
336
337 entry->replaceHttpReply(rep);
338 entry->complete();
339 return;
340 }
341
342 if (UsingSmp() && IamWorkerProcess()) {
343 // is client the right connection to pass here?
344 AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry, ale));
345 return;
346 }
347
348 Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
349 Must(action != nullptr);
350 action->run(entry, true);
351}
352
353/*
354 \ingroup CacheManagerInternal
355 * Renders the protection level text for an action.
356 * Also doubles as a check for the protection level.
357 */
358const char *
360{
361 assert(profile != nullptr);
362 const char *pwd = PasswdGet(Config.passwd_list, profile->name);
363
364 if (!pwd)
365 return profile->isPwReq ? "hidden" : "public";
366
367 if (!strcmp(pwd, "disable"))
368 return "disabled";
369
370 if (strcmp(pwd, "none") == 0)
371 return "public";
372
373 return "protected";
374}
375
376/*
377 * \ingroup CacheManagerInternal
378 * gets from the global Config the password the user would need to supply
379 * for the action she queried
380 */
381char *
383{
384 while (a) {
385 for (auto &w : a->actions) {
386 if (w.cmp(action) == 0)
387 return a->passwd;
388
389 static const SBuf allAction("all");
390 if (w == allAction)
391 return a->passwd;
392 }
393
394 a = a->next;
395 }
396
397 return nullptr;
398}
399
400void
401CacheManager::PutCommonResponseHeaders(HttpReply &response, const char *httpOrigin)
402{
403 // Allow cachemgr and other XHR scripts access to our version string
404 if (httpOrigin) {
405 response.header.putExt("Access-Control-Allow-Origin", httpOrigin);
406#if HAVE_AUTH_MODULE_BASIC
407 response.header.putExt("Access-Control-Allow-Credentials", "true");
408#endif
409 response.header.putExt("Access-Control-Expose-Headers", "Server");
410 }
411
412 HttpHdrCc cc;
413 // this is honored by more caches but allows pointless revalidation;
414 // revalidation will always fail because we do not support it (yet?)
415 cc.noCache(String());
416 // this is honored by fewer caches but prohibits pointless revalidation
417 cc.noStore(true);
418 response.putCc(cc);
419}
420
423{
424 static CacheManager *instance = nullptr;
425 if (!instance) {
426 debugs(16, 6, "starting cachemanager up");
427 instance = new CacheManager;
429 }
430 return instance;
431}
432
#define Assure(condition)
Definition Assure.h:35
#define Here()
source code location of the caller
Definition Here.h:15
time_t squid_curtime
class SquidConfig Config
String SBufToString(const SBuf &s)
std::ostream & CurrentException(std::ostream &os)
prints active (i.e., thrown but not yet handled) exception
#define Must(condition)
#define assert(EX)
Definition assert.h:17
void path(const char *p)
Definition Uri.h:96
SBuf & absolute() const
Definition Uri.cc:743
void host(const char *src)
Definition Uri.cc:154
static void Start(const Pointer &job)
Definition AsyncJob.cc:37
char * PasswdGet(Mgr::ActionPasswordList *, const char *)
const char * ActionProtection(const Mgr::ActionProfilePointer &profile)
static void PutCommonResponseHeaders(HttpReply &, const char *httpOrigin)
Mgr::ActionProfilePointer findAction(char const *action) const
void ParseHeaders(const HttpRequest *request, Mgr::ActionParams &params)
Mgr::Action::Pointer createRequestedAction(const Mgr::ActionParams &)
static CacheManager * GetInstance()
int CheckPassword(const Mgr::Command &cmd)
void registerProfile(const Mgr::ActionProfilePointer &)
remembers the given profile while ignoring attempts to register a same-name duplicate
static const SBuf & WellKnownUrlPathPrefix()
initial URL path characters that identify cache manager requests
Mgr::Action::Pointer createNamedAction(const char *actionName)
CacheManager()
use Instance() instead
Mgr::CommandPointer ParseUrl(const AnyP::Uri &)
void start(const Comm::ConnectionPointer &client, HttpRequest *request, StoreEntry *entry, const AccessLogEntryPointer &ale)
optimized set of C chars, with quick membership test and merge support
CharacterSet complement(const char *complementLabel=nullptr) const
char * url
Definition errorpage.h:178
HttpReply * BuildHttpReply(void)
const char * content() const
Definition HttpBody.h:44
void noCache(const String &v)
Definition HttpHdrCc.h:90
void noStore(bool v)
Definition HttpHdrCc.h:103
SBuf getAuthToken(Http::HdrType id, const char *auth_scheme) const
const char * getStr(Http::HdrType id) const
int has(Http::HdrType id) const
void putAuth(const char *auth_scheme, const char *realm)
void putExt(const char *name, const char *value)
Http::StatusLine sline
Definition HttpReply.h:56
HttpBody body
Definition HttpReply.h:58
Http::MethodType id() const
HttpRequestMethod method
RequestFlags flags
AnyP::Uri url
the request URI
HttpHeader header
Definition Message.h:74
void putCc(const HttpHdrCc &)
Definition Message.cc:33
void set(const AnyP::ProtocolVersion &newVersion, Http::StatusCode newStatus, const char *newReason=nullptr)
Definition StatusLine.cc:35
Cache Manager Action parameters extracted from the user request.
String userName
user login name; currently only used for logging
String password
user password; used for acceptance check and cleared
String actionName
action name (and credentials realm)
RequestFlags httpFlags
HTTP request flags.
HttpRequestMethod httpMethod
HTTP request method.
list of cachemgr password authorization definitions. Currently a POD.
ActionPasswordList * next
combined hard-coded action profile with user-supplied action parameters
Definition Command.h:22
ActionParams params
user-supplied action arguments
Definition Command.h:28
ActionProfilePointer profile
hard-coded action specification
Definition Command.h:27
static void Parse(Parser::Tokenizer &, QueryParams &)
parses the query string parameters
Definition SBuf.h:94
static const size_type npos
Definition SBuf.h:100
const char * c_str()
Definition SBuf.cc:516
Mgr::ActionPasswordList * passwd_list
const char * url() const
Definition store.cc:1566
void complete()
Definition store.cc:1031
time_t expires
Definition Store.h:225
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition store.cc:1705
char const * termedBuf() const
Definition SquidString.h:93
size_type size() const
Definition SquidString.h:74
an std::runtime_error with thrower location info
#define DBG_IMPORTANT
Definition Stream.h:38
#define debugs(SECTION, LEVEL, CONTENT)
Definition Stream.h:192
@ ERR_CACHE_MGR_ACCESS_DENIED
Definition forward.h:20
@ ERR_INVALID_URL
Definition forward.h:45
@ MGR_INDEX
Definition forward.h:86
void errorAppendEntry(StoreEntry *entry, ErrorState *err)
Definition errorpage.cc:738
@ scUnauthorized
Definition StatusCode.h:46
@ scNotFound
Definition StatusCode.h:49
@ scOkay
Definition StatusCode.h:27
AnyP::ProtocolVersion ProtocolVersion()
RefCount< ActionProfile > ActionProfilePointer
Definition forward.h:32
void RegisterBasics()
Registers profiles for the actions above; TODO: move elsewhere?
#define xstrdup
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
Definition Stream.h:63
Definition parse.c:160
bool IamWorkerProcess()
whether the current process handles HTTP transactions and such
Definition stub_tools.cc:47
bool UsingSmp()
Whether there should be more than one worker process running.
Definition tools.cc:697