This repository has been archived by the owner on Jun 1, 2021. It is now read-only.
/
netsniff.js
260 lines (220 loc) · 7.95 KB
/
netsniff.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
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function() {
function pad(n) {
return n < 10 ? '0' + n : n;
}
function ms(n) {
return n < 10 ? '00' + n : n < 100 ? '0' + n : n
}
return this.getFullYear() + '-' +
pad(this.getMonth() + 1) + '-' +
pad(this.getDate()) + 'T' +
pad(this.getHours()) + ':' +
pad(this.getMinutes()) + ':' +
pad(this.getSeconds()) + '.' +
ms(this.getMilliseconds()) + 'Z';
}
}
function isRedirect(reply) {
return [301, 302].indexOf(reply.status) >= 0;
}
function getHeaderValue(reply, name) {
var nameLowerCase = name.toLowerCase(),
value = reply.headers.reduce(function(prev, header) {
if (header.name.toLowerCase() === nameLowerCase) {
return header.value;
}
return prev;
}, null);
return value;
}
function createHAR(address, title, startTime, resources, msg) {
var entries = [];
resources.forEach(function(resource) {
var request = resource.request,
startReply = resource.startReply,
endReply = resource.endReply;
// if (!request || !startReply || !endReply) {
// return;
// }
startReply = startReply || {};
startReply.bodySize = startReply.bodySize || -1;
endReply = endReply || {};
endReply.bodySize = endReply.bodySize || -1;
// Exclude Data URI from HAR file because
// they aren't included in specification
if (request.url.match(/^data:[a-z;,]/i)) {
return;
}
entries.push({
startedDateTime: request.time.toISOString(),
time: endReply.time - request.time,
request: {
method: request.method,
url: request.url,
httpVersion: "HTTP/1.1",
cookies: [],
headers: request.headers,
queryString: [],
headersSize: -1,
bodySize: -1,
comment: request.comment
},
response: {
status: endReply.status,
statusText: endReply.statusText,
httpVersion: null,
cookies: [],
headers: endReply.headers,
redirectURL: (isRedirect(endReply) && getHeaderValue(endReply, "Location")) || "",
headersSize: -1,
bodySize: startReply.bodySize,
content: {
size: startReply.bodySize,
mimeType: endReply.contentType
},
comment: [startReply.comment, endReply.comment].join("\n").trim()
},
cache: {},
timings: {
blocked: 0,
dns: -1,
connect: -1,
send: 0,
wait: startReply.time - request.time,
receive: endReply.time - startReply.time,
ssl: -1
},
pageref: address
});
});
return {
log: {
version: '1.2',
creator: {
name: "PhantomJS",
version: phantom.version.major + '.' + phantom.version.minor + '.' + phantom.version.patch
},
pages: [{
startedDateTime: startTime.toISOString(),
id: address,
title: title,
pageTimings: {
onLoad: page.endTime - page.startTime
}
}],
entries: entries,
comment: msg
}
};
}
function exitWithErrorMessage(msg) {
function asyncExit() {
console.log("FAIL: " + msg);
if (page) {
try {
page.close();
} catch (e) {
console.log("FAIL: Could not close the page; " + e);
}
}
phantom.exit(1);
}
var timerId = setTimeout(asyncExit, 100);
}
function exitAfterTimeout(timeout) {
function loadTimeout() {
return exitWithErrorMessage('Could not completely load the address; timeout after ' + timeout + ' milliseconds.');
}
var timerId = setTimeout(loadTimeout, timeout);
}
function buildErrorResponse(errorObject) {
var response = {
// http://www.softwareishard.com/blog/har-12-spec/#response
// http://phantomjs.org/api/webpage/handler/on-resource-received.html
"status": errorObject.status || errorObject.errorCode || -1,
"statusText": errorObject.statusText || errorObject.errorString || null,
"httpVersion": errorObject.httpVersion || null,
"cookies": errorObject.cookies || [],
"headers": errorObject.headers || [],
"content": errorObject.content || {},
"redirectURL": errorObject.redirectURL || "",
"headersSize": errorObject.headersSize || -1,
"bodySize": errorObject.bodySize || -1,
"comment": errorObject.comment || "",
// http://phantomjs.org/api/webpage/handler/on-resource-timeout.html
// http://phantomjs.org/api/webpage/handler/on-resource-error.html
"id": errorObject.id,
"method": errorObject.method,
"url": errorObject.url,
"time": errorObject.time,
"errorCode": errorObject.errorCode,
"errorString": errorObject.errorString
};
return response;
}
var page = require('webpage').create(),
system = require('system'),
DEFAULT_PAGE_TIMEOUT = 60000,
DEFAULT_RESOURCE_TIMEOUT = 30000,
errorMessages = [];
if (system.args.length === 1) {
console.log('Usage: netsniff.js <some URL>');
phantom.exit(1);
} else {
page.address = system.args[1];
page.resources = [];
page.settings.resourceTimeout = DEFAULT_RESOURCE_TIMEOUT;
page.onLoadStarted = function() {
page.startTime = new Date();
};
page.onResourceRequested = function(req) {
page.resources[req.id] = {
request: req,
startReply: null,
endReply: null
};
};
page.onError = function(msg, trace) {
// Used to catch Javascript errors on the loaded page
errorMessages.push("JavaScript: An error occured; " + msg);
};
page.onResourceError = function(req) {
var originalRequest = page.resources[req.id],
msg = 'Could not load the resource; ' + req.errorCode + " \"" + req.errorString + "\" " + req.url,
response = buildErrorResponse(req);
response.comment = (( !! response.comment) ? response.comment + "\n" + msg : msg);
originalRequest.endReply = response;
};
page.onResourceTimeout = function(req) {
var originalRequest = page.resources[req.id],
msg = 'Could not load the resource; timeout after ' + page.settings.resourceTimeout + ' milliseconds ' + req.errorCode + " \"" + req.errorString + "\" " + req.url,
response = buildErrorResponse(req);
response.comment = (( !! response.comment) ? response.comment + "\n" + msg : msg);
originalRequest.startReply = response;
};
page.onResourceReceived = function(res) {
if (res.stage === 'start') {
page.resources[res.id].startReply = res;
}
if (res.stage === 'end') {
page.resources[res.id].endReply = res;
}
};
page.open(page.address, function(status) {
var har,
msg;
if (status !== 'success') {
errorMessages.push('Page: Could not load the address; ' + page.address);
}
page.endTime = new Date();
page.title = page.evaluate(function() {
return document.title;
});
msg = errorMessages ? errorMessages.join("\n") : undefined;
har = createHAR(page.address, page.title, page.startTime, page.resources, msg);
console.log(JSON.stringify(har, undefined, 4));
phantom.exit();
});
exitAfterTimeout(DEFAULT_PAGE_TIMEOUT);
}