1 // Copyright (c) 2012 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.
5 #ifndef NET_SOCKET_STREAM_SOCKET_STREAM_H_
6 #define NET_SOCKET_STREAM_SOCKET_STREAM_H_
12 #include "base/memory/linked_ptr.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "net/base/address_list.h"
16 #include "net/base/completion_callback.h"
17 #include "net/base/io_buffer.h"
18 #include "net/base/net_errors.h"
19 #include "net/base/net_export.h"
20 #include "net/base/net_log.h"
21 #include "net/base/privacy_mode.h"
22 #include "net/cookies/cookie_store.h"
23 #include "net/proxy/proxy_service.h"
24 #include "net/ssl/ssl_config_service.h"
25 #include "net/url_request/url_request.h"
29 class AuthChallengeInfo
;
31 class ChannelIDService
;
32 class ClientSocketFactory
;
33 class ClientSocketHandle
;
36 class HttpAuthController
;
38 class SingleRequestHostResolver
;
39 class SocketStreamMetrics
;
40 class TransportSecurityState
;
41 class URLRequestContext
;
43 // SocketStream is used to implement Web Sockets.
44 // It provides plain full-duplex stream with proxy and SSL support.
45 // For proxy authentication, only basic mechanisum is supported. It will try
46 // authentication identity for proxy URL first. If server requires proxy
47 // authentication, it will try authentication identity for realm that server
49 class NET_EXPORT SocketStream
50 : public base::RefCountedThreadSafe
<SocketStream
> {
52 // Derive from this class and add your own data members to associate extra
53 // information with a SocketStream. Use GetUserData(key) and
54 // SetUserData(key, data).
58 virtual ~UserData() {}
61 class NET_EXPORT Delegate
{
63 virtual int OnStartOpenConnection(SocketStream
* socket
,
64 const CompletionCallback
& callback
);
66 // Called when a socket stream has been connected. The socket stream is
67 // allowed to buffer pending send data at most |max_pending_send_allowed|
68 // bytes. A client of the socket stream should keep track of how much
69 // pending send data it has and must not call SendData() if the pending
70 // data goes over |max_pending_send_allowed| bytes.
71 virtual void OnConnected(SocketStream
* socket
,
72 int max_pending_send_allowed
) = 0;
74 // Called when |amount_sent| bytes of data are sent.
75 virtual void OnSentData(SocketStream
* socket
,
78 // Called when |len| bytes of |data| are received.
79 virtual void OnReceivedData(SocketStream
* socket
,
80 const char* data
, int len
) = 0;
82 // Called when the socket stream has been closed.
83 virtual void OnClose(SocketStream
* socket
) = 0;
85 // Called when proxy authentication required.
86 // The delegate should call RestartWithAuth() if credential for |auth_info|
87 // is found in password database, or call Close() to close the connection.
88 virtual void OnAuthRequired(SocketStream
* socket
,
89 AuthChallengeInfo
* auth_info
);
91 // Called when using SSL and the server responds with a certificate with an
92 // error. The delegate should call CancelBecauseOfCertError() or
93 // ContinueDespiteCertError() to resume connection handling.
94 virtual void OnSSLCertificateError(SocketStream
* socket
,
95 const SSLInfo
& ssl_info
,
98 // Called when an error occured.
99 // This is only for error reporting to the delegate.
100 // |error| is net::Error.
101 virtual void OnError(const SocketStream
* socket
, int error
) {}
103 // Called when reading cookies to allow the delegate to block access to the
105 virtual bool CanGetCookies(SocketStream
* socket
, const GURL
& url
);
107 // Called when a cookie is set to allow the delegate to block access to the
109 virtual bool CanSetCookie(SocketStream
* request
,
111 const std::string
& cookie_line
,
112 CookieOptions
* options
);
115 virtual ~Delegate() {}
118 SocketStream(const GURL
& url
, Delegate
* delegate
, URLRequestContext
* context
,
119 CookieStore
* cookie_store
);
121 // The user data allows the clients to associate data with this job.
122 // Multiple user data values can be stored under different keys.
123 // This job will TAKE OWNERSHIP of the given data pointer, and will
124 // delete the object if it is changed or the job is destroyed.
125 UserData
* GetUserData(const void* key
) const;
126 void SetUserData(const void* key
, UserData
* data
);
128 const GURL
& url() const { return url_
; }
129 bool is_secure() const;
130 const AddressList
& address_list() const { return addresses_
; }
131 Delegate
* delegate() const { return delegate_
; }
132 int max_pending_send_allowed() const { return max_pending_send_allowed_
; }
134 URLRequestContext
* context() { return context_
; }
136 const SSLConfig
& server_ssl_config() const { return server_ssl_config_
; }
137 PrivacyMode
privacy_mode() const { return privacy_mode_
; }
138 void CheckPrivacyMode();
140 BoundNetLog
* net_log() { return &net_log_
; }
142 // Opens the connection on the IO thread.
143 // Once the connection is established, calls delegate's OnConnected.
144 virtual void Connect();
146 // Buffers |data| of |len| bytes for send and returns true if successful.
147 // If size of buffered data exceeds |max_pending_send_allowed_|, sends no
148 // data and returns false. |len| must be positive.
149 virtual bool SendData(const char* data
, int len
);
151 // Requests to close the connection.
152 // Once the connection is closed, calls delegate's OnClose.
153 virtual void Close();
155 // Restarts with authentication info.
156 // Should be used for response of OnAuthRequired.
157 virtual void RestartWithAuth(const AuthCredentials
& credentials
);
159 // Detach delegate. Call before delegate is deleted.
160 // Once delegate is detached, close the socket stream and never call delegate
162 virtual void DetachDelegate();
164 // Detach the context.
165 virtual void DetachContext();
167 const ProxyServer
& proxy_server() const;
169 // Sets an alternative ClientSocketFactory. Doesn't take ownership of
170 // |factory|. For testing purposes only.
171 void SetClientSocketFactory(ClientSocketFactory
* factory
);
173 // Cancels the connection because of an error.
174 // |error| is net::Error which represents the error.
175 void CancelWithError(int error
);
177 // Cancels the connection because of receiving a certificate with an error.
178 void CancelWithSSLError(const SSLInfo
& ssl_info
);
180 // Continues to establish the connection in spite of an error. Usually this
181 // case happens because users allow certificate with an error by manual
182 // actions on alert dialog or browser cached such kinds of user actions.
183 void ContinueDespiteError();
185 CookieStore
* cookie_store() const;
188 friend class base::RefCountedThreadSafe
<SocketStream
>;
189 virtual ~SocketStream();
194 FRIEND_TEST_ALL_PREFIXES(SocketStreamTest
, IOPending
);
195 FRIEND_TEST_ALL_PREFIXES(SocketStreamTest
, SwitchAfterPending
);
196 FRIEND_TEST_ALL_PREFIXES(SocketStreamTest
,
197 NullContextSocketStreamShouldNotCrash
);
199 friend class WebSocketThrottleTest
;
201 typedef std::map
<const void*, linked_ptr
<UserData
> > UserDataMap
;
202 typedef std::deque
< scoped_refptr
<IOBufferWithSize
> > PendingDataQueue
;
204 class RequestHeaders
: public IOBuffer
{
206 RequestHeaders() : IOBuffer() {}
208 void SetDataOffset(size_t offset
) {
209 data_
= const_cast<char*>(headers_
.data()) + offset
;
212 std::string headers_
;
215 virtual ~RequestHeaders();
218 class ResponseHeaders
: public IOBuffer
{
222 void SetDataOffset(size_t offset
) { data_
= headers_
.get() + offset
; }
223 char* headers() const { return headers_
.get(); }
224 void Reset() { headers_
.reset(); }
225 void Realloc(size_t new_size
);
228 virtual ~ResponseHeaders();
230 scoped_ptr
<char, base::FreeDeleter
> headers_
;
235 STATE_BEFORE_CONNECT
,
236 STATE_BEFORE_CONNECT_COMPLETE
,
238 STATE_RESOLVE_PROXY_COMPLETE
,
240 STATE_RESOLVE_HOST_COMPLETE
,
241 STATE_RESOLVE_PROTOCOL
,
242 STATE_RESOLVE_PROTOCOL_COMPLETE
,
244 STATE_TCP_CONNECT_COMPLETE
,
245 STATE_GENERATE_PROXY_AUTH_TOKEN
,
246 STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
,
247 STATE_WRITE_TUNNEL_HEADERS
,
248 STATE_WRITE_TUNNEL_HEADERS_COMPLETE
,
249 STATE_READ_TUNNEL_HEADERS
,
250 STATE_READ_TUNNEL_HEADERS_COMPLETE
,
252 STATE_SOCKS_CONNECT_COMPLETE
,
253 STATE_SECURE_PROXY_CONNECT
,
254 STATE_SECURE_PROXY_CONNECT_COMPLETE
,
255 STATE_SECURE_PROXY_HANDLE_CERT_ERROR
,
256 STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE
,
258 STATE_SSL_CONNECT_COMPLETE
,
259 STATE_SSL_HANDLE_CERT_ERROR
,
260 STATE_SSL_HANDLE_CERT_ERROR_COMPLETE
,
267 kDirectConnection
, // If using a direct connection
268 kTunnelProxy
, // If using a tunnel (CONNECT method as HTTPS)
269 kSOCKSProxy
, // If using a SOCKS proxy
272 // Use the same number as HttpNetworkTransaction::kMaxHeaderBufSize.
273 enum { kMaxTunnelResponseHeadersSize
= 32768 }; // 32 kilobytes.
275 // Used for WebSocketThrottleTest.
276 void set_addresses(const AddressList
& addresses
);
281 // Calls OnError and OnClose of delegate, and no more
282 // notifications will be sent to delegate.
283 void Finish(int result
);
285 int DidEstablishConnection();
286 int DidReceiveData(int result
);
287 // Given the number of bytes sent,
288 // - notifies the |delegate_| and |metrics_| of this event.
289 // - drains sent data from |current_write_buf_|.
290 // - if |current_write_buf_| has been fully sent, sets NULL to
291 // |current_write_buf_| to get ready for next write.
292 // and then, returns OK.
293 void DidSendData(int result
);
295 void OnIOCompleted(int result
);
296 void OnReadCompleted(int result
);
297 void OnWriteCompleted(int result
);
299 void DoLoop(int result
);
301 int DoBeforeConnect();
302 int DoBeforeConnectComplete(int result
);
303 int DoResolveProxy();
304 int DoResolveProxyComplete(int result
);
306 int DoResolveHostComplete(int result
);
307 int DoResolveProtocol(int result
);
308 int DoResolveProtocolComplete(int result
);
309 int DoTcpConnect(int result
);
310 int DoTcpConnectComplete(int result
);
311 int DoGenerateProxyAuthToken();
312 int DoGenerateProxyAuthTokenComplete(int result
);
313 int DoWriteTunnelHeaders();
314 int DoWriteTunnelHeadersComplete(int result
);
315 int DoReadTunnelHeaders();
316 int DoReadTunnelHeadersComplete(int result
);
317 int DoSOCKSConnect();
318 int DoSOCKSConnectComplete(int result
);
319 int DoSecureProxyConnect();
320 int DoSecureProxyConnectComplete(int result
);
321 int DoSecureProxyHandleCertError(int result
);
322 int DoSecureProxyHandleCertErrorComplete(int result
);
324 int DoSSLConnectComplete(int result
);
325 int DoSSLHandleCertError(int result
);
326 int DoSSLHandleCertErrorComplete(int result
);
327 int DoReadWrite(int result
);
329 GURL
ProxyAuthOrigin() const;
330 int HandleAuthChallenge(const HttpResponseHeaders
* headers
);
331 int HandleCertificateRequest(int result
, SSLConfig
* ssl_config
);
332 void DoAuthRequired();
333 void DoRestartWithAuth();
335 int HandleCertificateError(int result
);
336 int AllowCertErrorForReconnection(SSLConfig
* ssl_config
);
338 // Returns the sum of the size of buffers in |pending_write_bufs_|.
339 size_t GetTotalSizeOfPendingWriteBufs() const;
341 BoundNetLog net_log_
;
344 // The number of bytes allowed to be buffered in this object. If the size of
345 // buffered data which is
346 // current_write_buf_.BytesRemaining() +
347 // sum of the size of buffers in |pending_write_bufs_|
348 // exceeds this limit, SendData() fails.
349 int max_pending_send_allowed_
;
350 URLRequestContext
* context_
;
352 UserDataMap user_data_
;
355 ClientSocketFactory
* factory_
;
357 ProxyMode proxy_mode_
;
360 ProxyService::PacRequest
* pac_request_
;
361 ProxyInfo proxy_info_
;
363 scoped_refptr
<HttpAuthController
> proxy_auth_controller_
;
365 scoped_refptr
<RequestHeaders
> tunnel_request_headers_
;
366 size_t tunnel_request_headers_bytes_sent_
;
367 scoped_refptr
<ResponseHeaders
> tunnel_response_headers_
;
368 int tunnel_response_headers_capacity_
;
369 int tunnel_response_headers_len_
;
371 scoped_ptr
<SingleRequestHostResolver
> resolver_
;
372 AddressList addresses_
;
373 scoped_ptr
<ClientSocketHandle
> connection_
;
375 SSLConfig server_ssl_config_
;
376 SSLConfig proxy_ssl_config_
;
377 PrivacyMode privacy_mode_
;
379 CompletionCallback io_callback_
;
381 scoped_refptr
<IOBuffer
> read_buf_
;
384 // Buffer to hold data to pass to socket_.
385 scoped_refptr
<DrainableIOBuffer
> current_write_buf_
;
386 // True iff there's no error and this instance is waiting for completion of
387 // Write operation by socket_.
388 bool waiting_for_write_completion_
;
389 PendingDataQueue pending_write_bufs_
;
394 scoped_ptr
<SocketStreamMetrics
> metrics_
;
396 // Cookie store to use for this socket stream.
397 scoped_refptr
<CookieStore
> cookie_store_
;
399 DISALLOW_COPY_AND_ASSIGN(SocketStream
);
404 #endif // NET_SOCKET_STREAM_SOCKET_STREAM_H_