diff options
author | Mattes D <github@xoft.cz> | 2016-03-01 16:58:43 +0100 |
---|---|---|
committer | Mattes D <github@xoft.cz> | 2016-03-01 16:58:43 +0100 |
commit | 7cc8f8dd2213cade66633d196f579895385a869a (patch) | |
tree | 83219a6eaf87a2050c10662fb8caa5d1514a6af4 /src/HTTPServer | |
parent | Merge pull request #3057 from tonibm19/master (diff) | |
parent | HTTP: Fixed typos and bad leftovers. (diff) | |
download | cuberite-7cc8f8dd2213cade66633d196f579895385a869a.tar cuberite-7cc8f8dd2213cade66633d196f579895385a869a.tar.gz cuberite-7cc8f8dd2213cade66633d196f579895385a869a.tar.bz2 cuberite-7cc8f8dd2213cade66633d196f579895385a869a.tar.lz cuberite-7cc8f8dd2213cade66633d196f579895385a869a.tar.xz cuberite-7cc8f8dd2213cade66633d196f579895385a869a.tar.zst cuberite-7cc8f8dd2213cade66633d196f579895385a869a.zip |
Diffstat (limited to '')
-rw-r--r-- | src/HTTP/CMakeLists.txt (renamed from src/HTTPServer/CMakeLists.txt) | 14 | ||||
-rw-r--r-- | src/HTTP/EnvelopeParser.cpp (renamed from src/HTTPServer/EnvelopeParser.cpp) | 6 | ||||
-rw-r--r-- | src/HTTP/EnvelopeParser.h (renamed from src/HTTPServer/EnvelopeParser.h) | 0 | ||||
-rw-r--r-- | src/HTTP/HTTPFormParser.cpp (renamed from src/HTTPServer/HTTPFormParser.cpp) | 6 | ||||
-rw-r--r-- | src/HTTP/HTTPFormParser.h (renamed from src/HTTPServer/HTTPFormParser.h) | 8 | ||||
-rw-r--r-- | src/HTTP/HTTPMessage.h (renamed from src/HTTPServer/HTTPMessage.h) | 114 | ||||
-rw-r--r-- | src/HTTP/HTTPServer.cpp (renamed from src/HTTPServer/HTTPServer.cpp) | 115 | ||||
-rw-r--r-- | src/HTTP/HTTPServer.h (renamed from src/HTTPServer/HTTPServer.h) | 28 | ||||
-rw-r--r-- | src/HTTP/HTTPServerConnection.h (renamed from src/HTTPServer/HTTPConnection.h) | 64 | ||||
-rw-r--r-- | src/HTTP/MultipartParser.cpp (renamed from src/HTTPServer/MultipartParser.cpp) | 0 | ||||
-rw-r--r-- | src/HTTP/MultipartParser.h (renamed from src/HTTPServer/MultipartParser.h) | 0 | ||||
-rw-r--r-- | src/HTTP/NameValueParser.cpp (renamed from src/HTTPServer/NameValueParser.cpp) | 0 | ||||
-rw-r--r-- | src/HTTP/NameValueParser.h (renamed from src/HTTPServer/NameValueParser.h) | 0 | ||||
-rw-r--r-- | src/HTTP/SslHTTPServerConnection.cpp (renamed from src/HTTPServer/SslHTTPConnection.cpp) | 12 | ||||
-rw-r--r-- | src/HTTP/SslHTTPServerConnection.h (renamed from src/HTTPServer/SslHTTPConnection.h) | 16 | ||||
-rw-r--r-- | src/HTTP/UrlParser.cpp (renamed from src/HTTPServer/UrlParser.cpp) | 0 | ||||
-rw-r--r-- | src/HTTP/UrlParser.h (renamed from src/HTTPServer/UrlParser.h) | 0 | ||||
-rw-r--r-- | src/HTTPServer/HTTPConnection.cpp | 278 | ||||
-rw-r--r-- | src/HTTPServer/HTTPMessage.cpp | 290 |
19 files changed, 132 insertions, 819 deletions
diff --git a/src/HTTPServer/CMakeLists.txt b/src/HTTP/CMakeLists.txt index a08a1fcf8..acb3ac2cd 100644 --- a/src/HTTPServer/CMakeLists.txt +++ b/src/HTTP/CMakeLists.txt @@ -6,31 +6,35 @@ include_directories ("${PROJECT_SOURCE_DIR}/../") SET (SRCS EnvelopeParser.cpp - HTTPConnection.cpp HTTPFormParser.cpp HTTPMessage.cpp + HTTPMessageParser.cpp HTTPServer.cpp + HTTPServerConnection.cpp MultipartParser.cpp NameValueParser.cpp - SslHTTPConnection.cpp + SslHTTPServerConnection.cpp + TransferEncodingParser.cpp UrlParser.cpp ) SET (HDRS EnvelopeParser.h - HTTPConnection.h HTTPFormParser.h HTTPMessage.h + HTTPMessageParser.h HTTPServer.h + HTTPServerConnection.h MultipartParser.h NameValueParser.h - SslHTTPConnection.h + SslHTTPServerConnection.h + TransferEncodingParser.h UrlParser.h ) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set_source_files_properties(HTTPServer.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors ") - set_source_files_properties(HTTPConnection.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum") + set_source_files_properties(HTTPServerConnection.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum") set_source_files_properties(HTTPMessage.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=tautological-compare") endif() diff --git a/src/HTTPServer/EnvelopeParser.cpp b/src/HTTP/EnvelopeParser.cpp index 407e9dcfc..1c49b643f 100644 --- a/src/HTTPServer/EnvelopeParser.cpp +++ b/src/HTTP/EnvelopeParser.cpp @@ -28,12 +28,12 @@ size_t cEnvelopeParser::Parse(const char * a_Data, size_t a_Size) } // Start searching 1 char from the end of the already received data, if available: - size_t SearchStart = m_IncomingData.size(); - SearchStart = (SearchStart > 1) ? SearchStart - 1 : 0; + auto searchStart = m_IncomingData.size(); + searchStart = (searchStart > 1) ? searchStart - 1 : 0; m_IncomingData.append(a_Data, a_Size); - size_t idxCRLF = m_IncomingData.find("\r\n", SearchStart); + size_t idxCRLF = m_IncomingData.find("\r\n", searchStart); if (idxCRLF == AString::npos) { // Not a complete line yet, all input consumed: diff --git a/src/HTTPServer/EnvelopeParser.h b/src/HTTP/EnvelopeParser.h index 2fa930539..2fa930539 100644 --- a/src/HTTPServer/EnvelopeParser.h +++ b/src/HTTP/EnvelopeParser.h diff --git a/src/HTTPServer/HTTPFormParser.cpp b/src/HTTP/HTTPFormParser.cpp index 497f84033..ea5da3c18 100644 --- a/src/HTTPServer/HTTPFormParser.cpp +++ b/src/HTTP/HTTPFormParser.cpp @@ -13,7 +13,7 @@ -cHTTPFormParser::cHTTPFormParser(cHTTPRequest & a_Request, cCallbacks & a_Callbacks) : +cHTTPFormParser::cHTTPFormParser(const cHTTPIncomingRequest & a_Request, cCallbacks & a_Callbacks) : m_Callbacks(a_Callbacks), m_IsValid(true), m_IsCurrentPartFile(false), @@ -121,7 +121,7 @@ bool cHTTPFormParser::Finish(void) -bool cHTTPFormParser::HasFormData(const cHTTPRequest & a_Request) +bool cHTTPFormParser::HasFormData(const cHTTPIncomingRequest & a_Request) { const AString & ContentType = a_Request.GetContentType(); return ( @@ -138,7 +138,7 @@ bool cHTTPFormParser::HasFormData(const cHTTPRequest & a_Request) -void cHTTPFormParser::BeginMultipart(const cHTTPRequest & a_Request) +void cHTTPFormParser::BeginMultipart(const cHTTPIncomingRequest & a_Request) { ASSERT(m_MultipartParser.get() == nullptr); m_MultipartParser.reset(new cMultipartParser(a_Request.GetContentType(), *this)); diff --git a/src/HTTPServer/HTTPFormParser.h b/src/HTTP/HTTPFormParser.h index f6cbe047f..6bf3e7d78 100644 --- a/src/HTTPServer/HTTPFormParser.h +++ b/src/HTTP/HTTPFormParser.h @@ -15,7 +15,7 @@ // fwd: -class cHTTPRequest; +class cHTTPIncomingRequest; @@ -51,7 +51,7 @@ public: /** Creates a parser that is tied to a request and notifies of various events using a callback mechanism */ - cHTTPFormParser(cHTTPRequest & a_Request, cCallbacks & a_Callbacks); + cHTTPFormParser(const cHTTPIncomingRequest & a_Request, cCallbacks & a_Callbacks); /** Creates a parser with the specified content type that reads data from a string */ cHTTPFormParser(eKind a_Kind, const char * a_Data, size_t a_Size, cCallbacks & a_Callbacks); @@ -64,7 +64,7 @@ public: bool Finish(void); /** Returns true if the headers suggest the request has form data parseable by this class */ - static bool HasFormData(const cHTTPRequest & a_Request); + static bool HasFormData(const cHTTPIncomingRequest & a_Request); protected: @@ -97,7 +97,7 @@ protected: /** Sets up the object for parsing a fpkMultipart request */ - void BeginMultipart(const cHTTPRequest & a_Request); + void BeginMultipart(const cHTTPIncomingRequest & a_Request); /** Parses m_IncomingData as form-urlencoded data (fpkURL or fpkFormUrlEncoded kinds) */ void ParseFormUrlEncoded(void); diff --git a/src/HTTPServer/HTTPMessage.h b/src/HTTP/HTTPMessage.h index 72ecb67d1..9afcd5b97 100644 --- a/src/HTTPServer/HTTPMessage.h +++ b/src/HTTP/HTTPMessage.h @@ -36,7 +36,7 @@ public: virtual ~cHTTPMessage() {} /** Adds a header into the internal map of headers. Recognizes special headers: Content-Type and Content-Length */ - void AddHeader(const AString & a_Key, const AString & a_Value); + virtual void AddHeader(const AString & a_Key, const AString & a_Value); void SetContentType (const AString & a_ContentType) { m_ContentType = a_ContentType; } void SetContentLength(size_t a_ContentLength) { m_ContentLength = a_ContentLength; } @@ -49,7 +49,8 @@ protected: eKind m_Kind; - cNameValueMap m_Headers; + /** Map of headers, with their keys lowercased. */ + AStringMap m_Headers; /** Type of the content; parsed by AddHeader(), set directly by SetContentLength() */ AString m_ContentType; @@ -64,22 +65,42 @@ protected: -class cHTTPRequest : - public cHTTPMessage, - protected cEnvelopeParser::cCallbacks +/** Stores outgoing response headers and serializes them to an HTTP data stream. */ +class cHTTPOutgoingResponse : + public cHTTPMessage { typedef cHTTPMessage super; public: - cHTTPRequest(void); + cHTTPOutgoingResponse(void); + + /** Appends the response to the specified datastream - response line and headers. + The body will be sent later directly through cConnection::Send() */ + void AppendToData(AString & a_DataStream) const; +} ; + - /** Parses the request line and then headers from the received data. - Returns the number of bytes consumed or AString::npos number for error - */ - size_t ParseHeaders(const char * a_Data, size_t a_Size); - /** Returns true if the request did contain a Content-Length header */ - bool HasReceivedContentLength(void) const { return (m_ContentLength != AString::npos); } + + +/** Provides storage for an incoming HTTP request. */ +class cHTTPIncomingRequest: + public cHTTPMessage +{ + typedef cHTTPMessage Super; +public: + /** Base class for anything that can be used as the UserData for the request. */ + class cUserData + { + public: + // Force a virtual destructor in descendants: + virtual ~cUserData() {} + }; + typedef SharedPtr<cUserData> cUserDataPtr; + + + /** Creates a new instance of the class, containing the method and URL provided by the client. */ + cHTTPIncomingRequest(const AString & a_Method, const AString & a_URL); /** Returns the method used in the request */ const AString & GetMethod(void) const { return m_Method; } @@ -87,20 +108,10 @@ public: /** Returns the URL used in the request */ const AString & GetURL(void) const { return m_URL; } - /** Returns the URL used in the request, without any parameters */ - AString GetBareURL(void) const; - - /** Sets the UserData pointer that is stored within this request. - The request doesn't touch this data (doesn't delete it)! */ - void SetUserData(void * a_UserData) { m_UserData = a_UserData; } - - /** Retrieves the UserData pointer that has been stored within this request. */ - void * GetUserData(void) const { return m_UserData; } + /** Returns the path part of the URL. */ + AString GetURLPath(void) const; - /** Returns true if more data is expected for the request headers */ - bool IsInHeaders(void) const { return m_EnvelopeParser.IsInHeaders(); } - - /** Returns true if the request did present auth data that was understood by the parser */ + /** Returns true if the request has had the Auth header present. */ bool HasAuth(void) const { return m_HasAuth; } /** Returns the username that the request presented. Only valid if HasAuth() is true */ @@ -111,15 +122,17 @@ public: bool DoesAllowKeepAlive(void) const { return m_AllowKeepAlive; } -protected: - /** Parser for the envelope data */ - cEnvelopeParser m_EnvelopeParser; + /** Attaches any kind of data to this request, to be later retrieved by GetUserData(). */ + void SetUserData(cUserDataPtr a_UserData) { m_UserData = a_UserData; } - /** True if the data received so far is parsed successfully. When false, all further parsing is skipped */ - bool m_IsValid; + /** Returns the data attached to this request by the class client. */ + cUserDataPtr GetUserData(void) { return m_UserData; } - /** Bufferred incoming data, while parsing for the request line */ - AString m_IncomingHeaderData; + /** Adds the specified header into the internal list of headers. + Overrides the parent to add recognizing additional headers: auth and keepalive. */ + virtual void AddHeader(const AString & a_Key, const AString & a_Value) override; + +protected: /** Method of the request (GET / PUT / POST / ...) */ AString m_Method; @@ -127,9 +140,6 @@ protected: /** Full URL of the request */ AString m_URL; - /** Data that the HTTPServer callbacks are allowed to store. */ - void * m_UserData; - /** Set to true if the request contains auth data that was understood by the parser */ bool m_HasAuth; @@ -143,34 +153,6 @@ protected: If false, the server will close the connection once the request is finished */ bool m_AllowKeepAlive; - - /** Parses the incoming data for the first line (RequestLine) - Returns the number of bytes consumed, or AString::npos for an error - */ - size_t ParseRequestLine(const char * a_Data, size_t a_Size); - - // cEnvelopeParser::cCallbacks overrides: - virtual void OnHeaderLine(const AString & a_Key, const AString & a_Value) override; -} ; - - - - - -class cHTTPResponse : - public cHTTPMessage -{ - typedef cHTTPMessage super; - -public: - cHTTPResponse(void); - - /** Appends the response to the specified datastream - response line and headers. - The body will be sent later directly through cConnection::Send() - */ - void AppendToData(AString & a_DataStream) const; -} ; - - - - + /** Any data attached to the request by the class client. */ + cUserDataPtr m_UserData; +}; diff --git a/src/HTTPServer/HTTPServer.cpp b/src/HTTP/HTTPServer.cpp index 814a87fe4..5a5bee045 100644 --- a/src/HTTPServer/HTTPServer.cpp +++ b/src/HTTP/HTTPServer.cpp @@ -5,10 +5,10 @@ #include "Globals.h" #include "HTTPServer.h" -#include "HTTPMessage.h" -#include "HTTPConnection.h" +#include "HTTPMessageParser.h" +#include "HTTPServerConnection.h" #include "HTTPFormParser.h" -#include "SslHTTPConnection.h" +#include "SslHTTPServerConnection.h" @@ -24,102 +24,6 @@ -class cDebugCallbacks : - public cHTTPServer::cCallbacks, - protected cHTTPFormParser::cCallbacks -{ - virtual void OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override - { - UNUSED(a_Connection); - - if (cHTTPFormParser::HasFormData(a_Request)) - { - a_Request.SetUserData(new cHTTPFormParser(a_Request, *this)); - } - } - - - virtual void OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size) override - { - UNUSED(a_Connection); - - cHTTPFormParser * FormParser = reinterpret_cast<cHTTPFormParser *>(a_Request.GetUserData()); - if (FormParser != nullptr) - { - FormParser->Parse(a_Data, a_Size); - } - } - - - virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override - { - cHTTPFormParser * FormParser = reinterpret_cast<cHTTPFormParser *>(a_Request.GetUserData()); - if (FormParser != nullptr) - { - if (FormParser->Finish()) - { - cHTTPResponse Resp; - Resp.SetContentType("text/html"); - a_Connection.Send(Resp); - a_Connection.Send("<html><body><table border=1 cellspacing=0><tr><th>Name</th><th>Value</th></tr>\r\n"); - for (cHTTPFormParser::iterator itr = FormParser->begin(), end = FormParser->end(); itr != end; ++itr) - { - a_Connection.Send(Printf("<tr><td valign=\"top\"><pre>%s</pre></td><td valign=\"top\"><pre>%s</pre></td></tr>\r\n", itr->first.c_str(), itr->second.c_str())); - } // for itr - FormParser[] - a_Connection.Send("</table></body></html>"); - return; - } - - // Parsing failed: - cHTTPResponse Resp; - Resp.SetContentType("text/plain"); - a_Connection.Send(Resp); - a_Connection.Send("Form parsing failed"); - return; - } - - // Test the auth failure and success: - if (a_Request.GetURL() == "/auth") - { - if (!a_Request.HasAuth() || (a_Request.GetAuthUsername() != "a") || (a_Request.GetAuthPassword() != "b")) - { - a_Connection.SendNeedAuth("Cuberite WebAdmin"); - return; - } - } - - cHTTPResponse Resp; - Resp.SetContentType("text/plain"); - a_Connection.Send(Resp); - a_Connection.Send("Hello, world"); - } - - - virtual void OnFileStart(cHTTPFormParser & a_Parser, const AString & a_FileName) override - { - // TODO - } - - - virtual void OnFileData(cHTTPFormParser & a_Parser, const char * a_Data, size_t a_Size) override - { - // TODO - } - - - virtual void OnFileEnd(cHTTPFormParser & a_Parser) override - { - // TODO - } - -}; - -static cDebugCallbacks g_DebugCallbacks; - - - - - //////////////////////////////////////////////////////////////////////////////// // cHTTPServerListenCallbacks: @@ -268,11 +172,11 @@ cTCPLink::cCallbacksPtr cHTTPServer::OnIncomingConnection(const AString & a_Remo if (m_Cert.get() != nullptr) { - return std::make_shared<cSslHTTPConnection>(*this, m_Cert, m_CertPrivKey); + return std::make_shared<cSslHTTPServerConnection>(*this, m_Cert, m_CertPrivKey); } else { - return std::make_shared<cHTTPConnection>(*this); + return std::make_shared<cHTTPServerConnection>(*this); } } @@ -280,7 +184,7 @@ cTCPLink::cCallbacksPtr cHTTPServer::OnIncomingConnection(const AString & a_Remo -void cHTTPServer::NewRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) +void cHTTPServer::NewRequest(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request) { m_Callbacks->OnRequestBegun(a_Connection, a_Request); } @@ -289,19 +193,18 @@ void cHTTPServer::NewRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Re -void cHTTPServer::RequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size) +void cHTTPServer::RequestBody(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request, const void * a_Data, size_t a_Size) { - m_Callbacks->OnRequestBody(a_Connection, a_Request, a_Data, a_Size); + m_Callbacks->OnRequestBody(a_Connection, a_Request, reinterpret_cast<const char *>(a_Data), a_Size); } -void cHTTPServer::RequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) +void cHTTPServer::RequestFinished(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request) { m_Callbacks->OnRequestFinished(a_Connection, a_Request); - a_Connection.AwaitNextRequest(); } diff --git a/src/HTTPServer/HTTPServer.h b/src/HTTP/HTTPServer.h index 2a094b413..1de0a6ce9 100644 --- a/src/HTTPServer/HTTPServer.h +++ b/src/HTTP/HTTPServer.h @@ -21,11 +21,9 @@ // fwd: class cHTTPMessage; -class cHTTPRequest; -class cHTTPResponse; -class cHTTPConnection; - -typedef std::vector<cHTTPConnection *> cHTTPConnections; +class cHTTPRequestParser; +class cHTTPIncomingRequest; +class cHTTPServerConnection; @@ -42,14 +40,14 @@ public: /** Called when a new request arrives over a connection and all its headers have been parsed. The request body needn't have arrived yet. */ - virtual void OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) = 0; + virtual void OnRequestBegun(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request) = 0; /** Called when another part of request body has arrived. May be called multiple times for a single request. */ - virtual void OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size) = 0; + virtual void OnRequestBody(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request, const char * a_Data, size_t a_Size) = 0; /** Called when the request body has been fully received in previous calls to OnRequestBody() */ - virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) = 0; + virtual void OnRequestFinished(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request) = 0; } ; cHTTPServer(void); @@ -65,8 +63,8 @@ public: void Stop(void); protected: - friend class cHTTPConnection; - friend class cSslHTTPConnection; + friend class cHTTPServerConnection; + friend class cSslHTTPServerConnection; friend class cHTTPServerListenCallbacks; /** The cNetwork API handle for the listening socket. */ @@ -86,15 +84,15 @@ protected: Returns the connection instance to be used as the cTCPLink callbacks. */ cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort); - /** Called by cHTTPConnection when it finishes parsing the request header */ - void NewRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request); + /** Called by cHTTPServerConnection when it finishes parsing the request header */ + void NewRequest(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request); /** Called by cHTTPConenction when it receives more data for the request body. May be called multiple times for a single request. */ - void RequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size); + void RequestBody(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request, const void * a_Data, size_t a_Size); - /** Called by cHTTPConnection when it detects that the request has finished (all of its body has been received) */ - void RequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request); + /** Called by cHTTPServerConnection when it detects that the request has finished (all of its body has been received) */ + void RequestFinished(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request); } ; diff --git a/src/HTTPServer/HTTPConnection.h b/src/HTTP/HTTPServerConnection.h index 414075411..4390471d0 100644 --- a/src/HTTPServer/HTTPConnection.h +++ b/src/HTTP/HTTPServerConnection.h @@ -10,6 +10,7 @@ #pragma once #include "../OSSupport/Network.h" +#include "HTTPMessageParser.h" @@ -17,39 +18,34 @@ // fwd: class cHTTPServer; -class cHTTPResponse; -class cHTTPRequest; +class cHTTPOutgoingResponse; +class cHTTPIncomingRequest; - -class cHTTPConnection : - public cTCPLink::cCallbacks +class cHTTPServerConnection : + public cTCPLink::cCallbacks, + public cHTTPMessageParser::cCallbacks { public: + /** Creates a new instance, connected to the specified HTTP server instance */ + cHTTPServerConnection(cHTTPServer & a_HTTPServer); - enum eState - { - wcsRecvHeaders, ///< Receiving request headers (m_CurrentRequest is created if nullptr) - wcsRecvBody, ///< Receiving request body (m_CurrentRequest is valid) - wcsRecvIdle, ///< Has received the entire body, waiting to send the response (m_CurrentRequest == nullptr) - wcsSendingResp, ///< Sending response body (m_CurrentRequest == nullptr) - wcsInvalid, ///< The request was malformed, the connection is closing - } ; - - cHTTPConnection(cHTTPServer & a_HTTPServer); - virtual ~cHTTPConnection(); + // Force a virtual destructor in all descendants + virtual ~cHTTPServerConnection(); /** Sends HTTP status code together with a_Reason (used for HTTP errors). - Sends the a_Reason as the body as well, so that browsers display it. */ + Sends the a_Reason as the body as well, so that browsers display it. + Clears the current request (since it's finished by this call). */ void SendStatusAndReason(int a_StatusCode, const AString & a_Reason); - /** Sends the "401 unauthorized" reply together with instructions on authorizing, using the specified realm */ + /** Sends the "401 unauthorized" reply together with instructions on authorizing, using the specified realm. + Clears the current request (since it's finished by this call). */ void SendNeedAuth(const AString & a_Realm); /** Sends the headers contained in a_Response */ - void Send(const cHTTPResponse & a_Response); + void Send(const cHTTPOutgoingResponse & a_Response); /** Sends the data as the response (may be called multiple times) */ void Send(const void * a_Data, size_t a_Size); @@ -57,13 +53,10 @@ public: /** Sends the data as the response (may be called multiple times) */ void Send(const AString & a_Data) { Send(a_Data.data(), a_Data.size()); } - /** Indicates that the current response is finished, gets ready for receiving another request (HTTP 1.1 keepalive) */ + /** Indicates that the current response is finished, gets ready for receiving another request (HTTP 1.1 keepalive). + Clears the current request (since it's finished by this call). */ void FinishResponse(void); - /** Resets the internal connection state for a new request. - Depending on the state, this will send an "InternalServerError" status or a "ResponseEnd" */ - void AwaitNextRequest(void); - /** Terminates the connection; finishes any request being currently processed */ void Terminate(void); @@ -73,19 +66,12 @@ protected: /** The parent webserver that is to be notified of events on this connection */ cHTTPServer & m_HTTPServer; - /** All the incoming data until the entire request header is parsed */ - AString m_IncomingHeaderData; - - /** Status in which the request currently is */ - eState m_State; + /** The parser responsible for reading the requests. */ + cHTTPMessageParser m_Parser; /** The request being currently received Valid only between having parsed the headers and finishing receiving the body. */ - cHTTPRequest * m_CurrentRequest; - - /** Number of bytes that remain to read for the complete body of the message to be received. - Valid only in wcsRecvBody */ - size_t m_CurrentRequestBodyRemaining; + std::unique_ptr<cHTTPIncomingRequest> m_CurrentRequest; /** The network link attached to this connection. */ cTCPLinkPtr m_Link; @@ -104,6 +90,14 @@ protected: /** An error has occurred on the socket. */ virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override; + // cHTTPMessageParser::cCallbacks overrides: + virtual void OnError(const AString & a_ErrorDescription) override; + virtual void OnFirstLine(const AString & a_FirstLine) override; + virtual void OnHeaderLine(const AString & a_Key, const AString & a_Value) override; + virtual void OnHeadersFinished(void) override; + virtual void OnBodyData(const void * a_Data, size_t a_Size) override; + virtual void OnBodyFinished(void) override; + // Overridable: /** Called to send raw data over the link. Descendants may provide data transformations (SSL etc.) */ virtual void SendData(const void * a_Data, size_t a_Size); @@ -116,7 +110,7 @@ protected: } } ; -typedef std::vector<cHTTPConnection *> cHTTPConnections; +typedef std::vector<cHTTPServerConnection *> cHTTPServerConnections; diff --git a/src/HTTPServer/MultipartParser.cpp b/src/HTTP/MultipartParser.cpp index 09f4fd02a..09f4fd02a 100644 --- a/src/HTTPServer/MultipartParser.cpp +++ b/src/HTTP/MultipartParser.cpp diff --git a/src/HTTPServer/MultipartParser.h b/src/HTTP/MultipartParser.h index 4f20b2bed..4f20b2bed 100644 --- a/src/HTTPServer/MultipartParser.h +++ b/src/HTTP/MultipartParser.h diff --git a/src/HTTPServer/NameValueParser.cpp b/src/HTTP/NameValueParser.cpp index f759c4d21..f759c4d21 100644 --- a/src/HTTPServer/NameValueParser.cpp +++ b/src/HTTP/NameValueParser.cpp diff --git a/src/HTTPServer/NameValueParser.h b/src/HTTP/NameValueParser.h index e205079db..e205079db 100644 --- a/src/HTTPServer/NameValueParser.h +++ b/src/HTTP/NameValueParser.h diff --git a/src/HTTPServer/SslHTTPConnection.cpp b/src/HTTP/SslHTTPServerConnection.cpp index 1cbe02312..547e6de3a 100644 --- a/src/HTTPServer/SslHTTPConnection.cpp +++ b/src/HTTP/SslHTTPServerConnection.cpp @@ -1,17 +1,17 @@ // SslHTTPConnection.cpp -// Implements the cSslHTTPConnection class representing a HTTP connection made over a SSL link +// Implements the cSslHTTPServerConnection class representing a HTTP connection made over a SSL link #include "Globals.h" -#include "SslHTTPConnection.h" +#include "SslHTTPServerConnection.h" #include "HTTPServer.h" -cSslHTTPConnection::cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cCryptoKeyPtr & a_PrivateKey) : +cSslHTTPServerConnection::cSslHTTPServerConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cCryptoKeyPtr & a_PrivateKey) : super(a_HTTPServer), m_Ssl(64000), m_Cert(a_Cert), @@ -25,7 +25,7 @@ cSslHTTPConnection::cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509Ce -cSslHTTPConnection::~cSslHTTPConnection() +cSslHTTPServerConnection::~cSslHTTPServerConnection() { m_Ssl.NotifyClose(); } @@ -34,7 +34,7 @@ cSslHTTPConnection::~cSslHTTPConnection() -void cSslHTTPConnection::OnReceivedData(const char * a_Data, size_t a_Size) +void cSslHTTPServerConnection::OnReceivedData(const char * a_Data, size_t a_Size) { // Process the received data: const char * Data = a_Data; @@ -77,7 +77,7 @@ void cSslHTTPConnection::OnReceivedData(const char * a_Data, size_t a_Size) -void cSslHTTPConnection::SendData(const void * a_Data, size_t a_Size) +void cSslHTTPServerConnection::SendData(const void * a_Data, size_t a_Size) { const char * OutgoingData = reinterpret_cast<const char *>(a_Data); size_t pos = 0; diff --git a/src/HTTPServer/SslHTTPConnection.h b/src/HTTP/SslHTTPServerConnection.h index b35bd8ba0..eceb80fb7 100644 --- a/src/HTTPServer/SslHTTPConnection.h +++ b/src/HTTP/SslHTTPServerConnection.h @@ -1,7 +1,7 @@ -// SslHTTPConnection.h +// SslHTTPServerConnection.h -// Declared the cSslHTTPConnection class representing a HTTP connection made over a SSL link +// Declares the cSslHTTPServerConnection class representing a HTTP connection made over an SSL link @@ -9,24 +9,24 @@ #pragma once -#include "HTTPConnection.h" +#include "HTTPServerConnection.h" #include "PolarSSL++/BufferedSslContext.h" -class cSslHTTPConnection : - public cHTTPConnection +class cSslHTTPServerConnection : + public cHTTPServerConnection { - typedef cHTTPConnection super; + typedef cHTTPServerConnection super; public: /** Creates a new connection on the specified server. Sends the specified cert as the server certificate, uses the private key for decryption. */ - cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cCryptoKeyPtr & a_PrivateKey); + cSslHTTPServerConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cCryptoKeyPtr & a_PrivateKey); - ~cSslHTTPConnection(); + ~cSslHTTPServerConnection(); protected: cBufferedSslContext m_Ssl; diff --git a/src/HTTPServer/UrlParser.cpp b/src/HTTP/UrlParser.cpp index 05db3e413..05db3e413 100644 --- a/src/HTTPServer/UrlParser.cpp +++ b/src/HTTP/UrlParser.cpp diff --git a/src/HTTPServer/UrlParser.h b/src/HTTP/UrlParser.h index 15a63e05d..15a63e05d 100644 --- a/src/HTTPServer/UrlParser.h +++ b/src/HTTP/UrlParser.h diff --git a/src/HTTPServer/HTTPConnection.cpp b/src/HTTPServer/HTTPConnection.cpp deleted file mode 100644 index 0db154139..000000000 --- a/src/HTTPServer/HTTPConnection.cpp +++ /dev/null @@ -1,278 +0,0 @@ - -// HTTPConnection.cpp - -// Implements the cHTTPConnection class representing a single persistent connection in the HTTP server. - -#include "Globals.h" -#include "HTTPConnection.h" -#include "HTTPMessage.h" -#include "HTTPServer.h" - - - - - -cHTTPConnection::cHTTPConnection(cHTTPServer & a_HTTPServer) : - m_HTTPServer(a_HTTPServer), - m_State(wcsRecvHeaders), - m_CurrentRequest(nullptr), - m_CurrentRequestBodyRemaining(0) -{ - // LOGD("HTTP: New connection at %p", this); -} - - - - - -cHTTPConnection::~cHTTPConnection() -{ - // LOGD("HTTP: Connection deleting: %p", this); - delete m_CurrentRequest; - m_CurrentRequest = nullptr; -} - - - - - -void cHTTPConnection::SendStatusAndReason(int a_StatusCode, const AString & a_Response) -{ - SendData(Printf("HTTP/1.1 %d %s\r\n", a_StatusCode, a_Response.c_str())); - SendData(Printf("Content-Length: %u\r\n\r\n", static_cast<unsigned>(a_Response.size()))); - SendData(a_Response.data(), a_Response.size()); - m_State = wcsRecvHeaders; -} - - - - - -void cHTTPConnection::SendNeedAuth(const AString & a_Realm) -{ - SendData(Printf("HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"%s\"\r\nContent-Length: 0\r\n\r\n", a_Realm.c_str())); - m_State = wcsRecvHeaders; -} - - - - - -void cHTTPConnection::Send(const cHTTPResponse & a_Response) -{ - ASSERT(m_State == wcsRecvIdle); - AString toSend; - a_Response.AppendToData(toSend); - m_State = wcsSendingResp; - SendData(toSend); -} - - - - - -void cHTTPConnection::Send(const void * a_Data, size_t a_Size) -{ - ASSERT(m_State == wcsSendingResp); - // We're sending in Chunked transfer encoding - SendData(Printf(SIZE_T_FMT_HEX "\r\n", a_Size)); - SendData(a_Data, a_Size); - SendData("\r\n"); -} - - - - - -void cHTTPConnection::FinishResponse(void) -{ - ASSERT(m_State == wcsSendingResp); - SendData("0\r\n\r\n"); - m_State = wcsRecvHeaders; -} - - - - - -void cHTTPConnection::AwaitNextRequest(void) -{ - switch (m_State) - { - case wcsRecvHeaders: - { - // Nothing has been received yet, or a special response was given (SendStatusAndReason() or SendNeedAuth()) - break; - } - - case wcsRecvIdle: - { - // The client is waiting for a response, send an "Internal server error": - SendData("HTTP/1.1 500 Internal Server Error\r\n\r\n"); - m_State = wcsRecvHeaders; - break; - } - - case wcsSendingResp: - { - // The response headers have been sent, we need to terminate the response body: - SendData("0\r\n\r\n"); - m_State = wcsRecvHeaders; - break; - } - - default: - { - ASSERT(!"Unhandled state recovery"); - break; - } - } -} - - - - - -void cHTTPConnection::Terminate(void) -{ - if (m_CurrentRequest != nullptr) - { - m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); - } - m_Link.reset(); -} - - - - - -void cHTTPConnection::OnLinkCreated(cTCPLinkPtr a_Link) -{ - ASSERT(m_Link == nullptr); - m_Link = a_Link; -} - - - - - -void cHTTPConnection::OnReceivedData(const char * a_Data, size_t a_Size) -{ - ASSERT(m_Link != nullptr); - - switch (m_State) - { - case wcsRecvHeaders: - { - if (m_CurrentRequest == nullptr) - { - m_CurrentRequest = new cHTTPRequest; - } - - size_t BytesConsumed = m_CurrentRequest->ParseHeaders(a_Data, a_Size); - if (BytesConsumed == AString::npos) - { - delete m_CurrentRequest; - m_CurrentRequest = nullptr; - m_State = wcsInvalid; - m_Link->Close(); - m_Link.reset(); - return; - } - if (m_CurrentRequest->IsInHeaders()) - { - // The request headers are not yet complete - return; - } - - // The request has finished parsing its headers successfully, notify of it: - m_State = wcsRecvBody; - m_HTTPServer.NewRequest(*this, *m_CurrentRequest); - m_CurrentRequestBodyRemaining = m_CurrentRequest->GetContentLength(); - if (m_CurrentRequestBodyRemaining == AString::npos) - { - // The body length was not specified in the request, assume zero - m_CurrentRequestBodyRemaining = 0; - } - - // Process the rest of the incoming data into the request body: - if (a_Size > BytesConsumed) - { - cHTTPConnection::OnReceivedData(a_Data + BytesConsumed, a_Size - BytesConsumed); - return; - } - else - { - cHTTPConnection::OnReceivedData("", 0); // If the request has zero body length, let it be processed right-away - return; - } - } - - case wcsRecvBody: - { - ASSERT(m_CurrentRequest != nullptr); - if (m_CurrentRequestBodyRemaining > 0) - { - size_t BytesToConsume = std::min(m_CurrentRequestBodyRemaining, static_cast<size_t>(a_Size)); - m_HTTPServer.RequestBody(*this, *m_CurrentRequest, a_Data, BytesToConsume); - m_CurrentRequestBodyRemaining -= BytesToConsume; - } - if (m_CurrentRequestBodyRemaining == 0) - { - m_State = wcsRecvIdle; - m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); - if (!m_CurrentRequest->DoesAllowKeepAlive()) - { - m_State = wcsInvalid; - m_Link->Close(); - m_Link.reset(); - return; - } - delete m_CurrentRequest; - m_CurrentRequest = nullptr; - } - break; - } - - default: - { - // TODO: Should we be receiving data in this state? - break; - } - } -} - - - - - -void cHTTPConnection::OnRemoteClosed(void) -{ - if (m_CurrentRequest != nullptr) - { - m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); - } - m_Link.reset(); -} - - - - - - -void cHTTPConnection::OnError(int a_ErrorCode, const AString & a_ErrorMsg) -{ - OnRemoteClosed(); -} - - - - -void cHTTPConnection::SendData(const void * a_Data, size_t a_Size) -{ - m_Link->Send(a_Data, a_Size); -} - - - - diff --git a/src/HTTPServer/HTTPMessage.cpp b/src/HTTPServer/HTTPMessage.cpp deleted file mode 100644 index 360145a9a..000000000 --- a/src/HTTPServer/HTTPMessage.cpp +++ /dev/null @@ -1,290 +0,0 @@ - -// HTTPMessage.cpp - -// Declares the cHTTPMessage class representing the common ancestor for HTTP request and response classes - -#include "Globals.h" -#include "HTTPMessage.h" - - - - - -// Disable MSVC warnings: -#if defined(_MSC_VER) - #pragma warning(push) - #pragma warning(disable:4355) // 'this' : used in base member initializer list -#endif - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cHTTPMessage: - -cHTTPMessage::cHTTPMessage(eKind a_Kind) : - m_Kind(a_Kind), - m_ContentLength(AString::npos) -{ -} - - - - - -void cHTTPMessage::AddHeader(const AString & a_Key, const AString & a_Value) -{ - AString Key = StrToLower(a_Key); - cNameValueMap::iterator itr = m_Headers.find(Key); - if (itr == m_Headers.end()) - { - m_Headers[Key] = a_Value; - } - else - { - // The header-field key is specified multiple times, combine into comma-separated list (RFC 2616 @ 4.2) - itr->second.append(", "); - itr->second.append(a_Value); - } - - // Special processing for well-known headers: - if (Key == "content-type") - { - m_ContentType = m_Headers[Key]; - } - else if (Key == "content-length") - { - if (!StringToInteger(m_Headers[Key], m_ContentLength)) - { - m_ContentLength = 0; - } - } -} - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cHTTPRequest: - -cHTTPRequest::cHTTPRequest(void) : - super(mkRequest), - m_EnvelopeParser(*this), - m_IsValid(true), - m_UserData(nullptr), - m_HasAuth(false), - m_AllowKeepAlive(false) -{ -} - - - - - -size_t cHTTPRequest::ParseHeaders(const char * a_Data, size_t a_Size) -{ - if (!m_IsValid) - { - return AString::npos; - } - - if (m_Method.empty()) - { - // The first line hasn't been processed yet - size_t res = ParseRequestLine(a_Data, a_Size); - ASSERT((res == AString::npos) || (res <= a_Size)); - if ((res == AString::npos) || (res == a_Size)) - { - return res; - } - size_t res2 = m_EnvelopeParser.Parse(a_Data + res, a_Size - res); - ASSERT((res2 == AString::npos) || (res2 <= a_Size - res)); - if (res2 == AString::npos) - { - m_IsValid = false; - return res2; - } - return res2 + res; - } - - if (m_EnvelopeParser.IsInHeaders()) - { - size_t res = m_EnvelopeParser.Parse(a_Data, a_Size); - ASSERT((res == AString::npos) || (res <= a_Size)); - if (res == AString::npos) - { - m_IsValid = false; - } - return res; - } - return 0; -} - - - - - -AString cHTTPRequest::GetBareURL(void) const -{ - size_t idxQM = m_URL.find('?'); - if (idxQM != AString::npos) - { - return m_URL.substr(0, idxQM); - } - else - { - return m_URL; - } -} - - - - - -size_t cHTTPRequest::ParseRequestLine(const char * a_Data, size_t a_Size) -{ - auto inBufferSoFar = m_IncomingHeaderData.size(); - m_IncomingHeaderData.append(a_Data, a_Size); - auto IdxEnd = m_IncomingHeaderData.size(); - - // Ignore the initial CRLFs (HTTP spec's "should") - size_t LineStart = 0; - while ( - (LineStart < IdxEnd) && - ( - (m_IncomingHeaderData[LineStart] == '\r') || - (m_IncomingHeaderData[LineStart] == '\n') - ) - ) - { - LineStart++; - } - if (LineStart >= IdxEnd) - { - m_IsValid = false; - return AString::npos; - } - - int NumSpaces = 0; - size_t MethodEnd = 0; - size_t URLEnd = 0; - for (size_t i = LineStart; i < IdxEnd; i++) - { - switch (m_IncomingHeaderData[i]) - { - case ' ': - { - switch (NumSpaces) - { - case 0: - { - MethodEnd = i; - break; - } - case 1: - { - URLEnd = i; - break; - } - default: - { - // Too many spaces in the request - m_IsValid = false; - return AString::npos; - } - } - NumSpaces += 1; - break; - } - case '\n': - { - if ((i == 0) || (m_IncomingHeaderData[i - 1] != '\r') || (NumSpaces != 2) || (i < URLEnd + 7)) - { - // LF too early, without a CR, without two preceeding spaces or too soon after the second space - m_IsValid = false; - return AString::npos; - } - // Check that there's HTTP / version at the end - if (strncmp(m_IncomingHeaderData.c_str() + URLEnd + 1, "HTTP/1.", 7) != 0) - { - m_IsValid = false; - return AString::npos; - } - m_Method = m_IncomingHeaderData.substr(LineStart, MethodEnd - LineStart); - m_URL = m_IncomingHeaderData.substr(MethodEnd + 1, URLEnd - MethodEnd - 1); - return i + 1 - inBufferSoFar; - } - } // switch (m_IncomingHeaderData[i]) - } // for i - m_IncomingHeaderData[] - - // CRLF hasn't been encountered yet, consider all data consumed - return a_Size; -} - - - - - -void cHTTPRequest::OnHeaderLine(const AString & a_Key, const AString & a_Value) -{ - if ( - (NoCaseCompare(a_Key, "Authorization") == 0) && - (strncmp(a_Value.c_str(), "Basic ", 6) == 0) - ) - { - AString UserPass = Base64Decode(a_Value.substr(6)); - size_t idxCol = UserPass.find(':'); - if (idxCol != AString::npos) - { - m_AuthUsername = UserPass.substr(0, idxCol); - m_AuthPassword = UserPass.substr(idxCol + 1); - m_HasAuth = true; - } - } - if ((a_Key == "Connection") && (NoCaseCompare(a_Value, "keep-alive") == 0)) - { - m_AllowKeepAlive = true; - } - AddHeader(a_Key, a_Value); -} - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cHTTPResponse: - -cHTTPResponse::cHTTPResponse(void) : - super(mkResponse) -{ -} - - - - - -void cHTTPResponse::AppendToData(AString & a_DataStream) const -{ - a_DataStream.append("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: "); - a_DataStream.append(m_ContentType); - a_DataStream.append("\r\n"); - for (cNameValueMap::const_iterator itr = m_Headers.begin(), end = m_Headers.end(); itr != end; ++itr) - { - if ((itr->first == "Content-Type") || (itr->first == "Content-Length")) - { - continue; - } - a_DataStream.append(itr->first); - a_DataStream.append(": "); - a_DataStream.append(itr->second); - a_DataStream.append("\r\n"); - } // for itr - m_Headers[] - a_DataStream.append("\r\n"); -} - - - - |