-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtotem.js
executable file
·3935 lines (3302 loc) · 100 KB
/
totem.js
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
// UNCLASSIFIED
/**
@class TOTEM
Provides basic web service as documented in README.md.
@requires http
@requires https
@requires fs
@requires constants
@requires cluster
@requires child-process
@requires os
@requires stream
@requires str
@requires enum
@requires jsdb
@requires mime
@requires socket.io
@requires socket.io-clusterhub
@requires mysql
@requires xml2js
@requires toobusy
@requires json2csv
@requires js2xmlparser
@requires toobusy-js
*/
var
// globals
ENV = process.env,
// NodeJS modules
STREAM = require("stream"), // pipe-able streams
HTTP = require("http"), //< http interface
HTTPS = require("https"), //< https interface
CP = require("child_process"), //< spawn OS shell commands
FS = require("fs"), //< access file system
CONS = require("constants"), //< constants for setting tcp sessions
CLUSTER = require("cluster"), //< multicore processing
URL = require("url"), //< url parsing
NET = require("net"), // network interface
VM = require("vm"), // virtual machines for tasking
OS = require('os'), // OS utilitites
// 3rd party modules
MIME = require("mime"), //< file mime types
SIO = require('socket.io'), //< Socket.io client mesh
SIOHUB = require('socket.io-clusterhub'), //< Socket.io client mesh for multicore app
MYSQL = require("mysql"), //< mysql conector
XML2JS = require("xml2js"), //< xml to json parser (*)
BUSY = require('toobusy-js'), //< denial-of-service protector (cant install on NodeJS 5.x+)
JS2XML = require('js2xmlparser'), //< JSON to XML parser
JS2CSV = require('json2csv'), //< JSON to CSV parser
// Totem modules
ENUM = require("enum"),
DB = require("jsdb"); //< DB database agnosticator
function Trace(msg,req,fwd) {
"totem".trace(msg,req,fwd);
}
const { Copy,Each,Log,isError,isArray,isString,isFunction,isEmpty,typeOf } = ENUM;
const { escape, escapeId } = MYSQL;
const { operators, reqFlags,paths,errors,site,probeSite,sqlThread,filterRecords,isEncrypted,guestProfile,
byArea,byType,byAction,byTable,timeIntervals } = TOTEM = module.exports = {
operators: ["=", "<", "<=", ">", ">=", "!=", "!bin=", "!exp=", "!nlp="],
/**
@cfg {Object}
@private
@member TOTEM
Error messages
*/
errors: {
pretty: err => {
return err+"";
},
badMethod: new Error("unsupported request method"),
noProtocol: new Error("no protocol specified to fetch"),
noRoute: new Error("no route"),
badQuery: new Error("invalid query"),
badGroup: new Error("invalid group requested"),
lostConnection: new Error("client connection lost"),
noDB: new Error("database unavailable"),
noProfile: new Error("user profile could not be determined"),
failedUser: new Error("failed modification of user profile"),
missingPass: new Error("missing initial user password"),
expiredCert: new Error("cert expired"),
rejectedClient: new Error("client rejected - bad cert, profile or session"),
tooBusy: new Error("too busy - try again later"),
noFile: new Error("file not found"),
noIndex: new Error("cannot index files here"),
badType: new Error("no such dataset type"),
badReturn: new Error("no data returned"),
noSockets: new Error("socket.io failed"),
noService: new Error("no service to start"),
noData: new Error("invalid dataset or query"),
retry: new Error("data fetch retries exceeded"),
notAllowed: new Error("this endpoint is disabled"),
noID: new Error("missing record id"),
noSession: new Error("no such session started"),
noAccess: new Error("no access to master core at this endpoint")
},
config: (opts,cb) => {
/**
@private
@method configService
@param {Object} opts configuration options following the ENUM.Copy() conventions.
@param {Function} cb callback(err) after service configured
Configure and start the service with options and optional callback when started.
Configure DB, define site context, then protect, connect, start and initialize this server.
*/
function protectService() {
/*
Create server's PKI certs (if needed), setup site context, connect, start then initializes.
*/
function connectService() {
/*
If the TOTEM server already connected, inherit the server; otherwise define a suitable
http/https interface ( if service encrypted/unencrypted), then start and initialize the service.
*/
function startService(server) {
/*
Attach port listener to server then start it.
*/
var
name = TOTEM.host.name,
mysql = paths.mysql;
Trace(`STARTING ${name}`);
TOTEM.server = server || { // define server
listen: function () {
Trace("NO SERVER");
},
on: function () {
Trace("NO SERVER");
}
};
if (server && name) // attach responder
server.on("request", (Req,Res) => { // start session
/*
Creates a HTTP/HTTPS request-repsonse session thread, then uses the byTable, byArea,
byType config to route this thread to the appropriate (req,res)-endpoint.
The newly formed request req contains:
.method: "GET, ... " // http method and its ...
.action: "select, ...", // corresponding crude name
.socketio: "path" // filepath to client's socketio.js
.where: {...}, // sql-ized query keys from url
.body: {...}, // body keys from request
.post: "..." // raw body text
.flags: {...}, // flag keys from url
.index: {...} // sql-ized index keys from url
.query: {...}, // raw keys from url
.files: [...] // files uploaded
.site: {...} // skinning context keys
.sql: connector // sql database connector (dummy if no mysql config)
.url : "url" // complete "/area/.../name.type?query" url
.search: "query" // query part
.path: "/..." // path part
.filearea: "area" // area part
.filename: "name" // name part
.type: "type" // type part
.connection: socket // http/https socket to retrieve client cert
The newly formed response res method accepts a string, an objects, an array, an error, or
a file-cache function to appropriately respond and close this thread and its sql connection.
The session is validated and logged, and the client is challenged as necessary.
@param {Object} Req http/https request
@param {Object} Res http/https response
*/
function startRequest( cb ) { //< callback cb() if not combating denial of service attacks
/**
@private
@method startRequest
@param {Function} callback() when completed
Start session and protect from denial of service attacks and, if unsuccessful then
terminaate request, otherise callback with request:
method = GET | PUT | POST | DELETE
action = select | update | insert | delete
sql = sql connector
reqSocket = socket to complete request
resSocket = socket to complete response
socketio: path to client's socketio
url = clean url
*/
function getSocket() { // returns suitable response socket depending on cross/same domain session
if ( Req.headers.origin ) { // cross domain session is in progress from master (on http) to its workers (on https)
Res.writeHead(200, {"content-type": "text/plain", "access-control-allow-origin": "*"});
Res.socket.write(Res._header);
Res._headerSent = true;
return Res.socket;
}
else // same domain (http-to-http or https-to-https) so must use the request socket
return Req.socket;
}
function getPost( cb ) { // Feed raw post to callback
var post = "";
Req
.on("data", function (chunk) {
post += chunk.toString();
})
.on("end", function () {
cb( post );
});
}
var
isBusy = BUSY ? BUSY() : false;
if ( isBusy )
return Res.end( errors.pretty( errors.toobusy ) );
else
switch ( Req.method ) {
case "PUT":
case "GET":
case "POST":
case "DELETE":
getPost( post => {
sqlThread( sql => {
cb({ // prime session request
sql: sql, // sql connector
post: post, // raw post body
method: Req.method, // get,put, etc
started: Req.headers.Date, // time client started request
action: TOTEM.crud[Req.method],
reqSocket: Req.socket, // use supplied request socket
resSocket: getSocket, // use this method to return a response socket
encrypted: isEncrypted(), // on encrypted worker
socketio: site.urls.socketio, // path to socket.io
url: unescape( Req.url.substr(1) || paths.nourl )
/*
There exists an edge case wherein an html tag within json content, e.g a <img src="/ABC">
embeded in a json string, is reflected back the server as a /%5c%22ABC%5c%22, which
unescapes to /\\"ABC\\". This is ok but can be confusing.
*/
});
});
});
break;
case "OPTIONS": // client making cross-domain call - must respond with what are valid methods
//Req.method = Req.headers["access-control-request-method"];
Res.writeHead(200, {
"access-control-allow-origin": "*",
"access-control-allow-methods": "POST, GET, DELETE, PUT, OPTIONS"
});
Res.end();
/*res.header = function () {
Res.writeHead(200);
Res.socket.write(Res._header);
Res.socket.write(Res._header);
Res._headerSent = true;
}; */
break;
default:
Res.end( errors.pretty(errors.badMethod) );
}
}
startRequest( req => { // start request if not busy.
function startResponse( cb ) {
/**
@private
@method startResponse
Start a session by attaching sql, cert, client, profile and session info to this request req with callback res(error).
@param {Object} req request
@param {Function} res response
* */
function res(data) { // Session response callback
// Session terminators respond with a string, file, db structure, or error message.
function sendString( data ) { // Send string - terminate sql connection
Res.end( data );
}
function sendFile(path,file,type,area) { // Cache and send file to client - terminate sql connection
// Trace(`SENDING ${path}`);
var
cache = TOTEM.cache,
never = cache.never,
cache = (never[file] || never[type]) ? {} : cache[area] || cache[type] || {};
//Log(path, cache[path] ? "cached" : "!cached");
if ( buf = cache[path] )
sendString( buf );
else
FS.readFile( path, (err,buf) => {
if (err)
sendError( errors.noFile );
else
sendString( cache[path] = new Buffer(buf) );
});
}
function sendError(err) { // Send pretty error message - terminate sql connection
switch ( req.type ) {
case "html":
case "db":
Res.end( errors.pretty(err) );
break;
default:
Res.end( err+"" );
}
}
function sendObject(obj) {
try {
sendString( JSON.stringify(obj) );
}
catch (err) { // infinite cycle
sendError( errors.badReturn );
}
}
function sendRecords(recs) { // Send records via converter
if ( route = filterRecords[req.type] ) // process record conversions
route(recs, req, recs => {
if (recs)
switch ( typeOf(recs) ) {
case "Error":
sendError( recs );
break;
case "String":
sendString( recs );
break;
case "Array":
case "Object":
default:
sendObject( recs );
}
else
sendError( errors.badReturn );
});
else
sendObject( recs );
}
var
req = Req.req,
sql = req.sql,
mimes = MIME.types,
mime = mimes[ isError(data||0) ? "html" : req.type ] || mimes.html;
// set appropriate headers to prevent http-parse errors when using master-worker proxy
if ( req.encrypted )
Res.setHeader("Set-Cookie", ["client="+req.client, "service="+TOTEM.host.name] );
Res.setHeader("Content-Type", mime);
/*
Res.setHeader("Access-Control-Allow-Origin", "*");
Res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Res.setHeader("Access-Control-Allow-Headers", '*');
Res.setHeader("Status", "200 OK");
Res.setHeader("Vary", "Accept");
//self.send_header('Content-Type', 'application/octet-stream')
*/
Res.statusCode = 200;
if (data != null)
switch ( typeOf(data) ) { // send based on its type
case "Error": // send error message
sendError( data );
break;
case "Function": // send file (search or direct)
sendFile( data(), req.file, req.type, req.area );
/*
if ( (search = req.query.search) && paths.mysql.search) // search for file via (e.g. nlp) score
sql.query(paths.mysql.search, {FullSearch:search}, (err, files) => {
if (err)
sendError( errors.noFile );
else
sendError( errors.noFile ); // reserved functionality
});
else {
if ( credit = paths.mysql.credit) // credit/charge client when file pulled from file system
sql.query( credit, {Name:req.node,Area:req.area} )
.on("result", file => {
if (file.Client != req.client)
sql.query("UPDATE openv.profiles SET Credit=Credit+1 WHERE ?",{Client: file.Client});
});
sendFile( data(), req.file, req.type, req.area );
} */
break;
case "Array": // send data records
sendRecords(data);
break;
case "String": // send message
case "Buffer":
sendString(data);
break;
case "Object":
default: // send data record
sendObject(data);
break;
}
else
sendError( errors.noData );
}
if (sock = req.reqSocket ) // have a valid request socket so ....
validateClient(req, err => {
if (err)
res(err);
else
if ( getSession = paths.mysql.getSession )
req.sql.query(getSession, {Client: req.client}, (err,ses) => {
if ( err )
res(err);
else {
req.session = new Object( ses[0] || {
Client: "guest@guest.org",
Connects: 1,
//ipAddress : "unknown",
Location: "unknown",
Joined: new Date()
});
cb( res );
}
});
else { // using dummy sessions
req.session = {};
cb( res );
}
});
else // lost reqest socket for some reason so ...
res( errors.lostConnection );
}
Req.req = req;
startResponse( res => { // start response if session validated.
function routeNode(node, req, cb) {
/**
@private
@method routeNode
Parse the node=/dataset.type on the current req thread, then route using byArea, byType, byTable,
byActionTable, or byAction routers.
@param {OFbject} req Totem session request
@param {Function} res Totem response callback
*/
function parseNode() {
/**
@private
@method parseNode
Parse node request req.node = /TABLE?QUERY&INDEX || /FILEAREA/FILENAME to define
the req .table, .path, .filearea, .filename, .type and the req .query, .index, .joins and .flags.
@param {Object} req Totem session request
*/
var
query = req.query = {},
index = req.index = {},
where = req.where = {},
flags = req.flags = {},
path = req.path = "./" + node.parseURL(query, index, flags, where), // .[/area1/area2/...]/table.type
areas = path.split("/"), // [".", area1, area2, ...]
file = req.file = areas.pop() || "", // table.type
[x,table,type] = [x,req.table,req.type] = file.match( /(.*)\.(.*)/ ) || ["", file, ""],
area = req.area = areas[1] || "",
body = req.body;
req.site = site;
const { strips, prefix, traps, id } = reqFlags;
for (var key in query) // strip or remap bogus keys
if ( key in strips )
delete query[key];
for (var key in flags) // trap special flags
if ( trap = traps[key] )
trap(req);
for (var key in body) // remap body flags
if ( key.startsWith(prefix) ) {
flags[key.substr(1)] = body[key]+"";
delete body[key];
}
if (id in body) { // remap body record id
where["="][id] = query[id] = body[id]+"";
delete body[id];
}
}
function sendFile(req,res) {
res( function () {return req.path; } );
}
function followRoute(route) {
/**
@private
@method followRoute
Log session metrics, trace the current route, then callback route on the supplied
request-response thread
@param {Function} route method endpoint to process session
@param {Object} req Totem session request
@param {Function} res Totem response callback
*/
function logMetrics( logAccess, log, sock) { //< log session metrics
sock._started = new Date();
/*
If maxlisteners is not set to infinity=0, the connection becomes sensitive to a sql
connector t/o and there will be random memory leak warnings.
*/
sock.setMaxListeners(0);
sock.on('close', function () { // cb when connection closed
var
secs = sock._started ? ((new Date()).getTime() - sock._started.getTime()) / 1000 : 0,
bytes = sock.bytesWritten;
sqlThread( sql => {
sql.query(logAccess, [ Copy(log, {
Delay: secs,
Transfer: bytes,
Event: sock._started,
Dataset: "",
Client: req.client,
Actions: 1
}), bytes, secs, log.Event ], err => Log("dblog", err) );
});
});
}
//Log("log check", req.area, req.reqSocket?true:false, req.log );
if ( !req.area ) // log if file not being specified
if ( sock = req.reqSocket ) // log if http has a request socket
if ( log = req.log ) // log if session logged
if ( logAccess = paths.mysql.logMetrics ) // log if logging enabled
logMetrics( logAccess, log, sock );
Trace( ( route.name || ("db"+req.action)).toUpperCase() + ` ${req.file}` );
route(req, recs => { // route request and capture records
var call = null;
if ( recs )
for ( var key in req.flags ) if ( !call ) { // perform once-only data restructing conversion
if ( key.startsWith("$") ) key = "$";
if ( call = reqFlags[key] ) {
call( recs, req, recs => cb(req, recs) );
break;
}
}
if ( !call )
cb(req,recs);
});
}
parseNode();
const { sql, path, area, table, type, action } = req;
// Log([action,path,area,table,type]);
if ( area ) {
if ( area == "socket.io" && !table ) // ignore socket keep-alives
res( "hush" );
else
if ( route = byArea[area] ) // send uncached, static file
followRoute( route );
else // send cashed file
followRoute( sendFile );
}
else
if ( route = byType[type] ) // route by type
followRoute( route );
else
if ( route = byTable[table] ) // route by endpoint name
followRoute( route );
else
if ( route = byAction[action] ) { // route by crud action
if ( route = route[table] )
followRoute( route );
else
if ( route = TOTEM[action] )
followRoute( route );
else
cb( req, errors.noRoute);
}
else
if ( route = TOTEM[action] ) // route to database
followRoute( route );
else
cb( req, errors.noRoute );
}
req.body = req.post.parseJSON( post => { // get parameters or yank files from body
var files = [], parms = {}, file = "", rem,filename,name,type;
if (post)
post.split("\r\n").forEach( (line,idx) => {
if ( idx % 2 )
files.push({
filename: filename.replace(/'/g,""),
name: name,
data: line,
type: type,
size: line.length
});
else
[rem,filename,name,type] = line.match( /<; filename=(.*) name=(.*) ><\/;>type=(.*)/ ) || [];
/*
if (parms.type) { // type was defined so have the file data
files.push( Copy(parms,{data: line, size: line.length}) );
parms = {};
}
else {
//Trace("LOAD "+line);
line.split(";").forEach( (arg,idx) => { // process one file at a time
Log("line ",idx,line.length);
var tok = arg
.replace("Content-Disposition: ","disposition=")
.replace("Content-Type: ","type=")
.split("="),
val = tok.pop(),
key = tok.pop();
if (key)
parms[key.replace(/ /g,"")] = val.replace(/"/g,"");
});
}
*/
});
//Log("body files=", files.length);
return {files: files};
}); // get body parameters/files
var
nodes = req.url.split(TOTEM.nodeDivider);
if ( !nodes.length )
res( null );
else
if (nodes.length == 1) // route just this node
routeNode( nodes[0], req, (req,recs) => {
// Log("exit route node", typeOf(recs), typeOf(recs[0]) );
res(recs);
});
else { // serialize nodes
var
routes = nodes.length,
routed = 0,
rtns = {};
nodes.forEach( node => { // enumerate nodes
if ( node )
routeNode( node, Copy(req,{}), (req,recs) => { // route the node and capture returned records
rtns[req.table] = recs;
if ( ++routed == routes ) res( rtns );
});
});
}
});
});
});
else
return cb( errors.noService );
if ( site.urls.socketio) { // attach socket.io and setup connection listeners
var
IO = TOTEM.IO = new SIO(server, { // use defaults but can override ...
//serveClient: true, // default true to prevent server from intercepting path
//path: "/socket.io" // default get-url that the client-side connect issues on calling io()
}),
HUBIO = TOTEM.HUBIO = new (SIOHUB); //< Hub fixes socket.io+cluster bug
if (IO) { // Setup client web-socket support
Trace("SOCKETS AT "+IO.path());
TOTEM.emitter = IO.sockets.emit;
IO.on("connect", socket => { // Trap every connect
//Trace("ALLOW SOCKETS");
socket.on("select", req => { // Trap connect raised on client "select/join request"
Trace(`CONNECTING ${req.client}`);
sqlThread( sql => {
if (newSession = mysql.newSession)
sql.query(newSession, {
Client : req.client,
Connects: 1,
Location: "unknown", //req.location,
//ipAddress: req.ip,
Joined: new Date(),
Message: req.message
});
if (challenge = mysql.challenge)
sql.query(challenge, {Client:req.client}).on("results", profile => {
if ( profile.Challenge)
challengeClient(sql, req.client, profile);
});
});
});
});
/*
IO.on("connect_error", err => {
Log(err);
});
IO.on("disconnection", socket => {
Log(">>DISCONNECT CLIENT");
}); */
}
else
return TOTEM.initialize( errors.noSockets );
}
// The BUSY interface provides a means to limit client connections that would lock the
// service (down deep in the tcp/icmp layer). Busy thus helps to thwart denial of
// service attacks. (Alas latest versions do not compile in latest NodeJS.)
if (BUSY && TOTEM.busyTime)
BUSY.maxLag(TOTEM.busyTime);
if (TOTEM.cores) // Using multiple cores
if (CLUSTER.isMaster) { // Listen on master port
server.listen( parseInt(TOTEM.domain.master.port), () => {
Trace("MASTER LISTENING");
});
CLUSTER.on('exit', (worker, code, signal)=> {
Trace(`CORE${worker.id} TERMINATED ${code||"ok"}`);
});
CLUSTER.on('online', worker => {
Trace(`CORE${worker.id} CONNECTED`);
});
for (var core = 0; core < TOTEM.cores; core++) // create the worker cores
worker = CLUSTER.fork();
}
else // Listen on worker port
server.listen( TOTEM.domain.worker.port , () => {
Trace(`CORE${CLUSTER.worker.id} AT ${site.urls.worker}`);
});
else // Using only a single core
server.listen( TOTEM.domain.master.port, () => {
Trace("MASTER LISTENING");
});
if ( TOTEM.faultless) { // catch core faults
process.on("uncaughtException", err => {
Trace(`FAULTED ${err}`);
});
process.on("exit", function (code) {
Trace(`HALTED ${code}`);
});
for (var signal in TOTEM.guards)
process.on(signal, function () {
Trace(`SIGNALED ${signal}`);
});
}
if (TOTEM.riddles) initChallenger();
if (CLUSTER.isMaster) // initialize service
sqlThread( sql => { // get a sql connection
Trace( [ // splash
"HOSTING " + site.nick,
"AT "+`(${site.urls.master}, ${site.urls.worker})`,
"DATABASE " + site.db ,
"FROM " + process.cwd(),
"WITH " + (site.urls.socketio||"NO")+" SOCKETS",
"WITH " + (TOTEM.faultless?"GUARDED":"UNGUARDED")+" THREADS",
"WITH "+ (TOTEM.riddles?"ANTIBOT":"NO ANTIBOT") + " PROTECTION",
"WITH " + (site.sessions||"UNLIMITED")+" CONNECTIONS",
"WITH " + (TOTEM.cores ? TOTEM.cores + " WORKERS AT "+site.urls.worker : "NO WORKERS")
].join("\n- ") );
// initialize file watcher
sql.query("UPDATE app.files SET State='watching' WHERE Area='uploads' AND State IS NULL");
var mTimes = TOTEM.mTimes;
Each(TOTEM.onFile, (area, cb) => { // callback cb(sql,name,area) when file changed
FS.readdir( area, (err, files) => {
if (err)
Log(err);
else
files.forEach( file => {
if ( !file.startsWith(".") && !file.startsWith("_") )
TOTEM.watchFile( area+file, cb );
});
});
});
// start watch dogs
Each( TOTEM.dogs, (key, dog) => {
if ( dog.cycle ) { // attach sql threaders and setup watchdog interval
//Trace("DOGING "+key);
dog.trace = dog.name.toUpperCase();
dog.forEach = DB.forEach;
dog.forAll = DB.forAll;
dog.forFirst = DB.forFirst;
dog.thread = sqlThread;
dog.site = site;
setInterval( args => {
//Trace("DOG "+args.name);
dog(dog); // feed dog attributes as parameters
}, timeIntervals[dog.cycle] || dog.cycle*1e3, {
name: key
});
}
});
TOTEM.initialize();
if (cb) cb( null );
});
}
var
host = TOTEM.host,
name = host.name,
certs = TOTEM.cache.certs,
trustStore = TOTEM.trustStore,
cert = certs.totem = { // totem service certs
pfx: FS.readFileSync(`${paths.certs}${name}.pfx`),
key: FS.readFileSync(`${paths.certs}${name}.key`),
crt: FS.readFileSync(`${paths.certs}${name}.crt`)
};
certs.fetch = { // data fetching certs
pfx: FS.readFileSync(`${paths.certs}fetch.pfx`),
key: FS.readFileSync(`${paths.certs}fetch.key`),
crt: FS.readFileSync(`${paths.certs}fetch.crt`),
ca: "", //FS.readFileSync(`${paths.certs}fetch.ca`),
_pfx: `${paths.certs}fetch.pfx`,
_crt: `${paths.certs}fetch.crt`,
_key: `${paths.certs}fetch.key`,
_ca: `${paths.certs}fetch.ca`,
_pass: ENV.FETCH_PASS
};
//Log( TOTEM.isEncrypted, CLUSTER.isMaster, CLUSTER.isWorker );
if ( isEncrypted() ) { // have encrypted services so start https service
try { // build the trust strore
Each( FS.readdirSync(paths.certs+"/truststore"), (n,file) => {
if (file.indexOf(".crt") >= 0 || file.indexOf(".cer") >= 0) {
Trace("TRUSTING "+file);
trustStore.push( FS.readFileSync( `${paths.certs}truststore/${file}`, "utf-8") );
}
});
}
catch (err) {
}
startService( HTTPS.createServer({
passphrase: host.encrypt, // passphrase for pfx
pfx: cert.pfx, // pfx/p12 encoded crt and key
ca: trustStore, // list of pki authorities (trusted serrver.trust)
crl: [], // pki revocation list
requestCert: true,
rejectUnauthorized: true
//secureProtocol: CONS.SSL_OP_NO_TLSv1_2
}) );
}
else // unencrpted services so start http service
startService( HTTP.createServer() );
}
var
host = TOTEM.host,
name = host.name,
urls = site.urls = TOTEM.cores
? {
socketio: TOTEM.sockets ? paths.url.socketio : "",
worker: host.worker,
master: host.master
}
: {
socketio: TOTEM.sockets ? paths.url.socketio : "",
worker: host.master,
master: host.master
},
pfx = `${paths.certs}${name}.pfx` ;
Trace( `PROTECTING ${name} USING ${pfx}` );
TOTEM.domain = {
master: URL.parse(urls.master),
worker: URL.parse(urls.worker)
};
if ( isEncrypted() ) // get a pfx cert if protecting an encrypted service
FS.access( pfx, FS.F_OK, err => {
if (err) // create the pfx cert then connect
createCert(name,host.encrypt, () => {
connectService();
});
else // got the pfx so connect
connectService();
});
else
connectService();
}
if (opts) Copy(opts, TOTEM, ".");
var
name = TOTEM.host.name;
Trace(`CONFIGURING ${name}`);
TOTEM.started = new Date();
//Copy(paths.mime.extensions, MIME.types);
Each( paths.mime.extensions, (key,val) => {