forked from YahooArchive/arrow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
executable file
·631 lines (524 loc) · 17.9 KB
/
server.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
#!/usr/bin/env node
/*jslint forin:true sub:true anon:true sloppy:true stupid:true nomen:true node:true continue:true*/
/*
* Copyright (c) 2012, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
var fs = require("fs");
var os = require("os");
var urlParser = require("url");
var querystring = require("querystring");
var path = require("path");
var nopt = require("nopt");
var http = require("http");
var express = require("express");
var log4js = require("log4js");
var childProcess = require("child_process");
var portchecker = require('../ext-lib/portchecker');
log4js.setGlobalLogLevel("INFO");
var logger = log4js.getLogger("ArrowServer");
var debug = false;
var arrowHost = "localhost";
var arrowPortMin = 10000;
var arrowPortMax = 11000;
var ghostPortMin = 10000;
var ghostPortMax = 11000;
var ghostPort = 0;
var arrowPort = 0;
var arrowAddress = "";
var parsed = nopt();
//setting appRoot
global.appRoot = path.resolve(__dirname, "..");
//help messages
function showHelp() {
console.info("\nOPTIONS :" + "\n" +
" --host : (optional) Fully qualified name of host where arrow server is running. (default: localhost)" + "\n" +
" --port : (optional) Arrow Server Port. (default: 4459) " + "\n" +
" --ghostPort : (optional) GhostDriver Port. (default: 4460) " + "\n\n"
);
console.log("\nEXAMPLES :" + "\n" +
" For local usage: " + "\n" +
" arrow_server ( Arrow server will start listening to localhost:4459 )" + "\n\n" +
" For remote usage: " + "\n" +
" arrow_server --host=minuteblue.corp.yahoo.com --port=4800 ( Arrow server will start listening to minuteblue.corp.yahoo.com:4800) " + "\n\n");
}
if (parsed.help) {
showHelp();
process.exit(0);
}
if (parsed["host"]) {
arrowHost = parsed["host"];
} else {
convertHostname();
}
if (parsed["port"]) {
var port = String(parsed["port"]);
if (-1 === port.indexOf("-")) {
arrowPortMin = arrowPortMax = parseInt(port, 10);
} else {
var range = port.split("-");
arrowPortMin = parseInt(range[0], 10);
arrowPortMax = parseInt(range[1], 10);
}
}
if (parsed["debug"]) {
debug = true;
}
var app = express();
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
var mimes = {
"css": "text/css",
"js": "text/javascript",
"htm": "text/html",
"html": "text/html",
"ico": "image/vnd.microsoft.icon",
"jpg": "image/jpeg",
"gif": "image/gif",
"png": "image/png",
"xml": "text/xml"
};
function serveStatic(pathname, req, res) {
fs.readFile(pathname, function (error, content) {
var tmp,
ext,
mime;
if (error) {
res.writeHead(404);
res.end("Error loading file " + pathname + ": " + error, "utf-8");
} else {
tmp = pathname.lastIndexOf(".");
ext = pathname.substring((tmp + 1));
mime = mimes[ext] || "text/plain";
res.writeHead(200, {"Content-Type": mime});
res.end(content);
}
});
}
function cleanUp() {
try {
fs.unlinkSync(global.appRoot + "/tmp/arrow_server.status");
fs.unlinkSync(global.appRoot + "/tmp/arrow_phantom_server.status");
} catch (ex) {}
if ( this.child.kill) {
this.child.kill();
}
console.log("Good bye!");
}
// file server
app.get("/arrow", function (req, res) {
serveStatic(__dirname + "/../lib/client/driver.html", req, res);
});
app.get("/arrow/static/*", function (req, res) {
serveStatic("/" + req.params[0], req, res);
});
// selenium ip hookup
app.get("/arrow/wd/:selPort", function (req, res) {
var selUrl = "http://" + req.connection.remoteAddress + ":" + req.params.selPort + "/wd/hub";
fs.writeFileSync("/tmp/arrow_sel_server.status", selUrl);
res.end("Selenium captured at: " + selUrl, "utf-8");
});
var sessions = [];
var wdtasks = [];
var wdTaskCounter = 0;
// shared functions
function validateSession(req, res) {
var sessionId = req.params.sessionId,
body;
if (sessions.hasOwnProperty(sessionId)) { return true; }
body = {
status: 9,
value: "No such sessionId: " + sessionId
};
res.send(body, 404);
return false;
}
function queueWdTask(params, req, res) {
var sessionId = req.params.sessionId,
curTask,
body,
task,
conn,
session;
if (wdtasks.hasOwnProperty(sessionId)) {
curTask = wdtasks[sessionId];
if (curTask) {
body = {
status: 9,
value: "A command is still running for sessionId: " + sessionId
};
res.send(body, 500);
return false;
}
}
task = {
"id": "taskid-" + wdTaskCounter,
"params": params,
"statusCode": 0,
"httpCode": 200
};
wdtasks[sessionId] = {
"request": req,
"response": res,
"task": task
};
wdTaskCounter += 1;
session = sessions[sessionId];
session.response.send(task);
delete sessions[sessionId]; // we dont need this anymore
conn = req.connection;
conn.on("close", function () {
if (wdtasks.hasOwnProperty(sessionId)) {
if (debug) {
console.log("Task connection closed, deleting task for session: " + sessionId);
}
delete wdtasks[sessionId];
}
});
return true;
}
// browsers running webdriver sessions
app.post("/arrow/slave/:sessionId", function (req, res) {
var timestamp = (new Date()).getTime(),
sessionId = req.params.sessionId,
prevTask = req.body,
prevTaskInfo,
resBody,
oldSession,
conn;
if (debug) {
console.log("Agent response:");
console.log(req.body);
}
prevTask = req.body;
// a task is also completed, send it to wd client
// TODO: validate that the task id matches
if (prevTask && prevTask.id && (wdtasks.hasOwnProperty(sessionId))) {
prevTaskInfo = wdtasks[sessionId];
delete wdtasks[sessionId];
resBody = {
"status": prevTask.statusCode,
"sessionId": sessionId,
"value": prevTask.result
};
if (debug) {
console.log("Task result:");
console.log(resBody);
}
prevTaskInfo.response.send(resBody, prevTask.httpCode);
}
if (sessions.hasOwnProperty(sessionId)) {
if (debug) { console.log("Killing old connection for session: " + sessionId); }
oldSession = sessions[sessionId];
oldSession.response.end();
delete sessions[sessionId];
}
console.log("Session registered: " + sessionId);
sessions[sessionId] = {
"sessionId": sessionId,
"timestamp": timestamp,
"request": req,
"response": res
};
conn = req.connection;
conn.on("close", function () {
if (sessions.hasOwnProperty(sessionId)) {
oldSession = sessions[sessionId];
if (oldSession.timestamp === timestamp) {
if (debug) { console.log("Session deleted: " + sessionId); }
delete sessions[sessionId];
} else {
if (debug) { console.log("Session already recaptured: " + sessionId); }
}
}
});
});
// webdriver
// Query the server status
app.get("/wd/hub/status", function (req, res) {
var body;
res.contentType("application/json");
body = {
build: { version: "1.0" },
os: { name: "rhel" }
};
res.send(body);
});
// Create a new session
app.post("/wd/hub/session", function (req, res) {
res.contentType("application/json");
res.send({status: 9, value: "Create session: Not Implemented"}, 501);
});
// Get all sessions
app.get("/wd/hub/sessions", function (req, res) {
var sessionIds = [],
sessionId,
body;
res.contentType("application/json");
sessionIds = [];
for (sessionId in sessions) {
sessionIds.push({"id": sessionId});
}
body = {
status: 0,
value: sessionIds
};
res.send(body);
});
// Retrieve the capabilities of the specified session
app.get("/wd/hub/session/:sessionId", function (req, res) {
var body,
session;
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
session = sessions[req.params.sessionId];
body = {
status: 0,
sessionId: req.params.sessionId,
value: {
platform: "ANY",
cssSelectorsEnabled: true,
javascriptEnabled: true,
browserName: session.request.headers["user-agent"],
nativeEvents: true,
takesScreenshot: false,
version: 1
}
};
res.send(body);
});
// Delete the session
app.del("/wd/hub/session/:sessionId", function (req, res) {
res.contentType("application/json");
res.send({status: 9, value: "Delete session: Not Implemented"}, 501);
});
// Get the current page title
app.get("/wd/hub/session/:sessionId/title", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "title"}, req, res);
});
// Get the current page url
app.get("/wd/hub/session/:sessionId/url", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "url"}, req, res);
});
var revProxyHost = "";
var revProxyPort = 80;
// Navigate to the url
app.post("/wd/hub/session/:sessionId/url", function (req, res) {
var url,
reqParams,
reqHost,
reqPort;
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
url = req.body.url;
reqParams = urlParser.parse(url);
reqHost = reqParams.hostname;
reqPort = 80;
if (reqParams.port) { reqPort = reqParams.port; }
if ((reqHost === arrowHost) && (reqPort === arrowPort)) {
if (debug) { console.log("Reverse proxy disabled"); }
revProxyHost = "";
} else {
console.log("Reverse proxy enabled for: " + reqHost + ":" + reqPort);
revProxyHost = reqHost;
revProxyPort = reqPort;
url = arrowAddress + reqParams.pathname;
}
queueWdTask({"type": "navigate", "url": url}, req, res);
});
// Execute sync script
app.post("/wd/hub/session/:sessionId/execute", function (req, res) {
var script;
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
script = req.body.script;
queueWdTask({"type": "execute", "script": script}, req, res);
});
// Execute async script
app.post("/wd/hub/session/:sessionId/execute_async", function (req, res) {
res.contentType("application/json");
res.send({status: 9, value: "execute_async: Not Implemented"}, 501);
});
// find an element
app.post("/wd/hub/session/:sessionId/element", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "element", "using": req.body.using, "value": req.body.value}, req, res);
});
// find an element starting from
app.post("/wd/hub/session/:sessionId/element/:id/element", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "element", "element": req.params.id, "using": req.body.using, "value": req.body.value}, req, res);
});
// find elements
app.post("/wd/hub/session/:sessionId/elements", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "elements", "using": req.body.using, "value": req.body.value}, req, res);
});
// find elements starting from
app.post("/wd/hub/session/:sessionId/elements/:id/element", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "elements", "element": req.params.id, "using": req.body.using, "value": req.body.value}, req, res);
});
// get text of an element
app.get("/wd/hub/session/:sessionId/element/:id/text", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "text", "element": req.params.id}, req, res);
});
// get tag of an element
app.get("/wd/hub/session/:sessionId/element/:id/name", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "name", "element": req.params.id}, req, res);
});
// get attribute of an element
app.get("/wd/hub/session/:sessionId/element/:id/attribute/:name", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "attribute", "element": req.params.id, "name": req.params.name}, req, res);
});
// click on an element
app.post("/wd/hub/session/:sessionId/element/:id/click", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "click", "element": req.params.id}, req, res);
});
// submit a form
app.post("/wd/hub/session/:sessionId/element/:id/submit", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "submit", "element": req.params.id}, req, res);
});
// send key strokes to an element
app.post("/wd/hub/session/:sessionId/element/:id/value", function (req, res) {
res.contentType("application/json");
if (!validateSession(req, res)) { return; }
queueWdTask({"type": "value", "element": req.params.id, "value": req.body.value}, req, res);
});
function serveRevProxy(req, res) {
var options,
proxy_request;
if (debug) {
console.log("Reverse proxy is serving: http://" + revProxyHost + ":" + revProxyPort + req.url);
}
req.headers["X-Forwarded-For"] = req.connection.remoteAddress;
req.headers["Host"] = revProxyHost;
options = {
host: revProxyHost,
port: revProxyPort,
path: req.url,
method: req.method,
headers: req.headers
};
proxy_request = http.request(options, function (proxy_response) {
//send headers and data as received
res.writeHead(proxy_response.statusCode, proxy_response.headers);
proxy_response.addListener("data", function (chunk) {
res.write(chunk);
});
proxy_response.addListener("end", function () {
res.end();
});
});
//deal with errors, timeout, con refused, ...
proxy_request.on("error", function (err) {
res.writeHead(500);
res.end(err.toString(), "utf-8");
});
//proxies to SEND request to the real server
req.addListener("data", function (chunk) {
proxy_request.write(chunk);
});
req.addListener("end", function () {
proxy_request.end();
});
}
// default handling
app.get("*", function (req, res) {
var docRoot;
if (revProxyHost.length > 0) {
serveRevProxy(req, res);
} else {
docRoot = process.cwd();
if ("/" === docRoot) { docRoot = ""; }
serveStatic(docRoot + req.url, req, res);
}
});
//starting ghostdriver
function startGhostDriver() {
if (parsed["ghostPort"]) {
ghostPort = String(parsed["ghostPort"]);
}
if (ghostPort > 0 ) {
ghostPortMin = ghostPortMax = ghostPort;
}
var self = this;
portchecker.getFirstAvailable(arrowPort, ghostPortMax, "localhost", function(p, host) {
if (p === -1) {
console.log('No free ports found for GhostDriver on ' + host + ' between ' + arrowPort + ' and ' + ghostPortMax);
} else {
// console.log('the first free port found for Gost Driver on ' + host + ' between ' + arrowPort + ' and ' + ghostPortMax + ' is ' + p);
ghostPort = p;
self.child = childProcess.spawn("node", [__dirname + "/ghostdriverlauncher.js", p, arrowHost]);
self.child.stdout.on("data", function (data) {
console.log(data.toString());
});
self.child.stderr.on("data", function (data) {
console.error(data.toString());
});
}
});
}
function convertHostname(){
var interfaces = os.networkInterfaces();
for ( netInterface in interfaces){
var length = 'interfaces.' + netInterface + '.length';
for (var i = 0; i< eval(length); i ++) {
var isInternal = 'interfaces.' + netInterface + '[' + i + '].internal';
var ipFamily = 'interfaces.' + netInterface + '[' + i + '].family';
var ipAddress = 'interfaces.' + netInterface + '[' + i + '].address';
if ((eval(isInternal) == false) && (eval(ipFamily) == "IPv4") && (arrowHost == "localhost" )){
arrowHost = eval(ipAddress);
return;
}
}
}
}
function runArrowServer(port) {
app.listen(port);
arrowPort = port;
arrowAddress = "http://" + arrowHost + ":" + port;
console.log("Server running at: " + arrowAddress);
fs.writeFileSync(global.appRoot + "/tmp/arrow_server.status", arrowAddress);
startGhostDriver();
}
//starting arrow server
portchecker.getFirstAvailable(arrowPortMin, arrowPortMax, "localhost", function(p, host) {
if (p === -1) {
console.log('No free ports found for arrow server on ' + host + ' between ' + arrowPortMin + ' and ' + arrowPortMax);
} else {
// console.log('The first free port found for arrow server on ' + host + ' between ' + arrowPortMin + ' and ' + arrowPortMax + ' is ' + p);
arrowPort = p;
runArrowServer(p);
}
});
process.on("uncaughtException", function (err) {
console.log("Uncaught exception: " + err);
process.exit();
});
process.on("SIGINT", function () {
process.exit();
});
process.on("exit", function (err) {
cleanUp();
});