Nats.xs

filter: Statementstmt 81.9% 1610 / 1965 Branchbran 62.4% 1055 / 1690 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 72.9% 2665 / 3655 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/EV/Nats.pm ↑ Summary
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4 #include "ppport.h"
5  
6 #include "EVAPI.h"
7 #include "ngx-queue.h"
8  
9 #include <sys/socket.h>
10 #include <sys/un.h>
11 #include <netinet/in.h>
12 #include <netinet/tcp.h>
13 #include <netdb.h>
14 #include <fcntl.h>
15 #include <errno.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <time.h>
20 #include <arpa/inet.h>
21  
22 /* Makefile.PL defines this from $EV::Nats::VERSION so the two cannot drift */
23 #ifndef EV_NATS_VERSION
24 #define EV_NATS_VERSION "0.00"
25 #endif
26  
27 #ifdef HAVE_OPENSSL
28 #include <openssl/ssl.h>
29 #include <openssl/err.h>
30 #include <openssl/x509v3.h>
31 #include <openssl/rand.h>
32 #endif
33  
34 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) \
35 || defined(__NetBSD__) || defined(__DragonFly__)
36 #define NATS_HAVE_ARC4RANDOM 1
37 #endif
38  
39 /* ================================================================
40 * Constants
41 * ================================================================ */
42  
43  
44 #define BUF_INIT_SIZE 16384
45 #define MAX_CONTROL_LINE 4096
46  
47 #define DEFAULT_MAX_PAYLOAD (1024 * 1024)
48 #define MAX_SERVER_POOL 64
49  
50 /* user inbox_prefix limit; the stored prefix adds ".<16 hex>." */
51 #define MAX_INBOX_BASE 64
52 #define INBOX_PREFIX_SIZE (MAX_INBOX_BASE + 20)
53 /* an inbox: the prefix plus a decimal uint64 */
54 #define INBOX_SUBJ_SIZE (INBOX_PREFIX_SIZE + 24)
55  
56 #define MAX_INBOUND_LINE (64 * 1024) /* INFO grows with connect_urls */
57 #define MAX_INBOUND_MSG (64 * 1024 * 1024) /* JetStream replies exceed max_payload */
58  
59 #define MSG_TYPE_MSG 0
60 #define MSG_TYPE_HMSG 1
61  
62 #define CLEAR_HANDLER(field) \
63 do { if (NULL != (field)) { SvREFCNT_dec(field); (field) = NULL; } } while(0)
64  
65 /* Taken before firing: a drain_cb that disconnects must not find it still
66 armed and recurse into cleanup. */
67 #define nats_fire_drain(self, err) \
68 STMT_START { SV *_dcb = (self)->drain_cb; \
69 if (_dcb) { (self)->drain_cb = NULL; nats_call_str((self), _dcb, 0, (err)); \
70 SvREFCNT_dec(_dcb); } } STMT_END
71  
72 /* a connection is on its way: writes queue until the handshake */
73 #define NATS_PENDING(self) \
74 ((self)->connecting || ((self)->reconnect_enabled && (self)->reconnect_timer_active))
75  
76  
77 #define NATS_CROAK_UNLESS_CONNECTED(self) \
78 do { \
79 if (!(self)->connected && !NATS_PENDING(self)) \
80 croak("not connected"); \
81 } while(0)
82  
83 /* ================================================================
84 * Type declarations
85 * ================================================================ */
86  
87 typedef struct nats_s nats_t;
88 typedef struct nats_sub_s nats_sub_t;
89 typedef struct nats_pub_s nats_pub_t;
90  
91 typedef nats_t* EV__Nats;
92  
93 static HV *nats_stash;
94  
95 /* T_NATS: the stash test is the fast path; subclasses take sv_derived_from */
96 631 static nats_t *nats_self(pTHX_ SV *arg)
97 {
98 631 ▶ if (SvROK(arg) && SvOBJECT(SvRV(arg))
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(arg) && SvOBJECT(SvRV(arg)) 631 0 631
if (SvROK(arg) && SvOBJECT(SvRV(arg)) 631 0 631
99 631 ▶ && (SvSTASH(SvRV(arg)) == nats_stash || sv_derived_from(arg, "EV::Nats"))) {
Branch: 2 branches
BranchTrueFalseTotal
&& (SvSTASH(SvRV(arg)) == nats_stash || sv_derived_from(arg, "EV::Nats"))) { 2 629 631
&& (SvSTASH(SvRV(arg)) == nats_stash || sv_derived_from(arg, "EV::Nats"))) { 1 1 2
100 630 nats_t *self = INT2PTR(nats_t *, SvIV(SvRV(arg)));
101 630 ▶ if (!self)
Branch: 1 branch
BranchTrueFalseTotal
if (!self) 1 629 630
102 1 croak("EV::Nats: object already destroyed");
103 629 return self;
104 }
105 1 croak("EV::Nats: not an EV::Nats object");
106 return NULL;
107 }
108  
109 /* ================================================================
110 * Data structures
111 * ================================================================ */
112  
113 struct nats_sub_s {
114 uint64_t sid;
115 SV *subject;
116 SV *queue_group;
117 SV *cb;
118 int max_msgs;
119 int received;
120 ngx_queue_t queue;
121 };
122  
123 /* one per client-sent PING, so the FIFO stays 1:1 with PONGs; PONG_DRAIN_LAST
124 fences what callbacks published while the drain's PONG was on its way */
125 enum { PONG_FLUSH, PONG_DRAIN, PONG_DRAIN_LAST, PONG_INTERNAL };
126 typedef struct nats_pong_cb_s {
127 SV *cb; /* PONG_FLUSH only; NULL for a cb-less flush */
128 int kind;
129 ngx_queue_t queue;
130 } nats_pong_cb_t;
131  
132 typedef struct nats_server_s {
133 char *host;
134 int port;
135 int implicit; /* learned from connect_urls, pruned once unadvertised */
136 int seen;
137 ngx_queue_t queue;
138 } nats_server_t;
139  
140 struct nats_pub_s {
141 char *data;
142 size_t len;
143 uint64_t req_id; /* the request this PUB carries, 0 for a publish */
144 ngx_queue_t queue;
145 };
146  
147 struct nats_s {
148 struct ev_loop *loop;
149 int fd;
150 int connected;
151 int connecting;
152 int connect_pending; /* nonblocking connect(2) still in flight */
153 int connect_sent; /* CONNECT, with every SUB, is in the write buffer */
154 unsigned conn_gen; /* bumped per socket: a callback may replace it */
155  
156 ev_io rio, wio;
157 int reading, writing;
158  
159 char *rbuf;
160 size_t rbuf_len, rbuf_cap;
161 size_t rbuf_off; /* parsed up to here; committed before each callback */
162  
163 char *wbuf;
164 size_t wbuf_len, wbuf_off, wbuf_cap;
165  
166 SV *on_error;
167 SV *on_connect;
168 SV *on_disconnect;
169 char *pending_croak; /* no-on_error error, fired at wrapper exit */
170 SV *pending_die; /* a callback's die, rethrown at wrapper exit */
171  
172 ngx_queue_t subs;
173 HV *sub_map; /* raw sid bytes -> nats_sub_t* */
174 uint64_t next_sid;
175  
176 ngx_queue_t wait_queue;
177 int waiting_count;
178 size_t wait_bytes; /* queued bytes, capped by reconnect_buf_size */
179 size_t reconnect_buf_size; /* 0 = unlimited */
180  
181 ev_prepare prepare_watcher;
182 int prepare_active;
183 int wbuf_dirty;
184  
185 char *host;
186 int port;
187 char *path; /* Unix socket path */
188  
189 /* getaddrinfo candidates kept across async connect failures for failover */
190 struct addrinfo *ai_res; /* the list to freeaddrinfo */
191 struct addrinfo *ai_next; /* next candidate to try */
192  
193 int reconnect_enabled;
194 int reconnect_delay_ms;
195 int max_reconnect_delay_ms;
196 int max_reconnect_attempts;
197 int reconnect_attempts;
198 ev_timer reconnect_timer;
199 int reconnect_timer_active;
200 int intentional_disconnect;
201  
202 int connect_timeout_ms;
203 ev_timer connect_timer;
204 int connect_timer_active;
205  
206 int ping_interval_ms;
207 ev_timer ping_timer;
208 int ping_timer_active;
209 int pings_outstanding;
210 int max_pings_outstanding;
211  
212 int max_payload;
213 SV *server_info_json;
214  
215 char *user;
216 char *pass;
217 char *token;
218 char *name;
219 int verbose;
220 int pedantic;
221 int echo;
222 int no_responders;
223  
224 char inbox_prefix[INBOX_PREFIX_SIZE];
225 /* new_inbox's own token: the request wildcard must not match it */
226 char user_inbox_prefix[INBOX_PREFIX_SIZE];
227 uint64_t next_req_id;
228 ngx_queue_t req_queue;
229 uint64_t inbox_sub_sid;
230  
231 /* one-shot internal callbacks fired when the connection drops */
232 ngx_queue_t disc_watch;
233 uint64_t next_watch_id;
234  
235 int msg_type;
236 /* MSG/HMSG fields: absolute offsets into rbuf (safe across Renew) */
237 size_t msg_subject_off;
238 size_t msg_subject_len;
239 size_t msg_reply_off; /* msg_reply_len == 0 means no reply */
240 size_t msg_reply_len;
241 uint64_t msg_sid;
242 size_t msg_hdr_len;
243 size_t msg_total_len;
244  
245 int priority;
246 int keepalive;
247  
248 UV msgs_in;
249 UV msgs_out;
250 UV bytes_in;
251 UV bytes_out;
252  
253 ngx_queue_t server_pool;
254 int server_pool_count;
255  
256 int draining;
257 SV *drain_cb;
258  
259 size_t slow_consumer_bytes; /* wbuf threshold, 0 = disabled */
260 SV *on_slow_consumer;
261 int slow_fired;
262  
263 int batch_mode;
264  
265 ngx_queue_t pong_cbs;
266 /* flushes made before the handshake completed; PINGed after it */
267 ngx_queue_t flush_wait;
268  
269 char *nkey_seed; /* base32 */
270 char *jwt;
271 char *server_nonce;
272  
273 int ldm; /* lame duck mode */
274 SV *on_ldm;
275  
276 /* Deferred destroy: DESTROY inside an event-loop callback only sets
277 destroy_pending; the outermost nats_on_* wrapper frees (cb_depth) */
278 int cb_depth;
279 int destroy_pending;
280 /* Borrowed owner referent; pinned across method-reachable user
281 callbacks so DESTROY cannot free self mid-method. */
282 SV *owner_sv;
283  
284 #ifdef HAVE_OPENSSL
285 SSL_CTX *ssl_ctx;
286 SSL *ssl;
287 int tls;
288 int tls_skip_verify;
289 char *tls_ca_file;
290 int ssl_handshaking;
291 int ssl_write_len;
292 #endif
293 SV *loop_sv;
294 };
295  
296 typedef struct nats_req_s {
297 uint64_t req_id;
298 nats_t *nats;
299 SV *cb;
300 ev_timer timer;
301 int timer_active;
302 int queued; /* PUB still in wait_queue, not yet on a socket */
303 ngx_queue_t queue;
304 } nats_req_t;
305  
306 typedef struct nats_watch_s {
307 uint64_t id;
308 SV *cb;
309 ngx_queue_t queue;
310 } nats_watch_t;
311  
312 /* ================================================================
313 * Forward declarations
314 * ================================================================ */
315  
316 static void nats_connect_tcp(nats_t *self);
317 static void nats_connect_unix(nats_t *self);
318 static void nats_free_addrinfo(nats_t *self);
319 static void nats_do_connect(nats_t *self);
320 static void nats_schedule_reconnect(nats_t *self);
321 static void nats_next_server(nats_t *self);
322 static void nats_free_server_pool(nats_t *self);
323 static void nats_on_read(struct ev_loop *loop, ev_io *w, int revents);
324 static void nats_on_prepare(struct ev_loop *loop, ev_prepare *w, int revents);
325 static void nats_parse_connect_urls(nats_t *self, const char *json, size_t len);
326 static void nats_on_write(struct ev_loop *loop, ev_io *w, int revents);
327 static void nats_on_connect_timeout(struct ev_loop *loop, ev_timer *w, int revents);
328 static void nats_on_reconnect_timer(struct ev_loop *loop, ev_timer *w, int revents);
329 static void nats_on_ping_timer(struct ev_loop *loop, ev_timer *w, int revents);
330 static int nats_send_connect(nats_t *self);
331 static void nats_try_write(nats_t *self);
332 static void nats_schedule_write(nats_t *self);
333 static void nats_process_line(nats_t *self, char *line, size_t len);
334 static void nats_parse(nats_t *self);
335 static void nats_process_msg(nats_t *self, char *payload, size_t len);
336 static void nats_emit_error(nats_t *self, const char *err);
337 static void nats_fail(nats_t *self, const char *err);
338 static void nats_cleanup(nats_t *self);
339 static void nats_destroy_now(nats_t *self);
340 static void nats_start_ping_timer(nats_t *self);
341 static void nats_drain_waiting(nats_t *self);
342 static void nats_setup_inbox(nats_t *self, const char *base);
343 static nats_sub_t *nats_find_sub(nats_t *self, uint64_t sid);
344 static void nats_remove_sub(nats_t *self, nats_sub_t *sub);
345 static void nats_cancel_requests(nats_t *self, const char *err, int queued);
346 static void nats_unqueue_requests(nats_t *self, uint64_t req_id);
347 static void nats_resub_all(nats_t *self);
348  
349 /* Call a callback whose args are pushed, inside an ENTER/LEAVE. The pin lets
350 it clear its own handler. Under a watcher a die is held until the wrapper
351 has finished its bookkeeping, then rethrown; from a method it propagates. */
352 357 static void nats_invoke(nats_t *self, SV *cb)
353 {
354 357 SV *pin = SvREFCNT_inc_simple_NN(cb);
355 357 SAVEFREESV(pin);
356 357 ▶ if (self->cb_depth == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->cb_depth == 0) { 12 345 357
357 12 call_sv(pin, G_DISCARD);
358 12 return;
359 }
360 345 call_sv(pin, G_DISCARD | G_EVAL);
361 345 ▶ if (SvTRUE(ERRSV) && !self->pending_die)
Branch: 3 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV) && !self->pending_die) 345 0 345
if (SvTRUE(ERRSV) && !self->pending_die) 6 339 345
if (SvTRUE(ERRSV) && !self->pending_die) 6 0 6
362 6 ▶ self->pending_die = newSVsv(ERRSV);
Branch: 1 branch
BranchTrueFalseTotal
self->pending_die = newSVsv(ERRSV); 6 0 6
363 }
364  
365 98 static void nats_call0(nats_t *self, SV *cb)
366 {
367 98 dSP;
368 98 ENTER; SAVETMPS;
369 98 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 98 98
370 98 PUTBACK;
371 98 nats_invoke(self, cb);
372 98 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 98 98
373 98 }
374  
375 /* cb->([undef,] $str), $str undef when str is NULL */
376 172 static void nats_call_str(nats_t *self, SV *cb, int lead_undef, const char *str)
377 {
378 172 dSP;
379 172 ENTER; SAVETMPS;
380 172 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 172 172
381 172 ▶ EXTEND(SP, 2);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 2); 0 172 172
382 172 ▶ if (lead_undef)
Branch: 1 branch
BranchTrueFalseTotal
if (lead_undef) 36 136 172
383 36 PUSHs(&PL_sv_undef);
384 172 ▶ PUSHs(str ? sv_2mortal(newSVpv(str, 0)) : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(str ? sv_2mortal(newSVpv(str, 0)) : &PL_sv_undef); 158 14 172
385 172 PUTBACK;
386 172 nats_invoke(self, cb);
387 172 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 158 14 172
388 172 }
389  
390 /* ================================================================
391 * String helpers
392 * ================================================================ */
393  
394 448 static void nats_set_strn(char **dst, const char *src, size_t l)
395 {
396 448 ▶ if (*dst) { Safefree(*dst); *dst = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (*dst) { Safefree(*dst); *dst = NULL; } 32 416 448
397 448 ▶ if (src) {
Branch: 1 branch
BranchTrueFalseTotal
if (src) { 233 215 448
398 233 Newx(*dst, l + 1, char);
399 233 memcpy(*dst, src, l);
400 233 (*dst)[l] = '\0';
401 }
402 448 }
403  
404 259 static void nats_set_str(char **dst, const char *src)
405 {
406 259 ▶ nats_set_strn(dst, src, src ? strlen(src) : 0);
Branch: 1 branch
BranchTrueFalseTotal
nats_set_strn(dst, src, src ? strlen(src) : 0); 45 214 259
407 259 }
408  
409 /* undef means unset: NULL, not an empty string */
410 111 static void nats_set_str_sv(char **dst, SV *val)
411 {
412 111 STRLEN l = 0;
413 222 ▶ const char *s = SvOK(val) ? SvPV(val, l) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
const char *s = SvOK(val) ? SvPV(val, l) : NULL; 111 0 111
414 111 nats_set_strn(dst, s, l);
415 111 }
416  
417 /* an int option: an IV out of range clamps instead of wrapping */
418 248 static int nats_clamp(IV v)
419 {
420 248 ▶ return v > INT_MAX ? INT_MAX : v < INT_MIN ? INT_MIN : (int)v;
Branch: 2 branches
BranchTrueFalseTotal
return v > INT_MAX ? INT_MAX : v < INT_MIN ? INT_MIN : (int)v; 245 3 248
return v > INT_MAX ? INT_MAX : v < INT_MIN ? INT_MIN : (int)v; 245 0 245
421 }
422  
423 141 static int nats_int(SV *val)
424 {
425 141 return nats_clamp(SvIV(val));
426 }
427  
428 /* ================================================================
429 * Buffer helpers
430 * ================================================================ */
431  
432 1134 static void buf_ensure(char **buf, size_t *cap, size_t needed)
433 {
434 1134 ▶ if (needed <= *cap)
Branch: 1 branch
BranchTrueFalseTotal
if (needed <= *cap) 951 183 1134
435 951 return;
436 183 ▶ size_t newcap = *cap ? *cap : BUF_INIT_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
size_t newcap = *cap ? *cap : BUF_INIT_SIZE; 9 174 183
437 192 ▶ while (newcap < needed)
Branch: 1 branch
BranchTrueFalseTotal
while (newcap < needed) 9 183 192
438 9 newcap *= 2;
439 183 Renew(*buf, newcap, char);
440 183 *cap = newcap;
441 }
442  
443 /* an empty buffer one large message grew is given back */
444 970 static void buf_trim(char **buf, size_t *cap)
445 {
446 970 ▶ if (*cap > 1024 * 1024) {
Branch: 1 branch
BranchTrueFalseTotal
if (*cap > 1024 * 1024) { 0 970 970
447 0 Safefree(*buf);
448 0 *buf = NULL;
449 0 *cap = 0;
450 }
451 970 }
452  
453 711 static void wbuf_append(nats_t *self, const char *data, size_t len)
454 {
455 711 size_t used = self->wbuf_len - self->wbuf_off;
456 711 ▶ if (self->wbuf_off > 0 && self->wbuf_off > self->wbuf_len / 2) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->wbuf_off > 0 && self->wbuf_off > self->wbuf_len / 2) { 0 711 711
if (self->wbuf_off > 0 && self->wbuf_off > self->wbuf_len / 2) { 0 0 0
457 0 ▶ if (used > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (used > 0) 0 0 0
458 0 memmove(self->wbuf, self->wbuf + self->wbuf_off, used);
459 0 self->wbuf_len = used;
460 0 self->wbuf_off = 0;
461 }
462 711 buf_ensure(&self->wbuf, &self->wbuf_cap, self->wbuf_len + len);
463 711 memcpy(self->wbuf + self->wbuf_len, data, len);
464 711 self->wbuf_len += len;
465 711 }
466  
467 /* Bounded substring search for counted buffers: rbuf slices are not
468 NUL-terminated, so strstr() is unsafe (memmem() is not portable). */
469 480 static const char *nats_memfind(const char *hay, size_t hay_len,
470 const char *needle, size_t needle_len)
471 {
472 const char *last;
473 const char *p;
474 480 ▶ if (needle_len == 0) return hay;
Branch: 1 branch
BranchTrueFalseTotal
if (needle_len == 0) return hay; 0 480 480
475 480 ▶ if (hay_len < needle_len) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (hay_len < needle_len) return NULL; 4 476 480
476 476 last = hay + (hay_len - needle_len);
477 476 p = hay;
478 6370 ▶ while (p <= last) {
Branch: 1 branch
BranchTrueFalseTotal
while (p <= last) { 6366 4 6370
479 6366 p = (const char *)memchr(p, needle[0], (size_t)(last - p) + 1);
480 6366 ▶ if (!p) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return NULL; 371 5995 6366
481 5995 ▶ if (memcmp(p, needle, needle_len) == 0) return p;
Branch: 1 branch
BranchTrueFalseTotal
if (memcmp(p, needle, needle_len) == 0) return p; 101 5894 5995
482 5894 p++;
483 }
484 4 return NULL;
485 }
486  
487 /* the value after an INFO key, past blanks; NULL when the key is absent */
488 383 static const char *nats_info_value(const char *p, const char *e, const char *key)
489 {
490 383 size_t klen = strlen(key);
491 383 const char *v = nats_memfind(p, (size_t)(e - p), key, klen);
492 383 ▶ if (!v) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!v) return NULL; 287 96 383
493 96 v += klen;
494 96 ▶ while (v < e && (*v == ' ' || *v == '\t')) v++;
Branch: 3 branches
BranchTrueFalseTotal
while (v < e && (*v == ' ' || *v == '\t')) v++; 96 0 96
while (v < e && (*v == ' ' || *v == '\t')) v++; 0 96 96
while (v < e && (*v == ' ' || *v == '\t')) v++; 0 96 96
495 96 return v;
496 }
497  
498 /* ================================================================
499 * NKey helpers (base32 + Ed25519)
500 * ================================================================ */
501  
502 #ifdef HAVE_OPENSSL
503 #include <openssl/evp.h>
504  
505 /* NATS base32 decode (RFC 4648, no padding). dst_cap bounds the output:
506 an over-long input (e.g. a hostile .creds seed) must not smash dst. */
507 10 static int nats_base32_decode(const char *src, size_t src_len,
508 unsigned char *dst, size_t dst_cap,
509 size_t *dst_len)
510 {
511 static const int8_t b32_tab[128] = {
512 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
513 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
514 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
515 -1,-1,26,27,28,29,30,31,-1,-1,-1,-1,-1,-1,-1,-1, /* 2-7 */
516 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* A-O */
517 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* P-Z */
518 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* a-o */
519 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* p-z */
520 };
521 10 uint64_t buf = 0;
522 10 int bits = 0;
523 10 size_t di = 0;
524 size_t i;
525  
526 428 ▶ for (i = 0; i < src_len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < src_len; i++) { 422 6 428
527 422 unsigned char c = (unsigned char)src[i];
528 422 ▶ if (c == '=' || c == ' ') continue;
Branch: 2 branches
BranchTrueFalseTotal
if (c == '=' || c == ' ') continue; 422 0 422
if (c == '=' || c == ' ') continue; 0 422 422
529 422 ▶ if (c >= 128 || b32_tab[c] < 0) return -1;
Branch: 2 branches
BranchTrueFalseTotal
if (c >= 128 || b32_tab[c] < 0) return -1; 422 0 422
if (c >= 128 || b32_tab[c] < 0) return -1; 3 419 422
530 419 buf = (buf << 5) | b32_tab[c];
531 419 bits += 5;
532 419 ▶ if (bits >= 8) {
Branch: 1 branch
BranchTrueFalseTotal
if (bits >= 8) { 259 160 419
533 259 bits -= 8;
534 259 ▶ if (di >= dst_cap) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (di >= dst_cap) return -1; 1 258 259
535 258 dst[di++] = (unsigned char)(buf >> bits);
536 }
537 }
538 6 *dst_len = di;
539 6 return 0;
540 }
541  
542 /* NATS base32 encode (RFC 4648, no padding). Streams 8-bit input through
543 a 5-bit accumulator. Returns number of chars written, or -1 if dst is
544 too small. */
545 8 static int nats_base32_encode(const unsigned char *src, size_t src_len,
546 char *dst, size_t dst_size)
547 {
548 static const char b32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
549 8 size_t di = 0;
550 8 uint64_t buf = 0;
551 8 int bits = 0;
552 size_t i;
553 291 ▶ for (i = 0; i < src_len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < src_len; i++) { 283 8 291
554 283 buf = (buf << 8) | src[i];
555 283 bits += 8;
556 734 ▶ while (bits >= 5) {
Branch: 1 branch
BranchTrueFalseTotal
while (bits >= 5) { 451 283 734
557 451 ▶ if (di >= dst_size) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (di >= dst_size) return -1; 0 451 451
558 451 bits -= 5;
559 451 dst[di++] = b32[(buf >> bits) & 0x1F];
560 }
561 }
562 8 ▶ if (bits > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (bits > 0) { 3 5 8
563 3 ▶ if (di >= dst_size) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (di >= dst_size) return -1; 0 3 3
564 3 dst[di++] = b32[(buf << (5 - bits)) & 0x1F];
565 }
566 8 return (int)di;
567 }
568  
569 /* NATS base64url encode (no padding) */
570 0 static int nats_base64url_encode(const unsigned char *src, size_t src_len, char *dst, size_t dst_size)
571 {
572 static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
573 0 size_t di = 0;
574 size_t i;
575 0 ▶ for (i = 0; i + 2 < src_len; i += 3) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 2 < src_len; i += 3) { 0 0 0
576 0 ▶ if (di + 4 > dst_size) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (di + 4 > dst_size) return -1; 0 0 0
577 0 uint32_t v = ((uint32_t)src[i] << 16) | ((uint32_t)src[i+1] << 8) | src[i+2];
578 0 dst[di++] = b64[(v >> 18) & 0x3F];
579 0 dst[di++] = b64[(v >> 12) & 0x3F];
580 0 dst[di++] = b64[(v >> 6) & 0x3F];
581 0 dst[di++] = b64[v & 0x3F];
582 }
583 0 ▶ if (i < src_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (i < src_len) { 0 0 0
584 0 ▶ if (di + 4 > dst_size) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (di + 4 > dst_size) return -1; 0 0 0
585 0 uint32_t v = (uint32_t)src[i] << 16;
586 0 ▶ if (i + 1 < src_len) v |= (uint32_t)src[i+1] << 8;
Branch: 1 branch
BranchTrueFalseTotal
if (i + 1 < src_len) v |= (uint32_t)src[i+1] << 8; 0 0 0
587 0 dst[di++] = b64[(v >> 18) & 0x3F];
588 0 dst[di++] = b64[(v >> 12) & 0x3F];
589 0 ▶ if (i + 1 < src_len) dst[di++] = b64[(v >> 6) & 0x3F];
Branch: 1 branch
BranchTrueFalseTotal
if (i + 1 < src_len) dst[di++] = b64[(v >> 6) & 0x3F]; 0 0 0
590 }
591 0 ▶ if (di < dst_size) dst[di] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (di < dst_size) dst[di] = '\0'; 0 0 0
592 0 return (int)di;
593 }
594  
595 /* CRC-16/XMODEM (poly 0x1021, init 0), as NKeys use; not CRC-16/IBM */
596 13 static uint16_t nats_crc16(const unsigned char *data, size_t len)
597 {
598 13 uint16_t crc = 0;
599 size_t i;
600 int j;
601 450 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 437 13 450
602 437 crc ^= ((uint16_t)data[i]) << 8;
603 3933 ▶ for (j = 0; j < 8; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < 8; j++) { 3496 437 3933
604 3496 ▶ if (crc & 0x8000) crc = (uint16_t)((crc << 1) ^ 0x1021);
Branch: 1 branch
BranchTrueFalseTotal
if (crc & 0x8000) crc = (uint16_t)((crc << 1) ^ 0x1021); 1701 1795 3496
605 1795 else crc = (uint16_t)(crc << 1);
606 }
607 }
608 13 return crc;
609 }
610  
611 /* Decode and CRC-check a seed: prefix(2) + seed(32) + CRC(2) into raw */
612 10 static EVP_PKEY *nats_seed_key(const char *seed_encoded, unsigned char raw[64])
613 {
614 10 size_t raw_len = 0;
615 10 ▶ if (nats_base32_decode(seed_encoded, strlen(seed_encoded), raw, 64, &raw_len) != 0
Branch: 1 branch
BranchTrueFalseTotal
if (nats_base32_decode(seed_encoded, strlen(seed_encoded), raw, 64, &raw_len) != 0 6 4 10
616 6 ▶ || raw_len != 36
Branch: 1 branch
BranchTrueFalseTotal
|| raw_len != 36 5 1 6
617 5 ▶ || nats_crc16(raw, 34) != ((uint16_t)raw[34] | ((uint16_t)raw[35] << 8)))
Branch: 1 branch
BranchTrueFalseTotal
|| nats_crc16(raw, 34) != ((uint16_t)raw[34] | ((uint16_t)raw[35] << 8))) 0 5 5
618 5 return NULL;
619 5 return EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, NULL, raw + 2, 32);
620 }
621  
622 0 static int nats_nkey_sign(const char *seed_encoded, const char *nonce, size_t nonce_len,
623 char *sig_out, size_t sig_out_size)
624 {
625 unsigned char raw[64];
626 0 EVP_PKEY *pkey = nats_seed_key(seed_encoded, raw);
627 0 ▶ if (!pkey) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (!pkey) return -1; 0 0 0
628  
629 0 EVP_MD_CTX *ctx = EVP_MD_CTX_new();
630 0 ▶ if (!ctx) { EVP_PKEY_free(pkey); return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (!ctx) { EVP_PKEY_free(pkey); return -1; } 0 0 0
631  
632 unsigned char sig[64];
633 0 size_t sig_len = sizeof(sig);
634  
635 0 int ok = (EVP_DigestSignInit(ctx, NULL, NULL, NULL, pkey) == 1 &&
636 0 EVP_DigestSign(ctx, sig, &sig_len, (const unsigned char *)nonce, nonce_len) == 1);
637  
638 0 EVP_MD_CTX_free(ctx);
639 0 EVP_PKEY_free(pkey);
640  
641 0 ▶ if (!ok) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (!ok) return -1; 0 0 0
642  
643 0 return nats_base64url_encode(sig, sig_len, sig_out, sig_out_size);
644 }
645  
646 10 static int nats_nkey_public(const char *seed_encoded, char *pub_out, size_t pub_out_size)
647 {
648 unsigned char raw[64];
649 10 EVP_PKEY *pkey = nats_seed_key(seed_encoded, raw);
650 10 ▶ if (!pkey) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (!pkey) return -1; 5 5 10
651  
652 unsigned char pub[32];
653 5 size_t pub_len = 32;
654 5 int ok = EVP_PKEY_get_raw_public_key(pkey, pub, &pub_len) == 1;
655 5 EVP_PKEY_free(pkey);
656 5 ▶ if (!ok) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (!ok) return -1; 0 5 5
657  
658 /* Derive public-key prefix from the role embedded in the seed prefix.
659 Seed encoding (NATS Go nkeys EncodeSeed):
660 raw[0] = PrefixByteSeed | (role >> 5)
661 raw[1] = (role & 31) << 3
662 so role = ((raw[0] & 7) << 5) | (raw[1] >> 3). */
663 5 unsigned char role = (unsigned char)(((raw[0] & 0x07) << 5) | (raw[1] >> 3));
664  
665 /* prefix(1) + pubkey(32) + CRC16(2); operator and account keep their
666 role, anything else signs as a user */
667 unsigned char full[35];
668 5 ▶ full[0] = role == 0x70 || role == 0x00 ? role : 0xA0;
Branch: 2 branches
BranchTrueFalseTotal
full[0] = role == 0x70 || role == 0x00 ? role : 0xA0; 5 0 5
full[0] = role == 0x70 || role == 0x00 ? role : 0xA0; 0 5 5
669 5 memcpy(full + 1, pub, 32);
670 5 uint16_t crc = nats_crc16(full, 33);
671 5 full[33] = crc & 0xFF;
672 5 full[34] = (crc >> 8) & 0xFF;
673  
674 /* Base32 encode 35 bytes -> 56 chars (35*8 = 280 bits, 280/5 = 56). */
675 5 ▶ int n = nats_base32_encode(full, sizeof(full), pub_out,
Branch: 1 branch
BranchTrueFalseTotal
int n = nats_base32_encode(full, sizeof(full), pub_out, 5 0 5
676 pub_out_size > 0 ? pub_out_size - 1 : 0);
677 5 ▶ if (n < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) return -1; 0 5 5
678 5 ▶ if ((size_t)n < pub_out_size) pub_out[n] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if ((size_t)n < pub_out_size) pub_out[n] = '\0'; 5 0 5
679 5 return n;
680 }
681 #endif
682  
683 /* ================================================================
684 * I/O helpers (with optional TLS)
685 * ================================================================ */
686  
687 423 static ssize_t nats_io_read(nats_t *self, void *buf, size_t len)
688 {
689 #ifdef HAVE_OPENSSL
690 423 ▶ if (self->ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl) { 0 423 423
691 0 ▶ int n = SSL_read(self->ssl, buf, (len > (size_t)INT_MAX) ? INT_MAX : (int)len);
Branch: 1 branch
BranchTrueFalseTotal
int n = SSL_read(self->ssl, buf, (len > (size_t)INT_MAX) ? INT_MAX : (int)len); 0 0 0
692 0 ▶ if (n <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { 0 0 0
693 0 int err = SSL_get_error(self->ssl, n);
694 0 ▶ if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
Branch: 2 branches
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { 0 0 0
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { 0 0 0
695 0 errno = EAGAIN;
696 0 return -1;
697 }
698 0 ▶ if (err == SSL_ERROR_ZERO_RETURN) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_ZERO_RETURN) return 0; 0 0 0
699 0 errno = EIO;
700 0 return -1;
701 }
702 0 return n;
703 }
704 #endif
705 423 return read(self->fd, buf, len);
706 }
707  
708 199 static ssize_t nats_io_write(nats_t *self, const void *buf, size_t len)
709 {
710 #ifdef HAVE_OPENSSL
711 199 ▶ if (self->ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl) { 0 199 199
712 /* Retries keep the original length even if producers append more. */
713 0 ▶ if (!self->ssl_write_len)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ssl_write_len) 0 0 0
714 0 ▶ self->ssl_write_len = len > (size_t)INT_MAX ? INT_MAX : (int)len;
Branch: 1 branch
BranchTrueFalseTotal
self->ssl_write_len = len > (size_t)INT_MAX ? INT_MAX : (int)len; 0 0 0
715 0 int n = SSL_write(self->ssl, buf, self->ssl_write_len);
716 0 ▶ if (n <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { 0 0 0
717 0 int err = SSL_get_error(self->ssl, n);
718 0 ▶ if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
Branch: 2 branches
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) { 0 0 0
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) { 0 0 0
719 0 errno = EAGAIN;
720 0 return -1;
721 }
722 0 errno = EIO;
723 0 return -1;
724 }
725 0 self->ssl_write_len = 0;
726 0 return n;
727 }
728 #endif
729 #ifdef MSG_NOSIGNAL
730 199 return send(self->fd, buf, len, MSG_NOSIGNAL);
731 #else
732 return write(self->fd, buf, len);
733 #endif
734 }
735  
736 #ifdef HAVE_OPENSSL
737 #ifdef MSG_NOSIGNAL
738 /* OpenSSL's socket BIO writes without MSG_NOSIGNAL. Keep signal suppression
739 local to this transport, including writes made during TLS reads. */
740 static BIO_METHOD *nats_socket_bio_method;
741  
742 0 static int nats_bio_read(BIO *bio, char *buf, int len)
743 {
744 0 nats_t *self = (nats_t *)BIO_get_data(bio);
745 0 BIO_clear_retry_flags(bio);
746 0 int n = read(self->fd, buf, len);
747 0 ▶ if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
Branch: 4 branches
BranchTrueFalseTotal
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
748 0 BIO_set_retry_read(bio);
749 0 return n;
750 }
751  
752 0 static int nats_bio_write(BIO *bio, const char *buf, int len)
753 {
754 0 nats_t *self = (nats_t *)BIO_get_data(bio);
755 0 BIO_clear_retry_flags(bio);
756 0 int n = send(self->fd, buf, len, MSG_NOSIGNAL);
757 0 ▶ if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
Branch: 4 branches
BranchTrueFalseTotal
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) 0 0 0
758 0 BIO_set_retry_write(bio);
759 0 return n;
760 }
761  
762 0 static long nats_bio_ctrl(BIO *bio, int cmd, long num, void *ptr)
763 {
764 0 nats_t *self = (nats_t *)BIO_get_data(bio);
765 (void)num;
766 0 ▶ if (cmd == BIO_CTRL_FLUSH) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (cmd == BIO_CTRL_FLUSH) return 1; 0 0 0
767 0 ▶ if (cmd == BIO_C_GET_FD) {
Branch: 1 branch
BranchTrueFalseTotal
if (cmd == BIO_C_GET_FD) { 0 0 0
768 0 ▶ if (ptr) *(int *)ptr = self->fd;
Branch: 1 branch
BranchTrueFalseTotal
if (ptr) *(int *)ptr = self->fd; 0 0 0
769 0 return self->fd;
770 }
771 0 return 0;
772 }
773  
774 0 static BIO *nats_socket_bio(nats_t *self)
775 {
776 0 ▶ if (!nats_socket_bio_method) {
Branch: 1 branch
BranchTrueFalseTotal
if (!nats_socket_bio_method) { 0 0 0
777 0 BIO_METHOD *method = BIO_meth_new(BIO_get_new_index() |
778 BIO_TYPE_SOURCE_SINK | BIO_TYPE_DESCRIPTOR, "EV::Nats socket");
779 0 ▶ if (!method) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!method) return NULL; 0 0 0
780 0 BIO_meth_set_read(method, nats_bio_read);
781 0 BIO_meth_set_write(method, nats_bio_write);
782 0 BIO_meth_set_ctrl(method, nats_bio_ctrl);
783 0 nats_socket_bio_method = method;
784 }
785 0 BIO *bio = BIO_new(nats_socket_bio_method);
786 0 ▶ if (bio) {
Branch: 1 branch
BranchTrueFalseTotal
if (bio) { 0 0 0
787 0 BIO_set_data(bio, self);
788 0 BIO_set_init(bio, 1);
789 }
790 0 return bio;
791 }
792 #endif
793  
794 0 static int nats_ssl_setup(nats_t *self)
795 {
796 0 ▶ if (!self->ssl_ctx) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ssl_ctx) { 0 0 0
797 0 self->ssl_ctx = SSL_CTX_new(TLS_client_method());
798 0 ▶ if (!self->ssl_ctx) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ssl_ctx) return -1; 0 0 0
799  
800 /* a failed load (e.g. no fd left) must not be cached for later attempts */
801 0 ▶ if (!(self->tls_ca_file && *self->tls_ca_file
Branch: 3 branches
BranchTrueFalseTotal
if (!(self->tls_ca_file && *self->tls_ca_file 0 0 0
if (!(self->tls_ca_file && *self->tls_ca_file 0 0 0
if (!(self->tls_ca_file && *self->tls_ca_file 0 0 0
802 0 ? SSL_CTX_load_verify_locations(self->ssl_ctx, self->tls_ca_file, NULL)
803 0 : SSL_CTX_set_default_verify_paths(self->ssl_ctx))) {
804 0 SSL_CTX_free(self->ssl_ctx);
805 0 self->ssl_ctx = NULL;
806 0 return -1;
807 }
808  
809 0 ▶ if (!self->tls_skip_verify)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->tls_skip_verify) 0 0 0
810 0 SSL_CTX_set_verify(self->ssl_ctx, SSL_VERIFY_PEER, NULL);
811 }
812  
813 0 self->ssl = SSL_new(self->ssl_ctx);
814 0 ▶ if (!self->ssl) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ssl) return -1; 0 0 0
815 0 SSL_set_mode(self->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
816  
817 #ifdef MSG_NOSIGNAL
818 0 BIO *bio = nats_socket_bio(self);
819 0 ▶ if (!bio) {
Branch: 1 branch
BranchTrueFalseTotal
if (!bio) { 0 0 0
820 0 SSL_free(self->ssl);
821 0 self->ssl = NULL;
822 0 return -1;
823 }
824 0 SSL_set_bio(self->ssl, bio, bio);
825 #else
826 SSL_set_fd(self->ssl, self->fd);
827 #endif
828 0 ▶ if (self->host) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->host) { 0 0 0
829 0 SSL_set_tlsext_host_name(self->ssl, self->host);
830 0 ▶ if (!self->tls_skip_verify) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->tls_skip_verify) { 0 0 0
831 0 X509_VERIFY_PARAM *vpm = SSL_get0_param(self->ssl);
832 /* set1_ip_asc fails for a DNS name; set1_host covers those */
833 0 ▶ if (vpm && !X509_VERIFY_PARAM_set1_ip_asc(vpm, self->host)) {
Branch: 2 branches
BranchTrueFalseTotal
if (vpm && !X509_VERIFY_PARAM_set1_ip_asc(vpm, self->host)) { 0 0 0
if (vpm && !X509_VERIFY_PARAM_set1_ip_asc(vpm, self->host)) { 0 0 0
834 0 X509_VERIFY_PARAM_set_hostflags(vpm, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
835 0 ▶ if (!X509_VERIFY_PARAM_set1_host(vpm, self->host, 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!X509_VERIFY_PARAM_set1_host(vpm, self->host, 0)) { 0 0 0
836 0 SSL_free(self->ssl);
837 0 self->ssl = NULL;
838 0 return -1;
839 }
840 }
841 }
842 }
843  
844 0 return 0;
845 }
846  
847 295 static void nats_ssl_cleanup(nats_t *self)
848 {
849 295 ▶ if (self->ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl) { 0 295 295
850 0 SSL_free(self->ssl);
851 0 self->ssl = NULL;
852 }
853 295 self->ssl_handshaking = 0;
854 295 self->ssl_write_len = 0;
855 295 }
856  
857 0 static int nats_ssl_handshake(nats_t *self)
858 {
859 0 int ret = SSL_connect(self->ssl);
860 0 ▶ if (ret == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret == 1) { 0 0 0
861 0 self->ssl_handshaking = 0;
862 0 return 1;
863 }
864 0 int err = SSL_get_error(self->ssl, ret);
865 0 ▶ if (err == SSL_ERROR_WANT_READ) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_READ) { 0 0 0
866 0 ▶ if (!self->reading) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->reading) { 0 0 0
867 0 ev_io_start(self->loop, &self->rio);
868 0 self->reading = 1;
869 }
870 /* Stop the write watcher: leaving it armed spins the loop
871 calling SSL_connect until the server's next flight arrives. */
872 0 ▶ if (self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->writing) { 0 0 0
873 0 ev_io_stop(self->loop, &self->wio);
874 0 self->writing = 0;
875 }
876 0 return 0;
877 }
878 0 ▶ if (err == SSL_ERROR_WANT_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_WRITE) { 0 0 0
879 0 ▶ if (!self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->writing) { 0 0 0
880 0 ev_io_start(self->loop, &self->wio);
881 0 self->writing = 1;
882 }
883 0 return 0;
884 }
885 0 return -1;
886 }
887  
888 /* Emit "<prefix>: <openssl-error>", clean up the connection. */
889 0 static void nats_ssl_fail(nats_t *self, const char *prefix)
890 {
891 char errbuf[256];
892 char msg[320];
893 0 unsigned long e = ERR_peek_last_error();
894 0 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 0 0 0
895 0 ERR_error_string_n(e, errbuf, sizeof(errbuf));
896 0 ERR_clear_error();
897 } else {
898 0 snprintf(errbuf, sizeof(errbuf), "unknown SSL error");
899 }
900 0 snprintf(msg, sizeof(msg), "%s: %s", prefix, errbuf);
901 0 nats_fail(self, msg);
902 0 }
903 #endif
904  
905 /* ================================================================
906 * JSON string escaper (for CONNECT command)
907 * ================================================================ */
908  
909 3 static int json_escape_string(char *dst, size_t dst_size, const char *src)
910 {
911 3 size_t di = 0;
912 3 const unsigned char *s = (const unsigned char *)src;
913  
914 3 dst[di++] = '"';
915  
916 8198 ▶ for (; *s; s++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; *s; s++) { 8196 2 8198
917 8196 ▶ size_t need = (*s == '"' || *s == '\\') ? 2 : (*s < 0x20) ? 6 : 1;
Branch: 3 branches
BranchTrueFalseTotal
size_t need = (*s == '"' || *s == '\\') ? 2 : (*s < 0x20) ? 6 : 1; 8196 0 8196
size_t need = (*s == '"' || *s == '\\') ? 2 : (*s < 0x20) ? 6 : 1; 8196 0 8196
size_t need = (*s == '"' || *s == '\\') ? 2 : (*s < 0x20) ? 6 : 1; 0 8196 8196
918 8196 ▶ if (di + need + 2 > dst_size) break; /* +2 for closing quote + NUL */
Branch: 1 branch
BranchTrueFalseTotal
if (di + need + 2 > dst_size) break; /* +2 for closing quote + NUL */ 1 8195 8196
919  
920 8195 ▶ if (*s == '"') {
Branch: 1 branch
BranchTrueFalseTotal
if (*s == '"') { 0 8195 8195
921 0 dst[di++] = '\\'; dst[di++] = '"';
922 8195 ▶ } else if (*s == '\\') {
Branch: 1 branch
BranchTrueFalseTotal
} else if (*s == '\\') { 0 8195 8195
923 0 dst[di++] = '\\'; dst[di++] = '\\';
924 8195 ▶ } else if (*s < 0x20) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (*s < 0x20) { 0 8195 8195
925 0 di += snprintf(dst + di, dst_size - di, "\\u%04x", *s);
926 } else {
927 8195 dst[di++] = *s;
928 }
929 }
930  
931 3 ▶ if (*s) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (*s) return -1; 1 2 3
932 2 dst[di++] = '"';
933 2 dst[di] = '\0';
934 2 return (int)di;
935 }
936  
937 /* ================================================================
938 * Random hex for inbox prefix
939 * ================================================================ */
940  
941 /* 0 when no entropy source answered (e.g. no fd left for /dev/urandom)
942 and the bytes came from a time-and-pid seeded rand() */
943 405 static int nats_random_bytes(unsigned char *out, int nbytes)
944 {
945 #ifdef HAVE_OPENSSL
946 405 ▶ if (RAND_bytes(out, nbytes) == 1)
Branch: 1 branch
BranchTrueFalseTotal
if (RAND_bytes(out, nbytes) == 1) 405 0 405
947 405 return 1;
948 #endif
949 #ifdef NATS_HAVE_ARC4RANDOM
950 arc4random_buf(out, nbytes);
951 return 1;
952 #else
953 0 int got = 0, i;
954 static int seeded;
955 0 int fd = open("/dev/urandom", O_RDONLY);
956 0 ▶ if (fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { 0 0 0
957 0 ▶ while (got < nbytes) {
Branch: 1 branch
BranchTrueFalseTotal
while (got < nbytes) { 0 0 0
958 0 ssize_t n = read(fd, out + got, nbytes - got);
959 0 ▶ if (n > 0) got += n;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) got += n; 0 0 0
960 0 ▶ else if (n == 0 || (errno != EINTR && errno != EAGAIN)) break;
Branch: 3 branches
BranchTrueFalseTotal
else if (n == 0 || (errno != EINTR && errno != EAGAIN)) break; 0 0 0
else if (n == 0 || (errno != EINTR && errno != EAGAIN)) break; 0 0 0
else if (n == 0 || (errno != EINTR && errno != EAGAIN)) break; 0 0 0
961 }
962 0 close(fd);
963 }
964 0 ▶ if (got == nbytes)
Branch: 1 branch
BranchTrueFalseTotal
if (got == nbytes) 0 0 0
965 0 return 1;
966 0 ▶ if (!seeded) {
Branch: 1 branch
BranchTrueFalseTotal
if (!seeded) { 0 0 0
967 0 srand((unsigned)time(NULL) ^ (unsigned)getpid() ^ (unsigned)(uintptr_t)&seeded);
968 0 seeded = 1;
969 }
970 0 ▶ for (i = got; i < nbytes; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = got; i < nbytes; i++) 0 0 0
971 0 out[i] = (unsigned char)(rand() & 0xFF);
972 0 return 0;
973 #endif
974 }
975  
976 300 static void nats_gen_hex(char *buf, int nbytes)
977 {
978 static const char hex[] = "0123456789abcdef";
979 unsigned char rnd[16];
980 300 ▶ if (nbytes < 0) nbytes = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (nbytes < 0) nbytes = 0; 0 300 300
981 300 ▶ if (nbytes > (int)sizeof(rnd)) nbytes = (int)sizeof(rnd);
Branch: 1 branch
BranchTrueFalseTotal
if (nbytes > (int)sizeof(rnd)) nbytes = (int)sizeof(rnd); 0 300 300
982 300 nats_random_bytes(rnd, nbytes);
983 int i;
984 2700 ▶ for (i = 0; i < nbytes; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nbytes; i++) { 2400 300 2700
985 2400 buf[i*2] = hex[rnd[i] >> 4];
986 2400 buf[i*2+1] = hex[rnd[i] & 0x0F];
987 }
988 300 }
989  
990 150 static void nats_setup_inbox(nats_t *self, const char *base)
991 {
992 char hex[20];
993 150 nats_gen_hex(hex, 8);
994 150 snprintf(self->inbox_prefix, sizeof(self->inbox_prefix),
995 "%s.%.16s.", base, hex);
996 150 nats_gen_hex(hex, 8);
997 150 snprintf(self->user_inbox_prefix, sizeof(self->user_inbox_prefix),
998 "%s.%.16s.", base, hex);
999 150 self->next_req_id = 1;
1000 150 }
1001  
1002 9 static int nats_inbox_base_ok(const char *p, size_t len)
1003 {
1004 size_t i;
1005 9 ▶ if (len == 0 || len > MAX_INBOX_BASE || p[0] == '.' || p[len - 1] == '.')
Branch: 4 branches
BranchTrueFalseTotal
if (len == 0 || len > MAX_INBOX_BASE || p[0] == '.' || p[len - 1] == '.') 8 1 9
if (len == 0 || len > MAX_INBOX_BASE || p[0] == '.' || p[len - 1] == '.') 7 1 8
if (len == 0 || len > MAX_INBOX_BASE || p[0] == '.' || p[len - 1] == '.') 6 1 7
if (len == 0 || len > MAX_INBOX_BASE || p[0] == '.' || p[len - 1] == '.') 1 5 6
1006 4 return 0;
1007 20 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 19 1 20
1008 19 unsigned char c = (unsigned char)p[i];
1009 19 ▶ if (c <= 0x20 || c == 0x7f || c == '*' || c == '>')
Branch: 4 branches
BranchTrueFalseTotal
if (c <= 0x20 || c == 0x7f || c == '*' || c == '>') 18 1 19
if (c <= 0x20 || c == 0x7f || c == '*' || c == '>') 18 0 18
if (c <= 0x20 || c == 0x7f || c == '*' || c == '>') 17 1 18
if (c <= 0x20 || c == 0x7f || c == '*' || c == '>') 1 16 17
1010 3 return 0;
1011 16 ▶ if (c == '.' && p[i + 1] == '.')
Branch: 2 branches
BranchTrueFalseTotal
if (c == '.' && p[i + 1] == '.') 3 13 16
if (c == '.' && p[i + 1] == '.') 1 2 3
1012 1 return 0;
1013 }
1014 1 return 1;
1015 }
1016  
1017 /* ================================================================
1018 * Subscription management
1019 * ================================================================ */
1020  
1021 75 static nats_sub_t *nats_find_sub(nats_t *self, uint64_t sid)
1022 {
1023 75 SV **svp = hv_fetch(self->sub_map, (const char *)&sid, sizeof(sid), 0);
1024 75 ▶ if (svp && SvIOK(*svp))
Branch: 2 branches
BranchTrueFalseTotal
if (svp && SvIOK(*svp)) 75 0 75
if (svp && SvIOK(*svp)) 75 0 75
1025 75 return INT2PTR(nats_sub_t *, SvIVX(*svp));
1026 0 return NULL;
1027 }
1028  
1029 67 static void nats_register_sub(nats_t *self, nats_sub_t *sub)
1030 {
1031 67 hv_store(self->sub_map, (const char *)&sub->sid, sizeof(sub->sid), newSViv(PTR2IV(sub)), 0);
1032 67 ngx_queue_insert_tail(&self->subs, &sub->queue);
1033 67 }
1034  
1035 41 static void nats_unregister_sub(nats_t *self, nats_sub_t *sub)
1036 {
1037 41 hv_delete(self->sub_map, (const char *)&sub->sid, sizeof(sub->sid), G_DISCARD);
1038 41 }
1039  
1040 41 static void nats_remove_sub(nats_t *self, nats_sub_t *sub)
1041 {
1042 41 SV *cb = sub->cb;
1043 41 nats_unregister_sub(self, sub);
1044 41 ngx_queue_remove(&sub->queue);
1045 41 ▶ CLEAR_HANDLER(sub->subject);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(sub->subject); 41 0 41
1046 41 ▶ CLEAR_HANDLER(sub->queue_group);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(sub->queue_group); 1 40 41
1047 41 Safefree(sub);
1048 /* last: freeing the callback can run a DESTROY that calls back in */
1049 41 ▶ if (cb)
Branch: 1 branch
BranchTrueFalseTotal
if (cb) 26 15 41
1050 26 SvREFCNT_dec(cb);
1051 41 }
1052  
1053 90 static void nats_resub_all(nats_t *self)
1054 {
1055 ngx_queue_t *q;
1056 char buf[MAX_CONTROL_LINE];
1057  
1058 97 ▶ ngx_queue_foreach(q, &self->subs) {
Branch: 2 branches
BranchTrueFalseTotal
ngx_queue_foreach(q, &self->subs) { 7 90 97
ngx_queue_foreach(q, &self->subs) { 7 0 7
1059 7 nats_sub_t *sub = ngx_queue_data(q, nats_sub_t, queue);
1060 STRLEN slen;
1061 7 const char *subj = SvPV(sub->subject, slen);
1062 int n;
1063  
1064 7 ▶ if (sub->queue_group) {
Branch: 1 branch
BranchTrueFalseTotal
if (sub->queue_group) { 0 7 7
1065 STRLEN glen;
1066 0 const char *grp = SvPV(sub->queue_group, glen);
1067 0 n = snprintf(buf, sizeof(buf), "SUB %.*s %.*s %" UVuf "\r\n",
1068 0 (int)slen, subj, (int)glen, grp, (UV)sub->sid);
1069 } else {
1070 7 n = snprintf(buf, sizeof(buf), "SUB %.*s %" UVuf "\r\n",
1071 7 (int)slen, subj, (UV)sub->sid);
1072 }
1073 7 wbuf_append(self, buf, n);
1074  
1075 /* Restore auto-unsub if partially consumed */
1076 7 ▶ if (sub->max_msgs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (sub->max_msgs > 0) { 1 6 7
1077 1 int remaining = sub->max_msgs - sub->received;
1078 1 ▶ if (remaining < 1) remaining = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (remaining < 1) remaining = 1; 0 1 1
1079 1 n = snprintf(buf, sizeof(buf), "UNSUB %" UVuf " %d\r\n",
1080 1 (UV)sub->sid, remaining);
1081 1 wbuf_append(self, buf, n);
1082 }
1083 }
1084 90 }
1085  
1086 /* ================================================================
1087 * Connection management
1088 * ================================================================ */
1089  
1090 295 static void nats_stop_watchers(nats_t *self)
1091 {
1092 295 ▶ if (self->reading) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reading) { 179 116 295
1093 179 ev_io_stop(self->loop, &self->rio);
1094 179 self->reading = 0;
1095 }
1096 295 ▶ if (self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->writing) { 84 211 295
1097 84 ev_io_stop(self->loop, &self->wio);
1098 84 self->writing = 0;
1099 }
1100 295 }
1101  
1102 295 static void nats_stop_timers(nats_t *self)
1103 {
1104 295 ▶ if (self->connect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timer_active) { 0 295 295
1105 0 ev_timer_stop(self->loop, &self->connect_timer);
1106 0 self->connect_timer_active = 0;
1107 }
1108 295 ▶ if (self->reconnect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_timer_active) { 2 293 295
1109 2 ev_timer_stop(self->loop, &self->reconnect_timer);
1110 2 self->reconnect_timer_active = 0;
1111 }
1112 295 ▶ if (self->ping_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ping_timer_active) { 87 208 295
1113 87 ev_timer_stop(self->loop, &self->ping_timer);
1114 87 self->ping_timer_active = 0;
1115 }
1116 295 ▶ if (self->prepare_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->prepare_active) { 10 285 295
1117 10 ev_prepare_stop(self->loop, &self->prepare_watcher);
1118 10 self->prepare_active = 0;
1119 }
1120 295 }
1121  
1122 /* Fail the requests whose PUB was on the socket (queued 0) or is being
1123 dropped from the wait queue (queued 1); a queued PUB that survives a
1124 failed reconnect attempt must not report a failure it later contradicts. */
1125 400 static void nats_cancel_requests(nats_t *self, const char *err, int queued)
1126 {
1127 ngx_queue_t doomed, *q, *next;
1128 400 ngx_queue_init(&doomed);
1129 437 ▶ for (q = ngx_queue_head(&self->req_queue); q != ngx_queue_sentinel(&self->req_queue); q = next) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = ngx_queue_head(&self->req_queue); q != ngx_queue_sentinel(&self->req_queue); q = next) { 37 400 437
1130 37 nats_req_t *req = ngx_queue_data(q, nats_req_t, queue);
1131 37 next = ngx_queue_next(q);
1132 37 ▶ if (req->queued != queued)
Branch: 1 branch
BranchTrueFalseTotal
if (req->queued != queued) 13 24 37
1133 13 continue;
1134 24 ngx_queue_remove(q);
1135 24 ngx_queue_insert_tail(&doomed, q);
1136 24 ▶ if (req->timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (req->timer_active) { 15 9 24
1137 15 ev_timer_stop(self->loop, &req->timer);
1138 15 req->timer_active = 0;
1139 }
1140 }
1141 424 ▶ while (!ngx_queue_empty(&doomed)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&doomed)) { 24 400 424
1142 24 q = ngx_queue_head(&doomed);
1143 24 nats_req_t *req = ngx_queue_data(q, nats_req_t, queue);
1144 24 ngx_queue_remove(q);
1145  
1146 24 ▶ if (req->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (req->cb) { 24 0 24
1147 24 nats_call_str(self, req->cb, 1, err);
1148 24 SvREFCNT_dec(req->cb);
1149 }
1150 24 Safefree(req);
1151 }
1152 400 }
1153  
1154 /* One-shot; a watcher added by a callback waits for the next drop. */
1155 124 static void nats_fire_disc_watchers(nats_t *self)
1156 {
1157 124 uint64_t last = self->next_watch_id;
1158 127 ▶ while (!ngx_queue_empty(&self->disc_watch)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->disc_watch)) { 3 124 127
1159 3 ngx_queue_t *q = ngx_queue_head(&self->disc_watch);
1160 3 nats_watch_t *w = ngx_queue_data(q, nats_watch_t, queue);
1161 3 ▶ if (w->id > last)
Branch: 1 branch
BranchTrueFalseTotal
if (w->id > last) 0 3 3
1162 0 break;
1163 3 ngx_queue_remove(q);
1164 3 SV *cb = w->cb;
1165 3 Safefree(w);
1166 3 ENTER;
1167 3 SAVEFREESV(cb);
1168 3 nats_call0(self, cb);
1169 3 LEAVE;
1170 }
1171 124 }
1172  
1173 /* Fail flush callbacks with "disconnected"; free markers silently.
1174 Detached first, so a callback that flushes again cannot loop here. */
1175 423 static void nats_fail_pong_queue(nats_t *self, ngx_queue_t *live)
1176 {
1177 423 ngx_queue_t detached, *head = &detached;
1178 423 ▶ if (ngx_queue_empty(live))
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(live)) 407 16 423
1179 407 return;
1180 16 ngx_queue_init(head);
1181 16 ngx_queue_add(head, live);
1182 16 ngx_queue_init(live);
1183 41 ▶ while (!ngx_queue_empty(head)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(head)) { 25 16 41
1184 25 ngx_queue_t *pq = ngx_queue_head(head);
1185 25 nats_pong_cb_t *pcb = ngx_queue_data(pq, nats_pong_cb_t, queue);
1186 25 ngx_queue_remove(pq);
1187 25 ▶ if (pcb->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (pcb->cb) { 6 19 25
1188 6 nats_call_str(self, pcb->cb, 0, "disconnected");
1189 6 SvREFCNT_dec(pcb->cb);
1190 }
1191 25 Safefree(pcb);
1192 }
1193 }
1194  
1195 192 static void nats_free_pong_queue(ngx_queue_t *head)
1196 {
1197 193 ▶ while (!ngx_queue_empty(head)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(head)) { 1 192 193
1198 1 ngx_queue_t *pq = ngx_queue_head(head);
1199 1 nats_pong_cb_t *pcb = ngx_queue_data(pq, nats_pong_cb_t, queue);
1200 1 ngx_queue_remove(pq);
1201 1 ▶ CLEAR_HANDLER(pcb->cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(pcb->cb); 1 0 1
1202 1 Safefree(pcb);
1203 }
1204 192 }
1205  
1206 typedef struct {
1207 SV *cb;
1208 const char *err;
1209 } nats_deferred_err_t;
1210  
1211 1 static void nats_on_deferred_err(int revents, void *arg)
1212 {
1213 1 nats_deferred_err_t *d = (nats_deferred_err_t *)arg;
1214 1 SV *cb = d->cb;
1215 1 const char *err = d->err;
1216 (void)revents;
1217 1 Safefree(d);
1218 1 dSP;
1219 1 ENTER; SAVETMPS;
1220 1 SAVEFREESV(cb);
1221 1 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 1 1
1222 1 ▶ EXTEND(SP, 1);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 1); 0 1 1
1223 1 PUSHs(sv_2mortal(newSVpv(err, 0)));
1224 1 PUTBACK;
1225 1 call_sv(cb, G_DISCARD);
1226 1 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 1 0 1
1227 1 }
1228  
1229 1 static void nats_defer_err(nats_t *self, SV *cb, const char *err)
1230 {
1231 nats_deferred_err_t *d;
1232 1 Newx(d, 1, nats_deferred_err_t);
1233 1 d->cb = newSVsv(cb);
1234 1 d->err = err;
1235 1 ev_once(self->loop, -1, 0, 0., nats_on_deferred_err, d);
1236 1 }
1237  
1238 175 static void nats_skip_waiting(nats_t *self)
1239 {
1240 291 ▶ while (!ngx_queue_empty(&self->wait_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->wait_queue)) { 116 175 291
1241 116 ngx_queue_t *q = ngx_queue_head(&self->wait_queue);
1242 116 nats_pub_t *pub = ngx_queue_data(q, nats_pub_t, queue);
1243 116 ngx_queue_remove(q);
1244 116 ▶ if (pub->data)
Branch: 1 branch
BranchTrueFalseTotal
if (pub->data) 116 0 116
1245 116 Safefree(pub->data);
1246 116 Safefree(pub);
1247 116 self->waiting_count--;
1248 }
1249 175 self->wait_bytes = 0;
1250 175 }
1251  
1252 199 static void nats_cleanup(nats_t *self)
1253 {
1254 199 SV *pin = self->owner_sv;
1255 199 ▶ if (pin) SvREFCNT_inc(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_inc(pin); 199 0 199
1256 /* the socket was up: a refused or unreachable attempt is not a drop */
1257 199 ▶ int was_connected = self->connected || (self->connecting && !self->connect_pending);
Branch: 3 branches
BranchTrueFalseTotal
int was_connected = self->connected || (self->connecting && !self->connect_pending); 115 84 199
int was_connected = self->connected || (self->connecting && !self->connect_pending); 90 25 115
int was_connected = self->connected || (self->connecting && !self->connect_pending); 7 83 90
1258 199 int established = self->connected;
1259  
1260 199 nats_stop_watchers(self);
1261 199 nats_stop_timers(self);
1262  
1263 199 self->connected = 0;
1264 199 self->connecting = 0;
1265 199 self->connect_pending = 0;
1266 199 self->connect_sent = 0;
1267 199 self->pings_outstanding = 0;
1268 199 self->ldm = 0; /* lame-duck flag is per-connection */
1269 199 nats_set_str(&self->server_nonce, NULL); /* stale nonce must not sign */
1270  
1271 199 nats_free_addrinfo(self);
1272  
1273 #ifdef HAVE_OPENSSL
1274 199 nats_ssl_cleanup(self);
1275 #endif
1276  
1277 199 ▶ if (self->fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) { 174 25 199
1278 174 close(self->fd);
1279 174 self->fd = -1;
1280 }
1281  
1282 199 self->rbuf_len = 0;
1283 199 self->rbuf_off = 0;
1284 199 self->wbuf_len = 0;
1285 199 self->wbuf_off = 0;
1286 199 buf_trim(&self->rbuf, &self->rbuf_cap);
1287 199 buf_trim(&self->wbuf, &self->wbuf_cap);
1288  
1289 199 nats_cancel_requests(self, "disconnected", 0);
1290 /* a fetch made during an outage still has its pull queued */
1291 199 ▶ if (established || self->intentional_disconnect)
Branch: 2 branches
BranchTrueFalseTotal
if (established || self->intentional_disconnect) 115 84 199
if (established || self->intentional_disconnect) 40 75 115
1292 124 nats_fire_disc_watchers(self);
1293  
1294 199 nats_fail_pong_queue(self, &self->pong_cbs);
1295 199 self->draining = 0;
1296 199 ▶ nats_fire_drain(self, "disconnected");
Branch: 1 branch
BranchTrueFalseTotal
nats_fire_drain(self, "disconnected"); 3 196 199
1297  
1298 199 ▶ if (was_connected && self->on_disconnect)
Branch: 2 branches
BranchTrueFalseTotal
if (was_connected && self->on_disconnect) 91 108 199
if (was_connected && self->on_disconnect) 16 75 91
1299 16 nats_call0(self, self->on_disconnect);
1300  
1301 199 nats_schedule_reconnect(self);
1302 199 ▶ if (pin) SvREFCNT_dec(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_dec(pin); 199 0 199
1303 199 }
1304  
1305 114 static void nats_emit_error(nats_t *self, const char *err)
1306 {
1307 114 ▶ if (self->on_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->on_error) { 113 1 114
1308 113 SV *pin = self->owner_sv;
1309 113 ▶ if (pin) SvREFCNT_inc(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_inc(pin); 113 0 113
1310 113 nats_call_str(self, self->on_error, 0, err);
1311 113 ▶ if (pin) SvREFCNT_dec(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_dec(pin); 113 0 113
1312 1 ▶ } else if (self->cb_depth > 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (self->cb_depth > 0) { 1 0 1
1313 /* Async context with no handler: stashing the first error and
1314 croaking it at the outermost wrapper exit lets the caller's
1315 cleanup and reconnect logic run instead of longjmping past it. */
1316 1 ▶ if (!self->pending_croak)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->pending_croak) 1 0 1
1317 1 nats_set_str(&self->pending_croak, err);
1318 } else {
1319 0 croak("EV::Nats: %s", err);
1320 }
1321 114 }
1322  
1323 /* Report err, then tear down -- unless on_error already replaced the socket. */
1324 84 static void nats_fail(nats_t *self, const char *err)
1325 {
1326 84 unsigned gen = self->conn_gen;
1327 84 ▶ if (self->owner_sv)
Branch: 1 branch
BranchTrueFalseTotal
if (self->owner_sv) 84 0 84
1328 84 sv_2mortal(SvREFCNT_inc(self->owner_sv));
1329 84 nats_emit_error(self, err);
1330 84 ▶ if (gen == self->conn_gen)
Branch: 1 branch
BranchTrueFalseTotal
if (gen == self->conn_gen) 83 1 84
1331 83 nats_cleanup(self);
1332 84 }
1333  
1334 /* Fire a deferred no-on_error croak after bookkeeping has run.
1335 Take-before-fire: the croak longjmps. */
1336 static void
1337 1 nats_fire_pending_croak(nats_t *self)
1338 {
1339 1 char *msg = self->pending_croak;
1340 1 self->pending_croak = NULL;
1341 1 SV *sv = sv_2mortal(newSVpvf("EV::Nats: %s", msg));
1342 1 Safefree(msg);
1343 1 croak_sv(sv);
1344 }
1345  
1346 /* keeps pong_cbs 1:1 with the PINGs sent */
1347 104 static void nats_push_pong_marker(nats_t *self)
1348 {
1349 nats_pong_cb_t *pcb;
1350 104 Newxz(pcb, 1, nats_pong_cb_t);
1351 104 pcb->kind = PONG_INTERNAL;
1352 104 ngx_queue_insert_tail(&self->pong_cbs, &pcb->queue);
1353 104 }
1354  
1355 /* ================================================================
1356 * CONNECT command builder
1357 * ================================================================ */
1358  
1359 #define CONNECT_BUF_SIZE 8192
1360 #define CONNECT_APPEND(fmt, ...) \
1361 do { \
1362 if (off >= (int)sizeof(buf)) { overflow = 1; break; } \
1363 int _n = snprintf(buf + off, sizeof(buf) - off, fmt, ##__VA_ARGS__); \
1364 if (_n < 0 || _n >= (int)(sizeof(buf) - off)) { overflow = 1; break; } \
1365 off += _n; \
1366 } while(0)
1367  
1368 #define CONNECT_STR(key, val) \
1369 do { \
1370 int _e = json_escape_string(escaped, sizeof(escaped), (val)); \
1371 if (_e < 0) overflow = 1; \
1372 else CONNECT_APPEND(",\"" key "\":%.*s", _e, escaped); \
1373 } while (0)
1374  
1375 /* 0 when it failed the connection instead: on_error may have replaced it */
1376 91 static int nats_send_connect(nats_t *self)
1377 {
1378 char buf[CONNECT_BUF_SIZE];
1379 /* sized to the whole buffer: production JWTs exceed 1 KB */
1380 91 int off = 0;
1381 91 int overflow = 0;
1382 char escaped[CONNECT_BUF_SIZE];
1383  
1384 91 ▶ CONNECT_APPEND("CONNECT {");
Branch: 3 branches
BranchTrueFalseTotal
CONNECT_APPEND("CONNECT {"); 0 91 91
CONNECT_APPEND("CONNECT {"); 91 0 91
CONNECT_APPEND("CONNECT {"); 0 91 91
1385 91 ▶ CONNECT_APPEND("\"verbose\":%s,\"pedantic\":%s,\"echo\":%s",
Branch: 6 branches
BranchTrueFalseTotal
CONNECT_APPEND("\"verbose\":%s,\"pedantic\":%s,\"echo\":%s", 0 91 91
CONNECT_APPEND("\"verbose\":%s,\"pedantic\":%s,\"echo\":%s", 91 0 91
CONNECT_APPEND("\"verbose\":%s,\"pedantic\":%s,\"echo\":%s", 0 91 91
CONNECT_APPEND("\"verbose\":%s,\"pedantic\":%s,\"echo\":%s", 0 91 91
CONNECT_APPEND("\"verbose\":%s,\"pedantic\":%s,\"echo\":%s", 91 0 91
CONNECT_APPEND("\"verbose\":%s,\"pedantic\":%s,\"echo\":%s", 0 91 91
1386 self->verbose ? "true" : "false",
1387 self->pedantic ? "true" : "false",
1388 self->echo ? "true" : "false");
1389 91 ▶ CONNECT_APPEND(",\"protocol\":1");
Branch: 3 branches
BranchTrueFalseTotal
CONNECT_APPEND(",\"protocol\":1"); 0 91 91
CONNECT_APPEND(",\"protocol\":1"); 91 0 91
CONNECT_APPEND(",\"protocol\":1"); 0 91 91
1390 91 ▶ if (self->no_responders)
Branch: 1 branch
BranchTrueFalseTotal
if (self->no_responders) 0 91 91
1391 0 ▶ CONNECT_APPEND(",\"no_responders\":true");
Branch: 3 branches
BranchTrueFalseTotal
CONNECT_APPEND(",\"no_responders\":true"); 0 0 0
CONNECT_APPEND(",\"no_responders\":true"); 0 0 0
CONNECT_APPEND(",\"no_responders\":true"); 0 0 0
1392 91 ▶ CONNECT_APPEND(",\"headers\":true");
Branch: 3 branches
BranchTrueFalseTotal
CONNECT_APPEND(",\"headers\":true"); 0 91 91
CONNECT_APPEND(",\"headers\":true"); 91 0 91
CONNECT_APPEND(",\"headers\":true"); 0 91 91
1393 91 ▶ CONNECT_APPEND(",\"lang\":\"perl-xs\",\"version\":\"" EV_NATS_VERSION "\"");
Branch: 3 branches
BranchTrueFalseTotal
CONNECT_APPEND(",\"lang\":\"perl-xs\",\"version\":\"" EV_NATS_VERSION "\""); 0 91 91
CONNECT_APPEND(",\"lang\":\"perl-xs\",\"version\":\"" EV_NATS_VERSION "\""); 91 0 91
CONNECT_APPEND(",\"lang\":\"perl-xs\",\"version\":\"" EV_NATS_VERSION "\""); 0 91 91
1394  
1395 91 ▶ if (self->user) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->user) { 1 90 91
1396 1 ▶ CONNECT_STR("user", self->user);
Branch: 4 branches
BranchTrueFalseTotal
CONNECT_STR("user", self->user); 0 1 1
CONNECT_STR("user", self->user); 0 1 1
CONNECT_STR("user", self->user); 1 0 1
CONNECT_STR("user", self->user); 0 1 1
1397 1 ▶ if (self->pass)
Branch: 1 branch
BranchTrueFalseTotal
if (self->pass) 1 0 1
1398 1 ▶ CONNECT_STR("pass", self->pass);
Branch: 4 branches
BranchTrueFalseTotal
CONNECT_STR("pass", self->pass); 0 1 1
CONNECT_STR("pass", self->pass); 0 1 1
CONNECT_STR("pass", self->pass); 1 0 1
CONNECT_STR("pass", self->pass); 0 1 1
1399 }
1400 91 ▶ if (self->token)
Branch: 1 branch
BranchTrueFalseTotal
if (self->token) 0 91 91
1401 0 ▶ CONNECT_STR("auth_token", self->token);
Branch: 4 branches
BranchTrueFalseTotal
CONNECT_STR("auth_token", self->token); 0 0 0
CONNECT_STR("auth_token", self->token); 0 0 0
CONNECT_STR("auth_token", self->token); 0 0 0
CONNECT_STR("auth_token", self->token); 0 0 0
1402 91 ▶ if (self->name)
Branch: 1 branch
BranchTrueFalseTotal
if (self->name) 1 90 91
1403 1 ▶ CONNECT_STR("name", self->name);
Branch: 4 branches
BranchTrueFalseTotal
CONNECT_STR("name", self->name); 1 0 1
CONNECT_STR("name", self->name); 0 0 0
CONNECT_STR("name", self->name); 0 0 0
CONNECT_STR("name", self->name); 0 0 0
1404 91 ▶ if (self->jwt)
Branch: 1 branch
BranchTrueFalseTotal
if (self->jwt) 0 91 91
1405 0 ▶ CONNECT_STR("jwt", self->jwt);
Branch: 4 branches
BranchTrueFalseTotal
CONNECT_STR("jwt", self->jwt); 0 0 0
CONNECT_STR("jwt", self->jwt); 0 0 0
CONNECT_STR("jwt", self->jwt); 0 0 0
CONNECT_STR("jwt", self->jwt); 0 0 0
1406 #ifdef HAVE_OPENSSL
1407 91 ▶ if (self->nkey_seed && self->server_nonce) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->nkey_seed && self->server_nonce) { 0 91 91
if (self->nkey_seed && self->server_nonce) { 0 0 0
1408 char sig[128];
1409 char pub[64];
1410 0 ▶ if (nats_nkey_sign(self->nkey_seed, self->server_nonce,
Branch: 1 branch
BranchTrueFalseTotal
if (nats_nkey_sign(self->nkey_seed, self->server_nonce, 0 0 0
1411 0 ▶ strlen(self->server_nonce), sig, sizeof(sig)) > 0 &&
Branch: 1 branch
BranchTrueFalseTotal
strlen(self->server_nonce), sig, sizeof(sig)) > 0 && 0 0 0
1412 0 nats_nkey_public(self->nkey_seed, pub, sizeof(pub)) > 0) {
1413 0 ▶ CONNECT_APPEND(",\"nkey\":\"%s\",\"sig\":\"%s\"", pub, sig);
Branch: 3 branches
BranchTrueFalseTotal
CONNECT_APPEND(",\"nkey\":\"%s\",\"sig\":\"%s\"", pub, sig); 0 0 0
CONNECT_APPEND(",\"nkey\":\"%s\",\"sig\":\"%s\"", pub, sig); 0 0 0
CONNECT_APPEND(",\"nkey\":\"%s\",\"sig\":\"%s\"", pub, sig); 0 0 0
1414 }
1415 }
1416 #endif
1417  
1418 91 ▶ CONNECT_APPEND("}\r\n");
Branch: 3 branches
BranchTrueFalseTotal
CONNECT_APPEND("}\r\n"); 0 91 91
CONNECT_APPEND("}\r\n"); 91 0 91
CONNECT_APPEND("}\r\n"); 0 91 91
1419  
1420 91 ▶ if (overflow) {
Branch: 1 branch
BranchTrueFalseTotal
if (overflow) { 1 90 91
1421 /* deterministic local failure: retries cannot help */
1422 1 self->intentional_disconnect = 1;
1423 1 nats_fail(self, "CONNECT command too long (auth/name fields)");
1424 1 return 0;
1425 }
1426  
1427 90 wbuf_append(self, buf, off);
1428  
1429 90 nats_resub_all(self);
1430 90 self->connect_sent = 1;
1431  
1432 90 wbuf_append(self, "PING\r\n", 6);
1433 90 nats_push_pong_marker(self);
1434 90 return 1;
1435 }
1436  
1437 /* ================================================================
1438 * Protocol parser
1439 * ================================================================ */
1440  
1441 /* 0 on success; -1 on empty input, a non-digit or overflow */
1442 343 static int nats_parse_u64(const char *tok, size_t tok_len, uint64_t *out)
1443 {
1444 343 uint64_t v = 0;
1445 size_t i;
1446 343 ▶ if (tok_len == 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (tok_len == 0) return -1; 0 343 343
1447 1349 ▶ for (i = 0; i < tok_len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < tok_len; i++) { 1010 339 1349
1448 uint64_t d;
1449 1010 ▶ if (tok[i] < '0' || tok[i] > '9') return -1;
Branch: 2 branches
BranchTrueFalseTotal
if (tok[i] < '0' || tok[i] > '9') return -1; 1009 1 1010
if (tok[i] < '0' || tok[i] > '9') return -1; 0 1009 1009
1450 1009 d = (uint64_t)(tok[i] - '0');
1451 1009 ▶ if (v > (UINT64_MAX - d) / 10) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (v > (UINT64_MAX - d) / 10) return -1; 3 1006 1009
1452 1006 v = v * 10 + d;
1453 }
1454 339 *out = v;
1455 339 return 0;
1456 }
1457  
1458 116 static int nats_parse_size(const char *tok, size_t tok_len, size_t *out)
1459 {
1460 uint64_t v;
1461 116 ▶ if (nats_parse_u64(tok, tok_len, &v) != 0 || v > (uint64_t)SIZE_MAX) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (nats_parse_u64(tok, tok_len, &v) != 0 || v > (uint64_t)SIZE_MAX) return -1; 2 114 116
1462 114 *out = (size_t)v;
1463 114 return 0;
1464 }
1465  
1466 /* MSG <subject> <sid> [reply] <#bytes>
1467 HMSG <subject> <sid> [reply] <#header bytes> <#total bytes> */
1468 102 static int nats_parse_msg_line(nats_t *self, char *line, size_t len, int hmsg)
1469 {
1470 102 ▶ char *p = line + (hmsg ? 5 : 4), *end = line + len;
Branch: 1 branch
BranchTrueFalseTotal
char *p = line + (hmsg ? 5 : 4), *end = line + len; 16 86 102
1471 char *tok[6];
1472 size_t tlen[6];
1473 102 ▶ int n = 0, base = hmsg ? 4 : 3, i;
Branch: 1 branch
BranchTrueFalseTotal
int n = 0, base = hmsg ? 4 : 3, i; 16 86 102
1474  
1475 454 ▶ while (n < 6) {
Branch: 1 branch
BranchTrueFalseTotal
while (n < 6) { 454 0 454
1476 708 ▶ while (p < end && (*p == ' ' || *p == '\t')) p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < end && (*p == ' ' || *p == '\t')) p++; 606 102 708
while (p < end && (*p == ' ' || *p == '\t')) p++; 254 352 606
while (p < end && (*p == ' ' || *p == '\t')) p++; 0 352 352
1477 454 ▶ if (p >= end) break;
Branch: 1 branch
BranchTrueFalseTotal
if (p >= end) break; 102 352 454
1478 352 tok[n] = p;
1479 1992 ▶ while (p < end && *p != ' ' && *p != '\t') p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < end && *p != ' ' && *p != '\t') p++; 1891 101 1992
while (p < end && *p != ' ' && *p != '\t') p++; 1640 251 1891
while (p < end && *p != ' ' && *p != '\t') p++; 1640 0 1640
1480 352 tlen[n] = p - tok[n];
1481 352 n++;
1482 }
1483 102 ▶ if (n != base && n != base + 1)
Branch: 2 branches
BranchTrueFalseTotal
if (n != base && n != base + 1) 35 67 102
if (n != base && n != base + 1) 2 33 35
1484 2 return -1;
1485 100 i = n - base + 2; /* index of the first length token */
1486 100 ▶ if (nats_parse_u64(tok[1], tlen[1], &self->msg_sid) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (nats_parse_u64(tok[1], tlen[1], &self->msg_sid) != 0) 0 100 100
1487 0 return -1;
1488 100 self->msg_subject_off = tok[0] - self->rbuf;
1489 100 self->msg_subject_len = tlen[0];
1490 100 ▶ self->msg_reply_off = n > base ? (size_t)(tok[2] - self->rbuf) : 0;
Branch: 1 branch
BranchTrueFalseTotal
self->msg_reply_off = n > base ? (size_t)(tok[2] - self->rbuf) : 0; 33 67 100
1491 100 ▶ self->msg_reply_len = n > base ? tlen[2] : 0;
Branch: 1 branch
BranchTrueFalseTotal
self->msg_reply_len = n > base ? tlen[2] : 0; 33 67 100
1492 100 self->msg_hdr_len = 0;
1493 100 ▶ if (hmsg) {
Branch: 1 branch
BranchTrueFalseTotal
if (hmsg) { 16 84 100
1494 16 ▶ if (nats_parse_size(tok[i], tlen[i], &self->msg_hdr_len) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (nats_parse_size(tok[i], tlen[i], &self->msg_hdr_len) != 0) 0 16 16
1495 0 return -1;
1496 16 i++;
1497 }
1498 100 ▶ if (nats_parse_size(tok[i], tlen[i], &self->msg_total_len) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (nats_parse_size(tok[i], tlen[i], &self->msg_total_len) != 0) 2 98 100
1499 2 return -1;
1500 /* an impossible header length delivers the frame as raw payload */
1501 98 ▶ if (self->msg_hdr_len > self->msg_total_len)
Branch: 1 branch
BranchTrueFalseTotal
if (self->msg_hdr_len > self->msg_total_len) 1 97 98
1502 1 self->msg_hdr_len = 0;
1503 98 self->msg_type = hmsg ? MSG_TYPE_HMSG : MSG_TYPE_MSG;
1504 98 return 0;
1505 }
1506  
1507 54 static void nats_process_msg(nats_t *self, char *payload, size_t len)
1508 {
1509 54 nats_sub_t *sub = nats_find_sub(self, self->msg_sid);
1510 54 ▶ if (!sub) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sub) return; 0 54 54
1511  
1512 54 self->msgs_in++;
1513 54 self->bytes_in += len;
1514 54 sub->received++;
1515  
1516 54 int max_msgs = sub->max_msgs;
1517 54 int received = sub->received;
1518 54 uint64_t sid = sub->sid;
1519  
1520 54 ▶ if (sub->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (sub->cb) { 54 0 54
1521 54 dSP;
1522 54 ENTER; SAVETMPS;
1523 54 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 54 54
1524 54 ▶ EXTEND(SP, 4);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 4); 0 54 54
1525  
1526 54 PUSHs(sv_2mortal(newSVpvn(self->rbuf + self->msg_subject_off, self->msg_subject_len)));
1527  
1528 54 ▶ if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) {
Branch: 3 branches
BranchTrueFalseTotal
if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) { 9 45 54
if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) { 7 2 9
if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) { 7 0 7
1529 7 PUSHs(sv_2mortal(newSVpvn(payload + self->msg_hdr_len, len - self->msg_hdr_len)));
1530 } else {
1531 47 PUSHs(sv_2mortal(newSVpvn(payload, len)));
1532 }
1533  
1534 54 ▶ if (self->msg_reply_len > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->msg_reply_len > 0) { 28 26 54
1535 28 PUSHs(sv_2mortal(newSVpvn(self->rbuf + self->msg_reply_off, self->msg_reply_len)));
1536 } else {
1537 26 PUSHs(&PL_sv_undef);
1538 }
1539  
1540 54 ▶ if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) {
Branch: 3 branches
BranchTrueFalseTotal
if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) { 9 45 54
if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) { 7 2 9
if (self->msg_type == MSG_TYPE_HMSG && self->msg_hdr_len > 0 && self->msg_hdr_len <= len) { 7 0 7
1541 7 PUSHs(sv_2mortal(newSVpvn(payload, self->msg_hdr_len)));
1542 }
1543  
1544 54 PUTBACK;
1545 /* a callback that unsubscribes its own sid frees the sub mid-call */
1546 54 nats_invoke(self, sub->cb);
1547 54 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 54 0 54
1548 }
1549  
1550 54 ▶ if (max_msgs > 0 && received >= max_msgs) {
Branch: 2 branches
BranchTrueFalseTotal
if (max_msgs > 0 && received >= max_msgs) { 1 53 54
if (max_msgs > 0 && received >= max_msgs) { 1 0 1
1551 1 sub = nats_find_sub(self, sid);
1552 1 ▶ if (sub)
Branch: 1 branch
BranchTrueFalseTotal
if (sub) 1 0 1
1553 1 nats_remove_sub(self, sub);
1554 }
1555 }
1556  
1557 34 static void nats_check_inbox_response(nats_t *self, const char *subject, size_t subject_len,
1558 const char *payload, size_t payload_len,
1559 const char *headers, size_t headers_len)
1560 {
1561 34 size_t pfx_len = strlen(self->inbox_prefix);
1562 34 ▶ if (subject_len <= pfx_len || memcmp(subject, self->inbox_prefix, pfx_len) != 0)
Branch: 2 branches
BranchTrueFalseTotal
if (subject_len <= pfx_len || memcmp(subject, self->inbox_prefix, pfx_len) != 0) 34 0 34
if (subject_len <= pfx_len || memcmp(subject, self->inbox_prefix, pfx_len) != 0) 0 34 34
1563 34 return;
1564  
1565 uint64_t req_id;
1566 34 ▶ if (nats_parse_u64(subject + pfx_len, subject_len - pfx_len, &req_id) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (nats_parse_u64(subject + pfx_len, subject_len - pfx_len, &req_id) != 0) 1 33 34
1567 1 return;
1568  
1569 ngx_queue_t *q;
1570 33 ▶ ngx_queue_foreach(q, &self->req_queue) {
Branch: 2 branches
BranchTrueFalseTotal
ngx_queue_foreach(q, &self->req_queue) { 33 0 33
ngx_queue_foreach(q, &self->req_queue) { 33 0 33
1571 33 nats_req_t *req = ngx_queue_data(q, nats_req_t, queue);
1572 33 ▶ if (req->req_id == req_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (req->req_id == req_id) { 33 0 33
1573 33 ngx_queue_remove(q);
1574 33 ▶ if (req->timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (req->timer_active) { 33 0 33
1575 33 ev_timer_stop(self->loop, &req->timer);
1576 33 req->timer_active = 0;
1577 }
1578 33 ▶ if (req->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (req->cb) { 33 0 33
1579 33 dSP;
1580 40 ▶ int is_no_responders = (headers && headers_len >= 12 &&
Branch: 2 branches
BranchTrueFalseTotal
int is_no_responders = (headers && headers_len >= 12 && 7 26 33
int is_no_responders = (headers && headers_len >= 12 && 7 0 7
1581 7 ▶ memcmp(headers, "NATS/1.0 503", 12) == 0);
Branch: 1 branch
BranchTrueFalseTotal
memcmp(headers, "NATS/1.0 503", 12) == 0); 3 4 7
1582 33 ENTER; SAVETMPS;
1583 33 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 33 33
1584 33 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 33 33
1585 33 ▶ if (is_no_responders) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_no_responders) { 3 30 33
1586 3 PUSHs(&PL_sv_undef);
1587 3 PUSHs(sv_2mortal(newSVpvn("no responders", 13)));
1588 } else {
1589 30 PUSHs(sv_2mortal(newSVpvn(payload, payload_len)));
1590 30 PUSHs(&PL_sv_undef);
1591 30 ▶ if (headers && headers_len > 0)
Branch: 2 branches
BranchTrueFalseTotal
if (headers && headers_len > 0) 4 26 30
if (headers && headers_len > 0) 4 0 4
1592 4 PUSHs(sv_2mortal(newSVpvn(headers, headers_len)));
1593 }
1594 33 PUTBACK;
1595 33 nats_invoke(self, req->cb);
1596 33 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 33 0 33
1597 33 SvREFCNT_dec(req->cb);
1598 }
1599 33 Safefree(req);
1600 33 return;
1601 }
1602 }
1603 }
1604  
1605 214 static void nats_process_line(nats_t *self, char *line, size_t len)
1606 {
1607 214 ▶ if (len > 0 && line[len-1] == '\r')
Branch: 2 branches
BranchTrueFalseTotal
if (len > 0 && line[len-1] == '\r') 214 0 214
if (len > 0 && line[len-1] == '\r') 214 0 214
1608 214 len--;
1609  
1610 214 ▶ if (len == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (len == 0) return; 1 213 214
1611  
1612 213 ▶ if (len > 5 && (line[0] == 'I' || line[0] == 'i') &&
Branch: 3 branches
BranchTrueFalseTotal
if (len > 5 && (line[0] == 'I' || line[0] == 'i') && 102 111 213
if (len > 5 && (line[0] == 'I' || line[0] == 'i') && 5 97 102
if (len > 5 && (line[0] == 'I' || line[0] == 'i') && 0 5 5
1613 97 ▶ (line[1] == 'N' || line[1] == 'n') &&
Branch: 2 branches
BranchTrueFalseTotal
(line[1] == 'N' || line[1] == 'n') && 0 97 97
(line[1] == 'N' || line[1] == 'n') && 0 0 0
1614 97 ▶ (line[2] == 'F' || line[2] == 'f') &&
Branch: 2 branches
BranchTrueFalseTotal
(line[2] == 'F' || line[2] == 'f') && 0 97 97
(line[2] == 'F' || line[2] == 'f') && 0 0 0
1615 97 ▶ (line[3] == 'O' || line[3] == 'o') &&
Branch: 2 branches
BranchTrueFalseTotal
(line[3] == 'O' || line[3] == 'o') && 0 97 97
(line[3] == 'O' || line[3] == 'o') && 0 0 0
1616 97 ▶ line[4] == ' ') {
Branch: 1 branch
BranchTrueFalseTotal
line[4] == ' ') { 97 0 97
1617  
1618 97 const char *p = line + 5, *e = line + len, *v;
1619 int enter_ldm;
1620 97 unsigned gen = self->conn_gen;
1621 97 ▶ CLEAR_HANDLER(self->server_info_json);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->server_info_json); 15 82 97
1622 97 self->server_info_json = newSVpvn(p, len - 5);
1623  
1624 97 ▶ if ((v = nats_info_value(p, e, "\"max_payload\":"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((v = nats_info_value(p, e, "\"max_payload\":"))) { 93 4 97
1625 93 const char *d = v;
1626 uint64_t mp;
1627 753 ▶ while (d < e && *d >= '0' && *d <= '9') d++;
Branch: 3 branches
BranchTrueFalseTotal
while (d < e && *d >= '0' && *d <= '9') d++; 753 0 753
while (d < e && *d >= '0' && *d <= '9') d++; 691 62 753
while (d < e && *d >= '0' && *d <= '9') d++; 660 31 691
1628 93 ▶ if (d > v) {
Branch: 1 branch
BranchTrueFalseTotal
if (d > v) { 93 0 93
1629 /* a hostile INFO must not wrap the signed field negative */
1630 93 ▶ if (nats_parse_u64(v, d - v, &mp) != 0 || mp > (uint64_t)INT_MAX)
Branch: 2 branches
BranchTrueFalseTotal
if (nats_parse_u64(v, d - v, &mp) != 0 || mp > (uint64_t)INT_MAX) 92 1 93
if (nats_parse_u64(v, d - v, &mp) != 0 || mp > (uint64_t)INT_MAX) 1 91 92
1631 2 mp = INT_MAX;
1632 93 ▶ if (mp > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (mp > 0) 93 0 93
1633 93 self->max_payload = (int)mp;
1634 }
1635 }
1636  
1637 97 nats_parse_connect_urls(self, p, e - p);
1638  
1639 97 ▶ if ((v = nats_info_value(p, e, "\"nonce\":")) && v < e && *v == '"') {
Branch: 3 branches
BranchTrueFalseTotal
if ((v = nats_info_value(p, e, "\"nonce\":")) && v < e && *v == '"') { 1 96 97
if ((v = nats_info_value(p, e, "\"nonce\":")) && v < e && *v == '"') { 1 0 1
if ((v = nats_info_value(p, e, "\"nonce\":")) && v < e && *v == '"') { 1 0 1
1640 1 const char *nend = memchr(v + 1, '"', e - v - 1);
1641 1 ▶ if (nend)
Branch: 1 branch
BranchTrueFalseTotal
if (nend) 0 1 1
1642 0 nats_set_strn(&self->server_nonce, v + 1, nend - v - 1);
1643 }
1644  
1645 97 v = nats_info_value(p, e, "\"ldm\":");
1646 97 ▶ enter_ldm = v && v < e && *v == 't' && !self->ldm;
Branch: 4 branches
BranchTrueFalseTotal
enter_ldm = v && v < e && *v == 't' && !self->ldm; 1 96 97
enter_ldm = v && v < e && *v == 't' && !self->ldm; 1 0 1
enter_ldm = v && v < e && *v == 't' && !self->ldm; 1 0 1
enter_ldm = v && v < e && *v == 't' && !self->ldm; 1 0 1
1647  
1648 97 ▶ if (self->connecting) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connecting) { 92 5 97
1649 /* tls_required: CONNECT would leak credentials over plaintext
1650 before the server could reject it; refuse instead */
1651 92 int tls_active = 0;
1652 #ifdef HAVE_OPENSSL
1653 92 tls_active = self->tls;
1654 #endif
1655 92 v = nats_info_value(p, e, "\"tls_required\":");
1656 92 ▶ if (v && e - v >= 4 && memcmp(v, "true", 4) == 0 && !tls_active) {
Branch: 4 branches
BranchTrueFalseTotal
if (v && e - v >= 4 && memcmp(v, "true", 4) == 0 && !tls_active) { 1 91 92
if (v && e - v >= 4 && memcmp(v, "true", 4) == 0 && !tls_active) { 1 0 1
if (v && e - v >= 4 && memcmp(v, "true", 4) == 0 && !tls_active) { 1 0 1
if (v && e - v >= 4 && memcmp(v, "true", 4) == 0 && !tls_active) { 1 0 1
1657 1 self->intentional_disconnect = 1;
1658 1 nats_fail(self, "server requires TLS but TLS is not enabled");
1659 1 return;
1660 }
1661 #ifdef HAVE_OPENSSL
1662 91 ▶ if (self->tls && !self->ssl) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->tls && !self->ssl) { 0 91 91
if (self->tls && !self->ssl) { 0 0 0
1663 0 ▶ if (nats_ssl_setup(self) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (nats_ssl_setup(self) != 0) { 0 0 0
1664 0 nats_ssl_fail(self, "SSL setup failed");
1665 0 return;
1666 }
1667 0 self->ssl_handshaking = 1;
1668 0 int hret = nats_ssl_handshake(self);
1669 0 ▶ if (hret < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hret < 0) { 0 0 0
1670 0 nats_ssl_fail(self, "SSL handshake failed");
1671 0 return;
1672 }
1673 0 ▶ if (hret == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (hret == 1) { 0 0 0
1674 0 self->ssl_handshaking = 0;
1675 0 ▶ if (nats_send_connect(self))
Branch: 1 branch
BranchTrueFalseTotal
if (nats_send_connect(self)) 0 0 0
1676 0 nats_try_write(self);
1677 }
1678 /* hret == 0: handshake in progress; nats_on_read will resume. */
1679 } else
1680 #endif
1681 91 ▶ if (nats_send_connect(self))
Branch: 1 branch
BranchTrueFalseTotal
if (nats_send_connect(self)) 90 1 91
1682 90 nats_try_write(self);
1683 }
1684 /* last: on_lame_duck may move to another server */
1685 96 ▶ if (enter_ldm && self->fd >= 0 && gen == self->conn_gen) {
Branch: 3 branches
BranchTrueFalseTotal
if (enter_ldm && self->fd >= 0 && gen == self->conn_gen) { 1 95 96
if (enter_ldm && self->fd >= 0 && gen == self->conn_gen) { 1 0 1
if (enter_ldm && self->fd >= 0 && gen == self->conn_gen) { 1 0 1
1686 1 self->ldm = 1;
1687 1 ▶ if (self->on_ldm)
Branch: 1 branch
BranchTrueFalseTotal
if (self->on_ldm) 0 1 1
1688 0 nats_call0(self, self->on_ldm);
1689 }
1690 96 return;
1691 }
1692  
1693 116 ▶ if (len == 4 && memcmp(line, "PING", 4) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (len == 4 && memcmp(line, "PING", 4) == 0) { 108 8 116
if (len == 4 && memcmp(line, "PING", 4) == 0) { 1 107 108
1694 1 wbuf_append(self, "PONG\r\n", 6);
1695 1 nats_try_write(self);
1696 1 return;
1697 }
1698  
1699 115 ▶ if (len == 4 && memcmp(line, "PONG", 4) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (len == 4 && memcmp(line, "PONG", 4) == 0) { 107 8 115
if (len == 4 && memcmp(line, "PONG", 4) == 0) { 107 0 107
1700 107 nats_pong_cb_t *pcb = NULL;
1701 107 ▶ if (self->pings_outstanding > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->pings_outstanding > 0) 2 105 107
1702 2 self->pings_outstanding--;
1703 /* taken before any callback, whose nested loop may read more PONGs */
1704 107 ▶ if (!ngx_queue_empty(&self->pong_cbs)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ngx_queue_empty(&self->pong_cbs)) { 107 0 107
1705 107 ngx_queue_t *pq = ngx_queue_head(&self->pong_cbs);
1706 107 pcb = ngx_queue_data(pq, nats_pong_cb_t, queue);
1707 107 ngx_queue_remove(pq);
1708 }
1709  
1710 107 ▶ if (self->connecting && !self->connected) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->connecting && !self->connected) { 88 19 107
if (self->connecting && !self->connected) { 88 0 88
1711 /* the CONNECT's PING, whose entry is an internal marker */
1712 88 ▶ if (pcb) {
Branch: 1 branch
BranchTrueFalseTotal
if (pcb) { 88 0 88
1713 88 ▶ CLEAR_HANDLER(pcb->cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(pcb->cb); 0 88 88
1714 88 Safefree(pcb);
1715 }
1716 88 self->connecting = 0;
1717 88 self->connected = 1;
1718 88 self->reconnect_attempts = 0;
1719 /* connect succeeded: drop the saved list; reconnect re-resolves */
1720 88 nats_free_addrinfo(self);
1721  
1722 88 ▶ if (self->connect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timer_active) { 1 87 88
1723 1 ev_timer_stop(self->loop, &self->connect_timer);
1724 1 self->connect_timer_active = 0;
1725 }
1726  
1727 88 nats_start_ping_timer(self);
1728  
1729 /* Drain the outage backlog first: publishes from on_connect
1730 must queue behind it, not jump ahead of it. */
1731 88 nats_drain_waiting(self);
1732  
1733 /* flushes made while connecting fence that backlog */
1734 88 ▶ if (self->connected && !ngx_queue_empty(&self->flush_wait)) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected && !ngx_queue_empty(&self->flush_wait)) { 88 0 88
if (self->connected && !ngx_queue_empty(&self->flush_wait)) { 1 87 88
1735 2 ▶ while (!ngx_queue_empty(&self->flush_wait)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->flush_wait)) { 1 1 2
1736 1 ngx_queue_t *fq = ngx_queue_head(&self->flush_wait);
1737 1 ngx_queue_remove(fq);
1738 1 wbuf_append(self, "PING\r\n", 6);
1739 1 ngx_queue_insert_tail(&self->pong_cbs, fq);
1740 }
1741 1 nats_schedule_write(self);
1742 }
1743  
1744 88 ▶ if (self->connected && self->on_connect)
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected && self->on_connect) 88 0 88
if (self->connected && self->on_connect) 79 9 88
1745 79 nats_call0(self, self->on_connect);
1746 88 return;
1747 }
1748  
1749 19 ▶ if (!pcb)
Branch: 1 branch
BranchTrueFalseTotal
if (!pcb) 0 19 19
1750 0 return;
1751 19 ▶ if (pcb->kind == PONG_DRAIN || pcb->kind == PONG_DRAIN_LAST) {
Branch: 2 branches
BranchTrueFalseTotal
if (pcb->kind == PONG_DRAIN || pcb->kind == PONG_DRAIN_LAST) { 13 6 19
if (pcb->kind == PONG_DRAIN || pcb->kind == PONG_DRAIN_LAST) { 3 10 13
1752 9 unsigned gen = self->conn_gen;
1753 /* drained subscriptions are gone; a later connect must not revive them */
1754 11 ▶ while (!ngx_queue_empty(&self->subs))
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->subs)) 2 9 11
1755 2 nats_remove_sub(self, ngx_queue_data(ngx_queue_head(&self->subs), nats_sub_t, queue));
1756 9 self->inbox_sub_sid = 0;
1757 9 ▶ if (pcb->kind == PONG_DRAIN && self->wbuf_len > self->wbuf_off) {
Branch: 2 branches
BranchTrueFalseTotal
if (pcb->kind == PONG_DRAIN && self->wbuf_len > self->wbuf_off) { 6 3 9
if (pcb->kind == PONG_DRAIN && self->wbuf_len > self->wbuf_off) { 3 3 6
1758 3 pcb->kind = PONG_DRAIN_LAST;
1759 3 wbuf_append(self, "PING\r\n", 6);
1760 3 ngx_queue_insert_tail(&self->pong_cbs, &pcb->queue);
1761 3 nats_try_write(self);
1762 3 return;
1763 }
1764 6 Safefree(pcb);
1765 6 self->draining = 0;
1766 6 ▶ nats_fire_drain(self, NULL);
Branch: 1 branch
BranchTrueFalseTotal
nats_fire_drain(self, NULL); 6 0 6
1767 6 ▶ if (gen == self->conn_gen) {
Branch: 1 branch
BranchTrueFalseTotal
if (gen == self->conn_gen) { 6 0 6
1768 6 self->intentional_disconnect = 1;
1769 6 nats_cleanup(self);
1770 }
1771 6 return;
1772 }
1773 10 ▶ if (pcb->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (pcb->cb) { 8 2 10
1774 8 nats_call_str(self, pcb->cb, 0, NULL);
1775 8 SvREFCNT_dec(pcb->cb);
1776 }
1777 10 Safefree(pcb);
1778 10 return;
1779 }
1780  
1781 8 ▶ if (len >= 4 && memcmp(line, "-ERR", 4) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (len >= 4 && memcmp(line, "-ERR", 4) == 0) { 5 3 8
if (len >= 4 && memcmp(line, "-ERR", 4) == 0) { 3 2 5
1782 3 char *msg = line + 4;
1783 3 size_t mlen = len - 4;
1784 9 ▶ while (mlen > 0 && (*msg == ' ' || *msg == '\'')) { msg++; mlen--; }
Branch: 3 branches
BranchTrueFalseTotal
while (mlen > 0 && (*msg == ' ' || *msg == '\'')) { msg++; mlen--; } 9 0 9
while (mlen > 0 && (*msg == ' ' || *msg == '\'')) { msg++; mlen--; } 3 6 9
while (mlen > 0 && (*msg == ' ' || *msg == '\'')) { msg++; mlen--; } 3 3 6
1785 6 ▶ while (mlen > 0 && msg[mlen-1] == '\'') mlen--;
Branch: 2 branches
BranchTrueFalseTotal
while (mlen > 0 && msg[mlen-1] == '\'') mlen--; 6 0 6
while (mlen > 0 && msg[mlen-1] == '\'') mlen--; 3 3 6
1786  
1787 char errbuf[512];
1788 3 snprintf(errbuf, sizeof(errbuf), "%.*s", (int)mlen, msg);
1789  
1790 /* nats-server capitalizes these; strcasestr is not portable, so
1791 lowercase a bounded copy. Auth errors are fatal: no reconnect. */
1792 {
1793 char lc[512];
1794 3 size_t i, n = strlen(errbuf);
1795 84 ▶ for (i = 0; i < n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) 81 3 84
1796 89 ▶ lc[i] = (errbuf[i] >= 'A' && errbuf[i] <= 'Z')
Branch: 2 branches
BranchTrueFalseTotal
lc[i] = (errbuf[i] >= 'A' && errbuf[i] <= 'Z') 71 10 81
lc[i] = (errbuf[i] >= 'A' && errbuf[i] <= 'Z') 8 63 71
1797 8 ? errbuf[i] + ('a' - 'A') : errbuf[i];
1798 3 lc[n] = '\0';
1799 /* the server keeps the connection open after these */
1800 3 ▶ if (strncmp(lc, "permissions violation", 21) == 0
Branch: 1 branch
BranchTrueFalseTotal
if (strncmp(lc, "permissions violation", 21) == 0 2 1 3
1801 2 ▶ || strncmp(lc, "invalid subject", 15) == 0
Branch: 1 branch
BranchTrueFalseTotal
|| strncmp(lc, "invalid subject", 15) == 0 1 1 2
1802 1 ▶ || strncmp(lc, "maximum subscriptions exceeded", 30) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
|| strncmp(lc, "maximum subscriptions exceeded", 30) == 0) { 0 1 1
1803 2 nats_emit_error(self, errbuf);
1804 2 return;
1805 }
1806 /* a timeout means the client was slow, not refused: retry */
1807 1 ▶ if ((strstr(lc, "authorization") || strstr(lc, "authentication"))
Branch: 2 branches
BranchTrueFalseTotal
if ((strstr(lc, "authorization") || strstr(lc, "authentication")) 1 0 1
if ((strstr(lc, "authorization") || strstr(lc, "authentication")) 0 1 1
1808 0 ▶ && !strstr(lc, "authentication timeout"))
Branch: 1 branch
BranchTrueFalseTotal
&& !strstr(lc, "authentication timeout")) 0 0 0
1809 0 self->intentional_disconnect = 1;
1810 }
1811 1 nats_fail(self, errbuf);
1812 1 return;
1813 }
1814 }
1815  
1816 /* ================================================================
1817 * IO callbacks
1818 * ================================================================ */
1819  
1820 72 static int nats_failover_next_addr(nats_t *self)
1821 {
1822 72 ▶ if (!self->ai_next) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ai_next) return 0; 72 0 72
1823 0 nats_stop_watchers(self);
1824 0 close(self->fd);
1825 0 self->fd = -1;
1826 0 nats_connect_tcp(self);
1827 0 return 1;
1828 }
1829  
1830 423 static void nats_on_read_inner(nats_t *self)
1831 {
1832  
1833 #ifdef HAVE_OPENSSL
1834 423 ▶ if (self->ssl_handshaking) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl_handshaking) { 0 423 423
1835 0 int hret = nats_ssl_handshake(self);
1836 0 ▶ if (hret == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hret == 0) return; 0 0 0
1837 0 ▶ if (hret < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hret < 0) { 0 0 0
1838 0 nats_ssl_fail(self, "SSL handshake failed");
1839 0 return;
1840 }
1841 0 self->ssl_handshaking = 0;
1842 0 ▶ if (self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->writing) { 0 0 0
1843 0 ev_io_stop(self->loop, &self->wio);
1844 0 self->writing = 0;
1845 }
1846 /* the post-INFO upgrade is done: CONNECT goes over TLS */
1847 0 ▶ if (self->connecting) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connecting) { 0 0 0
1848 0 ▶ if (!nats_send_connect(self))
Branch: 1 branch
BranchTrueFalseTotal
if (!nats_send_connect(self)) 0 0 0
1849 0 return;
1850 0 nats_try_write(self);
1851 }
1852 0 ▶ if (self->fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd < 0) 0 0 0
1853 0 return;
1854 }
1855 #endif
1856  
1857 423 buf_ensure(&self->rbuf, &self->rbuf_cap, self->rbuf_len + BUF_INIT_SIZE);
1858  
1859 423 ssize_t n = nats_io_read(self, self->rbuf + self->rbuf_len,
1860 423 self->rbuf_cap - self->rbuf_len);
1861  
1862 423 ▶ if (n <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { 106 317 423
1863 106 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 32 74 106
1864 32 nats_cleanup(self);
1865 74 ▶ } else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
Branch: 3 branches
BranchTrueFalseTotal
} else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) { 74 0 74
} else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) { 74 0 74
} else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) { 74 0 74
1866 /* a refused nonblocking connect can surface here as a read
1867 error, before nats_on_write's SO_ERROR check -- fail over too */
1868 74 ▶ if (self->connect_pending && nats_failover_next_addr(self))
Branch: 2 branches
BranchTrueFalseTotal
if (self->connect_pending && nats_failover_next_addr(self)) 72 2 74
if (self->connect_pending && nats_failover_next_addr(self)) 0 72 72
1869 0 return;
1870 74 nats_fail(self, strerror(errno));
1871 }
1872 106 return;
1873 }
1874  
1875 317 self->rbuf_len += n;
1876 317 nats_parse(self);
1877 }
1878  
1879 88 static void nats_dispatch_msg(nats_t *self, char *payload)
1880 {
1881 88 size_t total = self->msg_total_len, hl = self->msg_hdr_len;
1882  
1883 88 ▶ if (!(self->inbox_sub_sid && self->msg_sid == self->inbox_sub_sid)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!(self->inbox_sub_sid && self->msg_sid == self->inbox_sub_sid)) { 34 54 88
if (!(self->inbox_sub_sid && self->msg_sid == self->inbox_sub_sid)) { 0 34 34
1884 54 nats_process_msg(self, payload, total);
1885 54 return;
1886 }
1887 34 self->msgs_in++;
1888 34 self->bytes_in += total;
1889 34 ▶ nats_check_inbox_response(self, self->rbuf + self->msg_subject_off, self->msg_subject_len,
Branch: 1 branch
BranchTrueFalseTotal
nats_check_inbox_response(self, self->rbuf + self->msg_subject_off, self->msg_subject_len, 7 27 34
1890 34 payload + hl, total - hl, hl ? payload : NULL, hl);
1891 }
1892  
1893 /* The parse offset is committed past each frame before its callback runs,
1894 so a callback that re-enters the loop resumes after it; nothing reads
1895 rbuf after a callback returns, so a nested pass may compact it. */
1896 317 static void nats_parse(nats_t *self)
1897 {
1898 623 ▶ while (self->fd >= 0 && self->rbuf_off < self->rbuf_len) {
Branch: 2 branches
BranchTrueFalseTotal
while (self->fd >= 0 && self->rbuf_off < self->rbuf_len) { 614 9 623
while (self->fd >= 0 && self->rbuf_off < self->rbuf_len) { 336 278 614
1899 #ifdef HAVE_OPENSSL
1900 /* bytes after an INFO that started TLS belong to the handshake */
1901 336 ▶ if (self->ssl_handshaking) break;
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl_handshaking) break; 0 336 336
1902 #endif
1903 336 size_t off = self->rbuf_off;
1904 336 char *start = self->rbuf + off;
1905 336 char *nl = (char *)memchr(start, '\n', self->rbuf_len - off);
1906 336 ▶ if (!nl) {
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) { 20 316 336
1907 20 ▶ if (self->rbuf_len - off > MAX_INBOUND_LINE)
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len - off > MAX_INBOUND_LINE) 1 19 20
1908 1 nats_fail(self, "maximum control line exceeded");
1909 20 break;
1910 }
1911 316 size_t line_len = nl - start;
1912 316 ▶ size_t len = line_len > 0 && start[line_len - 1] == '\r' ? line_len - 1 : line_len;
Branch: 2 branches
BranchTrueFalseTotal
size_t len = line_len > 0 && start[line_len - 1] == '\r' ? line_len - 1 : line_len; 316 0 316
size_t len = line_len > 0 && start[line_len - 1] == '\r' ? line_len - 1 : line_len; 316 0 316
1913 316 ▶ int hmsg = len >= 5 && memcmp(start, "HMSG ", 5) == 0;
Branch: 2 branches
BranchTrueFalseTotal
int hmsg = len >= 5 && memcmp(start, "HMSG ", 5) == 0; 204 112 316
int hmsg = len >= 5 && memcmp(start, "HMSG ", 5) == 0; 16 188 204
1914  
1915 404 ▶ if (hmsg || (len >= 4 && memcmp(start, "MSG ", 4) == 0)) {
Branch: 3 branches
BranchTrueFalseTotal
if (hmsg || (len >= 4 && memcmp(start, "MSG ", 4) == 0)) { 300 16 316
if (hmsg || (len >= 4 && memcmp(start, "MSG ", 4) == 0)) { 296 4 300
if (hmsg || (len >= 4 && memcmp(start, "MSG ", 4) == 0)) { 86 210 296
1916 102 size_t body_off = off + line_len + 1;
1917 /* An unparseable frame is dropped: the sender is trusted, and
1918 killing the connection over one corrupt frame is an outage. */
1919 102 ▶ if (nats_parse_msg_line(self, start, len, hmsg) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (nats_parse_msg_line(self, start, len, hmsg) != 0) { 4 98 102
1920 4 self->rbuf_off = body_off;
1921 4 continue;
1922 }
1923 98 ▶ if (self->msg_total_len > MAX_INBOUND_MSG) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->msg_total_len > MAX_INBOUND_MSG) { 1 97 98
1924 1 nats_fail(self, "server sent message exceeding 64 MiB");
1925 1 break;
1926 }
1927 97 ▶ if (self->rbuf_len - body_off < self->msg_total_len + 2)
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len - body_off < self->msg_total_len + 2) 9 88 97
1928 9 break;
1929 88 self->rbuf_off = body_off + self->msg_total_len + 2;
1930 88 nats_dispatch_msg(self, self->rbuf + body_off);
1931 } else {
1932 214 self->rbuf_off = off + line_len + 1;
1933 214 nats_process_line(self, start, line_len);
1934 }
1935 }
1936 317 ▶ if (self->rbuf_off > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_off > 0) { 277 40 317
1937 277 self->rbuf_len -= self->rbuf_off;
1938 277 ▶ if (self->rbuf_len > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len > 0) 1 276 277
1939 1 memmove(self->rbuf, self->rbuf + self->rbuf_off, self->rbuf_len);
1940 else
1941 276 buf_trim(&self->rbuf, &self->rbuf_cap);
1942 277 self->rbuf_off = 0;
1943 }
1944 317 }
1945  
1946 /* cb_depth bracket: DESTROY during the dispatch only sets destroy_pending
1947 and the free runs here. nats_destroy_now frees self - touch nothing after.
1948 libev runs watchers outside any perl statement, so mortals made here
1949 (the pins in nats_fail) need this scope or they live until EV::run returns. */
1950 static void nats_unwind(nats_t *self);
1951  
1952 686 static void nats_dispatch(nats_t *self, void (*inner)(nats_t *))
1953 {
1954 686 SV *pin = self->owner_sv;
1955 686 self->cb_depth++;
1956 686 ▶ if (pin) SvREFCNT_inc(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_inc(pin); 686 0 686
1957 686 ENTER; SAVETMPS;
1958 686 inner(self);
1959 686 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 80 606 686
1960 686 ▶ if (pin) SvREFCNT_dec(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_dec(pin); 686 0 686
1961 686 nats_unwind(self);
1962 684 }
1963  
1964 /* Closes a cb_depth bracket, a watcher's or a method's that runs callbacks:
1965 the deferred free, then a held die or a handler-less error. */
1966 912 static void nats_unwind(nats_t *self)
1967 {
1968 912 ▶ if (--self->cb_depth == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (--self->cb_depth == 0) { 888 24 912
1969 888 SV *die = self->pending_die;
1970 888 self->pending_die = NULL;
1971 888 ▶ if (self->destroy_pending)
Branch: 1 branch
BranchTrueFalseTotal
if (self->destroy_pending) 4 884 888
1972 4 nats_destroy_now(self);
1973 884 ▶ else if (die) {
Branch: 1 branch
BranchTrueFalseTotal
else if (die) { 6 878 884
1974 6 Safefree(self->pending_croak);
1975 6 self->pending_croak = NULL;
1976 878 ▶ } else if (self->pending_croak)
Branch: 1 branch
BranchTrueFalseTotal
} else if (self->pending_croak) 1 877 878
1977 1 nats_fire_pending_croak(self);
1978 887 ▶ if (die)
Branch: 1 branch
BranchTrueFalseTotal
if (die) 6 881 887
1979 6 croak_sv(sv_2mortal(die));
1980 }
1981 905 }
1982  
1983 /* Opens the bracket in a method whose work can run callbacks (a synchronous
1984 write failure tears down): a die is held to nats_unwind, so it cannot cut
1985 that work short. */
1986 #define NATS_HOLD_DIES(self) STMT_START { \
1987 if ((self)->owner_sv) \
1988 sv_2mortal(SvREFCNT_inc((self)->owner_sv)); \
1989 (self)->cb_depth++; \
1990 } STMT_END
1991  
1992 #define NATS_WATCHER_CB(name, wtype, member) \
1993 static void name(struct ev_loop *loop, wtype *w, int revents) \
1994 { \
1995 (void)loop; (void)revents; \
1996 nats_dispatch((nats_t *)((char *)w - offsetof(nats_t, member)), name##_inner); \
1997 }
1998  
1999 423 NATS_WATCHER_CB(nats_on_read, ev_io, rio)
2000  
2001 301 static void nats_try_write(nats_t *self)
2002 {
2003 301 ▶ if (self->fd < 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd < 0) return; 0 301 301
2004  
2005 495 ▶ while (self->wbuf_off < self->wbuf_len) {
Branch: 1 branch
BranchTrueFalseTotal
while (self->wbuf_off < self->wbuf_len) { 199 296 495
2006 199 ssize_t n = nats_io_write(self, self->wbuf + self->wbuf_off,
2007 199 self->wbuf_len - self->wbuf_off);
2008 199 ▶ if (n <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { 5 194 199
2009 5 ▶ if (n == 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
Branch: 3 branches
BranchTrueFalseTotal
if (n == 0 || errno == EAGAIN || errno == EWOULDBLOCK) { 5 0 5
if (n == 0 || errno == EAGAIN || errno == EWOULDBLOCK) { 5 0 5
if (n == 0 || errno == EAGAIN || errno == EWOULDBLOCK) { 0 5 5
2010 0 ▶ if (!self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->writing) { 0 0 0
2011 0 ev_io_start(self->loop, &self->wio);
2012 0 self->writing = 1;
2013 }
2014 0 return;
2015 }
2016 5 ▶ if (errno == EINTR)
Branch: 1 branch
BranchTrueFalseTotal
if (errno == EINTR) 0 5 5
2017 0 continue;
2018 5 self->slow_fired = 0;
2019 5 nats_fail(self, strerror(errno));
2020 5 return;
2021 }
2022 194 self->wbuf_off += n;
2023 }
2024  
2025 296 self->wbuf_off = 0;
2026 296 self->wbuf_len = 0;
2027 296 buf_trim(&self->wbuf, &self->wbuf_cap);
2028 296 self->slow_fired = 0; /* buffer drained: re-arm slow-consumer edge */
2029  
2030 296 ▶ if (self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->writing) { 95 201 296
2031 95 ev_io_stop(self->loop, &self->wio);
2032 95 self->writing = 0;
2033 }
2034 }
2035  
2036 91 static void nats_on_write_inner(nats_t *self)
2037 {
2038 91 ▶ if (self->connect_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_pending) { 91 0 91
2039 91 int err = 0;
2040 91 socklen_t errlen = sizeof(err);
2041 91 getsockopt(self->fd, SOL_SOCKET, SO_ERROR, &err, &errlen);
2042 91 ▶ if (err) {
Branch: 1 branch
BranchTrueFalseTotal
if (err) { 0 91 91
2043 0 ▶ if (!nats_failover_next_addr(self))
Branch: 1 branch
BranchTrueFalseTotal
if (!nats_failover_next_addr(self)) 0 0 0
2044 0 nats_fail(self, strerror(err));
2045 0 return;
2046 }
2047 /* TCP connect complete. Fall through: wbuf may already hold part
2048 of the CONNECT flush; nats_try_write disarms wio once empty. */
2049 91 self->connect_pending = 0;
2050 }
2051  
2052 #ifdef HAVE_OPENSSL
2053 /* resume a TLS handshake stalled on SSL_ERROR_WANT_WRITE */
2054 91 ▶ if (self->ssl_handshaking) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl_handshaking) { 0 91 91
2055 0 int hret = nats_ssl_handshake(self);
2056 0 ▶ if (hret < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hret < 0) { 0 0 0
2057 0 nats_ssl_fail(self, "SSL handshake failed");
2058 0 return;
2059 }
2060 0 ▶ if (hret == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hret == 0) return; 0 0 0
2061 0 self->ssl_handshaking = 0;
2062 0 ▶ if (self->connecting && !nats_send_connect(self))
Branch: 2 branches
BranchTrueFalseTotal
if (self->connecting && !nats_send_connect(self)) 0 0 0
if (self->connecting && !nats_send_connect(self)) 0 0 0
2063 0 return;
2064 }
2065 #endif
2066  
2067 91 nats_try_write(self);
2068 }
2069  
2070 91 NATS_WATCHER_CB(nats_on_write, ev_io, wio)
2071  
2072 /* ================================================================
2073 * Timer callbacks
2074 * ================================================================ */
2075  
2076 0 static void nats_on_connect_timeout_inner(nats_t *self)
2077 {
2078 0 self->connect_timer_active = 0;
2079 /* an address that swallows the SYN: the host's next one may answer */
2080 0 ▶ if (self->connect_pending && nats_failover_next_addr(self))
Branch: 2 branches
BranchTrueFalseTotal
if (self->connect_pending && nats_failover_next_addr(self)) 0 0 0
if (self->connect_pending && nats_failover_next_addr(self)) 0 0 0
2081 0 return;
2082 0 nats_fail(self, "connect timeout");
2083 }
2084  
2085 0 NATS_WATCHER_CB(nats_on_connect_timeout, ev_timer, connect_timer)
2086  
2087 82 static void nats_on_reconnect_timer_inner(nats_t *self)
2088 {
2089 82 self->reconnect_timer_active = 0;
2090 82 self->reconnect_attempts++;
2091 82 self->intentional_disconnect = 0;
2092 82 ▶ if (self->server_pool_count > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->server_pool_count > 0) 24 58 82
2093 24 nats_next_server(self);
2094 82 nats_do_connect(self);
2095 82 }
2096  
2097 82 NATS_WATCHER_CB(nats_on_reconnect_timer, ev_timer, reconnect_timer)
2098  
2099 90 static void nats_start_ping_timer(nats_t *self)
2100 {
2101 90 ▶ if (self->ping_interval_ms <= 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->ping_interval_ms <= 0) return; 1 89 90
2102 89 double interval = self->ping_interval_ms / 1000.0;
2103 89 ev_timer_set(&self->ping_timer, interval, interval);
2104 89 ev_timer_start(self->loop, &self->ping_timer);
2105 89 self->ping_timer_active = 1;
2106 }
2107  
2108 12 static void nats_on_ping_timer_inner(nats_t *self)
2109 {
2110 12 self->pings_outstanding++;
2111 12 ▶ if (self->max_pings_outstanding > 0 &&
Branch: 1 branch
BranchTrueFalseTotal
if (self->max_pings_outstanding > 0 && 12 0 12
2112 12 ▶ self->pings_outstanding > self->max_pings_outstanding) {
Branch: 1 branch
BranchTrueFalseTotal
self->pings_outstanding > self->max_pings_outstanding) { 0 12 12
2113 0 nats_fail(self, "stale connection");
2114 0 return;
2115 }
2116  
2117 12 wbuf_append(self, "PING\r\n", 6);
2118 12 nats_push_pong_marker(self);
2119 12 nats_try_write(self);
2120 }
2121  
2122 12 NATS_WATCHER_CB(nats_on_ping_timer, ev_timer, ping_timer)
2123  
2124 /* ================================================================
2125 * Write coalescing via ev_prepare
2126 * ================================================================ */
2127  
2128 78 static void nats_on_prepare_inner(nats_t *self)
2129 {
2130 78 ▶ if (self->wbuf_dirty && self->fd >= 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->wbuf_dirty && self->fd >= 0) { 78 0 78
if (self->wbuf_dirty && self->fd >= 0) { 78 0 78
2131 78 self->wbuf_dirty = 0;
2132 78 nats_try_write(self);
2133 }
2134 /* Arm-on-demand: every producer either try_writes directly or goes
2135 through nats_schedule_write, so an empty wbuf needs no watcher. */
2136 78 ▶ if (self->prepare_active && self->wbuf_off >= self->wbuf_len) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->prepare_active && self->wbuf_off >= self->wbuf_len) { 78 0 78
if (self->prepare_active && self->wbuf_off >= self->wbuf_len) { 78 0 78
2137 78 ev_prepare_stop(self->loop, &self->prepare_watcher);
2138 78 self->prepare_active = 0;
2139 }
2140 78 }
2141  
2142 78 NATS_WATCHER_CB(nats_on_prepare, ev_prepare, prepare_watcher)
2143  
2144 /* the callers keep using self: the pin is mortal, not released on return */
2145 0 static void nats_fire_slow_consumer(nats_t *self)
2146 {
2147 0 ▶ if (self->owner_sv)
Branch: 1 branch
BranchTrueFalseTotal
if (self->owner_sv) 0 0 0
2148 0 sv_2mortal(SvREFCNT_inc(self->owner_sv));
2149 0 dSP;
2150 0 ENTER; SAVETMPS;
2151 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
2152 0 ▶ EXTEND(SP, 1);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 1); 0 0 0
2153 0 PUSHs(sv_2mortal(newSVuv(self->wbuf_len - self->wbuf_off)));
2154 0 PUTBACK;
2155 0 nats_invoke(self, self->on_slow_consumer);
2156 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
2157 0 }
2158  
2159 /* Edge-triggered slow-consumer check, shared by the write path and batch
2160 end: fires once when the buffer crosses the threshold and re-arms when
2161 a later call finds it drained back below. */
2162 static void
2163 203 nats_slow_check(nats_t *self)
2164 {
2165 203 ▶ if (self->slow_consumer_bytes == 0 || !self->on_slow_consumer)
Branch: 2 branches
BranchTrueFalseTotal
if (self->slow_consumer_bytes == 0 || !self->on_slow_consumer) 0 203 203
if (self->slow_consumer_bytes == 0 || !self->on_slow_consumer) 0 0 0
2166 203 return;
2167 0 ▶ if ((self->wbuf_len - self->wbuf_off) > self->slow_consumer_bytes) {
Branch: 1 branch
BranchTrueFalseTotal
if ((self->wbuf_len - self->wbuf_off) > self->slow_consumer_bytes) { 0 0 0
2168 0 ▶ if (!self->slow_fired) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->slow_fired) { 0 0 0
2169 0 self->slow_fired = 1;
2170 0 nats_fire_slow_consumer(self);
2171 }
2172 } else {
2173 0 self->slow_fired = 0;
2174 }
2175 }
2176  
2177 203 static void nats_schedule_write(nats_t *self)
2178 {
2179 203 ▶ if (self->batch_mode) return; /* writes batched, flushed on batch end */
Branch: 1 branch
BranchTrueFalseTotal
if (self->batch_mode) return; /* writes batched, flushed on batch end */ 0 203 203
2180  
2181 203 self->wbuf_dirty = 1;
2182 203 ▶ if (!self->prepare_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->prepare_active) { 88 115 203
2183 88 ev_prepare_start(self->loop, &self->prepare_watcher);
2184 88 self->prepare_active = 1;
2185 }
2186  
2187 203 nats_slow_check(self);
2188 }
2189  
2190 /* ================================================================
2191 * Request timeout
2192 * ================================================================ */
2193  
2194 /* Deliberately not cb_depth-guarded: nats_t is touched only before the
2195 callback, and the req is unlinked, so a connection-destroying callback is
2196 harmless. A live timer implies a live nats_t: teardown stops them all. */
2197 12 static void nats_on_request_timeout(struct ev_loop *loop, ev_timer *w, int revents)
2198 {
2199 12 nats_req_t *req = (nats_req_t *)((char *)w - offsetof(nats_req_t, timer));
2200 12 nats_t *self = req->nats;
2201 12 SV *cb = req->cb;
2202 (void)loop; (void)revents;
2203  
2204 12 ngx_queue_remove(&req->queue);
2205 12 ▶ if (req->queued)
Branch: 1 branch
BranchTrueFalseTotal
if (req->queued) 5 7 12
2206 5 nats_unqueue_requests(self, req->req_id);
2207 12 Safefree(req);
2208 12 ▶ if (cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (cb) { 12 0 12
2209 12 ENTER;
2210 12 SAVEFREESV(cb);
2211 12 nats_call_str(self, cb, 1, "request timeout");
2212 12 LEAVE;
2213 }
2214 12 }
2215  
2216 /* ================================================================
2217 * Write queue (for buffering during connect/reconnect)
2218 * ================================================================ */
2219  
2220 88 static void nats_drain_waiting(nats_t *self)
2221 {
2222 90 ▶ while (!ngx_queue_empty(&self->wait_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->wait_queue)) { 2 88 90
2223 2 ngx_queue_t *q = ngx_queue_head(&self->wait_queue);
2224 2 nats_pub_t *pub = ngx_queue_data(q, nats_pub_t, queue);
2225 2 ngx_queue_remove(q);
2226 2 self->waiting_count--;
2227  
2228 2 wbuf_append(self, pub->data, pub->len);
2229 2 Safefree(pub->data);
2230 2 Safefree(pub);
2231 }
2232 88 self->wait_bytes = 0;
2233 {
2234 ngx_queue_t *q;
2235 89 ▶ ngx_queue_foreach(q, &self->req_queue)
Branch: 2 branches
BranchTrueFalseTotal
ngx_queue_foreach(q, &self->req_queue) 1 88 89
ngx_queue_foreach(q, &self->req_queue) 1 0 1
2236 1 ngx_queue_data(q, nats_req_t, queue)->queued = 0;
2237 }
2238  
2239 88 ▶ if (self->wbuf_len > self->wbuf_off)
Branch: 1 branch
BranchTrueFalseTotal
if (self->wbuf_len > self->wbuf_off) 2 86 88
2240 2 nats_try_write(self);
2241 88 }
2242  
2243 /* Protocol fields are space-delimited: a blank or control byte silently
2244 reinterprets the frame (truncated subject, spoofed reply-to), so every
2245 caller-supplied subject, reply-to and queue group goes through here. */
2246 static int
2247 339 nats_field_ok(const char *p, size_t len)
2248 {
2249 size_t i;
2250 7889 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 7556 333 7889
2251 7556 unsigned char c = (unsigned char)p[i];
2252 7556 ▶ if (c <= 0x20 || c == 0x7f)
Branch: 2 branches
BranchTrueFalseTotal
if (c <= 0x20 || c == 0x7f) 7550 6 7556
if (c <= 0x20 || c == 0x7f) 0 7550 7550
2253 6 return 0;
2254 }
2255 333 return 1;
2256 }
2257  
2258 /* Check before allocating queued writes so a cap refusal strands nothing.
2259 Connected writes bypass the cap. */
2260 276 static int nats_queue_cap_ok(nats_t *self, size_t len)
2261 {
2262 276 ▶ if (self->connected || self->reconnect_buf_size == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected || self->reconnect_buf_size == 0) 139 137 276
if (self->connected || self->reconnect_buf_size == 0) 0 139 139
2263 137 return 1;
2264 139 return self->wait_bytes <= self->reconnect_buf_size
2265 139 ▶ && len <= self->reconnect_buf_size - self->wait_bytes;
Branch: 2 branches
BranchTrueFalseTotal
&& len <= self->reconnect_buf_size - self->wait_bytes; 136 3 139
&& len <= self->reconnect_buf_size - self->wait_bytes; 125 11 136
2266 }
2267  
2268 /* SUB and UNSUB never wait in wait_queue. Before CONNECT the registry alone
2269 is enough, as CONNECT replays it; after it they follow the CONNECT in
2270 wbuf, so a failed attempt drops them with it. */
2271 87 static void nats_sub_write(nats_t *self, const char *buf, size_t n)
2272 {
2273 87 ▶ if (!self->connected && !(self->connecting && self->connect_sent))
Branch: 3 branches
BranchTrueFalseTotal
if (!self->connected && !(self->connecting && self->connect_sent)) 23 64 87
if (!self->connected && !(self->connecting && self->connect_sent)) 15 8 23
if (!self->connected && !(self->connecting && self->connect_sent)) 14 1 15
2274 22 return;
2275 65 wbuf_append(self, buf, n);
2276 65 nats_schedule_write(self);
2277 }
2278  
2279 /* Unqueue the PUBs of request req_id, or of every request when 0: a
2280 request reported failed must not be sent later. */
2281 127 static void nats_unqueue_requests(nats_t *self, uint64_t req_id)
2282 {
2283 ngx_queue_t *q, *next;
2284 210 ▶ for (q = ngx_queue_head(&self->wait_queue); q != ngx_queue_sentinel(&self->wait_queue); q = next) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = ngx_queue_head(&self->wait_queue); q != ngx_queue_sentinel(&self->wait_queue); q = next) { 83 127 210
2285 83 nats_pub_t *pub = ngx_queue_data(q, nats_pub_t, queue);
2286 83 next = ngx_queue_next(q);
2287 83 ▶ if (!pub->req_id || (req_id && pub->req_id != req_id))
Branch: 3 branches
BranchTrueFalseTotal
if (!pub->req_id || (req_id && pub->req_id != req_id)) 7 76 83
if (!pub->req_id || (req_id && pub->req_id != req_id)) 5 2 7
if (!pub->req_id || (req_id && pub->req_id != req_id)) 0 5 5
2288 76 continue;
2289 7 ngx_queue_remove(q);
2290 7 self->waiting_count--;
2291 7 self->wait_bytes -= pub->len;
2292 7 Safefree(pub->data);
2293 7 Safefree(pub);
2294 }
2295 127 }
2296  
2297 /* no connection attempt is coming for the requests still queued */
2298 122 static void nats_drop_queued_requests(nats_t *self)
2299 {
2300 122 nats_unqueue_requests(self, 0);
2301 122 nats_cancel_requests(self, "disconnected", 1);
2302 122 }
2303  
2304 276 static void nats_cap_check(nats_t *self, size_t len)
2305 {
2306 276 ▶ if (!nats_queue_cap_ok(self, len))
Branch: 1 branch
BranchTrueFalseTotal
if (!nats_queue_cap_ok(self, len)) 14 262 276
2307 14 croak("reconnect buffer full (%" UVuf " byte limit)", (UV)self->reconnect_buf_size);
2308 262 }
2309  
2310 /* A caller-supplied subject, reply-to or queue group; an optional one is
2311 NULL when undef or empty. */
2312 572 static const char *nats_token(SV *sv, STRLEN *len, const char *what, int optional)
2313 {
2314 const char *p;
2315 572 *len = 0;
2316 572 ▶ if (!sv || !SvOK(sv)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!sv || !SvOK(sv)) { 572 0 572
if (!sv || !SvOK(sv)) { 230 342 572
2317 230 ▶ if (optional) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (optional) return NULL; 226 4 230
2318 4 croak("%s required", what);
2319 }
2320 342 p = SvPV(sv, *len);
2321 342 ▶ if (*len == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (*len == 0) { 3 339 342
2322 3 ▶ if (optional) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (optional) return NULL; 0 3 3
2323 3 croak("%s must not be empty", what);
2324 }
2325 339 ▶ if (!nats_field_ok(p, *len))
Branch: 1 branch
BranchTrueFalseTotal
if (!nats_field_ok(p, *len)) 6 333 339
2326 6 croak("%s must not contain whitespace", what);
2327 333 return p;
2328 }
2329  
2330 /* The server answers an empty token with -ERR 'Invalid Subject'. */
2331 38 static void nats_subscription_subject_check(const char *p, STRLEN len)
2332 {
2333 STRLEN i;
2334 38 ▶ if (p[0] == '.' || p[len - 1] == '.')
Branch: 2 branches
BranchTrueFalseTotal
if (p[0] == '.' || p[len - 1] == '.') 37 1 38
if (p[0] == '.' || p[len - 1] == '.') 1 36 37
2335 2 croak("subject must not have an empty token");
2336 401 ▶ for (i = 1; i < len; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i < len; i++) 366 35 401
2337 366 ▶ if (p[i] == '.' && p[i - 1] == '.')
Branch: 2 branches
BranchTrueFalseTotal
if (p[i] == '.' && p[i - 1] == '.') 36 330 366
if (p[i] == '.' && p[i - 1] == '.') 1 35 36
2338 1 croak("subject must not have an empty token");
2339 35 }
2340  
2341 277 static const char *nats_bytes(SV *sv, STRLEN *len)
2342 {
2343 277 ▶ if (sv && SvOK(sv))
Branch: 2 branches
BranchTrueFalseTotal
if (sv && SvOK(sv)) 277 0 277
if (sv && SvOK(sv)) 277 0 277
2344 277 return SvPV(sv, *len);
2345 0 *len = 0;
2346 0 return "";
2347 }
2348  
2349 21 static const char *nats_headers_pv(SV *sv, STRLEN *len)
2350 {
2351 const char *p;
2352 21 ▶ if (!SvOK(sv))
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(sv)) 1 20 21
2353 1 croak("headers required");
2354 20 p = SvPV(sv, *len);
2355 20 ▶ if (*len == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (*len == 0) 1 19 20
2356 1 croak("headers must not be empty");
2357 19 ▶ if (*len < 8 || memcmp(p, "NATS/1.0", 8) != 0)
Branch: 2 branches
BranchTrueFalseTotal
if (*len < 8 || memcmp(p, "NATS/1.0", 8) != 0) 19 0 19
if (*len < 8 || memcmp(p, "NATS/1.0", 8) != 0) 1 18 19
2358 1 croak("headers must start with NATS/1.0");
2359 18 return p;
2360 }
2361  
2362 /* PUB, or HPUB when hdrs is set, formatted into cmd; every refusal croaks
2363 here, before anything is queued. */
2364 277 static int nats_frame_cmd(nats_t *self, char *cmd, size_t cmdsz,
2365 const char *subj, STRLEN subj_len,
2366 const char *reply, STRLEN reply_len,
2367 const char *hdrs, STRLEN h_len, STRLEN pay_len)
2368 {
2369 277 unsigned long body = (unsigned long)(h_len + pay_len);
2370 int n;
2371 277 ▶ if (self->max_payload > 0 && body > (unsigned long)self->max_payload)
Branch: 2 branches
BranchTrueFalseTotal
if (self->max_payload > 0 && body > (unsigned long)self->max_payload) 277 0 277
if (self->max_payload > 0 && body > (unsigned long)self->max_payload) 0 277 277
2372 0 ▶ croak("%s exceeds max_payload (%d)", hdrs ? "message" : "payload", self->max_payload);
Branch: 1 branch
BranchTrueFalseTotal
croak("%s exceeds max_payload (%d)", hdrs ? "message" : "payload", self->max_payload); 0 0 0
2373 277 ▶ if (hdrs)
Branch: 1 branch
BranchTrueFalseTotal
if (hdrs) 18 259 277
2374 18 n = reply
2375 17 ? snprintf(cmd, cmdsz, "HPUB %.*s %.*s %lu %lu\r\n", (int)subj_len, subj,
2376 (int)reply_len, reply, (unsigned long)h_len, body)
2377 18 ▶ : snprintf(cmd, cmdsz, "HPUB %.*s %lu %lu\r\n", (int)subj_len, subj,
Branch: 1 branch
BranchTrueFalseTotal
: snprintf(cmd, cmdsz, "HPUB %.*s %lu %lu\r\n", (int)subj_len, subj, 17 1 18
2378 (unsigned long)h_len, body);
2379 else
2380 259 n = reply
2381 70 ? snprintf(cmd, cmdsz, "PUB %.*s %.*s %lu\r\n", (int)subj_len, subj,
2382 (int)reply_len, reply, body)
2383 259 ▶ : snprintf(cmd, cmdsz, "PUB %.*s %lu\r\n", (int)subj_len, subj, body);
Branch: 1 branch
BranchTrueFalseTotal
: snprintf(cmd, cmdsz, "PUB %.*s %lu\r\n", (int)subj_len, subj, body); 70 189 259
2384 277 ▶ if (n < 0 || (size_t)n >= cmdsz)
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0 || (size_t)n >= cmdsz) 277 0 277
if (n < 0 || (size_t)n >= cmdsz) 1 276 277
2385 1 croak("subject too long");
2386 276 nats_cap_check(self, n + body + 2);
2387 262 return n;
2388 }
2389  
2390 /* The caller checked the connection state (NATS_CROAK_UNLESS_CONNECTED)
2391 and nats_frame_cmd the cap, with no user code since: nothing here croaks. */
2392 262 static void nats_frame_write(nats_t *self, const char *cmd, int n,
2393 const char *hdrs, STRLEN h_len,
2394 const char *pay, STRLEN pay_len, uint64_t req_id)
2395 {
2396 262 size_t total = n + h_len + pay_len + 2;
2397 nats_pub_t *pub;
2398 262 self->msgs_out++;
2399 262 self->bytes_out += h_len + pay_len;
2400 262 ▶ if (self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connected) { 137 125 262
2401 137 wbuf_append(self, cmd, n);
2402 137 ▶ if (h_len > 0) wbuf_append(self, hdrs, h_len);
Branch: 1 branch
BranchTrueFalseTotal
if (h_len > 0) wbuf_append(self, hdrs, h_len); 9 128 137
2403 137 ▶ if (pay_len > 0) wbuf_append(self, pay, pay_len);
Branch: 1 branch
BranchTrueFalseTotal
if (pay_len > 0) wbuf_append(self, pay, pay_len); 127 10 137
2404 137 wbuf_append(self, "\r\n", 2);
2405 137 nats_schedule_write(self);
2406 137 return;
2407 }
2408 125 Newxz(pub, 1, nats_pub_t);
2409 125 Newx(pub->data, total, char);
2410 125 memcpy(pub->data, cmd, n);
2411 125 ▶ if (h_len > 0) memcpy(pub->data + n, hdrs, h_len);
Branch: 1 branch
BranchTrueFalseTotal
if (h_len > 0) memcpy(pub->data + n, hdrs, h_len); 6 119 125
2412 125 ▶ if (pay_len > 0) memcpy(pub->data + n + h_len, pay, pay_len);
Branch: 1 branch
BranchTrueFalseTotal
if (pay_len > 0) memcpy(pub->data + n + h_len, pay, pay_len); 122 3 125
2413 125 pub->data[total - 2] = '\r';
2414 125 pub->data[total - 1] = '\n';
2415 125 pub->len = total;
2416 125 pub->req_id = req_id;
2417 125 ngx_queue_insert_tail(&self->wait_queue, &pub->queue);
2418 125 self->waiting_count++;
2419 125 self->wait_bytes += total;
2420 }
2421  
2422 /* ================================================================
2423 * TCP connection
2424 * ================================================================ */
2425  
2426 223 static void nats_schedule_reconnect(nats_t *self)
2427 {
2428 /* If a user callback (on_disconnect/on_error) already kicked off a fresh
2429 connect, don't stomp on it. */
2430 223 ▶ if (self->fd >= 0 || self->connecting || self->reconnect_timer_active)
Branch: 3 branches
BranchTrueFalseTotal
if (self->fd >= 0 || self->connecting || self->reconnect_timer_active) 222 1 223
if (self->fd >= 0 || self->connecting || self->reconnect_timer_active) 222 0 222
if (self->fd >= 0 || self->connecting || self->reconnect_timer_active) 0 222 222
2431 1 return;
2432 222 int gave_up = 0;
2433 222 ▶ if (!self->intentional_disconnect && self->reconnect_enabled) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->intentional_disconnect && self->reconnect_enabled) { 136 86 222
if (!self->intentional_disconnect && self->reconnect_enabled) { 106 30 136
2434 106 ▶ if (self->max_reconnect_attempts == 0 ||
Branch: 1 branch
BranchTrueFalseTotal
if (self->max_reconnect_attempts == 0 || 106 0 106
2435 106 ▶ self->reconnect_attempts < self->max_reconnect_attempts) {
Branch: 1 branch
BranchTrueFalseTotal
self->reconnect_attempts < self->max_reconnect_attempts) { 102 4 106
2436 /* Exponential backoff with jitter */
2437 102 int shift = self->reconnect_attempts > 5 ? 5 : self->reconnect_attempts;
2438 102 int delay = self->reconnect_delay_ms * (1 << shift);
2439 102 ▶ if (self->max_reconnect_delay_ms > 0 && delay > self->max_reconnect_delay_ms)
Branch: 2 branches
BranchTrueFalseTotal
if (self->max_reconnect_delay_ms > 0 && delay > self->max_reconnect_delay_ms) 102 0 102
if (self->max_reconnect_delay_ms > 0 && delay > self->max_reconnect_delay_ms) 26 76 102
2440 26 delay = self->max_reconnect_delay_ms;
2441 /* Floor: a zero delay would spin the loop at full tilt. */
2442 102 ▶ if (delay < 100)
Branch: 1 branch
BranchTrueFalseTotal
if (delay < 100) 10 92 102
2443 10 delay = 100;
2444 102 double base = delay / 1000.0;
2445 unsigned char r[2];
2446 102 nats_random_bytes(r, 2);
2447 102 unsigned int rv = ((unsigned)r[0] << 8) | r[1];
2448 102 double jitter = base * (0.5 + (double)(rv % 1000) / 2000.0);
2449 102 ev_timer_set(&self->reconnect_timer, jitter, 0.0);
2450 102 ev_timer_start(self->loop, &self->reconnect_timer);
2451 102 self->reconnect_timer_active = 1;
2452 } else {
2453 4 gave_up = 1;
2454 }
2455 }
2456 222 ▶ if (!self->reconnect_timer_active)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->reconnect_timer_active) 120 102 222
2457 120 nats_drop_queued_requests(self);
2458 /* the connection a queued flush waited for has failed */
2459 222 nats_fail_pong_queue(self, &self->flush_wait);
2460 222 ▶ if (gave_up)
Branch: 1 branch
BranchTrueFalseTotal
if (gave_up) 4 218 222
2461 4 nats_emit_error(self, "max reconnect attempts reached");
2462 }
2463  
2464 111 static void nats_free_server_pool(nats_t *self)
2465 {
2466 179 ▶ while (!ngx_queue_empty(&self->server_pool)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->server_pool)) { 68 111 179
2467 68 ngx_queue_t *q = ngx_queue_head(&self->server_pool);
2468 68 nats_server_t *srv = ngx_queue_data(q, nats_server_t, queue);
2469 68 ngx_queue_remove(q);
2470 68 Safefree(srv->host);
2471 68 Safefree(srv);
2472 68 self->server_pool_count--;
2473 }
2474 111 }
2475  
2476 414 static nats_server_t *nats_pool_find(nats_t *self, const char *host, size_t hlen, int port)
2477 {
2478 ngx_queue_t *q;
2479 24018 ▶ ngx_queue_foreach(q, &self->server_pool) {
Branch: 2 branches
BranchTrueFalseTotal
ngx_queue_foreach(q, &self->server_pool) { 23604 414 24018
ngx_queue_foreach(q, &self->server_pool) { 23604 0 23604
2480 23604 nats_server_t *srv = ngx_queue_data(q, nats_server_t, queue);
2481 23604 ▶ if (srv->port == port && strlen(srv->host) == hlen &&
Branch: 2 branches
BranchTrueFalseTotal
if (srv->port == port && strlen(srv->host) == hlen && 23523 81 23604
if (srv->port == port && strlen(srv->host) == hlen && 3447 20076 23523
2482 3447 ▶ memcmp(srv->host, host, hlen) == 0)
Branch: 1 branch
BranchTrueFalseTotal
memcmp(srv->host, host, hlen) == 0) 0 3447 3447
2483 0 return srv;
2484 }
2485 414 return NULL;
2486 }
2487  
2488 414 static nats_server_t *nats_pool_add(nats_t *self, const char *host, size_t hlen, int port, int implicit)
2489 {
2490 nats_server_t *srv;
2491 414 ▶ if (self->server_pool_count >= MAX_SERVER_POOL)
Branch: 1 branch
BranchTrueFalseTotal
if (self->server_pool_count >= MAX_SERVER_POOL) 337 77 414
2492 337 return NULL;
2493 77 Newxz(srv, 1, nats_server_t);
2494 77 nats_set_strn(&srv->host, host, hlen);
2495 77 srv->port = port;
2496 77 srv->implicit = implicit;
2497 77 srv->seen = 1;
2498 77 ngx_queue_insert_tail(&self->server_pool, &srv->queue);
2499 77 self->server_pool_count++;
2500 77 return srv;
2501 }
2502  
2503 /* As nats.go: learned servers no longer advertised are dropped; the
2504 configured server and the current one always stay. */
2505 97 static void nats_parse_connect_urls(nats_t *self, const char *json, size_t len)
2506 {
2507 97 const char *key = "\"connect_urls\":[";
2508 97 const char *p = nats_memfind(json, len, key, strlen(key));
2509 ngx_queue_t *q, *next;
2510 nats_server_t *cur;
2511 97 int first = ngx_queue_empty(&self->server_pool);
2512 97 ▶ if (!p) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return; 92 5 97
2513  
2514 5 p += strlen(key);
2515 5 const char *end = json + len;
2516  
2517 5 ▶ ngx_queue_foreach(q, &self->server_pool)
Branch: 2 branches
BranchTrueFalseTotal
ngx_queue_foreach(q, &self->server_pool) 0 5 5
ngx_queue_foreach(q, &self->server_pool) 0 0 0
2518 0 ngx_queue_data(q, nats_server_t, queue)->seen = 0;
2519  
2520 414 ▶ while (p < end && *p != ']') {
Branch: 2 branches
BranchTrueFalseTotal
while (p < end && *p != ']') { 414 0 414
while (p < end && *p != ']') { 409 5 414
2521 1228 ▶ while (p < end && (*p == ' ' || *p == ',' || *p == '"')) p++;
Branch: 4 branches
BranchTrueFalseTotal
while (p < end && (*p == ' ' || *p == ',' || *p == '"')) p++; 1228 0 1228
while (p < end && (*p == ' ' || *p == ',' || *p == '"')) p++; 0 1228 1228
while (p < end && (*p == ' ' || *p == ',' || *p == '"')) p++; 408 820 1228
while (p < end && (*p == ' ' || *p == ',' || *p == '"')) p++; 411 409 820
2522 409 ▶ if (p >= end || *p == ']') break;
Branch: 2 branches
BranchTrueFalseTotal
if (p >= end || *p == ']') break; 409 0 409
if (p >= end || *p == ']') break; 409 0 409
2523  
2524 409 const char *start = p;
2525 409 ▶ if (p < end && *p == '[') {
Branch: 2 branches
BranchTrueFalseTotal
if (p < end && *p == '[') { 409 0 409
if (p < end && *p == '[') { 3 406 409
2526 /* Bracketed IPv6 literal: consume through the closing bracket
2527 so the ']' terminator below doesn't split host from port.
2528 Bounded to this entry: an unbalanced '[' must not swallow
2529 the entries that follow it. */
2530 3 const char *q = p + 1;
2531 20 ▶ while (q < end && *q != ']' && *q != '"' && *q != ',') q++;
Branch: 4 branches
BranchTrueFalseTotal
while (q < end && *q != ']' && *q != '"' && *q != ',') q++; 20 0 20
while (q < end && *q != ']' && *q != '"' && *q != ',') q++; 18 2 20
while (q < end && *q != ']' && *q != '"' && *q != ',') q++; 17 1 18
while (q < end && *q != ']' && *q != '"' && *q != ',') q++; 17 0 17
2532 3 ▶ if (q < end && *q == ']') p = (char *)q + 1;
Branch: 2 branches
BranchTrueFalseTotal
if (q < end && *q == ']') p = (char *)q + 1; 3 0 3
if (q < end && *q == ']') p = (char *)q + 1; 2 1 3
2533 }
2534 6372 ▶ while (p < end && *p != '"' && *p != ',' && *p != ']') p++;
Branch: 4 branches
BranchTrueFalseTotal
while (p < end && *p != '"' && *p != ',' && *p != ']') p++; 6372 0 6372
while (p < end && *p != '"' && *p != ',' && *p != ']') p++; 5963 409 6372
while (p < end && *p != '"' && *p != ',' && *p != ']') p++; 5963 0 5963
while (p < end && *p != '"' && *p != ',' && *p != ']') p++; 5963 0 5963
2535  
2536 409 size_t url_len = p - start;
2537 409 ▶ if (url_len > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (url_len > 0) { 409 0 409
2538 /* Split host and port. IPv6 arrives bracketed ("[::1]:4222");
2539 strip the brackets, which getaddrinfo rejects. */
2540 409 const char *hstart = start;
2541 409 const char *hend = start + url_len;
2542 409 const char *pstart = NULL;
2543 409 size_t plen = 0;
2544 411 ▶ if (url_len > 2 && start[0] == '[') {
Branch: 2 branches
BranchTrueFalseTotal
if (url_len > 2 && start[0] == '[') { 407 2 409
if (url_len > 2 && start[0] == '[') { 2 405 407
2545 2 const char *rb = memchr(start + 1, ']', url_len - 1);
2546 2 ▶ if (rb) {
Branch: 1 branch
BranchTrueFalseTotal
if (rb) { 1 1 2
2547 1 hstart = start + 1;
2548 1 hend = rb;
2549 1 ▶ if (rb + 1 < start + url_len && rb[1] == ':') {
Branch: 2 branches
BranchTrueFalseTotal
if (rb + 1 < start + url_len && rb[1] == ':') { 1 0 1
if (rb + 1 < start + url_len && rb[1] == ':') { 1 0 1
2550 1 pstart = rb + 2;
2551 1 plen = (start + url_len) - pstart;
2552 }
2553 }
2554 } else {
2555 407 const char *colon = NULL;
2556 const char *s;
2557 2041 ▶ for (s = start + url_len - 1; s >= start; s--) {
Branch: 1 branch
BranchTrueFalseTotal
for (s = start + url_len - 1; s >= start; s--) { 2038 3 2041
2558 2038 ▶ if (*s == ':') { colon = s; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (*s == ':') { colon = s; break; } 404 1634 2038
2559 }
2560 407 ▶ if (colon && colon > start) {
Branch: 2 branches
BranchTrueFalseTotal
if (colon && colon > start) { 404 3 407
if (colon && colon > start) { 404 0 404
2561 404 hend = colon;
2562 404 pstart = colon + 1;
2563 404 plen = (start + url_len) - pstart;
2564 }
2565 }
2566  
2567 409 int port = 4222;
2568 409 ▶ if (pstart && plen > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (pstart && plen > 0) { 405 4 409
if (pstart && plen > 0) { 405 0 405
2569 405 long pval = 0;
2570 size_t i;
2571 2025 ▶ for (i = 0; i < plen && pstart[i] >= '0' && pstart[i] <= '9'; i++) {
Branch: 3 branches
BranchTrueFalseTotal
for (i = 0; i < plen && pstart[i] >= '0' && pstart[i] <= '9'; i++) { 1621 404 2025
for (i = 0; i < plen && pstart[i] >= '0' && pstart[i] <= '9'; i++) { 1621 0 1621
for (i = 0; i < plen && pstart[i] >= '0' && pstart[i] <= '9'; i++) { 1621 0 1621
2572 1621 pval = pval * 10 + (pstart[i] - '0');
2573 1621 ▶ if (pval > 65535) { pval = 65535; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (pval > 65535) { pval = 65535; break; } 1 1620 1621
2574 }
2575 405 ▶ if (i > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (i > 0) 405 0 405
2576 405 port = (int)pval;
2577 }
2578 409 size_t hlen = hend - hstart;
2579 409 nats_server_t *srv = nats_pool_find(self, hstart, hlen, port);
2580 409 ▶ if (srv)
Branch: 1 branch
BranchTrueFalseTotal
if (srv) 0 409 409
2581 0 srv->seen = 1;
2582 else
2583 409 nats_pool_add(self, hstart, hlen, port, 1);
2584 }
2585  
2586 818 ▶ while (p < end && *p == '"') p++;
Branch: 2 branches
BranchTrueFalseTotal
while (p < end && *p == '"') p++; 818 0 818
while (p < end && *p == '"') p++; 409 409 818
2587 }
2588  
2589 5 ▶ if (!self->host)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->host) 0 5 5
2590 0 return;
2591 5 cur = nats_pool_find(self, self->host, strlen(self->host), self->port);
2592 78 ▶ for (q = ngx_queue_head(&self->server_pool); q != ngx_queue_sentinel(&self->server_pool); q = next) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = ngx_queue_head(&self->server_pool); q != ngx_queue_sentinel(&self->server_pool); q = next) { 73 5 78
2593 73 nats_server_t *srv = ngx_queue_data(q, nats_server_t, queue);
2594 73 next = ngx_queue_next(q);
2595 73 ▶ if (srv->implicit && !srv->seen && srv != cur) {
Branch: 3 branches
BranchTrueFalseTotal
if (srv->implicit && !srv->seen && srv != cur) { 73 0 73
if (srv->implicit && !srv->seen && srv != cur) { 0 73 73
if (srv->implicit && !srv->seen && srv != cur) { 0 0 0
2596 0 ngx_queue_remove(q);
2597 0 Safefree(srv->host);
2598 0 Safefree(srv);
2599 0 self->server_pool_count--;
2600 }
2601 }
2602 /* the current server stays even when it omits itself */
2603 5 ▶ if (!cur)
Branch: 1 branch
BranchTrueFalseTotal
if (!cur) 5 0 5
2604 5 cur = nats_pool_add(self, self->host, strlen(self->host), self->port, 1);
2605 /* first INFO after connect(): the current server is the configured one */
2606 5 ▶ if (cur && first)
Branch: 2 branches
BranchTrueFalseTotal
if (cur && first) 4 1 5
if (cur && first) 4 0 4
2607 4 cur->implicit = 0;
2608 }
2609  
2610 24 static void nats_next_server(nats_t *self)
2611 {
2612 24 ▶ if (ngx_queue_empty(&self->server_pool)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->server_pool)) return; 0 24 24
2613  
2614 /* take the head, then rotate it to the tail */
2615 24 ngx_queue_t *q = ngx_queue_head(&self->server_pool);
2616 24 nats_server_t *srv = ngx_queue_data(q, nats_server_t, queue);
2617  
2618 24 nats_set_str(&self->host, srv->host);
2619 24 self->port = srv->port;
2620 /* host changed: any saved getaddrinfo candidates are stale */
2621 24 nats_free_addrinfo(self);
2622  
2623 24 ngx_queue_remove(q);
2624 24 ngx_queue_insert_tail(&self->server_pool, q);
2625 }
2626  
2627 /* rv: the connect(2) result, nonzero for EINPROGRESS */
2628 179 static void nats_after_connect(nats_t *self, int fd, int rv)
2629 {
2630 #ifdef SO_NOSIGPIPE
2631 int flag = 1;
2632 setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(flag));
2633 #endif
2634 179 self->fd = fd;
2635 179 self->conn_gen++;
2636 179 self->connecting = 1;
2637 179 self->connected = 0;
2638 /* EINPROGRESS: the first EV_WRITE must SO_ERROR-check the connect */
2639 179 self->connect_pending = (rv != 0);
2640  
2641 179 ev_io_init(&self->rio, nats_on_read, fd, EV_READ);
2642 179 ev_io_init(&self->wio, nats_on_write, fd, EV_WRITE);
2643  
2644 179 ▶ if (self->priority) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->priority) { 0 179 179
2645 0 ev_set_priority(&self->rio, self->priority);
2646 0 ev_set_priority(&self->wio, self->priority);
2647 }
2648  
2649 179 ev_io_start(self->loop, &self->rio);
2650 179 self->reading = 1;
2651  
2652 179 ▶ if (rv != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (rv != 0) { 179 0 179
2653 179 ev_io_start(self->loop, &self->wio);
2654 179 self->writing = 1;
2655 }
2656  
2657 179 ▶ if (self->connect_timeout_ms > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timeout_ms > 0) { 1 178 179
2658 /* failover re-enters here with the timer still running: ev_timer_set
2659 on an active watcher corrupts libev's heap key, so stop it first */
2660 1 ▶ if (self->connect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timer_active) { 0 1 1
2661 0 ev_timer_stop(self->loop, &self->connect_timer);
2662 0 self->connect_timer_active = 0;
2663 }
2664 1 ev_now_update(self->loop);
2665 1 ev_timer_set(&self->connect_timer, self->connect_timeout_ms / 1000.0, 0.0);
2666 1 ev_timer_start(self->loop, &self->connect_timer);
2667 1 self->connect_timer_active = 1;
2668 }
2669 179 }
2670  
2671 407 static void nats_free_addrinfo(nats_t *self)
2672 {
2673 407 ▶ if (self->ai_res)
Branch: 1 branch
BranchTrueFalseTotal
if (self->ai_res) 179 228 407
2674 179 freeaddrinfo(self->ai_res);
2675 407 self->ai_res = NULL;
2676 407 self->ai_next = NULL;
2677 407 }
2678  
2679 /* Actual teardown behind DESTROY. With cb_depth > 0 DESTROY only sets
2680 destroy_pending and the outermost nats_on_* wrapper runs this once the
2681 callback returns. Callers must not touch self after this. */
2682 96 static void nats_destroy_now(nats_t *self)
2683 {
2684 96 ▶ CLEAR_HANDLER(self->on_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_error); 73 23 96
2685 96 ▶ CLEAR_HANDLER(self->on_connect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_connect); 21 75 96
2686 96 ▶ CLEAR_HANDLER(self->on_disconnect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_disconnect); 5 91 96
2687  
2688 96 nats_stop_watchers(self);
2689 96 nats_stop_timers(self);
2690  
2691 96 ▶ while (!ngx_queue_empty(&self->req_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->req_queue)) { 0 96 96
2692 0 ngx_queue_t *q = ngx_queue_head(&self->req_queue);
2693 0 nats_req_t *req = ngx_queue_data(q, nats_req_t, queue);
2694 0 ngx_queue_remove(q);
2695 0 ▶ if (req->timer_active)
Branch: 1 branch
BranchTrueFalseTotal
if (req->timer_active) 0 0 0
2696 0 ev_timer_stop(self->loop, &req->timer);
2697 0 ▶ CLEAR_HANDLER(req->cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(req->cb); 0 0 0
2698 0 Safefree(req);
2699 }
2700 96 nats_skip_waiting(self);
2701  
2702 96 nats_free_pong_queue(&self->pong_cbs);
2703 96 nats_free_pong_queue(&self->flush_wait);
2704 96 ▶ while (!ngx_queue_empty(&self->disc_watch)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->disc_watch)) { 0 96 96
2705 0 ngx_queue_t *q = ngx_queue_head(&self->disc_watch);
2706 0 nats_watch_t *w = ngx_queue_data(q, nats_watch_t, queue);
2707 0 ngx_queue_remove(q);
2708 0 ▶ CLEAR_HANDLER(w->cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(w->cb); 0 0 0
2709 0 Safefree(w);
2710 }
2711  
2712 117 ▶ while (!ngx_queue_empty(&self->subs)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->subs)) { 21 96 117
2713 21 ngx_queue_t *q = ngx_queue_head(&self->subs);
2714 21 nats_sub_t *sub = ngx_queue_data(q, nats_sub_t, queue);
2715 21 nats_remove_sub(self, sub);
2716 }
2717  
2718 96 ▶ if (self->fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) { 5 91 96
2719 5 close(self->fd);
2720 5 self->fd = -1;
2721 }
2722 96 nats_free_addrinfo(self);
2723  
2724 96 ▶ CLEAR_HANDLER(self->server_info_json);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->server_info_json); 29 67 96
2725 96 ▶ CLEAR_HANDLER(self->drain_cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->drain_cb); 0 96 96
2726 96 Safefree(self->pending_croak);
2727 96 ▶ CLEAR_HANDLER(self->pending_die);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->pending_die); 0 96 96
2728  
2729 96 nats_free_server_pool(self);
2730 96 ▶ if (self->sub_map) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->sub_map) { 96 0 96
2731 96 SvREFCNT_dec((SV *)self->sub_map);
2732 96 self->sub_map = NULL;
2733 }
2734 #ifdef HAVE_OPENSSL
2735 96 nats_ssl_cleanup(self);
2736 96 ▶ if (self->ssl_ctx) { SSL_CTX_free(self->ssl_ctx); self->ssl_ctx = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl_ctx) { SSL_CTX_free(self->ssl_ctx); self->ssl_ctx = NULL; } 0 96 96
2737 96 Safefree(self->tls_ca_file);
2738 #endif
2739  
2740 96 Safefree(self->rbuf);
2741 96 Safefree(self->wbuf);
2742 96 Safefree(self->host);
2743 96 Safefree(self->path);
2744 96 Safefree(self->user);
2745 96 Safefree(self->pass);
2746 96 Safefree(self->token);
2747 96 Safefree(self->name);
2748 96 Safefree(self->nkey_seed);
2749 96 Safefree(self->jwt);
2750 96 Safefree(self->server_nonce);
2751 96 ▶ CLEAR_HANDLER(self->on_slow_consumer);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_slow_consumer); 0 96 96
2752 96 ▶ CLEAR_HANDLER(self->on_ldm);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_ldm); 0 96 96
2753 96 ▶ CLEAR_HANDLER(self->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->loop_sv); 2 94 96
2754  
2755 96 Safefree(self);
2756 96 }
2757  
2758 187 static int nats_socket(int domain, int type, int protocol)
2759 {
2760 #ifdef SOCK_CLOEXEC
2761 187 return socket(domain, type | SOCK_CLOEXEC, protocol);
2762 #else
2763 int fd = socket(domain, type, protocol);
2764 if (fd >= 0)
2765 fcntl(fd, F_SETFD, FD_CLOEXEC);
2766 return fd;
2767 #endif
2768 }
2769  
2770 195 static void nats_connect_tcp(nats_t *self)
2771 {
2772 struct addrinfo hints, *rp;
2773 char port_str[8];
2774 195 int fd = -1;
2775 195 int rv = 0;
2776  
2777 /* Resolve once per host and keep the list: a connect that later fails
2778 via SO_ERROR fails over to the remaining candidates. */
2779 195 ▶ if (!self->ai_res) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->ai_res) { 195 0 195
2780 195 memset(&hints, 0, sizeof(hints));
2781 195 hints.ai_family = AF_UNSPEC;
2782 195 hints.ai_socktype = SOCK_STREAM;
2783  
2784 195 snprintf(port_str, sizeof(port_str), "%d", self->port);
2785  
2786 195 rv = getaddrinfo(self->host, port_str, &hints, &self->ai_res);
2787 195 ▶ if (rv != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (rv != 0) { 16 179 195
2788 16 self->ai_res = NULL;
2789 16 nats_emit_error(self, gai_strerror(rv));
2790 16 nats_schedule_reconnect(self);
2791 195 return;
2792 }
2793 179 self->ai_next = self->ai_res;
2794 }
2795  
2796 179 ▶ for (rp = self->ai_next; rp != NULL; rp = rp->ai_next) {
Branch: 1 branch
BranchTrueFalseTotal
for (rp = self->ai_next; rp != NULL; rp = rp->ai_next) { 179 0 179
2797 179 fd = nats_socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2798 179 ▶ if (fd < 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) continue; 0 179 179
2799  
2800 179 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
2801  
2802 179 int flag = 1;
2803 179 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
2804  
2805 179 ▶ if (self->keepalive > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->keepalive > 0) { 0 179 179
2806 0 setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &flag, sizeof(flag));
2807 #ifdef TCP_KEEPIDLE
2808 0 setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &self->keepalive, sizeof(self->keepalive));
2809 #endif
2810 }
2811  
2812 179 rv = connect(fd, rp->ai_addr, rp->ai_addrlen);
2813 179 ▶ if (rv == 0 || errno == EINPROGRESS) {
Branch: 2 branches
BranchTrueFalseTotal
if (rv == 0 || errno == EINPROGRESS) { 179 0 179
if (rv == 0 || errno == EINPROGRESS) { 179 0 179
2814 179 self->ai_next = rp->ai_next;
2815 179 nats_after_connect(self, fd, rv);
2816 179 return;
2817 }
2818  
2819 0 close(fd);
2820 0 fd = -1;
2821 }
2822  
2823 /* Address list exhausted: drop it so the next attempt re-resolves. */
2824 0 nats_free_addrinfo(self);
2825  
2826 0 ▶ if (self->connecting) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connecting) { 0 0 0
2827 /* failover from an attempt in flight: unwind it, or it wedges */
2828 0 nats_fail(self, "connection failed");
2829 0 return;
2830 }
2831 0 nats_emit_error(self, "connection failed");
2832 0 nats_schedule_reconnect(self);
2833 }
2834  
2835 8 static void nats_connect_unix(nats_t *self)
2836 {
2837 struct sockaddr_un addr;
2838 int fd;
2839  
2840 8 ▶ if (!self->path || strlen(self->path) >= sizeof(addr.sun_path)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->path || strlen(self->path) >= sizeof(addr.sun_path)) { 8 0 8
if (!self->path || strlen(self->path) >= sizeof(addr.sun_path)) { 0 8 8
2841 0 nats_emit_error(self, "invalid unix socket path");
2842 0 nats_schedule_reconnect(self);
2843 8 return;
2844 }
2845  
2846 8 fd = nats_socket(AF_UNIX, SOCK_STREAM, 0);
2847 8 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 0 8 8
2848 0 nats_emit_error(self, strerror(errno));
2849 0 nats_schedule_reconnect(self);
2850 0 return;
2851 }
2852  
2853 8 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
2854  
2855 8 memset(&addr, 0, sizeof(addr));
2856 8 addr.sun_family = AF_UNIX;
2857 8 strncpy(addr.sun_path, self->path, sizeof(addr.sun_path) - 1);
2858  
2859 8 int rv = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
2860 8 ▶ if (rv != 0 && errno != EINPROGRESS) {
Branch: 2 branches
BranchTrueFalseTotal
if (rv != 0 && errno != EINPROGRESS) { 8 0 8
if (rv != 0 && errno != EINPROGRESS) { 8 0 8
2861 8 close(fd);
2862 8 nats_emit_error(self, strerror(errno));
2863 8 nats_schedule_reconnect(self);
2864 8 return;
2865 }
2866  
2867 0 nats_after_connect(self, fd, rv);
2868 }
2869  
2870 188 static void nats_do_connect(nats_t *self)
2871 {
2872 188 ▶ if (self->path)
Branch: 1 branch
BranchTrueFalseTotal
if (self->path) 4 184 188
2873 4 nats_connect_unix(self);
2874 else
2875 184 nats_connect_tcp(self);
2876 188 }
2877  
2878 /* request() and hrequest(): headers is NULL for a plain PUB */
2879 87 static void nats_request(nats_t *self, SV *subject, SV *headers, SV *payload,
2880 SV *cb, int timeout_ms)
2881 {
2882 char reply_subj[INBOX_SUBJ_SIZE];
2883 char cmd[MAX_CONTROL_LINE];
2884 87 STRLEN subj_len, pay_len, h_len = 0;
2885 87 const char *subj, *pay, *hdrs = NULL;
2886  
2887 87 ▶ NATS_CROAK_UNLESS_CONNECTED(self);
Branch: 4 branches
BranchTrueFalseTotal
NATS_CROAK_UNLESS_CONNECTED(self); 26 61 87
NATS_CROAK_UNLESS_CONNECTED(self); 14 12 26
NATS_CROAK_UNLESS_CONNECTED(self); 6 8 14
NATS_CROAK_UNLESS_CONNECTED(self); 2 4 6
2888 77 subj = nats_token(subject, &subj_len, "subject", 0);
2889 74 ▶ if (headers)
Branch: 1 branch
BranchTrueFalseTotal
if (headers) 17 57 74
2890 17 hdrs = nats_headers_pv(headers, &h_len);
2891 74 pay = nats_bytes(payload, &pay_len);
2892 /* the writes below can run on_slow_consumer, which may drop the last ref */
2893 74 ▶ if (self->owner_sv)
Branch: 1 branch
BranchTrueFalseTotal
if (self->owner_sv) 74 0 74
2894 74 sv_2mortal(SvREFCNT_inc(self->owner_sv));
2895  
2896 /* every refusal croaks before anything is registered or queued */
2897 74 uint64_t req_id = self->next_req_id;
2898 74 int rlen = snprintf(reply_subj, sizeof(reply_subj), "%s%llu",
2899 74 self->inbox_prefix, (unsigned long long)req_id);
2900 74 int n = nats_frame_cmd(self, cmd, sizeof(cmd), subj, subj_len, reply_subj, rlen,
2901 hdrs, h_len, pay_len);
2902 /* taken before the SUB write, whose on_slow_consumer may request too */
2903 69 self->next_req_id++;
2904  
2905 69 ▶ if (!self->inbox_sub_sid) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->inbox_sub_sid) { 34 35 69
2906 char sbuf[MAX_CONTROL_LINE];
2907 34 int sn = snprintf(sbuf, sizeof(sbuf), "SUB %s* %" UVuf "\r\n",
2908 34 self->inbox_prefix, (UV)self->next_sid);
2909 nats_sub_t *sub;
2910 34 Newxz(sub, 1, nats_sub_t);
2911 34 sub->sid = self->next_sid++;
2912 34 sub->subject = newSVpvn(sbuf + 4, strlen(self->inbox_prefix) + 1);
2913 34 nats_register_sub(self, sub);
2914 34 self->inbox_sub_sid = sub->sid;
2915 34 nats_sub_write(self, sbuf, sn);
2916 /* the write may have run an on_slow_consumer that disconnected */
2917 34 ▶ NATS_CROAK_UNLESS_CONNECTED(self);
Branch: 4 branches
BranchTrueFalseTotal
NATS_CROAK_UNLESS_CONNECTED(self); 7 27 34
NATS_CROAK_UNLESS_CONNECTED(self); 3 4 7
NATS_CROAK_UNLESS_CONNECTED(self); 3 0 3
NATS_CROAK_UNLESS_CONNECTED(self); 0 3 3
2918 }
2919  
2920 nats_req_t *req;
2921 69 Newxz(req, 1, nats_req_t);
2922 69 req->req_id = req_id;
2923 69 req->nats = self;
2924 69 req->cb = newSVsv(cb);
2925 69 req->queued = !self->connected;
2926 69 ngx_queue_insert_tail(&self->req_queue, &req->queue);
2927  
2928 69 ▶ if (timeout_ms > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (timeout_ms > 0) { 60 9 69
2929 60 ev_now_update(self->loop);
2930 60 ev_timer_init(&req->timer, nats_on_request_timeout, timeout_ms / 1000.0, 0.0);
2931 60 ev_timer_start(self->loop, &req->timer);
2932 60 req->timer_active = 1;
2933 }
2934  
2935 69 nats_frame_write(self, cmd, n, hdrs, h_len, pay, pay_len, req_id);
2936 69 }
2937  
2938 /* ================================================================
2939 * XS interface
2940 * ================================================================ */
2941  
2942 /* an explicit target supersedes the discovered pool; its INFO repopulates it */
2943 15 static void nats_connect_begin(nats_t *self)
2944 {
2945 15 ▶ if (self->connected || self->connecting)
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected || self->connecting) 15 0 15
if (self->connected || self->connecting) 0 15 15
2946 0 croak("already connected");
2947 15 ▶ if (self->owner_sv)
Branch: 1 branch
BranchTrueFalseTotal
if (self->owner_sv) 15 0 15
2948 15 sv_2mortal(SvREFCNT_inc(self->owner_sv));
2949 15 ▶ if (self->reconnect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_timer_active) { 0 15 15
2950 0 ev_timer_stop(self->loop, &self->reconnect_timer);
2951 0 self->reconnect_timer_active = 0;
2952 }
2953 15 self->intentional_disconnect = 0;
2954 15 self->reconnect_attempts = 0;
2955 15 nats_free_server_pool(self);
2956 15 }
2957  
2958 MODULE = EV::Nats PACKAGE = EV::Nats
2959  
2960 PROTOTYPES: DISABLE
2961  
2962 BOOT:
2963 {
2964 21 ▶ I_EV_API("EV::Nats");
Branch: 3 branches
BranchTrueFalseTotal
I_EV_API("EV::Nats"); 0 21 21
I_EV_API("EV::Nats"); 21 0 21
I_EV_API("EV::Nats"); 0 21 21
2965 21 nats_stash = gv_stashpv("EV::Nats", GV_ADD);
2966 #ifdef HAVE_OPENSSL
2967 21 newCONSTSUB(nats_stash, "HAS_TLS", newSViv(1));
2968 21 newCONSTSUB(nats_stash, "HAS_NKEY", newSViv(1));
2969 #else
2970 newCONSTSUB(nats_stash, "HAS_TLS", newSViv(0));
2971 newCONSTSUB(nats_stash, "HAS_NKEY", newSViv(0));
2972 #endif
2973 }
2974  
2975 SV *
2976 new(class, ...)
2977 char *class
2978 PREINIT:
2979 nats_t *self;
2980 int i;
2981 SV *obj;
2982 CODE:
2983 149 Newxz(self, 1, nats_t);
2984 149 self->fd = -1;
2985 149 self->loop = EV_DEFAULT;
2986 149 self->max_payload = DEFAULT_MAX_PAYLOAD;
2987 149 self->port = 4222;
2988 149 self->echo = 1;
2989 149 self->ping_interval_ms = 120000;
2990 149 self->max_pings_outstanding = 2;
2991 149 self->reconnect_delay_ms = 2000;
2992 149 self->max_reconnect_delay_ms = 30000;
2993 149 self->max_reconnect_attempts = 60;
2994 149 self->reconnect_buf_size = 8 * 1024 * 1024;
2995  
2996 149 ngx_queue_init(&self->subs);
2997 149 ngx_queue_init(&self->wait_queue);
2998 149 ngx_queue_init(&self->req_queue);
2999  
3000 149 self->next_sid = 1;
3001  
3002 149 ev_timer_init(&self->connect_timer, nats_on_connect_timeout, 0., 0.);
3003 149 ev_timer_init(&self->reconnect_timer, nats_on_reconnect_timer, 0., 0.);
3004 149 ev_timer_init(&self->ping_timer, nats_on_ping_timer, 0., 0.);
3005 149 ev_prepare_init(&self->prepare_watcher, nats_on_prepare);
3006  
3007 149 ngx_queue_init(&self->server_pool);
3008 149 ngx_queue_init(&self->pong_cbs);
3009 149 ngx_queue_init(&self->flush_wait);
3010 149 ngx_queue_init(&self->disc_watch);
3011 149 self->sub_map = newHV();
3012  
3013 149 nats_setup_inbox(self, "_INBOX");
3014  
3015 /* mortal until returned: a croaking option frees self through DESTROY */
3016 149 obj = sv_2mortal(newRV_noinc(newSViv(PTR2IV(self))));
3017 149 sv_bless(obj, gv_stashpv(class, GV_ADD));
3018 149 self->owner_sv = SvRV(obj);
3019  
3020 149 ▶ if (items > 1 && (items - 1) % 2 == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (items > 1 && (items - 1) % 2 == 0) { 142 7 149
if (items > 1 && (items - 1) % 2 == 0) { 142 0 142
3021 680 ▶ for (i = 1; i < items; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i < items; i += 2) { 555 125 680
3022 555 const char *key = SvPV_nolen(ST(i));
3023 555 SV *val = ST(i + 1);
3024  
3025 555 ▶ if (strcmp(key, "host") == 0) nats_set_str_sv(&self->host, val);
Branch: 1 branch
BranchTrueFalseTotal
if (strcmp(key, "host") == 0) nats_set_str_sv(&self->host, val); 103 452 555
3026 452 ▶ else if (strcmp(key, "port") == 0) self->port = nats_int(val);
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "port") == 0) self->port = nats_int(val); 103 349 452
3027 349 ▶ else if (strcmp(key, "path") == 0) nats_set_str_sv(&self->path, val);
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "path") == 0) nats_set_str_sv(&self->path, val); 3 346 349
3028 346 ▶ else if (strcmp(key, "user") == 0) nats_set_str_sv(&self->user, val);
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "user") == 0) nats_set_str_sv(&self->user, val); 2 344 346
3029 344 ▶ else if (strcmp(key, "pass") == 0) nats_set_str_sv(&self->pass, val);
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "pass") == 0) nats_set_str_sv(&self->pass, val); 2 342 344
3030 342 ▶ else if (strcmp(key, "token") == 0) nats_set_str_sv(&self->token, val);
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "token") == 0) nats_set_str_sv(&self->token, val); 0 342 342
3031 342 ▶ else if (strcmp(key, "name") == 0) nats_set_str_sv(&self->name, val);
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "name") == 0) nats_set_str_sv(&self->name, val); 1 341 342
3032 341 ▶ else if (strcmp(key, "on_error") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "on_error") == 0) 127 214 341
3033 127 ▶ self->on_error = SvOK(val) ? newSVsv(val) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
self->on_error = SvOK(val) ? newSVsv(val) : NULL; 126 1 127
3034 214 ▶ else if (strcmp(key, "on_connect") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "on_connect") == 0) 73 141 214
3035 73 ▶ self->on_connect = SvOK(val) ? newSVsv(val) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
self->on_connect = SvOK(val) ? newSVsv(val) : NULL; 72 1 73
3036 141 ▶ else if (strcmp(key, "on_disconnect") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "on_disconnect") == 0) 11 130 141
3037 11 ▶ self->on_disconnect = SvOK(val) ? newSVsv(val) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
self->on_disconnect = SvOK(val) ? newSVsv(val) : NULL; 11 0 11
3038 130 ▶ else if (strcmp(key, "verbose") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "verbose") == 0) 0 130 130
3039 0 self->verbose = SvTRUE(val) ? 1 : 0;
3040 130 ▶ else if (strcmp(key, "pedantic") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "pedantic") == 0) 0 130 130
3041 0 self->pedantic = SvTRUE(val) ? 1 : 0;
3042 130 ▶ else if (strcmp(key, "echo") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "echo") == 0) 0 130 130
3043 0 self->echo = SvTRUE(val) ? 1 : 0;
3044 130 ▶ else if (strcmp(key, "no_responders") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "no_responders") == 0) 0 130 130
3045 0 self->no_responders = SvTRUE(val) ? 1 : 0;
3046 130 ▶ else if (strcmp(key, "reconnect") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "reconnect") == 0) 57 73 130
3047 57 self->reconnect_enabled = SvTRUE(val) ? 1 : 0;
3048 73 ▶ else if (strcmp(key, "reconnect_delay") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "reconnect_delay") == 0) 23 50 73
3049 23 self->reconnect_delay_ms = nats_int(val);
3050 50 ▶ else if (strcmp(key, "max_reconnect_attempts") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "max_reconnect_attempts") == 0) 3 47 50
3051 3 self->max_reconnect_attempts = nats_int(val);
3052 47 ▶ else if (strcmp(key, "max_reconnect_delay") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "max_reconnect_delay") == 0) 1 46 47
3053 1 self->max_reconnect_delay_ms = nats_int(val);
3054 46 ▶ else if (strcmp(key, "reconnect_buf_size") == 0) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "reconnect_buf_size") == 0) { 16 30 46
3055 16 IV v = SvIV(val);
3056 16 self->reconnect_buf_size = v < 0 ? 0 : (size_t)v;
3057 }
3058 30 ▶ else if (strcmp(key, "connect_timeout") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "connect_timeout") == 0) 1 29 30
3059 1 self->connect_timeout_ms = nats_int(val);
3060 29 ▶ else if (strcmp(key, "ping_interval") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "ping_interval") == 0) 4 25 29
3061 4 self->ping_interval_ms = nats_int(val);
3062 25 ▶ else if (strcmp(key, "max_pings_outstanding") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "max_pings_outstanding") == 0) 2 23 25
3063 2 self->max_pings_outstanding = nats_int(val);
3064 23 ▶ else if (strcmp(key, "priority") == 0) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "priority") == 0) { 3 20 23
3065 3 IV v = SvIV(val);
3066 3 ▶ if (v < -2 || v > 2)
Branch: 2 branches
BranchTrueFalseTotal
if (v < -2 || v > 2) 2 1 3
if (v < -2 || v > 2) 2 0 2
3067 3 croak("EV::Nats::new: 'priority' must be between -2 and +2");
3068 0 self->priority = (int)v;
3069 }
3070 20 ▶ else if (strcmp(key, "keepalive") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "keepalive") == 0) 0 20 20
3071 0 self->keepalive = nats_int(val);
3072 #ifndef HAVE_OPENSSL
3073 /* refused rather than ignored: plaintext would send the credentials */
3074 else if ((strcmp(key, "tls") == 0 && SvTRUE(val))
3075 || (strcmp(key, "tls_ca_file") == 0 && SvOK(val))
3076 || (strcmp(key, "nkey_seed") == 0 && SvOK(val)))
3077 croak("EV::Nats::new: '%s' needs a build with OpenSSL", key);
3078 else if (strcmp(key, "tls") == 0 || strcmp(key, "tls_ca_file") == 0
3079 || strcmp(key, "tls_skip_verify") == 0 || strcmp(key, "nkey_seed") == 0) {
3080 /* off or unset: nothing to refuse */
3081 }
3082 #else
3083 20 ▶ else if (strcmp(key, "tls") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "tls") == 0) 0 20 20
3084 0 self->tls = SvTRUE(val) ? 1 : 0;
3085 20 ▶ else if (strcmp(key, "tls_ca_file") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "tls_ca_file") == 0) 0 20 20
3086 0 nats_set_str_sv(&self->tls_ca_file, val);
3087 20 ▶ else if (strcmp(key, "tls_skip_verify") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "tls_skip_verify") == 0) 0 20 20
3088 0 self->tls_skip_verify = SvTRUE(val) ? 1 : 0;
3089 20 ▶ else if (strcmp(key, "nkey_seed") == 0) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "nkey_seed") == 0) { 2 18 20
3090 2 ▶ if (SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(val)) { 2 0 2
3091 STRLEN slen;
3092 2 const char *seed = SvPV(val, slen);
3093 char pub[64];
3094 2 ▶ if (nats_nkey_public(seed, pub, sizeof(pub)) <= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (nats_nkey_public(seed, pub, sizeof(pub)) <= 0) 2 0 2
3095 2 croak("invalid NKey seed");
3096 }
3097 0 nats_set_str_sv(&self->nkey_seed, val);
3098 }
3099 #endif
3100 18 ▶ else if (strcmp(key, "jwt") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "jwt") == 0) 0 18 18
3101 0 nats_set_str_sv(&self->jwt, val);
3102 18 ▶ else if (strcmp(key, "slow_consumer_bytes") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "slow_consumer_bytes") == 0) 0 18 18
3103 0 self->slow_consumer_bytes = (size_t)SvUV(val);
3104 18 ▶ else if (strcmp(key, "on_slow_consumer") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "on_slow_consumer") == 0) 0 18 18
3105 0 ▶ self->on_slow_consumer = SvOK(val) ? newSVsv(val) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
self->on_slow_consumer = SvOK(val) ? newSVsv(val) : NULL; 0 0 0
3106 18 ▶ else if (strcmp(key, "on_lame_duck") == 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "on_lame_duck") == 0) 0 18 18
3107 0 ▶ self->on_ldm = SvOK(val) ? newSVsv(val) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
self->on_ldm = SvOK(val) ? newSVsv(val) : NULL; 0 0 0
3108 18 ▶ else if (strcmp(key, "inbox_prefix") == 0) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "inbox_prefix") == 0) { 10 8 18
3109 10 ▶ if (SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(val)) { 9 1 10
3110 STRLEN blen;
3111 9 const char *base = SvPV(val, blen);
3112 9 ▶ if (!nats_inbox_base_ok(base, blen))
Branch: 1 branch
BranchTrueFalseTotal
if (!nats_inbox_base_ok(base, blen)) 8 1 9
3113 8 croak("EV::Nats::new: invalid 'inbox_prefix'");
3114 1 nats_setup_inbox(self, base);
3115 }
3116 }
3117 8 ▶ else if (strcmp(key, "loop") == 0) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strcmp(key, "loop") == 0) { 7 1 8
3118 7 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 6 1 7
3119 /* undef: keep the default loop */
3120 6 ▶ } else if (SvROK(val) && sv_derived_from(val, "EV::Loop")) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (SvROK(val) && sv_derived_from(val, "EV::Loop")) { 4 2 6
} else if (SvROK(val) && sv_derived_from(val, "EV::Loop")) { 2 2 4
3121 2 self->loop = (struct ev_loop *)SvIVx(SvRV(val));
3122 2 ▶ CLEAR_HANDLER(self->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->loop_sv); 0 2 2
3123 2 self->loop_sv = newSVsv(val);
3124 } else {
3125 4 croak("EV::Nats::new: 'loop' must be an EV::Loop");
3126 }
3127 }
3128 else
3129 1 warn("EV::Nats::new: unknown option '%s'", key);
3130 }
3131 }
3132  
3133 132 ▶ if (self->host || self->path) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->host || self->path) { 29 103 132
if (self->host || self->path) { 3 26 29
3134 106 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 106 0 106
3135 106 nats_do_connect(self);
3136 106 nats_unwind(self);
3137 }
3138  
3139 131 RETVAL = SvREFCNT_inc_simple_NN(obj);
3140 OUTPUT:
3141 RETVAL
3142  
3143 void
3144 connect(self, host, port = 4222)
3145 EV::Nats self
3146 char *host
3147 int port
3148 CODE:
3149 11 nats_connect_begin(self);
3150 11 nats_set_str(&self->path, NULL);
3151 11 nats_set_str(&self->host, host);
3152 11 self->port = port;
3153 11 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 11 0 11
3154 11 nats_connect_tcp(self);
3155 11 nats_unwind(self);
3156  
3157 void
3158 connect_unix(self, path)
3159 EV::Nats self
3160 char *path
3161 CODE:
3162 4 nats_connect_begin(self);
3163 4 nats_set_str(&self->host, NULL);
3164 4 nats_set_str(&self->path, path);
3165 4 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 4 0 4
3166 4 nats_connect_unix(self);
3167 4 nats_unwind(self);
3168  
3169 void
3170 disconnect(self)
3171 EV::Nats self
3172 CODE:
3173 78 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 78 0 78
3174 78 self->intentional_disconnect = 1;
3175 78 ▶ if (self->reconnect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_timer_active) { 15 63 78
3176 15 ev_timer_stop(self->loop, &self->reconnect_timer);
3177 15 self->reconnect_timer_active = 0;
3178 }
3179 78 nats_skip_waiting(self);
3180 78 nats_cancel_requests(self, "disconnected", 1);
3181 78 nats_cleanup(self);
3182 78 nats_unwind(self);
3183  
3184 int
3185 is_connected(self)
3186 EV::Nats self
3187 CODE:
3188 11 ▶ RETVAL = self->connected;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->connected; 1 10 11
3189 OUTPUT:
3190 RETVAL
3191  
3192 SV *
3193 timer(self, after, repeat, cb)
3194 EV::Nats self
3195 NV after
3196 NV repeat
3197 SV *cb
3198 CODE:
3199 {
3200 20 dSP;
3201 20 ev_now_update(self->loop);
3202 20 ENTER; SAVETMPS;
3203 20 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 20 20
3204 20 ▶ EXTEND(SP, 4);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 4); 0 20 20
3205 20 ▶ if (self->loop_sv) PUSHs(self->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (self->loop_sv) PUSHs(self->loop_sv); 1 19 20
3206 20 PUSHs(sv_2mortal(newSVnv(after)));
3207 20 PUSHs(sv_2mortal(newSVnv(repeat)));
3208 20 PUSHs(cb);
3209 20 PUTBACK;
3210 20 ▶ call_pv(self->loop_sv ? "EV::Loop::timer" : "EV::timer", G_SCALAR);
Branch: 1 branch
BranchTrueFalseTotal
call_pv(self->loop_sv ? "EV::Loop::timer" : "EV::timer", G_SCALAR); 1 19 20
3211 20 SPAGAIN;
3212 20 RETVAL = newSVsv(POPs);
3213 20 PUTBACK;
3214 20 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 20 0 20
3215 }
3216 OUTPUT:
3217 RETVAL
3218  
3219 UV
3220 watch_disconnect(self, cb)
3221 EV::Nats self
3222 SV *cb
3223 CODE:
3224 nats_watch_t *w;
3225 12 Newxz(w, 1, nats_watch_t);
3226 12 w->id = ++self->next_watch_id;
3227 12 w->cb = newSVsv(cb);
3228 12 ngx_queue_insert_tail(&self->disc_watch, &w->queue);
3229 12 ▶ RETVAL = (UV)w->id;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = (UV)w->id; 10 2 12
3230 OUTPUT:
3231 RETVAL
3232  
3233 void
3234 unwatch_disconnect(self, id)
3235 EV::Nats self
3236 UV id
3237 CODE:
3238 ngx_queue_t *q;
3239 9 ▶ ngx_queue_foreach(q, &self->disc_watch) {
Branch: 2 branches
BranchTrueFalseTotal
ngx_queue_foreach(q, &self->disc_watch) { 9 0 9
ngx_queue_foreach(q, &self->disc_watch) { 9 0 9
3240 9 nats_watch_t *w = ngx_queue_data(q, nats_watch_t, queue);
3241 9 ▶ if (w->id == (uint64_t)id) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->id == (uint64_t)id) { 9 0 9
3242 9 ngx_queue_remove(q);
3243 9 SvREFCNT_dec(w->cb);
3244 9 Safefree(w);
3245 9 break;
3246 }
3247 }
3248  
3249 void
3250 publish(self, subject, payload = &PL_sv_undef, reply = &PL_sv_undef)
3251 EV::Nats self
3252 SV *subject
3253 SV *payload
3254 SV *reply
3255 PREINIT:
3256 char cmd[MAX_CONTROL_LINE];
3257 STRLEN subj_len, reply_len, pay_len;
3258 const char *subj, *rep, *pay;
3259 int n;
3260 CODE:
3261 207 ▶ NATS_CROAK_UNLESS_CONNECTED(self);
Branch: 4 branches
BranchTrueFalseTotal
NATS_CROAK_UNLESS_CONNECTED(self); 131 76 207
NATS_CROAK_UNLESS_CONNECTED(self); 107 24 131
NATS_CROAK_UNLESS_CONNECTED(self); 106 1 107
NATS_CROAK_UNLESS_CONNECTED(self); 0 106 106
3262 206 subj = nats_token(subject, &subj_len, "subject", 0);
3263 203 rep = nats_token(reply, &reply_len, "reply subject", 1);
3264 202 pay = nats_bytes(payload, &pay_len);
3265 202 n = nats_frame_cmd(self, cmd, sizeof(cmd), subj, subj_len, rep, reply_len, NULL, 0, pay_len);
3266 193 nats_frame_write(self, cmd, n, NULL, 0, pay, pay_len, 0);
3267  
3268 void
3269 hpublish(self, subject, headers, payload = &PL_sv_undef, reply = &PL_sv_undef)
3270 EV::Nats self
3271 SV *subject
3272 SV *headers
3273 SV *payload
3274 SV *reply
3275 PREINIT:
3276 char cmd[MAX_CONTROL_LINE];
3277 STRLEN subj_len, reply_len, h_len, pay_len;
3278 const char *subj, *rep, *hdrs, *pay;
3279 int n;
3280 CODE:
3281 6 ▶ NATS_CROAK_UNLESS_CONNECTED(self);
Branch: 4 branches
BranchTrueFalseTotal
NATS_CROAK_UNLESS_CONNECTED(self); 6 0 6
NATS_CROAK_UNLESS_CONNECTED(self); 0 6 6
NATS_CROAK_UNLESS_CONNECTED(self); 0 0 0
NATS_CROAK_UNLESS_CONNECTED(self); 0 0 0
3282 6 subj = nats_token(subject, &subj_len, "subject", 0);
3283 4 rep = nats_token(reply, &reply_len, "reply subject", 1);
3284 4 hdrs = nats_headers_pv(headers, &h_len);
3285 1 pay = nats_bytes(payload, &pay_len);
3286 1 n = nats_frame_cmd(self, cmd, sizeof(cmd), subj, subj_len, rep, reply_len, hdrs, h_len, pay_len);
3287 0 nats_frame_write(self, cmd, n, hdrs, h_len, pay, pay_len, 0);
3288  
3289 UV
3290 subscribe(self, subject, cb, queue_group = &PL_sv_undef)
3291 EV::Nats self
3292 SV *subject
3293 SV *cb
3294 SV *queue_group
3295 PREINIT:
3296 nats_sub_t *sub;
3297 char buf[MAX_CONTROL_LINE];
3298 STRLEN subj_len, group_len;
3299 const char *subj, *group;
3300 CODE:
3301 41 subj = nats_token(subject, &subj_len, "subject", 0);
3302 38 nats_subscription_subject_check(subj, subj_len);
3303 35 group = nats_token(queue_group, &group_len, "queue group", 1);
3304 34 ▶ if (!SvROK(cb) || (SvTYPE(SvRV(cb)) != SVt_PVCV && !SvAMAGIC(cb)))
Branch: 5 branches
BranchTrueFalseTotal
if (!SvROK(cb) || (SvTYPE(SvRV(cb)) != SVt_PVCV && !SvAMAGIC(cb))) 33 1 34
if (!SvROK(cb) || (SvTYPE(SvRV(cb)) != SVt_PVCV && !SvAMAGIC(cb))) 0 33 33
if (!SvROK(cb) || (SvTYPE(SvRV(cb)) != SVt_PVCV && !SvAMAGIC(cb))) 0 0 0
if (!SvROK(cb) || (SvTYPE(SvRV(cb)) != SVt_PVCV && !SvAMAGIC(cb))) 0 0 0
if (!SvROK(cb) || (SvTYPE(SvRV(cb)) != SVt_PVCV && !SvAMAGIC(cb))) 0 0 0
3305 1 croak("callback must be a code reference");
3306  
3307 /* formatted before anything is registered: a refusal strands nothing */
3308 33 uint64_t sid = self->next_sid;
3309 33 int n = group
3310 1 ? snprintf(buf, sizeof(buf), "SUB %.*s %.*s %" UVuf "\r\n",
3311 (int)subj_len, subj, (int)group_len, group, (UV)sid)
3312 33 ▶ : snprintf(buf, sizeof(buf), "SUB %.*s %" UVuf "\r\n",
Branch: 1 branch
BranchTrueFalseTotal
: snprintf(buf, sizeof(buf), "SUB %.*s %" UVuf "\r\n", 1 32 33
3313 (int)subj_len, subj, (UV)sid);
3314 33 ▶ if (n < 0 || n >= (int)sizeof(buf))
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0 || n >= (int)sizeof(buf)) 33 0 33
if (n < 0 || n >= (int)sizeof(buf)) 0 33 33
3315 0 croak("subject too long");
3316  
3317 33 Newxz(sub, 1, nats_sub_t);
3318 33 sub->sid = self->next_sid++;
3319 33 sub->subject = newSVpvn(subj, subj_len);
3320 33 sub->cb = newSVsv(cb);
3321 33 ▶ sub->queue_group = group ? newSVpvn(group, group_len) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
sub->queue_group = group ? newSVpvn(group, group_len) : NULL; 1 32 33
3322 33 nats_register_sub(self, sub);
3323 33 nats_sub_write(self, buf, n);
3324  
3325 33 ▶ RETVAL = (UV)sid;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = (UV)sid; 12 21 33
3326 OUTPUT:
3327 RETVAL
3328  
3329 void
3330 unsubscribe(self, sid, max_msgs_iv = 0)
3331 EV::Nats self
3332 UV sid
3333 IV max_msgs_iv
3334 PREINIT:
3335 char buf[64];
3336 int n;
3337 int max_msgs;
3338 CODE:
3339 20 max_msgs = nats_clamp(max_msgs_iv);
3340 20 nats_sub_t *sub = nats_find_sub(self, (uint64_t)sid);
3341  
3342 20 ▶ if (max_msgs > 0 && !(sub && sub->received >= max_msgs)) {
Branch: 3 branches
BranchTrueFalseTotal
if (max_msgs > 0 && !(sub && sub->received >= max_msgs)) { 4 16 20
if (max_msgs > 0 && !(sub && sub->received >= max_msgs)) { 4 0 4
if (max_msgs > 0 && !(sub && sub->received >= max_msgs)) { 3 1 4
3343 3 ▶ if (sub)
Branch: 1 branch
BranchTrueFalseTotal
if (sub) 3 0 3
3344 3 sub->max_msgs = max_msgs;
3345 3 n = snprintf(buf, sizeof(buf), "UNSUB %" UVuf " %d\r\n", sid, max_msgs);
3346 } else {
3347 17 ▶ if (sub)
Branch: 1 branch
BranchTrueFalseTotal
if (sub) 17 0 17
3348 17 nats_remove_sub(self, sub);
3349 17 n = snprintf(buf, sizeof(buf), "UNSUB %" UVuf "\r\n", sid);
3350 }
3351 20 nats_sub_write(self, buf, n);
3352  
3353 void
3354 request(self, subject, payload, cb, timeout_ms = 5000)
3355 EV::Nats self
3356 SV *subject
3357 SV *payload
3358 SV *cb
3359 IV timeout_ms
3360 CODE:
3361 64 nats_request(self, subject, NULL, payload, cb, nats_clamp(timeout_ms));
3362  
3363 void
3364 hrequest(self, subject, headers, payload, cb, timeout_ms = 5000)
3365 EV::Nats self
3366 SV *subject
3367 SV *headers
3368 SV *payload
3369 SV *cb
3370 IV timeout_ms
3371 CODE:
3372 23 nats_request(self, subject, headers, payload, cb, nats_clamp(timeout_ms));
3373  
3374 void
3375 ping(self)
3376 EV::Nats self
3377 CODE:
3378 /* Unlike publish, a PING cannot be deferred: bytes appended pre-CONNECT
3379 would hit the wire before the CONNECT handshake. */
3380 3 ▶ if (!self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) 1 2 3
3381 1 croak("not connected");
3382 2 wbuf_append(self, "PING\r\n", 6);
3383 2 nats_push_pong_marker(self);
3384 2 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 2 0 2
3385 2 nats_try_write(self);
3386 2 nats_unwind(self);
3387  
3388 void
3389 flush(self, cb = NULL)
3390 EV::Nats self
3391 SV *cb
3392 PREINIT:
3393 nats_pong_cb_t *pcb;
3394 CODE:
3395 18 ▶ if (cb && !SvOK(cb))
Branch: 2 branches
BranchTrueFalseTotal
if (cb && !SvOK(cb)) 16 2 18
if (cb && !SvOK(cb)) 0 16 16
3396 0 cb = NULL;
3397 18 ▶ if (!self->connected && !NATS_PENDING(self)) {
Branch: 4 branches
BranchTrueFalseTotal
if (!self->connected && !NATS_PENDING(self)) { 6 12 18
if (!self->connected && !NATS_PENDING(self)) { 5 1 6
if (!self->connected && !NATS_PENDING(self)) { 3 2 5
if (!self->connected && !NATS_PENDING(self)) { 0 3 3
3398 2 ▶ if (!cb)
Branch: 1 branch
BranchTrueFalseTotal
if (!cb) 1 1 2
3399 1 croak("not connected");
3400 1 nats_defer_err(self, cb, "not connected");
3401 1 XSRETURN_EMPTY;
3402 }
3403 16 Newxz(pcb, 1, nats_pong_cb_t);
3404 16 ▶ if (cb)
Branch: 1 branch
BranchTrueFalseTotal
if (cb) 15 1 16
3405 15 pcb->cb = newSVsv(cb);
3406 16 ▶ if (!self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) { 4 12 16
3407 4 ngx_queue_insert_tail(&self->flush_wait, &pcb->queue);
3408 4 XSRETURN_EMPTY;
3409 }
3410 12 wbuf_append(self, "PING\r\n", 6);
3411 /* Queue before the write, always (a NULL-cb placeholder without a
3412 callback): on a synchronous write failure nats_cleanup drains this
3413 entry instead of stranding it, and the 1:1 PING/PONG accounting
3414 survives a cb-less flush. */
3415 12 ngx_queue_insert_tail(&self->pong_cbs, &pcb->queue);
3416 12 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 12 0 12
3417 12 nats_try_write(self);
3418 12 nats_unwind(self);
3419  
3420 SV *
3421 server_info(self)
3422 EV::Nats self
3423 CODE:
3424 2 ▶ if (self->server_info_json)
Branch: 1 branch
BranchTrueFalseTotal
if (self->server_info_json) 2 0 2
3425 2 RETVAL = newSVsv(self->server_info_json);
3426 else
3427 0 RETVAL = &PL_sv_undef;
3428 OUTPUT:
3429 RETVAL
3430  
3431 int
3432 max_payload(self, ...)
3433 EV::Nats self
3434 CODE:
3435 4 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 0 4 4
3436 0 IV v = SvIV(ST(1));
3437 /* clamp: a negative limit would wrap to SIZE_MAX in the size_t guards */
3438 0 ▶ self->max_payload = v < 0 ? 0 : (v > INT_MAX ? INT_MAX : (int)v);
Branch: 2 branches
BranchTrueFalseTotal
self->max_payload = v < 0 ? 0 : (v > INT_MAX ? INT_MAX : (int)v); 0 0 0
self->max_payload = v < 0 ? 0 : (v > INT_MAX ? INT_MAX : (int)v); 0 0 0
3439 }
3440 4 ▶ RETVAL = self->max_payload;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->max_payload; 1 3 4
3441 OUTPUT:
3442 RETVAL
3443  
3444 int
3445 waiting_count(self)
3446 EV::Nats self
3447 CODE:
3448 11 ▶ RETVAL = self->waiting_count;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->waiting_count; 1 10 11
3449 OUTPUT:
3450 RETVAL
3451  
3452 void
3453 skip_waiting(self)
3454 EV::Nats self
3455 CODE:
3456 1 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 1 0 1
3457 1 nats_skip_waiting(self);
3458 1 nats_cancel_requests(self, "disconnected", 1);
3459 1 nats_unwind(self);
3460  
3461 void
3462 reconnect(self, enable, ...)
3463 EV::Nats self
3464 int enable
3465 CODE:
3466 2 self->reconnect_enabled = enable;
3467 2 ▶ if (items > 2) self->reconnect_delay_ms = nats_int(ST(2));
Branch: 1 branch
BranchTrueFalseTotal
if (items > 2) self->reconnect_delay_ms = nats_int(ST(2)); 0 2 2
3468 2 ▶ if (items > 3) self->max_reconnect_attempts = nats_int(ST(3));
Branch: 1 branch
BranchTrueFalseTotal
if (items > 3) self->max_reconnect_attempts = nats_int(ST(3)); 0 2 2
3469 2 ▶ if (!enable && self->reconnect_timer_active) {
Branch: 2 branches
BranchTrueFalseTotal
if (!enable && self->reconnect_timer_active) { 2 0 2
if (!enable && self->reconnect_timer_active) { 2 0 2
3470 2 ev_timer_stop(self->loop, &self->reconnect_timer);
3471 2 self->reconnect_timer_active = 0;
3472 2 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 2 0 2
3473 2 nats_drop_queued_requests(self);
3474 2 nats_fail_pong_queue(self, &self->flush_wait);
3475 2 nats_unwind(self);
3476 }
3477  
3478 int
3479 reconnect_enabled(self)
3480 EV::Nats self
3481 CODE:
3482 0 ▶ RETVAL = self->reconnect_enabled;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->reconnect_enabled; 0 0 0
3483 OUTPUT:
3484 RETVAL
3485  
3486 UV
3487 reconnect_buf_size(self, ...)
3488 EV::Nats self
3489 CODE:
3490 6 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 3 3 6
3491 3 IV v = SvIV(ST(1));
3492 3 self->reconnect_buf_size = v < 0 ? 0 : (size_t)v;
3493 }
3494 6 ▶ RETVAL = (UV)self->reconnect_buf_size;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = (UV)self->reconnect_buf_size; 0 6 6
3495 OUTPUT:
3496 RETVAL
3497  
3498 int
3499 connect_timeout(self, ...)
3500 EV::Nats self
3501 ALIAS:
3502 max_pings_outstanding = 1
3503 keepalive = 2
3504 PREINIT:
3505 int *slot;
3506 CODE:
3507 2 slot = ix == 0 ? &self->connect_timeout_ms
3508 2 ▶ : ix == 1 ? &self->max_pings_outstanding : &self->keepalive;
Branch: 2 branches
BranchTrueFalseTotal
: ix == 1 ? &self->max_pings_outstanding : &self->keepalive; 2 0 2
: ix == 1 ? &self->max_pings_outstanding : &self->keepalive; 0 0 0
3509 2 ▶ if (items > 1)
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) 1 1 2
3510 1 *slot = nats_int(ST(1));
3511 2 ▶ RETVAL = *slot;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = *slot; 0 2 2
3512 OUTPUT:
3513 RETVAL
3514  
3515 int
3516 ping_interval(self, ...)
3517 EV::Nats self
3518 CODE:
3519 4 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 3 1 4
3520 3 self->ping_interval_ms = nats_int(ST(1));
3521 /* ev_timer_set on an active watcher corrupts libev's heap */
3522 3 ▶ if (self->ping_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ping_timer_active) { 2 1 3
3523 2 ev_timer_stop(self->loop, &self->ping_timer);
3524 2 self->ping_timer_active = 0;
3525 }
3526 3 ▶ if (self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (self->connected) 2 1 3
3527 2 nats_start_ping_timer(self);
3528 }
3529 4 ▶ RETVAL = self->ping_interval_ms;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->ping_interval_ms; 0 4 4
3530 OUTPUT:
3531 RETVAL
3532  
3533 int
3534 priority(self, ...)
3535 EV::Nats self
3536 CODE:
3537 2 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 2 0 2
3538 2 IV v = SvIV(ST(1));
3539 2 ▶ if (v < -2 || v > 2)
Branch: 2 branches
BranchTrueFalseTotal
if (v < -2 || v > 2) 2 0 2
if (v < -2 || v > 2) 1 1 2
3540 1 croak("priority must be between -2 and +2");
3541 1 self->priority = (int)v;
3542 }
3543 1 ▶ RETVAL = self->priority;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->priority; 0 1 1
3544 OUTPUT:
3545 RETVAL
3546  
3547 void
3548 on_error(self, ...)
3549 EV::Nats self
3550 ALIAS:
3551 on_connect = 1
3552 on_disconnect = 2
3553 on_lame_duck = 3
3554 PREINIT:
3555 SV **slot;
3556 PPCODE:
3557 6 ▶ slot = ix == 0 ? &self->on_error : ix == 1 ? &self->on_connect
Branch: 1 branch
BranchTrueFalseTotal
slot = ix == 0 ? &self->on_error : ix == 1 ? &self->on_connect 4 1 5
3558 1 ▶ : ix == 2 ? &self->on_disconnect : &self->on_ldm;
Branch: 2 branches
BranchTrueFalseTotal
: ix == 2 ? &self->on_disconnect : &self->on_ldm; 0 1 1
: ix == 2 ? &self->on_disconnect : &self->on_ldm; 1 0 1
3559 5 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 5 0 5
3560 5 ▶ CLEAR_HANDLER(*slot);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(*slot); 5 0 5
3561 5 ▶ if (SvOK(ST(1)))
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(ST(1))) 4 1 5
3562 4 *slot = newSVsv(ST(1));
3563 }
3564 5 ▶ if (GIMME_V != G_VOID && *slot)
Branch: 2 branches
BranchTrueFalseTotal
if (GIMME_V != G_VOID && *slot) 0 5 5
if (GIMME_V != G_VOID && *slot) 0 0 0
3565 0 PUSHs(sv_2mortal(newSVsv(*slot)));
3566  
3567 #ifdef HAVE_OPENSSL
3568  
3569 void
3570 tls(self, enable, ca_file = &PL_sv_undef, skip_verify = 0)
3571 EV::Nats self
3572 int enable
3573 SV *ca_file
3574 int skip_verify
3575 PREINIT:
3576 1 ▶ STRLEN ca_len = 0;
Branch: 1 branch
BranchTrueFalseTotal
STRLEN ca_len = 0; 0 1 1
3577 const char *ca;
3578 CODE:
3579 1 ▶ ca = SvOK(ca_file) ? SvPV(ca_file, ca_len) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
ca = SvOK(ca_file) ? SvPV(ca_file, ca_len) : NULL; 0 1 1
3580 1 self->tls = enable;
3581 1 self->tls_skip_verify = skip_verify;
3582 1 ▶ nats_set_strn(&self->tls_ca_file, ca_len ? ca : NULL, ca_len);
Branch: 1 branch
BranchTrueFalseTotal
nats_set_strn(&self->tls_ca_file, ca_len ? ca : NULL, ca_len); 0 1 1
3583 /* Drop the cached context so the next handshake picks the new CA and
3584 verify mode up; an active SSL holds its own reference, so this is
3585 safe on a live connection. */
3586 1 ▶ if (self->ssl_ctx) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl_ctx) { 0 1 1
3587 0 SSL_CTX_free(self->ssl_ctx);
3588 0 self->ssl_ctx = NULL;
3589 }
3590  
3591 #endif
3592  
3593 void
3594 stats(self)
3595 EV::Nats self
3596 PPCODE:
3597 2 ▶ EXTEND(SP, 8);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 8); 0 2 2
3598 2 PUSHs(sv_2mortal(newSVpvs("msgs_in")));
3599 2 PUSHs(sv_2mortal(newSVuv(self->msgs_in)));
3600 2 PUSHs(sv_2mortal(newSVpvs("msgs_out")));
3601 2 PUSHs(sv_2mortal(newSVuv(self->msgs_out)));
3602 2 PUSHs(sv_2mortal(newSVpvs("bytes_in")));
3603 2 PUSHs(sv_2mortal(newSVuv(self->bytes_in)));
3604 2 PUSHs(sv_2mortal(newSVpvs("bytes_out")));
3605 2 PUSHs(sv_2mortal(newSVuv(self->bytes_out)));
3606  
3607 void
3608 reset_stats(self)
3609 EV::Nats self
3610 CODE:
3611 0 self->msgs_in = 0;
3612 0 self->msgs_out = 0;
3613 0 self->bytes_in = 0;
3614 0 self->bytes_out = 0;
3615  
3616 SV *
3617 new_inbox(self)
3618 EV::Nats self
3619 CODE:
3620 {
3621 char inbox[INBOX_SUBJ_SIZE];
3622 17 int len = snprintf(inbox, sizeof(inbox), "%s%llu", self->user_inbox_prefix,
3623 17 (unsigned long long)self->next_req_id++);
3624 17 RETVAL = newSVpvn(inbox, len);
3625 }
3626 OUTPUT:
3627 RETVAL
3628  
3629 int
3630 subscription_count(self)
3631 EV::Nats self
3632 CODE:
3633 22 ▶ RETVAL = HvKEYS(self->sub_map);
Branch: 2 branches
BranchTrueFalseTotal
RETVAL = HvKEYS(self->sub_map); 0 22 22
RETVAL = HvKEYS(self->sub_map); 9 13 22
3634 OUTPUT:
3635 RETVAL
3636  
3637 int
3638 is_subscribed(self, sid)
3639 EV::Nats self
3640 UV sid
3641 CODE:
3642 0 ▶ RETVAL = nats_find_sub(self, (uint64_t)sid) != NULL;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = nats_find_sub(self, (uint64_t)sid) != NULL; 0 0 0
3643 OUTPUT:
3644 RETVAL
3645  
3646 void
3647 batch(self, code)
3648 EV::Nats self
3649 SV *code
3650 CODE:
3651 2 self->batch_mode = 1;
3652 2 SV *pin = self->owner_sv;
3653 2 ▶ if (pin) SvREFCNT_inc(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_inc(pin); 2 0 2
3654 {
3655 2 dSP;
3656 2 ENTER; SAVETMPS;
3657 2 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 2 2
3658 2 PUTBACK;
3659 /* G_EVAL: a die() must not longjmp past the batch_mode reset below;
3660 that would wedge the write path for the connection's lifetime */
3661 2 call_sv(code, G_DISCARD | G_EVAL);
3662 2 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 2 2
3663 }
3664 2 self->batch_mode = 0;
3665 2 ▶ if (self->wbuf_len > self->wbuf_off)
Branch: 1 branch
BranchTrueFalseTotal
if (self->wbuf_len > self->wbuf_off) 0 2 2
3666 0 nats_schedule_write(self);
3667 2 ▶ if (pin) SvREFCNT_dec(pin);
Branch: 1 branch
BranchTrueFalseTotal
if (pin) SvREFCNT_dec(pin); 2 0 2
3668 /* state restored; rethrow so the caller still sees the exception */
3669 2 ▶ if (SvTRUE(ERRSV))
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) 2 0 2
if (SvTRUE(ERRSV)) 1 1 2
3670 1 ▶ croak_sv(ERRSV);
Branch: 1 branch
BranchTrueFalseTotal
croak_sv(ERRSV); 1 0 1
3671  
3672 void
3673 slow_consumer(self, bytes_threshold, cb = NULL)
3674 EV::Nats self
3675 UV bytes_threshold
3676 SV *cb
3677 CODE:
3678 0 self->slow_consumer_bytes = (size_t)bytes_threshold;
3679 0 self->slow_fired = 0;
3680 0 ▶ CLEAR_HANDLER(self->on_slow_consumer);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_slow_consumer); 0 0 0
3681 0 ▶ if (cb && SvOK(cb))
Branch: 2 branches
BranchTrueFalseTotal
if (cb && SvOK(cb)) 0 0 0
if (cb && SvOK(cb)) 0 0 0
3682 0 self->on_slow_consumer = newSVsv(cb);
3683  
3684 #ifdef HAVE_OPENSSL
3685  
3686 void
3687 nkey_seed(self, seed)
3688 EV::Nats self
3689 const char *seed
3690 CODE:
3691 4 ▶ if (seed) {
Branch: 1 branch
BranchTrueFalseTotal
if (seed) { 4 0 4
3692 char pub[64];
3693 4 ▶ if (nats_nkey_public(seed, pub, sizeof(pub)) <= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (nats_nkey_public(seed, pub, sizeof(pub)) <= 0) 1 3 4
3694 1 croak("invalid NKey seed");
3695 }
3696 3 nats_set_str(&self->nkey_seed, seed);
3697  
3698 SV *
3699 nkey_public_from_seed(class, seed)
3700 SV *class
3701 const char *seed
3702 CODE:
3703 (void)class;
3704 {
3705 char pub[64];
3706 4 int n = nats_nkey_public(seed, pub, sizeof(pub));
3707 4 ▶ if (n <= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) 2 2 4
3708 2 croak("invalid NKey seed");
3709 2 RETVAL = newSVpvn(pub, n);
3710 }
3711 OUTPUT:
3712 RETVAL
3713  
3714 SV *
3715 nkey_generate_user_seed(class)
3716 SV *class
3717 CODE:
3718 (void)class;
3719 {
3720 unsigned char raw[36];
3721 /* S+User seed: b1 = PrefixByteSeed | (PrefixByteUser >> 5) = 0x95;
3722 b2 = (PrefixByteUser & 31) << 3 = 0x00. */
3723 3 raw[0] = 0x95;
3724 3 raw[1] = 0x00;
3725 3 ▶ if (!nats_random_bytes(raw + 2, 32))
Branch: 1 branch
BranchTrueFalseTotal
if (!nats_random_bytes(raw + 2, 32)) 0 3 3
3726 0 croak("no entropy source for an NKey seed");
3727 3 uint16_t crc = nats_crc16(raw, 34);
3728 3 raw[34] = crc & 0xFF;
3729 3 raw[35] = (crc >> 8) & 0xFF;
3730 /* 36 bytes -> 58 base32 chars (288 bits, 57 full chars + 1 flush). */
3731 char enc[60];
3732 3 int n = nats_base32_encode(raw, sizeof(raw), enc, sizeof(enc));
3733 3 ▶ if (n < 0) croak("base32 buffer overflow");
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) croak("base32 buffer overflow"); 0 3 3
3734 3 RETVAL = newSVpvn(enc, n);
3735 }
3736 OUTPUT:
3737 RETVAL
3738  
3739 #endif
3740  
3741 void
3742 jwt(self, jwt_token)
3743 EV::Nats self
3744 const char *jwt_token
3745 CODE:
3746 2 nats_set_str(&self->jwt, jwt_token);
3747  
3748 void
3749 drain(self, cb = NULL)
3750 EV::Nats self
3751 SV *cb
3752 CODE:
3753 13 ▶ if (!self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) 1 12 13
3754 1 croak("not connected");
3755 12 ▶ if (self->draining) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->draining) { 2 10 12
3756 2 ▶ if (cb && SvOK(cb))
Branch: 2 branches
BranchTrueFalseTotal
if (cb && SvOK(cb)) 1 1 2
if (cb && SvOK(cb)) 1 0 1
3757 1 croak("drain already in progress");
3758 1 return;
3759 }
3760 10 self->draining = 1;
3761 10 ▶ CLEAR_HANDLER(self->drain_cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->drain_cb); 0 10 10
3762 10 ▶ if (cb && SvOK(cb))
Branch: 2 branches
BranchTrueFalseTotal
if (cb && SvOK(cb)) 9 1 10
if (cb && SvOK(cb)) 9 0 9
3763 9 self->drain_cb = newSVsv(cb);
3764  
3765 {
3766 ngx_queue_t *q;
3767 char buf[64];
3768 15 ▶ ngx_queue_foreach(q, &self->subs) {
Branch: 2 branches
BranchTrueFalseTotal
ngx_queue_foreach(q, &self->subs) { 5 10 15
ngx_queue_foreach(q, &self->subs) { 5 0 5
3769 5 nats_sub_t *sub = ngx_queue_data(q, nats_sub_t, queue);
3770 5 int n = snprintf(buf, sizeof(buf), "UNSUB %" UVuf "\r\n", (UV)sub->sid);
3771 5 wbuf_append(self, buf, n);
3772 }
3773 }
3774  
3775 /* Queued before the write so a synchronous write failure cannot strand
3776 a marker that would tear down the next connection. */
3777 10 wbuf_append(self, "PING\r\n", 6);
3778 {
3779 nats_pong_cb_t *pcb;
3780 10 Newxz(pcb, 1, nats_pong_cb_t);
3781 10 pcb->kind = PONG_DRAIN;
3782 10 ngx_queue_insert_tail(&self->pong_cbs, &pcb->queue);
3783 }
3784 10 ▶ NATS_HOLD_DIES(self);
Branch: 1 branch
BranchTrueFalseTotal
NATS_HOLD_DIES(self); 10 0 10
3785 10 nats_try_write(self);
3786 10 nats_unwind(self);
3787  
3788 void
3789 DESTROY(obj)
3790 SV *obj
3791 PREINIT:
3792 nats_t *self;
3793 CODE:
3794 151 ▶ if (!SvROK(obj) || !SvOBJECT(SvRV(obj)) || !sv_derived_from(obj, "EV::Nats"))
Branch: 3 branches
BranchTrueFalseTotal
if (!SvROK(obj) || !SvOBJECT(SvRV(obj)) || !sv_derived_from(obj, "EV::Nats")) 151 0 151
if (!SvROK(obj) || !SvOBJECT(SvRV(obj)) || !sv_derived_from(obj, "EV::Nats")) 151 0 151
if (!SvROK(obj) || !SvOBJECT(SvRV(obj)) || !sv_derived_from(obj, "EV::Nats")) 0 151 151
3795 0 return;
3796 151 self = INT2PTR(nats_t *, SvIV(SvRV(obj)));
3797 151 ▶ if (!self)
Branch: 1 branch
BranchTrueFalseTotal
if (!self) 2 149 151
3798 2 return;
3799 /* methods called after an explicit DESTROY now croak instead of
3800 reaching freed memory */
3801 149 sv_setiv(SvRV(obj), 0);
3802 149 self->intentional_disconnect = 1;
3803  
3804 149 ▶ if (PL_dirty) {
Branch: 1 branch
BranchTrueFalseTotal
if (PL_dirty) { 53 96 149
3805 53 ▶ if (self->fd >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) 0 53 53
3806 0 close(self->fd);
3807 53 return;
3808 }
3809  
3810 /* DESTROY from inside an event-loop callback: defer the free until the
3811 outermost wrapper returns; its C frames still use self */
3812 96 ▶ if (self->cb_depth > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->cb_depth > 0) { 4 92 96
3813 4 self->destroy_pending = 1;
3814 4 return;
3815 }
3816  
3817 92 nats_destroy_now(self);
« blib/lib/EV/Nats.pm ↑ Summary