-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathconn.c
4468 lines (3668 loc) · 120 KB
/
conn.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015-2024 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "natsp.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "conn.h"
#include "mem.h"
#include "buf.h"
#include "parser.h"
#include "srvpool.h"
#include "url.h"
#include "opts.h"
#include "util.h"
#include "timer.h"
#include "sub.h"
#include "msg.h"
#include "asynccb.h"
#include "comsock.h"
#include "nkeys.h"
#include "crypto.h"
#include "js.h"
#include "glib/glib.h"
#define DEFAULT_SCRATCH_SIZE (512)
#define MAX_INFO_MESSAGE_SIZE (32768)
#define DEFAULT_FLUSH_TIMEOUT (10000)
#define NATS_EVENT_ACTION_ADD (true)
#define NATS_EVENT_ACTION_REMOVE (false)
#ifdef DEV_MODE
// For type safety
static void _retain(natsConnection *nc) { nc->refs++; }
static void _release(natsConnection *nc) { nc->refs--; }
void natsConn_Lock(natsConnection *nc) { natsMutex_Lock(nc->mu); }
void natsConn_Unlock(natsConnection *nc) { natsMutex_Unlock(nc->mu); }
#else
// We know what we are doing :-)
#define _retain(c) ((c)->refs++)
#define _release(c) ((c)->refs--)
#endif // DEV_MODE
// CLIENT_PROTO_ZERO is the original client protocol from 2009.
// http://nats.io/documentation/internals/nats-protocol/
#define CLIENT_PROTO_ZERO (0)
// CLIENT_PROTO_INFO signals a client can receive more then the original INFO block.
// This can be used to update clients on other cluster members, etc.
#define CLIENT_PROTO_INFO (1)
/*
* Forward declarations:
*/
static natsStatus
_spinUpSocketWatchers(natsConnection *nc);
static natsStatus
_processConnInit(natsConnection *nc);
static void
_close(natsConnection *nc, natsConnStatus status, bool fromPublicClose, bool doCBs);
static bool
_processOpError(natsConnection *nc, natsStatus s, bool initialConnect);
static natsStatus
_flushTimeout(natsConnection *nc, int64_t timeout);
static bool
_processAuthError(natsConnection *nc, int errCode, char *error);
static int
_checkAuthError(char *error);
/*
* ----------------------------------------
*/
struct threadsToJoin
{
natsThread *readLoop;
natsThread *flusher;
natsThread *reconnect;
bool joinReconnect;
} threadsToJoin;
static void
_initThreadsToJoin(struct threadsToJoin *ttj, natsConnection *nc, bool joinReconnect)
{
memset(ttj, 0, sizeof(threadsToJoin));
ttj->joinReconnect = joinReconnect;
if (nc->readLoopThread != NULL)
{
ttj->readLoop = nc->readLoopThread;
nc->readLoopThread = NULL;
}
if (joinReconnect && (nc->reconnectThread != NULL))
{
ttj->reconnect = nc->reconnectThread;
nc->reconnectThread = NULL;
}
if (nc->flusherThread != NULL)
{
nc->flusherStop = true;
natsCondition_Signal(nc->flusherCond);
ttj->flusher = nc->flusherThread;
nc->flusherThread = NULL;
}
}
static void
_joinThreads(struct threadsToJoin *ttj)
{
if (ttj->readLoop != NULL)
{
natsThread_Join(ttj->readLoop);
natsThread_Destroy(ttj->readLoop);
}
if (ttj->joinReconnect && (ttj->reconnect != NULL))
{
natsThread_Join(ttj->reconnect);
natsThread_Destroy(ttj->reconnect);
}
if (ttj->flusher != NULL)
{
natsThread_Join(ttj->flusher);
natsThread_Destroy(ttj->flusher);
}
}
static void
_clearServerInfo(natsServerInfo *si)
{
int i;
NATS_FREE(si->id);
NATS_FREE(si->host);
NATS_FREE(si->version);
for (i=0; i<si->connectURLsCount; i++)
NATS_FREE(si->connectURLs[i]);
NATS_FREE(si->connectURLs);
NATS_FREE(si->nonce);
NATS_FREE(si->clientIP);
memset(si, 0, sizeof(natsServerInfo));
}
static void
_freeConn(natsConnection *nc)
{
if (nc == NULL)
return;
natsTimer_Destroy(nc->ptmr);
natsBuf_Destroy(nc->pending);
natsBuf_Destroy(nc->scratch);
natsBuf_Destroy(nc->bw);
natsSrvPool_Destroy(nc->srvPool);
_clearServerInfo(&(nc->info));
natsCondition_Destroy(nc->flusherCond);
natsCondition_Destroy(nc->pongs.cond);
natsParser_Destroy(nc->ps);
natsThread_Destroy(nc->readLoopThread);
natsThread_Destroy(nc->flusherThread);
natsHash_Destroy(nc->subs);
natsOptions_Destroy(nc->opts);
if (nc->sockCtx.ssl != NULL)
SSL_free(nc->sockCtx.ssl);
NATS_FREE(nc->el.buffer);
natsConn_destroyRespPool(nc);
natsInbox_Destroy(nc->respSub);
natsStrHash_Destroy(nc->respMap);
natsCondition_Destroy(nc->reconnectCond);
natsMutex_Destroy(nc->subsMu);
natsMutex_Destroy(nc->mu);
NATS_FREE(nc);
natsLib_Release();
}
void
natsConn_retain(natsConnection *nc)
{
if (nc == NULL)
return;
natsConn_Lock(nc);
nc->refs++;
natsConn_Unlock(nc);
}
void
natsConn_release(natsConnection *nc)
{
int refs = 0;
if (nc == NULL)
return;
natsConn_Lock(nc);
refs = --(nc->refs);
natsConn_Unlock(nc);
if (refs == 0)
_freeConn(nc);
}
void
natsConn_lockAndRetain(natsConnection *nc)
{
natsConn_Lock(nc);
nc->refs++;
}
void
natsConn_unlockAndRelease(natsConnection *nc)
{
int refs = 0;
refs = --(nc->refs);
natsConn_Unlock(nc);
if (refs == 0)
_freeConn(nc);
}
natsStatus
natsConn_bufferFlush(natsConnection *nc)
{
natsStatus s = NATS_OK;
int bufLen = natsBuf_Len(nc->bw);
if (bufLen == 0)
return NATS_OK;
if (nc->usePending)
{
s = natsBuf_Append(nc->pending, natsBuf_Data(nc->bw), bufLen);
}
else if (nc->sockCtx.useEventLoop)
{
if (!(nc->el.writeAdded))
{
nc->el.writeAdded = true;
s = nc->opts->evCbs.write(nc->el.data, NATS_EVENT_ACTION_ADD);
if (s != NATS_OK)
nats_setError(s, "Error processing write request: %d - %s",
s, natsStatus_GetText(s));
}
return NATS_UPDATE_ERR_STACK(s);
}
else
{
s = natsSock_WriteFully(&(nc->sockCtx), natsBuf_Data(nc->bw), bufLen);
}
natsBuf_Reset(nc->bw);
return NATS_UPDATE_ERR_STACK(s);
}
natsStatus
natsConn_bufferWrite(natsConnection *nc, const char *buffer, int len)
{
natsStatus s = NATS_OK;
int offset = 0;
int avail = 0;
if (len <= 0)
return NATS_OK;
if (nc->usePending)
return natsBuf_Append(nc->pending, buffer, len);
if (nc->sockCtx.useEventLoop)
{
s = natsBuf_Append(nc->bw, buffer, len);
if ((s == NATS_OK)
&& (natsBuf_Len(nc->bw) >= nc->opts->ioBufSize)
&& !(nc->el.writeAdded))
{
nc->el.writeAdded = true;
s = nc->opts->evCbs.write(nc->el.data, NATS_EVENT_ACTION_ADD);
if (s != NATS_OK)
nats_setError(s, "Error processing write request: %d - %s",
s, natsStatus_GetText(s));
}
return NATS_UPDATE_ERR_STACK(s);
}
if (nc->dontSendInPlace)
{
s = natsBuf_Append(nc->bw, buffer, len);
return NATS_UPDATE_ERR_STACK(s);
}
// If we have more data that can fit..
while ((s == NATS_OK) && (len > natsBuf_Available(nc->bw)))
{
// If there is nothing in the buffer...
if (natsBuf_Len(nc->bw) == 0)
{
// Do a single socket write to avoid a copy
s = natsSock_WriteFully(&(nc->sockCtx), buffer + offset, len);
// We are done
return NATS_UPDATE_ERR_STACK(s);
}
// We already have data in the buffer, check how many more bytes
// can we fit
avail = natsBuf_Available(nc->bw);
// Append that much bytes
s = natsBuf_Append(nc->bw, buffer + offset, avail);
// Flush the buffer
if (s == NATS_OK)
s = natsConn_bufferFlush(nc);
// If success, then decrement what's left to send and update the
// offset.
if (s == NATS_OK)
{
len -= avail;
offset += avail;
}
}
// If there is data left, the buffer can now hold this data.
if ((s == NATS_OK) && (len > 0))
s = natsBuf_Append(nc->bw, buffer + offset, len);
return NATS_UPDATE_ERR_STACK(s);
}
natsStatus
natsConn_bufferWriteString(natsConnection *nc, const char *string)
{
natsStatus s = natsConn_bufferWrite(nc, string, (int) strlen(string));
return NATS_UPDATE_ERR_STACK(s);
}
// _createConn will connect to the server and do the right thing when an
// existing connection is in place.
static natsStatus
_createConn(natsConnection *nc)
{
natsStatus s = NATS_OK;
// Sets a deadline for the connect process (not just the low level
// tcp connect. The deadline will be removed when we have received
// the PONG to our initial PING. See _processConnInit().
natsSock_InitDeadline(&nc->sockCtx, nc->opts->timeout);
// Set the IP resolution order
nc->sockCtx.orderIP = nc->opts->orderIP;
// Set ctx.noRandomize based on public NoRandomize option.
nc->sockCtx.noRandomize = nc->opts->noRandomize;
s = natsSock_ConnectTcp(&(nc->sockCtx), nc->cur->url->host, nc->cur->url->port);
if (s == NATS_OK)
nc->sockCtx.fdActive = true;
// Need to create or reset the buffer even on failure in case we allow
// retry on failed connect
if ((s == NATS_OK) || nc->opts->retryOnFailedConnect)
{
natsStatus ls = NATS_OK;
if (nc->bw == NULL)
ls = natsBuf_Create(&(nc->bw), nc->opts->ioBufSize);
else
natsBuf_Reset(nc->bw);
if (s == NATS_OK)
s = ls;
}
if (s != NATS_OK)
{
// reset the deadline
natsSock_ClearDeadline(&nc->sockCtx);
}
return NATS_UPDATE_ERR_STACK(s);
}
static void
_clearControlContent(natsControl *control)
{
NATS_FREE(control->op);
NATS_FREE(control->args);
}
static void
_initControlContent(natsControl *control)
{
control->op = NULL;
control->args = NULL;
}
static bool
_isConnecting(natsConnection *nc)
{
return nc->status == NATS_CONN_STATUS_CONNECTING;
}
static bool
_isConnected(natsConnection *nc)
{
return ((nc->status == NATS_CONN_STATUS_CONNECTED) || natsConn_isDraining(nc));
}
bool
natsConn_isClosed(natsConnection *nc)
{
return nc->status == NATS_CONN_STATUS_CLOSED;
}
bool
natsConn_isReconnecting(natsConnection *nc)
{
return (nc->pending != NULL);
}
bool
natsConn_isDraining(natsConnection *nc)
{
return ((nc->status == NATS_CONN_STATUS_DRAINING_SUBS) || (nc->status == NATS_CONN_STATUS_DRAINING_PUBS));
}
bool
natsConn_isDrainingPubs(natsConnection *nc)
{
return nc->status == NATS_CONN_STATUS_DRAINING_PUBS;
}
static natsStatus
_readOp(natsConnection *nc, natsControl *control)
{
natsStatus s = NATS_OK;
char buffer[MAX_INFO_MESSAGE_SIZE];
buffer[0] = '\0';
s = natsSock_ReadLine(&(nc->sockCtx), buffer, sizeof(buffer));
if (s == NATS_OK)
s = nats_ParseControl(control, buffer);
return NATS_UPDATE_ERR_STACK(s);
}
static void
_unpackSrvVersion(natsConnection *nc)
{
nc->srvVersion.ma = 0;
nc->srvVersion.mi = 0;
nc->srvVersion.up = 0;
if (nats_IsStringEmpty(nc->info.version))
return;
sscanf(nc->info.version, "%d.%d.%d", &(nc->srvVersion.ma), &(nc->srvVersion.mi), &(nc->srvVersion.up));
}
bool
natsConn_srvVersionAtLeast(natsConnection *nc, int major, int minor, int update)
{
bool ok;
natsConn_Lock(nc);
ok = (((nc->srvVersion.ma > major)
|| ((nc->srvVersion.ma == major) && (nc->srvVersion.mi > minor))
|| ((nc->srvVersion.ma == major) && (nc->srvVersion.mi == minor) && (nc->srvVersion.up >= update))) ? true : false);
natsConn_Unlock(nc);
return ok;
}
// _processInfo is used to parse the info messages sent
// from the server.
// This function may update the server pool.
static natsStatus
_processInfo(natsConnection *nc, char *info, int len)
{
natsStatus s = NATS_OK;
nats_JSON *json = NULL;
bool postDiscoveredServersCb = false;
bool postLameDuckCb = false;
if (info == NULL)
return NATS_OK;
natsOptions_lock(nc->opts);
postDiscoveredServersCb = (nc->opts->discoveredServersCb != NULL);
postLameDuckCb = (nc->opts->lameDuckCb != NULL);
natsOptions_unlock(nc->opts);
_clearServerInfo(&(nc->info));
s = nats_JSONParse(&json, info, len);
if (s != NATS_OK)
return NATS_UPDATE_ERR_STACK(s);
IFOK(s, nats_JSONGetStr(json, "server_id", &(nc->info.id)));
IFOK(s, nats_JSONGetStr(json, "version", &(nc->info.version)));
IFOK(s, nats_JSONGetStr(json, "host", &(nc->info.host)));
IFOK(s, nats_JSONGetInt(json, "port", &(nc->info.port)));
IFOK(s, nats_JSONGetBool(json, "auth_required", &(nc->info.authRequired)));
IFOK(s, nats_JSONGetBool(json, "tls_required", &(nc->info.tlsRequired)));
IFOK(s, nats_JSONGetBool(json, "tls_available", &(nc->info.tlsAvailable)));
IFOK(s, nats_JSONGetLong(json, "max_payload", &(nc->info.maxPayload)));
IFOK(s, nats_JSONGetArrayStr(json, "connect_urls",
&(nc->info.connectURLs),
&(nc->info.connectURLsCount)));
IFOK(s, nats_JSONGetInt(json, "proto", &(nc->info.proto)));
IFOK(s, nats_JSONGetULong(json, "client_id", &(nc->info.CID)));
IFOK(s, nats_JSONGetStr(json, "nonce", &(nc->info.nonce)));
IFOK(s, nats_JSONGetStr(json, "client_ip", &(nc->info.clientIP)));
IFOK(s, nats_JSONGetBool(json, "ldm", &(nc->info.lameDuckMode)));
IFOK(s, nats_JSONGetBool(json, "headers", &(nc->info.headers)));
if (s == NATS_OK)
_unpackSrvVersion(nc);
// The array could be empty/not present on initial connect,
// if advertise is disabled on that server, or servers that
// did not include themselves in the async INFO protocol.
// If empty, do not remove the implicit servers from the pool.
if ((s == NATS_OK) && !nc->opts->ignoreDiscoveredServers && (nc->info.connectURLsCount > 0))
{
bool added = false;
const char *tlsName = NULL;
if ((nc->cur != NULL) && (nc->cur->url != NULL) && !nats_HostIsIP(nc->cur->url->host))
tlsName = (const char*) nc->cur->url->host;
s = natsSrvPool_addNewURLs(nc->srvPool,
nc->cur->url,
nc->info.connectURLs,
nc->info.connectURLsCount,
tlsName,
&added);
if ((s == NATS_OK) && added && !nc->initc && postDiscoveredServersCb)
natsAsyncCb_PostConnHandler(nc, ASYNC_DISCOVERED_SERVERS);
}
// Process the LDM callback after the above. It will cover cases where
// we have connect URLs and invoke discovered server callback, and case
// where we don't.
if ((s == NATS_OK) && nc->info.lameDuckMode && postLameDuckCb)
natsAsyncCb_PostConnHandler(nc, ASYNC_LAME_DUCK_MODE);
if (s != NATS_OK)
s = nats_setError(NATS_PROTOCOL_ERROR,
"Invalid protocol: %s", nats_GetLastError(NULL));
nats_JSONDestroy(json);
return NATS_UPDATE_ERR_STACK(s);
}
// natsConn_processAsyncINFO does the same than processInfo, but is called
// from the parser. Calls processInfo under connection's lock
// protection.
void
natsConn_processAsyncINFO(natsConnection *nc, char *buf, int len)
{
natsConn_Lock(nc);
// Ignore errors, we will simply not update the server pool...
(void) _processInfo(nc, buf, len);
natsConn_Unlock(nc);
}
#if defined(NATS_HAS_TLS)
static int
_collectSSLErr(int preverifyOk, X509_STORE_CTX* ctx)
{
SSL *ssl = NULL;
X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
int depth = X509_STORE_CTX_get_error_depth(ctx);
int err = X509_STORE_CTX_get_error(ctx);
natsConnection *nc = NULL;
// Retrieve the SSL object, then our connection...
ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
nc = (natsConnection*) SSL_get_ex_data(ssl, 0);
// Should we skip serve certificate verification?
if (nc->opts->sslCtx->skipVerify)
return 1;
if (!preverifyOk)
{
char certName[256]= {0};
X509_NAME_oneline(X509_get_subject_name(cert), certName, sizeof(certName));
if (err == X509_V_ERR_HOSTNAME_MISMATCH)
{
snprintf_truncate(nc->errStr, sizeof(nc->errStr), "%d:%s:expected=%s:cert=%s",
err, X509_verify_cert_error_string(err), nc->tlsName,
certName);
}
else
{
char issuer[256] = {0};
X509_NAME_oneline(X509_get_issuer_name(cert), issuer, sizeof(issuer));
snprintf_truncate(nc->errStr, sizeof(nc->errStr), "%d:%s:depth=%d:cert=%s:issuer=%s",
err, X509_verify_cert_error_string(err), depth,
certName, issuer);
}
}
return preverifyOk;
}
#endif
// makeTLSConn will wrap an existing Conn using TLS
static natsStatus
_makeTLSConn(natsConnection *nc)
{
#if defined(NATS_HAS_TLS)
natsStatus s = NATS_OK;
SSL *ssl = NULL;
// Reset nc->errStr before initiating the handshake...
nc->errStr[0] = '\0';
natsMutex_Lock(nc->opts->sslCtx->lock);
s = natsSock_SetBlocking(nc->sockCtx.fd, true);
if (s == NATS_OK)
{
ssl = SSL_new(nc->opts->sslCtx->ctx);
if (ssl == NULL)
{
s = nats_setError(NATS_SSL_ERROR,
"Error creating SSL object: %s",
NATS_SSL_ERR_REASON_STRING);
}
else
{
nats_sslRegisterThreadForCleanup();
SSL_set_ex_data(ssl, 0, (void*) nc);
}
}
if (s == NATS_OK)
{
SSL_set_connect_state(ssl);
if (SSL_set_fd(ssl, (int) nc->sockCtx.fd) != 1)
{
s = nats_setError(NATS_SSL_ERROR,
"Error connecting the SSL object to a file descriptor : %s",
NATS_SSL_ERR_REASON_STRING);
}
}
if (s == NATS_OK)
{
if (nc->opts->sslCtx->skipVerify)
{
SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
}
else
{
nc->tlsName = NULL;
// If we don't force hostname verification, perform it only
// if expectedHostname is set (to be backward compatible with
// releases prior to 2.0.0)
if (nc->opts->sslCtx->expectedHostname != NULL)
nc->tlsName = nc->opts->sslCtx->expectedHostname;
#if defined(NATS_FORCE_HOST_VERIFICATION)
else if (nc->cur->tlsName != NULL)
nc->tlsName = nc->cur->tlsName;
else
nc->tlsName = nc->cur->url->host;
#endif
if (nc->tlsName != NULL)
{
#if defined(NATS_USE_OPENSSL_1_1)
SSL_set_hostflags(ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
if (!SSL_set1_host(ssl, nc->tlsName))
#else
X509_VERIFY_PARAM *param = SSL_get0_param(ssl);
X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
if (!X509_VERIFY_PARAM_set1_host(param, nc->tlsName, 0))
#endif
s = nats_setError(NATS_SSL_ERROR, "unable to set expected hostname '%s'", nc->tlsName);
}
if (s == NATS_OK)
SSL_set_verify(ssl, SSL_VERIFY_PEER, _collectSSLErr);
}
}
#if defined(NATS_USE_OPENSSL_1_1)
// add the host name in the SNI extension
if ((s == NATS_OK) && (nc->cur != NULL) && (!SSL_set_tlsext_host_name(ssl, nc->cur->url->host)))
{
s = nats_setError(NATS_SSL_ERROR, "unable to set SNI extension for hostname '%s'", nc->cur->url->host);
}
#endif
if ((s == NATS_OK) && (SSL_do_handshake(ssl) != 1))
{
s = nats_setError(NATS_SSL_ERROR,
"SSL handshake error: %s",
(nc->errStr[0] != '\0' ? nc->errStr : NATS_SSL_ERR_REASON_STRING));
}
// Make sure that if nc-errStr was set in _collectSSLErr but
// the overall handshake is ok, then we clear the error
if (s == NATS_OK)
{
nc->errStr[0] = '\0';
s = natsSock_SetBlocking(nc->sockCtx.fd, false);
}
natsMutex_Unlock(nc->opts->sslCtx->lock);
if (s != NATS_OK)
{
if (ssl != NULL)
SSL_free(ssl);
}
else
{
nc->sockCtx.ssl = ssl;
}
return NATS_UPDATE_ERR_STACK(s);
#else
return nats_setError(NATS_ILLEGAL_STATE, "%s", NO_SSL_ERR);
#endif
}
// This will check to see if the connection should be
// secure. This can be dictated from either end and should
// only be called after the INIT protocol has been received.
static natsStatus
_checkForSecure(natsConnection *nc)
{
natsStatus s = NATS_OK;
// Check for mismatch in setups
if (nc->opts->secure && !nc->info.tlsRequired && !nc->info.tlsAvailable)
s = nats_setDefaultError(NATS_SECURE_CONNECTION_WANTED);
else if (nc->info.tlsRequired && !nc->opts->secure)
{
// Switch to Secure since server needs TLS.
s = natsOptions_SetSecure(nc->opts, true);
}
if ((s == NATS_OK) && nc->opts->secure)
{
// If TLS handshake first is true, we have already done
// the handshake, so do it only if false.
if (!nc->opts->tlsHandshakeFirst)
s = _makeTLSConn(nc);
}
return NATS_UPDATE_ERR_STACK(s);
}
static natsStatus
_processExpectedInfo(natsConnection *nc)
{
natsControl control;
natsStatus s;
_initControlContent(&control);
s = _readOp(nc, &control);
if (s != NATS_OK)
return NATS_UPDATE_ERR_STACK(s);
if ((s == NATS_OK)
&& ((control.op == NULL)
|| (strcmp(control.op, _INFO_OP_) != 0)))
{
s = nats_setError(NATS_PROTOCOL_ERROR,
"Unexpected protocol: got '%s' instead of '%s'",
(control.op == NULL ? "<null>" : control.op),
_INFO_OP_);
}
if (s == NATS_OK)
s = _processInfo(nc, control.args, -1);
if (s == NATS_OK)
s = _checkForSecure(nc);
_clearControlContent(&control);
return NATS_UPDATE_ERR_STACK(s);
}
static char*
_escape(char *origin)
{
char escChar[] = {'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\'};
char escRepl[] = {'a', 'b', 'f', 'n', 'r', 't', 'v', '\\'};
int l = (int) strlen(origin);
int ec = 0;
char *dest = NULL;
char *ptr = NULL;
int i;
int j;
for (i=0; i<l; i++)
{
for (j=0; j<8; j++)
{
if (origin[i] == escChar[j])
{
ec++;
break;
}
}
}
if (ec == 0)
return origin;
dest = NATS_MALLOC(l + ec + 1);
if (dest == NULL)
return NULL;
ptr = dest;
for (i=0; i<l; i++)
{
for (j=0; j<8 ;j++)
{
if (origin[i] == escChar[j])
{
*ptr++ = '\\';
*ptr++ = escRepl[j];
break;
}
}
if(j == 8 )
*ptr++ = origin[i];
}
*ptr = '\0';
return dest;
}
static natsStatus
_connectProto(natsConnection *nc, char **proto)
{
natsStatus s = NATS_OK;
natsOptions *opts = nc->opts;
const char *token= NULL;
const char *user = NULL;
const char *pwd = NULL;
const char *name = NULL;
char *sig = NULL;
char *ujwt = NULL;
char *nkey = NULL;
int res;
unsigned char *sigRaw = NULL;
int sigRawLen = 0;
// Check if NoEcho is set and we have a server that supports it.
if (opts->noEcho && (nc->info.proto < 1))
return NATS_NO_SERVER_SUPPORT;
if (nc->cur->url->username != NULL)
user = nc->cur->url->username;
if (nc->cur->url->password != NULL)
pwd = nc->cur->url->password;
if ((user != NULL) && (pwd == NULL))
{
token = user;
user = NULL;
}
if ((user == NULL) && (token == NULL))
{
// Take from options (possibly all NULL)
user = opts->user;
pwd = opts->password;
token = opts->token;
nkey = opts->nkey;
// Options take precedence for an implicit URL. If above is still
// empty, we will check if we have saved a user from an explicit
// URL in the server pool.
if (nats_IsStringEmpty(user)
&& nats_IsStringEmpty(token)
&& (nc->srvPool->user != NULL))
{
user = nc->srvPool->user;
pwd = nc->srvPool->pwd;
// Again, if there is no password, assume username is token.
if (pwd == NULL)
{
token = user;
user = NULL;
}
}
}
if (opts->userJWTHandler != NULL)
{
char *errTxt = NULL;
bool userCb = opts->userJWTHandler != natsConn_userCreds;
// If callback is not the internal one, we need to release connection lock.
if (userCb)
natsConn_Unlock(nc);
s = opts->userJWTHandler(&ujwt, &errTxt, (void*) opts->userJWTClosure);
if (userCb)
{
natsConn_Lock(nc);
if (natsConn_isClosed(nc) && (s == NATS_OK))
s = NATS_CONNECTION_CLOSED;
}
if ((s != NATS_OK) && (errTxt != NULL))
{
s = nats_setError(s, "%s", errTxt);
NATS_FREE(errTxt);
}
if ((s == NATS_OK) && !nats_IsStringEmpty(nkey))
s = nats_setError(NATS_ILLEGAL_STATE, "%s", "user JWT callback and NKey cannot be both specified");
if ((s == NATS_OK) && (ujwt != NULL))
{
char *tmp = _escape(ujwt);
if (tmp == NULL)
{
s = nats_setDefaultError(NATS_NO_MEMORY);
}
else if (tmp != ujwt)
{
NATS_FREE(ujwt);
ujwt = tmp;
}
}
}
if ((s == NATS_OK) && (!nats_IsStringEmpty(ujwt) || !nats_IsStringEmpty(nkey)))
{
char *errTxt = NULL;
bool userCb = opts->sigHandler != natsConn_signatureHandler;
if (userCb)
natsConn_Unlock(nc);
s = opts->sigHandler(&errTxt, &sigRaw, &sigRawLen, nc->info.nonce, opts->sigClosure);
if (userCb)
{
natsConn_Lock(nc);
if (natsConn_isClosed(nc) && (s == NATS_OK))
s = NATS_CONNECTION_CLOSED;
}
if ((s != NATS_OK) && (errTxt != NULL))
{
s = nats_setError(s, "%s", errTxt);