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