forked from mdeforall/atompm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpwsd.js
833 lines (739 loc) · 26.7 KB
/
httpwsd.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
/* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
* Copyright 2011 by the AToMPM team and licensed under the LGPL
* See COPYING.lesser and README.md in the root of this project for full details
*/
/*********************************** IMPORTS **********************************/
var _util = require("util"),
_fs = require('fs'),
_http = require('http'),
_path = require('path'),
_url = require('url'),
_utils = require('./utils'),
_sio = require('socket.io'),
_cp = require('child_process'),
_fspp = require('./___fs++'),
_duri = require('./___dataurize');
/*********************************** GLOBALS **********************************/
/* an array of WebWorkers
... each has its own mmmk instance */
var workers = new Array();
/* an array of response objects
... for workers to write on when they complete requests */
var responses = new Array();
/* a map of worker ids to socket.io socket session ids
... each socket is registered to exactly one worker
... several sockets may be registered to the same worker */
var workerIds2socketIds = {};
/************************************ UTILS ***********************************/
/** Remove invalid characters from a string. **/
function __clean_string(s)
{
if (s == undefined) {
return s;
}
s = JSON.stringify(s);
s = s.replace(/'/g, '');
s = s.replace(/"/g, '');
s = s.replace(/‘/g, '');
s = s.replace(/’/g, '');
s = s.replace(/\\/g, '\\');
s = s.replace(/\//g, '\/');
s = s.replace(/\\n/g, ' ');
return s;
}
/** Syntactic sugar to build and send HTTP responses **/
function __respond(response, statusCode, reason, data, headers)
{
response.writeHead(
statusCode,
__clean_string(reason),
(headers || {'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'}));
var encoding =
(headers &&
(headers['Content-Type'].match(/image/) ||
headers['Content-Type'].match(/pdf/) ||
headers['Content-Type'].match(/zip/) ) ?
'binary' :
'utf8'),
content = reason || data;
if( _utils.isObject(content) )
response.end(_utils.jsons(content,null,'\t'), encoding);
else
response.end(content, encoding);
}
/** Syntactic sugar to build and send a socket.io message **/
function __send(socket, statusCode, reason, data, headers)
{
socket.json.emit('message',
{'statusCode':statusCode,
'reason':reason,
'headers':(headers || {'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'}),
'data':data});
}
/************************************ LOGIC ***********************************/
var httpserver = _http.createServer(
function(req, resp)
{
var url = _url.parse(req.url,true);
url.pathname = decodeURI(url.pathname);
/* serve client */
if( req.method == 'GET' && url.pathname == '/atompm' )
_fs.readFile('./client/atompm.html', 'utf8',
function(err, data)
{
if(err)
__respond(resp,500,String(err));
else
__respond(resp,200,'',data,{'Content-Type': 'text/html'});
});
else if( req.method == 'GET' && url.pathname == '/favicon.png' )
_fs.readFile('./favicon.png', 'binary',
function(err, data)
{
if(err)
__respond(resp,500,String(err));
else
__respond(resp,200,'',data,{'Content-Type': 'image/png'});
});
/* provide an interface to the unfortunately unavoidable dataurize
module which returns data URIs for resources at arbitrary URLs */
else if( req.method == 'GET' && url.pathname == '/datauri' )
{
var target = _url.parse(decodeURI(url['query']['target']));
_duri.dataurize(
target,
function(err,datauri)
{
if(err)
__respond(resp,500,_utils.jsons(err));
else
__respond(resp,200,'',datauri);
});
}
/* serve metamodels, buttons models and their icons */
else if( req.method == 'GET' &&
(url.pathname.match(/\.metamodel$/) ||
url.pathname.match(/\.buttons.model$/) ||
url.pathname.match(/\.icon\.png$/i)) )
{
var isIcon = url.pathname.match(/\.icon\.png$/i);
_fs.readFile('./users/'+url.pathname, (isIcon ? 'binary' : 'utf8'),
function(err, data)
{
if(err)
__respond(resp,500,String(err));
else
{
var contentType =
(isIcon ?
{'Content-Type': 'image/png'} :
{'Content-Type': 'application/json'});
__respond(resp,200,'',data,contentType);
}
});
}
/* serve ordinary files (e.g., js includes, images, css)
NOTE:: distinguish between atompm images (e.g., grid background,
filebrowser icons) and CS/Images */
else if( req.method == 'GET' &&
(url.pathname.match(/\.html$/) ||
url.pathname.match(/\.css$/) ||
url.pathname.match(/\.js$/) ||
url.pathname.match(/\.pdf$/) ||
url.pathname.match(/\.png$/i) ||
url.pathname.match(/\.jpg$/i) ||
url.pathname.match(/\.jpeg$/i) ||
url.pathname.match(/\.gif$/i) ||
url.pathname.match(/\.svg$/i)) )
{
var isImage = url.pathname.match(/\.png$/i) ||
url.pathname.match(/\.jpg$/i) ||
url.pathname.match(/\.jpeg$/i) ||
url.pathname.match(/\.gif$/i) ||
url.pathname.match(/\.svg$/i),
isText = ! isImage && ! url.pathname.match(/\.pdf$/);
if( isImage && ! url.pathname.match(/^\/client\/media\//) )
url.pathname = '/users/'+url.pathname;
_fs.readFile('.'+url.pathname, (isText ? 'utf8' : 'binary'),
function(err, data)
{
if(err)
__respond(resp,500,String(err));
else
{
var contentType =
(url.pathname.match(/\.html$/) ?
{'Content-Type': 'text/html'} :
url.pathname.match(/\.css$/) ?
{'Content-Type': 'text/css'} :
url.pathname.match(/\.js$/) ?
{'Content-Type': 'application/javascript'} :
url.pathname.match(/\.pdf$/) ?
{'Content-Type': 'application/pdf'} :
url.pathname.match(/\.png$/i) ?
{'Content-Type': 'image/png'} :
url.pathname.match(/\.jpg$/i) ||
url.pathname.match(/\.jpeg$/i) ?
{'Content-Type': 'image/jpeg'} :
url.pathname.match(/\.gif$/i) ?
{'Content-Type': 'image/gif'} :
url.pathname.match(/\.svg$/i) ?
{'Content-Type': 'image/svg+xml'} :
undefined);
__respond(resp,200,'',data,contentType);
}
});
}
/* serve encrypted user password */
else if( req.method == 'GET' && url.pathname == '/passwd' )
_fs.readFile('./users/'+url['query']['username']+'/passwd', 'utf8',
function(err, data)
{
if(err)
__respond(resp,500,String(err));
else
__respond(resp,200,'',data,{'Content-Type': 'text/html'});
});
/* create new user
1. make sure user doesn't already exist
2. make a new copy of ./users/(default)
3. create password file */
else if( req.method == 'POST' && url.pathname == '/user' )
{
var userdir = './users/'+url['query']['username'];
_fs.exists(userdir,
function(exists)
{
if( exists )
{
__respond(resp,500,'username already exists');
return;
}
_fspp.cp('./users/(default)/',userdir,
function(err, stdout, stderr)
{
if( err )
{
__respond(resp,500,String(err));
return;
}
_fs.writeFile(
userdir+'/passwd',
url['query']['password'],
function(err)
{
if( err )
__respond(resp,500,String(err));
else
__respond(resp,200);
});
});
});
}
/* serve [a subset of] user preferences */
else if( req.method == 'GET' && url.pathname.match(/prefs$/) )
_fs.readFile('./users/'+url.pathname, 'utf8',
function(err, data)
{
if(err)
__respond(resp,500,String(err));
else if( url['query']['subset'] == undefined )
__respond(resp,200,'',data);
else
try
{
__respond(
resp,
200,
'',
_utils.splitDict(
_utils.jsonp(data),
_utils.jsonp(url['query']['subset'])));
}
catch(err) {__respond(resp,500,String(err));}
});
/* update user preferences
1 retrieve all post data
2 read prefs file from disk
3 apply changes
4 write updated prefs to disk */
else if( req.method == 'PUT' && url.pathname.match(/prefs$/) )
{
var reqData = '';
req.addListener("data", function(chunk) {reqData += chunk;});
req.addListener("end",
function()
{
_fs.readFile('./users/'+url.pathname, 'utf8',
function(err, prefs)
{
if(err)
__respond(resp,500,String(err));
else
{
try
{
prefs = _utils.jsonp(prefs);
reqData = _utils.jsonp(reqData);
}
catch(err)
{
__respond(resp,500,String(err));
return;
}
for( var pref in reqData )
prefs[pref]['value'] = reqData[pref];
_fs.writeFile(
'./users/'+url.pathname,
_utils.jsons(prefs,null,'\t'),
function(err, data)
{
if(err)
__respond(resp,500,String(err));
else
__respond(resp,200);
});
}
});
});
}
/* delete specified file/folder */
else if( req.method == 'DELETE' && url.pathname.match(/\.(file|folder)$/) )
{
if (url.pathname.match('_Trash_')) {
__respond(resp,500,"cannot remove trash!");
} else {
var matches = url.pathname.match(/^\/(.*?)\/(.*\/)?(.*)\.(file|folder)$/),
username = matches[1],
folder = matches[2] || '',
fname = matches[3],
userdir = './users/'+username+'/',
ondelete =
function(err, stdout, stderr)
{
if( err )
__respond(resp,500,String(err));
else
__respond(resp,200);
},
deletef =
function(response)
{
var newname = userdir+'_Trash_/'+folder+fname;
if (_fs.existsSync(newname)) {
if (url.pathname.match(/\.folder$/)) {
_fspp.deleteFolderRecursive(newname);
} else {
_fs.unlink(newname);
}
}
_fspp.mv(userdir+folder+fname,userdir+'_Trash_/'+folder,ondelete);
};
_fs.exists(userdir+'_Trash_/'+folder,
function(exists)
{
if( ! exists )
_fspp.mkdirs(userdir+'_Trash_/'+folder,deletef);
else {
deletef();
}
});
}
}
/* create folder */
else if( req.method == 'POST' && url.pathname.match(/\.folder$/) )
{
var matches = url.pathname.match(/^\/(.*?)\/(.*)\.folder$/),
username = matches[1],
folder = matches[2],
userdir = './users/'+username+'/',
oncreate =
function(err, stdout, stderr)
{
if( err )
__respond(resp,500,String(err));
else
__respond(resp,200);
};
_fs.exists(userdir+folder,
function(exists)
{
if( ! exists )
_fspp.mkdirs(userdir+folder,oncreate);
else {
oncreate("folder " + folder + " already exists");
}
});
}
/* rename file/folder (or move) */
else if( req.method == 'PUT' && url.pathname.match(/\.(folder|file)$/) )
{
req.setEncoding('utf8');
var data = '';
req.addListener("data", function(chunk) {data += chunk;});
req.addListener("end",
function() {
data = _utils.jsonp(data);
if (data.match(/^\//)) {
// move
var matches = url.pathname.match(/^\/(.*?)\/(.*\/)?(.*)\.(file|folder)$/),
username = matches[1],
folder = matches[2] || '',
fname = matches[3],
userdir = './users/'+username,
onmove =
function(err, stdout, stderr)
{
if( err )
__respond(resp,500,String(err));
else
__respond(resp,200);
};
if (_fs.existsSync(userdir+data+fname)) {
if (url.pathname.match(/\.folder$/)) {
_fspp.deleteFolderRecursive(userdir+data+fname);
} else {
_fs.unlink(newname);
}
}
_fspp.mv(userdir+"/"+folder+fname,userdir+data,onmove);
} else {
// rename
var matches = url.pathname.match(/^\/(.*?)\/(.*\/)?(.*)\.(file|folder)$/),
username = matches[1],
folder = matches[2] || '',
fname = matches[3],
userdir = './users/'+username+'/',
onrename =
function(err, stdout, stderr)
{
if( err )
__respond(resp,500,String(err));
else
__respond(resp,200);
};
_fs.rename(userdir+folder+fname,userdir+folder+data,onrename);
}
}
);
}
else if (req.method == 'POST' && url.pathname.match(/\.formalism$/)) {
// create new formalism
var matches = url.pathname.match(/^(.*)\/(.*)\.formalism$/),
username = matches[1],
formalism = matches[2],
userdir = './users/'+username+"/",
oncreatefolder =
function(err, stdout, stderr)
{
if( err )
__respond(resp,500,String(err));
else {
_fs.createReadStream(userdir+"Formalisms/__Templates__/MetamodelTemplate.model").pipe(_fs.createWriteStream(userdir+"Formalisms/"+formalism+"/"+formalism+".model"));
_fs.createReadStream(userdir+"Formalisms/__Templates__/ConcreteSyntaxTemplate.model").pipe(_fs.createWriteStream(userdir+"Formalisms/"+formalism+"/"+formalism+".defaultIcons.model"));
_fs.createReadStream(userdir+"Formalisms/__Templates__/MetamodelTemplate.metamodel").pipe(_fs.createWriteStream(userdir+"Formalisms/"+formalism+"/"+formalism+".metamodel"));
_fs.createReadStream(userdir+"Formalisms/__Templates__/ConcreteSyntaxTemplate.defaultIcons.metamodel").pipe(_fs.createWriteStream(userdir+"Formalisms/"+formalism+"/"+formalism+".defaultIcons.metamodel"));
_fs.createReadStream(userdir+"Formalisms/__Templates__/T_TransformationTemplate.model").pipe(_fs.createWriteStream(userdir+"Formalisms/"+formalism+"/OperationalSemantics/T_OperationalSemantics.model"));
_fs.createReadStream(userdir+"Formalisms/__Templates__/T_TransformationTemplate.model").pipe(_fs.createWriteStream(userdir+"Formalisms/"+formalism+"/TranslationalSemantics/T_TranslationalSemantics.model"));
__respond(resp,200);
}
};
_fs.mkdir(userdir+"Formalisms/"+formalism,function(err, stdout, stderr) {
if( err )
__respond(resp,500,String(err));
else {
_fs.mkdirSync(userdir+"Formalisms/"+formalism+"/OperationalSemantics");
_fs.mkdir(userdir+"Formalisms/"+formalism+"/TranslationalSemantics", oncreatefolder);
}
});
}
else if (req.method == 'POST' && url.pathname.match(/\.transformation$/)) {
// create new transformation
var matches = url.pathname.match(/^\/(.*?)\/(.*)\.transformation$/),
username = matches[1],
userdir = './users/'+username+"/";
_fs.createReadStream(userdir+"Formalisms/__Templates__/T_TransformationTemplate.model").pipe(_fs.createWriteStream('./users/'+url.pathname.slice(0, -(".transformation".length))));
__respond(resp,200);
}
else if (req.method == 'POST' && url.pathname.match(/\.rule$/)) {
// create new rule
var matches = url.pathname.match(/^\/(.*?)\/(.*)\.rule$/),
username = matches[1],
userdir = './users/'+username+"/";
_fs.createReadStream(userdir+"Formalisms/__Templates__/R_RuleTemplate.model").pipe(_fs.createWriteStream('./users/'+url.pathname.slice(0, -(".rule".length))));
__respond(resp,200);
}
/* extract user-uploaded archive to specified folder
1. read in all data
2. make sure destination exists and is a directory
3. write data to temp file (upload###.zip)
4. extract temp file and remove it
NOTE:: it's not clear why (despite hours of googling) but the
"req.setEncoding('utf8')" statement makes the difference
between retrieving correct and corrupted (when non-text
files in zip) data */
else if( req.method == 'PUT' && url.pathname.match(/\.file$/) )
{
req.setEncoding('utf8');
let reqData = '',
tmpzip = 'upload'+Date.now()+'.zip',
destdir = './users/'+url.pathname.match(/(.*)\.file$/)[1]+'/';
if( url.pathname.contains("..") || url.pathname.contains(";") ) {
__respond(resp, 404,
'invalid pathname, no semicolons or .. allowed :: ' + url.pathname);
return;
}
req.addListener("data", function(chunk) {reqData += chunk;});
req.addListener("end",
function()
{
_fs.stat(destdir,
function(err,stats)
{
if( err )
__respond(resp,404,String(err));
else if( ! stats.isDirectory() )
__respond(resp,404,
'destination is not a directory :: '+destdir);
else
_fs.writeFile(
destdir+tmpzip,eval('('+reqData+')'),
'binary',
function(err)
{
_cp.exec('cd '+destdir+'; unzip -o '+tmpzip,
function(err, stdout, stderr)
{
if( err )
__respond(resp,500,String(err));
else
__respond(resp,200);
_fs.unlink(destdir+tmpzip, function(err){
console.log("Unlinked " + destdir + tmpzip);
}
);
});
});
});
});
}
/* serve specified file/folder within a zip file */
else if( req.method == 'GET' && url.pathname.match(/\.file$/) )
{
let matches = url.pathname.match(/^\/(.*?)\/(.*)\.file$/),
username = matches[1],
fname = './'+matches[2],
userdir = './users/'+username+'/',
tmpzip = 'download'+Date.now()+'.zip';
if( username.contains("..") || username.contains(";") ) {
__respond(resp, 404,
'invalid username, no colons or .. allowed :: ' + username);
return;
}
_fs.exists(userdir+fname,
function(exists)
{
if( ! exists )
__respond(resp,404,
'requested file/folder does not exist :: '+fname);
else
_cp.exec('cd '+userdir+'; zip -r '+tmpzip+' "'+fname+'"',
function(err, stdout, stderr)
{
if( err )
__respond(resp,500,String(err));
else
_fs.readFile(userdir+tmpzip,
function(err, data)
{
__respond(resp,200,'',data,
{'Content-Type':'application/zip',
'Content-Disposition':
'attachment; filename="'+tmpzip+'"'});
_fs.unlink(userdir+tmpzip, function(err){
console.log("Unlinked " + userdir+tmpzip);
});
});
});
});
}
/* serve list of all files */
else if( req.method == 'GET' &&
url.pathname.match(/^\/.+\/filelist$/) )
{
var matches = url.pathname.match(/^\/(.+)\/filelist$/);
_fspp.findfiles('./users/'+matches[1],
function(err, stdout, stderr)
{
if( err )
__respond(resp,404,String(err));
else
__respond(resp,200,'',stdout);
});
}
/* spawn new worker */
else if( (url.pathname == '/csworker' || url.pathname == '/asworker')
&& req.method == 'POST' )
{
/* setup and store new worker */
var worker = _cp.fork(_path.join(__dirname, '__worker.js')),
wid = workers.push(worker)-1;
workerIds2socketIds[wid] = [];
worker.on('message',
function(msg)
{
/* push changes (if any) to registered sockets... even empty
changelogs are pushed to facilitate sequence number-based
ordering */
if( msg['changelog'] != undefined )
{
var _msg = {'changelog':msg['changelog'],
'sequence#':msg['sequence#'],
'hitchhiker':msg['hitchhiker']};
workerIds2socketIds[wid].forEach(
function(sid)
{
__send(
wsserver.sockets.sockets[sid],
undefined,
undefined,
_msg);
});
}
/* respond to a request */
if( msg['respIndex'] != undefined )
__respond(
responses[msg['respIndex']],
msg['statusCode'],
msg['reason'],
JSON.stringify(
{'headers':
(msg['headers'] ||
{'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'}),
'data':msg['data'],
'sequence#':msg['sequence#']}),
{'Content-Type': 'application/json'});
});
worker.send(
{'workerType':url.pathname,
'workerId':wid});
/* respond worker id (used to identify associated worker) */
__respond(
resp,
201,
'',
''+wid);
return;
}
/* check for worker id and it's validity */
else if( url['query'] == undefined ||
url['query']['wid'] == undefined )
__respond(resp, 400, 'missing worker id');
else if( workers[url['query']['wid']] == undefined )
__respond(resp, 400, 'invalid worker id :: '+url['query']['wid']);
/* save resp object and forward request to worker (if request is PUT or
POST, recover request data first)
TBI:: only registered sockets should be allowed to speak to worker
... one way of doing this is forcing request urls to contain
cid=socket.id## */
else if( req.method == 'PUT' || req.method == 'POST' )
{
var reqData = '';
req.addListener("data", function(chunk) {reqData += chunk;});
req.addListener("end",
function()
{
workers[url['query']['wid']].send(
{'method':req.method,
'uri':url.pathname,
'reqData':(reqData == '' ?
undefined :
eval('('+reqData+')')),
'uriData':url['query'],
'respIndex':responses.push(resp)-1});
});
}
else
workers[url['query']['wid']].send(
{'method':req.method,
'uri':url.pathname,
'uriData':url['query'],
'respIndex':responses.push(resp)-1});
});
httpserver.listen(8124);
var wsserver = _sio.listen(httpserver);
wsserver.configure(
function()
{
wsserver.set('log level',2);
});
wsserver.sockets.on('connection',
function(socket)
{
/* unregister this socket from the specified worker ... when a worker
has no more registered sockets, terminate it */
function unregister(wid)
{
var i = workerIds2socketIds[wid].indexOf(socket.id);
if( i == -1 )
__send(socket,403,'already unregistered from worker');
else
{
workerIds2socketIds[wid].splice(i,1);
if( workerIds2socketIds[wid].length == 0 )
{
workers[wid].kill();
workers[wid] = undefined;
delete workerIds2socketIds[wid];
}
__send(socket,200);
}
}
/* onmessage : on reception of data from client */
socket.on('message',
function(msg/*{method:_,url:_}*/)
{
var url = _url.parse(msg.url,true);
/* check for worker id and it's validity */
if( url['query'] == undefined ||
url['query']['wid'] == undefined )
return __send(socket,400,'missing worker id');
var wid = url['query']['wid'];
if( workers[wid] == undefined )
__send(socket,400,'unknown worker id :: '+wid);
/* register socket for requested worker */
else if( msg.method == 'POST' &&
url.pathname.match(/changeListener$/) )
{
if( workerIds2socketIds[wid].indexOf(socket.id) > -1 )
__send(socket,403,'already registered to worker');
else
{
workerIds2socketIds[wid].push(socket.id);
__send(socket,201);
}
}
/* unregister socket for requested worker */
else if( msg.method == 'DELETE' &&
url.pathname.match(/changeListener$/) )
unregister(wid);
/* unsupported request */
else
__send(socket,501);
});
/* ondisconnect : on disconnection of socket */
socket.on('disconnect',
function()
{
for( var wid in workerIds2socketIds )
for( var i in workerIds2socketIds[wid] )
if( workerIds2socketIds[wid][i] == socket.id )
{
unregister(wid);
return;
}
});
});