Permalink
Browse files

updated

  • Loading branch information...
1 parent 50ec89e commit d58e3f2065fa0013345229c7766207e8cdeebf67 @rehorn committed Apr 4, 2013
Showing with 2,169 additions and 85 deletions.
  1. 0 {lib → }/keys/cert.pem
  2. 0 {lib → }/keys/key.pem
  3. +122 −48 lib/core.js
  4. +52 −3 lib/livepool/config.js
  5. +4 −0 lib/livepool/event.js
  6. +14 −17 lib/livepool/logger.js
  7. 0 lib/livepool/{responders → responder}/combo.js
  8. 0 lib/livepool/{responders → responder}/index.js
  9. +27 −0 lib/livepool/responder/local.js
  10. 0 lib/livepool/{responders → responder}/proxy.js
  11. 0 lib/livepool/{responders → responder}/qzmin.js
  12. 0 lib/livepool/{responders → responder}/remote.js
  13. +2 −5 lib/livepool/util.js
  14. +5 −12 lib/rules/project1.js
  15. +22 −0 lib/rules/project2.js
  16. +2 −0 lib/rules/readme.md
  17. BIN lib/template/200_FiddlerGif.dat
  18. +5 −0 lib/template/200_SimpleHTML.dat
  19. BIN lib/template/200_TransPixel.dat
  20. +4 −0 lib/template/204_NoContent.dat
  21. +5 −0 lib/template/302_Redirect.dat
  22. +5 −0 lib/template/303_RedirectWithGet.dat
  23. +4 −0 lib/template/304_NotModified.dat
  24. +5 −0 lib/template/307_RedirectWithMethod.dat
  25. +7 −0 lib/template/401_AuthBasic.dat
  26. +7 −0 lib/template/401_AuthDigest.dat
  27. +5 −0 lib/template/403_AuthDeny.dat
  28. +6 −0 lib/template/404_Plain.dat
  29. +7 −0 lib/template/407_ProxyAuthBasic.dat
  30. +6 −0 lib/template/502_Unreachable.dat
  31. 0 lib/livepool/responders/local.js → log/log.txt
  32. +1 −0 log/req.js
  33. +19 −0 node_modules/mime/LICENSE
  34. +63 −0 node_modules/mime/README.md
  35. +104 −0 node_modules/mime/mime.js
  36. +36 −0 node_modules/mime/package.json
  37. +55 −0 node_modules/mime/test.js
  38. +1,510 −0 node_modules/mime/types/mime.types
  39. +65 −0 node_modules/mime/types/node.types
File renamed without changes.
File renamed without changes.
View
@@ -1,16 +1,32 @@
var http = require('http'),
+ https = require('https'),
httpProxy = require('http-proxy'),
proxy = new httpProxy.RoutingProxy(),
- httpSever;
+ fs = require('fs'),
+ net = require('net'),
+ url = require('url'),
+ _ = require('underscore');
+
+var path = require('path')
+
+var httpServer, httpsServer, https2http;
var livepool = module.exports = {};
livepool.verson = '0.0.1';
livepool.startTime = (new Date()).getTime();
var config = liveRequire('config'),
logger = liveRequire('logger'),
- util = liveRequire('util');
+ util = liveRequire('util'),
+ eventCenter = liveRequire('event');
+
+var global = config.global,
+ httpPort = global.http,
+ httpsPort = global.https,
+ proxyAgent = global.proxy || '',
+ proxyAgent = proxyAgent.split(':'),
+ localName = 'localhost';
function publish(source, methodName, newMethodName) {
livepool[newMethodName || methodName] = source[methodName].bind(source);
@@ -20,60 +36,118 @@ function liveRequire(module){
return livepool[module] = require('./livepool/' + module);
}
-livepool.run = function(){
- var httpPort = config.http,
- proxyPort = config.proxy;
-
+livepool.run = function (){
logger.writeline();
logger.log('livepool'.cyan + ' is running, port: ' + String(httpPort).cyan);
- // httpSever = http.createServer(function(req, res){
- // var project1 = require('./rules/project1');
- // host = req.headers.host,
- // hostRouter = _.clone(defaultRouter);
-
- // _.extend(hostRouter, config.hostRouter);
+ var options = {
+ key: fs.readFileSync('keys/key.pem'),
+ cert: fs.readFileSync('keys/cert.pem')
+ };
+
+ var project1 = require('./rules/project1');
+ var handler = project1.handler;
+ var arr = [];
+ var tmp = _.each(handler, function(item){
+ item.match = item.match || '';
+ var split = item.match.split(/\s+/);
+ _.each(split, function(s){
+ arr.push({
+ base: project1.base,
+ match: s.replace(/\./g, '\\.').replace(/\*/g, '.*'),
+ action: item.action,
+ enabled: item.enabled
+ });
+ });
+ });
+ console.log('arr:', arr);
+ httpServer = http.createServer(function (req, res){
+ var host = req.headers.host;
+ var reqUrl = url.parse(req.url);
+ var pathname = reqUrl.pathname;
+
+ var find = _.find(arr, function(item){
+ return new RegExp(item.match).test(req.url);
+ });
+ if(find){
+ var filepath = path.resolve(find.base, pathname.substring(1));
+ console.log(filepath);
+ if(fs.existsSync(filepath)){
+ var responder = require('./livepool/responder/local');
+ responder(filepath, req, res);
+ }else{
+ proxy.proxyRequest(req, res, {
+ host: proxyAgent[0] || host,
+ port: proxyAgent[1] || 80
+ });
+ }
+ }else{
+ proxy.proxyRequest(req, res, {
+ host: proxyAgent[0] || host,
+ port: proxyAgent[1] || 80
+ });
+ }
- // if(hostRouter && hostRouter[host]){
- // var url = req.url,
- // mapRules = config.mapRules, i;
-
- // if(!forwardList.exec(url) && ~(i = testRules(req.url, config.mapRules))){
- // console.log('[%s] request %s', req.connection.remoteAddress, url);
- // var map = mapRules[i];
- // isHttpType(map.target) ?
- // httpHanlder(req, res, map) : localHanlder(req, res, map)
- // }else{
- // var target = hostRouter[host].split(':');
- // proxy.proxyRequest(req, res, {
- // host: target[0] || "127.0.0.1",
- // port: target[1] || 80
- // });
- // }
- // }else{
- // res.end('Please add this domain router in the config file first.');
- // }
- // res.writeHead(200, { 'Content-Type': 'text/plain' });
- // res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
- // res.end();
- // });
- // httpSever.listen(httpPort);
-
- httpProxy.createServer(function (req, res, proxy) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
- res.end();
-
- // proxy.proxyRequest(req, res, {
- // host: 'localhost',
- // port: 9000
- // });
- }).listen(8000);
+ }).listen(httpPort);
+
+ https2http = new httpProxy.HttpProxy({
+ target: {
+ host: localName,
+ port: httpPort
+ }
+ });
+
+ httpsServer = https.createServer(options, function (req, res){
+ console.log('https request proxied...');
+ https2http.proxyRequest(req, res);
+ }).listen(httpsPort);
+
+ proxyHttps();
+};
+// proxy https request from httpServer to httpsServer, stolen form nproxy
+function proxyHttps() {
+ httpServer.on('connect', function(req, socket, upgradeHead) {
+ var netClient = net.createConnection(httpsPort);
+
+ netClient.on('connect', function() {
+ // logger.info('connect to https server successfully!');
+ socket.write("HTTP/1.1 200 Connection established\r\nProxy-agent: Netscape-Proxy/1.1\r\n\r\n");
+ });
+
+ socket.on('data', function(chunk) {
+ netClient.write(chunk);
+ });
+ socket.on('end', function() {
+ netClient.end();
+ });
+ socket.on('close', function() {
+ netClient.end();
+ });
+ socket.on('error', function(err) {
+ logger.error('socket error ' + err.message);
+ netClient.end();
+ });
+
+ netClient.on('data', function(chunk) {
+ socket.write(chunk);
+ });
+ netClient.on('end', function() {
+ socket.end();
+ });
+ netClient.on('close', function() {
+ socket.end();
+ });
+ netClient.on('error', function(err) {
+ logger.error('netClient error ' + err.message);
+ socket.end();
+ });
+
+ });
};
-livepool.stop = function(){
+livepool.stop = function (){
if(httpSever){
httpSever.close();
}
View
@@ -1,5 +1,54 @@
-module.exports = {
+var config = module.exports = {};
+
+var eventCenter;
+
+config.init = function (eventCenter){
+ eventCenter = eventCenter;
+};
+
+config.global = {
http: 8000,
- proxy: 9000
-};
+ https: 8001,
+ proxy: "proxy.tencent.com:8080"
+};
+
+config.ruleGroup = {
+ name: "__project__",
+ index: 0,
+ enabled: 0,
+ base: '',
+ host: '*',
+ // handleAll: 0, // 本地找不到替换版本,直接proxy代理线上
+ handler: [],
+ router: []
+};
+
+config.ruleGroups = [];
+
+config.readConfig = function(){
+
+};
+
+config.updateConfig = function(config){
+
+};
+
+config.getAllHandlers = function(ruleGroups){
+ if(!_.isArray(ruleGroups)) {
+ ruleGroups = [ruleGroups];
+ }
+ _.each(ruleGroups, function(group){
+
+ });
+};
+
+config.getHandler = function(reqUrl){
+
+};
+
+config.getRouter = function(reqUrl){
+
+};
+
+
View
@@ -0,0 +1,4 @@
+
+var EventEmitter = require('events').EventEmitter;
+
+module.exports = new EventEmitter();
View
@@ -5,20 +5,11 @@
*/
var util = require('util'),
- colors = require('colors');
+ colors = require('colors'),
+ fs = require('fs');
-/**
- * The level to log at, change this to alter the global logging level.
- * Possible options are: error, warning, info, debug. Default level is info.
- */
exports.level = 'info';
-/**
- * Executes a function only if the current log level is in the levels list
- *
- * @param {Array} levels
- * @param {Function} fn
- */
var forLevels = function(levels, fn) {
return function(label, val) {
for (var i = 0; i < levels.length; i++) {
@@ -102,21 +93,27 @@ exports.end = function(msg) {
exports.success(msg);
};
exports.success = function(msg) {
- //console.log(('\n' +'OK'.bold + (msg ? ': '.bold + msg: '')).green);
+ exports.log(('\n' +'OK'.bold + (msg ? ': '.bold + msg: '')).green);
};
var _onExit = function() {
if (!exports.clean_exit) {
- //console.log('\n' +'Failed'.bold.red);
+ exports.log('\n' +'Failed'.bold.red);
process.removeListener('exit', _onExit);
process.exit(1);
}
};
process.on('exit', _onExit);
-/**
- * Log uncaught exceptions in the same style as normal errors.
- */
process.on('uncaughtException', function(err) {
- exports.error(err.stack || err);
+ // exports.error(err.stack || err);
+ exports.error('uncaughtException: ' + (err.stack || err));
+
+ try{
+ fs.appendFile('log/log.txt', '\r\n' + (err.stack || err), function (err) {
+ if (err) throw err;
+ });
+ }catch(e){
+ exports.error(e);
+ }
});
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,27 @@
+
+var fs =require('fs');
+var mime =require('mime');
+
+function localFileResponder(filePath, req, res, next) {
+ // if (!utils.isAbsolutePath(filePath)) {
+ // throw new Error('Not a valid file path');
+ // }
+
+ fs.stat(filePath, function(err, stat) {
+ if (err) {
+ throw err;
+ }
+ if (!stat.isFile()) {
+ throw new Error('The responder is not a file!');
+ }
+
+ res.statusCode = 200;
+ res.setHeader('Content-Length', stat.size);
+ res.setHeader('Content-Type', mime.lookup(filePath));
+ res.setHeader('Server', 'nproxy');
+
+ fs.createReadStream(filePath).pipe(res);
+ });
+};
+
+module.exports = localFileResponder;
File renamed without changes.
File renamed without changes.
View
@@ -1,11 +1,8 @@
var _ = require('underscore'),
- path = require('path');
+ path = require('path'),
+ fs = require('fs');
var util = module.exports = {};
util._ = _;
-
-/**
- * wildcard
- */
View
@@ -2,17 +2,15 @@ module.exports = {
name: "project1",
index: 0,
enabled: 1,
- global: {
- base: "E:\connect\bapp\widget_trunk\web\chat\src",
- host: "*chat.qq.com *.url.cn",
- handleAll: 0
- },
+ base: "E:/connect/bapp/widget_trunk/web/chat/src",
+ // host: "*chat.qq.com *.url.cn",
+ // handleAll: 0,
handler: [{
match: "chat.qq.com",
action: "./",
enabled: 1
}, {
- match: "*.url.cn",
+ match: "*.url.cn/chat/",
action: "./",
enabled: 1
}],
@@ -24,10 +22,5 @@ module.exports = {
match: "chat.qq.com",
action: "172.23.136.86",
enabled: 1
- }],
- plugin: {
- backend: {
-
- }
- }
+ }]
};
Oops, something went wrong.

0 comments on commit d58e3f2

Please sign in to comment.