wshandshake.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Copyright (c) 2020-2021 Paul-Louis Ageneau
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. */
  8. #ifndef RTC_IMPL_WS_HANDSHAKE_H
  9. #define RTC_IMPL_WS_HANDSHAKE_H
  10. #include "common.hpp"
  11. #if RTC_ENABLE_WEBSOCKET
  12. #include <list>
  13. #include <map>
  14. #include <stdexcept>
  15. #include <vector>
  16. namespace rtc::impl {
  17. class WsHandshake final {
  18. public:
  19. WsHandshake();
  20. WsHandshake(string host, string path = "/", std::vector<string> protocols = {});
  21. string host() const;
  22. string path() const;
  23. std::vector<string> protocols() const;
  24. string generateHttpRequest();
  25. string generateHttpResponse();
  26. string generateHttpError(int responseCode = 400);
  27. class Error : public std::runtime_error {
  28. public:
  29. explicit Error(const string &w);
  30. };
  31. class RequestError : public Error {
  32. public:
  33. explicit RequestError(const string &w, int responseCode = 400);
  34. int responseCode() const;
  35. private:
  36. const int mResponseCode;
  37. };
  38. size_t parseHttpRequest(const byte *buffer, size_t size);
  39. size_t parseHttpResponse(const byte *buffer, size_t size);
  40. private:
  41. static string generateKey();
  42. static string computeAcceptKey(const string &key);
  43. static size_t parseHttpLines(const byte *buffer, size_t size, std::list<string> &lines);
  44. static std::multimap<string, string> parseHttpHeaders(const std::list<string> &lines);
  45. string mHost;
  46. string mPath;
  47. std::vector<string> mProtocols;
  48. string mKey;
  49. mutable std::mutex mMutex;
  50. };
  51. } // namespace rtc::impl
  52. #endif
  53. #endif