anyproxy/proxy.js

74 lines
2.4 KiB
JavaScript
Raw Normal View History

2014-08-11 16:43:14 +08:00
var http = require('http'),
https = require('https'),
fs = require('fs'),
net = require('net'),
async = require("async"),
url = require('url'),
exec = require('child_process').exec,
program = require('commander'),
2014-08-13 11:51:39 +08:00
color = require('colorful'),
certMgr = require("./lib/certMgr"),
2014-08-11 16:43:14 +08:00
requestHandler = require("./lib/requestHandler");
var T_TYPE_HTTP = 0,
T_TYPE_HTTPS = 1,
DEFAULT_PORT = 8001,
DEFAULT_HOST = "localhost",
DEFAULT_TYPE = T_TYPE_HTTP;
2014-08-13 11:51:39 +08:00
var httpProxyServer;
2014-08-11 16:43:14 +08:00
2014-08-13 11:51:39 +08:00
function startServer(type, port, hostname,rule){
2014-08-11 16:43:14 +08:00
var proxyType = /https/i.test(type || DEFAULT_TYPE) ? T_TYPE_HTTPS : T_TYPE_HTTP ,
proxyPort = port || DEFAULT_PORT,
proxyHost = hostname || DEFAULT_HOST;
2014-08-13 11:51:39 +08:00
requestHandler.setRules(rule);
2014-08-11 16:43:14 +08:00
async.series([
2014-08-13 11:51:39 +08:00
//creat proxy server
2014-08-11 16:43:14 +08:00
function(callback){
if(proxyType == T_TYPE_HTTPS){
2014-08-11 17:48:32 +08:00
certMgr.getCertificate(proxyHost,function(err,keyContent,crtContent){
2014-08-11 16:43:14 +08:00
if(err){
callback(err);
}else{
httpProxyServer = https.createServer({
key : keyContent,
cert: crtContent
2014-08-13 11:51:39 +08:00
},requestHandler.userRequestHandler);
2014-08-11 16:43:14 +08:00
callback(null);
}
});
}else{
2014-08-13 11:51:39 +08:00
httpProxyServer = http.createServer(requestHandler.userRequestHandler);
2014-08-11 16:43:14 +08:00
callback(null);
}
},
//listen CONNECT method for https over http
function(callback){
2014-08-13 11:51:39 +08:00
httpProxyServer.on('connect',requestHandler.connectReqHandler);
2014-08-11 16:43:14 +08:00
httpProxyServer.listen(proxyPort);
callback(null);
}
],
//final callback
function(err,result){
if(!err){
2014-08-13 11:51:39 +08:00
var tipText = (proxyType == T_TYPE_HTTP ? "Http" : "Https") + " proxy started at port " + proxyPort;
console.log(color.green(tipText));
2014-08-11 16:43:14 +08:00
}else{
2014-08-13 11:51:39 +08:00
var tipText = "err when start proxy server :(";
console.log(color.red(tipText));
2014-08-11 16:43:14 +08:00
console.log(err);
}
}
);
}
2014-08-13 11:51:39 +08:00
module.exports.startServer = startServer;