1 // SPDX-License-Identifier: Apache-2.0 2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors 3 #pragma once 4 5 #include "async_resp.hpp" 6 #include "baserule.hpp" 7 #include "http_request.hpp" 8 #include "logging.hpp" 9 #include "websocket.hpp" 10 11 #include <boost/asio/ip/tcp.hpp> 12 #include <boost/asio/ssl/stream.hpp> 13 #include <boost/beast/http/status.hpp> 14 15 #include <functional> 16 #include <memory> 17 #include <string> 18 #include <string_view> 19 #include <vector> 20 21 namespace crow 22 { 23 class WebSocketRule : public BaseRule 24 { 25 using self_t = WebSocketRule; 26 27 public: WebSocketRule(const std::string & ruleIn)28 explicit WebSocketRule(const std::string& ruleIn) : BaseRule(ruleIn) 29 { 30 isUpgrade = true; 31 // Clear GET handler 32 methodsBitfield = 0; 33 } 34 validate()35 void validate() override {} 36 handle(const Request &,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const std::vector<std::string> &)37 void handle(const Request& /*req*/, 38 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 39 const std::vector<std::string>& /*params*/) override 40 { 41 BMCWEB_LOG_ERROR( 42 "Handle called on websocket rule. This should never happen"); 43 asyncResp->res.result( 44 boost::beast::http::status::internal_server_error); 45 } 46 47 void handleUpgrade(const Request& req, 48 const std::shared_ptr<bmcweb::AsyncResp>& /*asyncResp*/, 49 boost::asio::ip::tcp::socket&& adaptor) override; 50 51 void handleUpgrade(const Request& req, 52 const std::shared_ptr<bmcweb::AsyncResp>& /*asyncResp*/, 53 boost::asio::ssl::stream<boost::asio::ip::tcp::socket>&& 54 adaptor) override; 55 56 template <typename Func> onopen(Func f)57 self_t& onopen(Func f) 58 { 59 openHandler = f; 60 return *this; 61 } 62 63 template <typename Func> onmessage(Func f)64 self_t& onmessage(Func f) 65 { 66 messageHandler = f; 67 return *this; 68 } 69 70 template <typename Func> onmessageex(Func f)71 self_t& onmessageex(Func f) 72 { 73 messageExHandler = f; 74 return *this; 75 } 76 77 template <typename Func> onclose(Func f)78 self_t& onclose(Func f) 79 { 80 closeHandler = f; 81 return *this; 82 } 83 84 template <typename Func> onerror(Func f)85 self_t& onerror(Func f) 86 { 87 errorHandler = f; 88 return *this; 89 } 90 91 protected: 92 std::function<void(crow::websocket::Connection&)> openHandler; 93 std::function<void(crow::websocket::Connection&, const std::string&, bool)> 94 messageHandler; 95 std::function<void(crow::websocket::Connection&, std::string_view, 96 crow::websocket::MessageType type, 97 std::function<void()>&& whenComplete)> 98 messageExHandler; 99 std::function<void(crow::websocket::Connection&, const std::string&)> 100 closeHandler; 101 std::function<void(crow::websocket::Connection&)> errorHandler; 102 }; 103 } // namespace crow 104