Nats.xs

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