xs/io.c

filter: Statementstmt 62.2% 363 / 583 Branchbran 43.3% 210 / 484 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 53.7% 573 / 1067 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xs/proto_http.c ↑ Summary xs/queues.c »
1 /* --- Async TCP connect, I/O dispatch, timers, keepalive, reconnect,
2 * pipeline advance, and OpenSSL one-time init. ---
3 *
4 * Forward decls for symbols defined later in this file but called from
5 * earlier in the same file (cross-file callers use the forwards in
6 * ClickHouse.xs).
7 */
8 static void io_cb(EV_P_ ev_io *w, int revents);
9 static void on_connect_done(ev_clickhouse_t *self);
10 static void start_keepalive(ev_clickhouse_t *self);
11  
12 /* Stash connection parameters without connecting (async-DNS pre-store). */
13 50 static void store_conn_params(ev_clickhouse_t *self, const char *host,
14 unsigned int port, const char *user,
15 const char *password, const char *database)
16 {
17 50 ▶ CLEAR_STR(self->host);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->host); 0 50 50
18 50 ▶ CLEAR_STR(self->user);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->user); 0 50 50
19 50 ▶ CLEAR_STR(self->password);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->password); 0 50 50
20 50 ▶ CLEAR_STR(self->database);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->database); 0 50 50
21  
22 50 self->host = safe_strdup(host);
23 50 self->port = port;
24 50 self->user = safe_strdup(user);
25 50 self->password = safe_strdup(password);
26 50 self->database = safe_strdup(database);
27 50 }
28  
29 #ifdef HAVE_OPENSSL
30 /* Drain OpenSSL's per-thread error queue into self->last_tls_error
31 * (most recent error wins). Safe to call when the queue is empty —
32 * we leave the previous value untouched. */
33 0 static void capture_tls_error(ev_clickhouse_t *self) {
34 0 unsigned long e = 0, last = 0;
35 0 ▶ while ((e = ERR_get_error()) != 0) last = e;
Branch: 1 branch
BranchTrueFalseTotal
while ((e = ERR_get_error()) != 0) last = e; 0 0 0
36 0 ▶ if (!last) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!last) return; 0 0 0
37 char buf[256];
38 0 ERR_error_string_n(last, buf, sizeof(buf));
39 0 ▶ CLEAR_STR(self->last_tls_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->last_tls_error); 0 0 0
40 0 self->last_tls_error = savepv(buf);
41 }
42  
43 /* SSL_ERROR_SYSCALL leaves OpenSSL's error queue empty — the detail
44 * lives in errno (ret < 0) or is a bare EOF (ret == 0). Record it so
45 * last_tls_error says something useful instead of going stale. */
46 1 static void capture_tls_syscall_error(ev_clickhouse_t *self, int ret) {
47 char ebuf[160];
48 1 ▶ if (ret == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (ret == 0) 0 1 1
49 0 snprintf(ebuf, sizeof(ebuf), "TLS handshake EOF (SSL_ERROR_SYSCALL)");
50 else
51 1 snprintf(ebuf, sizeof(ebuf), "TLS handshake I/O error: %s (SSL_ERROR_SYSCALL)",
52 1 strerror(errno));
53 1 ▶ CLEAR_STR(self->last_tls_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->last_tls_error); 0 1 1
54 1 self->last_tls_error = savepv(ebuf);
55 1 }
56 #endif
57  
58 /* Report a connect that failed before any I/O (resolver, BSD loopback
59 * refusal) from the loop, so on_error never fires inside new(). */
60 1 static void defer_connect_failure(ev_clickhouse_t *self, const char *msg) {
61 1 ▶ CLEAR_STR(self->connect_err);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->connect_err); 0 1 1
62 1 self->connect_err = savepv(msg);
63 1 ▶ if (self->timing) ev_timer_stop(self->loop, &self->timer);
Branch: 1 branch
BranchTrueFalseTotal
if (self->timing) ev_timer_stop(self->loop, &self->timer); 0 1 1
64 1 ev_timer_set(&self->timer, 0.0, 0.0);
65 1 ev_timer_start(self->loop, &self->timer);
66 1 self->timing = 1;
67 1 }
68  
69 82 static void start_connect(ev_clickhouse_t *self) {
70 82 struct addrinfo hints, *res = NULL, *ai;
71 82 int fd = -1, ret;
72 char port_str[16];
73  
74 82 ▶ CLEAR_STR(self->connect_err);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->connect_err); 0 82 82
75  
76 82 self->connect_gen++;
77  
78 {
79 82 int gen = self->connect_gen;
80 82 emit_trace(self, "connect %s:%u (%s)",
81 self->host, self->port,
82 82 ▶ self->protocol == PROTO_NATIVE ? "native" : "http");
Branch: 1 branch
BranchTrueFalseTotal
self->protocol == PROTO_NATIVE ? "native" : "http"); 32 50 82
83 /* A finish()/reset() from the handler wins: the outer frame must
84 * not connect over it (a finish would be silently undone). All
85 * callers end right after start_connect, so freeing here is safe. */
86 83 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 82 82
87 82 ▶ if (self->magic != EV_CH_MAGIC) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC) return; 0 82 82
88 82 ▶ if (self->connect_gen != gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; 0 82 82
89 }
90 82 snprintf(port_str, sizeof(port_str), "%u", self->port);
91  
92 82 Zero(&hints, 1, struct addrinfo);
93 82 hints.ai_family = AF_UNSPEC;
94 82 hints.ai_socktype = SOCK_STREAM;
95  
96 82 ret = getaddrinfo(self->host, port_str, &hints, &res);
97 82 ▶ if (ret != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret != 0) { 1 81 82
98 char errbuf[256];
99 1 snprintf(errbuf, sizeof(errbuf), "getaddrinfo: %s", gai_strerror(ret));
100 1 defer_connect_failure(self, errbuf);
101 1 return;
102 }
103  
104 /* Try each resolved address in turn: dual-stack names routinely
105 * list an unreachable family first, and DNS round-robin sets may
106 * hold a dead entry. The first connect() that starts (immediate or
107 * EINPROGRESS) wins; only total failure reports an error. */
108 {
109 81 int saved_errno = 0;
110 81 ▶ for (ai = res; ai != NULL; ai = ai->ai_next) {
Branch: 1 branch
BranchTrueFalseTotal
for (ai = res; ai != NULL; ai = ai->ai_next) { 81 0 81
111 81 int one = 1, fl;
112 81 fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
113 81 ▶ if (fd < 0) { saved_errno = errno; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { saved_errno = errno; continue; } 0 81 81
114 81 fl = fcntl(fd, F_GETFL);
115 81 ▶ if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) { 81 0 81
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) { 0 81 81
116 0 saved_errno = errno;
117 0 close(fd);
118 0 fd = -1;
119 0 continue;
120 }
121 81 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
122 81 ret = connect(fd, ai->ai_addr, ai->ai_addrlen);
123 81 ▶ if (ret == 0 || errno == EINPROGRESS) break;
Branch: 2 branches
BranchTrueFalseTotal
if (ret == 0 || errno == EINPROGRESS) break; 81 0 81
if (ret == 0 || errno == EINPROGRESS) break; 0 81 81
124 0 saved_errno = errno;
125 0 close(fd);
126 0 fd = -1;
127 }
128 81 freeaddrinfo(res);
129 81 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 0 81 81
130 char errbuf[256];
131 0 ▶ snprintf(errbuf, sizeof(errbuf), "connect: %s",
Branch: 1 branch
BranchTrueFalseTotal
snprintf(errbuf, sizeof(errbuf), "connect: %s", 0 0 0
132 strerror(saved_errno ? saved_errno : ECONNREFUSED));
133 0 defer_connect_failure(self, errbuf);
134 0 return;
135 }
136 }
137  
138 81 self->fd = fd;
139 81 self->connecting = 1;
140  
141 81 ev_io_init(&self->rio, io_cb, self->fd, EV_READ);
142 81 self->rio.data = (void *)self;
143 81 ev_io_init(&self->wio, io_cb, self->fd, EV_WRITE);
144 81 self->wio.data = (void *)self;
145  
146 /* Arm connect_timeout on both paths: an immediately-connected
147 * socket still stalls in the TLS handshake / ServerHello phases. */
148 81 ▶ if (self->connect_timeout > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timeout > 0) { 7 74 81
149 /* ev_timer_set on an active watcher corrupts libev's heap. */
150 7 ▶ if (self->timing) ev_timer_stop(self->loop, &self->timer);
Branch: 1 branch
BranchTrueFalseTotal
if (self->timing) ev_timer_stop(self->loop, &self->timer); 0 7 7
151 7 ev_now_update(self->loop);
152 7 ev_timer_set(&self->timer, (ev_tstamp)self->connect_timeout, 0.0);
153 7 ev_timer_start(self->loop, &self->timer);
154 7 self->timing = 1;
155 }
156  
157 /* In progress, or connected at once (BSD loopback): either way wait
158 * for writability, so on_connect never fires inside new() */
159 81 start_writing(self);
160 }
161  
162 /* Mark the connection as ready, fire on_connect, dispatch queued queries.
163 * Returns 1 if self was freed. */
164 62 static int finish_connect(ev_clickhouse_t *self) {
165 62 self->handshaking = 0;
166 62 stop_timing(self);
167 /* Reset only here — at TCP accept time a peer that stalls the TLS
168 * handshake or ServerHello would otherwise spin reconnects forever
169 * without ever tripping reconnect_max_attempts. */
170 62 self->reconnect_attempts = 0;
171 62 self->connected = 1;
172 62 ▶ CLEAR_STR(self->last_tls_error); /* successful connect supersedes stale TLS error */
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->last_tls_error); /* successful connect supersedes stale TLS error */ 0 62 62
173 62 start_keepalive(self); /* idle pings start at connect, not first query */
174 124 if (self->on_connect &&
175 62 fire_zero_arg_cb(self, self->on_connect, "connect")) return 1;
176 62 ▶ if (!ngx_queue_empty(&self->send_queue))
Branch: 1 branch
BranchTrueFalseTotal
if (!ngx_queue_empty(&self->send_queue)) 40 22 62
177 40 return pipeline_advance(self);
178 22 return 0;
179 }
180  
181 70 static void on_connect_done(ev_clickhouse_t *self) {
182 70 self->connecting = 0;
183 /* TLS / native ServerHello may still be pending; queries issued in
184 * this window must queue, not croak "not connected". finish_connect
185 * clears it once the connection is fully ready. */
186 70 self->handshaking = 1;
187  
188 70 stop_writing(self);
189 /* Keep the connect_timeout timer armed across the TLS handshake and
190 * native ServerHello phases — finish_connect() stops it once the
191 * connection is fully ready to accept queries. */
192  
193 #ifdef HAVE_OPENSSL
194 70 ▶ if (self->tls_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->tls_enabled) { 1 69 70
195 int ret;
196 1 self->ssl_ctx = SSL_CTX_new(TLS_client_method());
197 1 ▶ if (!self->ssl_ctx) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ssl_ctx) { 0 1 1
198 0 fail_connection(self, "SSL_CTX_new failed");
199 0 return;
200 }
201 1 SSL_CTX_set_default_verify_paths(self->ssl_ctx);
202 1 ▶ if (self->tls_skip_verify)
Branch: 1 branch
BranchTrueFalseTotal
if (self->tls_skip_verify) 1 0 1
203 1 SSL_CTX_set_verify(self->ssl_ctx, SSL_VERIFY_NONE, NULL);
204 else
205 0 SSL_CTX_set_verify(self->ssl_ctx, SSL_VERIFY_PEER, NULL);
206 1 ▶ if (self->tls_ca_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->tls_ca_file) { 0 1 1
207 0 ▶ if (SSL_CTX_load_verify_locations(self->ssl_ctx, self->tls_ca_file, NULL) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (SSL_CTX_load_verify_locations(self->ssl_ctx, self->tls_ca_file, NULL) != 1) { 0 0 0
208 0 capture_tls_error(self);
209 0 fail_connection(self, "SSL_CTX_load_verify_locations failed");
210 0 return;
211 }
212 }
213 /* Mutual TLS: load client certificate + private key when both
214 * are configured. SSL_CTX_check_private_key verifies that the
215 * private key matches the loaded certificate's public half. */
216 1 ▶ if (self->tls_cert_file && self->tls_key_file) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->tls_cert_file && self->tls_key_file) { 0 1 1
if (self->tls_cert_file && self->tls_key_file) { 0 0 0
217 0 ▶ if (SSL_CTX_use_certificate_chain_file(self->ssl_ctx, self->tls_cert_file) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (SSL_CTX_use_certificate_chain_file(self->ssl_ctx, self->tls_cert_file) != 1) { 0 0 0
218 0 capture_tls_error(self);
219 0 fail_connection(self, "SSL_CTX_use_certificate_chain_file failed");
220 0 return;
221 }
222 0 ▶ if (SSL_CTX_use_PrivateKey_file(self->ssl_ctx, self->tls_key_file, SSL_FILETYPE_PEM) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (SSL_CTX_use_PrivateKey_file(self->ssl_ctx, self->tls_key_file, SSL_FILETYPE_PEM) != 1) { 0 0 0
223 0 capture_tls_error(self);
224 0 fail_connection(self, "SSL_CTX_use_PrivateKey_file failed");
225 0 return;
226 }
227 0 ▶ if (SSL_CTX_check_private_key(self->ssl_ctx) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (SSL_CTX_check_private_key(self->ssl_ctx) != 1) { 0 0 0
228 0 capture_tls_error(self);
229 0 fail_connection(self, "TLS client cert / private key mismatch");
230 0 return;
231 }
232 1 ▶ } else if (self->tls_cert_file || self->tls_key_file) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (self->tls_cert_file || self->tls_key_file) { 1 0 1
} else if (self->tls_cert_file || self->tls_key_file) { 0 1 1
233 0 fail_connection(self, "tls_cert_file and tls_key_file must both be set");
234 0 return;
235 }
236 1 self->ssl = SSL_new(self->ssl_ctx);
237 1 ▶ if (!self->ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ssl) { 0 1 1
238 0 capture_tls_error(self);
239 0 fail_connection(self, "SSL_new failed");
240 0 return;
241 }
242 1 SSL_set_fd(self->ssl, self->fd);
243  
244 1 int host_is_ip = is_ip_literal(self->host);
245  
246 /* SNI must not be sent for IP address literals (RFC 6066 s3) */
247 1 ▶ if (!host_is_ip)
Branch: 1 branch
BranchTrueFalseTotal
if (!host_is_ip) 0 1 1
248 0 SSL_set_tlsext_host_name(self->ssl, self->host);
249  
250 /* Verify server certificate matches hostname or IP */
251 1 ▶ if (!self->tls_skip_verify) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->tls_skip_verify) { 0 1 1
252 0 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
253 0 X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
254 0 ▶ if (host_is_ip)
Branch: 1 branch
BranchTrueFalseTotal
if (host_is_ip) 0 0 0
255 0 X509_VERIFY_PARAM_set1_ip_asc(param, self->host);
256 else
257 0 X509_VERIFY_PARAM_set1_host(param, self->host, 0);
258 }
259  
260 1 ret = SSL_connect(self->ssl);
261 1 ▶ if (ret == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret == 1) { 0 1 1
262 /* handshake done immediately */
263 0 goto handshake_done;
264 } else {
265 1 int err = SSL_get_error(self->ssl, ret);
266 1 ▶ if (err == SSL_ERROR_WANT_READ) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_READ) { 1 0 1
267 1 start_reading(self);
268 0 ▶ } else if (err == SSL_ERROR_WANT_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (err == SSL_ERROR_WANT_WRITE) { 0 0 0
269 0 start_writing(self);
270 } else {
271 0 ▶ if (err == SSL_ERROR_SYSCALL)
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_SYSCALL) 0 0 0
272 0 capture_tls_syscall_error(self, ret);
273 else
274 0 capture_tls_error(self);
275 0 fail_connection(self, "SSL_connect failed");
276 0 return;
277 }
278 /* continue TLS handshake in io_cb */
279 1 return;
280 }
281 }
282 69 handshake_done:
283 #endif
284  
285 69 ▶ if (self->protocol == PROTO_NATIVE) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE) { 27 42 69
286 /* Send ClientHello and wait for ServerHello */
287 size_t hello_len;
288 27 char *hello = build_native_hello(self, &hello_len);
289 27 send_replace(self, hello, hello_len);
290  
291 27 self->native_state = NATIVE_WAIT_HELLO;
292 27 start_writing(self);
293 27 return;
294 }
295  
296 /* HTTP protocol: connection is ready */
297 42 (void)finish_connect(self);
298 }
299  
300 /* --- I/O callbacks --- */
301  
302 /* Returns 1 if self was freed (caller must not access self). */
303 109 static int try_write(ev_clickhouse_t *self) {
304 218 ▶ while (self->send_pos < self->send_len) {
Branch: 1 branch
BranchTrueFalseTotal
while (self->send_pos < self->send_len) { 109 109 218
305 109 ssize_t n = ch_write(self, self->send_buf + self->send_pos,
306 109 self->send_len - self->send_pos);
307 109 ▶ if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) { 0 109 109
308 0 ▶ if (errno == EAGAIN || errno == EWOULDBLOCK) {
Branch: 2 branches
BranchTrueFalseTotal
if (errno == EAGAIN || errno == EWOULDBLOCK) { 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK) { 0 0 0
309 0 start_writing(self);
310 0 return 0;
311 }
312 0 return teardown_io_error_reconnect(self, strerror(errno), "write error");
313 }
314 109 ▶ if (n == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) 0 109 109
315 0 return teardown_io_error_reconnect(self, "connection closed during write",
316 "connection closed");
317 109 self->send_pos += n;
318 }
319  
320 /* all sent */
321 109 stop_writing(self);
322 109 self->send_len = 0;
323 109 self->send_pos = 0;
324  
325 /* start reading responses */
326 109 start_reading(self);
327  
328 /* check if more to send */
329 109 ▶ if (!ngx_queue_empty(&self->send_queue))
Branch: 1 branch
BranchTrueFalseTotal
if (!ngx_queue_empty(&self->send_queue)) 0 109 109
330 0 return pipeline_advance(self);
331 109 return 0;
332 }
333  
334 80 static void on_readable(ev_clickhouse_t *self) {
335 ssize_t n;
336  
337 80 ensure_recv_cap(self, self->recv_len + 4096);
338 80 n = ch_read(self, self->recv_buf + self->recv_len,
339 80 self->recv_cap - self->recv_len);
340  
341 80 ▶ if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) { 1 79 80
342 1 ▶ if (errno == EAGAIN || errno == EWOULDBLOCK) return;
Branch: 2 branches
BranchTrueFalseTotal
if (errno == EAGAIN || errno == EWOULDBLOCK) return; 1 0 1
if (errno == EAGAIN || errno == EWOULDBLOCK) return; 0 1 1
343 1 teardown_io_error_reconnect(self, strerror(errno), "read error");
344 1 return;
345 }
346  
347 79 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 28 51 79
348 /* connection closed — fire on_error and drain pending if we
349 * have an in-flight request or haven't finished handshake */
350 28 ▶ int had_inflight = (self->send_count > 0 || !self->connected);
Branch: 2 branches
BranchTrueFalseTotal
int had_inflight = (self->send_count > 0 || !self->connected); 0 28 28
int had_inflight = (self->send_count > 0 || !self->connected); 0 0 0
351 28 int has_queued = !ngx_queue_empty(&self->send_queue);
352 28 int gen = self->connect_gen;
353  
354 28 ▶ if (had_inflight) {
Branch: 1 branch
BranchTrueFalseTotal
if (had_inflight) { 28 0 28
355 28 emit_error(self, "connection closed by server");
356 28 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 28 28
357 28 ▶ if (self->connect_gen != gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; 0 28 28
358 /* Only cancel in-flight cb_queue (irrecoverable).
359 * Keep send_queue if auto_reconnect — those haven't been sent yet. */
360 28 ▶ if (!self->auto_reconnect || !has_queued) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->auto_reconnect || !has_queued) { 24 4 28
if (!self->auto_reconnect || !has_queued) { 24 0 24
361 28 ▶ if (cancel_pending(self, "connection closed",
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_pending(self, "connection closed", 0 28 28
362 28 ▶ !(self->auto_reconnect && self->host)))
Branch: 2 branches
BranchTrueFalseTotal
!(self->auto_reconnect && self->host))) 24 4 28
!(self->auto_reconnect && self->host))) 0 24 24
363 0 return;
364 } else {
365 /* Cancel only the in-flight cb_queue entries */
366 0 self->callback_depth++;
367 0 drain_cb_queue(self, "connection closed");
368 0 self->callback_depth--;
369 0 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 0 0
370 }
371 28 ▶ if (self->connect_gen != gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; 0 28 28
372 }
373 28 ▶ if (cleanup_connection(self, 0)) return; /* on_disconnect freed self */
Branch: 1 branch
BranchTrueFalseTotal
if (cleanup_connection(self, 0)) return; /* on_disconnect freed self */ 0 28 28
374 /* reset() from on_disconnect already reconnected — scheduling
375 * another reconnect would burn an attempt (inflating backoff,
376 * or tripping max_reconnect_attempts on a healthy link). */
377 28 ▶ if (self->connect_gen != gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; 13 15 28
378  
379 /* Auto-reconnect if we have queued requests or flag is set */
380 15 ▶ if (self->auto_reconnect && self->host) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->auto_reconnect && self->host) { 12 3 15
if (self->auto_reconnect && self->host) { 12 0 12
381 12 schedule_reconnect(self);
382 }
383 15 return;
384 }
385  
386 51 self->recv_len += n;
387  
388 #ifdef HAVE_OPENSSL
389 /* TLS records already sitting in OpenSSL's buffer don't trip the
390 * socket watcher: a reply whose tail stays buffered while the
391 * socket runs dry would stall for lack of a new EV_READ. Drain
392 * everything buffered before parsing. No user code runs here, so
393 * self cannot be freed mid-loop (teardown paths return outright). */
394 51 ▶ while (self->ssl && SSL_pending(self->ssl) > 0) {
Branch: 2 branches
BranchTrueFalseTotal
while (self->ssl && SSL_pending(self->ssl) > 0) { 0 51 51
while (self->ssl && SSL_pending(self->ssl) > 0) { 0 0 0
395 0 ensure_recv_cap(self, self->recv_len + 4096);
396 0 n = ch_read(self, self->recv_buf + self->recv_len,
397 0 self->recv_cap - self->recv_len);
398 0 ▶ if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) { 0 0 0
399 0 ▶ if (errno == EAGAIN || errno == EWOULDBLOCK) break;
Branch: 2 branches
BranchTrueFalseTotal
if (errno == EAGAIN || errno == EWOULDBLOCK) break; 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK) break; 0 0 0
400 0 teardown_io_error_reconnect(self, strerror(errno), "read error");
401 0 return;
402 }
403 /* Clean TLS close: the socket EOF follows on its own event;
404 * buffered bytes may still complete the response, so parse on. */
405 0 ▶ if (n == 0) break;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) break; 0 0 0
406 0 self->recv_len += n;
407 }
408 #endif
409  
410 /* Defensive ceiling: a runaway response (server stuck in a bad state,
411 * pathological row sizes, or a header-injection attack) shouldn't be
412 * able to consume unbounded memory. Caller opts in via max_recv_buffer;
413 * 0 (default) keeps the historical behaviour of growing without limit
414 * up to CH_MAX_DECOMPRESS_SIZE on compressed paths. */
415 51 ▶ if (self->max_recv_buffer > 0 && self->recv_len > self->max_recv_buffer) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->max_recv_buffer > 0 && self->recv_len > self->max_recv_buffer) { 0 51 51
if (self->max_recv_buffer > 0 && self->recv_len > self->max_recv_buffer) { 0 0 0
416 char errmsg[80];
417 0 int gen = self->connect_gen;
418 0 snprintf(errmsg, sizeof(errmsg),
419 "recv buffer %lu exceeded max_recv_buffer %lu",
420 0 (unsigned long)self->recv_len,
421 0 (unsigned long)self->max_recv_buffer);
422 0 ▶ if (teardown_io_error(self, errmsg, "recv buffer overflow")) return;
Branch: 1 branch
BranchTrueFalseTotal
if (teardown_io_error(self, errmsg, "recv buffer overflow")) return; 0 0 0
423 /* The peer is healthy (it just answered too much), so
424 * re-establish the link like any other teardown — without
425 * this an auto_reconnect connection stays down forever after
426 * one oversize response. */
427 0 ▶ if (self->connect_gen == gen && self->auto_reconnect && self->host)
Branch: 3 branches
BranchTrueFalseTotal
if (self->connect_gen == gen && self->auto_reconnect && self->host) 0 0 0
if (self->connect_gen == gen && self->auto_reconnect && self->host) 0 0 0
if (self->connect_gen == gen && self->auto_reconnect && self->host) 0 0 0
428 0 schedule_reconnect(self);
429 0 return;
430 }
431  
432 51 ▶ if (self->protocol == PROTO_HTTP) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_HTTP) { 1 50 51
433 1 process_http_response(self);
434 } else {
435 50 process_native_response(self);
436 }
437 }
438  
439 180 static void io_cb(EV_P_ ev_io *w, int revents) {
440 180 ev_clickhouse_t *self = (ev_clickhouse_t *)w->data;
441 (void)loop;
442  
443 180 ▶ if (self == NULL || self->magic != EV_CH_MAGIC) return;
Branch: 2 branches
BranchTrueFalseTotal
if (self == NULL || self->magic != EV_CH_MAGIC) return; 180 0 180
if (self == NULL || self->magic != EV_CH_MAGIC) return; 0 180 180
444  
445 180 ▶ if (self->connecting) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connecting) { 72 108 180
446 /* check connect result */
447 72 int err = 0;
448 72 socklen_t errlen = sizeof(err);
449  
450 72 stop_writing(self);
451 /* Don't stop the connect_timeout timer here — it must keep
452 * running across TLS handshake and native ServerHello stages.
453 * finish_connect() stops it once the connection is fully ready. */
454  
455 72 ▶ if (getsockopt(self->fd, SOL_SOCKET, SO_ERROR, &err, &errlen) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (getsockopt(self->fd, SOL_SOCKET, SO_ERROR, &err, &errlen) < 0) 0 72 72
456 0 err = errno;
457 72 ▶ if (err != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (err != 0) { 2 70 72
458 char errbuf[256];
459 2 snprintf(errbuf, sizeof(errbuf), "connect: %s", strerror(err));
460 2 fail_connection(self, errbuf);
461 2 return;
462 }
463  
464 70 on_connect_done(self);
465 70 return;
466 }
467  
468 #ifdef HAVE_OPENSSL
469 108 ▶ if (self->ssl && !self->connected && self->native_state != NATIVE_WAIT_HELLO
Branch: 3 branches
BranchTrueFalseTotal
if (self->ssl && !self->connected && self->native_state != NATIVE_WAIT_HELLO 1 107 108
if (self->ssl && !self->connected && self->native_state != NATIVE_WAIT_HELLO 1 0 1
if (self->ssl && !self->connected && self->native_state != NATIVE_WAIT_HELLO 1 0 1
470 1 ▶ && self->native_state != NATIVE_WAIT_RESULT
Branch: 1 branch
BranchTrueFalseTotal
&& self->native_state != NATIVE_WAIT_RESULT 1 0 1
471 1 ▶ && self->native_state != NATIVE_WAIT_INSERT_META) {
Branch: 1 branch
BranchTrueFalseTotal
&& self->native_state != NATIVE_WAIT_INSERT_META) { 1 0 1
472 /* TLS handshake in progress */
473 1 int ret = SSL_connect(self->ssl);
474 1 ▶ if (ret == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret == 1) { 0 1 1
475 0 stop_reading(self);
476 0 stop_writing(self);
477  
478 0 ▶ if (self->protocol == PROTO_NATIVE) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE) { 0 0 0
479 /* Send ClientHello over TLS, then wait for ServerHello */
480 size_t hello_len;
481 0 char *hello = build_native_hello(self, &hello_len);
482 0 send_replace(self, hello, hello_len);
483 0 self->native_state = NATIVE_WAIT_HELLO;
484 0 start_writing(self);
485 0 return;
486 }
487  
488 /* HTTP protocol: fire on_connect */
489 0 (void)finish_connect(self);
490 0 return;
491 } else {
492 1 int err = SSL_get_error(self->ssl, ret);
493 1 stop_reading(self);
494 1 stop_writing(self);
495 1 ▶ if (err == SSL_ERROR_WANT_READ) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_READ) { 0 1 1
496 0 start_reading(self);
497 1 ▶ } else if (err == SSL_ERROR_WANT_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (err == SSL_ERROR_WANT_WRITE) { 0 1 1
498 0 start_writing(self);
499 } else {
500 1 ▶ if (err == SSL_ERROR_SYSCALL)
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_SYSCALL) 1 0 1
501 1 capture_tls_syscall_error(self, ret);
502 else
503 0 capture_tls_error(self);
504 1 fail_connection(self, "SSL handshake failed");
505 }
506 1 return;
507 }
508 }
509 #endif
510  
511 107 ▶ if (revents & EV_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (revents & EV_WRITE) { 27 80 107
512 27 ▶ if (try_write(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (try_write(self)) return; 0 27 27
513 27 ▶ if (self->fd < 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd < 0) return; 0 27 27
514 27 ▶ if (self->pending_addendum_finish && self->send_pos >= self->send_len) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->pending_addendum_finish && self->send_pos >= self->send_len) { 0 27 27
if (self->pending_addendum_finish && self->send_pos >= self->send_len) { 0 0 0
515 0 self->pending_addendum_finish = 0;
516 0 self->native_state = NATIVE_IDLE;
517 0 ▶ if (finish_connect(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (finish_connect(self)) return; 0 0 0
518 }
519 }
520  
521 107 ▶ if (revents & EV_READ) {
Branch: 1 branch
BranchTrueFalseTotal
if (revents & EV_READ) { 80 27 107
522 80 on_readable(self);
523 }
524 }
525  
526 10 static void timer_cb(EV_P_ ev_timer *w, int revents) {
527 10 ev_clickhouse_t *self = (ev_clickhouse_t *)w->data;
528 (void)loop;
529 (void)revents;
530  
531 10 ▶ if (self == NULL || self->magic != EV_CH_MAGIC) return;
Branch: 2 branches
BranchTrueFalseTotal
if (self == NULL || self->magic != EV_CH_MAGIC) return; 10 0 10
if (self == NULL || self->magic != EV_CH_MAGIC) return; 0 10 10
532  
533 10 self->timing = 0;
534  
535 /* Treat any pre-`connected=1` timeout as a connect timeout — covers
536 * TCP connect, TLS handshake, and native ServerHello stages. */
537 10 ▶ if (!self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) { 7 3 10
538 7 char *err = self->connect_err;
539 7 self->connect_err = NULL;
540 7 stop_writing(self);
541 7 ▶ fail_connection(self, err ? err : "connect timeout");
Branch: 1 branch
BranchTrueFalseTotal
fail_connection(self, err ? err : "connect timeout"); 1 6 7
542 7 Safefree(err);
543 } else {
544 /* query timeout */
545 3 ▶ CLEAR_SV(self->native_rows);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_rows); 0 3 3
546 3 ▶ CLEAR_SV(self->native_col_names);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_col_names); 0 3 3
547 3 ▶ CLEAR_SV(self->native_col_types);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_col_types); 0 3 3
548 3 ▶ CLEAR_SV(self->native_totals);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_totals); 0 3 3
549 3 ▶ CLEAR_SV(self->native_extremes);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_extremes); 0 3 3
550 3 lc_free_dicts(self);
551 3 ▶ CLEAR_INSERT(self); free_insert_default_state(self);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(self); free_insert_default_state(self); 0 3 3
CLEAR_INSERT(self); free_insert_default_state(self); 0 3 3
552 3 ▶ CLEAR_STR(self->insert_err);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->insert_err); 0 3 3
553 3 self->native_state = NATIVE_IDLE;
554 3 ▶ if (self->send_count > 0) self->send_count--;
Branch: 1 branch
BranchTrueFalseTotal
if (self->send_count > 0) self->send_count--; 3 0 3
555  
556 3 int gen = self->connect_gen;
557 /* Must reconnect — server may still be processing */
558 3 ▶ if (teardown_after_deliver(self, "query timeout", "query timeout")) return;
Branch: 1 branch
BranchTrueFalseTotal
if (teardown_after_deliver(self, "query timeout", "query timeout")) return; 0 3 3
559 3 ▶ if (self->connect_gen != gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; 0 3 3
560 3 ▶ if (self->auto_reconnect && self->host)
Branch: 2 branches
BranchTrueFalseTotal
if (self->auto_reconnect && self->host) 3 0 3
if (self->auto_reconnect && self->host) 3 0 3
561 3 schedule_reconnect(self);
562 }
563 }
564  
565 /* --- Keepalive timer callback --- */
566  
567 4 static void ka_timer_cb(EV_P_ ev_timer *w, int revents) {
568 4 ev_clickhouse_t *self = (ev_clickhouse_t *)((char *)w -
569 offsetof(ev_clickhouse_t, ka_timer));
570 (void)revents;
571  
572 4 ▶ if (self->magic != EV_CH_MAGIC) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC) return; 0 4 4
573 4 ▶ if (!self->connected || self->send_count > 0) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!self->connected || self->send_count > 0) return; 4 0 4
if (!self->connected || self->send_count > 0) return; 0 4 4
574  
575 /* Native: enqueue like the HTTP branch below rather than writing into
576 * send_buf, so a queued query can never overwrite the unsent ping and the
577 * PONG is matched to its callback by the normal response path. The send
578 * entry carries a deadline so a server that never PONGs is detected. */
579 4 ▶ if (self->protocol == PROTO_NATIVE) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE) { 0 4 4
580 size_t ping_len;
581 0 char *ping = build_native_ping(&ping_len);
582 0 ev_ch_send_t *s = alloc_send();
583 0 s->data = ping;
584 0 s->data_len = ping_len;
585 0 s->cb = SvREFCNT_inc(keepalive_noop_cb);
586 0 s->query_timeout = self->query_timeout > 0
587 0 ▶ ? self->query_timeout : self->keepalive;
Branch: 1 branch
BranchTrueFalseTotal
? self->query_timeout : self->keepalive; 0 0 0
588 0 enqueue_send(self, s);
589 } else {
590 /* HTTP: enqueue a real ping with a no-op callback. ClickHouse's
591 * HTTP server closes idle connections after a few seconds, so
592 * relying on TCP keepalive (kernel default ~2h) is not enough. */
593 size_t req_len;
594 4 char *req = build_http_ping_request(self, &req_len);
595 4 ev_ch_send_t *s = alloc_send();
596 4 s->data = req;
597 4 s->data_len = req_len;
598 4 s->cb = SvREFCNT_inc(keepalive_noop_cb);
599 8 s->query_timeout = self->query_timeout > 0
600 4 ▶ ? self->query_timeout : self->keepalive;
Branch: 1 branch
BranchTrueFalseTotal
? self->query_timeout : self->keepalive; 0 4 4
601 4 enqueue_send(self, s);
602 }
603 }
604  
605 75 static void start_keepalive(ev_clickhouse_t *self) {
606 75 ▶ if (self->keepalive > 0 && !self->ka_timing && self->connected) {
Branch: 3 branches
BranchTrueFalseTotal
if (self->keepalive > 0 && !self->ka_timing && self->connected) { 4 71 75
if (self->keepalive > 0 && !self->ka_timing && self->connected) { 4 0 4
if (self->keepalive > 0 && !self->ka_timing && self->connected) { 4 0 4
607 4 ev_now_update(self->loop);
608 4 ev_timer_init(&self->ka_timer, ka_timer_cb, self->keepalive, self->keepalive);
609 4 ev_timer_start(self->loop, &self->ka_timer);
610 4 self->ka_timing = 1;
611 }
612 75 }
613  
614 250 static void stop_keepalive(ev_clickhouse_t *self) {
615 250 ▶ if (self->ka_timing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ka_timing) { 4 246 250
616 4 ev_timer_stop(self->loop, &self->ka_timer);
617 4 self->ka_timing = 0;
618 }
619 250 }
620  
621 /* --- Reconnect with backoff --- */
622  
623 19 static void reconnect_timer_cb(EV_P_ ev_timer *w, int revents) {
624 19 ev_clickhouse_t *self = (ev_clickhouse_t *)((char *)w -
625 offsetof(ev_clickhouse_t, reconnect_timer));
626 (void)revents; (void)loop;
627 19 self->reconnect_timing = 0;
628 19 ▶ if (self->magic != EV_CH_MAGIC || self->connected || self->connecting) return;
Branch: 3 branches
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC || self->connected || self->connecting) return; 19 0 19
if (self->magic != EV_CH_MAGIC || self->connected || self->connecting) return; 19 0 19
if (self->magic != EV_CH_MAGIC || self->connected || self->connecting) return; 0 19 19
629 19 start_connect(self);
630 }
631  
632 20 static void schedule_reconnect(ev_clickhouse_t *self) {
633 20 ▶ if (!self->auto_reconnect || !self->host || self->magic != EV_CH_MAGIC) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!self->auto_reconnect || !self->host || self->magic != EV_CH_MAGIC) return; 20 0 20
if (!self->auto_reconnect || !self->host || self->magic != EV_CH_MAGIC) return; 20 0 20
if (!self->auto_reconnect || !self->host || self->magic != EV_CH_MAGIC) return; 0 20 20
634 20 ▶ if (self->reconnect_max_attempts > 0
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_max_attempts > 0 16 4 20
635 16 ▶ && self->reconnect_attempts >= self->reconnect_max_attempts) {
Branch: 1 branch
BranchTrueFalseTotal
&& self->reconnect_attempts >= self->reconnect_max_attempts) { 1 15 16
636 /* Give up so the user isn't trapped in an infinite loop on a
637 * permanent failure (bad host, wrong creds). Drain any queries
638 * still in send_queue first so their callbacks see the failure
639 * instead of being silently orphaned. */
640 1 int gen = self->connect_gen;
641 1 emit_error(self, "max reconnect attempts exceeded");
642 1 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 1 1
643 /* reset() from on_error won: the new generation owns the
644 * queues — failing them here would kill its queries. */
645 1 ▶ if (self->connect_gen != gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; 0 1 1
646 1 (void)cancel_pending(self, "max reconnect attempts exceeded", 1);
647 1 return;
648 }
649 /* Always defer through ev_timer so a synchronous start_connect failure
650 * (e.g. getaddrinfo error) cannot cause unbounded fail_connection ->
651 * schedule_reconnect -> start_connect recursion on the C stack. A
652 * delay of 0 fires on the next event-loop iteration, not inline. */
653 19 ▶ double delay = self->reconnect_delay > 0 ? self->reconnect_delay : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
double delay = self->reconnect_delay > 0 ? self->reconnect_delay : 0.0; 19 0 19
654 int i;
655 22 ▶ for (i = 0; i < self->reconnect_attempts && i < 20; i++)
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < self->reconnect_attempts && i < 20; i++) 3 19 22
for (i = 0; i < self->reconnect_attempts && i < 20; i++) 3 0 3
656 3 delay *= 2;
657 19 ▶ if (self->reconnect_max_delay > 0 && delay > self->reconnect_max_delay)
Branch: 2 branches
BranchTrueFalseTotal
if (self->reconnect_max_delay > 0 && delay > self->reconnect_max_delay) 0 19 19
if (self->reconnect_max_delay > 0 && delay > self->reconnect_max_delay) 0 0 0
658 0 delay = self->reconnect_max_delay;
659 /* Apply jitter AFTER the cap so a configured ceiling isn't silently
660 * exceeded. rand() / RAND_MAX is uniform in [0, 1]; clamping to the
661 * cap again keeps the worst case bounded. */
662 19 ▶ if (self->reconnect_jitter > 0 && delay > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->reconnect_jitter > 0 && delay > 0) { 0 19 19
if (self->reconnect_jitter > 0 && delay > 0) { 0 0 0
663 0 double j = ((double)rand() / (double)RAND_MAX) * self->reconnect_jitter;
664 0 delay += delay * j;
665 0 ▶ if (self->reconnect_max_delay > 0 && delay > self->reconnect_max_delay)
Branch: 2 branches
BranchTrueFalseTotal
if (self->reconnect_max_delay > 0 && delay > self->reconnect_max_delay) 0 0 0
if (self->reconnect_max_delay > 0 && delay > self->reconnect_max_delay) 0 0 0
666 0 delay = self->reconnect_max_delay;
667 }
668 19 self->reconnect_attempts++;
669 19 ▶ if (self->reconnect_timing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_timing) { 0 19 19
670 0 ev_timer_stop(self->loop, &self->reconnect_timer);
671 0 self->reconnect_timing = 0;
672 }
673 19 ev_now_update(self->loop);
674 19 ev_timer_init(&self->reconnect_timer, reconnect_timer_cb, delay, 0);
675 19 ev_timer_start(self->loop, &self->reconnect_timer);
676 19 self->reconnect_timing = 1;
677 }
678  
679 /* Free LowCardinality cross-block dictionary state */
680 171 static void lc_free_dicts(ev_clickhouse_t *self) {
681 171 ▶ if (self->lc_dicts) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->lc_dicts) { 0 171 171
682 int c;
683 0 ▶ for (c = 0; c < self->lc_num_cols; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < self->lc_num_cols; c++) { 0 0 0
684 0 ▶ if (self->lc_dicts[c]) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->lc_dicts[c]) { 0 0 0
685 uint64_t j;
686 0 ▶ for (j = 0; j < self->lc_dict_sizes[c]; j++)
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < self->lc_dict_sizes[c]; j++) 0 0 0
687 0 SvREFCNT_dec(self->lc_dicts[c][j]);
688 0 Safefree(self->lc_dicts[c]);
689 }
690 }
691 0 Safefree(self->lc_dicts);
692 0 Safefree(self->lc_dict_sizes);
693 0 self->lc_dicts = NULL;
694 0 self->lc_dict_sizes = NULL;
695 0 self->lc_num_cols = 0;
696 }
697 171 }
698  
699 /* --- Pipeline orchestrator --- */
700  
701 /* Send one request at a time, wait for response, then send the next.
702 * Returns 1 if self was freed (caller must not access self). */
703 61 static int pipeline_advance(ev_clickhouse_t *self) {
704 61 ▶ if (!self->connected || self->in_dispatch) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!self->connected || self->in_dispatch) return 0; 61 0 61
if (!self->connected || self->in_dispatch) return 0; 0 61 61
705  
706 61 ▶ if (self->send_count > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->send_count > 0) { 61 0 61
707 0 start_reading(self);
708 0 return 0;
709 }
710  
711 /* A cancel() from on_query_start drops the staged entry below and
712 * loops back here so the next queued query dispatches instead of
713 * stranding. Each iteration shrinks the queue or dispatches, so
714 * the loop terminates. */
715 62 again:
716  
717 /* Check drain callback when all pending work is done */
718 62 ▶ if (ngx_queue_empty(&self->send_queue) && self->pending_count == 0
Branch: 2 branches
BranchTrueFalseTotal
if (ngx_queue_empty(&self->send_queue) && self->pending_count == 0 13 49 62
if (ngx_queue_empty(&self->send_queue) && self->pending_count == 0 13 0 13
719 13 ▶ && self->on_drain) {
Branch: 1 branch
BranchTrueFalseTotal
&& self->on_drain) { 0 13 13
720 0 SV *drain_cb = self->on_drain;
721 0 self->on_drain = NULL;
722 0 ▶ if (fire_zero_arg_cb(self, drain_cb, "drain")) {
Branch: 1 branch
BranchTrueFalseTotal
if (fire_zero_arg_cb(self, drain_cb, "drain")) { 0 0 0
723 0 SvREFCNT_dec(drain_cb);
724 0 return 1;
725 }
726 /* Dropping the last ref to the drain CV can free a closure that
727 * captured $ch — DESTROY then runs. Guard with callback_depth so
728 * the free is deferred, then detect it before touching self. */
729 0 self->callback_depth++;
730 0 SvREFCNT_dec(drain_cb);
731 0 self->callback_depth--;
732 0 ▶ if (check_destroyed(self)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return 1; 0 0 0
733 }
734  
735 /* Restart keepalive timer when idle (start_keepalive is a no-op if already
736 * timing or if keepalive disabled) */
737 62 ▶ if (ngx_queue_empty(&self->send_queue) && self->pending_count == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (ngx_queue_empty(&self->send_queue) && self->pending_count == 0) 13 49 62
if (ngx_queue_empty(&self->send_queue) && self->pending_count == 0) 13 0 13
738 13 start_keepalive(self);
739  
740 /* send next request from queue */
741 62 ▶ if (!ngx_queue_empty(&self->send_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ngx_queue_empty(&self->send_queue)) { 49 13 62
742 /* Stop keepalive during active query */
743 49 stop_keepalive(self);
744 49 emit_trace(self, "dispatch query (pending=%d)", self->pending_count);
745  
746 /* on_trace is user code: it may have called finish()/reset() or
747 * dropped the last reference (DESTROY), any of which drains or
748 * frees the send queue. Re-validate the connection and re-derive
749 * the head entry AFTER the trace so we never touch a send struct
750 * that cancel_pending has already released to the freelist. */
751 49 ▶ if (self->magic != EV_CH_MAGIC || !self->connected
Branch: 2 branches
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC || !self->connected 49 0 49
if (self->magic != EV_CH_MAGIC || !self->connected 49 0 49
752 49 ▶ || ngx_queue_empty(&self->send_queue))
Branch: 1 branch
BranchTrueFalseTotal
|| ngx_queue_empty(&self->send_queue)) 0 49 49
753 0 return check_destroyed(self);
754  
755 49 ngx_queue_t *q = ngx_queue_head(&self->send_queue);
756 49 ev_ch_send_t *send = ngx_queue_data(q, ev_ch_send_t, queue);
757  
758 49 ▶ if (send->deferred_sql) {
Branch: 1 branch
BranchTrueFalseTotal
if (send->deferred_sql) { 0 49 49
759 /* Pre-connect native entry: build now that server_revision
760 * is known. On old servers with query parameters the build
761 * fails — fail just this entry, the rest still dispatch. */
762 char *req;
763 size_t req_len;
764 /* The build stringifies stashed setting SVs: overload/tie
765 * runs arbitrary Perl that may destroy/reset/finish/cancel
766 * this connection, freeing the send entry and its inputs
767 * mid-build. Hold local refs/copies across the call, then
768 * re-validate everything before touching send/self. */
769 0 size_t dsql_len = send->deferred_sql_len;
770 char *dsql;
771 0 HV *ddef = send->deferred_defaults;
772 0 HV *dovr = send->deferred_overrides;
773 0 size_t dext_len = send->deferred_ext_len;
774 0 char *dext = NULL;
775 /* Counted copies (ext is a binary blob, not NUL-terminated). */
776 0 Newx(dsql, dsql_len + 1, char);
777 0 Copy(send->deferred_sql, dsql, dsql_len, char);
778 0 dsql[dsql_len] = '\0';
779 0 ▶ if (send->deferred_ext) {
Branch: 1 branch
BranchTrueFalseTotal
if (send->deferred_ext) { 0 0 0
780 0 ▶ Newx(dext, dext_len ? dext_len : 1, char);
Branch: 1 branch
BranchTrueFalseTotal
Newx(dext, dext_len ? dext_len : 1, char); 0 0 0
781 0 Copy(send->deferred_ext, dext, dext_len, char);
782 }
783 0 int gen0 = self->connect_gen;
784 0 ▶ if (ddef) SvREFCNT_inc((SV *)ddef);
Branch: 1 branch
BranchTrueFalseTotal
if (ddef) SvREFCNT_inc((SV *)ddef); 0 0 0
785 0 ▶ if (dovr) SvREFCNT_inc((SV *)dovr);
Branch: 1 branch
BranchTrueFalseTotal
if (dovr) SvREFCNT_inc((SV *)dovr); 0 0 0
786 0 self->callback_depth++;
787 0 req = build_native_query(self, dsql, dsql_len, ddef, dovr,
788 dext, dext_len, &req_len);
789 /* Drop pins BEFORE depth-- (a setting holding the last
790 * $ch ref must DESTROY into depth>0). */
791 0 ▶ if (ddef) SvREFCNT_dec((SV *)ddef);
Branch: 1 branch
BranchTrueFalseTotal
if (ddef) SvREFCNT_dec((SV *)ddef); 0 0 0
792 0 ▶ if (dovr) SvREFCNT_dec((SV *)dovr);
Branch: 1 branch
BranchTrueFalseTotal
if (dovr) SvREFCNT_dec((SV *)dovr); 0 0 0
793 0 Safefree(dsql);
794 0 ▶ if (dext) Safefree(dext);
Branch: 1 branch
BranchTrueFalseTotal
if (dext) Safefree(dext); 0 0 0
795 0 self->callback_depth--;
796 0 ▶ if (self->magic != EV_CH_MAGIC) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC) { 0 0 0
797 0 ▶ if (req) Safefree(req);
Branch: 1 branch
BranchTrueFalseTotal
if (req) Safefree(req); 0 0 0
798 0 check_destroyed(self);
799 0 return 1;
800 }
801 {
802 /* reset()/finish() own the queue now; cancel() already
803 * failed the entry. Either way our send is gone. */
804 ngx_queue_t *qq;
805 0 int still_queued = 0;
806 0 ▶ if (self->connect_gen == gen0 && self->connected) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->connect_gen == gen0 && self->connected) { 0 0 0
if (self->connect_gen == gen0 && self->connected) { 0 0 0
807 0 for (qq = ngx_queue_head(&self->send_queue);
808 0 ▶ qq != ngx_queue_sentinel(&self->send_queue);
Branch: 1 branch
BranchTrueFalseTotal
qq != ngx_queue_sentinel(&self->send_queue); 0 0 0
809 0 qq = ngx_queue_next(qq)) {
810 0 ▶ if (qq == q) { still_queued = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (qq == q) { still_queued = 1; break; } 0 0 0
811 }
812 }
813 0 ▶ if (!still_queued) {
Branch: 1 branch
BranchTrueFalseTotal
if (!still_queued) { 0 0 0
814 0 ▶ if (req) Safefree(req);
Branch: 1 branch
BranchTrueFalseTotal
if (req) Safefree(req); 0 0 0
815 0 return 0;
816 }
817 }
818 0 free_send_deferred(send);
819 0 ▶ if (!req) {
Branch: 1 branch
BranchTrueFalseTotal
if (!req) { 0 0 0
820 0 SV *fail_cb = send->cb;
821 0 SV *fail_oqc = send->on_complete;
822 char errmsg[64];
823 0 int gen0 = self->connect_gen;
824 0 unsigned seq0 = self->dispatch_seq;
825 /* Adopt the failed entry's own query_id for the fire so
826 * on_query_complete doesn't report a stale earlier id
827 * (same idiom as cancel_pending). */
828 0 char *qid0 = self->last_query_id;
829 0 self->last_query_id = send->query_id;
830 0 send->query_id = NULL;
831 0 send->on_complete = NULL;
832 0 ngx_queue_remove(q);
833 0 ▶ CLEAR_INSERT(send);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(send); 0 0 0
CLEAR_INSERT(send); 0 0 0
834 0 ▶ CLEAR_SV(send->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(send->on_data); 0 0 0
835 0 release_send(send);
836 0 self->pending_count--;
837 0 snprintf(errmsg, sizeof(errmsg),
838 "query parameters require server revision >= %d",
839 DBMS_MIN_REVISION_WITH_PARAMETERS);
840 0 self->callback_depth++;
841 0 self->force_zero_dur = 1;
842 0 fire_err_and_complete(self, fail_cb, errmsg, fail_oqc);
843 0 self->force_zero_dur = 0;
844 0 self->callback_depth--;
845 0 ▶ if (check_destroyed(self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) { 0 0 0
846 /* Adopted id died with the struct; ours to free. */
847 0 ▶ if (qid0) Safefree(qid0);
Branch: 1 branch
BranchTrueFalseTotal
if (qid0) Safefree(qid0); 0 0 0
848 0 return 1;
849 }
850 0 ▶ if (self->dispatch_seq == seq0 && self->connect_gen == gen0) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->dispatch_seq == seq0 && self->connect_gen == gen0) { 0 0 0
if (self->dispatch_seq == seq0 && self->connect_gen == gen0) { 0 0 0
851 0 ▶ CLEAR_STR(self->last_query_id);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->last_query_id); 0 0 0
852 0 self->last_query_id = qid0;
853 0 ▶ } else if (qid0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (qid0) { 0 0 0
854 0 Safefree(qid0);
855 }
856 /* A reset() from the handler owns the queue now — the
857 * inner frame dispatches it (same as cancel_pending). */
858 0 ▶ if (self->connect_gen != gen0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen0) return 0; 0 0 0
859 0 goto again;
860 }
861 0 send->data = req;
862 0 send->data_len = req_len;
863 }
864  
865 /* set up send buffer */
866 49 ensure_send_cap(self, send->data_len);
867 49 Copy(send->data, self->send_buf, send->data_len, char);
868 49 self->send_len = send->data_len;
869 49 self->send_pos = 0;
870  
871 /* move cb to recv queue */
872 49 SV *dispatched_cb = send->cb;
873 49 ngx_queue_remove(q);
874 49 push_cb_owned_ex(self, send->cb, send->raw,
875 send->on_data, send->on_complete,
876 send->query_timeout);
877 49 ▶ CLEAR_SV(send->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(send->on_data); 0 49 49
878 49 send->on_complete = NULL; /* ownership transferred to cbt */
879 /* Track query_id + dispatch start time (used by on_query_complete). */
880 49 ▶ CLEAR_STR(self->last_query_id);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->last_query_id); 1 48 49
881 49 ▶ if (send->query_id) { self->last_query_id = send->query_id; send->query_id = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (send->query_id) { self->last_query_id = send->query_id; send->query_id = NULL; } 2 47 49
882 49 ▶ CLEAR_STR(self->query_session_tz);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->query_session_tz); 0 49 49
883 49 self->query_session_tz = send->session_tz;
884 49 send->session_tz = NULL;
885 49 ev_now_update(self->loop);
886 49 self->query_start_time = ev_now(self->loop);
887 49 self->dispatch_seq++;
888  
889 /* on_query_start: fire with the resolved query_id, just before
890 * the write side runs. Suppressed for keepalive PINGs to match
891 * on_query_complete semantics. */
892 49 ▶ if (self->on_query_start && !IS_KEEPALIVE_CB(dispatched_cb)) {
Branch: 3 branches
BranchTrueFalseTotal
if (self->on_query_start && !IS_KEEPALIVE_CB(dispatched_cb)) { 2 47 49
if (self->on_query_start && !IS_KEEPALIVE_CB(dispatched_cb)) { 2 0 2
if (self->on_query_start && !IS_KEEPALIVE_CB(dispatched_cb)) { 2 0 2
893 2 dSP;
894 2 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 2 2
895 2 ▶ EXTEND(SP, 1);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 1); 0 2 2
896 2 ▶ PUSHs(self->last_query_id
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(self->last_query_id 2 0 2
897 ? sv_2mortal(newSVpv(self->last_query_id, 0))
898 : &PL_sv_undef);
899 2 PUTBACK;
900 2 int gen_before = self->connect_gen;
901 2 self->callback_depth++;
902 /* Visible to cancel(): the entry is dequeued (and its bytes
903 * staged in send_buf) but send_count isn't bumped yet. */
904 2 self->in_dispatch = 1;
905 2 PINNED_CALL_SV(self->on_query_start, G_EVAL | G_VOID | G_DISCARD);
906 2 self->in_dispatch = 0;
907 2 self->callback_depth--;
908 2 ▶ WARN_AND_CLEAR_ERRSV("on_query_start");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("on_query_start"); 2 0 2
WARN_AND_CLEAR_ERRSV("on_query_start"); 0 2 2
WARN_AND_CLEAR_ERRSV("on_query_start"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_query_start"); 0 0 0
909 2 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 2 0 2
910 /* The handler may have torn the connection down: DESTROY
911 * (dropped the last ref), reset() (rotated it — connect_gen
912 * bumped), or finish() (closed it — connected cleared). In
913 * every case the cb was already delivered by cancel_pending;
914 * drop the local send entry (already dequeued, so cancel_pending
915 * never saw it) without dispatching it. Falling through on a
916 * !connected struct would re-arm a stray query-timeout timer
917 * and leave send_count stuck at 1. The `||` short-circuits
918 * before reading self->connect_gen when self has been freed. */
919 2 int destroyed = check_destroyed(self);
920 2 ▶ if (destroyed || self->connect_gen != gen_before
Branch: 2 branches
BranchTrueFalseTotal
if (destroyed || self->connect_gen != gen_before 2 0 2
if (destroyed || self->connect_gen != gen_before 2 0 2
921 2 ▶ || !self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
|| !self->connected) { 0 2 2
922 0 Safefree(send->data);
923 0 ▶ CLEAR_INSERT(send);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(send); 0 0 0
CLEAR_INSERT(send); 0 0 0
924 0 release_send(send);
925 /* A nested cancel() may have armed this before the
926 * handler tore the connection down — don't let the
927 * stale flag drop a healthy later dispatch. (When
928 * destroyed, self is already freed: touch nothing.) */
929 0 ▶ if (!destroyed)
Branch: 1 branch
BranchTrueFalseTotal
if (!destroyed) 0 0 0
930 0 self->dispatch_cancelled = 0;
931 0 return destroyed ? 1 : 0;
932 }
933 2 ▶ if (self->dispatch_cancelled) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->dispatch_cancelled) { 1 1 2
934 /* cancel() from on_query_start: the callback was
935 * already failed with "query cancelled" — drop the
936 * staged entry without writing anything and take the
937 * next queued query. */
938 1 self->dispatch_cancelled = 0;
939 1 Safefree(send->data);
940 1 ▶ CLEAR_INSERT(send);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(send); 0 1 1
CLEAR_INSERT(send); 0 1 1
941 1 release_send(send);
942 1 goto again;
943 }
944 }
945  
946 /* Clear per-query accumulated state so accessors don't return
947 * the previous query's data. native_rows is already NULL at
948 * EndOfStream; col_names/types are also cleared here so DDL
949 * (or any query that emits no DATA block) does not leave the
950 * previous SELECT's schema visible. */
951 48 ▶ CLEAR_SV(self->native_col_names);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_col_names); 0 48 48
952 48 ▶ CLEAR_SV(self->native_col_types);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_col_types); 0 48 48
953 48 ▶ CLEAR_SV(self->native_totals);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_totals); 0 48 48
954 48 ▶ CLEAR_SV(self->native_extremes);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_extremes); 0 48 48
955 48 self->cancelled = 0;
956 48 self->last_error_code = 0;
957 48 self->profile_rows = 0;
958 48 self->profile_bytes = 0;
959 48 self->profile_rows_before_limit = 0;
960 48 ▶ if (self->progress_period > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->progress_period > 0) { 0 48 48
961 0 memset(self->progress_acc, 0, sizeof(self->progress_acc));
962 0 self->progress_last = 0.0;
963 }
964  
965 /* transfer deferred insert data from send entry to self */
966 48 ▶ if (send->insert_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (send->insert_data) { 0 48 48
967 0 self->insert_data = send->insert_data;
968 0 self->insert_data_len = send->insert_data_len;
969 0 self->insert_native_body = send->insert_native_body;
970 0 send->insert_data = NULL;
971 }
972 48 ▶ if (send->insert_av) {
Branch: 1 branch
BranchTrueFalseTotal
if (send->insert_av) { 16 32 48
973 16 self->insert_av = send->insert_av;
974 16 send->insert_av = NULL;
975 }
976 48 ▶ if (send->insert_empty_as_default)
Branch: 1 branch
BranchTrueFalseTotal
if (send->insert_empty_as_default) 0 48 48
977 0 self->insert_empty_as_default = 1;
978 48 ▶ if (send->insert_defaults) {
Branch: 1 branch
BranchTrueFalseTotal
if (send->insert_defaults) { 0 48 48
979 0 self->insert_defaults = send->insert_defaults;
980 0 send->insert_defaults = NULL;
981 }
982  
983 48 Safefree(send->data);
984 48 double qt = send->query_timeout;
985 48 release_send(send);
986 48 self->send_count++;
987  
988 /* Start query timeout timer */
989 48 ▶ double timeout = qt > 0 ? qt : self->query_timeout;
Branch: 1 branch
BranchTrueFalseTotal
double timeout = qt > 0 ? qt : self->query_timeout; 4 44 48
990 48 ▶ if (timeout > 0 && !self->timing) {
Branch: 2 branches
BranchTrueFalseTotal
if (timeout > 0 && !self->timing) { 4 44 48
if (timeout > 0 && !self->timing) { 4 0 4
991 4 ev_timer_set(&self->timer, (ev_tstamp)timeout, 0.0);
992 4 ev_timer_start(self->loop, &self->timer);
993 4 self->timing = 1;
994 }
995  
996 48 ▶ if (self->protocol == PROTO_NATIVE) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE) { 18 30 48
997 18 ▶ if (self->insert_data || self->insert_av)
Branch: 2 branches
BranchTrueFalseTotal
if (self->insert_data || self->insert_av) 18 0 18
if (self->insert_data || self->insert_av) 16 2 18
998 16 self->native_state = NATIVE_WAIT_INSERT_META;
999 else
1000 2 self->native_state = NATIVE_WAIT_RESULT;
1001 }
1002  
1003 48 return try_write(self);
1004 }
1005 13 return 0;
1006 }
1007  
1008 /* --- OpenSSL init (must be in plain C, not inside XS BOOT) --- */
1009  
1010 81 static void ch_openssl_init(void) {
1011 #ifdef HAVE_OPENSSL
1012 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1013 81 OPENSSL_init_ssl(0, NULL);
1014 #else
1015 SSL_library_init();
1016 SSL_load_error_strings();
1017 OpenSSL_add_all_algorithms();
1018 #endif
1019 #endif
1020 81 }
« xs/proto_http.c ↑ Summary xs/queues.c »