Line data Source code
1 : /* 2 : * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. 3 : */ 4 : 5 : #ifndef __HTTP_SESSION_H__ 6 : #define __HTTP_SESSION_H__ 7 : 8 : #include <atomic> 9 : #include <mutex> 10 : 11 : #include <boost/scoped_ptr.hpp> 12 : #include <tbb/concurrent_queue.h> 13 : 14 : #include "base/util.h" 15 : #include "io/ssl_session.h" 16 : 17 : class HttpRequest; 18 : class HttpServer; 19 : 20 : class HttpSession: public SslSession { 21 : public: 22 : typedef boost::function<void(HttpSession *session, 23 : enum TcpSession::Event event)> SessionEventCb; 24 : 25 : HttpSession(HttpServer *server, SslSocket *sock, bool async_ready = true); 26 : virtual ~HttpSession(); 27 : const std::string get_context() { return context_str_; } 28 : 29 : static bool SendSession(std::string const& s, 30 : const uint8_t *data, size_t size, size_t *sent) { 31 : HttpSessionPtr hs = GetSession(s); 32 : if (!hs) return false; 33 : return hs->Send(data, size, sent); 34 : } 35 : static std::string get_client_context(std::string const& s) { 36 : HttpSessionPtr hs = GetSession(s); 37 : if (!hs) return ""; 38 : return hs->get_client_context(); 39 : } 40 : static bool set_client_context(std::string const& s, 41 : const std::string& ctx) { 42 : HttpSessionPtr hs = GetSession(s); 43 : if (!hs) return false; 44 : hs->set_client_context(ctx); 45 : return true; 46 : } 47 : static long GetPendingTaskCount() { 48 : return task_count_; 49 : } 50 : 51 : void AcceptSession(); 52 : void RegisterEventCb(SessionEventCb cb); 53 : 54 : protected: 55 : virtual void OnRead(Buffer buffer); 56 : 57 : private: 58 : class RequestBuilder; 59 : class RequestHandler; 60 : typedef boost::intrusive_ptr<HttpSession> HttpSessionPtr; 61 : typedef std::map<std::string, HttpSessionPtr> map_type; 62 : 63 : void OnSessionEvent(TcpSession *session, 64 : enum TcpSession::Event event); 65 : 66 0 : static map_type* GetMap() { 67 0 : if (!context_map_) { 68 0 : context_map_ = new map_type(); 69 : } 70 0 : return context_map_; 71 : } 72 : static HttpSessionPtr GetSession(std::string const& s) { 73 : std::scoped_lock lock(map_mutex_); 74 : map_type::iterator it = GetMap()->find(s); 75 : if (it == GetMap()->end()) { 76 : return 0; 77 : } 78 : return it->second; 79 : } 80 : const std::string get_client_context() { return client_context_str_; } 81 : void set_client_context(const std::string& client_ctx) 82 : { client_context_str_ = client_ctx; } 83 : boost::scoped_ptr<RequestBuilder> request_builder_; 84 : tbb::concurrent_queue<HttpRequest *> request_queue_; 85 : std::atomic<bool> req_queue_empty_; 86 : std::string context_str_; 87 : std::string client_context_str_; 88 : SessionEventCb event_cb_; 89 : 90 : static int req_handler_task_id_; 91 : static map_type* context_map_; 92 : static std::mutex map_mutex_; 93 : static std::atomic<long> task_count_; 94 : 95 : DISALLOW_COPY_AND_ASSIGN(HttpSession); 96 : }; 97 : 98 : #endif /* __HTTP_SESSION_H__ */