Home | History | Annotate | Download | only in http
      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 HttpCache::Transaction, a private class of HttpCache so
      6 // it should only be included by http_cache.cc
      7 
      8 #ifndef NET_HTTP_HTTP_CACHE_TRANSACTION_H_
      9 #define NET_HTTP_HTTP_CACHE_TRANSACTION_H_
     10 #pragma once
     11 
     12 #include <string>
     13 
     14 #include "base/string16.h"
     15 #include "base/time.h"
     16 #include "net/base/net_log.h"
     17 #include "net/http/http_cache.h"
     18 #include "net/http/http_response_info.h"
     19 #include "net/http/http_transaction.h"
     20 
     21 namespace net {
     22 
     23 class HttpResponseHeaders;
     24 class PartialData;
     25 struct HttpRequestInfo;
     26 
     27 // This is the transaction that is returned by the HttpCache transaction
     28 // factory.
     29 class HttpCache::Transaction : public HttpTransaction {
     30  public:
     31   // The transaction has the following modes, which apply to how it may access
     32   // its cache entry.
     33   //
     34   //  o If the mode of the transaction is NONE, then it is in "pass through"
     35   //    mode and all methods just forward to the inner network transaction.
     36   //
     37   //  o If the mode of the transaction is only READ, then it may only read from
     38   //    the cache entry.
     39   //
     40   //  o If the mode of the transaction is only WRITE, then it may only write to
     41   //    the cache entry.
     42   //
     43   //  o If the mode of the transaction is READ_WRITE, then the transaction may
     44   //    optionally modify the cache entry (e.g., possibly corresponding to
     45   //    cache validation).
     46   //
     47   //  o If the mode of the transaction is UPDATE, then the transaction may
     48   //    update existing cache entries, but will never create a new entry or
     49   //    respond using the entry read from the cache.
     50   enum Mode {
     51     NONE            = 0,
     52     READ_META       = 1 << 0,
     53     READ_DATA       = 1 << 1,
     54     READ            = READ_META | READ_DATA,
     55     WRITE           = 1 << 2,
     56     READ_WRITE      = READ | WRITE,
     57     UPDATE          = READ_META | WRITE,  // READ_WRITE & ~READ_DATA
     58   };
     59 
     60   Transaction(HttpCache* cache);
     61   virtual ~Transaction();
     62 
     63   Mode mode() const { return mode_; }
     64 
     65   const std::string& key() const { return cache_key_; }
     66 
     67   // Writes |buf_len| bytes of meta-data from the provided buffer |buf|. to the
     68   // HTTP cache entry that backs this transaction (if any).
     69   // Returns the number of bytes actually written, or a net error code. If the
     70   // operation cannot complete immediately, returns ERR_IO_PENDING, grabs a
     71   // reference to the buffer (until completion), and notifies the caller using
     72   // the provided |callback| when the operatiopn finishes.
     73   //
     74   // The first time this method is called for a given transaction, previous
     75   // meta-data will be overwritten with the provided data, and subsequent
     76   // invocations will keep appending to the cached entry.
     77   //
     78   // In order to guarantee that the metadata is set to the correct entry, the
     79   // response (or response info) must be evaluated by the caller, for instance
     80   // to make sure that the response_time is as expected, before calling this
     81   // method.
     82   int WriteMetadata(IOBuffer* buf, int buf_len, CompletionCallback* callback);
     83 
     84   // This transaction is being deleted and we are not done writing to the cache.
     85   // We need to indicate that the response data was truncated.  Returns true on
     86   // success.
     87   bool AddTruncatedFlag();
     88 
     89   // Returns the LoadState of the writer transaction of a given ActiveEntry. In
     90   // other words, returns the LoadState of this transaction without asking the
     91   // http cache, because this transaction should be the one currently writing
     92   // to the cache entry.
     93   LoadState GetWriterLoadState() const;
     94 
     95   CompletionCallback* io_callback() { return &io_callback_; }
     96 
     97   const BoundNetLog& net_log() const;
     98 
     99   // HttpTransaction methods:
    100   virtual int Start(const HttpRequestInfo*, CompletionCallback*,
    101                     const BoundNetLog&);
    102   virtual int RestartIgnoringLastError(CompletionCallback* callback);
    103   virtual int RestartWithCertificate(X509Certificate* client_cert,
    104                                      CompletionCallback* callback);
    105   virtual int RestartWithAuth(const string16& username,
    106                               const string16& password,
    107                               CompletionCallback* callback);
    108   virtual bool IsReadyToRestartForAuth();
    109   virtual int Read(IOBuffer* buf, int buf_len, CompletionCallback* callback);
    110   virtual void StopCaching();
    111   virtual const HttpResponseInfo* GetResponseInfo() const;
    112   virtual LoadState GetLoadState() const;
    113   virtual uint64 GetUploadProgress(void) const;
    114 
    115  private:
    116   static const size_t kNumValidationHeaders = 2;
    117   // Helper struct to pair a header name with its value, for
    118   // headers used to validate cache entries.
    119   struct ValidationHeaders {
    120     ValidationHeaders() : initialized(false) {}
    121 
    122     std::string values[kNumValidationHeaders];
    123     bool initialized;
    124   };
    125 
    126   enum State {
    127     STATE_NONE,
    128     STATE_GET_BACKEND,
    129     STATE_GET_BACKEND_COMPLETE,
    130     STATE_SEND_REQUEST,
    131     STATE_SEND_REQUEST_COMPLETE,
    132     STATE_SUCCESSFUL_SEND_REQUEST,
    133     STATE_NETWORK_READ,
    134     STATE_NETWORK_READ_COMPLETE,
    135     STATE_INIT_ENTRY,
    136     STATE_OPEN_ENTRY,
    137     STATE_OPEN_ENTRY_COMPLETE,
    138     STATE_CREATE_ENTRY,
    139     STATE_CREATE_ENTRY_COMPLETE,
    140     STATE_DOOM_ENTRY,
    141     STATE_DOOM_ENTRY_COMPLETE,
    142     STATE_ADD_TO_ENTRY,
    143     STATE_ADD_TO_ENTRY_COMPLETE,
    144     STATE_NOTIFY_BEFORE_SEND_HEADERS,
    145     STATE_NOTIFY_BEFORE_SEND_HEADERS_COMPLETE,
    146     STATE_START_PARTIAL_CACHE_VALIDATION,
    147     STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
    148     STATE_UPDATE_CACHED_RESPONSE,
    149     STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
    150     STATE_OVERWRITE_CACHED_RESPONSE,
    151     STATE_TRUNCATE_CACHED_DATA,
    152     STATE_TRUNCATE_CACHED_DATA_COMPLETE,
    153     STATE_TRUNCATE_CACHED_METADATA,
    154     STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
    155     STATE_PARTIAL_HEADERS_RECEIVED,
    156     STATE_CACHE_READ_RESPONSE,
    157     STATE_CACHE_READ_RESPONSE_COMPLETE,
    158     STATE_CACHE_WRITE_RESPONSE,
    159     STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
    160     STATE_CACHE_WRITE_RESPONSE_COMPLETE,
    161     STATE_CACHE_READ_METADATA,
    162     STATE_CACHE_READ_METADATA_COMPLETE,
    163     STATE_CACHE_QUERY_DATA,
    164     STATE_CACHE_QUERY_DATA_COMPLETE,
    165     STATE_CACHE_READ_DATA,
    166     STATE_CACHE_READ_DATA_COMPLETE,
    167     STATE_CACHE_WRITE_DATA,
    168     STATE_CACHE_WRITE_DATA_COMPLETE
    169   };
    170 
    171   // This is a helper function used to trigger a completion callback.  It may
    172   // only be called if callback_ is non-null.
    173   void DoCallback(int rv);
    174 
    175   // This will trigger the completion callback if appropriate.
    176   int HandleResult(int rv);
    177 
    178   // Runs the state transition loop.
    179   int DoLoop(int result);
    180 
    181   // Each of these methods corresponds to a State value.  If there is an
    182   // argument, the value corresponds to the return of the previous state or
    183   // corresponding callback.
    184   int DoGetBackend();
    185   int DoGetBackendComplete(int result);
    186   int DoSendRequest();
    187   int DoSendRequestComplete(int result);
    188   int DoSuccessfulSendRequest();
    189   int DoNetworkRead();
    190   int DoNetworkReadComplete(int result);
    191   int DoInitEntry();
    192   int DoOpenEntry();
    193   int DoOpenEntryComplete(int result);
    194   int DoCreateEntry();
    195   int DoCreateEntryComplete(int result);
    196   int DoDoomEntry();
    197   int DoDoomEntryComplete(int result);
    198   int DoAddToEntry();
    199   int DoAddToEntryComplete(int result);
    200   int DoNotifyBeforeSendHeaders();
    201   int DoNotifyBeforeSendHeadersComplete(int result);
    202   int DoStartPartialCacheValidation();
    203   int DoCompletePartialCacheValidation(int result);
    204   int DoUpdateCachedResponse();
    205   int DoUpdateCachedResponseComplete(int result);
    206   int DoOverwriteCachedResponse();
    207   int DoTruncateCachedData();
    208   int DoTruncateCachedDataComplete(int result);
    209   int DoTruncateCachedMetadata();
    210   int DoTruncateCachedMetadataComplete(int result);
    211   int DoPartialHeadersReceived();
    212   int DoCacheReadResponse();
    213   int DoCacheReadResponseComplete(int result);
    214   int DoCacheWriteResponse();
    215   int DoCacheWriteTruncatedResponse();
    216   int DoCacheWriteResponseComplete(int result);
    217   int DoCacheReadMetadata();
    218   int DoCacheReadMetadataComplete(int result);
    219   int DoCacheQueryData();
    220   int DoCacheQueryDataComplete(int result);
    221   int DoCacheReadData();
    222   int DoCacheReadDataComplete(int result);
    223   int DoCacheWriteData(int num_bytes);
    224   int DoCacheWriteDataComplete(int result);
    225 
    226   // Sets request_ and fields derived from it.
    227   void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
    228 
    229   // Returns true if the request should be handled exclusively by the network
    230   // layer (skipping the cache entirely).
    231   bool ShouldPassThrough();
    232 
    233   // Called to begin reading from the cache.  Returns network error code.
    234   int BeginCacheRead();
    235 
    236   // Called to begin validating the cache entry.  Returns network error code.
    237   int BeginCacheValidation();
    238 
    239   // Called to begin validating an entry that stores partial content.  Returns
    240   // a network error code.
    241   int BeginPartialCacheValidation();
    242 
    243   // Validates the entry headers against the requested range and continues with
    244   // the validation of the rest of the entry.  Returns a network error code.
    245   int ValidateEntryHeadersAndContinue(bool byte_range_requested);
    246 
    247   // Called to start requests which were given an "if-modified-since" or
    248   // "if-none-match" validation header by the caller (NOT when the request was
    249   // conditionalized internally in response to LOAD_VALIDATE_CACHE).
    250   // Returns a network error code.
    251   int BeginExternallyConditionalizedRequest();
    252 
    253   // Called to restart a network transaction after an error.  Returns network
    254   // error code.
    255   int RestartNetworkRequest();
    256 
    257   // Called to restart a network transaction with a client certificate.
    258   // Returns network error code.
    259   int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
    260 
    261   // Called to restart a network transaction with authentication credentials.
    262   // Returns network error code.
    263   int RestartNetworkRequestWithAuth(const string16& username,
    264                                     const string16& password);
    265 
    266   // Called to determine if we need to validate the cache entry before using it.
    267   bool RequiresValidation();
    268 
    269   // Called to make the request conditional (to ask the server if the cached
    270   // copy is valid).  Returns true if able to make the request conditional.
    271   bool ConditionalizeRequest();
    272 
    273   // Makes sure that a 206 response is expected.  Returns true on success.
    274   // On success, |partial_content| will be set to true if we are processing a
    275   // partial entry.
    276   bool ValidatePartialResponse(bool* partial_content);
    277 
    278   // Handles a response validation error by bypassing the cache.
    279   void IgnoreRangeRequest();
    280 
    281   // Changes the response code of a range request to be 416 (Requested range not
    282   // satisfiable).
    283   void FailRangeRequest();
    284 
    285   // Reads data from the network.
    286   int ReadFromNetwork(IOBuffer* data, int data_len);
    287 
    288   // Reads data from the cache entry.
    289   int ReadFromEntry(IOBuffer* data, int data_len);
    290 
    291   // Called to write data to the cache entry.  If the write fails, then the
    292   // cache entry is destroyed.  Future calls to this function will just do
    293   // nothing without side-effect.  Returns a network error code.
    294   int WriteToEntry(int index, int offset, IOBuffer* data, int data_len,
    295                    CompletionCallback* callback);
    296 
    297   // Called to write response_ to the cache entry. |truncated| indicates if the
    298   // entry should be marked as incomplete.
    299   int WriteResponseInfoToEntry(bool truncated);
    300 
    301   // Called to append response data to the cache entry.  Returns a network error
    302   // code.
    303   int AppendResponseDataToEntry(IOBuffer* data, int data_len,
    304                                 CompletionCallback* callback);
    305 
    306   // Called when we are done writing to the cache entry.
    307   void DoneWritingToEntry(bool success);
    308 
    309   // Deletes the current partial cache entry (sparse), and optionally removes
    310   // the control object (partial_).
    311   void DoomPartialEntry(bool delete_object);
    312 
    313   // Performs the needed work after receiving data from the network, when
    314   // working with range requests.
    315   int DoPartialNetworkReadCompleted(int result);
    316 
    317   // Performs the needed work after receiving data from the cache, when
    318   // working with range requests.
    319   int DoPartialCacheReadCompleted(int result);
    320 
    321   // Returns true if we should bother attempting to resume this request if it
    322   // is aborted while in progress. If |has_data| is true, the size of the stored
    323   // data is considered for the result.
    324   bool CanResume(bool has_data);
    325 
    326   // Called to signal completion of asynchronous IO.
    327   void OnIOComplete(int result);
    328 
    329   State next_state_;
    330   const HttpRequestInfo* request_;
    331   BoundNetLog net_log_;
    332   scoped_ptr<HttpRequestInfo> custom_request_;
    333   // If extra_headers specified a "if-modified-since" or "if-none-match",
    334   // |external_validation_| contains the value of those headers.
    335   ValidationHeaders external_validation_;
    336   base::WeakPtr<HttpCache> cache_;
    337   HttpCache::ActiveEntry* entry_;
    338   base::TimeTicks entry_lock_waiting_since_;
    339   HttpCache::ActiveEntry* new_entry_;
    340   scoped_ptr<HttpTransaction> network_trans_;
    341   CompletionCallback* callback_;  // Consumer's callback.
    342   HttpResponseInfo response_;
    343   HttpResponseInfo auth_response_;
    344   const HttpResponseInfo* new_response_;
    345   std::string cache_key_;
    346   Mode mode_;
    347   State target_state_;
    348   bool reading_;  // We are already reading.
    349   bool invalid_range_;  // We may bypass the cache for this request.
    350   bool truncated_;  // We don't have all the response data.
    351   bool is_sparse_;  // The data is stored in sparse byte ranges.
    352   bool server_responded_206_;
    353   bool cache_pending_;  // We are waiting for the HttpCache.
    354   scoped_refptr<IOBuffer> read_buf_;
    355   int io_buf_len_;
    356   int read_offset_;
    357   int effective_load_flags_;
    358   int write_len_;
    359   scoped_ptr<PartialData> partial_;  // We are dealing with range requests.
    360   uint64 final_upload_progress_;
    361   CompletionCallbackImpl<Transaction> io_callback_;
    362   scoped_refptr<CancelableCompletionCallback<Transaction> > cache_callback_;
    363   scoped_refptr<CancelableCompletionCallback<Transaction> >
    364       write_headers_callback_;
    365 };
    366 
    367 }  // namespace net
    368 
    369 #endif  // NET_HTTP_HTTP_CACHE_TRANSACTION_H_
    370