Home | History | Annotate | Download | only in fetch
      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.
      4 
      5 #ifndef NET_BASE_TOOLS_HTTP_LISTEN_SOCKET_H_
      6 #define NET_BASE_TOOLS_HTTP_LISTEN_SOCKET_H_
      7 
      8 #include "base/message_loop/message_loop.h"
      9 #include "net/socket/stream_listen_socket.h"
     10 #include "net/socket/tcp_listen_socket.h"
     11 
     12 class HttpServerRequestInfo;
     13 class HttpServerResponseInfo;
     14 
     15 // Implements a simple HTTP listen socket on top of the raw socket interface.
     16 class HttpListenSocket : public net::TCPListenSocket,
     17                          public net::StreamListenSocket::Delegate {
     18  public:
     19   class Delegate {
     20    public:
     21     virtual void OnRequest(HttpListenSocket* connection,
     22                            HttpServerRequestInfo* info) = 0;
     23 
     24    protected:
     25     virtual ~Delegate() {}
     26   };
     27 
     28   static scoped_refptr<HttpListenSocket> CreateAndListen(
     29       const std::string& ip, int port, HttpListenSocket::Delegate* delegate);
     30 
     31   // Send a server response.
     32   // TODO(mbelshe): make this capable of non-ascii data.
     33   void Respond(HttpServerResponseInfo* info, std::string& data);
     34 
     35   // StreamListenSocket::Delegate.
     36   virtual void DidAccept(net::StreamListenSocket* server,
     37                          net::StreamListenSocket* connection) OVERRIDE;
     38   virtual void DidRead(net::StreamListenSocket* connection,
     39                        const char* data, int len) OVERRIDE;
     40   virtual void DidClose(net::StreamListenSocket* sock) OVERRIDE;
     41 
     42  protected:
     43   // Overrides TCPListenSocket::Accept().
     44   virtual void Accept() OVERRIDE;
     45 
     46  private:
     47   friend class base::RefCountedThreadSafe<net::StreamListenSocket>;
     48 
     49   static const int kReadBufSize = 16 * 1024;
     50 
     51   // Must run in the IO thread.
     52   HttpListenSocket(SocketDescriptor s, HttpListenSocket::Delegate* del);
     53   virtual ~HttpListenSocket();
     54 
     55   // Expects the raw data to be stored in recv_data_. If parsing is successful,
     56   // will remove the data parsed from recv_data_, leaving only the unused
     57   // recv data.
     58   HttpServerRequestInfo* ParseHeaders();
     59 
     60   HttpListenSocket::Delegate* const delegate_;
     61   std::string recv_data_;
     62 
     63   DISALLOW_COPY_AND_ASSIGN(HttpListenSocket);
     64 };
     65 
     66 #endif // NET_BASE_TOOLS_HTTP_LISTEN_SOCKET_H_
     67