1bcb7b674e40bd71c2c40643b57ccf7c788ef175
[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 connection;
13
14 class connection_delegate {
15     public:
16         virtual bool got_pdu(const shared_ptr<connection> & c, const string & b) = 0;
17         virtual ~connection_delegate();
18 };
19
20 class connection : private aio_callback, public enable_shared_from_this<connection> {
21     public:
22         connection(connection_delegate * delegate, socket_t && f1, int lossytest=0);
23         ~connection();
24
25         bool isdead() { return dead_; }
26
27         bool send(const string & b);
28
29         static shared_ptr<connection> to_dst(const sockaddr_in & dst, connection_delegate *mgr, int lossy=0);
30
31         const time_point<steady_clock> create_time = steady_clock::now();
32         const file_t fd;
33
34     private:
35         void write_cb(int s);
36         void read_cb(int s);
37
38         bool readpdu();
39         bool writepdu();
40
41         connection_delegate * delegate_;
42         bool dead_ = false;
43
44         struct charbuf {
45             string buf;
46             size_t solong = 0; // number of bytes written or read so far
47         };
48
49         charbuf wpdu_;
50         charbuf rpdu_;
51
52         int waiters_ = 0;
53         int lossy_ = 0;
54
55         mutex m_;
56         cond send_complete_;
57         cond send_wait_;
58 };
59
60 class connection_listener : private aio_callback {
61     public:
62         connection_listener(connection_delegate * delegate, in_port_t port, int lossytest=0);
63         ~connection_listener();
64         inline in_port_t port() { return port_; }
65     private:
66         void write_cb(int) {}
67         void read_cb(int s);
68
69         in_port_t port_;
70         mutex m_;
71
72         socket_t tcp_; // listens for connections
73         connection_delegate * delegate_;
74         int lossy_;
75         map<int, shared_ptr<connection>> conns_;
76 };
77 #endif