cache_manager.cc
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2023 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
49{
50public:
52
53public:
54 ClassActionCreator(Handler *aHandler): handler(aHandler) {}
55
57 return handler(cmd);
58 }
59
60private:
62};
63
65void
67{
68 Must(profile != nullptr);
69 if (!CacheManager::findAction(profile->name)) {
70 menu_.push_back(profile);
71 debugs(16, 3, "registered profile: " << *profile);
72 } else {
73 debugs(16, 2, "skipped duplicate profile: " << *profile);
74 }
75}
76
83void
84CacheManager::registerProfile(char const * action, char const * desc, OBJH * handler, int pw_req_flag, int atomic)
85{
86 debugs(16, 3, "registering legacy " << action);
88 desc, pw_req_flag, atomic, new Mgr::FunActionCreator(handler));
89 registerProfile(profile);
90}
91
98void
99CacheManager::registerProfile(char const * action, char const * desc,
101 int pw_req_flag, int atomic)
102{
104 desc, pw_req_flag, atomic, new ClassActionCreator(handler));
105 registerProfile(profile);
106}
107
116{
117 Must(action != nullptr);
118 Menu::const_iterator a;
119
120 debugs(16, 5, "CacheManager::findAction: looking for action " << action);
121 for (a = menu_.begin(); a != menu_.end(); ++a) {
122 if (0 == strcmp((*a)->name, action)) {
123 debugs(16, 6, " found");
124 return *a;
125 }
126 }
127
128 debugs(16, 6, "Action not found.");
130}
131
133CacheManager::createNamedAction(const char *actionName)
134{
135 Must(actionName);
136
138 cmd->profile = findAction(actionName);
139 cmd->params.actionName = actionName;
140
141 Must(cmd->profile != nullptr);
142 return cmd->profile->creator->create(cmd);
143}
144
147{
149 cmd->params = params;
150 cmd->profile = findAction(params.actionName.termedBuf());
151 Must(cmd->profile != nullptr);
152 return cmd->profile->creator->create(cmd);
153}
154
155const SBuf &
157{
158 static const SBuf prefix("/squid-internal-mgr/");
159 return prefix;
160}
161
176{
178
180
182 cmd->params.httpUri = SBufToString(uri.absolute());
183
184 static const auto fieldChars = CharacterSet("mgr-field", "?#").complement();
185
186 SBuf action;
187 if (!tok.prefix(action, fieldChars)) {
188 static const SBuf indexReport("index");
189 action = indexReport;
190 }
191 cmd->params.actionName = SBufToString(action);
192
193 const auto profile = findAction(action.c_str());
194 if (!profile)
195 throw TextException(ToSBuf("action '", action, "' not found"), Here());
196
197 const char *prot = ActionProtection(profile);
198 if (!strcmp(prot, "disabled") || !strcmp(prot, "hidden"))
199 throw TextException(ToSBuf("action '", action, "' is ", prot), Here());
200 cmd->profile = profile;
201
202 // TODO: fix when AnyP::Uri::parse() separates path?query#fragment
203 SBuf params;
204 if (tok.skip('?')) {
205 params = tok.remaining();
206 Mgr::QueryParams::Parse(tok, cmd->params.queryParams);
207 }
208
209 if (!tok.skip('#') && !tok.atEnd())
210 throw TextException("invalid characters in URL", Here());
211 // else ignore #fragment (if any)
212
213 debugs(16, 3, "MGR request: host=" << uri.host() << ", action=" << action << ", params=" << params);
214
215 return cmd;
216}
217
219/*
220 \ingroup CacheManagerInternal
221 * Decodes the headers needed to perform user authentication and fills
222 * the details into the cachemgrStateData argument
223 */
224void
226{
227 assert(request);
228
229 params.httpMethod = request->method.id();
230 params.httpFlags = request->flags;
231
232#if HAVE_AUTH_MODULE_BASIC
233 // TODO: use the authentication system decode to retrieve these details properly.
234
235 /* base 64 _decoded_ user:passwd pair */
236 const auto basic_cookie(request->header.getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
237
238 if (basic_cookie.isEmpty())
239 return;
240
241 const auto colonPos = basic_cookie.find(':');
242 if (colonPos == SBuf::npos) {
243 debugs(16, DBG_IMPORTANT, "ERROR: CacheManager::ParseHeaders: unknown basic_cookie format '" << basic_cookie << "'");
244 return;
245 }
246
247 /* found user:password pair, reset old values */
248 params.userName = SBufToString(basic_cookie.substr(0, colonPos));
249 params.password = SBufToString(basic_cookie.substr(colonPos+1));
250
251 /* warning: this prints decoded password which maybe not be what you want to do @?@ @?@ */
252 debugs(16, 9, "CacheManager::ParseHeaders: got user: '" <<
253 params.userName << "' passwd: '" << params.password << "'");
254#endif
255}
256
264int
266{
267 assert(cmd.profile != nullptr);
268 const char *action = cmd.profile->name;
269 char *pwd = PasswdGet(Config.passwd_list, action);
270
271 debugs(16, 4, "CacheManager::CheckPassword for action " << action);
272
273 if (pwd == nullptr)
274 return cmd.profile->isPwReq;
275
276 if (strcmp(pwd, "disable") == 0)
277 return 1;
278
279 if (strcmp(pwd, "none") == 0)
280 return 0;
281
282 if (!cmd.params.password.size())
283 return 1;
284
285 return cmd.params.password != pwd;
286}
287
294void
296{
297 debugs(16, 3, "request-url= '" << request->url << "', entry-url='" << entry->url() << "'");
298
300 try {
301 cmd = ParseUrl(request->url);
302
303 } catch (...) {
304 debugs(16, 2, "request URL error: " << CurrentException);
305 const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request, ale);
306 err->url = xstrdup(entry->url());
307 err->detailError(new ExceptionErrorDetail(Here().id()));
308 errorAppendEntry(entry, err);
309 entry->expires = squid_curtime;
310 return;
311 }
312
313 const char *actionName = cmd->profile->name;
314
315 entry->expires = squid_curtime;
316
317 debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");
318
319 /* get additional info from request headers */
320 ParseHeaders(request, cmd->params);
321
322 const char *userName = cmd->params.userName.size() ?
323 cmd->params.userName.termedBuf() : "unknown";
324
325 /* Check password */
326
327 if (CheckPassword(*cmd) != 0) {
328 /* build error message */
330 /* warn if user specified incorrect password */
331
332 if (cmd->params.password.size()) {
333 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
334 userName << "@" <<
335 client << ": incorrect password for '" <<
336 actionName << "'" );
337 } else {
338 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
339 userName << "@" <<
340 client << ": password needed for '" <<
341 actionName << "'" );
342 }
343
344 HttpReply *rep = errState.BuildHttpReply();
345
346#if HAVE_AUTH_MODULE_BASIC
347 /*
348 * add Authenticate header using action name as a realm because
349 * password depends on the action
350 */
351 rep->header.putAuth("Basic", actionName);
352#endif
353
354 const auto originOrNil = request->header.getStr(Http::HdrType::ORIGIN);
355 PutCommonResponseHeaders(*rep, originOrNil);
356
357 /* store the reply */
358 entry->replaceHttpReply(rep);
359
360 entry->expires = squid_curtime;
361
362 entry->complete();
363
364 return;
365 }
366
367 if (request->header.has(Http::HdrType::ORIGIN)) {
368 cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
369 }
370
371 debugs(16, 2, "CacheManager: " <<
372 userName << "@" <<
373 client << " requesting '" <<
374 actionName << "'" );
375
376 // special case: an index page
377 if (!strcmp(cmd->profile->name, "index")) {
378 ErrorState err(MGR_INDEX, Http::scOkay, request, ale);
379 err.url = xstrdup(entry->url());
380 HttpReply *rep = err.BuildHttpReply();
381 if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
383
384 const auto originOrNil = request->header.getStr(Http::HdrType::ORIGIN);
385 PutCommonResponseHeaders(*rep, originOrNil);
386
387 entry->replaceHttpReply(rep);
388 entry->complete();
389 return;
390 }
391
392 if (UsingSmp() && IamWorkerProcess()) {
393 // is client the right connection to pass here?
394 AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry, ale));
395 return;
396 }
397
398 Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
399 Must(action != nullptr);
400 action->run(entry, true);
401}
402
403/*
404 \ingroup CacheManagerInternal
405 * Renders the protection level text for an action.
406 * Also doubles as a check for the protection level.
407 */
408const char *
410{
411 assert(profile != nullptr);
412 const char *pwd = PasswdGet(Config.passwd_list, profile->name);
413
414 if (!pwd)
415 return profile->isPwReq ? "hidden" : "public";
416
417 if (!strcmp(pwd, "disable"))
418 return "disabled";
419
420 if (strcmp(pwd, "none") == 0)
421 return "public";
422
423 return "protected";
424}
425
426/*
427 * \ingroup CacheManagerInternal
428 * gets from the global Config the password the user would need to supply
429 * for the action she queried
430 */
431char *
433{
434 while (a) {
435 for (auto &w : a->actions) {
436 if (w.cmp(action) == 0)
437 return a->passwd;
438
439 static const SBuf allAction("all");
440 if (w == allAction)
441 return a->passwd;
442 }
443
444 a = a->next;
445 }
446
447 return nullptr;
448}
449
450void
451CacheManager::PutCommonResponseHeaders(HttpReply &response, const char *httpOrigin)
452{
453 // Allow cachemgr and other XHR scripts access to our version string
454 if (httpOrigin) {
455 response.header.putExt("Access-Control-Allow-Origin", httpOrigin);
456#if HAVE_AUTH_MODULE_BASIC
457 response.header.putExt("Access-Control-Allow-Credentials", "true");
458#endif
459 response.header.putExt("Access-Control-Expose-Headers", "Server");
460 }
461
462 HttpHdrCc cc;
463 // this is honored by more caches but allows pointless revalidation;
464 // revalidation will always fail because we do not support it (yet?)
465 cc.noCache(String());
466 // this is honored by fewer caches but prohibits pointless revalidation
467 cc.noStore(true);
468 response.putCc(cc);
469}
470
473{
474 static CacheManager *instance = nullptr;
475 if (!instance) {
476 debugs(16, 6, "starting cachemanager up");
479 }
480 return instance;
481}
482
#define Assure(condition)
Definition: Assure.h:35
#define Here()
source code location of the caller
Definition: Here.h:15
time_t squid_curtime
Definition: stub_libtime.cc:20
class SquidConfig Config
Definition: SquidConfig.cc:12
String SBufToString(const SBuf &s)
Definition: StringConvert.h:26
std::ostream & CurrentException(std::ostream &os)
prints active (i.e., thrown but not yet handled) exception
#define Must(condition)
Definition: TextException.h:75
#define assert(EX)
Definition: assert.h:17
Definition: Uri.h:31
void path(const char *p)
Definition: Uri.h:101
SBuf & absolute() const
Definition: Uri.cc:668
void host(const char *src)
Definition: Uri.cc:100
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)
static const SBuf & WellKnownUrlPathPrefix()
initial URL path characters that identify cache manager requests
Mgr::Action::Pointer createNamedAction(const char *actionName)
void registerProfile(char const *action, char const *desc, OBJH *handler, int pw_req_flag, int atomic)
CacheManager()
use Instance() instead
Definition: CacheManager.h:62
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
Definition: CharacterSet.h:18
CharacterSet complement(const char *complementLabel=nullptr) const
Definition: CharacterSet.cc:74
creates Action using supplied Action::Create method and command
ClassActionCreator(Handler *aHandler)
Mgr::Action::Pointer Handler(const Mgr::Command::Pointer &cmd)
Mgr::Action::Pointer create(const Mgr::Command::Pointer &cmd) const override
returns a pointer to the new Action object for cmd; never nil
char * url
Definition: errorpage.h:178
HttpReply * BuildHttpReply(void)
Definition: errorpage.cc:1277
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
Definition: HttpHeader.cc:1276
const char * getStr(Http::HdrType id) const
Definition: HttpHeader.cc:1164
int has(Http::HdrType id) const
Definition: HttpHeader.cc:938
void putAuth(const char *auth_scheme, const char *realm)
Definition: HttpHeader.cc:1005
void putExt(const char *name, const char *value)
Definition: HttpHeader.cc:1076
Http::StatusLine sline
Definition: HttpReply.h:56
HttpBody body
Definition: HttpReply.h:58
Http::MethodType id() const
Definition: RequestMethod.h:70
HttpRequestMethod method
Definition: HttpRequest.h:114
RequestFlags flags
Definition: HttpRequest.h:141
AnyP::Uri url
the request URI
Definition: HttpRequest.h:115
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.
Definition: ActionParams.h:24
String userName
user login name; currently only used for logging
Definition: ActionParams.h:40
String password
user password; used for acceptance check and cleared
Definition: ActionParams.h:41
String actionName
action name (and credentials realm)
Definition: ActionParams.h:39
RequestFlags httpFlags
HTTP request flags.
Definition: ActionParams.h:35
HttpRequestMethod httpMethod
HTTP request method.
Definition: ActionParams.h:34
list of cachemgr password authorization definitions. Currently a POD.
ActionPasswordList * next
hard-coded Cache Manager action configuration, including Action creator
Definition: ActionProfile.h:22
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
creates FunAction using ActionCreator API
Definition: FunAction.h:45
static void Parse(Parser::Tokenizer &, QueryParams &)
parses the query string parameters
Definition: QueryParams.cc:112
Definition: SBuf.h:94
static const size_type npos
Definition: SBuf.h:99
Mgr::ActionPasswordList * passwd_list
Definition: SquidConfig.h:261
const char * url() const
Definition: store.cc:1552
void complete()
Definition: store.cc:1017
time_t expires
Definition: Store.h:226
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition: store.cc:1691
char const * termedBuf() const
Definition: SquidString.h:92
size_type size() const
Definition: SquidString.h:73
an std::runtime_error with thrower location info
Definition: TextException.h:21
#define DBG_IMPORTANT
Definition: Stream.h:38
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:194
@ 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:717
void OBJH(StoreEntry *)
Definition: forward.h:44
@ scUnauthorized
Definition: StatusCode.h:45
@ scNotFound
Definition: StatusCode.h:48
@ scOkay
Definition: StatusCode.h:26
AnyP::ProtocolVersion ProtocolVersion(unsigned int aMajor, unsigned int aMinor)
HTTP version label information.
Command
what kind of I/O the disker needs to do or have done
Definition: IpcIoFile.h:33
RefCount< ActionProfile > ActionProfilePointer
Definition: forward.h:32
void RegisterBasics()
Registers profiles for the actions above; TODO: move elsewhere?
#define xstrdup
static void handler(int signo)
Definition: purge.cc:858
static bool action(int fd, size_t metasize, const char *fn, const char *url, const SquidMetaList &meta)
Definition: purge.cc:315
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
Definition: Stream.h:63
Definition: parse.c:160
static CacheManager * instance
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:696

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors