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