-
Notifications
You must be signed in to change notification settings - Fork 7
/
websocket_module.cc
4163 lines (3717 loc) · 151 KB
/
websocket_module.cc
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
#include "global.h"
#include "ssh2_module.h"
#include "websocket_module.h"
//#define DEBUG_EVENTS
//#define EVENT_DEBUG_STDOUT
#ifdef DEBUG_EVENTS
# ifdef EVENT_DEBUG_STDOUT
# undef lprintf
# define lprintf(f,...) printf( "%d~" f "\n", (int)(GetThisThreadID() & 0x7FFFFFF),##__VA_ARGS__)
# endif
#endif
/*
MessageEvent.data Read only
The data sent by the message emitter.
MessageEvent.origin Read only
A USVString representing the origin of the message emitter.
MessageEvent.lastEventId Read only
A DOMString representing a unique ID for the event.
MessageEvent.source Read only
A MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter.
MessageEvent.ports Read only
*/
/*
CONNECTING = 0
OPEN (1)
CLOSING (2)
CLOSED (3)
---
LISTENING (4)
Constructor(DOMString type, optional CloseEventInit eventInitDict)]
interface CloseEvent : Event {
readonly attribute boolean wasClean;
readonly attribute unsigned short code;
readonly attribute DOMString reason;
};
dictionary CloseEventInit : EventInit {
boolean wasClean;
unsigned short code;
DOMString reason;
};
readonly attribute unsigned short readyState;
readonly attribute unsigned long bufferedAmount;
readonly attribute DOMString extensions;
The extensions attribute returns the extensions selected by the server, if any. (Currently this will only ever be the empty string.)
readonly attribute DOMString protocol;
The protocol attribute returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form
of the constructor's second argument to perform subprotocol negotiation.
attribute DOMString binaryType;
void send(DOMString data);
void send(Blob data);
void send(ArrayBuffer data);
void send(ArrayBufferView data);
*/
enum wsEvents {
WS_EVENT_OPEN, // onaccept/onopen callback (wss(passes wssi),wsc)
WS_EVENT_ACCEPT, // onaccept callback (wss)
WS_EVENT_CLOSE, // onClose callback (wss(internal only), wssi, wsc)
WS_EVENT_READ, // onMessage callback (wssi,wsc)
WS_EVENT_ERROR, // error event (unused) (wssi,wss,wsc)
WS_EVENT_REQUEST,// websocket non-upgrade request
WS_EVENT_RESPONSE,// websocket non-upgrade request
WS_EVENT_ERROR_CLOSE, // illegal server connection
WS_EVENT_LOW_ERROR,
WS_EVENT_RELEASE_BUFFER,
WS_EVENT_ACCEPT_SSH, // a new websocket over SSH connection to create (uses wssi)
};
struct optionStrings {
Isolate *isolate;
Eternal<String> *portString;
Eternal<String> *urlString;
Eternal<String> *v4String;
Eternal<String> *v6String;
Eternal<String> *localFamilyString;
Eternal<String> *remoteFamilyString;
Eternal<String> *localPortString;
Eternal<String> *remotePortString;
Eternal<String> *addressString;
Eternal<String> *localAddrString;
Eternal<String> *remoteAddrString;
Eternal<String>* localNameString;
Eternal<String>* remoteNameString;
Eternal<String> *localMacString;
Eternal<String> *remoteMacString;
Eternal<String> *headerString;
Eternal<String> *certString;
Eternal<String> *CGIString;
Eternal<String> *contentString;
Eternal<String> *keyString;
Eternal<String> *pemString;
Eternal<String> *passString;
Eternal<String> *deflateString;
Eternal<String> *deflateAllowString;
Eternal<String>* resolveString;
Eternal<String>* getMacString;
Eternal<String> *caString;
Eternal<String> *vUString;
Eternal<String> *connectionString;
Eternal<String> *maskingString;
Eternal<String> *bytesReadString;
Eternal<String> *bytesWrittenString;
Eternal<String> *requestString;
Eternal<String> *readyStateString;
Eternal<String> *bufferedAmountString;
Eternal<String> *hostnameString;
Eternal<String>* hostsString;
Eternal<String>* hostString;
Eternal<String> *rejectUnauthorizedString;
Eternal<String> *pathString;
Eternal<String> *methodString;
Eternal<String> *redirectString;
Eternal<String> *keepAliveString;
Eternal<String> *versionString;
Eternal<String> *onReplyString;
Eternal<String> *agentString;
Eternal<String> *timeoutString;
Eternal<String> *retriesString;
Eternal<String>* pipeString;
};
static PLIST strings;
struct wssHostOption {
char* host;
int hostlen;
char* cert_chain;
int cert_chain_len;
char* key;
int key_len;
char* pass;
int pass_len;
};
struct wssOptions {
char *url;
char *address;
int port;
bool ssl;
char *cert_chain;
int cert_chain_len;
char *key;
int key_len;
char *pass;
int pass_len;
bool deflate;
bool deflate_allow;
bool apply_masking;
PLIST hostList;
SSH2_Channel* channel;
bool resolveName;
bool getMAC;
bool pipe;
};
struct wscOptions {
char *url;
char *protocol;
bool ssl;
char *key;
int key_len;
char *pass;
int pass_len;
char *root_cert;
bool deflate;
bool deflate_allow;
bool apply_masking;
bool keep_alive;
bool resolveName;
bool getMAC;
};
struct pendingSend {
LOGICAL binary;
POINTER buffer;
size_t buflen;
};
struct wssEvent {
enum wsEvents eventType;
class wssObject *_this;
class SSH2_Channel *channel;
union {
struct pendingWrite* write;
struct {
int accepted;
const char *protocol;
const char *resource;
} request;
struct {
int error;
const char *buffer;
size_t buflen;
int fallback_ssl;
} error;
}data;
PLIST send;
PCLIENT pc;
PTHREAD waiter;
LOGICAL done;
class wssiObject *result;
int uses;
};
typedef struct wssEvent WSS_EVENT;
#define MAXWSS_EVENTSPERSET 64
DeclareSet( WSS_EVENT );
struct wssiEvent {
enum wsEvents eventType;
class wssiObject *_this;
//PLIST send;
//LOGICAL send_close; // need reason.
int code;
CPOINTER buf;
size_t buflen;
LOGICAL binary;
//PTHREAD waiter;
//LOGICAL done;
};
typedef struct wssiEvent WSSI_EVENT;
#define MAXWSSI_EVENTSPERSET 128
DeclareSet( WSSI_EVENT );
struct wscEvent {
enum wsEvents eventType;
class wscObject *_this;
CPOINTER buf;
int code;
size_t buflen;
LOGICAL binary;
};
typedef struct wscEvent WSC_EVENT;
#define MAXWSC_EVENTSPERSET 128
DeclareSet( WSC_EVENT );
struct httpRequestEvent {
enum wsEvents eventType;
class httpRequestObject *_this;
HTTPState state;
};
typedef struct httpRequestEvent HTTP_REQUEST_EVENT;
#define MAXHTTP_REQUEST_EVENTSPERSET 128
DeclareSet( HTTP_REQUEST_EVENT );
struct socketTransport {
class wssiObject *wssi;
WSS_EVENT* acceptEventMessage;
const char *protocolResponse;
};
struct socketUnloadStation {
Persistent<Object> this_;
String::Utf8Value* s; // destination address
uv_async_t clientSocketPoster;
uv_loop_t *targetThread;
Persistent<Function> cb; // callback to invoke
PLIST transport;
};
struct pendingWrite {
Persistent<ArrayBuffer> buffer;
CPOINTER data;
wssObject* wss;
};
static struct local {
int data;
//uv_loop_t* loop;
int waiting;
PTHREAD jsThread;
CRITICALSECTION csWssEvents;
PWSS_EVENTSET wssEvents;
CRITICALSECTION csWssiEvents;
PWSSI_EVENTSET wssiEvents;
CRITICALSECTION csWscEvents;
PWSC_EVENTSET wscEvents;
CRITICALSECTION csHttpRequestEvents;
PHTTP_REQUEST_EVENTSET httpRequestEvents;
PLIST transportDestinations;
PLIST pendingWrites;
CRITICALSECTION csConnect;
CRITICALSECTION csOpen;
} l;
static void promoteSSH_to_Websocket( const v8::FunctionCallbackInfo<Value>& args );
static struct optionStrings *getStrings( Isolate *isolate ) {
INDEX idx;
struct optionStrings * check;
LIST_FORALL( strings, idx, struct optionStrings *, check ) {
if( check->isolate == isolate )
break;
}
if( !check ) {
check = NewArray( struct optionStrings, 1 );
AddLink( &strings, check );
check->isolate = isolate;
check->readyStateString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "readyState" ) );
check->portString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "port" ) );
check->urlString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "url" ) );
check->localPortString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "localPort" ) );
check->remotePortString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "remotePort" ) );
check->addressString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "address" ) );
check->localAddrString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "localAddress" ) );
check->remoteAddrString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "remoteAddress" ) );
check->localNameString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "localName" ) );
check->remoteNameString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "remoteName" ) );
check->localMacString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "localMAC" ) );
check->remoteMacString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "remoteMAC" ) );
check->localFamilyString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "localFamily" ) );
check->remoteFamilyString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "remoteFamily" ) );
check->headerString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "headers" ) );
check->CGIString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "CGI" ) );
check->contentString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "content" ) );
check->certString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "cert" ) );
check->keyString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "key" ) );
check->pemString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "pem" ) );
check->passString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "passphrase" ) );
check->resolveString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "resolveNames" ) );
check->getMacString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "getMAC" ) );
check->deflateString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "perMessageDeflate" ) );
check->pipeString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "pipe" ) );
check->deflateAllowString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "perMessageDeflateAllow" ) );
check->caString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "ca" ) );
check->v4String = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "IPv4" ) );
check->v6String = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "IPv6" ) );
check->vUString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "unknown" ) );
check->connectionString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "connection" ) );
check->maskingString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "masking" ) );
check->bytesReadString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "bytesRead" ) );
check->bytesWrittenString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "bytesWritten" ) );
check->requestString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "request" ) );
check->bufferedAmountString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "bufferedAmount" ) );
check->hostnameString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "hostname" ) );
check->hostString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "host" ) );
check->hostsString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "hosts" ) );
check->retriesString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "retries" ) );
check->timeoutString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "timeout" ) );
check->pathString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "path" ) );
check->methodString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "method" ) );
check->redirectString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "redirect" ) );
check->rejectUnauthorizedString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "rejectUnauthorized" ) );
check->keepAliveString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "keepAlive" ) );
check->versionString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "version" ) );
check->onReplyString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "onReply" ) );
check->agentString = new Eternal<String>( isolate, String::NewFromUtf8Literal( isolate, "agent" ) );
}
return check;
}
class httpRequestObject : public node::ObjectWrap {
public:
PCLIENT pc;
//static Persistent<Function> constructor;
Persistent<Object> _this;
struct HTTPRequestOptions* opts;
//PVARTEXT pvtResult;
bool ssl;
int port;
char *hostname;
const char *method = "GET";
const char* content = NULL;
size_t contentLen = 0;
const char* httpVersion = NULL;
int timeout = 3000;
int retries = 3;
PLIST headers = NULL;
char *ca = NULL;
char *path = NULL;
char *agent = NULL;
bool rejectUnauthorized;
bool firstDispatchDone;
bool dataDispatch;
bool endDispatch;
bool finished;
PTHREAD waiter;
PTEXT result;
HTTPState state;
// if set, will be called when content buffer has been sent.
//void ( *writeComplete )(void );
public:
httpRequestObject();
static void New( const v8::FunctionCallbackInfo<Value>& args );
static void on( const v8::FunctionCallbackInfo<Value>& args );
static void wait( const v8::FunctionCallbackInfo<Value>& args );
static void get( const v8::FunctionCallbackInfo<Value>& args );
static void gets( const v8::FunctionCallbackInfo<Value>& args );
static void getRequest( const v8::FunctionCallbackInfo<Value>& args, bool secure );
Persistent<Object> resultObject;
Persistent<Function, CopyablePersistentTraits<Function>> resultCallback;
Persistent<Function, CopyablePersistentTraits<Function>> cbError;
uv_async_t async; // keep this instance around for as long as we might need to do the periodic callback
PLINKQUEUE eventQueue;
~httpRequestObject();
};
// web sock server Object
class httpObject : public node::ObjectWrap {
public:
PCLIENT pc;
//static Persistent<Function> constructor;
PVARTEXT pvtResult;
bool ssl;
wssObject* wss;
Isolate *isolate;
bool headWritten = false;
public:
httpObject();
static void New( const v8::FunctionCallbackInfo<Value>& args );
static void writeHead( const v8::FunctionCallbackInfo<Value>& args );
static void end( const v8::FunctionCallbackInfo<Value>& args );
~httpObject();
};
// web sock client Object
class wscObject : public node::ObjectWrap {
public:
PCLIENT pc;
bool resolveAddr;
bool resolveMac;
uv_async_t async; // keep this instance around for as long as we might need to do the periodic callback
Persistent<Object> _this;
PLINKQUEUE eventQueue;
//wscEvent *eventMessage;
LOGICAL closed;
enum wsReadyStates readyState;
Isolate *isolate;
public:
//static Persistent<Function> constructor;
//static Persistent<FunctionTemplate> tpl;
//Persistent<Function, CopyablePersistentTraits<Function>> openCallback; //
//Persistent<Function, CopyablePersistentTraits<Function>> messageCallback; //
//Persistent<Function, CopyablePersistentTraits<Function>> errorCallback; //
//Persistent<Function, CopyablePersistentTraits<Function>> closeCallback; //
PLIST openCallbacks = NULL;
PLIST messageCallbacks = NULL;
PLIST closeCallbacks = NULL;
PLIST errorCallbacks = NULL;
public:
wscObject( wscOptions *opts );
static void New( const v8::FunctionCallbackInfo<Value>& args );
static void close( const v8::FunctionCallbackInfo<Value>& args );
static void on( const v8::FunctionCallbackInfo<Value>& args );
static void onMessage( const v8::FunctionCallbackInfo<Value>& args );
static void onError( const v8::FunctionCallbackInfo<Value>& args );
static void onClose( const v8::FunctionCallbackInfo<Value>& args );
static void onOpen( const v8::FunctionCallbackInfo<Value>& args );
static void getOnMessage( const v8::FunctionCallbackInfo<Value>& args );
static void getOnError( const v8::FunctionCallbackInfo<Value>& args );
static void getOnClose( const v8::FunctionCallbackInfo<Value>& args );
static void getOnOpen( const v8::FunctionCallbackInfo<Value>& args );
static void write( const v8::FunctionCallbackInfo<Value>& args );
static void getReadyState( const FunctionCallbackInfo<Value>& args );
static void ping( const v8::FunctionCallbackInfo<Value>& args );
static void nodelay( const v8::FunctionCallbackInfo<Value>& args );
static void aggregate( const v8::FunctionCallbackInfo<Value>& args );
~wscObject();
};
class callbackFunction {
public:
Persistent<Function, CopyablePersistentTraits<Function>> callback; //
};
// web sock server instance Object (a connection from a remote)
class wssiObject : public node::ObjectWrap {
public:
uv_async_t async; // keep this instance around for as long as we might need to do the periodic callback
Persistent<Object> _this;
PLINKQUEUE eventQueue;
PCLIENT pc;
struct html5_web_socket* wsPipe;
bool resolveAddr;
bool resolveMac;
LOGICAL closed;
const char *protocolResponse;
enum wsReadyStates readyState;
Isolate *isolate;
class wssiObjectReference *wssiRef;
class wssObject *server; // send open event to this object.
WSS_EVENT* acceptEventMessage;
Persistent<Promise> acceptPromise;
LOGICAL blockReturn;
LOGICAL thrown; // prevent event to server connect callback, event becomes post to thread
public:
//static Persistent<Function> constructor;
//static Persistent<FunctionTemplate> tpl;
////Persistent<Function, CopyablePersistentTraits<Function>> openCallback; //
//Persistent<Function, CopyablePersistentTraits<Function>> errorCallback; //
//Persistent<Function, CopyablePersistentTraits<Function>> messageCallback; //
//Persistent<Function, CopyablePersistentTraits<Function>> closeCallback; //
PLIST messageCallbacks = NULL;
PLIST closeCallbacks = NULL;
PLIST errorCallbacks = NULL;
public:
wssiObject();
static void New( const v8::FunctionCallbackInfo<Value>& args );
static void write( const v8::FunctionCallbackInfo<Value>& args );
static void close( const v8::FunctionCallbackInfo<Value>& args );
static void on( const v8::FunctionCallbackInfo<Value>& args );
static void onmessage( const v8::FunctionCallbackInfo<Value>& args );
static void onclose( const v8::FunctionCallbackInfo<Value>& args );
static void getReadyState( const FunctionCallbackInfo<Value>& args );
static void nodelay( const FunctionCallbackInfo<Value>& args );
static void ping( const v8::FunctionCallbackInfo<Value>& args );
static void aggregate( const v8::FunctionCallbackInfo<Value>& args );
~wssiObject();
};
class wssiObjectReference {
public:
class wssiObject *wssi;
};
//------------------------------------ Event Helpers ---------------------------------------
static WSS_EVENT *GetWssEvent() {
EnterCriticalSec( &l.csWssEvents );
WSS_EVENT *evt = GetFromSet( WSS_EVENT, &l.wssEvents );
memset( evt, 0, sizeof( WSS_EVENT ) );
evt->uses = 1;
LeaveCriticalSec( &l.csWssEvents );
return evt;
}
static WSSI_EVENT *GetWssiEvent() {
EnterCriticalSec( &l.csWssiEvents );
WSSI_EVENT *evt = GetFromSet( WSSI_EVENT, &l.wssiEvents );
memset( evt, 0, sizeof( WSSI_EVENT ) );
LeaveCriticalSec( &l.csWssiEvents );
return evt;
}
static WSC_EVENT *GetWscEvent() {
EnterCriticalSec( &l.csWscEvents );
WSC_EVENT *evt = GetFromSet( WSC_EVENT, &l.wscEvents );
memset( evt, 0, sizeof( WSC_EVENT ) );
LeaveCriticalSec( &l.csWscEvents );
return evt;
}
static HTTP_REQUEST_EVENT *GetHttpRequestEvent() {
EnterCriticalSec( &l.csHttpRequestEvents );
HTTP_REQUEST_EVENT *evt = GetFromSet( HTTP_REQUEST_EVENT, &l.httpRequestEvents );
memset( evt, 0, sizeof( HTTP_REQUEST_EVENT ) );
LeaveCriticalSec( &l.csHttpRequestEvents );
return evt;
}
static void HoldWssEvent( WSS_EVENT *evt ) {
evt->uses++;
}
static void DropWssEvent( WSS_EVENT *evt ) {
EnterCriticalSec( &l.csWssEvents );
if( !(--evt->uses ) ) {
DeleteFromSet( WSS_EVENT, l.wssEvents, evt );
}
//lprintf( "Events outstanding:%d %d", evt->uses, CountUsedInSet( WSS_EVENT, l.wssEvents ) );
LeaveCriticalSec( &l.csWssEvents );
}
static void DropWssiEvent( WSSI_EVENT *evt ) {
EnterCriticalSec( &l.csWssiEvents );
DeleteFromSet( WSSI_EVENT, l.wssiEvents, evt );
LeaveCriticalSec( &l.csWssiEvents );
}
static void DropWscEvent( WSC_EVENT *evt ) {
EnterCriticalSec( &l.csWscEvents );
DeleteFromSet( WSC_EVENT, l.wscEvents, evt );
LeaveCriticalSec( &l.csWscEvents );
}
static void DropHttpRequestEvent( HTTP_REQUEST_EVENT *evt ) {
EnterCriticalSec( &l.csHttpRequestEvents );
DeleteFromSet( HTTP_REQUEST_EVENT, l.httpRequestEvents, evt );
LeaveCriticalSec( &l.csHttpRequestEvents );
}
static void uv_closed_wssi( uv_handle_t* handle ) {
wssiObject* myself = (wssiObject*)handle->data;
//myself->openCallback.Reset();
INDEX idx;
callbackFunction* c;
LIST_FORALL( myself->messageCallbacks, idx, callbackFunction*, c ) c->callback.Reset();
LIST_FORALL( myself->closeCallbacks, idx, callbackFunction*, c ) c->callback.Reset();
LIST_FORALL( myself->errorCallbacks, idx, callbackFunction*, c ) c->callback.Reset();
myself->_this.Reset();
}
static void uv_closed_wss( uv_handle_t* handle ) {
wssObject* myself = (wssObject*)handle->data;
myself->openCallback.Reset();
myself->acceptCallback.Reset();
myself->requestCallback.Reset();
myself->errorCloseCallback.Reset();
myself->_this.Reset();
}
static void uv_closed_wsc( uv_handle_t* handle ) {
wscObject* myself = (wscObject*)handle->data;
INDEX idx;
callbackFunction* c;
LIST_FORALL( myself->messageCallbacks, idx, callbackFunction*, c ) c->callback.Reset();
LIST_FORALL( myself->closeCallbacks, idx, callbackFunction*, c ) c->callback.Reset();
LIST_FORALL( myself->errorCallbacks, idx, callbackFunction*, c ) c->callback.Reset();
LIST_FORALL( myself->openCallbacks, idx, callbackFunction*, c ) c->callback.Reset();
myself->_this.Reset();
}
struct cgiParams {
Isolate *isolate;
Local<Object> cgi;
};
static void cgiParamSave(uintptr_t psv, PTEXT name, PTEXT value){
struct cgiParams *cgi = (struct cgiParams*)psv;
Isolate *isolate = cgi->isolate;
Local<Context> context = cgi->isolate->GetCurrentContext();
if( value )
SETT( cgi->cgi, name, String::NewFromUtf8( cgi->isolate, GetText( value ), v8::NewStringType::kNormal ).ToLocalChecked() );
else
SETT( cgi->cgi, name, Null( cgi->isolate ) );
}
static Local<Object> makeSocket( Isolate* isolate, PCLIENT pc, struct html5_web_socket* pipe, wssObject* wss, wscObject* wsc, wssiObject* wssi ) {
Local<Context> context = isolate->GetCurrentContext();
//wssi
if( wss || wsc || wssi ) {
if( wssi && wssi->wsPipe )
pc = NULL;
}
PLIST headers = (pc)?GetWebSocketHeaders( pc ):wss?GetWebSocketPipeHeaders( wss->wsPipe ) : wssi ? GetWebSocketPipeHeaders( wssi->wsPipe ) : NULL;
PTEXT resource = ( pc ) ?GetWebSocketResource( pc ):wss?GetWebSocketPipeResource( wss->wsPipe ) : wssi ? GetWebSocketPipeResource( wssi->wsPipe ) : NULL;
SOCKADDR *remoteAddress = ( pc ) ?(SOCKADDR *)GetNetworkLong( pc, GNL_REMOTE_ADDRESS ) : NULL;
SOCKADDR *localAddress = ( pc ) ? (SOCKADDR *)GetNetworkLong( pc, GNL_LOCAL_ADDRESS ): NULL;
Local<String> remote = String::NewFromUtf8( isolate, remoteAddress?GetAddrName( remoteAddress ):"0.0.0.0", v8::NewStringType::kNormal ).ToLocalChecked();
Local<String> local = String::NewFromUtf8( isolate, localAddress?GetAddrName( localAddress ):"0.0.0.0", v8::NewStringType::kNormal ).ToLocalChecked();
uint8_t mac[12];
TEXTCHAR macText[36];
size_t maclen = 12;
uint8_t macRemote[12];
TEXTCHAR macRemoteText[36];
size_t macRemoteLen = 12;
//lprintf( "Mac AAddress of socket:" );
//LogBinary( mac, maclen );
//LogBinary( macRemote, macRemoteLen );
// Local<String> localMac = String::NewFromUtf8( isolate, GetAddrName( remoteAddress ):"0.0.0.0", v8::NewStringType::kNormal ).ToLocalChecked();
Local<Object> result = Object::New( isolate );
Local<Object> arr = Object::New( isolate );
INDEX idx;
struct HttpField *header;
LIST_FORALL( headers, idx, struct HttpField *, header ) {
SETT( arr, header->name
, String::NewFromUtf8( isolate, (const char*)GetText( header->value ), NewStringType::kNormal, (int)GetTextSize( header->value ) ).ToLocalChecked() );
}
optionStrings *strings = getStrings( isolate );
SETV( result, strings->headerString->Get( isolate ), arr );
CTEXTSTR host = pc?ssl_GetRequestedHostName( pc ):NULL;
if( host )
SETV( result, strings->hostnameString->Get( isolate ), String::NewFromUtf8( isolate, host, v8::NewStringType::kNormal ).ToLocalChecked() );
else
SETV( result, strings->hostnameString->Get( isolate ), Null( isolate ) );
if( remoteAddress )
SETV( result, strings->remoteFamilyString->Get( isolate )
, (remoteAddress->sa_family == AF_INET) ? strings->v4String->Get( isolate ) :
(remoteAddress->sa_family == AF_INET6) ? strings->v6String->Get( isolate ) : strings->vUString->Get( isolate )
);
SETV( result, strings->remoteAddrString->Get( isolate ), remote );
SETV( result, strings->remotePortString->Get( isolate ), Integer::New( isolate, pc?(int32_t)GetNetworkLong( pc, GNL_PORT ):0 ) );
if( localAddress )
SETV( result, strings->localFamilyString->Get( isolate )
, (localAddress->sa_family == AF_INET)?strings->v4String->Get(isolate):
(localAddress->sa_family == AF_INET6) ? strings->v6String->Get( isolate ) : strings->vUString->Get(isolate)
);
SETV( result, strings->localAddrString->Get( isolate ), local );
SETV( result, strings->localPortString->Get( isolate ), Integer::New( isolate, pc?(int32_t)GetNetworkLong( pc, GNL_MYPORT ):0 ) );
if( pc && ( ( wss && wss->resolveAddr ) || ( wsc && wsc->resolveAddr ) || ( wssi && wssi->resolveAddr ) ) ) {
char tmp[NI_MAXHOST+1];
#define SOCKADDR_LENGTH(sa) ( (int)*(uintptr_t*)( ( (uintptr_t)(sa) ) - 2*sizeof(uintptr_t) ) )
if( remoteAddress ) {
getnameinfo( remoteAddress, SOCKADDR_LENGTH( remoteAddress ), tmp, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
SETV( result, strings->remoteNameString->Get(isolate), String::NewFromUtf8( isolate, tmp ).ToLocalChecked() );
}
if( localAddress ) {
getnameinfo( localAddress, SOCKADDR_LENGTH( localAddress ), tmp, NI_MAXHOST, NULL, 0, NI_NAMEREQD );
SETV( result, strings->localNameString->Get( isolate ), String::NewFromUtf8( isolate, tmp ).ToLocalChecked() );
}
}
if( pc && ( ( wss && wss->resolveMac ) || ( wsc && wsc->resolveMac ) || ( wssi && wssi->resolveMac ) ) ) {
if( !GetMacAddress( pc, mac, &maclen, macRemote, &macRemoteLen ) ) {
strcpy( macText, "00:00:00:00:00:00" );
strcpy( macRemoteText, "00:00:00:00:00:00" );
} else {
if( !maclen )
snprintf( macText, 36, "00:00:00:00:00:00" );
else
snprintf( macText, 36, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
if( !macRemoteLen )
snprintf( macRemoteText, 36, "00:00:00:00:00:00" );
else
snprintf( macRemoteText, 36, "%02x:%02x:%02x:%02x:%02x:%02x", macRemote[0], macRemote[1], macRemote[2], macRemote[3], macRemote[4], macRemote[5] );
}
SETV( result, strings->remoteMacString->Get( isolate ), String::NewFromUtf8( isolate, macRemoteText, v8::NewStringType::kNormal ).ToLocalChecked() );
SETV( result, strings->localMacString->Get( isolate ), String::NewFromUtf8( isolate, macText, v8::NewStringType::kNormal ).ToLocalChecked() );
}
// SETV( result, strings->localMacString->Get( isolate ), localMac );
return result;
}
static Local<Value> makeRequest( Isolate *isolate, struct optionStrings *strings, PCLIENT pc, int sslRedirect, wssObject *wss ) {
// .url
// .socket
Local<Context> context = isolate->GetCurrentContext();
Local<Object> req = Object::New( isolate );
Local<Object> socket;
struct HttpState *pHttpState = pc?GetWebSocketHttpState( pc ):wss?GetWebSocketPipeHttpState( wss->wsPipe ):NULL;
if( pHttpState ) {
struct cgiParams cgi;
PTEXT content;
cgi.isolate = isolate;
cgi.cgi = Object::New( isolate );
ProcessCGIFields( pHttpState, cgiParamSave, (uintptr_t)&cgi );
SETV( req, strings->redirectString->Get( isolate ), sslRedirect?True( isolate ):False(isolate) );
SETV( req, strings->CGIString->Get( isolate ), cgi.cgi );
SETV( req, strings->versionString->Get( isolate ), Integer::New( isolate, GetHttpVersion( pHttpState ) ) );
if (content = GetHttpContent(pHttpState))
SETV( req, strings->contentString->Get(isolate), String::NewFromUtf8(isolate, GetText(content), v8::NewStringType::kNormal).ToLocalChecked());
else
SETV( req, strings->contentString->Get(isolate), Null(isolate));
if (!GetText(GetHttpRequest(pHttpState))) {
//lprintf("lost request url");
return Null( isolate );
}
else
SETV( req, strings->urlString->Get(isolate)
, String::NewFromUtf8(isolate
, GetText(GetHttpRequest(pHttpState)),v8::NewStringType::kNormal).ToLocalChecked());
//ResetHttpContent(pc, pHttpState);
}
SETV( req, strings->connectionString->Get( isolate ), socket = makeSocket( isolate, pc, wss->wsPipe, wss, NULL, NULL ) );
SETV( req, strings->headerString->Get( isolate ), GETV( socket, strings->headerString->Get( isolate ) ) );
return req;
}
static void acceptResolved(const v8::FunctionCallbackInfo<Value>& args ) {
v8::Isolate* isolate = args.GetIsolate();
Local<Object> wssi = args.Data().As<Object>();
wssiObject *wssiInternal = wssiObject::Unwrap<wssiObject>( wssi );
struct wssEvent *eventMessage = wssiInternal->acceptEventMessage;
//lprintf( "Resolve called on promise...");
if( eventMessage ) {
wssiInternal->acceptEventMessage = NULL;
eventMessage->done = TRUE;
eventMessage->data.request.accepted = 1;
eventMessage->result = wssiInternal;
args.GetReturnValue().Set( wssiInternal->acceptPromise.Get(isolate) );
wssiInternal->acceptPromise.Reset();
if( eventMessage->waiter )
WakeThread( eventMessage->waiter );
}
}
static void acceptRejected(const v8::FunctionCallbackInfo<Value>& args ) {
v8::Isolate* isolate = args.GetIsolate();
Local<Object> wssi = args.Data().As<Object>();
wssiObject *wssiInternal = wssiObject::Unwrap<wssiObject>( wssi );
struct wssEvent *eventMessage = wssiInternal->acceptEventMessage;
//lprintf( "Reject called on promise...");
if( eventMessage ) { // this is released on post...
wssiInternal->acceptEventMessage = NULL;
eventMessage->done = TRUE;
eventMessage->data.request.accepted = 0;
args.GetReturnValue().Set( wssiInternal->acceptPromise.Get(isolate) );
wssiInternal->acceptPromise.Reset();
if( eventMessage->waiter )
WakeThread( eventMessage->waiter );
}
}
static void uv_closed_httpRequest( uv_handle_t* handle ) {
httpRequestObject* myself = (httpRequestObject*)handle->data;
myself->_this.Reset();
delete myself;
}
static void httpRequestAsyncMsg( uv_async_t* handle ) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
HandleScope scope( isolate );
httpRequestObject* myself = (httpRequestObject*)handle->data;
struct HTTPRequestOptions *opts = myself->opts;
Local<Context> context = isolate->GetCurrentContext();
{
struct httpRequestEvent* eventMessage;
while( eventMessage = (struct httpRequestEvent*)DequeLink( &myself->eventQueue ) ) {
Local<Value> argv[1];
Local<ArrayBuffer> ab;
switch( eventMessage->eventType ) {
case WS_EVENT_RESPONSE:
{
HTTPState state;
Local<Function> cb;
Local<Object> result; result = Object::New( isolate );
state = eventMessage->state;
{
HTTPRequestOptions* opts; opts = myself->opts;
char* header;
INDEX idx;
// cleanup what we allocated.
LIST_FORALL( opts->headers, idx, char*, header )
Release( header );
DeleteList( &opts->headers );
}
if( !state ) {
SET( result, "error",
state ? String::NewFromUtf8Literal( isolate, "No Content" ) : String::NewFromUtf8Literal( isolate, "Connect Error" ) );
cb = Local<Function>::New( isolate, myself->resultCallback );
argv[0] = result;
cb->Call( context, myself->_this.Get( isolate ), 1, argv );
//args.GetReturnValue().Set( result );
myself->_this.Reset();
myself->resultCallback.Reset();
break;
}
PTEXT content; content = GetHttpContent( state );
if( state && GetHttpResponseCode( state ) ) {
if( content ) {
SET( result, "content"
, String::NewFromUtf8( isolate, GetText( content ), v8::NewStringType::kNormal ).ToLocalChecked() );
}
SET( result, "statusCode"
, Integer::New( isolate, GetHttpResponseCode( state ) ) );
const char* textCode = GetHttpResponseStatus( state );
SET( result, "status"
, String::NewFromUtf8( isolate, textCode ? textCode : "NO RESPONSE", v8::NewStringType::kNormal ).ToLocalChecked() );
Local<Array> arr = Array::New( isolate );
PLIST headers = GetHttpHeaderFields( state );
INDEX idx;
struct HttpField* header;
//headers
LIST_FORALL( headers, idx, struct HttpField*, header ) {
SETT( arr, header->name
, String::NewFromUtf8( isolate, (const char*)GetText( header->value )
, NewStringType::kNormal, (int)GetTextSize( header->value ) ).ToLocalChecked() );
}
SET( result, "headers", arr );
DestroyHttpState( state );
} else {
SET( result, "error",
state ? String::NewFromUtf8Literal( isolate, "No Content" )
: String::NewFromUtf8Literal( isolate, "Connect Error" ) );
}
LineRelease( opts->url );
cb = Local<Function>::New( isolate, myself->resultCallback );
argv[0] = result;
cb->Call( context, Undefined(isolate), 1, argv );
Deallocate( HTTPRequestOptions*, myself->opts);
DeleteLinkQueue(&myself->eventQueue);
#ifdef DEBUG_EVENTS
lprintf( "Sack uv_close1 %p", &myself->async );
#endif
myself->_this.Reset();
myself->resultCallback.Reset();
uv_close( (uv_handle_t*)&myself->async, uv_closed_httpRequest );
DropHttpRequestEvent( eventMessage );
break;
}
}
}
}
}
static void wssiAsyncMsg( uv_async_t* handle ) {
// Called by UV in main thread after our worker thread calls uv_async_send()
// I.e. it's safe to callback to the CB we defined in node!
v8::Isolate* isolate = v8::Isolate::GetCurrent();
HandleScope scope( isolate );
wssiObject* myself = (wssiObject*)handle->data;
Local<Context> context = isolate->GetCurrentContext();
{
struct wssiEvent* eventMessage;
INDEX idx;
callbackFunction* callback;
while( eventMessage = ( struct wssiEvent* )DequeLink( &myself->eventQueue ) ) {
Local<Value> argv[2];
Local<ArrayBuffer> ab;
switch( eventMessage->eventType ) {
case WS_EVENT_OPEN:
if( !myself->thrown && !myself->server->openCallback.IsEmpty() ) {
Local<Function> cb = Local<Function>::New( isolate, myself->server->openCallback );
argv[0] = myself->_this.Get( isolate );
cb->Call( context, myself->_this.Get( isolate ), 1, argv );
}
break;
case WS_EVENT_READ:
LIST_FORALL( myself->messageCallbacks, idx, callbackFunction*, callback ) {
//if( !myself->messageCallback.IsEmpty() ) {
if( eventMessage->binary ) {
#if ( NODE_MAJOR_VERSION >= 14 )
std::shared_ptr<BackingStore> bs = ArrayBuffer::NewBackingStore( (POINTER)eventMessage->buf, eventMessage->buflen, releaseBufferBackingStore, NULL );
ab = ArrayBuffer::New( isolate, bs );
#else
ab =
ArrayBuffer::New( isolate
, (void*)eventMessage->buf
, eventMessage->buflen );
#endif
PARRAY_BUFFER_HOLDER holder = GetHolder();
holder->o.Reset( isolate, ab );
holder->o.SetWeak<ARRAY_BUFFER_HOLDER>( holder, releaseBuffer, WeakCallbackType::kParameter );
holder->buffer = eventMessage->buf;
argv[0] = ab;
callback->callback.Get( isolate )->Call( context, eventMessage->_this->_this.Get( isolate ), 1, argv );
// buf will deallocate when the arraybuffer does.