]> git.ipfire.org Git - thirdparty/squid.git/blame - src/external_acl.cc
document ALE new members
[thirdparty/squid.git] / src / external_acl.cc
CommitLineData
d9572179 1/*
bde978a6 2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
d9572179 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.
d9572179 7 */
8
bbc27441
AJ
9/* DEBUG: section 82 External ACL */
10
582c2af2 11#include "squid.h"
c0941a6a 12#include "acl/Acl.h"
582c2af2 13#include "acl/FilledChecklist.h"
8a01b99e 14#include "cache_cf.h"
a46d2c0e 15#include "client_side.h"
4e56d7f6 16#include "client_side_request.h"
5c336a3b 17#include "comm/Connection.h"
2eceb328 18#include "ConfigParser.h"
582c2af2 19#include "ExternalACL.h"
f9b6ff6e 20#include "ExternalACLEntry.h"
582c2af2 21#include "fde.h"
4e56d7f6 22#include "format/Token.h"
aa839030 23#include "helper.h"
24438ec5 24#include "helper/Reply.h"
a5bac1d2 25#include "HttpHeaderTools.h"
582c2af2
FC
26#include "HttpReply.h"
27#include "HttpRequest.h"
28#include "ip/tools.h"
0eb49b6d 29#include "MemBuf.h"
582c2af2 30#include "mgr/Registration.h"
1fa9b1a7 31#include "rfc1738.h"
4d5904f7 32#include "SquidConfig.h"
f9b6ff6e 33#include "SquidString.h"
582c2af2
FC
34#include "SquidTime.h"
35#include "Store.h"
4e540555 36#include "tools.h"
b1bd952a 37#include "URL.h"
d295d770 38#include "wordlist.h"
cb4f4424 39#if USE_OPENSSL
cedca6e7 40#include "ssl/ServerBump.h"
4db984be
CT
41#include "ssl/support.h"
42#endif
582c2af2
FC
43#if USE_AUTH
44#include "auth/Acl.h"
45#include "auth/Gadgets.h"
46#include "auth/UserRequest.h"
47#endif
48#if USE_IDENT
49#include "ident/AclIdent.h"
50#endif
d9572179 51
52#ifndef DEFAULT_EXTERNAL_ACL_TTL
53#define DEFAULT_EXTERNAL_ACL_TTL 1 * 60 * 60
54#endif
d4f2f353 55#ifndef DEFAULT_EXTERNAL_ACL_CHILDREN
56#define DEFAULT_EXTERNAL_ACL_CHILDREN 5
d9572179 57#endif
58
c0941a6a 59static char *makeExternalAclKey(ACLFilledChecklist * ch, external_acl_data * acl_data);
abdd93d0
AJ
60static void external_acl_cache_delete(external_acl * def, const ExternalACLEntryPointer &entry);
61static int external_acl_entry_expired(external_acl * def, const ExternalACLEntryPointer &entry);
62static int external_acl_grace_expired(external_acl * def, const ExternalACLEntryPointer &entry);
63static void external_acl_cache_touch(external_acl * def, const ExternalACLEntryPointer &entry);
64static ExternalACLEntryPointer external_acl_cache_add(external_acl * def, const char *key, ExternalACLEntryData const &data);
d9572179 65
66/******************************************************************
67 * external_acl directive
68 */
62e76326 69
1e5562e3 70class external_acl
62e76326 71{
f205a92e
SM
72 /* FIXME: These are not really cbdata, but it is an easy way
73 * to get them pooled, refcounted, accounted and freed properly...
74 */
f963b531 75 CBDATA_CLASS(external_acl);
1e5562e3 76
77public:
f963b531
AJ
78 external_acl();
79 ~external_acl();
80
d9572179 81 external_acl *next;
1e5562e3 82
abdd93d0 83 void add(const ExternalACLEntryPointer &);
1e5562e3 84
85 void trimCache();
86
d9572179 87 int ttl;
1e5562e3 88
d9572179 89 int negative_ttl;
1e5562e3 90
47b0c1fa 91 int grace;
92
d9572179 93 char *name;
1e5562e3 94
4e56d7f6 95 Format::Format format;
1e5562e3 96
d9572179 97 wordlist *cmdline;
1e5562e3 98
76d9b994 99 Helper::ChildConfig children;
07eca7e0 100
e6ccf245 101 helper *theHelper;
1e5562e3 102
d9572179 103 hash_table *cache;
1e5562e3 104
d9572179 105 dlink_list lru_list;
1e5562e3 106
d9572179 107 int cache_size;
1e5562e3 108
d9572179 109 int cache_entries;
1e5562e3 110
d9572179 111 dlink_list queue;
1e5562e3 112
2f1431ea 113#if USE_AUTH
3265364b
AJ
114 /**
115 * Configuration flag. May only be altered by the configuration parser.
116 *
117 * Indicates that all uses of this external_acl_type helper require authentication
118 * details to be processed. If none are available its a fail match.
119 */
e870b1f8 120 bool require_auth;
2f1431ea 121#endif
dc1af3cf 122
26ac0430 123 enum {
dc1af3cf 124 QUOTE_METHOD_SHELL = 1,
125 QUOTE_METHOD_URL
2fadd50d 126 } quote;
cc192b50 127
b7ac5457 128 Ip::Address local_addr;
d9572179 129};
130
f963b531
AJ
131CBDATA_CLASS_INIT(external_acl);
132
133external_acl::external_acl() :
cc8c4af2 134 next(NULL),
f963b531
AJ
135 ttl(DEFAULT_EXTERNAL_ACL_TTL),
136 negative_ttl(-1),
137 grace(1),
138 name(NULL),
4e56d7f6 139 format("external_acl_type"),
f963b531
AJ
140 cmdline(NULL),
141 children(DEFAULT_EXTERNAL_ACL_CHILDREN),
142 theHelper(NULL),
143 cache(NULL),
144 cache_size(256*1024),
145 cache_entries(0),
146#if USE_AUTH
147 require_auth(0),
148#endif
149 quote(external_acl::QUOTE_METHOD_URL)
d9572179 150{
f963b531
AJ
151 local_addr.setLocalhost();
152}
62e76326 153
f963b531
AJ
154external_acl::~external_acl()
155{
156 xfree(name);
f963b531
AJ
157 wordlistDestroy(&cmdline);
158
159 if (theHelper) {
160 helperShutdown(theHelper);
161 delete theHelper;
162 theHelper = NULL;
d9572179 163 }
62e76326 164
f963b531
AJ
165 while (lru_list.tail) {
166 ExternalACLEntryPointer e(static_cast<ExternalACLEntry *>(lru_list.tail->data));
167 external_acl_cache_delete(this, e);
168 }
169 if (cache)
170 hashFreeMemory(cache);
171
172 while (next) {
173 external_acl *node = next;
174 next = node->next;
175 node->next = NULL; // prevent recursion
176 delete node;
abdd93d0 177 }
d9572179 178}
179
180void
181parse_externalAclHelper(external_acl ** list)
182{
f963b531
AJ
183 external_acl *a = new external_acl;
184 char *token = ConfigParser::NextToken();
62e76326 185
d9572179 186 if (!token)
62e76326 187 self_destruct();
188
d9572179 189 a->name = xstrdup(token);
190
2eceb328
CT
191 // Allow supported %macros inside quoted tokens
192 ConfigParser::EnableMacros();
193 token = ConfigParser::NextToken();
62e76326 194
d9572179 195 /* Parse options */
196 while (token) {
62e76326 197 if (strncmp(token, "ttl=", 4) == 0) {
198 a->ttl = atoi(token + 4);
199 } else if (strncmp(token, "negative_ttl=", 13) == 0) {
200 a->negative_ttl = atoi(token + 13);
07eca7e0 201 } else if (strncmp(token, "children=", 9) == 0) {
48d54e4d 202 a->children.n_max = atoi(token + 9);
fa84c01d 203 debugs(0, DBG_CRITICAL, "WARNING: external_acl_type option children=N has been deprecated in favor of children-max=N and children-startup=N");
48d54e4d
AJ
204 } else if (strncmp(token, "children-max=", 13) == 0) {
205 a->children.n_max = atoi(token + 13);
206 } else if (strncmp(token, "children-startup=", 17) == 0) {
207 a->children.n_startup = atoi(token + 17);
208 } else if (strncmp(token, "children-idle=", 14) == 0) {
209 a->children.n_idle = atoi(token + 14);
07eca7e0 210 } else if (strncmp(token, "concurrency=", 12) == 0) {
48d54e4d 211 a->children.concurrency = atoi(token + 12);
6825b101
CT
212 } else if (strncmp(token, "queue-size=", 11) == 0) {
213 a->children.queue_size = atoi(token + 11);
214 a->children.defaultQueueSize = false;
62e76326 215 } else if (strncmp(token, "cache=", 6) == 0) {
216 a->cache_size = atoi(token + 6);
47b0c1fa 217 } else if (strncmp(token, "grace=", 6) == 0) {
218 a->grace = atoi(token + 6);
dc1af3cf 219 } else if (strcmp(token, "protocol=2.5") == 0) {
220 a->quote = external_acl::QUOTE_METHOD_SHELL;
221 } else if (strcmp(token, "protocol=3.0") == 0) {
05e52854
AJ
222 debugs(3, DBG_PARSE_NOTE(2), "WARNING: external_acl_type option protocol=3.0 is deprecated. Remove this from your config.");
223 a->quote = external_acl::QUOTE_METHOD_URL;
dc1af3cf 224 } else if (strcmp(token, "quote=url") == 0) {
05e52854 225 debugs(3, DBG_PARSE_NOTE(2), "WARNING: external_acl_type option quote=url is deprecated. Remove this from your config.");
dc1af3cf 226 a->quote = external_acl::QUOTE_METHOD_URL;
227 } else if (strcmp(token, "quote=shell") == 0) {
05e52854 228 debugs(3, DBG_PARSE_NOTE(2), "WARNING: external_acl_type option quote=shell is deprecated. Use protocol=2.5 if still needed.");
dc1af3cf 229 a->quote = external_acl::QUOTE_METHOD_SHELL;
cc192b50 230
26ac0430
AJ
231 /* INET6: allow admin to configure some helpers explicitly to
232 bind to IPv4/v6 localhost port. */
cc192b50 233 } else if (strcmp(token, "ipv4") == 0) {
4dd643d5 234 if ( !a->local_addr.setIPv4() ) {
fa84c01d 235 debugs(3, DBG_CRITICAL, "WARNING: Error converting " << a->local_addr << " to IPv4 in " << a->name );
cc192b50 236 }
237 } else if (strcmp(token, "ipv6") == 0) {
055421ee 238 if (!Ip::EnableIpv6)
fa84c01d 239 debugs(3, DBG_CRITICAL, "WARNING: --enable-ipv6 required for external ACL helpers to use IPv6: " << a->name );
055421ee 240 // else nothing to do.
62e76326 241 } else {
242 break;
243 }
244
2eceb328 245 token = ConfigParser::NextToken();
d9572179 246 }
2eceb328 247 ConfigParser::DisableMacros();
62e76326 248
6f78f0ed 249 /* check that child startup value is sane. */
a3cecd6c
AJ
250 if (a->children.n_startup > a->children.n_max)
251 a->children.n_startup = a->children.n_max;
48d54e4d 252
6f78f0ed 253 /* check that child idle value is sane. */
a3cecd6c
AJ
254 if (a->children.n_idle > a->children.n_max)
255 a->children.n_idle = a->children.n_max;
256 if (a->children.n_idle < 1)
257 a->children.n_idle = 1;
48d54e4d 258
d9572179 259 if (a->negative_ttl == -1)
62e76326 260 a->negative_ttl = a->ttl;
d9572179 261
e44a3ec4 262 if (a->children.defaultQueueSize)
6825b101
CT
263 a->children.queue_size = 2 * a->children.n_max;
264
4e56d7f6
AJ
265 /* Legacy external_acl_type format parser.
266 * Handles a series of %... tokens where any non-% means
267 * the start of another parameter field (ie the path to binary).
268 */
269 enum Format::Quoting quote = Format::LOG_QUOTE_NONE;
270 Format::Token **fmt = &a->format.format;
712fa21e 271 bool data_used = false;
d9572179 272 while (token) {
4e56d7f6 273 /* stop on first non-% token found */
62e76326 274 if (*token != '%')
275 break;
276
4e56d7f6 277 *fmt = new Format::Token;
09e34608
AJ
278 // these tokens are whitespace delimited
279 (*fmt)->space = true;
4e56d7f6
AJ
280
281 // compatibility for old tokens incompatible with Format::Token syntax
282#if USE_OPENSSL // dont bother if we dont have to.
283 if (strncmp(token, "%USER_CERT_", 11) == 0) {
284 (*fmt)->type = Format::LFT_EXT_ACL_USER_CERT;
285 (*fmt)->data.string = xstrdup(token + 11);
286 (*fmt)->data.header.header = (*fmt)->data.string;
f06585e0 287 } else if (strncmp(token, "%USER_CA_CERT_", 14) == 0) {
4e56d7f6
AJ
288 (*fmt)->type = Format::LFT_EXT_ACL_USER_CA_CERT;
289 (*fmt)->data.string = xstrdup(token + 14);
290 (*fmt)->data.header.header = (*fmt)->data.string;
f06585e0 291 } else if (strncmp(token, "%CA_CERT_", 9) == 0) {
3650c90e 292 debugs(82, DBG_PARSE_NOTE(DBG_IMPORTANT), "WARNING: external_acl_type %CA_CERT_* code is obsolete. Use %USER_CA_CERT_* instead");
4e56d7f6
AJ
293 (*fmt)->type = Format::LFT_EXT_ACL_USER_CA_CERT;
294 (*fmt)->data.string = xstrdup(token + 9);
295 (*fmt)->data.header.header = (*fmt)->data.string;
296 } else
a7ad6e4e 297#endif
4e56d7f6
AJ
298 {
299 // we can use the Format::Token::parse() method since it
300 // only pulls off one token. Since we already checked
301 // for '%' prefix above this is guaranteed to be a token.
302 const size_t len = (*fmt)->parse(token, &quote);
303 assert(len == strlen(token));
304 }
305
306 // process special token-specific actions (only if necessary)
2f1431ea 307#if USE_AUTH
4e56d7f6
AJ
308 if ((*fmt)->type == Format::LFT_USER_LOGIN)
309 a->require_auth = true;
2f1431ea 310#endif
62e76326 311
712fa21e
AJ
312 if ((*fmt)->type == Format::LFT_EXT_ACL_DATA)
313 data_used = true;
314
4e56d7f6 315 fmt = &((*fmt)->next);
2eceb328 316 token = ConfigParser::NextToken();
d9572179 317 }
318
319 /* There must be at least one format token */
4e56d7f6 320 if (!a->format.format)
62e76326 321 self_destruct();
d9572179 322
712fa21e
AJ
323 // format has implicit %DATA on the end if not used explicitly
324 if (!data_used) {
325 *fmt = new Format::Token;
326 (*fmt)->type = Format::LFT_EXT_ACL_DATA;
57c2fb88 327 (*fmt)->quote = Format::LOG_QUOTE_URL;
712fa21e
AJ
328 }
329
d9572179 330 /* helper */
331 if (!token)
62e76326 332 self_destruct();
333
d9572179 334 wordlistAdd(&a->cmdline, token);
335
336 /* arguments */
a336d130 337 parse_wordlist(&a->cmdline);
d9572179 338
339 while (*list)
62e76326 340 list = &(*list)->next;
341
d9572179 342 *list = a;
343}
344
345void
346dump_externalAclHelper(StoreEntry * sentry, const char *name, const external_acl * list)
347{
348 const external_acl *node;
d9572179 349 const wordlist *word;
62e76326 350
d9572179 351 for (node = list; node; node = node->next) {
62e76326 352 storeAppendPrintf(sentry, "%s %s", name, node->name);
353
4dd643d5 354 if (!node->local_addr.isIPv6())
cc192b50 355 storeAppendPrintf(sentry, " ipv4");
356 else
357 storeAppendPrintf(sentry, " ipv6");
358
62e76326 359 if (node->ttl != DEFAULT_EXTERNAL_ACL_TTL)
360 storeAppendPrintf(sentry, " ttl=%d", node->ttl);
361
362 if (node->negative_ttl != node->ttl)
363 storeAppendPrintf(sentry, " negative_ttl=%d", node->negative_ttl);
364
47b0c1fa 365 if (node->grace)
366 storeAppendPrintf(sentry, " grace=%d", node->grace);
367
48d54e4d
AJ
368 if (node->children.n_max != DEFAULT_EXTERNAL_ACL_CHILDREN)
369 storeAppendPrintf(sentry, " children-max=%d", node->children.n_max);
62e76326 370
48d54e4d
AJ
371 if (node->children.n_startup != 1)
372 storeAppendPrintf(sentry, " children-startup=%d", node->children.n_startup);
62e76326 373
48d54e4d
AJ
374 if (node->children.n_idle != (node->children.n_max + node->children.n_startup) )
375 storeAppendPrintf(sentry, " children-idle=%d", node->children.n_idle);
376
377 if (node->children.concurrency)
378 storeAppendPrintf(sentry, " concurrency=%d", node->children.concurrency);
07eca7e0 379
47b0c1fa 380 if (node->cache)
381 storeAppendPrintf(sentry, " cache=%d", node->cache_size);
382
05e52854
AJ
383 if (node->quote == external_acl::QUOTE_METHOD_SHELL)
384 storeAppendPrintf(sentry, " protocol=2.5");
385
4e56d7f6 386 node->format.dump(sentry, NULL, false);
62e76326 387
388 for (word = node->cmdline; word; word = word->next)
389 storeAppendPrintf(sentry, " %s", word->key);
390
391 storeAppendPrintf(sentry, "\n");
d9572179 392 }
393}
394
395void
396free_externalAclHelper(external_acl ** list)
397{
f963b531
AJ
398 delete *list;
399 *list = NULL;
d9572179 400}
401
402static external_acl *
403find_externalAclHelper(const char *name)
404{
405 external_acl *node;
406
407 for (node = Config.externalAclHelperList; node; node = node->next) {
62e76326 408 if (strcmp(node->name, name) == 0)
409 return node;
d9572179 410 }
62e76326 411
d9572179 412 return NULL;
413}
414
1e5562e3 415void
abdd93d0 416external_acl::add(const ExternalACLEntryPointer &anEntry)
1e5562e3 417{
418 trimCache();
abdd93d0 419 assert(anEntry != NULL);
1e5562e3 420 assert (anEntry->def == NULL);
421 anEntry->def = this;
abdd93d0
AJ
422 ExternalACLEntry *e = const_cast<ExternalACLEntry *>(anEntry.getRaw()); // XXX: make hash a std::map of Pointer.
423 hash_join(cache, e);
424 dlinkAdd(e, &e->lru, &lru_list);
425 e->lock(); //cbdataReference(e); // lock it on behalf of the hash
95dc7ff4 426 ++cache_entries;
1e5562e3 427}
428
429void
430external_acl::trimCache()
431{
abdd93d0
AJ
432 if (cache_size && cache_entries >= cache_size) {
433 ExternalACLEntryPointer e(static_cast<ExternalACLEntry *>(lru_list.tail->data));
434 external_acl_cache_delete(this, e);
435 }
1e5562e3 436}
437
d9572179 438/******************************************************************
439 * external acl type
440 */
441
f963b531
AJ
442class external_acl_data
443{
444 CBDATA_CLASS(external_acl_data);
445
446public:
447 explicit external_acl_data(external_acl *aDef) : def(cbdataReference(aDef)), name(NULL), arguments(NULL) {}
448 ~external_acl_data();
449
d9572179 450 external_acl *def;
ec2d5242 451 const char *name;
d9572179 452 wordlist *arguments;
453};
454
f963b531
AJ
455CBDATA_CLASS_INIT(external_acl_data);
456
457external_acl_data::~external_acl_data()
d9572179 458{
f963b531
AJ
459 xfree(name);
460 wordlistDestroy(&arguments);
461 cbdataReferenceDone(def);
d9572179 462}
463
464void
b0dd28ba 465ACLExternal::parse()
d9572179 466{
b0dd28ba 467 if (data)
62e76326 468 self_destruct();
469
16c5ad96 470 char *token = ConfigParser::strtokFile();
62e76326 471
d9572179 472 if (!token)
62e76326 473 self_destruct();
474
f963b531 475 data = new external_acl_data(find_externalAclHelper(token));
62e76326 476
d9572179 477 if (!data->def)
62e76326 478 self_destruct();
479
ec2d5242
HN
480 // def->name is the name of the external_acl_type.
481 // this is the name of the 'acl' directive being tested
482 data->name = xstrdup(AclMatchedName);
483
16c5ad96 484 while ((token = ConfigParser::strtokFile())) {
62e76326 485 wordlistAdd(&data->arguments, token);
d9572179 486 }
d9572179 487}
488
4b0f5de8 489bool
490ACLExternal::valid () const
491{
2f1431ea 492#if USE_AUTH
4b0f5de8 493 if (data->def->require_auth) {
494 if (authenticateSchemeCount() == 0) {
fa84c01d 495 debugs(28, DBG_CRITICAL, "Can't use proxy auth because no authentication schemes were compiled.");
4b0f5de8 496 return false;
497 }
498
499 if (authenticateActiveSchemeCount() == 0) {
fa84c01d 500 debugs(28, DBG_CRITICAL, "Can't use proxy auth because no authentication schemes are fully configured.");
4b0f5de8 501 return false;
502 }
503 }
2f1431ea 504#endif
4b0f5de8 505
506 return true;
507}
508
509bool
510ACLExternal::empty () const
511{
512 return false;
513}
514
b0dd28ba 515ACLExternal::~ACLExternal()
d9572179 516{
f963b531
AJ
517 delete data;
518 xfree(class_);
d9572179 519}
520
1abe0161 521static void
abdd93d0 522copyResultsFromEntry(HttpRequest *req, const ExternalACLEntryPointer &entry)
1abe0161
AJ
523{
524 if (req) {
525#if USE_AUTH
526 if (entry->user.size())
527 req->extacl_user = entry->user;
528
529 if (entry->password.size())
530 req->extacl_passwd = entry->password;
531#endif
532 if (!req->tag.size())
533 req->tag = entry->tag;
534
535 if (entry->log.size())
536 req->extacl_log = entry->log;
537
538 if (entry->message.size())
539 req->extacl_message = entry->message;
a1df1417
NH
540
541 // attach the helper kv-pair to the transaction
542 UpdateRequestNotes(req->clientConnectionManager.get(), *req, entry->notes);
1abe0161
AJ
543 }
544}
545
e5f825ea 546static allow_t
c0941a6a 547aclMatchExternal(external_acl_data *acl, ACLFilledChecklist *ch)
d9572179 548{
c69ce640 549 debugs(82, 9, HERE << "acl=\"" << acl->def->name << "\"");
abdd93d0 550 ExternalACLEntryPointer entry = ch->extacl_entry;
62e76326 551
6f58d7d7
AR
552 external_acl_message = "MISSING REQUIRED INFORMATION";
553
abdd93d0
AJ
554 if (entry != NULL) {
555 if (entry->def == acl->def) {
ad06254e 556 /* Ours, use it.. if the key matches */
6f58d7d7
AR
557 const char *key = makeExternalAclKey(ch, acl);
558 if (!key)
559 return ACCESS_DUNNO; // insufficent data to continue
ad06254e 560 if (strcmp(key, (char*)entry->key) != 0) {
abdd93d0 561 debugs(82, 9, "entry key='" << (char *)entry->key << "', our key='" << key << "' dont match. Discarded.");
ad06254e 562 // too bad. need a new lookup.
abdd93d0 563 entry = ch->extacl_entry = NULL;
ad06254e 564 }
62e76326 565 } else {
abdd93d0
AJ
566 /* Not ours.. get rid of it */
567 debugs(82, 9, "entry " << entry << " not valid or not ours. Discarded.");
568 if (entry != NULL) {
569 debugs(82, 9, "entry def=" << entry->def << ", our def=" << acl->def);
6f58d7d7 570 const char *key = makeExternalAclKey(ch, acl); // may be nil
abdd93d0 571 debugs(82, 9, "entry key='" << (char *)entry->key << "', our key='" << key << "'");
c69ce640 572 }
abdd93d0 573 entry = ch->extacl_entry = NULL;
62e76326 574 }
d9572179 575 }
62e76326 576
d9572179 577 if (!entry) {
c69ce640 578 debugs(82, 9, HERE << "No helper entry available");
2f1431ea 579#if USE_AUTH
62e76326 580 if (acl->def->require_auth) {
62e76326 581 /* Make sure the user is authenticated */
e5f825ea 582 debugs(82, 3, HERE << acl->def->name << " check user authenticated.");
e0f7153c
AR
583 const allow_t ti = AuthenticateAcl(ch);
584 if (ti != ACCESS_ALLOWED) {
e5f825ea 585 debugs(82, 2, HERE << acl->def->name << " user not authenticated (" << ti << ")");
e0f7153c 586 return ti;
62e76326 587 }
e5f825ea 588 debugs(82, 3, HERE << acl->def->name << " user is authenticated.");
62e76326 589 }
2f1431ea 590#endif
6f58d7d7 591 const char *key = makeExternalAclKey(ch, acl);
41218131 592
593 if (!key) {
594 /* Not sufficient data to process */
e5f825ea 595 return ACCESS_DUNNO;
41218131 596 }
597
abdd93d0 598 entry = static_cast<ExternalACLEntry *>(hash_lookup(acl->def->cache, key));
62e76326 599
abdd93d0
AJ
600 const ExternalACLEntryPointer staleEntry = entry;
601 if (entry != NULL && external_acl_entry_expired(acl->def, entry))
e0f7153c
AR
602 entry = NULL;
603
abdd93d0 604 if (entry != NULL && external_acl_grace_expired(acl->def, entry)) {
e0f7153c
AR
605 // refresh in the background
606 ExternalACLLookup::Start(ch, acl, true);
607 debugs(82, 4, HERE << "no need to wait for the refresh of '" <<
608 key << "' in '" << acl->def->name << "' (ch=" << ch << ").");
609 }
610
611 if (!entry) {
e5f825ea 612 debugs(82, 2, HERE << acl->def->name << "(\"" << key << "\") = lookup needed");
95a83c22 613
6825b101 614 if (!acl->def->theHelper->queueFull()) {
e5f825ea 615 debugs(82, 2, HERE << "\"" << key << "\": queueing a call.");
6f58d7d7
AR
616 if (!ch->goAsync(ExternalACLLookup::Instance()))
617 debugs(82, 2, "\"" << key << "\": no async support!");
e5f825ea 618 debugs(82, 2, HERE << "\"" << key << "\": return -1.");
e0f7153c 619 return ACCESS_DUNNO; // expired cached or simply absent entry
47b0c1fa 620 } else {
e0f7153c 621 if (!staleEntry) {
e5f825ea 622 debugs(82, DBG_IMPORTANT, "WARNING: external ACL '" << acl->def->name <<
bf8fe701 623 "' queue overload. Request rejected '" << key << "'.");
4a972fa2 624 external_acl_message = "SYSTEM TOO BUSY, TRY AGAIN LATER";
e5f825ea 625 return ACCESS_DUNNO;
47b0c1fa 626 } else {
e5f825ea 627 debugs(82, DBG_IMPORTANT, "WARNING: external ACL '" << acl->def->name <<
bf8fe701 628 "' queue overload. Using stale result. '" << key << "'.");
e0f7153c 629 entry = staleEntry;
47b0c1fa 630 /* Fall thru to processing below */
631 }
632 }
633 }
d9572179 634 }
62e76326 635
e0f7153c
AR
636 debugs(82, 4, HERE << "entry = { date=" <<
637 (long unsigned int) entry->date <<
638 ", result=" << entry->result <<
639 " tag=" << entry->tag <<
640 " log=" << entry->log << " }");
641#if USE_AUTH
642 debugs(82, 4, HERE << "entry user=" << entry->user);
643#endif
644
d9572179 645 external_acl_cache_touch(acl->def, entry);
a7a42b14 646 external_acl_message = entry->message.termedBuf();
4a972fa2 647
e5f825ea 648 debugs(82, 2, HERE << acl->def->name << " = " << entry->result);
1abe0161 649 copyResultsFromEntry(ch->request, entry);
e5f825ea 650 return entry->result;
d9572179 651}
652
b0dd28ba 653int
654ACLExternal::match(ACLChecklist *checklist)
655{
e5f825ea 656 allow_t answer = aclMatchExternal(data, Filled(checklist));
e5f825ea
AJ
657
658 // convert to tri-state ACL match 1,0,-1
9b831d57 659 switch (answer) {
e5f825ea 660 case ACCESS_ALLOWED:
e5f825ea
AJ
661 return 1; // match
662
663 case ACCESS_DENIED:
e5f825ea
AJ
664 return 0; // non-match
665
666 case ACCESS_DUNNO:
667 case ACCESS_AUTH_REQUIRED:
668 default:
e0f7153c 669 // If the answer is not allowed or denied (matches/not matches) and
6f58d7d7
AR
670 // async authentication is not in progress, then we are done.
671 if (checklist->keepMatching())
e0f7153c 672 checklist->markFinished(answer, "aclMatchExternal exception");
e5f825ea
AJ
673 return -1; // other
674 }
b0dd28ba 675}
676
dfad5100 677SBufList
b0dd28ba 678ACLExternal::dump() const
d9572179 679{
b0dd28ba 680 external_acl_data const *acl = data;
dfad5100
FC
681 SBufList rv;
682 rv.push_back(SBuf(acl->def->name));
62e76326 683
dfad5100
FC
684 for (wordlist *arg = acl->arguments; arg; arg = arg->next) {
685 SBuf s;
686 s.Printf(" %s", arg->key);
687 rv.push_back(s);
d9572179 688 }
62e76326 689
dfad5100 690 return rv;
d9572179 691}
692
693/******************************************************************
694 * external_acl cache
695 */
696
d9572179 697static void
abdd93d0 698external_acl_cache_touch(external_acl * def, const ExternalACLEntryPointer &entry)
d9572179 699{
c69ce640
AJ
700 // this must not be done when nothing is being cached.
701 if (def->cache_size <= 0 || (def->ttl <= 0 && entry->result == 1) || (def->negative_ttl <= 0 && entry->result != 1))
702 return;
703
d9572179 704 dlinkDelete(&entry->lru, &def->lru_list);
abdd93d0
AJ
705 ExternalACLEntry *e = const_cast<ExternalACLEntry *>(entry.getRaw()); // XXX: make hash a std::map of Pointer.
706 dlinkAdd(e, &entry->lru, &def->lru_list);
d9572179 707}
708
709static char *
c0941a6a 710makeExternalAclKey(ACLFilledChecklist * ch, external_acl_data * acl_data)
d9572179 711{
032785bf 712 static MemBuf mb;
09e34608 713 mb.reset();
62e76326 714
4e56d7f6
AJ
715 // check for special case tokens in the format
716 for (Format::Token *t = acl_data->def->format.format; t ; t = t->next) {
62e76326 717
4e56d7f6
AJ
718 if (t->type == Format::LFT_EXT_ACL_NAME) {
719 // setup for %ACL
720 safe_free(ch->al->_private.lastAclName);
721 ch->al->_private.lastAclName = xstrdup(acl_data->name);
789dda8d
CT
722 }
723
778647be 724 if (t->type == Format::LFT_EXT_ACL_DATA) {
4e56d7f6
AJ
725 // setup string for %DATA
726 SBuf sb;
4e56d7f6 727 for (auto arg = acl_data->arguments; arg; arg = arg->next) {
778647be 728 if (sb.length())
ec2d5242
HN
729 sb.append(" ", 1);
730
731 if (acl_data->def->quote == external_acl::QUOTE_METHOD_URL) {
732 const char *quoted = rfc1738_escape(arg->key);
733 sb.append(quoted, strlen(quoted));
734 } else {
735 static MemBuf mb2;
736 mb2.init();
737 strwordquote(&mb2, arg->key);
738 sb.append(mb2.buf, mb2.size);
739 mb2.clean();
740 }
ec2d5242 741 }
778647be
AJ
742
743 ch->al->_private.lastAclData = sb.c_str();
dc1af3cf 744 }
62e76326 745
33c2eb4d 746#if USE_IDENT
4e56d7f6 747 if (t->type == Format::LFT_USER_IDENT) {
a51ed963 748 if (!*ch->rfc931) {
4e56d7f6
AJ
749 // if we fail to go async, we still return NULL and the caller
750 // will detect the failure in ACLExternal::match().
751 (void)ch->goAsync(IdentLookup::Instance());
752 return NULL;
ec2d5242 753 }
ec2d5242 754 }
33c2eb4d 755#endif
d9572179 756 }
62e76326 757
712fa21e 758 // assemble the full helper lookup string
4e56d7f6
AJ
759 acl_data->def->format.assemble(mb, ch->al, 0);
760
d9572179 761 return mb.buf;
d9572179 762}
763
764static int
abdd93d0 765external_acl_entry_expired(external_acl * def, const ExternalACLEntryPointer &entry)
d9572179 766{
c69ce640
AJ
767 if (def->cache_size <= 0)
768 return 1;
769
d9572179 770 if (entry->date + (entry->result == 1 ? def->ttl : def->negative_ttl) < squid_curtime)
62e76326 771 return 1;
d9572179 772 else
62e76326 773 return 0;
d9572179 774}
62e76326 775
47b0c1fa 776static int
abdd93d0 777external_acl_grace_expired(external_acl * def, const ExternalACLEntryPointer &entry)
47b0c1fa 778{
c69ce640
AJ
779 if (def->cache_size <= 0)
780 return 1;
781
47b0c1fa 782 int ttl;
783 ttl = entry->result == 1 ? def->ttl : def->negative_ttl;
784 ttl = (ttl * (100 - def->grace)) / 100;
785
98b70eff 786 if (entry->date + ttl <= squid_curtime)
47b0c1fa 787 return 1;
788 else
789 return 0;
790}
791
abdd93d0 792static ExternalACLEntryPointer
1e5562e3 793external_acl_cache_add(external_acl * def, const char *key, ExternalACLEntryData const & data)
d9572179 794{
abdd93d0 795 ExternalACLEntryPointer entry;
c69ce640
AJ
796
797 // do not bother caching this result if TTL is going to expire it immediately
798 if (def->cache_size <= 0 || (def->ttl <= 0 && data.result == 1) || (def->negative_ttl <= 0 && data.result != 1)) {
799 debugs(82,6, HERE);
800 entry = new ExternalACLEntry;
801 entry->key = xstrdup(key);
802 entry->update(data);
803 entry->def = def;
804 return entry;
805 }
806
807 entry = static_cast<ExternalACLEntry *>(hash_lookup(def->cache, key));
bf8fe701 808 debugs(82, 2, "external_acl_cache_add: Adding '" << key << "' = " << data.result);
62e76326 809
abdd93d0
AJ
810 if (entry != NULL) {
811 debugs(82, 3, "updating existing entry");
c69ce640 812 entry->update(data);
62e76326 813 external_acl_cache_touch(def, entry);
62e76326 814 return entry;
d9572179 815 }
62e76326 816
1e5562e3 817 entry = new ExternalACLEntry;
4a8b20e8 818 entry->key = xstrdup(key);
c69ce640 819 entry->update(data);
1e5562e3 820
6ca34f6f 821 def->add(entry);
1e5562e3 822
d9572179 823 return entry;
824}
825
826static void
abdd93d0 827external_acl_cache_delete(external_acl * def, const ExternalACLEntryPointer &entry)
d9572179 828{
abdd93d0 829 assert(entry != NULL);
c69ce640 830 assert(def->cache_size > 0 && entry->def == def);
abdd93d0
AJ
831 ExternalACLEntry *e = const_cast<ExternalACLEntry *>(entry.getRaw()); // XXX: make hash a std::map of Pointer.
832 hash_remove_link(def->cache, e);
833 dlinkDelete(&e->lru, &def->lru_list);
834 e->unlock(); // unlock on behalf of the hash
d9572179 835 def->cache_entries -= 1;
d9572179 836}
837
838/******************************************************************
839 * external_acl helpers
840 */
841
f963b531
AJ
842class externalAclState
843{
844 CBDATA_CLASS(externalAclState);
845
846public:
847 externalAclState(external_acl* aDef, const char *aKey) :
848 callback(NULL),
849 callback_data(NULL),
850 key(xstrdup(aKey)),
851 def(cbdataReference(aDef)),
852 queue(NULL)
853 {}
854 ~externalAclState();
62e76326 855
d9572179 856 EAH *callback;
857 void *callback_data;
858 char *key;
859 external_acl *def;
860 dlink_node list;
861 externalAclState *queue;
862};
863
f963b531
AJ
864CBDATA_CLASS_INIT(externalAclState);
865
866externalAclState::~externalAclState()
d9572179 867{
f963b531
AJ
868 xfree(key);
869 cbdataReferenceDone(callback_data);
870 cbdataReferenceDone(def);
d9572179 871}
872
d9572179 873/*
874 * The helper program receives queries on stdin, one
07eca7e0 875 * per line, and must return the result on on stdout
d9572179 876 *
877 * General result syntax:
878 *
879 * OK/ERR keyword=value ...
880 *
881 * Keywords:
882 *
4a972fa2 883 * user= The users name (login)
884 * message= Message describing the reason
f53969cc
SM
885 * tag= A string tag to be applied to the request that triggered the acl match.
886 * applies to both OK and ERR responses.
887 * Won't override existing request tags.
888 * log= A string to be used in access logging
d9572179 889 *
890 * Other keywords may be added to the protocol later
891 *
05e52854
AJ
892 * value needs to be URL-encoded or enclosed in double quotes (")
893 * with \-escaping on any whitespace, quotes, or slashes (\).
d9572179 894 */
d9572179 895static void
24438ec5 896externalAclHandleReply(void *data, const Helper::Reply &reply)
d9572179 897{
e6ccf245 898 externalAclState *state = static_cast<externalAclState *>(data);
d9572179 899 externalAclState *next;
1e5562e3 900 ExternalACLEntryData entryData;
e5f825ea 901 entryData.result = ACCESS_DENIED;
d9572179 902
0272dd08 903 debugs(82, 2, HERE << "reply=" << reply);
d9572179 904
2428ce02 905 if (reply.result == Helper::Okay)
0272dd08
AJ
906 entryData.result = ACCESS_ALLOWED;
907 // XXX: handle other non-DENIED results better
62e76326 908
24438ec5 909 // XXX: make entryData store a proper Helper::Reply object instead of copying.
ab332e27 910
a0592634
AJ
911 entryData.notes.append(&reply.notes);
912
cf9f0261
CT
913 const char *label = reply.notes.findFirst("tag");
914 if (label != NULL && *label != '\0')
915 entryData.tag = label;
62e76326 916
cf9f0261
CT
917 label = reply.notes.findFirst("message");
918 if (label != NULL && *label != '\0')
919 entryData.message = label;
62e76326 920
cf9f0261
CT
921 label = reply.notes.findFirst("log");
922 if (label != NULL && *label != '\0')
923 entryData.log = label;
62e76326 924
2f1431ea 925#if USE_AUTH
cf9f0261
CT
926 label = reply.notes.findFirst("user");
927 if (label != NULL && *label != '\0')
928 entryData.user = label;
7bbefa01 929
cf9f0261
CT
930 label = reply.notes.findFirst("password");
931 if (label != NULL && *label != '\0')
932 entryData.password = label;
2f1431ea 933#endif
62e76326 934
d9572179 935 dlinkDelete(&state->list, &state->def->queue);
62e76326 936
abdd93d0 937 ExternalACLEntryPointer entry;
4960475f 938 if (cbdataReferenceValid(state->def)) {
0272dd08 939 // only cache OK and ERR results.
2428ce02 940 if (reply.result == Helper::Okay || reply.result == Helper::Error)
1e5562e3 941 entry = external_acl_cache_add(state->def, state->key, entryData);
62e76326 942 else {
abdd93d0 943 const ExternalACLEntryPointer oldentry = static_cast<ExternalACLEntry *>(hash_lookup(state->def->cache, state->key));
62e76326 944
abdd93d0 945 if (oldentry != NULL)
2ae2408b 946 external_acl_cache_delete(state->def, oldentry);
62e76326 947 }
466090ac 948 }
d9572179 949
950 do {
62e76326 951 void *cbdata;
47b0c1fa 952 if (state->callback && cbdataReferenceValidDone(state->callback_data, &cbdata))
62e76326 953 state->callback(cbdata, entry);
954
955 next = state->queue;
f963b531 956 state->queue = NULL;
d9572179 957
f963b531 958 delete state;
d9572179 959
62e76326 960 state = next;
d9572179 961 } while (state);
962}
963
964void
e0f7153c 965ACLExternal::ExternalAclLookup(ACLChecklist *checklist, ACLExternal * me)
d9572179 966{
e0f7153c
AR
967 ExternalACLLookup::Start(checklist, me->data, false);
968}
c8e7608c 969
e0f7153c
AR
970void
971ExternalACLLookup::Start(ACLChecklist *checklist, external_acl_data *acl, bool inBackground)
972{
973 external_acl *def = acl->def;
c0f81932 974
c0941a6a 975 ACLFilledChecklist *ch = Filled(checklist);
c8e7608c 976 const char *key = makeExternalAclKey(ch, acl);
6f58d7d7 977 assert(key); // XXX: will fail if EXT_ACL_IDENT case needs an async lookup
62e76326 978
e0f7153c
AR
979 debugs(82, 2, HERE << (inBackground ? "bg" : "fg") << " lookup in '" <<
980 def->name << "' for '" << key << "'");
62e76326 981
47b0c1fa 982 /* Check for a pending lookup to hook into */
c69ce640 983 // only possible if we are caching results.
e0f7153c 984 externalAclState *oldstate = NULL;
c69ce640 985 if (def->cache_size > 0) {
e0f7153c 986 for (dlink_node *node = def->queue.head; node; node = node->next) {
c69ce640 987 externalAclState *oldstatetmp = static_cast<externalAclState *>(node->data);
62e76326 988
c69ce640
AJ
989 if (strcmp(key, oldstatetmp->key) == 0) {
990 oldstate = oldstatetmp;
991 break;
992 }
47b0c1fa 993 }
994 }
62e76326 995
e0f7153c
AR
996 // A background refresh has no need to piggiback on a pending request:
997 // When the pending request completes, the cache will be refreshed anyway.
998 if (oldstate && inBackground) {
999 debugs(82, 7, HERE << "'" << def->name << "' queue is already being refreshed (ch=" << ch << ")");
47b0c1fa 1000 return;
1001 }
62e76326 1002
f963b531 1003 externalAclState *state = new externalAclState(def, key);
62e76326 1004
e0f7153c
AR
1005 if (!inBackground) {
1006 state->callback = &ExternalACLLookup::LookupDone;
1007 state->callback_data = cbdataReference(checklist);
d9572179 1008 }
62e76326 1009
47b0c1fa 1010 if (oldstate) {
1011 /* Hook into pending lookup */
1012 state->queue = oldstate->queue;
1013 oldstate->queue = state;
1014 } else {
e0f7153c
AR
1015 /* No pending lookup found. Sumbit to helper */
1016
e0f7153c 1017 MemBuf buf;
2fe7eff9 1018 buf.init();
4391cd15 1019 buf.appendf("%s\n", key);
bf8fe701 1020 debugs(82, 4, "externalAclLookup: looking up for '" << key << "' in '" << def->name << "'.");
ab321f4b 1021
6825b101
CT
1022 if (!def->theHelper->trySubmit(buf.buf, externalAclHandleReply, state)) {
1023 debugs(82, 7, HERE << "'" << def->name << "' submit to helper failed");
1024 assert(inBackground); // or the caller should have checked
f963b531 1025 delete state;
6825b101
CT
1026 return;
1027 }
62e76326 1028
47b0c1fa 1029 dlinkAdd(state, &state->list, &def->queue);
62e76326 1030
2fe7eff9 1031 buf.clean();
47b0c1fa 1032 }
62e76326 1033
bf8fe701 1034 debugs(82, 4, "externalAclLookup: will wait for the result of '" << key <<
1035 "' in '" << def->name << "' (ch=" << ch << ").");
d9572179 1036}
1037
1038static void
1039externalAclStats(StoreEntry * sentry)
1040{
f963b531 1041 for (external_acl *p = Config.externalAclHelperList; p; p = p->next) {
62e76326 1042 storeAppendPrintf(sentry, "External ACL Statistics: %s\n", p->name);
1043 storeAppendPrintf(sentry, "Cache size: %d\n", p->cache->count);
bf3e8d5a
AJ
1044 assert(p->theHelper);
1045 p->theHelper->packStatsInto(sentry);
62e76326 1046 storeAppendPrintf(sentry, "\n");
d9572179 1047 }
1048}
1049
6b7d87bb
FC
1050static void
1051externalAclRegisterWithCacheManager(void)
1052{
8822ebee 1053 Mgr::RegisterAction("external_acl",
d9fc6862
A
1054 "External ACL stats",
1055 externalAclStats, 0, 1);
6b7d87bb
FC
1056}
1057
d9572179 1058void
1059externalAclInit(void)
1060{
f963b531 1061 for (external_acl *p = Config.externalAclHelperList; p; p = p->next) {
62e76326 1062 if (!p->cache)
30abd221 1063 p->cache = hash_create((HASHCMP *) strcmp, hashPrime(1024), hash4);
62e76326 1064
1065 if (!p->theHelper)
48d54e4d 1066 p->theHelper = new helper(p->name);
62e76326 1067
1068 p->theHelper->cmdline = p->cmdline;
1069
1af735c7 1070 p->theHelper->childs.updateLimits(p->children);
07eca7e0 1071
62e76326 1072 p->theHelper->ipc_type = IPC_TCP_SOCKET;
1073
cc192b50 1074 p->theHelper->addr = p->local_addr;
1075
62e76326 1076 helperOpenServers(p->theHelper);
d9572179 1077 }
62e76326 1078
ea391f18 1079 externalAclRegisterWithCacheManager();
d9572179 1080}
1081
1082void
1083externalAclShutdown(void)
1084{
1085 external_acl *p;
62e76326 1086
d9572179 1087 for (p = Config.externalAclHelperList; p; p = p->next) {
62e76326 1088 helperShutdown(p->theHelper);
d9572179 1089 }
1090}
225b7b10 1091
1092ExternalACLLookup ExternalACLLookup::instance_;
1093ExternalACLLookup *
1094ExternalACLLookup::Instance()
1095{
1096 return &instance_;
1097}
1098
1099void
1100ExternalACLLookup::checkForAsync(ACLChecklist *checklist)const
1101{
b0dd28ba 1102 /* TODO: optimise this - we probably have a pointer to this
1103 * around somewhere */
97427e90 1104 ACL *acl = ACL::FindByName(AclMatchedName);
ab321f4b 1105 assert(acl);
b0dd28ba 1106 ACLExternal *me = dynamic_cast<ACLExternal *> (acl);
1107 assert (me);
e0f7153c 1108 ACLExternal::ExternalAclLookup(checklist, me);
225b7b10 1109}
1110
e0f7153c 1111/// Called when an async lookup returns
225b7b10 1112void
abdd93d0 1113ExternalACLLookup::LookupDone(void *data, const ExternalACLEntryPointer &result)
225b7b10 1114{
c0941a6a 1115 ACLFilledChecklist *checklist = Filled(static_cast<ACLChecklist*>(data));
abdd93d0 1116 checklist->extacl_entry = result;
6f58d7d7 1117 checklist->resumeNonBlockingCheck(ExternalACLLookup::Instance());
225b7b10 1118}
b0dd28ba 1119
1120/* This registers "external" in the registry. To do dynamic definitions
1121 * of external ACL's, rather than a static prototype, have a Prototype instance
1122 * prototype in the class that defines each external acl 'class'.
1123 * Then, then the external acl instance is created, it self registers under
1124 * it's name.
1125 * Be sure that clone is fully functional for that acl class though!
1126 */
1127ACL::Prototype ACLExternal::RegistryProtoype(&ACLExternal::RegistryEntry_, "external");
1128
1129ACLExternal ACLExternal::RegistryEntry_("external");
1130
1131ACL *
1132ACLExternal::clone() const
1133{
1134 return new ACLExternal(*this);
1135}
1136
86c63190 1137ACLExternal::ACLExternal(char const *theClass) : data(NULL), class_(xstrdup(theClass))
b0dd28ba 1138{}
1139
86c63190 1140ACLExternal::ACLExternal(ACLExternal const & old) : data(NULL), class_(old.class_ ? xstrdup(old.class_) : NULL)
b0dd28ba 1141{
1142 /* we don't have copy constructors for the data yet */
86c63190 1143 assert(!old.data);
b0dd28ba 1144}
1145
b0dd28ba 1146char const *
1147ACLExternal::typeString() const
1148{
1149 return class_;
1150}
1151
e870b1f8 1152bool
1153ACLExternal::isProxyAuth() const
1154{
2f1431ea 1155#if USE_AUTH
e870b1f8 1156 return data->def->require_auth;
2f1431ea
AJ
1157#else
1158 return false;
1159#endif
e870b1f8 1160}
f53969cc 1161