forked from ericmandel/js9
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs9Helper.js
1601 lines (1537 loc) · 47.5 KB
/
js9Helper.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
/*
*
* js9Helper: Node-based back-end server for JS9 (September 4, 2012)
*
* Principals: Eric Mandel
* Organization: Center for Astrophysics | Harvard & Smithsonian, Cambridge MA
* Contact: [email protected]
*
* Copyright (c) 2012 - 2024 Smithsonian Astrophysical Observatory
*
*
*/
/* global */
"use strict";
// load required modules
const http = require('http'),
server = require('socket.io'),
os = require('os'),
path = require('path'),
https = require('https'),
url = require('url'),
qs = require('querystring'),
cproc = require("child_process"),
fs = require("fs"),
{ v4: uuidv4 } = require('uuid'),
rmdir = require('rimraf');
// internal variables
let i, app, io, secure;
let fits2fits = {};
let quotacheck = {};
let analysis = {str:[], pkgs:[]};
let plugins = [];
const installDir = __dirname;
const currentDir = process.cwd();
const myProg = process.argv[0].split("/").reverse()[0];
const myArgs = process.argv.slice(2);
const prefsfile = path.join(installDir, "js9Prefs.json");
const securefile = path.join(installDir, "js9Secure.json");
const js9Queue = {};
const rmQueue = {};
const merges = {};
// secure options ... change as necessary in securefile
const secureOpts = {
// key: "path_to_private.key", // openssl genrsa -out file 2014
// cert: "path_to_certificate_file", // from the certificate authority
// ca: "path_to_certificate_authority" // can be a chain file
};
// default options ... change as necessary in prefsfile
const globalOpts = {
helperPort: 2718,
// listen on all interfaces
helperHost: "0.0.0.0",
// we need a large buffer for returning arbitrary analysis results
// default ping timeout is too short, and Chrome gets disconnect errors
// v2 requires cors to be set explicitly
// allowEIO3 support socketio v2
socketioOpts: {maxHttpBufferSize: 10E9,
pingInterval: 20000,
pingTimeout: 30000,
cors:{origin: true},
allowEIO3: true},
cmd: "js9helper",
analysisPlugins: "analysis-plugins",
analysisWrappers: "analysis-wrappers",
restrictWrappers: true,
helperPlugins: "helper-plugins",
dataPathModify: true,
fileTranslate: [], // file translation, e.g. ["/notebooks/",""]
maxBinaryBuffer: 150*1024000, // exec buffer: good for 4096^2 64-bit image
maxTextBuffer: 5*1024000, // exec buffer: good for text
textEncoding: "ascii", // encoding for returned stdout from exec
rmWorkDir: true, // remove workdir on disconnect?
rmWorkDelay: 15000, // delay before removing workdir
remoteMsgs: 1, // -1 => pageid only, 0 => local only,
// 1 => same, 2 => local->all 3 => all->all
remoteMsgsHeader: "x-forwarded-for"
};
// globalOpts that might need to have paths relative to __dirname
const globalRelatives = ["analysisPlugins",
"analysisWrappers",
"helperPlugins"];
//
// routines that might depend on specific implementations of socket.io
//
// get ip address and port of the current socket or http connection
const getHost = function(req){
let key = globalOpts.remoteMsgsHeader;
// socket.io
if( req.handshake ){
if( key && req.handshake.headers && req.handshake.headers[key] ){
return req.handshake.headers[key].split(',')[0];
} else {
return req.client.conn.remoteAddress;
}
}
// http server
// http://stackoverflow.com/questions/19266329/node-js-get-clients-ip
if( key && req.headers && req.headers[key] ){
return req.headers[key].split(',')[0];
} else {
return req.connection.remoteAddress;
}
};
// http://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients
// v3 update: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/#API-change
// is it v2 or v3? emperically, for v3 the connected property is undefined
const getClients = function(){
let id;
const res = [];
// check for conected targets connected (default: using v2 or v3)
const v2 = io.of("/").connected;
const v3 = io.of("/").sockets;
if( typeof v2 === "object" ){
// v2 protocol
for( id of Object.keys(v2) ){
if( !v2[id].js9worker ){
res.push(v2[id]);
}
}
} else if( typeof v3 === "object" ){
// v3 protocol
v3.forEach((value) => {
if( !value.js9worker ){
res.push(value);
}
})
}
return res;
};
// utilities
// create a nice date/time string for logging
const datestr = function(){
return new Date().toLocaleString(undefined, {hour12: false});
};
// output a log message on the console
const clog = function(){
const args = Array.prototype.slice.call(arguments, 0);
args.push(` [${datestr()}]`);
// eslint-disable-next-line no-console
console.log.apply(null, args);
};
// output string to log file
// eslint-disable-next-line no-unused-vars
const flog = function(s){
const buffer = new Buffer(`${s}\n`);
fs.open('tmp/js9node.log', 'a', (err, fd) => {
if( fd ){
fs.write(fd, buffer, 0, buffer.length, null,
// eslint-disable-next-line no-unused-vars
(err, written, bytes) => { fs.closeSync(fd); });
}
});
};
// output an error message on the console
const cerr = function(){
const args = Array.prototype.slice.call(arguments, 0);
args.unshift("ERROR: ");
args.push(` [${datestr()}]`);
// eslint-disable-next-line no-console
console.log.apply(null, args);
};
// getTargets: identify target(s) for an external msg for a given ip
// returns: array of validated targets
const getTargets = function(socket, msg){
let i, j, c, clip, displays;
const browserip = msg.browserip || "*";
const targets = [];
// ip associated with this socket
const myip = getHost(socket);
// list of all clients connected on this socket
const clients = getClients();
// authentication function
const authenticate = (myip, clip, mypageid, cpageid) => {
// pageid only: for when host ip is mangled (e.g. JupyterLab)
// (obviously, a page id must be passed or else authentication fails)
if( globalOpts.remoteMsgs === -1 ){
if( mypageid && mypageid === cpageid ){
return true;
}
return false;
}
// localhost to localhost is allowed
if( ((myip === "127.0.0.1") ||
(myip === "::ffff:127.0.0.1") ||
(myip === "::1")) &&
((clip === "127.0.0.1") ||
(clip === "::ffff:127.0.0.1") ||
(clip === "::1")) &&
(globalOpts.remoteMsgs >= 0) ){
return true;
}
// I can send to myself, if we configured that way
if( (myip === clip) &&
(globalOpts.remoteMsgs >= 1) ){
return true;
}
// allow localhost to send to everyone else
if( ((myip === "127.0.0.1") ||
(myip === "::ffff:127.0.0.1") ||
(myip === "::1")) &&
globalOpts.remoteMsgs >= 2 ){
return true;
}
// security risk: anyone can send to anyone
if( globalOpts.remoteMsgs >= 3 ){
return true;
}
// can't send to anyone
return false;
};
// look at all clients
for(i=0; i<clients.length; i++){
// current client
c = clients[i];
// sanity check
if( !c.js9 ){
continue;
}
// client ip
clip = getHost(c);
// authentication
if( !authenticate(myip, clip, msg.pageid, c.js9.pageid) ){
continue;
}
// look for matching clients
// pageid is a unique id associated with a specific page
if( msg.pageid ){
if( msg.pageid === c.js9.pageid ){
targets.push(c);
}
} else if( ((browserip === "*") || (browserip === clip)) ){
// look for matches in display id
displays = c.js9.displays;
for(j=0; j<displays.length; j++){
// look for matching display
if( msg.id === displays[j] ){
targets.push(c);
}
}
}
}
return targets;
};
// connectWorker: identify main socket for this worker
const connectWorker = function(socket, pageid){
let i, c, clip;
// ip associated with this socket
const myip = getHost(socket);
// list of all clients connected on this socket
const clients = getClients();
// sanity check
if( !pageid ){
return null;
}
// look at all clients
for(i=0; i<clients.length; i++){
// current client
c = clients[i];
// check for client with same pageid
if( c.js9 && (c.js9.pageid === pageid) ){
// get client ip
clip = getHost(c);
// ip of worker and client must match!
if( myip === clip ){
return c;
}
}
}
return null;
};
// envClean: clean incoming environment variables
// this should match cleaning in js9Helper.cgi
const envClean = function(s) {
if( typeof s === "string" ){
return s.replace(/[`&]/g, "").replace(/\(\)\s*\{.*/g, "");
}
return s;
};
const loadSecurePreferences = function(securefile){
let s, obj, opt;
let secure = false;
if( fs.existsSync(securefile) ){
s = fs.readFileSync(securefile, "utf-8");
if( s ){
try{ obj = JSON.parse(s.toString()); }
catch(e){ cerr("can't parse: ", securefile, e); }
// merge opts into secureOpts
for( opt of Object.keys(obj) ){
switch(opt){
case "key":
secureOpts.key = fs.readFileSync(obj[opt]);
break;
case "cert":
secureOpts.cert = fs.readFileSync(obj[opt]);
break;
case "ca":
secureOpts.ca = fs.readFileSync(obj[opt]);
break;
default:
cerr("unknown secure option: ", opt);
break;
}
}
// if we have a prefs file, we need to have defined required props
if( secureOpts.key && secureOpts.cert ){
secure = true;
} else {
cerr("missing one or more required secure properties");
}
}
}
return secure;
};
// load preference file, if possible
const loadPreferences = function(prefs){
let s, obj, opt, otype, jtype;
if( fs.existsSync(prefs) ){
s = fs.readFileSync(prefs, "utf-8");
} else if( typeof prefs === "string" ){
s = `{"globalOpts": ${prefs}}`;
}
if( s ){
try{ obj = JSON.parse(s.toString()); }
catch(e){ cerr("can't parse: ", prefsfile, e); }
// look for globalOpts object and merge
if( obj && typeof obj.globalOpts === "object" ){
for( opt of Object.keys(obj.globalOpts) ){
otype = typeof obj.globalOpts[opt];
jtype = typeof globalOpts[opt];
if( (jtype === otype) || (jtype === "undefined") ){
switch(otype){
case "number":
globalOpts[opt] = obj.globalOpts[opt];
break;
case "boolean":
globalOpts[opt] = obj.globalOpts[opt];
break;
case "string":
globalOpts[opt] = obj.globalOpts[opt];
break;
case "object":
if( jtype === "undefined" ){
globalOpts[opt] = obj.globalOpts[opt];
} else {
Object.assign(globalOpts[opt], obj.globalOpts[opt]);
}
break;
default:
break;
}
}
}
}
// some directories should be relative to __dirname
globalRelatives.forEach((s) => {
const file = globalOpts[s];
if( file && !path.isAbsolute(file) ){
globalOpts[s] = path.join(installDir, file);
}
});
// initialize the wrapper path, if necessary
if( !globalOpts.analysisWrapPath){
globalOpts.analysisWrapPath = globalOpts.analysisWrappers;
}
// use system tmp directory for workDir, if necessary
if( globalOpts.workDir === "$tmp" ){
globalOpts.workDir = os.tmpdir();
}
}
};
// load analysis plugin files, if available
const loadAnalysisTasks = function(dir, todir){
if( fs.existsSync(dir) ){
fs.readdir(dir, (err, files) => {
let i, j, a, arr, jstr, pathname;
for(i=0; i<files.length; i++){
pathname = `${dir}/${files[i]}`;
if( fs.existsSync(pathname) ){
// only json files ... also avoid Mac OSX xattr files
if( !pathname.match(/.json$/) || files[i].match(/\._/) ){
continue;
}
analysis.temp = fs.readFileSync(pathname, "utf-8");
if( analysis.temp ){
jstr = analysis.temp.toString().trim();
switch(files[i]){
case "fits2fits.json":
try{ fits2fits = JSON.parse(jstr); }
catch(e1){cerr("can't parse: ", pathname, e1);}
break;
case "quotacheck.json":
try{ quotacheck = JSON.parse(jstr); }
catch(e1){cerr("can't parse: ", pathname, e1);}
break;
default:
try{
arr = JSON.parse(jstr);
// todir defined => prepend it to paths
if( todir && arr ){
for(j=0; j<arr.length; j++){
a = arr[j];
if( a.purl ){
a.purl = `${todir}/${a.purl}`;
}
}
analysis.pkgs.push(arr);
analysis.str.push(JSON.stringify(arr));
} else {
analysis.pkgs.push(arr);
analysis.str.push(jstr);
}
}
catch(e2){cerr("can't parse: ", pathname, e2);}
break;
}
}
}
}
});
}
};
// addAnalysisTask: add to the list of analysis tasks sent to browser
const addAnalysisTask = function(obj) {
analysis.pkgs.push(obj);
analysis.str.push(`[${JSON.stringify(obj)}]`);
};
// load user-defined plugins, if possible
const loadHelperPlugins = function(dir){
if( fs.existsSync(dir) ){
fs.readdir(dir, (err, files) => {
let i, x, pathname, name;
for(i=0; i<files.length; i++){
pathname = `${dir}/${files[i]}`;
if( fs.existsSync(pathname) ){
// only js files, please
if( !pathname.match(/.js$/) ){
continue;
}
// name of message
name = files[i].replace(/.js$/, "");
try{ x = require(pathname); }
catch(e){ cerr("warning: can't load: ", pathname); }
if( x ){
plugins.push({name: name,
sockio: x.sockio,
http: x.http,
httpList: x.httpList});
}
}
}
});
}
};
// merge a directory containing analysis tasks, etc.
const mergeDirectory = function(dir){
let s, stat, mergeTo;
// only merge once
if( merges[dir] ){ return "OK"; }
// look for directory info
try{ stat = fs.statSync(dir); } catch(e){ stat = null; }
if( !stat || !stat.isDirectory() ){
s = `ERROR: invalid merge directory: ${dir||"<none>"}`;
clog(s);
return s;
}
// how to get from merge dir to install dir
mergeTo = path.relative(__dirname, dir);
// process entries in the merge directory
try{ fs.readdir(dir, (err, files) => {
let d, i, file, stat;
for(i=0; i<files.length; i++){
file = files[i];
d = `${dir}/${file}`;
switch(file){
case "analysis-wrappers":
try{ stat = fs.statSync(d); } catch(e){ stat = null; }
if( stat && stat.isDirectory() ){
globalOpts.analysisWrapPath += `:${d}`;
}
break;
case "analysis-plugins":
try{ stat = fs.statSync(d); } catch(e){ stat = null; }
if( stat && stat.isDirectory() ){
loadAnalysisTasks(d, mergeTo);
}
break;
case "bin":
try{ stat = fs.statSync(d); } catch(e){ stat = null; }
if( stat && stat.isDirectory() ){
process.env.PATH += `:${d}`;
}
break;
case "params":
break;
default:
break;
}
}
}); }
catch(e){
s = `ERROR: can't read files from merge directory: ${dir}`;
clog(s);
return s;
}
// we have merged this dir
merges[dir] = true;
clog("merge: %s", dir);
return "OK";
};
// parse an argument string into an array of arguments, where
// spaces and quotes are delimiters
const parseArgs = function(argstr){
let targs, i, j, ci, c1, c2, s;
const args = [];
// temporarily replace spaces inside file extension brackets
// https://stackoverflow.com/questions/16644159/regex-to-remove-spaces-between-and
const nargstr = argstr.replace(/\s+(?=[^[\]]*\])/g, "__sp__");
// split arguments on spaces
targs = nargstr.split(" ");
// now re-combine quoted args into one arg
for(i=0, j=0, ci=-1; i<targs.length; i++){
// remove or rename dangerous characters
s = targs[i].replace(/`/g, "").replace(/&/g, "__ampersand__");
// are we re-combining?
if( ci >= 0 ){
// yes, add to current arg
args[ci] = `${args[ci]} ${s}`;
} else {
// no, add another arg
args[j] = s;
}
if( ci === -1 ){
// new quoted string?
c1 = s.charAt(0);
c2 = s.charAt(s.length-1);
if( c1 === "'" || c1 === '"' ){
// spread across more than one arg, so we need to recombine?
if( c2 === c1 ){
// no just remove the quotes from this one
args[j] = args[j].substr(1,args[j].length-2);
j++;
} else {
// yes
ci = j;
}
} else {
// no
j++;
}
} else {
// end of current quoted string?
c2 = s.charAt(s.length-1);
if( c2 === c1 ){
// yes, remove enclosing quotes
args[ci] = args[ci].substr(1,args[ci].length-2);
ci = -1;
j++;
}
}
}
// now put back the spaces
for(i=0; i<args.length; i++){
args[i] = args[i].replace(/__sp__/g, " ");
}
return args;
};
// get data path
const getDataPath = function(s){
let i, t, narr;
let arr = [];
let dataPath="";
// always use the global dataPath set by the site
if( globalOpts.dataPath ){
dataPath = envClean(globalOpts.dataPath);
arr = dataPath.split(":");
}
// add user dataPath, if permitted
if( s && globalOpts.dataPathModify ){
t = envClean(s);
narr = t.split(":");
for(i=0; i<narr.length; i++){
if( !arr.includes(narr[i]) ){
if( dataPath ){
dataPath += ":";
}
dataPath += narr[i];
}
}
}
if( dataPath ){
dataPath += ":";
}
// always add js9Helper install directory
dataPath += installDir;
return dataPath;
};
// see if a file exists in the dataPath
const getFilePath = function(file, dataPath, myenv, dohide){
let i, s, s1, froot1, fext, parr, from, to;
// eslint-disable-next-line no-unused-vars
const repl = (m, t, o) => {
if( myenv && myenv[t] ){
return myenv[t];
}
return m;
};
const hide = (s) => {
const rexp = new RegExp(`^${installDir}`);
return s.replace(rexp, "${JS9_DIR}");
};
// sanity check
if( !file ){
return;
}
// translate filename, if necessary
if( globalOpts.fileTranslate &&
Array.isArray(globalOpts.fileTranslate) &&
globalOpts.fileTranslate[0] ){
from = new RegExp(globalOpts.fileTranslate[0]);
to = globalOpts.fileTranslate[1] || "";
file = file.replace(from, to);
}
// look for and remove the extension
froot1 = file.replace(/\[.*]$/,"");
s = file.match(/\[.*]$/,"");
if( s ){
fext = s[0];
} else {
fext = "";
}
parr = dataPath.split(":");
// everything gets tested relative to the current directory
// (we'll use an absolute path to it to help the analysis wrapper)
parr.unshift(process.cwd());
// absolute paths get tested on their own (BEFORE testing ./absolute/path)
if( path.isAbsolute(froot1) ){
parr.unshift("");
}
// check is file is in any of the directories in the path
for(i=0; i<parr.length; i++){
// replace environment variables in path, if possible
s = parr[i].replace(/\${?([a-zA-Z][a-zA-Z0-9_()]+)}?/g, repl);
// make up pathnames to check
s1 = path.join(s, froot1);
if( fs.existsSync(s1) ){
if( !s1.match(/\//) ){
s1 = `${currentDir}/${s1}`;
}
// found the file add extension to full path
s1 += fext;
if( dohide === false ){
return s1;
}
return hide(s1);
}
}
return;
};
// get size of a file
const getFileSize = function(file){
let stats;
let size = 0;
const froot = file
.replace(/\[.*]$/,"")
.replace(/\$\{?JS9_DIR\}?/, installDir);
if( fs.existsSync(froot) ){
stats = fs.statSync(froot);
if( stats ){
size = stats.size;
}
}
return size;
};
//
// message callbacks
//
// execCmd: exec a analysis wrapper routine to run a command
// this is the default callback for server-side analysis tasks
const execCmd = function(socket, obj, cbfunc) {
let cmd, tcmd, argstr, args, maxbuf, child, s, myid, myrtype;
let myworkdir = null;
const myip = getHost(socket);
const myenv = process.env;
const res = {stdout: null, stderr: null, errcode: 0,
encoding: globalOpts.textEncoding};
const dangerousCharsRegex = /[^a-zA-Z0-9_]/g;
// sanity check
if( !obj || !obj.cmd || !socket.js9 ){
if( cbfunc ){
res.stderr = "JS9 helper is unavailable";
cbfunc(res);
}
return;
}
myid = obj.id;
myrtype = obj.rtype || "binary";
// stdin processing
if( obj.stdin && typeof obj.stdin === "object" ){
// first chunk gets sent after process is started (see below),
// otherwise send a new chunk to stdin now and return
socket.js9.child.stdin.write(obj.stdin.data);
// if this was the last chunk, close off stdin and delete child
if( (obj.stdin.cur + obj.stdin.len) >= obj.stdin.total ){
socket.js9.child.stdin.end();
delete socket.js9.child;
}
if( cbfunc ){
res.stdout = "OK";
cbfunc(res);
}
return;
}
// id of js9 display
myenv.JS9_ID = envClean(myid);
// host ip
myenv.JS9_HOST = envClean(myip);
// JS9 base dir
myenv.JS9_DIR = installDir;
// JS9 unique page id
myenv.JS9_PAGEID = socket.js9.pageid;
// js9 cookie in the sending browser
if( obj.cookie ){
myenv.HTTP_COOKIE = envClean(obj.cookie);
}
// datapath (for finding data files)
myenv.JS9_DATAPATH = getDataPath(obj.dataPath);
// set max buffer size
switch(myrtype){
case "text":
case "plot":
case "alert":
maxbuf = globalOpts.maxTextBuffer;
break;
default:
maxbuf = globalOpts.maxBinaryBuffer;
break;
}
// the command string
argstr = obj.cmd;
// expand directory macros
argstr = argstr
.replace(/\$\{?JS9_DIR\}?/, installDir)
.replace(/\$\{?JS9_WORKDIR\}?/, (socket.js9.rworkDir || ""));
// split arguments on spaces, respecting quotes
args = parseArgs(argstr);
// remove dangerous characters from command, if necessary
// a second safety check is below, so this is not strictly necessary
// (and we can allow it to be turned off for backward compatibility)
if( globalOpts.restrictWrappers ){
tcmd = args[0];
args[0] = args[0].replace(dangerousCharsRegex, "");
if( tcmd !== args[0] ){
clog("SECURITY WARNING: ignoring dangerous cmd: '%s'", tcmd);
return;
}
}
// handle fitshelper specially
if( args[0] === globalOpts.cmd ){
// if FITS, handle this request internally instead of exec'ing
// (makes external analysis possible without building js9 programs)
if( obj.image && (path.extname(obj.image) !== ".png") ){
// check primary file
s = getFilePath(obj.image, myenv.JS9_DATAPATH, myenv);
if( !s && obj.image2 && obj.image !== obj.image2 ){
// check alternate (usually with path to installdir removed)
s = getFilePath(obj.image2, myenv.JS9_DATAPATH, myenv);
}
if( s ){
res.stdout = `${obj.image} ${s}`;
}
if( cbfunc ){
cbfunc(res);
}
return;
}
// handle fitshelper specially
cmd = args[0];
} else {
// start in the appropriate work directory, if possible
if( (obj.useWorkDir !== false) && socket.js9.aworkDir ){
// abdsolute working directory to cd into
myworkdir = socket.js9.aworkDir;
// working directory relative to JS9 dir is for the worker
myenv.JS9_WORKDIR = socket.js9.rworkDir;
myenv.JS9_WORKDIR_QUOTA = globalOpts.workDirQuota;
}
// construct wrapper path
// cmd = globalOpts.analysisWrappers + "/" + args[0];
// get path of wrapper script
cmd = getFilePath(args[0], globalOpts.analysisWrapPath, myenv, false);
// make sure we got a wrapper (else we're under attack?)
if( !cmd || (cmd === args[0]) ){
clog("SECURITY WARNING: ignoring wrapperless cmd: '%s'", args[0]);
if( cbfunc ){
res.stderr = `can't find JS9 wrapper script: ${args[0]}`;
cbfunc(res);
}
return;
}
// make path absolute in case we change directories
if( cmd.charAt(0) !== "/" ){
cmd = `${installDir}/${cmd}`;
}
}
// log what we are about to do
clog("exec: %s %s", cmd, JSON.stringify(args.slice(1)));
// execute the analysis script with cmd arguments
// NB: can't use exec because the shell breaks, e.g. region command lines
try{
child = cproc.execFile(cmd, args.slice(1),
{ encoding: "utf8",
timeout: 0,
maxBuffer: maxbuf,
killSignal: "SIGTERM",
cwd: myworkdir,
env: myenv
},
// return from exec
(errcode, stdout, stderr) => {
if( errcode ){
res.errcode = errcode.errno || errcode.code;
}
if( stdout ){
switch(myrtype){
case "text":
case "plot":
case "png":
case "alert":
res.stdout = stdout.toString(res.encoding);
break;
default:
res.encoding = "binary";
res.stdout = stdout;
break;
}
}
if( stderr ){
res.stderr = stderr.toString();
}
// send results back to browser
if( cbfunc ){ cbfunc(res); }
});
// first time through: save child for uploading data
if( obj.stdin === true ){
// save child so we can process future chunks of data
socket.js9.child = child;
// set up to send raw data
socket.js9.child.stdin.setEncoding = 'binary';
}
} catch(e){
// send exec error back to browser
res.stderr = `ERROR: could not exec ${cmd}: ${e.message}`;
res.stdout = null;
if( cbfunc ){ cbfunc(res); }
}
};
// sendAnalysis: send list of analysis routines to browser
const sendAnalysisTasks = function(cbfunc) {
let s;
if( analysis && analysis.str.length ){
s = `[${analysis.str.join(",")}]`;
if( cbfunc ){ cbfunc(s); }
}
};
// pageReady: wait for a Web browser to load a JS9 page and connect
// used by js9Msg.js to start up a Web browser before executing commands
const pageReady = function(socket, obj, cbfunc, tries){
let i, targets;
const timeout = obj.timeout || 500;
const maxtries = obj.tries || 10;
// callback func
const myfunc = (s) => {
if( cbfunc ){ cbfunc(s); }
};
setTimeout(() => {
// look for targets
targets = getTargets(socket, obj);
// if we have at least one ...
if( (targets.length === 1) || (targets.length > 1 && obj.multi) ){
// send command to JS9 instance(s)
for(i=0; i<targets.length; i++){
targets[i].emit("msg", obj, myfunc);
}
} else {
// no targets: have we tried enough?
if( !targets.length ){
if( tries < maxtries ){
// no, try again
pageReady(socket, obj, cbfunc, tries+1);
} else {
// yes, it's an error
if( cbfunc ){
cbfunc("ERROR: timeout waiting for Web page");
}
}
} else {
// it's an error
if( cbfunc ){
cbfunc(`ERROR: ${targets.length} JS9 instance(s) found with id ${obj.id} (${obj.cmd})`);
}
}
}
}, timeout);
};
// sendMsg: send a message to the browser
// this is the default callback for external communication with JS9
const sendMsg = function(socket, obj, cbfunc) {
let s, i, myip, targets;
// callback func
const myfunc = (s) => {
if( cbfunc ){ cbfunc(s); }
};
// get list of targets to send to
targets = getTargets(socket, obj);
// commands not going to a browser
switch(obj.cmd){
case "alive":
myfunc("OK");
return;
case "merge":
// local connections only
myip = getHost(socket);
if( (myip === "127.0.0.1") || (myip === "::ffff:127.0.0.1") ){
myfunc(mergeDirectory(obj.args[0]));
} else {
s = `ERROR: rejecting remote merge request from: ${myip}`;
clog(s);
myfunc(s);
}
return;
case "targets":
myfunc(targets.length);
return;
case "getAnalysis":
sendAnalysisTasks(cbfunc);
return;
case "addDisplay":
case "renameDisplay":
case "worker":
case "image":
case "runAnalysis":
case "fits2fits":
case "quotacheck":
myfunc(`ERROR: ${obj.cmd} not available via js9 messaging script`);
return;
}
// look for one target (or else that multi is allowed)
if( (targets.length === 1) || (targets.length > 1 && obj.multi) ){
// send command to JS9 instance(s)
for(i=0; i<targets.length; i++){
targets[i].emit("msg", obj, myfunc);
}
} else {
// no targets: wait for the page to get ready?
if( !targets.length && obj.pageReady ){
pageReady(socket, obj, cbfunc, 0);
return;
}
// it's an error
if( cbfunc ){
cbfunc(`ERROR: ${targets.length} JS9 instance(s) found with id ${obj.id} (${obj.cmd})`);
}
}
};
//
// protocol handlers
//