87d17e44ca777d80f1adea83029261517dbef52d
[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 : private 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
38         time_point<steady_clock> create_time() const { return create_time_; }
39
40         static shared_ptr<connection> to_dst(const sockaddr_in &dst, connection_delegate *mgr, int lossy=0);
41
42     private:
43         void write_cb(int s);
44         void read_cb(int s);
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 : private aio_callback {
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     private:
72         void write_cb(int) {}
73         void read_cb(int s);
74
75         in_port_t port_;
76         mutex m_;
77
78         socket_t tcp_; // listens for connections
79         connection_delegate *mgr_;
80         int lossy_;
81         map<int, shared_ptr<connection>> conns_;
82 };
83 #endif