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