Files

598 lines
16 KiB
C++

/**
* @file include/ActivMiddleware/ActivBase/Http.h
*
* @brief Header file for various HTTP-related classes.
*/
#if (!defined ACTIV_BASE_HTTP_H)
#define ACTIV_BASE_HTTP_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/CxxYZ/unordered_map.h"
#include "ActivMiddleware/Misc/FunctionObjects.h"
#include "ActivMiddleware/Misc/Singleton.h"
#include "ActivMiddleware/Misc/StlHelper.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
// Forward references of some HTTP classes.
template<typename T>
class HttpValidatorBase;
class HttpRequest;
class HttpResponse;
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of HTTP verbs.
*/
#define ACTIV_HTTP_VERB_LIST(d) \
d(HEAD) \
d(GET) \
d(POST) \
d(PUT) \
d(DELETE) \
d(TRACE) \
d(OPTIONS) \
d(CONNECT)
#define ACTIV_MAKE_HTTP_VERB_ENUM_VALUE(v) HTTP_VERB_##v,
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Enumeration of HTTP verbs.
*/
enum HttpVerb
{
ACTIV_HTTP_VERB_LIST(ACTIV_MAKE_HTTP_VERB_ENUM_VALUE)
NUMBER_OF_HTTP_VERBS,
HTTP_VERB_UNKNOWN = -1
};
#undef ACTIV_MAKE_HTTP_VERB_ENUM_VALUE
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Enumeration of HTTP status codes.
*/
enum HttpStatusCode
{
HTTP_STATUS_CODE_UNDEFINED = 0,
// Success codes.
HTTP_STATUS_CODE_OK = 200,
// Client error codes.
HTTP_STATUS_CODE_BAD_REQUEST = 400,
HTTP_STATUS_CODE_UNAUTHORIZED = 401,
HTTP_STATUS_CODE_NOT_FOUND = 404,
// Server error codes.
HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR = 500
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP helper singleton for verb mappings, etc.
*/
class HttpHelper : private Singleton<HttpHelper>
{
public:
/**
* @brief Get the HttpVerb from a string.
*
* @param str
*
* @return HttpVerb.
*/
const HttpVerb StringToHttpVerb(const String &str) const;
/**
* @brief Get the HttpVerb from a pointer and length.
*
* @param pStr
* @param length
*
* @return HttpVerb.
*/
const HttpVerb StringToHttpVerb(const char *pStr, const size_t length) const;
/**
* @brief Get a string representation of an HttpVerb.
*
* @param httpVerb
*
* @return String.
*/
const String &HttpVerbToString(const HttpVerb httpVerb) const;
/**
* @brief Singleton accessor.
*
* @return HttpHelper reference.
*/
ACTIV_BASE_API static HttpHelper &GetInstance();
/**
* @brief Get a standard http success (200) header for html content.
*
* @param bodyLength the length of the http response body.
*
* @return String.
*/
ACTIV_BASE_API static String GetStandardHtmlSuccessHttpHeader(const size_t bodyLength);
/**
* @brief Get a standard http not found (404) header.
*
* @param bodyLength the length of the http response body.
*
* @return String.
*/
ACTIV_BASE_API static String GetStandardNotFoundHttpHeader(const size_t bodyLength);
/**
* @brief Get a standard http internal server error (500) header.
*
* @param bodyLength the length of the http response body.
*
* @return String.
*/
ACTIV_BASE_API static String GetStandardInternalServerErrorHttpHeader(const size_t bodyLength);
private:
typedef std::vector<String> VerbNameList;
typedef CxxYZ::unordered_map<size_t, HttpVerb> VerbMap;
/**
* @brief Constructor.
*/
HttpHelper();
/**
* @brief Make list of verb strings.
*/
static const VerbNameList MakeVerbNameList();
/**
* @brief Make a map from verb-hash to string.
*/
static const VerbMap MakeVerbMap(const VerbNameList &verbNameList);
const VerbNameList m_verbNameList;
const VerbMap m_verbMap;
friend class Singleton<HttpHelper>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpVerb HttpHelper::StringToHttpVerb(const String &str) const
{
return StringToHttpVerb(str.c_str(), str.length());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpVerb HttpHelper::StringToHttpVerb(const char *pStr, const size_t length) const
{
const size_t hashValue = Boost::hash_range<const char *>(pStr, pStr + length);
const VerbMap::const_iterator iter = m_verbMap.find(hashValue);
if (ACTIV_LIKELY(iter != m_verbMap.end()))
return iter->second;
return HTTP_VERB_UNKNOWN;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpHelper::HttpVerbToString(const HttpVerb httpVerb) const
{
if (ACTIV_LIKELY(httpVerb >= static_cast<HttpVerb>(0)) && ACTIV_LIKELY(httpVerb < NUMBER_OF_HTTP_VERBS))
return m_verbNameList[httpVerb];
return m_verbNameList[NUMBER_OF_HTTP_VERBS];
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP Exception.
*/
class HttpException : public Exception
{
public:
/**
* @brief Constructor.
*
* @param file the file which raised the exception.
* @param function the function which raised the exception.
* @param line the line number which raised the exception.
* @param errorCode the exception specific error code, in this case an HttpStatusCode value.
* @param reasonPhrase HTTP reason phrase.
*/
ACTIV_BASE_API HttpException(const char *file, const char *function, const uint_fast32_t line, const uint_fast32_t errorCode,
const String &reasonPhrase);
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP message.
*/
class HttpMessage
{
public:
typedef std::pair<String, String> HeaderPair; ///< Key,value header pair.
typedef std::vector<HeaderPair> HeaderList; ///< List of header key,value pairs.
/**
* @brief Default constructor.
*/
HttpMessage();
/**
* @brief Destructor.
*/
virtual ~HttpMessage();
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void Reset();
/**
* @brief Sort headers.
*
* Headers must be sorted before using GetHeaderValue().
*/
void SortHeaders();
/**
* @brief Get the value of a header field.
*
* @param keyName
*
* @return Reference to the key's value.
*
* @throw Exception if key is not found.
*/
const String &GetHeaderValue(const String &keyName) const;
/**
* @brief Get an iterator to the the first header.
*
* @return Iterator.
*/
const HeaderList::const_iterator begin() const;
/**
* @brief Get an iterator to past the the last header.
*
* @return Iterator.
*/
const HeaderList::const_iterator end() const;
/**
* @brief Get the HTTP version string.
*
* @return String reference.
*/
const String &GetHttpVersion() const;
protected:
/**
* @brief Callback invoked by HttpValidator on receipt of HTTP body.
*
* @param statusCode STATUS_CODE_SUCCESS if message type can have no body, or if content-length is defined
* and all body has (now) been received. STATUS_CODE_PENDING if the message type can have a content-length, it is
* defined but we've not yet received the whole body. STATUS_CODE_UNDEFINED_LENGTH for messages that can have a body
* but there was no content-length field (body is everything until the underlying connection is closed).
* @param pBody
* @param bodyLength
*
* @retval STATUS_CODE_SUCCESS
* @retval ... cause immediate return from HttpValidator::ConsumeBytes() with this status code.
*/
ACTIV_BASE_API virtual const StatusCode OnBody(const StatusCode statusCode, const void * const pBody, const size_t bodyLength);
private:
typedef PairComparisonObject<HeaderPair, CaseInsensitiveLessThanStringComparisonObject, SelectFirst> Sorter;
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void InternalReset();
String m_httpVersion;
HeaderList m_headerList; ///< List of header fields.
friend class HttpValidatorBase<HttpRequest>;
friend class HttpValidatorBase<HttpResponse>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpMessage::HttpMessage()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpMessage::~HttpMessage()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpMessage::Reset()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpMessage::SortHeaders()
{
std::sort(m_headerList.begin(), m_headerList.end(), Sorter());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpMessage::GetHeaderValue(const String &keyName) const
{
const std::pair<HeaderList::const_iterator, HeaderList::const_iterator> res =
std::equal_range(m_headerList.begin(), m_headerList.end(), keyName, Sorter());
if (res.first != res.second)
return res.first->second;
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_FOUND);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpMessage::HeaderList::const_iterator HttpMessage::begin() const
{
return m_headerList.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpMessage::HeaderList::const_iterator HttpMessage::end() const
{
return m_headerList.end();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpMessage::GetHttpVersion() const
{
return m_httpVersion;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpMessage::InternalReset()
{
m_httpVersion.clear();
m_headerList.clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP request.
*/
class HttpRequest : public HttpMessage
{
public:
typedef HttpRequest Self; ///< This type.
/**
* @brief Default constructor.
*/
HttpRequest();
/**
* @brief Reset.
*
* Clears down fields in this class and base.
*/
void Reset();
/**
* @brief Get the HTTP verb for this request.
*
* @return HttpVerb.
*/
const HttpVerb GetHttpVerb() const;
/**
* @brief Get the URI.
*
* @return String reference.
*/
const String &GetUri() const;
/**
* @brief Get the URI.
*
* @return String reference.
*/
String &GetUri();
private:
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void InternalReset();
HttpVerb m_httpVerb;
String m_uri;
friend class HttpValidatorBase<HttpRequest>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpRequest::HttpRequest()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpRequest::Reset()
{
HttpMessage::Reset();
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpVerb HttpRequest::GetHttpVerb() const
{
return m_httpVerb;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpRequest::GetUri() const
{
return m_uri;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline String &HttpRequest::GetUri()
{
return m_uri;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpRequest::InternalReset()
{
m_httpVerb = HTTP_VERB_UNKNOWN;
m_uri.clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP response.
*/
class HttpResponse : public HttpMessage
{
public:
typedef HttpResponse Self; ///< This type.
/**
* @brief Default constructor.
*/
HttpResponse();
/**
* @brief Reset.
*
* Clears down fields in this class and base.
*/
void Reset();
/**
* @brief Get the HTTP response status code.
*
* @return Status code.
*/
const HttpStatusCode GetStatusCode() const;
/**
* @brief Get the HTTP reason reason phrase.
*
* @return String reference.
*/
const String &GetReasonPhrase() const;
private:
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void InternalReset();
HttpStatusCode m_httpStatusCode;
String m_reasonPhrase;
friend class HttpValidatorBase<HttpResponse>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpResponse::HttpResponse()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpResponse::Reset()
{
HttpMessage::Reset();
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpStatusCode HttpResponse::GetStatusCode() const
{
return m_httpStatusCode;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpResponse::GetReasonPhrase() const
{
return m_reasonPhrase;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpResponse::InternalReset()
{
m_httpStatusCode = HTTP_STATUS_CODE_UNDEFINED;
m_reasonPhrase.clear();
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_HTTP_H)