]> git.ipfire.org Git - thirdparty/squid.git/blame - src/store.cc
Fix crash bug in HttpHeader::clean()
[thirdparty/squid.git] / src / store.cc
CommitLineData
164f7660 1
30a4f2a8 2/*
8638fc66 3 * DEBUG: section 20 Storage Manager
30a4f2a8 4 * AUTHOR: Harvest Derived
5 *
2b6662ba 6 * SQUID Web Proxy Cache http://www.squid-cache.org/
e25c139f 7 * ----------------------------------------------------------
30a4f2a8 8 *
2b6662ba 9 * Squid is the result of efforts by numerous individuals from
10 * the Internet community; see the CONTRIBUTORS file for full
11 * details. Many organizations have provided support for Squid's
12 * development; see the SPONSORS file for full details. Squid is
13 * Copyrighted (C) 2001 by the Regents of the University of
14 * California; see the COPYRIGHT file for full details. Squid
15 * incorporates software developed and/or copyrighted by other
16 * sources; see the CREDITS file for full details.
30a4f2a8 17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
26ac0430 22 *
30a4f2a8 23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
26ac0430 27 *
30a4f2a8 28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, write to the Free Software
cbdec147 30 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
e25c139f 31 *
c943f331 32 */
090089c4 33
582c2af2 34#include "squid.h"
b814e8d4 35#include "CacheDigest.h"
ec20038e
AJ
36#include "CacheManager.h"
37#include "comm/Connection.h"
81a94152 38#include "ETag.h"
a553a5a3 39#include "event.h"
04f55905 40#include "fde.h"
af69c635 41#include "globals.h"
582c2af2 42#include "http.h"
528b2c61 43#include "HttpReply.h"
44#include "HttpRequest.h"
528b2c61 45#include "mem_node.h"
582c2af2
FC
46#include "MemObject.h"
47#include "mgr/Registration.h"
48#include "mgr/StoreIoAction.h"
49#include "profiler/Profiler.h"
e452f48d 50#include "repl_modules.h"
f206b652 51#include "RequestFlags.h"
4d5904f7 52#include "SquidConfig.h"
582c2af2 53#include "SquidTime.h"
e4f1fdae 54#include "StatCounters.h"
582c2af2 55#include "stmem.h"
602d9612 56#include "Store.h"
35a28a37 57#include "store_digest.h"
fb548aaf 58#include "store_key_md5.h"
e87137f1 59#include "store_key_md5.h"
10818c0a 60#include "store_log.h"
687f5275 61#include "store_rebuild.h"
e87137f1
FC
62#include "StoreClient.h"
63#include "StoreIOState.h"
64#include "StoreMeta.h"
65#include "StrList.h"
582c2af2 66#include "swap_log_op.h"
e87137f1 67#include "SwapDir.h"
5bed43d6 68#include "tools.h"
9a0a18de 69#if USE_DELAY_POOLS
b67e2c8c 70#include "DelayPools.h"
71#endif
582c2af2
FC
72#if HAVE_LIMITS_H
73#include <limits.h>
74#endif
090089c4 75
06e91875
FC
76#include <stack>
77
090089c4 78#define REBUILD_TIMESTAMP_DELTA_MAX 2
227fbb74 79
c21ad0f5 80#define STORE_IN_MEM_BUCKETS (229)
090089c4 81
4b981814
AJ
82/** \todo Convert these string constants to enum string-arrays generated */
83
26ac0430
AJ
84const char *memStatusStr[] = {
85 "NOT_IN_MEMORY",
86 "IN_MEMORY"
87};
88
89const char *pingStatusStr[] = {
90 "PING_NONE",
91 "PING_WAITING",
92 "PING_DONE"
93};
94
95const char *storeStatusStr[] = {
96 "STORE_OK",
97 "STORE_PENDING"
98};
99
100const char *swapStatusStr[] = {
101 "SWAPOUT_NONE",
102 "SWAPOUT_WRITING",
103 "SWAPOUT_DONE"
104};
9dfb6c1c 105
25b6a907 106/*
107 * This defines an repl type
108 */
109
110typedef struct _storerepl_entry storerepl_entry_t;
111
26ac0430 112struct _storerepl_entry {
25b6a907 113 const char *typestr;
114 REMOVALPOLICYCREATE *create;
115};
116
117static storerepl_entry_t *storerepl_list = NULL;
118
e3ef2b09 119/*
120 * local function prototypes
121 */
007b8be4 122static int getKeyCounter(void);
8423ff74 123static OBJH storeCheckCachableStats;
e42d5181 124static EVH storeLateRelease;
a21fbb54 125
e3ef2b09 126/*
127 * local variables
128 */
06e91875 129static std::stack<StoreEntry*> LateReleaseStack;
04eb0689 130MemAllocator *StoreEntry::pool = NULL;
e6ccf245 131
c8f4eac4 132StorePointer Store::CurrentRoot = NULL;
133
134void
135Store::Root(Store * aRoot)
136{
137 CurrentRoot = aRoot;
138}
139
140void
141Store::Root(StorePointer aRoot)
142{
143 Root(aRoot.getRaw());
144}
145
146void
147Store::Stats(StoreEntry * output)
148{
149 assert (output);
150 Root().stat(*output);
151}
152
153void
154Store::create()
155{}
156
157void
158Store::diskFull()
159{}
160
161void
162Store::sync()
163{}
164
165void
166Store::unlink (StoreEntry &anEntry)
167{
168 fatal("Store::unlink on invalid Store\n");
169}
170
e6ccf245 171void *
3b13a8fd 172StoreEntry::operator new (size_t bytecount)
e6ccf245 173{
3b13a8fd 174 assert (bytecount == sizeof (StoreEntry));
62e76326 175
e6ccf245 176 if (!pool) {
04eb0689 177 pool = memPoolCreate ("StoreEntry", bytecount);
b001e822 178 pool->setChunkSize(2048 * 1024);
e6ccf245 179 }
62e76326 180
b001e822 181 return pool->alloc();
e6ccf245 182}
183
184void
3b13a8fd 185StoreEntry::operator delete (void *address)
e6ccf245 186{
dc47f531 187 pool->freeOne(address);
e6ccf245 188}
189
5ed72359 190void
191StoreEntry::makePublic()
192{
193 /* This object can be cached for a long time */
194
6919be24 195 if (!EBIT_TEST(flags, RELEASE_REQUEST))
d88e3c49 196 setPublicKey();
5ed72359 197}
198
199void
200StoreEntry::makePrivate()
201{
202 /* This object should never be cached at all */
d88e3c49 203 expireNow();
204 releaseRequest(); /* delete object when not used */
5ed72359 205}
206
207void
208StoreEntry::cacheNegatively()
209{
210 /* This object may be negatively cached */
d88e3c49 211 negativeCache();
6919be24 212 makePublic();
5ed72359 213}
214
e6ccf245 215size_t
3b13a8fd 216StoreEntry::inUseCount()
e6ccf245 217{
218 if (!pool)
62e76326 219 return 0;
9f9e06f3 220 return pool->getInUseCount();
e6ccf245 221}
222
332dafa2 223const char *
3b13a8fd 224StoreEntry::getMD5Text() const
332dafa2 225{
226 return storeKeyText((const cache_key *)key);
227}
228
a46d2c0e 229#include "comm.h"
230
231void
232StoreEntry::DeferReader(void *theContext, CommRead const &aRead)
e6ccf245 233{
a46d2c0e 234 StoreEntry *anEntry = (StoreEntry *)theContext;
3e4bebf8 235 anEntry->delayAwareRead(aRead.conn,
a46d2c0e 236 aRead.buf,
237 aRead.len,
65517dc8 238 aRead.callback);
e6ccf245 239}
66cedb85 240
a46d2c0e 241void
3e4bebf8 242StoreEntry::delayAwareRead(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer callback)
a46d2c0e 243{
244 size_t amountToRead = bytesWanted(Range<size_t>(0, len));
245 /* sketch: readdeferer* = getdeferer.
65517dc8 246 * ->deferRead (fd, buf, len, callback, DelayAwareRead, this)
a46d2c0e 247 */
248
249 if (amountToRead == 0) {
250 assert (mem_obj);
251 /* read ahead limit */
252 /* Perhaps these two calls should both live in MemObject */
9a0a18de 253#if USE_DELAY_POOLS
a46d2c0e 254 if (!mem_obj->readAheadPolicyCanRead()) {
a5f42284 255#endif
3e4bebf8 256 mem_obj->delayRead(DeferredRead(DeferReader, this, CommRead(conn, buf, len, callback)));
a46d2c0e 257 return;
9a0a18de 258#if USE_DELAY_POOLS
a46d2c0e 259 }
260
261 /* delay id limit */
3e4bebf8 262 mem_obj->mostBytesAllowed().delayRead(DeferredRead(DeferReader, this, CommRead(conn, buf, len, callback)));
a46d2c0e 263 return;
a5f42284 264
265#endif
266
a46d2c0e 267 }
268
109cf61c 269 if (fd_table[conn->fd].closing()) {
f5f9e44c
AR
270 // Readers must have closing callbacks if they want to be notified. No
271 // readers appeared to care around 2009/12/14 as they skipped reading
272 // for other reasons. Closing may already be true at the delyaAwareRead
273 // call time or may happen while we wait after delayRead() above.
109cf61c 274 debugs(20, 3, HERE << "wont read from closing " << conn << " for " <<
f5f9e44c
AR
275 callback);
276 return; // the read callback will never be called
277 }
278
3e4bebf8 279 comm_read(conn, buf, amountToRead, callback);
a46d2c0e 280}
281
282size_t
384a7590 283StoreEntry::bytesWanted (Range<size_t> const aRange, bool ignoreDelayPools) const
528b2c61 284{
528b2c61 285 if (mem_obj == NULL)
4dc2b072 286 return aRange.end;
62e76326 287
bc87dc25 288#if URL_CHECKSUM_DEBUG
62e76326 289
528b2c61 290 mem_obj->checkUrlChecksum();
62e76326 291
528b2c61 292#endif
62e76326 293
a46d2c0e 294 if (!mem_obj->readAheadPolicyCanRead())
295 return 0;
62e76326 296
384a7590 297 return mem_obj->mostBytesWanted(aRange.end, ignoreDelayPools);
a46d2c0e 298}
62e76326 299
a46d2c0e 300bool
301StoreEntry::checkDeferRead(int fd) const
302{
303 return (bytesWanted(Range<size_t>(0,INT_MAX)) == 0);
304}
62e76326 305
a46d2c0e 306void
307StoreEntry::setNoDelay (bool const newValue)
308{
309 if (mem_obj)
310 mem_obj->setNoDelay(newValue);
528b2c61 311}
bc87dc25 312
f25d697f
AR
313// XXX: Type names mislead. STORE_DISK_CLIENT actually means that we should
314// open swapin file, aggressively trim memory, and ignore read-ahead gap.
315// It does not mean we will read from disk exclusively (or at all!).
316// XXX: May create STORE_DISK_CLIENT with no disk caching configured.
317// XXX: Collapsed clients cannot predict their type.
528b2c61 318store_client_t
319StoreEntry::storeClientType() const
227fbb74 320{
7d31d5fa 321 /* The needed offset isn't in memory
322 * XXX TODO: this is wrong for range requests
323 * as the needed offset may *not* be 0, AND
324 * offset 0 in the memory object is the HTTP headers.
325 */
326
9487bae9
AR
327 assert(mem_obj);
328
528b2c61 329 if (mem_obj->inmem_lo)
62e76326 330 return STORE_DISK_CLIENT;
331
528b2c61 332 if (EBIT_TEST(flags, ENTRY_ABORTED)) {
62e76326 333 /* I don't think we should be adding clients to aborted entries */
e0236918 334 debugs(20, DBG_IMPORTANT, "storeClientType: adding to ENTRY_ABORTED entry");
62e76326 335 return STORE_MEM_CLIENT;
528b2c61 336 }
62e76326 337
528b2c61 338 if (store_status == STORE_OK) {
7d31d5fa 339 /* the object has completed. */
340
344a9006 341 if (mem_obj->inmem_lo == 0 && !isEmpty()) {
47ce0a58 342 if (swap_status == SWAPOUT_DONE) {
e2851fe7 343 debugs(20,7, HERE << mem_obj << " lo: " << mem_obj->inmem_lo << " hi: " << mem_obj->endOffset() << " size: " << mem_obj->object_sz);
e1381638 344 if (mem_obj->endOffset() == mem_obj->object_sz) {
f25d697f 345 /* hot object fully swapped in (XXX: or swapped out?) */
e1381638
AJ
346 return STORE_MEM_CLIENT;
347 }
47ce0a58 348 } else {
e1381638
AJ
349 /* Memory-only, or currently being swapped out */
350 return STORE_MEM_CLIENT;
47ce0a58
HN
351 }
352 }
353 return STORE_DISK_CLIENT;
528b2c61 354 }
62e76326 355
528b2c61 356 /* here and past, entry is STORE_PENDING */
357 /*
358 * If this is the first client, let it be the mem client
359 */
360 if (mem_obj->nclients == 1)
62e76326 361 return STORE_MEM_CLIENT;
362
528b2c61 363 /*
364 * If there is no disk file to open yet, we must make this a
365 * mem client. If we can't open the swapin file before writing
366 * to the client, there is no guarantee that we will be able
367 * to open it later when we really need it.
368 */
369 if (swap_status == SWAPOUT_NONE)
62e76326 370 return STORE_MEM_CLIENT;
371
528b2c61 372 /*
373 * otherwise, make subsequent clients read from disk so they
374 * can not delay the first, and vice-versa.
375 */
376 return STORE_DISK_CLIENT;
227fbb74 377}
378
8ebae981
AJ
379StoreEntry::StoreEntry() :
380 mem_obj(NULL),
ec4c70ce
AJ
381 timestamp(-1),
382 lastref(-1),
8ebae981 383 expires(-1),
c95983c8 384 lastmod(-1),
8ebae981
AJ
385 swap_file_sz(0),
386 refcount(0),
387 flags(0),
388 swap_filen(-1),
389 swap_dirn(-1),
8ebae981
AJ
390 mem_status(NOT_IN_MEMORY),
391 ping_status(PING_NONE),
392 store_status(STORE_PENDING),
1bfe9ade
AR
393 swap_status(SWAPOUT_NONE),
394 lock_count(0)
090089c4 395{
539283df 396 debugs(20, 5, "StoreEntry constructed, this=" << this);
c8f4eac4 397}
62e76326 398
6d8d05b5
DK
399StoreEntry::~StoreEntry()
400{
539283df 401 debugs(20, 5, "StoreEntry destructed, this=" << this);
6d8d05b5
DK
402}
403
0ad2b63b
CT
404#if USE_ADAPTATION
405void
406StoreEntry::deferProducer(const AsyncCall::Pointer &producer)
407{
408 if (!deferredProducer)
409 deferredProducer = producer;
410 else
e83cdc25 411 debugs(20, 5, HERE << "Deferred producer call is allready set to: " <<
0ad2b63b
CT
412 *deferredProducer << ", requested call: " << *producer);
413}
414
415void
416StoreEntry::kickProducer()
417{
e83cdc25 418 if (deferredProducer != NULL) {
0ad2b63b
CT
419 ScheduleCallHere(deferredProducer);
420 deferredProducer = NULL;
421 }
422}
423#endif
424
3900307b 425void
426StoreEntry::destroyMemObject()
090089c4 427{
3900307b 428 debugs(20, 3, HERE << "destroyMemObject " << mem_obj);
29c56e41
AR
429
430 if (MemObject *mem = mem_obj) {
431 // Store::Root() is FATALly missing during shutdown
432 if (mem->xitTable.index >= 0 && !shutting_down)
433 Store::Root().transientsDisconnect(*mem);
434 if (mem->memCache.index >= 0 && !shutting_down)
435 Store::Root().memoryDisconnect(*this);
436
437 setMemStatus(NOT_IN_MEMORY);
438 mem_obj = NULL;
439 delete mem;
440 }
090089c4 441}
442
c8f4eac4 443void
528b2c61 444destroyStoreEntry(void *data)
090089c4 445{
59dbbc5c 446 debugs(20, 3, HERE << "destroyStoreEntry: destroying " << data);
c8f4eac4 447 StoreEntry *e = static_cast<StoreEntry *>(static_cast<hash_link *>(data));
9e975e4e 448 assert(e != NULL);
62e76326 449
e6ccf245 450 if (e == NullStoreEntry::getInstance())
62e76326 451 return;
452
fa6d2c65
AR
453 // Store::Root() is FATALly missing during shutdown
454 if (e->swap_filen >= 0 && !shutting_down) {
455 SwapDir &sd = dynamic_cast<SwapDir&>(*e->store());
456 sd.disconnect(*e);
457 }
458
3900307b 459 e->destroyMemObject();
62e76326 460
3900307b 461 e->hashDelete();
62e76326 462
332dafa2 463 assert(e->key == NULL);
62e76326 464
e6ccf245 465 delete e;
227fbb74 466}
090089c4 467
090089c4 468/* ----- INTERFACE BETWEEN STORAGE MANAGER AND HASH TABLE FUNCTIONS --------- */
469
f09f5b26 470void
3900307b 471StoreEntry::hashInsert(const cache_key * someKey)
090089c4 472{
4475555f 473 debugs(20, 3, "StoreEntry::hashInsert: Inserting Entry " << *this << " key '" << storeKeyText(someKey) << "'");
3900307b 474 key = storeKeyDup(someKey);
475 hash_join(store_table, this);
090089c4 476}
477
3900307b 478void
479StoreEntry::hashDelete()
090089c4 480{
cb868059
AR
481 if (key) { // some test cases do not create keys and do not hashInsert()
482 hash_remove_link(store_table, this);
483 storeKeyFree((const cache_key *)key);
484 key = NULL;
485 }
090089c4 486}
487
090089c4 488/* -------------------------------------------------------------------------- */
489
090089c4 490/* get rid of memory copy of the object */
d88e3c49 491void
492StoreEntry::purgeMem()
090089c4 493{
d88e3c49 494 if (mem_obj == NULL)
62e76326 495 return;
496
bf8fe701 497 debugs(20, 3, "StoreEntry::purgeMem: Freeing memory-copy of " << getMD5Text());
62e76326 498
ce49546e 499 Store::Root().memoryUnlink(*this);
62e76326 500
d88e3c49 501 if (swap_status != SWAPOUT_DONE)
502 release();
090089c4 503}
504
6a566b9c 505void
18994992 506StoreEntry::lock(const char *context)
6a566b9c 507{
5db6bf73 508 ++lock_count;
18994992
AR
509 debugs(20, 3, context << " locked key " << getMD5Text() << ' ' << *this);
510}
511
512void
9d4e9cfb
AR
513StoreEntry::touch()
514{
c21ad0f5 515 lastref = squid_curtime;
516 Store::Root().reference(*this);
090089c4 517}
518
43ae1d95 519void
520StoreEntry::setReleaseFlag()
521{
522 if (EBIT_TEST(flags, RELEASE_REQUEST))
523 return;
524
bf8fe701 525 debugs(20, 3, "StoreEntry::setReleaseFlag: '" << getMD5Text() << "'");
43ae1d95 526
527 EBIT_SET(flags, RELEASE_REQUEST);
1bfe9ade
AR
528
529 Store::Root().markForUnlink(*this);
43ae1d95 530}
531
b8d8561b 532void
d88e3c49 533StoreEntry::releaseRequest()
2285407f 534{
d88e3c49 535 if (EBIT_TEST(flags, RELEASE_REQUEST))
62e76326 536 return;
537
6919be24 538 setReleaseFlag(); // makes validToSend() false, preventing future hits
62e76326 539
d88e3c49 540 setPrivateKey();
2285407f 541}
542
b8d8561b 543int
18994992 544StoreEntry::unlock(const char *context)
090089c4 545{
18994992
AR
546 debugs(20, 3, (context ? context : "somebody") <<
547 " unlocking key " << getMD5Text() << ' ' << *this);
c47b98ac 548 assert(lock_count > 0);
5e263176 549 --lock_count;
62e76326 550
c21ad0f5 551 if (lock_count)
552 return (int) lock_count;
62e76326 553
c21ad0f5 554 if (store_status == STORE_PENDING)
555 setReleaseFlag();
62e76326 556
c21ad0f5 557 assert(storePendingNClients(this) == 0);
62e76326 558
9199139f 559 if (EBIT_TEST(flags, RELEASE_REQUEST)) {
5f33b71d 560 this->release();
984f9874
AR
561 return 0;
562 }
563
9487bae9 564 if (EBIT_TEST(flags, KEY_PRIVATE))
e0236918 565 debugs(20, DBG_IMPORTANT, "WARNING: " << __FILE__ << ":" << __LINE__ << ": found KEY_PRIVATE");
62e76326 566
9487bae9 567 Store::Root().handleIdleEntry(*this); // may delete us
6c895381 568 return 0;
090089c4 569}
570
e6ccf245 571void
60745f24 572StoreEntry::getPublicByRequestMethod (StoreClient *aClient, HttpRequest * request, const HttpRequestMethod& method)
e6ccf245 573{
574 assert (aClient);
3b13a8fd 575 StoreEntry *result = storeGetPublicByRequestMethod( request, method);
62e76326 576
e6ccf245 577 if (!result)
62e76326 578 aClient->created (NullStoreEntry::getInstance());
e6ccf245 579 else
62e76326 580 aClient->created (result);
e6ccf245 581}
582
583void
190154cf 584StoreEntry::getPublicByRequest (StoreClient *aClient, HttpRequest * request)
e6ccf245 585{
586 assert (aClient);
3b13a8fd 587 StoreEntry *result = storeGetPublicByRequest (request);
62e76326 588
e6ccf245 589 if (!result)
62e76326 590 result = NullStoreEntry::getInstance();
591
e6ccf245 592 aClient->created (result);
593}
594
595void
60745f24 596StoreEntry::getPublic (StoreClient *aClient, const char *uri, const HttpRequestMethod& method)
e6ccf245 597{
598 assert (aClient);
3b13a8fd 599 StoreEntry *result = storeGetPublic (uri, method);
62e76326 600
e6ccf245 601 if (!result)
62e76326 602 result = NullStoreEntry::getInstance();
603
e6ccf245 604 aClient->created (result);
605}
606
08e5d64f 607StoreEntry *
60745f24 608storeGetPublic(const char *uri, const HttpRequestMethod& method)
08e5d64f 609{
c8f4eac4 610 return Store::Root().get(storeKeyPublic(uri, method));
08e5d64f 611}
612
f66a9ef4 613StoreEntry *
60745f24 614storeGetPublicByRequestMethod(HttpRequest * req, const HttpRequestMethod& method)
f66a9ef4 615{
c8f4eac4 616 return Store::Root().get(storeKeyPublicByRequestMethod(req, method));
f66a9ef4 617}
618
619StoreEntry *
190154cf 620storeGetPublicByRequest(HttpRequest * req)
f66a9ef4 621{
622 StoreEntry *e = storeGetPublicByRequestMethod(req, req->method);
62e76326 623
c2a7cefd 624 if (e == NULL && req->method == Http::METHOD_HEAD)
62e76326 625 /* We can generate a HEAD reply from a cached GET object */
c2a7cefd 626 e = storeGetPublicByRequestMethod(req, Http::METHOD_GET);
62e76326 627
f66a9ef4 628 return e;
629}
630
007b8be4 631static int
632getKeyCounter(void)
04e8dbaa 633{
007b8be4 634 static int key_counter = 0;
62e76326 635
007b8be4 636 if (++key_counter < 0)
62e76326 637 key_counter = 1;
638
007b8be4 639 return key_counter;
04e8dbaa 640}
641
c8f4eac4 642/* RBC 20050104 AFAICT this should become simpler:
643 * rather than reinserting with a special key it should be marked
644 * as 'released' and then cleaned up when refcounting indicates.
645 * the StoreHashIndex could well implement its 'released' in the
646 * current manner.
647 * Also, clean log writing should skip over ia,t
648 * Otherwise, we need a 'remove from the index but not the store
649 * concept'.
650 */
6c57e268 651void
d88e3c49 652StoreEntry::setPrivateKey()
227fbb74 653{
9fb13bb6 654 const cache_key *newkey;
62e76326 655
d88e3c49 656 if (key && EBIT_TEST(flags, KEY_PRIVATE))
c21ad0f5 657 return; /* is already private */
62e76326 658
d88e3c49 659 if (key) {
6919be24
AR
660 setReleaseFlag(); // will markForUnlink(); all caches/workers will know
661
662 // TODO: move into SwapDir::markForUnlink() already called by Root()
d88e3c49 663 if (swap_filen > -1)
664 storeDirSwapLog(this, SWAP_LOG_DEL);
62e76326 665
3900307b 666 hashDelete();
b109de6b 667 }
62e76326 668
c877c0bc 669 if (mem_obj && mem_obj->hasUris()) {
d88e3c49 670 mem_obj->id = getKeyCounter();
c877c0bc 671 newkey = storeKeyPrivate(mem_obj->storeId(), mem_obj->method, mem_obj->id);
9fb13bb6 672 } else {
c2a7cefd 673 newkey = storeKeyPrivate("JUNK", Http::METHOD_NONE, getKeyCounter());
9fb13bb6 674 }
62e76326 675
9fb13bb6 676 assert(hash_lookup(store_table, newkey) == NULL);
d88e3c49 677 EBIT_SET(flags, KEY_PRIVATE);
3900307b 678 hashInsert(newkey);
227fbb74 679}
680
b8d8561b 681void
d88e3c49 682StoreEntry::setPublicKey()
227fbb74 683{
9fb13bb6 684 const cache_key *newkey;
62e76326 685
d88e3c49 686 if (key && !EBIT_TEST(flags, KEY_PRIVATE))
c21ad0f5 687 return; /* is already public */
62e76326 688
d88e3c49 689 assert(mem_obj);
62e76326 690
f3e570e9 691 /*
692 * We can't make RELEASE_REQUEST objects public. Depending on
693 * when RELEASE_REQUEST gets set, we might not be swapping out
694 * the object. If we're not swapping out, then subsequent
695 * store clients won't be able to access object data which has
696 * been freed from memory.
d87ebd78 697 *
6919be24 698 * If RELEASE_REQUEST is set, setPublicKey() should not be called.
f3e570e9 699 */
6a566b9c 700#if MORE_DEBUG_OUTPUT
62e76326 701
d88e3c49 702 if (EBIT_TEST(flags, RELEASE_REQUEST))
e0236918 703 debugs(20, DBG_IMPORTANT, "assertion failed: RELEASE key " << key << ", url " << mem_obj->url);
62e76326 704
2b906e48 705#endif
62e76326 706
d88e3c49 707 assert(!EBIT_TEST(flags, RELEASE_REQUEST));
62e76326 708
d88e3c49 709 if (mem_obj->request) {
710 HttpRequest *request = mem_obj->request;
62e76326 711
d88e3c49 712 if (!mem_obj->vary_headers) {
62e76326 713 /* First handle the case where the object no longer varies */
714 safe_free(request->vary_headers);
715 } else {
d88e3c49 716 if (request->vary_headers && strcmp(request->vary_headers, mem_obj->vary_headers) != 0) {
62e76326 717 /* Oops.. the variance has changed. Kill the base object
718 * to record the new variance key
719 */
c21ad0f5 720 safe_free(request->vary_headers); /* free old "bad" variance key */
c877c0bc 721 if (StoreEntry *pe = storeGetPublic(mem_obj->storeId(), mem_obj->method))
5f33b71d 722 pe->release();
62e76326 723 }
724
725 /* Make sure the request knows the variance status */
726 if (!request->vary_headers) {
d88e3c49 727 const char *vary = httpMakeVaryMark(request, mem_obj->getReply());
62e76326 728
729 if (vary)
730 request->vary_headers = xstrdup(vary);
731 }
732 }
733
9487bae9
AR
734 // TODO: storeGetPublic() calls below may create unlocked entries.
735 // We should add/use storeHas() API or lock/unlock those entries.
c877c0bc 736 if (mem_obj->vary_headers && !storeGetPublic(mem_obj->storeId(), mem_obj->method)) {
62e76326 737 /* Create "vary" base object */
30abd221 738 String vary;
c877c0bc 739 StoreEntry *pe = storeCreateEntry(mem_obj->storeId(), mem_obj->logUri(), request->flags, request->method);
62e76326 740 /* We are allowed to do this typecast */
eab8dcfa 741 HttpReply *rep = new HttpReply;
955394ce 742 rep->setHeaders(Http::scOkay, "Internal marker object", "x-squid-internal/vary", -1, -1, squid_curtime + 100000);
d88e3c49 743 vary = mem_obj->getReply()->header.getList(HDR_VARY);
62e76326 744
30abd221 745 if (vary.size()) {
62e76326 746 /* Again, we own this structure layout */
b4f2886c 747 rep->header.putStr(HDR_VARY, vary.termedBuf());
30abd221 748 vary.clean();
62e76326 749 }
750
f66a9ef4 751#if X_ACCELERATOR_VARY
d88e3c49 752 vary = mem_obj->getReply()->header.getList(HDR_X_ACCELERATOR_VARY);
62e76326 753
b38b26cb 754 if (vary.size() > 0) {
62e76326 755 /* Again, we own this structure layout */
b4197865 756 rep->header.putStr(HDR_X_ACCELERATOR_VARY, vary.termedBuf());
30abd221 757 vary.clean();
62e76326 758 }
759
f66a9ef4 760#endif
b8a899c0 761 pe->replaceHttpReply(rep, false); // no write until key is public
62e76326 762
3900307b 763 pe->timestampsSet();
ba27c9a0 764
eab8dcfa 765 pe->makePublic();
62e76326 766
b8a899c0
AR
767 pe->startWriting(); // after makePublic()
768
62e76326 769 pe->complete();
eab8dcfa 770
1bfe9ade 771 pe->unlock("StoreEntry::setPublicKey+Vary");
62e76326 772 }
773
d88e3c49 774 newkey = storeKeyPublicByRequest(mem_obj->request);
f66a9ef4 775 } else
c877c0bc 776 newkey = storeKeyPublic(mem_obj->storeId(), mem_obj->method);
62e76326 777
c877c0bc
AR
778 if (StoreEntry *e2 = (StoreEntry *)hash_lookup(store_table, newkey)) {
779 debugs(20, 3, "Making old " << *e2 << " private.");
d88e3c49 780 e2->setPrivateKey();
5f33b71d 781 e2->release();
62e76326 782
d88e3c49 783 if (mem_obj->request)
784 newkey = storeKeyPublicByRequest(mem_obj->request);
62e76326 785 else
c877c0bc 786 newkey = storeKeyPublic(mem_obj->storeId(), mem_obj->method);
6eb42cae 787 }
62e76326 788
d88e3c49 789 if (key)
3900307b 790 hashDelete();
62e76326 791
d88e3c49 792 EBIT_CLR(flags, KEY_PRIVATE);
62e76326 793
3900307b 794 hashInsert(newkey);
62e76326 795
d88e3c49 796 if (swap_filen > -1)
797 storeDirSwapLog(this, SWAP_LOG_ADD);
227fbb74 798}
799
b8d8561b 800StoreEntry *
1bfe9ade 801storeCreatePureEntry(const char *url, const char *log_url, const RequestFlags &flags, const HttpRequestMethod& method)
090089c4 802{
090089c4 803 StoreEntry *e = NULL;
bf8fe701 804 debugs(20, 3, "storeCreateEntry: '" << url << "'");
090089c4 805
c877c0bc 806 e = new StoreEntry();
c877c0bc
AR
807 e->makeMemObject();
808 e->mem_obj->setUris(url, log_url, method);
62e76326 809
45e5102d 810 if (flags.cachable) {
62e76326 811 EBIT_CLR(e->flags, RELEASE_REQUEST);
090089c4 812 } else {
d88e3c49 813 e->releaseRequest();
090089c4 814 }
62e76326 815
234967c9 816 e->store_status = STORE_PENDING;
090089c4 817 e->refcount = 0;
b8de7ebe 818 e->lastref = squid_curtime;
3900307b 819 e->timestamp = -1; /* set in StoreEntry::timestampsSet() */
30a4f2a8 820 e->ping_status = PING_NONE;
d46a87a8 821 EBIT_SET(e->flags, ENTRY_VALIDATED);
090089c4 822 return e;
823}
824
1bfe9ade
AR
825StoreEntry *
826storeCreateEntry(const char *url, const char *logUrl, const RequestFlags &flags, const HttpRequestMethod& method)
827{
828 StoreEntry *e = storeCreatePureEntry(url, logUrl, flags, method);
829 e->lock("storeCreateEntry");
830
831 if (neighbors_do_private_keys || !flags.hierarchical)
832 e->setPrivateKey();
833 else
834 e->setPublicKey();
835
836 return e;
837}
838
6eb42cae 839/* Mark object as expired */
b8d8561b 840void
d88e3c49 841StoreEntry::expireNow()
9174e204 842{
bf8fe701 843 debugs(20, 3, "StoreEntry::expireNow: '" << getMD5Text() << "'");
d88e3c49 844 expires = squid_curtime;
9174e204 845}
846
528b2c61 847void
848StoreEntry::write (StoreIOBuffer writeBuffer)
849{
850 assert(mem_obj != NULL);
528b2c61 851 /* This assert will change when we teach the store to update */
d2639a5b 852 PROF_start(StoreEntry_write);
528b2c61 853 assert(store_status == STORE_PENDING);
62e76326 854
55759ffb
AR
855 // XXX: caller uses content offset, but we also store headers
856 if (const HttpReply *reply = mem_obj->getReply())
857 writeBuffer.offset += reply->hdr_sz;
858
d2639a5b 859 debugs(20, 5, "storeWrite: writing " << writeBuffer.length << " bytes for '" << getMD5Text() << "'");
860 PROF_stop(StoreEntry_write);
528b2c61 861 storeGetMemSpace(writeBuffer.length);
55759ffb
AR
862 mem_obj->write(writeBuffer);
863
864 if (!EBIT_TEST(flags, DELAY_SENDING))
865 invokeHandlers();
528b2c61 866}
867
c21ad0f5 868/* Append incoming data from a primary server to an entry. */
869void
870StoreEntry::append(char const *buf, int len)
871{
872 assert(mem_obj != NULL);
3a1c3e2f 873 assert(len >= 0);
c21ad0f5 874 assert(store_status == STORE_PENDING);
528b2c61 875
876 StoreIOBuffer tempBuffer;
877 tempBuffer.data = (char *)buf;
878 tempBuffer.length = len;
aa18a4ca 879 /*
880 * XXX sigh, offset might be < 0 here, but it gets "corrected"
881 * later. This offset crap is such a mess.
882 */
c21ad0f5 883 tempBuffer.offset = mem_obj->endOffset() - (getReply() ? getReply()->hdr_sz : 0);
884 write(tempBuffer);
090089c4 885}
886
b8d8561b 887void
fe4e214f 888storeAppendPrintf(StoreEntry * e, const char *fmt,...)
15c05bb0 889{
62d32805 890 va_list args;
891 va_start(args, fmt);
62e76326 892
cb69b4c7 893 storeAppendVPrintf(e, fmt, args);
894 va_end(args);
895}
896
897/* used be storeAppendPrintf and Packer */
898void
899storeAppendVPrintf(StoreEntry * e, const char *fmt, va_list vargs)
900{
901 LOCAL_ARRAY(char, buf, 4096);
15c05bb0 902 buf[0] = '\0';
cb69b4c7 903 vsnprintf(buf, 4096, fmt, vargs);
3900307b 904 e->append(buf, strlen(buf));
c30c5a73 905}
906
26ac0430 907struct _store_check_cachable_hist {
62e76326 908
26ac0430 909 struct {
62e76326 910 int non_get;
911 int not_entry_cachable;
912 int wrong_content_length;
913 int negative_cached;
914 int too_big;
915 int too_small;
916 int private_key;
917 int too_many_open_files;
918 int too_many_open_fds;
2fadd50d 919 } no;
62e76326 920
26ac0430 921 struct {
62e76326 922 int Default;
2fadd50d
HN
923 } yes;
924} store_check_cachable_hist;
8423ff74 925
c47511fd 926int
927storeTooManyDiskFilesOpen(void)
928{
929 if (Config.max_open_disk_fds == 0)
62e76326 930 return 0;
931
83a29c95 932 if (store_open_disk_fd > Config.max_open_disk_fds)
62e76326 933 return 1;
934
c47511fd 935 return 0;
936}
937
3900307b 938int
939StoreEntry::checkTooSmall()
d20b1cd0 940{
3900307b 941 if (EBIT_TEST(flags, ENTRY_SPECIAL))
62e76326 942 return 0;
943
3900307b 944 if (STORE_OK == store_status)
945 if (mem_obj->object_sz < 0 ||
26ac0430 946 mem_obj->object_sz < Config.Store.minObjectSize)
62e76326 947 return 1;
3900307b 948 if (getReply()->content_length > -1)
47f6e231 949 if (getReply()->content_length < Config.Store.minObjectSize)
62e76326 950 return 1;
d20b1cd0 951 return 0;
952}
953
ddc9b32c
AR
954// TODO: remove checks already performed by swapoutPossible()
955// TODO: move "too many open..." checks outside -- we are called too early/late
f09f5b26 956int
3900307b 957StoreEntry::checkCachable()
6602e70e 958{
2ac237e2 959#if CACHE_ALL_METHODS
62e76326 960
c2a7cefd 961 if (mem_obj->method != Http::METHOD_GET) {
bf8fe701 962 debugs(20, 2, "StoreEntry::checkCachable: NO: non-GET method");
5db6bf73 963 ++store_check_cachable_hist.no.non_get;
2ac237e2 964 } else
965#endif
3900307b 966 if (store_status == STORE_OK && EBIT_TEST(flags, ENTRY_BAD_LENGTH)) {
bf8fe701 967 debugs(20, 2, "StoreEntry::checkCachable: NO: wrong content-length");
5db6bf73 968 ++store_check_cachable_hist.no.wrong_content_length;
6919be24 969 } else if (EBIT_TEST(flags, RELEASE_REQUEST)) {
bf8fe701 970 debugs(20, 2, "StoreEntry::checkCachable: NO: not cachable");
6919be24 971 ++store_check_cachable_hist.no.not_entry_cachable; // TODO: rename?
3900307b 972 } else if (EBIT_TEST(flags, ENTRY_NEGCACHED)) {
bf8fe701 973 debugs(20, 3, "StoreEntry::checkCachable: NO: negative cached");
5db6bf73 974 ++store_check_cachable_hist.no.negative_cached;
c21ad0f5 975 return 0; /* avoid release call below */
3900307b 976 } else if ((getReply()->content_length > 0 &&
b51ec8c8
AJ
977 getReply()->content_length > store_maxobjsize) ||
978 mem_obj->endOffset() > store_maxobjsize) {
bf8fe701 979 debugs(20, 2, "StoreEntry::checkCachable: NO: too big");
5db6bf73 980 ++store_check_cachable_hist.no.too_big;
3900307b 981 } else if (checkTooSmall()) {
bf8fe701 982 debugs(20, 2, "StoreEntry::checkCachable: NO: too small");
5db6bf73 983 ++store_check_cachable_hist.no.too_small;
3900307b 984 } else if (EBIT_TEST(flags, KEY_PRIVATE)) {
bf8fe701 985 debugs(20, 3, "StoreEntry::checkCachable: NO: private key");
5db6bf73 986 ++store_check_cachable_hist.no.private_key;
3900307b 987 } else if (swap_status != SWAPOUT_NONE) {
62e76326 988 /*
989 * here we checked the swap_status because the remaining
990 * cases are only relevant only if we haven't started swapping
991 * out the object yet.
992 */
993 return 1;
994 } else if (storeTooManyDiskFilesOpen()) {
bf8fe701 995 debugs(20, 2, "StoreEntry::checkCachable: NO: too many disk files open");
5db6bf73 996 ++store_check_cachable_hist.no.too_many_open_files;
62e76326 997 } else if (fdNFree() < RESERVED_FD) {
bf8fe701 998 debugs(20, 2, "StoreEntry::checkCachable: NO: too many FD's open");
5db6bf73 999 ++store_check_cachable_hist.no.too_many_open_fds;
62e76326 1000 } else {
5db6bf73 1001 ++store_check_cachable_hist.yes.Default;
62e76326 1002 return 1;
1003 }
1004
3900307b 1005 releaseRequest();
6602e70e 1006 return 0;
1007}
1008
3900307b 1009void
1010storeCheckCachableStats(StoreEntry *sentry)
8423ff74 1011{
c40acff3 1012 storeAppendPrintf(sentry, "Category\t Count\n");
1013
a0cd8f99 1014#if CACHE_ALL_METHODS
62e76326 1015
8423ff74 1016 storeAppendPrintf(sentry, "no.non_get\t%d\n",
62e76326 1017 store_check_cachable_hist.no.non_get);
a0cd8f99 1018#endif
62e76326 1019
8423ff74 1020 storeAppendPrintf(sentry, "no.not_entry_cachable\t%d\n",
62e76326 1021 store_check_cachable_hist.no.not_entry_cachable);
8423ff74 1022 storeAppendPrintf(sentry, "no.wrong_content_length\t%d\n",
62e76326 1023 store_check_cachable_hist.no.wrong_content_length);
8423ff74 1024 storeAppendPrintf(sentry, "no.negative_cached\t%d\n",
62e76326 1025 store_check_cachable_hist.no.negative_cached);
8423ff74 1026 storeAppendPrintf(sentry, "no.too_big\t%d\n",
62e76326 1027 store_check_cachable_hist.no.too_big);
d20b1cd0 1028 storeAppendPrintf(sentry, "no.too_small\t%d\n",
62e76326 1029 store_check_cachable_hist.no.too_small);
8423ff74 1030 storeAppendPrintf(sentry, "no.private_key\t%d\n",
62e76326 1031 store_check_cachable_hist.no.private_key);
c5f627c2 1032 storeAppendPrintf(sentry, "no.too_many_open_files\t%d\n",
62e76326 1033 store_check_cachable_hist.no.too_many_open_files);
59ffcdf8 1034 storeAppendPrintf(sentry, "no.too_many_open_fds\t%d\n",
62e76326 1035 store_check_cachable_hist.no.too_many_open_fds);
8423ff74 1036 storeAppendPrintf(sentry, "yes.default\t%d\n",
62e76326 1037 store_check_cachable_hist.yes.Default);
8423ff74 1038}
1039
b8d8561b 1040void
528b2c61 1041StoreEntry::complete()
090089c4 1042{
bf8fe701 1043 debugs(20, 3, "storeComplete: '" << getMD5Text() << "'");
62e76326 1044
528b2c61 1045 if (store_status != STORE_PENDING) {
62e76326 1046 /*
1047 * if we're not STORE_PENDING, then probably we got aborted
1048 * and there should be NO clients on this entry
1049 */
1050 assert(EBIT_TEST(flags, ENTRY_ABORTED));
1051 assert(mem_obj->nclients == 0);
1052 return;
b6403fac 1053 }
62e76326 1054
7d31d5fa 1055 /* This is suspect: mem obj offsets include the headers. do we adjust for that
1056 * in use of object_sz?
1057 */
528b2c61 1058 mem_obj->object_sz = mem_obj->endOffset();
7d31d5fa 1059
528b2c61 1060 store_status = STORE_OK;
7d31d5fa 1061
528b2c61 1062 assert(mem_status == NOT_IN_MEMORY);
62e76326 1063
528b2c61 1064 if (!validLength()) {
62e76326 1065 EBIT_SET(flags, ENTRY_BAD_LENGTH);
d88e3c49 1066 releaseRequest();
41587298 1067 }
62e76326 1068
6cfa8966 1069#if USE_CACHE_DIGESTS
528b2c61 1070 if (mem_obj->request)
62e76326 1071 mem_obj->request->hier.store_complete_stop = current_time;
1072
39edba21 1073#endif
d20b1cd0 1074 /*
d88e3c49 1075 * We used to call invokeHandlers, then storeSwapOut. However,
d20b1cd0 1076 * Madhukar Reddy <myreddy@persistence.com> reported that
1077 * responses without content length would sometimes get released
1078 * in client_side, thinking that the response is incomplete.
1079 */
d88e3c49 1080 invokeHandlers();
7e3e1d01 1081}
1082
090089c4 1083/*
474cac1b 1084 * Someone wants to abort this transfer. Set the reason in the
1085 * request structure, call the server-side callback and mark the
2b906e48 1086 * entry for releasing
090089c4 1087 */
b8d8561b 1088void
bfb55b6f 1089StoreEntry::abort()
090089c4 1090{
5db6bf73 1091 ++statCounter.aborted_requests;
bfb55b6f 1092 assert(store_status == STORE_PENDING);
1093 assert(mem_obj != NULL);
bf8fe701 1094 debugs(20, 6, "storeAbort: " << getMD5Text());
34266cde 1095
1bfe9ade 1096 lock("StoreEntry::abort"); /* lock while aborting */
d88e3c49 1097 negativeCache();
34266cde 1098
d88e3c49 1099 releaseRequest();
34266cde 1100
bfb55b6f 1101 EBIT_SET(flags, ENTRY_ABORTED);
34266cde 1102
3900307b 1103 setMemStatus(NOT_IN_MEMORY);
34266cde 1104
bfb55b6f 1105 store_status = STORE_OK;
34266cde 1106
474cac1b 1107 /* Notify the server side */
62e76326 1108
8ea67c2b 1109 /*
1110 * DPW 2007-05-07
1111 * Should we check abort.data for validity?
1112 */
bfb55b6f 1113 if (mem_obj->abort.callback) {
26ac0430 1114 if (!cbdataReferenceValid(mem_obj->abort.data))
e0236918 1115 debugs(20, DBG_IMPORTANT,HERE << "queueing event when abort.data is not valid");
bfb55b6f 1116 eventAdd("mem_obj->abort.callback",
1117 mem_obj->abort.callback,
1118 mem_obj->abort.data,
62e76326 1119 0.0,
8ea67c2b 1120 true);
26ac0430 1121 unregisterAbort();
bfcaf585 1122 }
62e76326 1123
1124 /* XXX Should we reverse these two, so that there is no
26ac0430 1125 * unneeded disk swapping triggered?
528b2c61 1126 */
474cac1b 1127 /* Notify the client side */
d88e3c49 1128 invokeHandlers();
62e76326 1129
aa1a691e
AR
1130 // abort swap out, invalidating what was created so far (release follows)
1131 swapOutFileClose(StoreIOState::writerGone);
62e76326 1132
1bfe9ade 1133 unlock("StoreEntry::abort"); /* unlock */
090089c4 1134}
1135
6d3c2758
HN
1136/**
1137 * Clear Memory storage to accommodate the given object len
1138 */
1139void
d4432957 1140storeGetMemSpace(int size)
090089c4 1141{
1d5161bd 1142 PROF_start(storeGetMemSpace);
b32508fb 1143 StoreEntry *e = NULL;
20cba4b4 1144 int released = 0;
b32508fb 1145 static time_t last_check = 0;
528b2c61 1146 size_t pages_needed;
6a566b9c 1147 RemovalPurgeWalker *walker;
62e76326 1148
1d5161bd 1149 if (squid_curtime == last_check) {
1150 PROF_stop(storeGetMemSpace);
62e76326 1151 return;
1d5161bd 1152 }
62e76326 1153
b32508fb 1154 last_check = squid_curtime;
62e76326 1155
2ad51840 1156 pages_needed = (size + SM_PAGE_SIZE-1) / SM_PAGE_SIZE;
62e76326 1157
1d5161bd 1158 if (mem_node::InUseCount() + pages_needed < store_pages_max) {
1159 PROF_stop(storeGetMemSpace);
62e76326 1160 return;
1d5161bd 1161 }
62e76326 1162
e4049756 1163 debugs(20, 2, "storeGetMemSpace: Starting, need " << pages_needed <<
1164 " pages");
62e76326 1165
6a566b9c 1166 /* XXX what to set as max_scan here? */
1167 walker = mem_policy->PurgeInit(mem_policy, 100000);
62e76326 1168
c1dd71ae 1169 while ((e = walker->Next(walker))) {
d88e3c49 1170 e->purgeMem();
5db6bf73 1171 ++released;
62e76326 1172
1173 if (mem_node::InUseCount() + pages_needed < store_pages_max)
1174 break;
8350fe9b 1175 }
62e76326 1176
6a566b9c 1177 walker->Done(walker);
bf8fe701 1178 debugs(20, 3, "storeGetMemSpace stats:");
1179 debugs(20, 3, " " << std::setw(6) << hot_obj_count << " HOT objects");
1180 debugs(20, 3, " " << std::setw(6) << released << " were released");
1d5161bd 1181 PROF_stop(storeGetMemSpace);
090089c4 1182}
1183
c8f4eac4 1184/* thunk through to Store::Root().maintain(). Note that this would be better still
26ac0430
AJ
1185 * if registered against the root store itself, but that requires more complex
1186 * update logic - bigger fish to fry first. Long term each store when
c8f4eac4 1187 * it becomes active will self register
1188 */
1189void
1190Store::Maintain(void *notused)
1191{
1192 Store::Root().maintain();
1193
1194 /* Reregister a maintain event .. */
1195 eventAdd("MaintainSwapSpace", Maintain, NULL, 1.0, 1);
1196
1197}
1198
090089c4 1199/* The maximum objects to scan for maintain storage space */
c21ad0f5 1200#define MAINTAIN_MAX_SCAN 1024
1201#define MAINTAIN_MAX_REMOVE 64
090089c4 1202
2b906e48 1203/*
fcefe642 1204 * This routine is to be called by main loop in main.c.
1205 * It removes expired objects on only one bucket for each time called.
fcefe642 1206 *
1207 * This should get called 1/s from main().
1208 */
679ac4f0 1209void
c8f4eac4 1210StoreController::maintain()
090089c4 1211{
6a566b9c 1212 static time_t last_warn_time = 0;
cd748f27 1213
88bfe092 1214 PROF_start(storeMaintainSwapSpace);
c8f4eac4 1215 swapDir->maintain();
62e76326 1216
c8f4eac4 1217 /* this should be emitted by the oversize dir, not globally */
62e76326 1218
39c1e1d9 1219 if (Store::Root().currentSize() > Store::Root().maxSize()) {
62e76326 1220 if (squid_curtime - last_warn_time > 10) {
c575fb6a 1221 debugs(20, DBG_CRITICAL, "WARNING: Disk space over limit: "
cc34568d
DK
1222 << Store::Root().currentSize() / 1024.0 << " KB > "
1223 << (Store::Root().maxSize() >> 10) << " KB");
62e76326 1224 last_warn_time = squid_curtime;
1225 }
6a566b9c 1226 }
62e76326 1227
88bfe092 1228 PROF_stop(storeMaintainSwapSpace);
090089c4 1229}
1230
090089c4 1231/* release an object from a cache */
6c78a099 1232void
5f33b71d 1233StoreEntry::release()
090089c4 1234{
88bfe092 1235 PROF_start(storeRelease);
1bfe9ade 1236 debugs(20, 3, "releasing " << *this << ' ' << getMD5Text());
090089c4 1237 /* If, for any reason we can't discard this object because of an
1238 * outstanding request, mark it for pending release */
62e76326 1239
3900307b 1240 if (locked()) {
d88e3c49 1241 expireNow();
bf8fe701 1242 debugs(20, 3, "storeRelease: Only setting RELEASE_REQUEST bit");
d88e3c49 1243 releaseRequest();
62e76326 1244 PROF_stop(storeRelease);
1245 return;
090089c4 1246 }
62e76326 1247
ce49546e
AR
1248 Store::Root().memoryUnlink(*this);
1249
bef81ea5 1250 if (StoreController::store_dirs_rebuilding && swap_filen > -1) {
d88e3c49 1251 setPrivateKey();
62e76326 1252
5f33b71d 1253 if (swap_filen > -1) {
acc5dc4c
AR
1254 // lock the entry until rebuilding is done
1255 lock("storeLateRelease");
5f33b71d 1256 setReleaseFlag();
3aa53107 1257 LateReleaseStack.push(this);
62e76326 1258 } else {
5f33b71d 1259 destroyStoreEntry(static_cast<hash_link *>(this));
22c25cbb 1260 // "this" is no longer valid
62e76326 1261 }
22c25cbb
AR
1262
1263 PROF_stop(storeRelease);
1264 return;
43d9cf56 1265 }
62e76326 1266
5f33b71d 1267 storeLog(STORE_LOG_RELEASE, this);
62e76326 1268
5f33b71d 1269 if (swap_filen > -1) {
f58bb2f4 1270 // log before unlink() below clears swap_filen
5f33b71d 1271 if (!EBIT_TEST(flags, KEY_PRIVATE))
1272 storeDirSwapLog(this, SWAP_LOG_DEL);
62e76326 1273
f58bb2f4 1274 unlink();
090089c4 1275 }
62e76326 1276
5f33b71d 1277 destroyStoreEntry(static_cast<hash_link *>(this));
88bfe092 1278 PROF_stop(storeRelease);
090089c4 1279}
1280
e42d5181 1281static void
1282storeLateRelease(void *unused)
1283{
1284 StoreEntry *e;
1285 int i;
1286 static int n = 0;
62e76326 1287
bef81ea5 1288 if (StoreController::store_dirs_rebuilding) {
62e76326 1289 eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
1290 return;
e42d5181 1291 }
62e76326 1292
3aa53107 1293 // TODO: this works but looks unelegant.
5db6bf73 1294 for (i = 0; i < 10; ++i) {
3aa53107
FC
1295 if (LateReleaseStack.empty()) {
1296 e = NULL;
1297 } else {
1298 e = LateReleaseStack.top();
1299 LateReleaseStack.pop();
1300 }
62e76326 1301
1302 if (e == NULL) {
1303 /* done! */
e0236918 1304 debugs(20, DBG_IMPORTANT, "storeLateRelease: released " << n << " objects");
62e76326 1305 return;
1306 }
1307
1bfe9ade 1308 e->unlock("storeLateRelease");
5db6bf73 1309 ++n;
e42d5181 1310 }
62e76326 1311
e42d5181 1312 eventAdd("storeLateRelease", storeLateRelease, NULL, 0.0, 1);
1313}
1314
090089c4 1315/* return 1 if a store entry is locked */
cd748f27 1316int
3900307b 1317StoreEntry::locked() const
090089c4 1318{
3900307b 1319 if (lock_count)
62e76326 1320 return 1;
1321
b8890359 1322 /*
1bfe9ade
AR
1323 * SPECIAL, PUBLIC entries should be "locked";
1324 * XXX: Their owner should lock them then instead of relying on this hack.
b8890359 1325 */
3900307b 1326 if (EBIT_TEST(flags, ENTRY_SPECIAL))
1327 if (!EBIT_TEST(flags, KEY_PRIVATE))
62e76326 1328 return 1;
1329
30a4f2a8 1330 return 0;
090089c4 1331}
1332
528b2c61 1333bool
1334StoreEntry::validLength() const
6602e70e 1335{
47f6e231 1336 int64_t diff;
d8b249ef 1337 const HttpReply *reply;
528b2c61 1338 assert(mem_obj != NULL);
1339 reply = getReply();
bf8fe701 1340 debugs(20, 3, "storeEntryValidLength: Checking '" << getMD5Text() << "'");
e4049756 1341 debugs(20, 5, "storeEntryValidLength: object_len = " <<
707fdc47 1342 objectLen());
bf8fe701 1343 debugs(20, 5, "storeEntryValidLength: hdr_sz = " << reply->hdr_sz);
1344 debugs(20, 5, "storeEntryValidLength: content_length = " << reply->content_length);
62e76326 1345
d8b249ef 1346 if (reply->content_length < 0) {
bf8fe701 1347 debugs(20, 5, "storeEntryValidLength: Unspecified content length: " << getMD5Text());
62e76326 1348 return 1;
ffe4a367 1349 }
62e76326 1350
07304bf9 1351 if (reply->hdr_sz == 0) {
bf8fe701 1352 debugs(20, 5, "storeEntryValidLength: Zero header size: " << getMD5Text());
62e76326 1353 return 1;
ffe4a367 1354 }
62e76326 1355
c2a7cefd 1356 if (mem_obj->method == Http::METHOD_HEAD) {
bf8fe701 1357 debugs(20, 5, "storeEntryValidLength: HEAD request: " << getMD5Text());
62e76326 1358 return 1;
ffe4a367 1359 }
62e76326 1360
9b769c67 1361 if (reply->sline.status() == Http::scNotModified)
62e76326 1362 return 1;
1363
9b769c67 1364 if (reply->sline.status() == Http::scNoContent)
62e76326 1365 return 1;
1366
707fdc47 1367 diff = reply->hdr_sz + reply->content_length - objectLen();
62e76326 1368
ebf4efff 1369 if (diff == 0)
62e76326 1370 return 1;
1371
bf8fe701 1372 debugs(20, 3, "storeEntryValidLength: " << (diff < 0 ? -diff : diff) << " bytes too " << (diff < 0 ? "big" : "small") <<"; '" << getMD5Text() << "'" );
62e76326 1373
ebf4efff 1374 return 0;
ffe4a367 1375}
6602e70e 1376
6b7d87bb
FC
1377static void
1378storeRegisterWithCacheManager(void)
1379{
8822ebee
AR
1380 Mgr::RegisterAction("storedir", "Store Directory Stats", Store::Stats, 0, 1);
1381 Mgr::RegisterAction("store_io", "Store IO Interface Stats", &Mgr::StoreIoAction::Create, 0, 1);
1382 Mgr::RegisterAction("store_check_cachable_stats", "storeCheckCachable() Stats",
d9fc6862 1383 storeCheckCachableStats, 0, 1);
6b7d87bb
FC
1384}
1385
b8d8561b 1386void
1387storeInit(void)
c943f331 1388{
25535cbe 1389 storeKeyInit();
6a566b9c 1390 mem_policy = createRemovalPolicy(Config.memPolicy);
8638fc66 1391 storeDigestInit();
e3ef2b09 1392 storeLogOpen();
e42d5181 1393 eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
c8f4eac4 1394 Store::Root().init();
b2c141d4 1395 storeRebuildStart();
d120ed12
FC
1396
1397 storeRegisterWithCacheManager();
62ee09ca 1398}
1399
b8d8561b 1400void
1401storeConfigure(void)
b1c0cc67 1402{
c8f4eac4 1403 store_swap_high = (long) (((float) Store::Root().maxSize() *
62e76326 1404 (float) Config.Swap.highWaterMark) / (float) 100);
c8f4eac4 1405 store_swap_low = (long) (((float) Store::Root().maxSize() *
62e76326 1406 (float) Config.Swap.lowWaterMark) / (float) 100);
505d4821 1407 store_pages_max = Config.memMaxSize / sizeof(mem_node);
090089c4 1408}
1409
9487bae9
AR
1410bool
1411StoreEntry::memoryCachable() const
56f29785 1412{
3900307b 1413 if (mem_obj == NULL)
62e76326 1414 return 0;
1415
3900307b 1416 if (mem_obj->data_hdr.size() == 0)
62e76326 1417 return 0;
1418
19fdd3f3 1419 if (mem_obj->inmem_lo != 0)
e1381638 1420 return 0;
19fdd3f3 1421
d227e181 1422 if (!Config.onoff.memory_cache_first && swap_status == SWAPOUT_DONE && refcount == 1)
e1381638 1423 return 0;
19fdd3f3
HN
1424
1425 return 1;
56f29785 1426}
1427
edce4d98 1428int
3900307b 1429StoreEntry::checkNegativeHit() const
edce4d98 1430{
3900307b 1431 if (!EBIT_TEST(flags, ENTRY_NEGCACHED))
62e76326 1432 return 0;
1433
3900307b 1434 if (expires <= squid_curtime)
62e76326 1435 return 0;
1436
3900307b 1437 if (store_status != STORE_OK)
62e76326 1438 return 0;
1439
edce4d98 1440 return 1;
1441}
1442
ac9cc053
AJ
1443/**
1444 * Set object for negative caching.
1445 * Preserves any expiry information given by the server.
1446 * In absence of proper expiry info it will set to expire immediately,
1447 * or with HTTP-violations enabled the configured negative-TTL is observed
1448 */
b8d8561b 1449void
d88e3c49 1450StoreEntry::negativeCache()
79b5cc5f 1451{
da03a7e0
AJ
1452 // XXX: should make the default for expires 0 instead of -1
1453 // so we can distinguish "Expires: -1" from nothing.
1454 if (expires <= 0)
626096be 1455#if USE_HTTP_VIOLATIONS
ac9cc053
AJ
1456 expires = squid_curtime + Config.negativeTtl;
1457#else
1458 expires = squid_curtime;
1459#endif
d88e3c49 1460 EBIT_SET(flags, ENTRY_NEGCACHED);
79b5cc5f 1461}
0a21bd84 1462
1463void
1464storeFreeMemory(void)
1465{
c8f4eac4 1466 Store::Root(NULL);
9bc73deb 1467#if USE_CACHE_DIGESTS
62e76326 1468
8638fc66 1469 if (store_digest)
62e76326 1470 cacheDigestDestroy(store_digest);
1471
c68e9c6b 1472#endif
62e76326 1473
8638fc66 1474 store_digest = NULL;
0a21bd84 1475}
a7e59001 1476
1477int
1478expiresMoreThan(time_t expires, time_t when)
1479{
c21ad0f5 1480 if (expires < 0) /* No Expires given */
62e76326 1481 return 1;
1482
48f44632 1483 return (expires > (squid_curtime + when));
a7e59001 1484}
fe54d06d 1485
1486int
3900307b 1487StoreEntry::validToSend() const
fe54d06d 1488{
3900307b 1489 if (EBIT_TEST(flags, RELEASE_REQUEST))
62e76326 1490 return 0;
1491
3900307b 1492 if (EBIT_TEST(flags, ENTRY_NEGCACHED))
1493 if (expires <= squid_curtime)
62e76326 1494 return 0;
1495
3900307b 1496 if (EBIT_TEST(flags, ENTRY_ABORTED))
62e76326 1497 return 0;
1498
22696a16
AR
1499 // now check that the entry has a cache backing or is collapsed
1500 if (swap_filen > -1) // backed by a disk cache
1501 return 1;
1502
1503 if (swappingOut()) // will be backed by a disk cache
1504 return 1;
1505
1506 if (!mem_obj) // not backed by a memory cache and not collapsed
1507 return 0;
1508
1509 if (mem_obj->memCache.index >= 0) // backed by a shared memory cache
1510 return 0;
1511
1512 // StoreEntry::storeClientType() assumes DISK_CLIENT here, but there is no
1513 // disk cache backing so we should not rely on the store cache at all. This
1514 // is wrong for range requests that could feed off nibbled memory (XXX).
1515 if (mem_obj->inmem_lo) // in local memory cache, but got nibbled at
1516 return 0;
1517
fe54d06d 1518 return 1;
1519}
62663274 1520
ca98227c 1521void
3900307b 1522StoreEntry::timestampsSet()
ca98227c 1523{
3900307b 1524 const HttpReply *reply = getReply();
2f58241d 1525 time_t served_date = reply->date;
a9925b40 1526 int age = reply->header.getInt(HDR_AGE);
31d36bfd 1527 /* Compute the timestamp, mimicking RFC2616 section 13.2.3. */
2f58241d 1528 /* make sure that 0 <= served_date <= squid_curtime */
62e76326 1529
2f58241d 1530 if (served_date < 0 || served_date > squid_curtime)
62e76326 1531 served_date = squid_curtime;
1532
525bf9dc
BD
1533 /* Bug 1791:
1534 * If the returned Date: is more than 24 hours older than
1535 * the squid_curtime, then one of us needs to use NTP to set our
1536 * clock. We'll pretend that our clock is right.
1537 */
1538 else if (served_date < (squid_curtime - 24 * 60 * 60) )
1539 served_date = squid_curtime;
62e76326 1540
efd900cb 1541 /*
212cbb48 1542 * Compensate with Age header if origin server clock is ahead
1543 * of us and there is a cache in between us and the origin
1544 * server. But DONT compensate if the age value is larger than
1545 * squid_curtime because it results in a negative served_date.
efd900cb 1546 */
1547 if (age > squid_curtime - served_date)
62e76326 1548 if (squid_curtime > age)
1549 served_date = squid_curtime - age;
1550
31d36bfd
AR
1551 // compensate for Squid-to-server and server-to-Squid delays
1552 if (mem_obj && mem_obj->request) {
1553 const time_t request_sent =
1554 mem_obj->request->hier.peer_http_request_sent.tv_sec;
1555 if (0 < request_sent && request_sent < squid_curtime)
1556 served_date -= (squid_curtime - request_sent);
1557 }
1558
0d465a25 1559 if (reply->expires > 0 && reply->date > -1)
26ac0430 1560 expires = served_date + (reply->expires - reply->date);
0d465a25 1561 else
26ac0430 1562 expires = reply->expires;
62e76326 1563
3900307b 1564 lastmod = reply->last_modified;
62e76326 1565
3900307b 1566 timestamp = served_date;
ca98227c 1567}
429fdbec 1568
bfcaf585 1569void
3900307b 1570StoreEntry::registerAbort(STABH * cb, void *data)
bfcaf585 1571{
3900307b 1572 assert(mem_obj);
1573 assert(mem_obj->abort.callback == NULL);
1574 mem_obj->abort.callback = cb;
8ea67c2b 1575 mem_obj->abort.data = cbdataReference(data);
bfcaf585 1576}
1577
1578void
3900307b 1579StoreEntry::unregisterAbort()
bfcaf585 1580{
3900307b 1581 assert(mem_obj);
8ea67c2b 1582 if (mem_obj->abort.callback) {
26ac0430
AJ
1583 mem_obj->abort.callback = NULL;
1584 cbdataReferenceDone(mem_obj->abort.data);
8ea67c2b 1585 }
bfcaf585 1586}
88738790 1587
f09f5b26 1588void
3900307b 1589StoreEntry::dump(int l) const
1590{
bf8fe701 1591 debugs(20, l, "StoreEntry->key: " << getMD5Text());
1592 debugs(20, l, "StoreEntry->next: " << next);
1593 debugs(20, l, "StoreEntry->mem_obj: " << mem_obj);
4a7a3d56 1594 debugs(20, l, "StoreEntry->timestamp: " << timestamp);
1595 debugs(20, l, "StoreEntry->lastref: " << lastref);
1596 debugs(20, l, "StoreEntry->expires: " << expires);
1597 debugs(20, l, "StoreEntry->lastmod: " << lastmod);
1598 debugs(20, l, "StoreEntry->swap_file_sz: " << swap_file_sz);
bf8fe701 1599 debugs(20, l, "StoreEntry->refcount: " << refcount);
1600 debugs(20, l, "StoreEntry->flags: " << storeEntryFlags(this));
4a7a3d56 1601 debugs(20, l, "StoreEntry->swap_dirn: " << swap_dirn);
1602 debugs(20, l, "StoreEntry->swap_filen: " << swap_filen);
1603 debugs(20, l, "StoreEntry->lock_count: " << lock_count);
1604 debugs(20, l, "StoreEntry->mem_status: " << mem_status);
1605 debugs(20, l, "StoreEntry->ping_status: " << ping_status);
1606 debugs(20, l, "StoreEntry->store_status: " << store_status);
1607 debugs(20, l, "StoreEntry->swap_status: " << swap_status);
d377699f 1608}
1609
1f38f50a 1610/*
1611 * NOTE, this function assumes only two mem states
1612 */
f09f5b26 1613void
3900307b 1614StoreEntry::setMemStatus(mem_status_t new_status)
8350fe9b 1615{
3900307b 1616 if (new_status == mem_status)
62e76326 1617 return;
1618
6ebe9a4c
AR
1619 // are we using a shared memory cache?
1620 if (Config.memShared && IamWorkerProcess()) {
9487bae9
AR
1621 // This method was designed to update replacement policy, not to
1622 // actually purge something from the memory cache (TODO: rename?).
1623 // Shared memory cache does not have a policy that needs updates.
1624 mem_status = new_status;
1625 return;
1626 }
1627
3900307b 1628 assert(mem_obj != NULL);
62e76326 1629
b93bcace 1630 if (new_status == IN_MEMORY) {
3900307b 1631 assert(mem_obj->inmem_lo == 0);
62e76326 1632
3900307b 1633 if (EBIT_TEST(flags, ENTRY_SPECIAL)) {
c877c0bc 1634 debugs(20, 4, "not inserting special " << *this << " into policy");
62e76326 1635 } else {
3900307b 1636 mem_policy->Add(mem_policy, this, &mem_obj->repl);
c877c0bc 1637 debugs(20, 4, "inserted " << *this << " key: " << getMD5Text());
62e76326 1638 }
1639
5db6bf73 1640 ++hot_obj_count; // TODO: maintain for the shared hot cache as well
b93bcace 1641 } else {
3900307b 1642 if (EBIT_TEST(flags, ENTRY_SPECIAL)) {
c877c0bc 1643 debugs(20, 4, "not removing special " << *this << " from policy");
62e76326 1644 } else {
3900307b 1645 mem_policy->Remove(mem_policy, this, &mem_obj->repl);
c877c0bc 1646 debugs(20, 4, "removed " << *this);
62e76326 1647 }
1648
5e263176 1649 --hot_obj_count;
b93bcace 1650 }
62e76326 1651
3900307b 1652 mem_status = new_status;
8350fe9b 1653}
6e86c3e8 1654
9fb13bb6 1655const char *
3900307b 1656StoreEntry::url() const
9fb13bb6 1657{
3900307b 1658 if (this == NULL)
62e76326 1659 return "[null_entry]";
3900307b 1660 else if (mem_obj == NULL)
62e76326 1661 return "[null_mem_obj]";
9fb13bb6 1662 else
c877c0bc 1663 return mem_obj->storeId();
9fb13bb6 1664}
24ffafb4 1665
c877c0bc
AR
1666MemObject *
1667StoreEntry::makeMemObject()
24ffafb4 1668{
c877c0bc
AR
1669 if (!mem_obj)
1670 mem_obj = new MemObject();
1671 return mem_obj;
1672}
9487bae9 1673
c877c0bc
AR
1674void
1675StoreEntry::createMemObject(const char *aUrl, const char *aLogUrl, const HttpRequestMethod &aMethod)
1676{
1677 makeMemObject();
1678 mem_obj->setUris(aUrl, aLogUrl, aMethod);
c21ad0f5 1679}
1680
1681/* this just sets DELAY_SENDING */
1682void
1683StoreEntry::buffer()
1684{
1685 EBIT_SET(flags, DELAY_SENDING);
1686}
1687
438fc1e3 1688/* this just clears DELAY_SENDING and Invokes the handlers */
1689void
c21ad0f5 1690StoreEntry::flush()
438fc1e3 1691{
c21ad0f5 1692 if (EBIT_TEST(flags, DELAY_SENDING)) {
1693 EBIT_CLR(flags, DELAY_SENDING);
d88e3c49 1694 invokeHandlers();
b66315e4 1695 }
25535cbe 1696}
07304bf9 1697
47f6e231 1698int64_t
707fdc47 1699StoreEntry::objectLen() const
07304bf9 1700{
707fdc47 1701 assert(mem_obj != NULL);
1702 return mem_obj->object_sz;
07304bf9 1703}
1704
47f6e231 1705int64_t
b37bde1e 1706StoreEntry::contentLen() const
07304bf9 1707{
b37bde1e 1708 assert(mem_obj != NULL);
1709 assert(getReply() != NULL);
1710 return objectLen() - getReply()->hdr_sz;
07304bf9 1711}
f3986a15 1712
528b2c61 1713HttpReply const *
1714StoreEntry::getReply () const
f3986a15 1715{
528b2c61 1716 if (NULL == mem_obj)
62e76326 1717 return NULL;
1718
528b2c61 1719 return mem_obj->getReply();
f3986a15 1720}
db1cd23c 1721
1722void
3900307b 1723StoreEntry::reset()
db1cd23c 1724{
3900307b 1725 assert (mem_obj);
bf8fe701 1726 debugs(20, 3, "StoreEntry::reset: " << url());
3900307b 1727 mem_obj->reset();
1728 HttpReply *rep = (HttpReply *) getReply(); // bypass const
06a5ae20 1729 rep->reset();
3900307b 1730 expires = lastmod = timestamp = -1;
db1cd23c 1731}
2b906e48 1732
cd748f27 1733/*
1734 * storeFsInit
1735 *
1736 * This routine calls the SETUP routine for each fs type.
1737 * I don't know where the best place for this is, and I'm not going to shuffle
1738 * around large chunks of code right now (that can be done once its working.)
1739 */
1740void
1741storeFsInit(void)
1742{
22d38e05 1743 storeReplSetup();
cd748f27 1744}
1745
22d38e05 1746/*
1747 * called to add another store removal policy module
1748 */
1749void
a2c963ae 1750storeReplAdd(const char *type, REMOVALPOLICYCREATE * create)
22d38e05 1751{
1752 int i;
62e76326 1753
d64c1498 1754 /* find the number of currently known repl types */
5db6bf73 1755 for (i = 0; storerepl_list && storerepl_list[i].typestr; ++i) {
d64c1498 1756 if (strcmp(storerepl_list[i].typestr, type) == 0) {
e0236918 1757 debugs(20, DBG_IMPORTANT, "WARNING: Trying to load store replacement policy " << type << " twice.");
d64c1498
AJ
1758 return;
1759 }
22d38e05 1760 }
62e76326 1761
22d38e05 1762 /* add the new type */
e6ccf245 1763 storerepl_list = static_cast<storerepl_entry_t *>(xrealloc(storerepl_list, (i + 2) * sizeof(storerepl_entry_t)));
62e76326 1764
22d38e05 1765 memset(&storerepl_list[i + 1], 0, sizeof(storerepl_entry_t));
62e76326 1766
22d38e05 1767 storerepl_list[i].typestr = type;
62e76326 1768
22d38e05 1769 storerepl_list[i].create = create;
1770}
1771
1772/*
1773 * Create a removal policy instance
1774 */
1775RemovalPolicy *
1776createRemovalPolicy(RemovalPolicySettings * settings)
1777{
1778 storerepl_entry_t *r;
62e76326 1779
5db6bf73 1780 for (r = storerepl_list; r && r->typestr; ++r) {
62e76326 1781 if (strcmp(r->typestr, settings->type) == 0)
1782 return r->create(settings->args);
22d38e05 1783 }
62e76326 1784
e0236918
FC
1785 debugs(20, DBG_IMPORTANT, "ERROR: Unknown policy " << settings->type);
1786 debugs(20, DBG_IMPORTANT, "ERROR: Be sure to have set cache_replacement_policy");
1787 debugs(20, DBG_IMPORTANT, "ERROR: and memory_replacement_policy in squid.conf!");
0c5ccf11 1788 fatalf("ERROR: Unknown policy %s\n", settings->type);
c21ad0f5 1789 return NULL; /* NOTREACHED */
22d38e05 1790}
1791
cd748f27 1792#if 0
fc8b9fc0 1793void
1794storeSwapFileNumberSet(StoreEntry * e, sfileno filn)
1795{
1796 if (e->swap_file_number == filn)
62e76326 1797 return;
1798
fc8b9fc0 1799 if (filn < 0) {
62e76326 1800 assert(-1 == filn);
1801 storeDirMapBitReset(e->swap_file_number);
1802 storeDirLRUDelete(e);
1803 e->swap_file_number = -1;
fc8b9fc0 1804 } else {
62e76326 1805 assert(-1 == e->swap_file_number);
1806 storeDirMapBitSet(e->swap_file_number = filn);
1807 storeDirLRUAdd(e);
fc8b9fc0 1808 }
1809}
62e76326 1810
cd748f27 1811#endif
e6ccf245 1812
db237875 1813/*
1814 * Replace a store entry with
528b2c61 1815 * a new reply. This eats the reply.
1816 */
4a56ee8d 1817void
3756e5c0 1818StoreEntry::replaceHttpReply(HttpReply *rep, bool andStartWriting)
4a56ee8d 1819{
bf8fe701 1820 debugs(20, 3, "StoreEntry::replaceHttpReply: " << url());
62e76326 1821
4a56ee8d 1822 if (!mem_obj) {
fa84c01d 1823 debugs(20, DBG_CRITICAL, "Attempt to replace object with no in-memory representation");
62e76326 1824 return;
528b2c61 1825 }
62e76326 1826
4a56ee8d 1827 mem_obj->replaceHttpReply(rep);
1828
3756e5c0
AR
1829 if (andStartWriting)
1830 startWriting();
1831}
1832
3756e5c0
AR
1833void
1834StoreEntry::startWriting()
1835{
1836 Packer p;
1837
528b2c61 1838 /* TODO: when we store headers serparately remove the header portion */
1839 /* TODO: mark the length of the headers ? */
1840 /* We ONLY want the headers */
4a56ee8d 1841 packerToStoreInit(&p, this);
62e76326 1842
4a56ee8d 1843 assert (isEmpty());
3756e5c0 1844 assert(mem_obj);
9199139f 1845
3756e5c0
AR
1846 const HttpReply *rep = getReply();
1847 assert(rep);
62e76326 1848
3756e5c0
AR
1849 rep->packHeadersInto(&p);
1850 mem_obj->markEndOfReplyHeaders();
4475555f 1851 EBIT_CLR(flags, ENTRY_FWD_HDR_WAIT);
62e76326 1852
0521f8be 1853 rep->body.packInto(&p);
62e76326 1854
528b2c61 1855 packerClean(&p);
1856}
62e76326 1857
528b2c61 1858char const *
1859StoreEntry::getSerialisedMetaData()
1860{
1861 StoreMeta *tlv_list = storeSwapMetaBuild(this);
1862 int swap_hdr_sz;
1863 char *result = storeSwapMetaPack(tlv_list, &swap_hdr_sz);
1864 storeSwapTLVFree(tlv_list);
aa1a691e
AR
1865 assert (swap_hdr_sz >= 0);
1866 mem_obj->swap_hdr_sz = (size_t) swap_hdr_sz;
528b2c61 1867 return result;
1868}
1869
528b2c61 1870void
5b55f1f1 1871StoreEntry::trimMemory(const bool preserveSwappable)
528b2c61 1872{
7fef2365 1873 /*
1874 * DPW 2007-05-09
1875 * Bug #1943. We must not let go any data for IN_MEMORY
1876 * objects. We have to wait until the mem_status changes.
1877 */
1878 if (mem_status == IN_MEMORY)
26ac0430 1879 return;
7fef2365 1880
c5426f8f
AR
1881 if (EBIT_TEST(flags, ENTRY_SPECIAL))
1882 return; // cannot trim because we do not load them again
1883
99921d9d
AR
1884 if (preserveSwappable)
1885 mem_obj->trimSwappable();
1886 else
1887 mem_obj->trimUnSwappable();
1888
1889 debugs(88, 7, *this << " inmem_lo=" << mem_obj->inmem_lo);
528b2c61 1890}
62e76326 1891
0655fa4d 1892bool
190154cf 1893StoreEntry::modifiedSince(HttpRequest * request) const
0655fa4d 1894{
1895 int object_length;
1896 time_t mod_time = lastmod;
1897
1898 if (mod_time < 0)
1899 mod_time = timestamp;
1900
bf8fe701 1901 debugs(88, 3, "modifiedSince: '" << url() << "'");
0655fa4d 1902
4a7a3d56 1903 debugs(88, 3, "modifiedSince: mod_time = " << mod_time);
0655fa4d 1904
1905 if (mod_time < 0)
1906 return true;
1907
1908 /* Find size of the object */
1909 object_length = getReply()->content_length;
1910
1911 if (object_length < 0)
b37bde1e 1912 object_length = contentLen();
0655fa4d 1913
1914 if (mod_time > request->ims) {
bf8fe701 1915 debugs(88, 3, "--> YES: entry newer than client");
0655fa4d 1916 return true;
1917 } else if (mod_time < request->ims) {
bf8fe701 1918 debugs(88, 3, "--> NO: entry older than client");
0655fa4d 1919 return false;
1920 } else if (request->imslen < 0) {
bf8fe701 1921 debugs(88, 3, "--> NO: same LMT, no client length");
0655fa4d 1922 return false;
1923 } else if (request->imslen == object_length) {
bf8fe701 1924 debugs(88, 3, "--> NO: same LMT, same length");
0655fa4d 1925 return false;
1926 } else {
bf8fe701 1927 debugs(88, 3, "--> YES: same LMT, different length");
0655fa4d 1928 return true;
1929 }
1930}
1931
46017fdd
CT
1932bool
1933StoreEntry::hasEtag(ETag &etag) const
1934{
1935 if (const HttpReply *reply = getReply()) {
1936 etag = reply->header.getETag(HDR_ETAG);
1937 if (etag.str)
1938 return true;
1939 }
1940 return false;
1941}
1942
79c8035e
AR
1943bool
1944StoreEntry::hasIfMatchEtag(const HttpRequest &request) const
1945{
1946 const String reqETags = request.header.getList(HDR_IF_MATCH);
1947 return hasOneOfEtags(reqETags, false);
1948}
1949
1950bool
1951StoreEntry::hasIfNoneMatchEtag(const HttpRequest &request) const
1952{
1953 const String reqETags = request.header.getList(HDR_IF_NONE_MATCH);
1954 // weak comparison is allowed only for HEAD or full-body GET requests
450fe1cb 1955 const bool allowWeakMatch = !request.flags.isRanged &&
c2a7cefd 1956 (request.method == Http::METHOD_GET || request.method == Http::METHOD_HEAD);
79c8035e
AR
1957 return hasOneOfEtags(reqETags, allowWeakMatch);
1958}
1959
1960/// whether at least one of the request ETags matches entity ETag
1961bool
1962StoreEntry::hasOneOfEtags(const String &reqETags, const bool allowWeakMatch) const
1963{
1964 const ETag repETag = getReply()->header.getETag(HDR_ETAG);
1965 if (!repETag.str)
1966 return strListIsMember(&reqETags, "*", ',');
1967
1968 bool matched = false;
1969 const char *pos = NULL;
1970 const char *item;
1971 int ilen;
1972 while (!matched && strListGetItem(&reqETags, ',', &item, &ilen, &pos)) {
1973 if (!strncmp(item, "*", ilen))
1974 matched = true;
1975 else {
1976 String str;
1977 str.append(item, ilen);
1978 ETag reqETag;
1979 if (etagParseInit(&reqETag, str.termedBuf())) {
1980 matched = allowWeakMatch ? etagIsWeakEqual(repETag, reqETag) :
b59e6847 1981 etagIsStrongEqual(repETag, reqETag);
79c8035e
AR
1982 }
1983 }
1984 }
1985 return matched;
1986}
1987
7d3c4ca1 1988SwapDir::Pointer
c8f4eac4 1989StoreEntry::store() const
1990{
1991 assert(0 <= swap_dirn && swap_dirn < Config.cacheSwap.n_configured);
1992 return INDEXSD(swap_dirn);
1993}
1994
1995void
1996StoreEntry::unlink()
1997{
f58bb2f4
AR
1998 store()->unlink(*this); // implies disconnect()
1999 swap_filen = -1;
2000 swap_dirn = -1;
2001 swap_status = SWAPOUT_NONE;
c8f4eac4 2002}
0655fa4d 2003
aa18a4ca 2004/*
2005 * return true if the entry is in a state where
2006 * it can accept more data (ie with write() method)
2007 */
2008bool
2009StoreEntry::isAccepting() const
2010{
2011 if (STORE_PENDING != store_status)
2012 return false;
2013
2014 if (EBIT_TEST(flags, ENTRY_ABORTED))
2015 return false;
2016
2017 return true;
2018}
2019
2c4cd1ad
AR
2020std::ostream &operator <<(std::ostream &os, const StoreEntry &e)
2021{
c0280457
AR
2022 os << "e:";
2023
99921d9d
AR
2024 if (e.mem_obj) {
2025 if (e.mem_obj->xitTable.index > -1)
2026 os << 't' << e.mem_obj->xitTable.index;
2027 if (e.mem_obj->memCache.index > -1)
2028 os << 'm' << e.mem_obj->memCache.index;
2029 }
c0280457 2030 if (e.swap_filen > -1 || e.swap_dirn > -1)
99921d9d 2031 os << 'd' << e.swap_filen << '@' << e.swap_dirn;
4475555f
AR
2032
2033 os << '=';
c0280457
AR
2034
2035 // print only non-default status values, using unique letters
2036 if (e.mem_status != NOT_IN_MEMORY ||
9d4e9cfb
AR
2037 e.store_status != STORE_PENDING ||
2038 e.swap_status != SWAPOUT_NONE ||
2039 e.ping_status != PING_NONE) {
c0280457
AR
2040 if (e.mem_status != NOT_IN_MEMORY) os << 'm';
2041 if (e.store_status != STORE_PENDING) os << 's';
2042 if (e.swap_status != SWAPOUT_NONE) os << 'w' << e.swap_status;
2043 if (e.ping_status != PING_NONE) os << 'p' << e.ping_status;
c0280457
AR
2044 }
2045
2046 // print only set flags, using unique letters
2047 if (e.flags) {
2048 if (EBIT_TEST(e.flags, ENTRY_SPECIAL)) os << 'S';
2049 if (EBIT_TEST(e.flags, ENTRY_REVALIDATE)) os << 'R';
99921d9d 2050 if (EBIT_TEST(e.flags, DELAY_SENDING)) os << 'P';
c0280457
AR
2051 if (EBIT_TEST(e.flags, RELEASE_REQUEST)) os << 'X';
2052 if (EBIT_TEST(e.flags, REFRESH_REQUEST)) os << 'F';
c0280457
AR
2053 if (EBIT_TEST(e.flags, ENTRY_DISPATCHED)) os << 'D';
2054 if (EBIT_TEST(e.flags, KEY_PRIVATE)) os << 'I';
2055 if (EBIT_TEST(e.flags, ENTRY_FWD_HDR_WAIT)) os << 'W';
2056 if (EBIT_TEST(e.flags, ENTRY_NEGCACHED)) os << 'N';
2057 if (EBIT_TEST(e.flags, ENTRY_VALIDATED)) os << 'V';
2058 if (EBIT_TEST(e.flags, ENTRY_BAD_LENGTH)) os << 'L';
2059 if (EBIT_TEST(e.flags, ENTRY_ABORTED)) os << 'A';
c0280457
AR
2060 }
2061
4475555f
AR
2062 if (e.mem_obj && e.mem_obj->smpCollapsed)
2063 os << 'O';
2064
1bfe9ade 2065 return os << '/' << &e << '*' << e.locks();
2c4cd1ad
AR
2066}
2067
e6ccf245 2068/* NullStoreEntry */
2069
2070NullStoreEntry NullStoreEntry::_instance;
2071
2072NullStoreEntry *
2073NullStoreEntry::getInstance()
2074{
2075 return &_instance;
2076}
332dafa2 2077
2078char const *
2079NullStoreEntry::getMD5Text() const
2080{
2081 return "N/A";
2082}
528b2c61 2083
43ae1d95 2084void
2085NullStoreEntry::operator delete(void*)
2086{
2087 fatal ("Attempt to delete NullStoreEntry\n");
2088}
2089
528b2c61 2090char const *
2091NullStoreEntry::getSerialisedMetaData()
2092{
2093 return NULL;
2094}