Use in-class initialization for making it harder to forget to set a default.
[cubemap] / client.cpp
1 #include <stdio.h>
2 #include <arpa/inet.h>
3 #include <netinet/in.h>
4 #include <stdint.h>
5 #include <sys/socket.h>
6
7 #include "client.h"
8 #include "log.h"
9 #include "state.pb.h"
10 #include "stream.h"
11
12 #ifndef SO_MAX_PACING_RATE
13 #define SO_MAX_PACING_RATE 47
14 #endif
15
16 using namespace std;
17
18 Client::Client(int sock)
19         : sock(sock)
20 {
21         request.reserve(1024);
22
23         if (clock_gettime(CLOCK_MONOTONIC_COARSE, &connect_time) == -1) {
24                 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
25                 return;
26         }
27
28         // Find the remote address, and convert it to ASCII.
29         sockaddr_in6 addr;
30         socklen_t addr_len = sizeof(addr);
31
32         if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &addr_len) == -1) {
33                 log_perror("getpeername");
34                 remote_addr = "";
35                 return;
36         }
37
38         char buf[INET6_ADDRSTRLEN];
39         if (IN6_IS_ADDR_V4MAPPED(&addr.sin6_addr)) {
40                 // IPv4 address, really.
41                 if (inet_ntop(AF_INET, &addr.sin6_addr.s6_addr32[3], buf, sizeof(buf)) == nullptr) {
42                         log_perror("inet_ntop");
43                         remote_addr = "";
44                 } else {
45                         remote_addr = buf;
46                 }
47         } else {
48                 if (inet_ntop(addr.sin6_family, &addr.sin6_addr, buf, sizeof(buf)) == nullptr) {
49                         log_perror("inet_ntop");
50                         remote_addr = "";
51                 } else {
52                         remote_addr = buf;
53                 }
54         }
55 }
56         
57 Client::Client(const ClientProto &serialized, Stream *stream)
58         : sock(serialized.sock()),
59           remote_addr(serialized.remote_addr()),
60           referer(serialized.referer()),
61           user_agent(serialized.user_agent()),
62           state(State(serialized.state())),
63           request(serialized.request()),
64           url(serialized.url()),
65           stream(stream),
66           header_or_short_response(serialized.header_or_short_response()),
67           header_or_short_response_bytes_sent(serialized.header_or_short_response_bytes_sent()),
68           stream_pos(serialized.stream_pos()),
69           bytes_sent(serialized.bytes_sent()),
70           bytes_lost(serialized.bytes_lost()),
71           num_loss_events(serialized.num_loss_events())
72 {
73         if (stream != nullptr) {
74                 if (setsockopt(sock, SOL_SOCKET, SO_MAX_PACING_RATE, &stream->pacing_rate, sizeof(stream->pacing_rate)) == -1) {
75                         if (stream->pacing_rate != ~0U) {
76                                 log_perror("setsockopt(SO_MAX_PACING_RATE)");
77                         }
78                 }
79         }
80         connect_time.tv_sec = serialized.connect_time_sec();
81         connect_time.tv_nsec = serialized.connect_time_nsec();
82
83         in_ktls_mode = false;
84         if (serialized.has_tls_context()) {
85                 tls_context = tls_import_context(
86                         reinterpret_cast<const unsigned char *>(serialized.tls_context().data()),
87                         serialized.tls_context().size());
88                 if (tls_context == nullptr) {
89                         log(WARNING, "tls_import_context() failed, TLS client might not survive across restart");
90                 } else {
91                         tls_data_to_send = tls_get_write_buffer(tls_context, &tls_data_left_to_send);
92
93                         assert(serialized.tls_output_bytes_already_consumed() <= tls_data_left_to_send);
94                         if (serialized.tls_output_bytes_already_consumed() >= tls_data_left_to_send) {
95                                 tls_buffer_clear(tls_context);
96                                 tls_data_to_send = nullptr;
97                         } else {
98                                 tls_data_to_send += serialized.tls_output_bytes_already_consumed();
99                                 tls_data_left_to_send -= serialized.tls_output_bytes_already_consumed();
100                         }
101                         in_ktls_mode = serialized.in_ktls_mode();
102                 }
103         } else {
104                 tls_context = nullptr;
105         }
106 }
107
108 ClientProto Client::serialize() const
109 {
110         ClientProto serialized;
111         serialized.set_sock(sock);
112         serialized.set_remote_addr(remote_addr);
113         serialized.set_referer(referer);
114         serialized.set_user_agent(user_agent);
115         serialized.set_connect_time_sec(connect_time.tv_sec);
116         serialized.set_connect_time_nsec(connect_time.tv_nsec);
117         serialized.set_state(state);
118         serialized.set_request(request);
119         serialized.set_url(url);
120         serialized.set_header_or_short_response(header_or_short_response);
121         serialized.set_header_or_short_response_bytes_sent(serialized.header_or_short_response_bytes_sent());
122         serialized.set_stream_pos(stream_pos);
123         serialized.set_bytes_sent(bytes_sent);
124         serialized.set_bytes_lost(bytes_lost);
125         serialized.set_num_loss_events(num_loss_events);
126
127         if (tls_context != nullptr) {
128                 bool small_version = false;
129                 int required_size = tls_export_context(tls_context, nullptr, 0, small_version);
130                 if (required_size <= 0) {
131                         // Can happen if we're in the middle of the key exchange, unfortunately.
132                         // We'll get an error fairly fast, and this client hasn't started playing
133                         // anything yet, so just log the error and continue.
134                         //
135                         // In theory, we could still rescue it if we had sent _zero_ bytes,
136                         // by doing an entirely new TLS context, but it's an edge case
137                         // that's not really worth it.
138                         log(WARNING, "tls_export_context() failed (returned %d), TLS client might not survive across restart",
139                                 required_size);
140                 } else {
141                         string *serialized_context = serialized.mutable_tls_context();
142                         serialized_context->resize(required_size);
143
144                         int ret = tls_export_context(tls_context,
145                                 reinterpret_cast<unsigned char *>(&(*serialized_context)[0]),
146                                 serialized_context->size(),
147                                 small_version);
148                         assert(ret == required_size);
149
150                         // tls_export_context() has exported the contents of the write buffer, but it doesn't
151                         // know how much of that we've consumed, so we need to figure that out by ourselves.
152                         // In a sense, it's unlikely that this will ever be relevant, though, since TLSe can't
153                         // currently serialize in-progress key exchanges.
154                         unsigned base_tls_data_left_to_send;
155                         const unsigned char *base_tls_data_to_send = tls_get_write_buffer(tls_context, &base_tls_data_left_to_send);
156                         if (base_tls_data_to_send == nullptr) {
157                                 assert(tls_data_to_send == nullptr);
158                         } else {
159                                 assert(tls_data_to_send + tls_data_left_to_send == base_tls_data_to_send + base_tls_data_left_to_send);
160                         }
161                         serialized.set_tls_output_bytes_already_consumed(tls_data_to_send - base_tls_data_to_send);
162                         serialized.set_in_ktls_mode(in_ktls_mode);
163                 }
164         }
165
166         return serialized;
167 }
168
169 namespace {
170
171 string escape_string(const string &str) {
172         string ret;
173         for (size_t i = 0; i < str.size(); ++i) {
174                 char buf[16];
175                 if (isprint(str[i]) && str[i] >= 32 && str[i] != '"' && str[i] != '\\') {
176                         ret.push_back(str[i]);
177                 } else {
178                         snprintf(buf, sizeof(buf), "\\x%02x", (unsigned char)str[i]);
179                         ret += buf;
180                 }
181         }
182         return ret;
183 }
184
185 } // namespace
186         
187 ClientStats Client::get_stats() const
188 {
189         ClientStats stats;
190         if (url.empty()) {
191                 stats.url = "-";
192         } else {
193                 stats.url = url;
194         }
195         stats.sock = sock;
196         stats.remote_addr = remote_addr;
197         stats.referer = escape_string(referer);
198         stats.user_agent = escape_string(user_agent);
199         stats.connect_time = connect_time;
200         stats.bytes_sent = bytes_sent;
201         stats.bytes_lost = bytes_lost;
202         stats.num_loss_events = num_loss_events;
203         return stats;
204 }