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