97bacbb7900c97401e9baebf3c05e5277931e4fe
[invirt/third/libt4.git] / rpc / connection.h
1 #ifndef connection_h
2 #define connection_h
3
4 #include "types.h"
5 #include <arpa/inet.h>
6 #include <netinet/in.h>
7 #include "poll_mgr.h"
8 #include "file.h"
9
10 constexpr size_t size_t_max = numeric_limits<size_t>::max();
11
12 class thread_exit_exception : exception {};
13
14 class connection;
15
16 class connection_delegate {
17     public:
18         virtual bool got_pdu(const shared_ptr<connection> & c, const string & b) = 0;
19         virtual ~connection_delegate() {}
20 };
21
22 class connection : public aio_callback, public enable_shared_from_this<connection> {
23     public:
24         struct charbuf {
25             string buf;
26             size_t solong = 0; // number of bytes written or read so far
27         };
28
29         connection(connection_delegate *m1, socket_t && f1, int lossytest=0);
30         ~connection();
31
32         int channo() { return fd_; }
33         bool isdead() { lock ml(m_); return dead_; }
34         void closeconn();
35
36         bool send(const string & b);
37         void write_cb(int s);
38         void read_cb(int s);
39
40         time_point<steady_clock> create_time() const { return create_time_; }
41
42         static shared_ptr<connection> to_dst(const sockaddr_in &dst, connection_delegate *mgr, int lossy=0);
43
44     private:
45
46         bool readpdu();
47         bool writepdu();
48
49         connection_delegate *mgr_;
50         const file_t fd_;
51         bool dead_ = false;
52
53         charbuf wpdu_;
54         charbuf rpdu_;
55
56         time_point<steady_clock> create_time_;
57
58         int waiters_ = 0;
59         int lossy_ = 0;
60
61         mutex m_;
62         cond send_complete_;
63         cond send_wait_;
64 };
65
66 class tcpsconn {
67     public:
68         tcpsconn(connection_delegate *m1, in_port_t port, int lossytest=0);
69         ~tcpsconn();
70         inline in_port_t port() { return port_; }
71         void accept_conn();
72     private:
73         in_port_t port_;
74         mutex m_;
75         thread th_;
76         file_t pipe_[2];
77
78         socket_t tcp_; // listens for connections
79         connection_delegate *mgr_;
80         int lossy_;
81         map<int, shared_ptr<connection>> conns_;
82
83         void process_accept();
84 };
85 #endif