forked from twleung/nodejs-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
executable file
·102 lines (89 loc) · 2.55 KB
/
proxy.js
File metadata and controls
executable file
·102 lines (89 loc) · 2.55 KB
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
/*
** Peteris Krumins (peter@catonmat.net)
** http://www.catonmat.net -- good coders code, great reuse
**
** A simple proxy server written in node.js.
**
*/
var http = require('http');
var sys = require('sys');
var fs = require('fs');
var blacklist = [];
var iplist = [];
fs.watchFile('./blacklist', function(c,p) { update_blacklist(); });
fs.watchFile('./iplist', function(c,p) { update_iplist(); });
function update_blacklist() {
fs.stat('./blacklist', function(err, stats) {
if (!err) {
sys.log("Updating blacklist.");
blacklist = fs.readFileSync('./blacklist').split('\n')
.filter(function(rx) { return rx.length })
.map(function(rx) { return RegExp(rx) });
}
});
}
function update_iplist() {
fs.stat('./iplist', function(err, stats) {
if (!err) {
sys.log("Updating iplist.");
iplist = fs.readFileSync('./iplist').split('\n')
.filter(function(rx) { return rx.length });
}
});
}
function ip_allowed(ip) {
for (i in iplist) {
if (iplist[i] == ip) {
return true;
}
}
return false;
}
function host_allowed(host) {
for (i in blacklist) {
if (blacklist[i].test(host)) {
return false;
}
}
return true;
}
function deny(response, msg) {
response.writeHead(401);
response.write(msg);
response.end();
}
http.createServer(function(request, response) {
var ip = request.connection.remoteAddress;
if (!ip_allowed(ip)) {
msg = "IP " + ip + " is not allowed to use this proxy";
deny(response, msg);
sys.log(msg);
return;
}
if (!host_allowed(request.url)) {
msg = "Host " + request.url + " has been denied by proxy configuration";
deny(response, msg);
sys.log(msg);
return;
}
sys.log(ip + ": " + request.method + " " + request.url);
var proxy = http.createClient(80, request.headers['host'])
var proxy_request = proxy.request(request.method, request.url, request.headers);
proxy_request.addListener('response', function(proxy_response) {
proxy_response.addListener('data', function(chunk) {
response.write(chunk);
});
proxy_response.addListener('end', function() {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
request.addListener('data', function(chunk) {
proxy_request.write(chunk);
});
request.addListener('end', function() {
proxy_request.end();
});
}).listen(8080);
update_blacklist();
update_iplist();