c2cbcf5033bf76c86ccdf36e28078d525f969841
[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           stream_pos_end(serialized.stream_pos_end()),
70           bytes_sent(serialized.bytes_sent()),
71           bytes_lost(serialized.bytes_lost()),
72           num_loss_events(serialized.num_loss_events())
73 {
74         if (stream != nullptr) {
75                 if (setsockopt(sock, SOL_SOCKET, SO_MAX_PACING_RATE, &stream->pacing_rate, sizeof(stream->pacing_rate)) == -1) {
76                         if (stream->pacing_rate != ~0U) {
77                                 log_perror("setsockopt(SO_MAX_PACING_RATE)");
78                         }
79                 }
80         }
81         connect_time.tv_sec = serialized.connect_time_sec();
82         connect_time.tv_nsec = serialized.connect_time_nsec();
83
84         in_ktls_mode = false;
85         if (serialized.has_tls_context()) {
86                 tls_context = tls_import_context(
87                         reinterpret_cast<const unsigned char *>(serialized.tls_context().data()),
88                         serialized.tls_context().size());
89                 if (tls_context == nullptr) {
90                         log(WARNING, "tls_import_context() failed, TLS client might not survive across restart");
91                 } else {
92                         tls_data_to_send = tls_get_write_buffer(tls_context, &tls_data_left_to_send);
93
94                         assert(serialized.tls_output_bytes_already_consumed() <= tls_data_left_to_send);
95                         if (serialized.tls_output_bytes_already_consumed() >= tls_data_left_to_send) {
96                                 tls_buffer_clear(tls_context);
97                                 tls_data_to_send = nullptr;
98                         } else {
99                                 tls_data_to_send += serialized.tls_output_bytes_already_consumed();
100                                 tls_data_left_to_send -= serialized.tls_output_bytes_already_consumed();
101                         }
102                         in_ktls_mode = serialized.in_ktls_mode();
103                 }
104         } else {
105                 tls_context = nullptr;
106         }
107 }
108
109 ClientProto Client::serialize() const
110 {
111         ClientProto serialized;
112         serialized.set_sock(sock);
113         serialized.set_remote_addr(remote_addr);
114         serialized.set_referer(referer);
115         serialized.set_user_agent(user_agent);
116         serialized.set_connect_time_sec(connect_time.tv_sec);
117         serialized.set_connect_time_nsec(connect_time.tv_nsec);
118         serialized.set_state(state);
119         serialized.set_request(request);
120         serialized.set_url(url);
121         serialized.set_header_or_short_response(header_or_short_response);
122         serialized.set_header_or_short_response_bytes_sent(serialized.header_or_short_response_bytes_sent());
123         serialized.set_stream_pos(stream_pos);
124         serialized.set_stream_pos_end(stream_pos_end);
125         serialized.set_bytes_sent(bytes_sent);
126         serialized.set_bytes_lost(bytes_lost);
127         serialized.set_num_loss_events(num_loss_events);
128
129         if (tls_context != nullptr) {
130                 bool small_version = false;
131                 int required_size = tls_export_context(tls_context, nullptr, 0, small_version);
132                 if (required_size <= 0) {
133                         // Can happen if we're in the middle of the key exchange, unfortunately.
134                         // We'll get an error fairly fast, and this client hasn't started playing
135                         // anything yet, so just log the error and continue.
136                         //
137                         // In theory, we could still rescue it if we had sent _zero_ bytes,
138                         // by doing an entirely new TLS context, but it's an edge case
139                         // that's not really worth it.
140                         log(WARNING, "tls_export_context() failed (returned %d), TLS client might not survive across restart",
141                                 required_size);
142                 } else {
143                         string *serialized_context = serialized.mutable_tls_context();
144                         serialized_context->resize(required_size);
145
146                         int ret = tls_export_context(tls_context,
147                                 reinterpret_cast<unsigned char *>(&(*serialized_context)[0]),
148                                 serialized_context->size(),
149                                 small_version);
150                         assert(ret == required_size);
151
152                         // tls_export_context() has exported the contents of the write buffer, but it doesn't
153                         // know how much of that we've consumed, so we need to figure that out by ourselves.
154                         // In a sense, it's unlikely that this will ever be relevant, though, since TLSe can't
155                         // currently serialize in-progress key exchanges.
156                         unsigned base_tls_data_left_to_send;
157                         const unsigned char *base_tls_data_to_send = tls_get_write_buffer(tls_context, &base_tls_data_left_to_send);
158                         if (base_tls_data_to_send == nullptr) {
159                                 assert(tls_data_to_send == nullptr);
160                         } else {
161                                 assert(tls_data_to_send + tls_data_left_to_send == base_tls_data_to_send + base_tls_data_left_to_send);
162                         }
163                         serialized.set_tls_output_bytes_already_consumed(tls_data_to_send - base_tls_data_to_send);
164                         serialized.set_in_ktls_mode(in_ktls_mode);
165                 }
166         }
167
168         return serialized;
169 }
170
171 namespace {
172
173 string escape_string(const string &str) {
174         string ret;
175         for (size_t i = 0; i < str.size(); ++i) {
176                 char buf[16];
177                 if (isprint(str[i]) && str[i] >= 32 && str[i] != '"' && str[i] != '\\') {
178                         ret.push_back(str[i]);
179                 } else {
180                         snprintf(buf, sizeof(buf), "\\x%02x", (unsigned char)str[i]);
181                         ret += buf;
182                 }
183         }
184         return ret;
185 }
186
187 } // namespace
188         
189 ClientStats Client::get_stats() const
190 {
191         ClientStats stats;
192         if (url.empty()) {
193                 stats.url = "-";
194         } else {
195                 stats.url = url;
196         }
197         stats.sock = sock;
198         stats.remote_addr = remote_addr;
199         stats.referer = escape_string(referer);
200         stats.user_agent = escape_string(user_agent);
201         stats.connect_time = connect_time;
202         stats.bytes_sent = bytes_sent;
203         stats.bytes_lost = bytes_lost;
204         stats.num_loss_events = num_loss_events;
205         return stats;
206 }