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