]> git.ipfire.org Git - thirdparty/squid.git/blame - src/Store.h
Source Format Enforcement (#532)
[thirdparty/squid.git] / src / Store.h
CommitLineData
e6ccf245 1/*
77b1029d 2 * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
e6ccf245 3 *
bbc27441
AJ
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.
e6ccf245 7 */
bbc27441 8
e6ccf245 9#ifndef SQUID_STORE_H
10#define SQUID_STORE_H
11
0f33a01d 12#include "base/Packable.h"
21dfc374 13#include "base/Range.h"
8bf217bd 14#include "base/RefCount.h"
3e4bebf8 15#include "comm/forward.h"
582c2af2 16#include "CommRead.h"
c6983ec7 17#include "hash.h"
f35c0145 18#include "http/forward.h"
c24f7fb6 19#include "http/RequestMethod.h"
43ca19e0 20#include "HttpReply.h"
04ebce55 21#include "MemObject.h"
aa839030 22#include "RemovalPolicy.h"
2745fea5
AR
23#include "store/Controller.h"
24#include "store/forward.h"
e1ba42a4 25#include "store_key_md5.h"
582c2af2 26#include "StoreIOBuffer.h"
93bc1434 27#include "StoreStats.h"
528b2c61 28
f41735ea 29#if USE_SQUID_ESI
f99c2cfe 30#include "esi/Element.h"
43ae1d95 31#endif
32
27e059d4 33#include <ostream>
27e059d4 34
65517dc8 35class AsyncCall;
582c2af2 36class HttpRequest;
71b673d4 37class RequestFlags;
c8f4eac4 38
8822ebee
AR
39extern StoreIoStats store_io_stats;
40
0f33a01d 41class StoreEntry : public hash_link, public Packable
62e76326 42{
43
332dafa2 44public:
a46d2c0e 45 static DeferredRead::DeferrableRead DeferReader;
46 bool checkDeferRead(int fd) const;
62e76326 47
69565793 48 const char *getMD5Text() const;
c8f4eac4 49 StoreEntry();
6d8d05b5 50 virtual ~StoreEntry();
43ae1d95 51
66d51f4f
AR
52 MemObject &mem() { assert(mem_obj); return *mem_obj; }
53 const MemObject &mem() const { assert(mem_obj); return *mem_obj; }
54
55 /// \retval * the address of freshest reply (if mem_obj exists)
56 /// \retval nullptr when mem_obj does not exist
57 /// \see MemObject::freshestReply()
58 const HttpReply *hasFreshestReply() const { return mem_obj ? &mem_obj->freshestReply() : nullptr; }
59
69565793 60 void write(StoreIOBuffer);
04ebce55 61
69565793 62 /** Check if the Store entry is empty
04ebce55
FC
63 * \retval true Store contains 0 bytes of data.
64 * \retval false Store contains 1 or more bytes of data.
65 * \retval false Store contains negative content !!!!!!
66 */
66d51f4f 67 bool isEmpty() const { return mem().endOffset() == 0; }
69565793
EB
68 bool isAccepting() const;
69 size_t bytesWanted(Range<size_t> const aRange, bool ignoreDelayPool = false) const;
7224ca5a
AR
70 /// flags [truncated or too big] entry with ENTRY_BAD_LENGTH and releases it
71 void lengthWentBad(const char *reason);
69565793
EB
72 void complete();
73 store_client_t storeClientType() const;
66d51f4f
AR
74 /// \returns a malloc()ed buffer containing a length-long packed swap header
75 const char *getSerialisedMetaData(size_t &length) const;
eacfca83
AR
76 /// Store a prepared error response. MemObject locks the reply object.
77 void storeErrorResponse(HttpReply *reply);
66d51f4f 78 void replaceHttpReply(const HttpReplyPointer &, const bool andStartWriting = true);
3756e5c0 79 void startWriting(); ///< pack and write reply headers and, maybe, body
5b55f1f1 80 /// whether we may start writing to disk (now or in the future)
69565793
EB
81 bool mayStartSwapOut();
82 void trimMemory(const bool preserveSwappable);
0cdcf3d7 83
2da4bfe6 84 // called when a decision to cache in memory has been made
0cdcf3d7
AR
85 void memOutDecision(const bool willCacheInRam);
86 // called when a decision to cache on disk has been made
87 void swapOutDecision(const MemObject::SwapOut::Decision &decision);
88
bfb55b6f 89 void abort();
4310f8b0 90 bool makePublic(const KeyScope keyScope = ksDefault);
39fe14b2
EB
91 void makePrivate(const bool shareable);
92 /// A low-level method just resetting "private key" flags.
93 /// To avoid key inconsistency please use forcePublicKey()
94 /// or similar instead.
95 void clearPrivate();
4310f8b0 96 bool setPublicKey(const KeyScope keyScope = ksDefault);
1a210de4
EB
97 /// Resets existing public key to a public key with default scope,
98 /// releasing the old default-scope entry (if any).
99 /// Does nothing if the existing public key already has default scope.
100 void clearPublicKeyScope();
4310f8b0
EB
101
102 /// \returns public key (if the entry has it) or nil (otherwise)
103 const cache_key *publicKey() const {
104 return (!EBIT_TEST(flags, KEY_PRIVATE)) ?
105 reinterpret_cast<const cache_key*>(key): // may be nil
106 nullptr;
107 }
108
109 /// Either fills this entry with private key or changes the existing key
110 /// from public to private.
111 /// \param permanent whether this entry should be private forever.
112 void setPrivateKey(const bool shareable, const bool permanent);
113
d88e3c49 114 void expireNow();
4310f8b0
EB
115 /// Makes the StoreEntry private and marks the corresponding entry
116 /// for eventual removal from the Store.
39fe14b2 117 void releaseRequest(const bool shareable = false);
d88e3c49 118 void negativeCache();
4310f8b0 119 bool cacheNegatively(); /** \todo argh, why both? */
d88e3c49 120 void invokeHandlers();
9487bae9 121 void cacheInMemory(); ///< start or continue storing in memory cache
c07cbbf4 122 void swapOut();
5b55f1f1
CT
123 /// whether we are in the process of writing this entry to disk
124 bool swappingOut() const { return swap_status == SWAPOUT_WRITING; }
4310f8b0
EB
125 /// whether the entire entry is now on disk (possibly marked for deletion)
126 bool swappedOut() const { return swap_status == SWAPOUT_DONE; }
02ba667b
EB
127 /// whether we failed to write this entry to disk
128 bool swapoutFailed() const { return swap_status == SWAPOUT_FAILED; }
aa1a691e 129 void swapOutFileClose(int how);
3900307b 130 const char *url() const;
7015a149
AR
131 /// Satisfies cachability requirements shared among disk and RAM caches.
132 /// Encapsulates common checks of mayStartSwapOut() and memoryCachable().
133 /// TODO: Rename and make private so only those two methods can call this.
134 bool checkCachable();
3900307b 135 int checkNegativeHit() const;
508590d9 136 int locked() const { return lock_count; }
3900307b 137 int validToSend() const;
97754f5a 138 bool memoryCachable(); ///< checkCachable() and can be cached in memory
4475555f 139
76d61119
EB
140 /// initialize mem_obj; assert if mem_obj already exists
141 /// avoid this method in favor of createMemObject(trio)!
142 void createMemObject();
c877c0bc 143
76d61119 144 /// initialize mem_obj with URIs/method; assert if mem_obj already exists
c877c0bc 145 void createMemObject(const char *storeId, const char *logUri, const HttpRequestMethod &aMethod);
4475555f 146
76d61119
EB
147 /// initialize mem_obj (if needed) and set URIs/method (if missing)
148 void ensureMemObject(const char *storeId, const char *logUri, const HttpRequestMethod &aMethod);
149
3900307b 150 void dump(int debug_lvl) const;
151 void hashDelete();
152 void hashInsert(const cache_key *);
153 void registerAbort(STABH * cb, void *);
154 void reset();
155 void setMemStatus(mem_status_t);
1a210de4 156 bool timestampsSet();
3900307b 157 void unregisterAbort();
158 void destroyMemObject();
159 int checkTooSmall();
528b2c61 160
3e4bebf8 161 void delayAwareRead(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer callback);
43ae1d95 162
a46d2c0e 163 void setNoDelay (bool const);
438b41ba
EB
164 void lastModified(const time_t when) { lastModified_ = when; }
165 /// \returns entry's 'effective' modification time
166 time_t lastModified() const {
167 // may still return -1 if timestamp is not set
168 return lastModified_ < 0 ? timestamp : lastModified_;
169 }
170 /// \returns a formatted string with entry's timestamps
171 const char *describeTimestamps() const;
172 // TODO: consider removing currently unsupported imslen parameter
173 bool modifiedSince(const time_t ims, const int imslen = -1) const;
79c8035e
AR
174 /// has ETag matching at least one of the If-Match etags
175 bool hasIfMatchEtag(const HttpRequest &request) const;
176 /// has ETag matching at least one of the If-None-Match etags
177 bool hasIfNoneMatchEtag(const HttpRequest &request) const;
46017fdd
CT
178 /// whether this entry has an ETag; if yes, puts ETag value into parameter
179 bool hasEtag(ETag &etag) const;
63be0a78 180
66d51f4f
AR
181 /// Updates easily-accessible non-Store-specific parts of the entry.
182 /// Use Controller::updateOnNotModified() instead of this helper.
183 /// \returns whether anything was actually updated
184 bool updateOnNotModified(const StoreEntry &e304);
185
2745fea5
AR
186 /// the disk this entry is [being] cached on; asserts for entries w/o a disk
187 Store::Disk &disk() const;
4310f8b0
EB
188 /// whether one of this StoreEntry owners has locked the corresponding
189 /// disk entry (at the specified disk entry coordinates, if any)
190 bool hasDisk(const sdirno dirn = -1, const sfileno filen = -1) const;
191 /// Makes hasDisk(dirn, filn) true. The caller should have locked
192 /// the corresponding disk store entry for reading or writing.
193 void attachToDisk(const sdirno, const sfileno, const swap_status_t);
194 /// Makes hasDisk() false. The caller should have unlocked
195 /// the corresponding disk store entry.
196 void detachFromDisk();
197
198 /// whether there is a corresponding locked transients table entry
199 bool hasTransients() const { return mem_obj && mem_obj->xitTable.index >= 0; }
200 /// whether there is a corresponding locked shared memory table entry
201 bool hasMemStore() const { return mem_obj && mem_obj->memCache.index >= 0; }
a46d2c0e 202
d2a6dcba
EB
203 /// whether this entry can feed collapsed requests and only them
204 bool hittingRequiresCollapsing() const { return EBIT_TEST(flags, ENTRY_REQUIRES_COLLAPSING); }
205
206 /// allow or forbid collapsed requests feeding
207 void setCollapsingRequirement(const bool required);
819be284 208
e6ccf245 209 MemObject *mem_obj;
210 RemovalPolicyNode repl;
211 /* START OF ON-DISK STORE_META_STD TLV field */
212 time_t timestamp;
213 time_t lastref;
214 time_t expires;
438b41ba
EB
215private:
216 time_t lastModified_; ///< received Last-Modified value or -1; use lastModified()
217public:
47f6e231 218 uint64_t swap_file_sz;
f45dd259
AJ
219 uint16_t refcount;
220 uint16_t flags;
e6ccf245 221 /* END OF ON-DISK STORE_META_STD */
62e76326 222
051dedf9
AR
223 /// unique ID inside a cache_dir for swapped out entries; -1 for others
224 sfileno swap_filen:25; // keep in sync with SwapFilenMax
d1398b75
HN
225
226 sdirno swap_dirn:7;
62e76326 227
d1398b75 228 mem_status_t mem_status:3;
62e76326 229
d1398b75 230 ping_status_t ping_status:3;
62e76326 231
d1398b75 232 store_status_t store_status:3;
62e76326 233
d1398b75 234 swap_status_t swap_status:3;
62e76326 235
e6ccf245 236public:
237 static size_t inUseCount();
60745f24 238 static void getPublicByRequestMethod(StoreClient * aClient, HttpRequest * request, const HttpRequestMethod& method);
190154cf 239 static void getPublicByRequest(StoreClient * aClient, HttpRequest * request);
60745f24 240 static void getPublic(StoreClient * aClient, const char *uri, const HttpRequestMethod& method);
528b2c61 241
0b934349
AJ
242 void *operator new(size_t byteCount);
243 void operator delete(void *address);
f41735ea 244#if USE_SQUID_ESI
43ae1d95 245
246 ESIElement::Pointer cachedESITree;
247#endif
66d51f4f
AR
248 int64_t objectLen() const { return mem().object_sz; }
249 int64_t contentLen() const { return objectLen() - mem().baseReply().hdr_sz; }
c21ad0f5 250
18994992 251 /// claim shared ownership of this entry (for use in a given context)
acc5dc4c 252 /// matching lock() and unlock() contexts eases leak triage but is optional
18994992 253 void lock(const char *context);
1bfe9ade 254
18994992
AR
255 /// disclaim shared ownership; may remove entry from store and delete it
256 /// returns remaning lock level (zero for unlocked and possibly gone entry)
acc5dc4c 257 int unlock(const char *context);
1bfe9ade
AR
258
259 /// returns a local concurrent use counter, for debugging
260 int locks() const { return static_cast<int>(lock_count); }
261
18994992
AR
262 /// update last reference timestamp and related Store metadata
263 void touch();
264
4310f8b0
EB
265 /// One of the three methods to get rid of an unlocked StoreEntry object.
266 /// Removes all unlocked (and marks for eventual removal all locked) Store
267 /// entries, including attached and unattached entries that have our key.
268 /// Also destroys us if we are unlocked or makes us private otherwise.
69565793 269 void release(const bool shareable = false);
39fe14b2 270
4310f8b0
EB
271 /// One of the three methods to get rid of an unlocked StoreEntry object.
272 /// May destroy this object if it is unlocked; does nothing otherwise.
273 /// Unlike release(), may not trigger eviction of underlying store entries,
274 /// but, unlike destroyStoreEntry(), does honor an earlier release request.
275 void abandon(const char *context) { if (!locked()) doAbandon(context); }
276
39fe14b2
EB
277 /// May the caller commit to treating this [previously locked]
278 /// entry as a cache hit?
279 bool mayStartHitting() const {
280 return !EBIT_TEST(flags, KEY_PRIVATE) || shareableWhenPrivate;
281 }
62e76326 282
0ad2b63b
CT
283#if USE_ADAPTATION
284 /// call back producer when more buffer space is available
285 void deferProducer(const AsyncCall::Pointer &producer);
286 /// calls back producer registered with deferProducer
287 void kickProducer();
288#endif
289
0f33a01d
AJ
290 /* Packable API */
291 virtual void append(char const *, int);
292 virtual void vappendf(const char *, va_list);
7e10ac87
AJ
293 virtual void buffer();
294 virtual void flush();
0f33a01d 295
0cdcf3d7 296protected:
4310f8b0
EB
297 typedef Store::EntryGuard EntryGuard;
298
0cdcf3d7 299 void transientsAbandonmentCheck();
4310f8b0
EB
300 /// does nothing except throwing if disk-associated data members are inconsistent
301 void checkDisk() const;
0cdcf3d7 302
e6ccf245 303private:
4310f8b0 304 void doAbandon(const char *context);
2be042f6 305 bool checkTooBig() const;
1a210de4 306 void forcePublicKey(const cache_key *newkey);
4310f8b0 307 StoreEntry *adjustVary();
1a210de4 308 const cache_key *calcPublicKey(const KeyScope keyScope);
2be042f6 309
04eb0689 310 static MemAllocator *pool;
528b2c61 311
f53969cc 312 unsigned short lock_count; /* Assume < 65536! */
1bfe9ade 313
39fe14b2
EB
314 /// Nobody can find/lock KEY_PRIVATE entries, but some transactions
315 /// (e.g., collapsed requests) find/lock a public entry before it becomes
316 /// private. May such transactions start using the now-private entry
317 /// they previously locked? This member should not affect transactions
318 /// that already started reading from the entry.
319 bool shareableWhenPrivate;
320
0ad2b63b
CT
321#if USE_ADAPTATION
322 /// producer callback registered with deferProducer
323 AsyncCall::Pointer deferredProducer;
324#endif
325
528b2c61 326 bool validLength() const;
79c8035e 327 bool hasOneOfEtags(const String &reqETags, const bool allowWeakMatch) const;
39fe14b2
EB
328
329 friend std::ostream &operator <<(std::ostream &os, const StoreEntry &e);
e6ccf245 330};
331
2c4cd1ad
AR
332std::ostream &operator <<(std::ostream &os, const StoreEntry &e);
333
63be0a78 334/// \ingroup StoreAPI
c8f4eac4 335typedef void (*STOREGETCLIENT) (StoreEntry *, void *cbdata);
336
2745fea5 337namespace Store {
4310f8b0
EB
338
339/// a smart pointer similar to std::unique_ptr<> that automatically
340/// release()s and unlock()s the guarded Entry on stack-unwinding failures
341class EntryGuard {
342public:
343 /// \param entry either nil or a locked Entry to manage
344 /// \param context default unlock() message
345 EntryGuard(Entry *entry, const char *context):
346 entry_(entry), context_(context) {
347 assert(!entry_ || entry_->locked());
348 }
349
350 ~EntryGuard() {
351 if (entry_) {
352 // something went wrong -- the caller did not unlockAndReset() us
353 onException();
354 }
355 }
356
357 EntryGuard(EntryGuard &&) = delete; // no copying or moving (for now)
358
359 /// like std::unique_ptr::get()
360 /// \returns nil or the guarded (locked) entry
361 Entry *get() {
362 return entry_;
363 }
364
365 /// like std::unique_ptr::reset()
366 /// stops guarding the entry
367 /// unlocks the entry (which may destroy it)
368 void unlockAndReset(const char *resetContext = nullptr) {
369 if (entry_) {
370 entry_->unlock(resetContext ? resetContext : context_);
371 entry_ = nullptr;
372 }
373 }
374
375private:
376 void onException() noexcept;
377
378 Entry *entry_; ///< the guarded Entry or nil
379 const char *context_; ///< default unlock() message
380};
381
7d84d4ca
SM
382void Stats(StoreEntry *output);
383void Maintain(void *unused);
4310f8b0 384}; // namespace Store
c8f4eac4 385
63be0a78 386/// \ingroup StoreAPI
71b673d4 387size_t storeEntryInUse();
63be0a78 388
389/// \ingroup StoreAPI
71b673d4 390const char *storeEntryFlags(const StoreEntry *);
63be0a78 391
392/// \ingroup StoreAPI
71b673d4 393void storeEntryReplaceObject(StoreEntry *, HttpReply *);
e6ccf245 394
63be0a78 395/// \ingroup StoreAPI
71b673d4 396StoreEntry *storeGetPublic(const char *uri, const HttpRequestMethod& method);
63be0a78 397
398/// \ingroup StoreAPI
1a210de4 399StoreEntry *storeGetPublicByRequest(HttpRequest * request, const KeyScope keyScope = ksDefault);
63be0a78 400
401/// \ingroup StoreAPI
1a210de4 402StoreEntry *storeGetPublicByRequestMethod(HttpRequest * request, const HttpRequestMethod& method, const KeyScope keyScope = ksDefault);
63be0a78 403
404/// \ingroup StoreAPI
1bfe9ade 405/// Like storeCreatePureEntry(), but also locks the entry and sets entry key.
71b673d4 406StoreEntry *storeCreateEntry(const char *, const char *, const RequestFlags &, const HttpRequestMethod&);
63be0a78 407
1bfe9ade
AR
408/// \ingroup StoreAPI
409/// Creates a new StoreEntry with mem_obj and sets initial flags/states.
4310f8b0 410StoreEntry *storeCreatePureEntry(const char *storeId, const char *logUrl, const HttpRequestMethod&);
1bfe9ade 411
63be0a78 412/// \ingroup StoreAPI
71b673d4 413void storeInit(void);
63be0a78 414
63be0a78 415/// \ingroup StoreAPI
71b673d4 416void storeConfigure(void);
63be0a78 417
418/// \ingroup StoreAPI
71b673d4 419void storeFreeMemory(void);
63be0a78 420
421/// \ingroup StoreAPI
71b673d4 422int expiresMoreThan(time_t, time_t);
63be0a78 423
63be0a78 424/// \ingroup StoreAPI
71b673d4 425void storeAppendPrintf(StoreEntry *, const char *,...) PRINTF_FORMAT_ARG2;
63be0a78 426
427/// \ingroup StoreAPI
71b673d4 428void storeAppendVPrintf(StoreEntry *, const char *, va_list ap);
63be0a78 429
430/// \ingroup StoreAPI
71b673d4 431int storeTooManyDiskFilesOpen(void);
63be0a78 432
433/// \ingroup StoreAPI
71b673d4 434void storeHeapPositionUpdate(StoreEntry *, SwapDir *);
63be0a78 435
436/// \ingroup StoreAPI
71b673d4 437void storeSwapFileNumberSet(StoreEntry * e, sfileno filn);
63be0a78 438
439/// \ingroup StoreAPI
71b673d4 440void storeFsInit(void);
63be0a78 441
442/// \ingroup StoreAPI
71b673d4 443void storeFsDone(void);
63be0a78 444
445/// \ingroup StoreAPI
71b673d4 446void storeReplAdd(const char *, REMOVALPOLICYCREATE *);
63be0a78 447
4310f8b0
EB
448/// One of the three methods to get rid of an unlocked StoreEntry object.
449/// This low-level method ignores lock()ing and release() promises. It never
450/// leaves the entry in the local store_table.
451/// TODO: Hide by moving its functionality into the StoreEntry destructor.
c8f4eac4 452extern FREE destroyStoreEntry;
e6ccf245 453
6d3c2758 454/// \ingroup StoreAPI
71b673d4 455void storeGetMemSpace(int size);
6d3c2758 456
e6ccf245 457#endif /* SQUID_STORE_H */
f53969cc 458