1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This file declares a HttpTransactionFactory implementation that can be
6// layered on top of another HttpTransactionFactory to add HTTP caching.  The
7// caching logic follows RFC 2616 (any exceptions are called out in the code).
8//
9// The HttpCache takes a disk_cache::Backend as a parameter, and uses that for
10// the cache storage.
11//
12// See HttpTransactionFactory and HttpTransaction for more details.
13
14#ifndef NET_HTTP_HTTP_CACHE_H_
15#define NET_HTTP_HTTP_CACHE_H_
16#pragma once
17
18#include <list>
19#include <set>
20#include <string>
21
22#include "base/basictypes.h"
23#include "base/file_path.h"
24#include "base/hash_tables.h"
25#include "base/memory/scoped_ptr.h"
26#include "base/memory/weak_ptr.h"
27#include "base/message_loop_proxy.h"
28#include "base/task.h"
29#include "base/threading/non_thread_safe.h"
30#include "net/base/cache_type.h"
31#include "net/base/completion_callback.h"
32#include "net/base/load_states.h"
33#include "net/base/net_export.h"
34#include "net/http/http_transaction_factory.h"
35
36class GURL;
37
38namespace disk_cache {
39class Backend;
40class Entry;
41}
42
43namespace net {
44
45class CertVerifier;
46class DnsCertProvenanceChecker;
47class DnsRRResolver;
48class HostResolver;
49class HttpAuthHandlerFactory;
50class HttpNetworkSession;
51struct HttpRequestInfo;
52class HttpResponseInfo;
53class IOBuffer;
54class NetLog;
55class NetworkDelegate;
56class ProxyService;
57class SSLConfigService;
58class ViewCacheHelper;
59
60class NET_EXPORT HttpCache : public HttpTransactionFactory,
61                  public base::SupportsWeakPtr<HttpCache>,
62                  public base::NonThreadSafe {
63 public:
64  // The cache mode of operation.
65  enum Mode {
66    // Normal mode just behaves like a standard web cache.
67    NORMAL = 0,
68    // Record mode caches everything for purposes of offline playback.
69    RECORD,
70    // Playback mode replays from a cache without considering any
71    // standard invalidations.
72    PLAYBACK,
73    // Disables reads and writes from the cache.
74    // Equivalent to setting LOAD_DISABLE_CACHE on every request.
75    DISABLE
76  };
77
78  // A BackendFactory creates a backend object to be used by the HttpCache.
79  class NET_EXPORT BackendFactory {
80   public:
81    virtual ~BackendFactory() {}
82
83    // The actual method to build the backend. Returns a net error code. If
84    // ERR_IO_PENDING is returned, the |callback| will be notified when the
85    // operation completes, and |backend| must remain valid until the
86    // notification arrives.
87    // The implementation must not access the factory object after invoking the
88    // |callback| because the object can be deleted from within the callback.
89    virtual int CreateBackend(NetLog* net_log,
90                              disk_cache::Backend** backend,
91                              CompletionCallback* callback) = 0;
92  };
93
94  // A default backend factory for the common use cases.
95  class NET_EXPORT DefaultBackend : public BackendFactory {
96   public:
97    // |path| is the destination for any files used by the backend, and
98    // |cache_thread| is the thread where disk operations should take place. If
99    // |max_bytes| is  zero, a default value will be calculated automatically.
100    DefaultBackend(CacheType type, const FilePath& path, int max_bytes,
101                   base::MessageLoopProxy* thread);
102    virtual ~DefaultBackend();
103
104    // Returns a factory for an in-memory cache.
105    static BackendFactory* InMemory(int max_bytes);
106
107    // BackendFactory implementation.
108    virtual int CreateBackend(NetLog* net_log,
109                              disk_cache::Backend** backend,
110                              CompletionCallback* callback);
111
112   private:
113    CacheType type_;
114    const FilePath path_;
115    int max_bytes_;
116    scoped_refptr<base::MessageLoopProxy> thread_;
117  };
118
119  // The disk cache is initialized lazily (by CreateTransaction) in this case.
120  // The HttpCache takes ownership of the |backend_factory|.
121  HttpCache(HostResolver* host_resolver,
122            CertVerifier* cert_verifier,
123            DnsRRResolver* dnsrr_resolver,
124            DnsCertProvenanceChecker* dns_cert_checker,
125            ProxyService* proxy_service,
126            SSLConfigService* ssl_config_service,
127            HttpAuthHandlerFactory* http_auth_handler_factory,
128            NetworkDelegate* network_delegate,
129            NetLog* net_log,
130            BackendFactory* backend_factory);
131
132  // The disk cache is initialized lazily (by CreateTransaction) in  this case.
133  // Provide an existing HttpNetworkSession, the cache can construct a
134  // network layer with a shared HttpNetworkSession in order for multiple
135  // network layers to share information (e.g. authentication data). The
136  // HttpCache takes ownership of the |backend_factory|.
137  HttpCache(HttpNetworkSession* session, BackendFactory* backend_factory);
138
139  // Initialize the cache from its component parts, which is useful for
140  // testing.  The lifetime of the network_layer and backend_factory are managed
141  // by the HttpCache and will be destroyed using |delete| when the HttpCache is
142  // destroyed.
143  HttpCache(HttpTransactionFactory* network_layer,
144            NetLog* net_log,
145            BackendFactory* backend_factory);
146
147  ~HttpCache();
148
149  HttpTransactionFactory* network_layer() { return network_layer_.get(); }
150
151  // Retrieves the cache backend for this HttpCache instance. If the backend
152  // is not initialized yet, this method will initialize it. The return value is
153  // a network error code, and it could be ERR_IO_PENDING, in which case the
154  // |callback| will be notified when the operation completes. The pointer that
155  // receives the |backend| must remain valid until the operation completes.
156  int GetBackend(disk_cache::Backend** backend, CompletionCallback* callback);
157
158  // Returns the current backend (can be NULL).
159  disk_cache::Backend* GetCurrentBackend();
160
161  // Given a header data blob, convert it to a response info object.
162  static bool ParseResponseInfo(const char* data, int len,
163                                HttpResponseInfo* response_info,
164                                bool* response_truncated);
165
166  // Writes |buf_len| bytes of metadata stored in |buf| to the cache entry
167  // referenced by |url|, as long as the entry's |expected_response_time| has
168  // not changed. This method returns without blocking, and the operation will
169  // be performed asynchronously without any completion notification.
170  void WriteMetadata(const GURL& url, base::Time expected_response_time,
171                     IOBuffer* buf, int buf_len);
172
173  // Get/Set the cache's mode.
174  void set_mode(Mode value) { mode_ = value; }
175  Mode mode() { return mode_; }
176
177  // Close currently active sockets so that fresh page loads will not use any
178  // recycled connections.  For sockets currently in use, they may not close
179  // immediately, but they will not be reusable. This is for debugging.
180  void CloseAllConnections();
181
182  // Close all idle connections. Will close all sockets not in active use.
183  void CloseIdleConnections();
184
185  // HttpTransactionFactory implementation:
186  virtual int CreateTransaction(scoped_ptr<HttpTransaction>* trans);
187  virtual HttpCache* GetCache();
188  virtual HttpNetworkSession* GetSession();
189  virtual void Suspend(bool suspend);
190
191 protected:
192  // Disk cache entry data indices.
193  enum {
194    kResponseInfoIndex = 0,
195    kResponseContentIndex,
196    kMetadataIndex,
197
198    // Must remain at the end of the enum.
199    kNumCacheEntryDataIndices
200  };
201  friend class ViewCacheHelper;
202
203 private:
204  // Types --------------------------------------------------------------------
205
206  class BackendCallback;
207  class MetadataWriter;
208  class SSLHostInfoFactoryAdaptor;
209  class Transaction;
210  class WorkItem;
211  friend class Transaction;
212  struct PendingOp;  // Info for an entry under construction.
213
214  typedef std::list<Transaction*> TransactionList;
215  typedef std::list<WorkItem*> WorkItemList;
216
217  struct ActiveEntry {
218    explicit ActiveEntry(disk_cache::Entry* entry);
219    ~ActiveEntry();
220
221    disk_cache::Entry* disk_entry;
222    Transaction*       writer;
223    TransactionList    readers;
224    TransactionList    pending_queue;
225    bool               will_process_pending_queue;
226    bool               doomed;
227  };
228
229  typedef base::hash_map<std::string, ActiveEntry*> ActiveEntriesMap;
230  typedef base::hash_map<std::string, PendingOp*> PendingOpsMap;
231  typedef std::set<ActiveEntry*> ActiveEntriesSet;
232  typedef base::hash_map<std::string, int> PlaybackCacheMap;
233
234  // Methods ------------------------------------------------------------------
235
236  // Creates the |backend| object and notifies the |callback| when the operation
237  // completes. Returns an error code.
238  int CreateBackend(disk_cache::Backend** backend,
239                    CompletionCallback* callback);
240
241  // Makes sure that the backend creation is complete before allowing the
242  // provided transaction to use the object. Returns an error code.  |trans|
243  // will be notified via its IO callback if this method returns ERR_IO_PENDING.
244  // The transaction is free to use the backend directly at any time after
245  // receiving the notification.
246  int GetBackendForTransaction(Transaction* trans);
247
248  // Generates the cache key for this request.
249  std::string GenerateCacheKey(const HttpRequestInfo*);
250
251  // Dooms the entry selected by |key|. |trans| will be notified via its IO
252  // callback if this method returns ERR_IO_PENDING. The entry can be
253  // currently in use or not.
254  int DoomEntry(const std::string& key, Transaction* trans);
255
256  // Dooms the entry selected by |key|. |trans| will be notified via its IO
257  // callback if this method returns ERR_IO_PENDING. The entry should not
258  // be currently in use.
259  int AsyncDoomEntry(const std::string& key, Transaction* trans);
260
261  // Closes a previously doomed entry.
262  void FinalizeDoomedEntry(ActiveEntry* entry);
263
264  // Returns an entry that is currently in use and not doomed, or NULL.
265  ActiveEntry* FindActiveEntry(const std::string& key);
266
267  // Creates a new ActiveEntry and starts tracking it. |disk_entry| is the disk
268  // cache entry.
269  ActiveEntry* ActivateEntry(disk_cache::Entry* disk_entry);
270
271  // Deletes an ActiveEntry.
272  void DeactivateEntry(ActiveEntry* entry);
273
274  // Deletes an ActiveEntry using an exhaustive search.
275  void SlowDeactivateEntry(ActiveEntry* entry);
276
277  // Returns the PendingOp for the desired |key|. If an entry is not under
278  // construction already, a new PendingOp structure is created.
279  PendingOp* GetPendingOp(const std::string& key);
280
281  // Deletes a PendingOp.
282  void DeletePendingOp(PendingOp* pending_op);
283
284  // Opens the disk cache entry associated with |key|, returning an ActiveEntry
285  // in |*entry|. |trans| will be notified via its IO callback if this method
286  // returns ERR_IO_PENDING.
287  int OpenEntry(const std::string& key, ActiveEntry** entry,
288                Transaction* trans);
289
290  // Creates the disk cache entry associated with |key|, returning an
291  // ActiveEntry in |*entry|. |trans| will be notified via its IO callback if
292  // this method returns ERR_IO_PENDING.
293  int CreateEntry(const std::string& key, ActiveEntry** entry,
294                  Transaction* trans);
295
296  // Destroys an ActiveEntry (active or doomed).
297  void DestroyEntry(ActiveEntry* entry);
298
299  // Adds a transaction to an ActiveEntry. If this method returns ERR_IO_PENDING
300  // the transaction will be notified about completion via its IO callback. This
301  // method returns ERR_CACHE_RACE to signal the transaction that it cannot be
302  // added to the provided entry, and it should retry the process with another
303  // one (in this case, the entry is no longer valid).
304  int AddTransactionToEntry(ActiveEntry* entry, Transaction* trans);
305
306  // Called when the transaction has finished working with this entry. |cancel|
307  // is true if the operation was cancelled by the caller instead of running
308  // to completion.
309  void DoneWithEntry(ActiveEntry* entry, Transaction* trans, bool cancel);
310
311  // Called when the transaction has finished writting to this entry. |success|
312  // is false if the cache entry should be deleted.
313  void DoneWritingToEntry(ActiveEntry* entry, bool success);
314
315  // Called when the transaction has finished reading from this entry.
316  void DoneReadingFromEntry(ActiveEntry* entry, Transaction* trans);
317
318  // Convers the active writter transaction to a reader so that other
319  // transactions can start reading from this entry.
320  void ConvertWriterToReader(ActiveEntry* entry);
321
322  // Returns the LoadState of the provided pending transaction.
323  LoadState GetLoadStateForPendingTransaction(const Transaction* trans);
324
325  // Removes the transaction |trans|, from the pending list of an entry
326  // (PendingOp, active or doomed entry).
327  void RemovePendingTransaction(Transaction* trans);
328
329  // Removes the transaction |trans|, from the pending list of |entry|.
330  bool RemovePendingTransactionFromEntry(ActiveEntry* entry,
331                                         Transaction* trans);
332
333  // Removes the transaction |trans|, from the pending list of |pending_op|.
334  bool RemovePendingTransactionFromPendingOp(PendingOp* pending_op,
335                                             Transaction* trans);
336
337  // Resumes processing the pending list of |entry|.
338  void ProcessPendingQueue(ActiveEntry* entry);
339
340  // Events (called via PostTask) ---------------------------------------------
341
342  void OnProcessPendingQueue(ActiveEntry* entry);
343
344  // Callbacks ----------------------------------------------------------------
345
346  // Processes BackendCallback notifications.
347  void OnIOComplete(int result, PendingOp* entry);
348
349  // Processes the backend creation notification.
350  void OnBackendCreated(int result, PendingOp* pending_op);
351
352
353  // Variables ----------------------------------------------------------------
354
355  NetLog* net_log_;
356
357  // Used when lazily constructing the disk_cache_.
358  scoped_ptr<BackendFactory> backend_factory_;
359  bool building_backend_;
360
361  Mode mode_;
362
363  const scoped_ptr<SSLHostInfoFactoryAdaptor> ssl_host_info_factory_;
364
365  const scoped_ptr<HttpTransactionFactory> network_layer_;
366  scoped_ptr<disk_cache::Backend> disk_cache_;
367
368  // The set of active entries indexed by cache key.
369  ActiveEntriesMap active_entries_;
370
371  // The set of doomed entries.
372  ActiveEntriesSet doomed_entries_;
373
374  // The set of entries "under construction".
375  PendingOpsMap pending_ops_;
376
377  ScopedRunnableMethodFactory<HttpCache> task_factory_;
378
379  scoped_ptr<PlaybackCacheMap> playback_cache_map_;
380
381  DISALLOW_COPY_AND_ASSIGN(HttpCache);
382};
383
384}  // namespace net
385
386#endif  // NET_HTTP_HTTP_CACHE_H_
387