cache_manager.cc
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2022 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 "HttpReply.h"
21#include "HttpRequest.h"
22#include "mgr/Action.h"
23#include "mgr/ActionCreator.h"
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"
30#include "mgr/QueryParams.h"
31#include "parser/Tokenizer.h"
32#include "protos.h"
33#include "sbuf/Stream.h"
34#include "sbuf/StringConvert.h"
35#include "SquidConfig.h"
36#include "Store.h"
37#include "tools.h"
38#include "wordlist.h"
39
40#include <algorithm>
41
43#define MGR_PASSWD_SZ 128
44
47{
48public:
50
51public:
52 ClassActionCreator(Handler *aHandler): handler(aHandler) {}
53
55 return handler(cmd);
56 }
57
58private:
60};
61
63void
65{
66 Must(profile != nullptr);
67 if (!CacheManager::findAction(profile->name)) {
68 menu_.push_back(profile);
69 debugs(16, 3, "registered profile: " << *profile);
70 } else {
71 debugs(16, 2, "skipped duplicate profile: " << *profile);
72 }
73}
74
81void
82CacheManager::registerProfile(char const * action, char const * desc, OBJH * handler, int pw_req_flag, int atomic)
83{
84 debugs(16, 3, "registering legacy " << action);
86 desc, pw_req_flag, atomic, new Mgr::FunActionCreator(handler));
87 registerProfile(profile);
88}
89
96void
97CacheManager::registerProfile(char const * action, char const * desc,
99 int pw_req_flag, int atomic)
100{
102 desc, pw_req_flag, atomic, new ClassActionCreator(handler));
103 registerProfile(profile);
104}
105
114{
115 Must(action != nullptr);
116 Menu::const_iterator a;
117
118 debugs(16, 5, "CacheManager::findAction: looking for action " << action);
119 for (a = menu_.begin(); a != menu_.end(); ++a) {
120 if (0 == strcmp((*a)->name, action)) {
121 debugs(16, 6, " found");
122 return *a;
123 }
124 }
125
126 debugs(16, 6, "Action not found.");
128}
129
131CacheManager::createNamedAction(const char *actionName)
132{
133 Must(actionName);
134
136 cmd->profile = findAction(actionName);
137 cmd->params.actionName = actionName;
138
139 Must(cmd->profile != nullptr);
140 return cmd->profile->creator->create(cmd);
141}
142
145{
147 cmd->params = params;
148 cmd->profile = findAction(params.actionName.termedBuf());
149 Must(cmd->profile != nullptr);
150 return cmd->profile->creator->create(cmd);
151}
152
153static const CharacterSet &
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
181{
183
184 static const SBuf internalMagicPrefix("/squid-internal-mgr/");
185 if (!tok.skip(internalMagicPrefix) && !tok.skip('/'))
186 throw TextException("invalid URL path", Here());
187
189 cmd->params.httpUri = SBufToString(uri.absolute());
190
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 }
202 }
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());
208
209 const char *prot = ActionProtection(profile);
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);
218 }
219
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
234 return cmd;
235}
236
238/*
239 \ingroup CacheManagerInternal
240 * Decodes the headers needed to perform user authentication and fills
241 * the details into the cachemgrStateData argument
242 */
243void
245{
247
248 params.httpMethod = request->method.id();
249 params.httpFlags = request->flags;
250
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 */
255 const auto basic_cookie(request->header.getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
256
257 if (basic_cookie.isEmpty())
258 return;
259
260 const auto colonPos = basic_cookie.find(':');
261 if (colonPos == SBuf::npos) {
262 debugs(16, DBG_IMPORTANT, "ERROR: CacheManager::ParseHeaders: unknown basic_cookie format '" << basic_cookie << "'");
263 return;
264 }
265
266 /* found user:password pair, reset old values */
267 params.userName = SBufToString(basic_cookie.substr(0, colonPos));
268 params.password = SBufToString(basic_cookie.substr(colonPos+1));
269
270 /* warning: this prints decoded password which maybe not be what you want to do @?@ @?@ */
271 debugs(16, 9, "CacheManager::ParseHeaders: got user: '" <<
272 params.userName << "' passwd: '" << params.password << "'");
273#endif
274}
275
283int
285{
286 assert(cmd.profile != nullptr);
287 const char *action = cmd.profile->name;
288 char *pwd = PasswdGet(Config.passwd_list, action);
289
290 debugs(16, 4, "CacheManager::CheckPassword for action " << action);
291
292 if (pwd == nullptr)
293 return cmd.profile->isPwReq;
294
295 if (strcmp(pwd, "disable") == 0)
296 return 1;
297
298 if (strcmp(pwd, "none") == 0)
299 return 0;
300
301 if (!cmd.params.password.size())
302 return 1;
303
304 return cmd.params.password != pwd;
305}
306
313void
315{
316 debugs(16, 3, "request-url= '" << request->url << "', entry-url='" << entry->url() << "'");
317
319 try {
320 cmd = ParseUrl(request->url);
321
322 } catch (...) {
323 debugs(16, 2, "request URL error: " << CurrentException);
324 const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request, ale);
325 err->url = xstrdup(entry->url());
326 err->detailError(new ExceptionErrorDetail(Here().id()));
327 errorAppendEntry(entry, err);
328 entry->expires = squid_curtime;
329 return;
330 }
331
332 const char *actionName = cmd->profile->name;
333
334 entry->expires = squid_curtime;
335
336 debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");
337
338 /* get additional info from request headers */
339 ParseHeaders(request, cmd->params);
340
341 const char *userName = cmd->params.userName.size() ?
342 cmd->params.userName.termedBuf() : "unknown";
343
344 /* Check password */
345
346 if (CheckPassword(*cmd) != 0) {
347 /* build error message */
349 /* warn if user specified incorrect password */
350
351 if (cmd->params.password.size()) {
352 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
353 userName << "@" <<
354 client << ": incorrect password for '" <<
355 actionName << "'" );
356 } else {
357 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
358 userName << "@" <<
359 client << ": password needed for '" <<
360 actionName << "'" );
361 }
362
363 HttpReply *rep = errState.BuildHttpReply();
364
365#if HAVE_AUTH_MODULE_BASIC
366 /*
367 * add Authenticate header using action name as a realm because
368 * password depends on the action
369 */
370 rep->header.putAuth("Basic", actionName);
371#endif
372 // Allow cachemgr and other XHR scripts access to our version string
373 if (request->header.has(Http::HdrType::ORIGIN)) {
374 rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
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 }
380
381 /* store the reply */
382 entry->replaceHttpReply(rep);
383
384 entry->expires = squid_curtime;
385
386 entry->complete();
387
388 return;
389 }
390
391 if (request->header.has(Http::HdrType::ORIGIN)) {
392 cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
393 }
394
395 debugs(16, 2, "CacheManager: " <<
396 userName << "@" <<
397 client << " requesting '" <<
398 actionName << "'" );
399
400 // special case: /squid-internal-mgr/ index page
401 if (!strcmp(cmd->profile->name, "index")) {
403 err.url = xstrdup(entry->url());
404 HttpReply *rep = err.BuildHttpReply();
405 if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
407 // Allow cachemgr and other XHR scripts access to our version string
408 if (request->header.has(Http::HdrType::ORIGIN)) {
409 rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
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
420 if (UsingSmp() && IamWorkerProcess()) {
421 // is client the right connection to pass here?
422 AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry, ale));
423 return;
424 }
425
426 Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
427 Must(action != nullptr);
428 action->run(entry, true);
429}
430
431/*
432 \ingroup CacheManagerInternal
433 * Renders the protection level text for an action.
434 * Also doubles as a check for the protection level.
435 */
436const char *
438{
439 assert(profile != nullptr);
440 const char *pwd = PasswdGet(Config.passwd_list, profile->name);
441
442 if (!pwd)
443 return profile->isPwReq ? "hidden" : "public";
444
445 if (!strcmp(pwd, "disable"))
446 return "disabled";
447
448 if (strcmp(pwd, "none") == 0)
449 return "public";
450
451 return "protected";
452}
453
454/*
455 * \ingroup CacheManagerInternal
456 * gets from the global Config the password the user would need to supply
457 * for the action she queried
458 */
459char *
461{
462 while (a) {
463 for (auto &w : a->actions) {
464 if (w.cmp(action) == 0)
465 return a->passwd;
466
467 static const SBuf allAction("all");
468 if (w == allAction)
469 return a->passwd;
470 }
471
472 a = a->next;
473 }
474
475 return nullptr;
476}
477
480{
481 static CacheManager *instance = nullptr;
482 if (!instance) {
483 debugs(16, 6, "starting cachemanager up");
486 }
487 return instance;
488}
489
#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:71
#define assert(EX)
Definition: assert.h:19
static const CharacterSet & MgrFieldChars(const AnyP::ProtocolType &protocol)
Definition: Uri.h:31
AnyP::UriScheme const & getScheme() const
Definition: Uri.h:67
void path(const char *p)
Definition: Uri.h:99
SBuf & absolute() const
Definition: Uri.cc:584
void host(const char *src)
Definition: Uri.cc:99
static void Start(const Pointer &job)
Definition: AsyncJob.cc:24
char * PasswdGet(Mgr::ActionPasswordList *, const char *)
const char * ActionProtection(const Mgr::ActionProfilePointer &profile)
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)
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:53
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)
virtual Mgr::Action::Pointer create(const Mgr::Command::Pointer &cmd) const
returns a pointer to the new Action object for cmd; never nil
Mgr::Action::Pointer Handler(const Mgr::Command::Pointer &cmd)
char * url
Definition: errorpage.h:176
HttpReply * BuildHttpReply(void)
Definition: errorpage.cc:1279
const char * content() const
Definition: HttpBody.h:44
void putAuth(const char *auth_scheme, const char *realm)
Definition: HttpHeader.cc:1037
void putExt(const char *name, const char *value)
Definition: HttpHeader.cc:1109
Http::StatusLine sline
Definition: HttpReply.h:56
HttpBody body
Definition: HttpReply.h:58
HttpHeader header
Definition: Message.h:74
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:259
const char * url() const
Definition: store.cc:1533
void complete()
Definition: store.cc:1004
time_t expires
Definition: Store.h:226
void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting=true)
Definition: store.cc:1672
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:41
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:196
@ 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:719
void OBJH(StoreEntry *)
Definition: forward.h:44
ProtocolType
Definition: ProtocolType.h:23
@ PROTO_CACHE_OBJECT
Definition: ProtocolType.h:31
@ 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:854
static bool action(int fd, size_t metasize, const char *fn, const char *url, const SquidMetaList &meta)
Definition: purge.cc:311
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
Definition: Stream.h:63
char * url
Definition: tcp-banger2.c:114
char method[16]
Definition: tcp-banger2.c:115
Definition: parse.c:160
static CacheManager * instance
bool IamWorkerProcess()
whether the current process handles HTTP transactions and such
Definition: stub_tools.cc:47
struct _request * request(char *urlin)
Definition: tcp-banger2.c:291
bool UsingSmp()
Whether there should be more than one worker process running.
Definition: tools.cc:693

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors