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