forked from liangqing/PacProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProxyServer.js
88 lines (82 loc) · 2.64 KB
/
ProxyServer.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
var Net = require('net')
, Http = require('http')
, Https = require('https')
, Socks = require('./lib/socks')
, Request = require('./lib/request')
, defaultConfig = {
server: {
type: 'socks'
, host: '127.0.0.1'
, port: 9999
}
, pac: {
path: 'autoproxy.pac'
, disableDNS: false
}
, logger: {
level: 'info'
}
}
, router , logger, config
try {
config = require('./lib/class').extend(true, {}, defaultConfig, require('./config').config)
} catch(err) {
console.log('Failed to load config file, use default configuration')
config = defaultConfig
}
logger = require('./lib/log').create(config.logger)
router = require('./lib/router').create(config.pac)
.on('proxyFound', function(request, proxy) {
logger.info('Proxy('+JSON.stringify(proxy)+') found for '+request)
})
.on('proxyConnected', function(request, proxy) {
if(proxy.type === 'direct') {
logger.info('Connected to '+request)
} else {
logger.info('Connected to proxy '+JSON.stringify(proxy)+' for '+request)
}
})
.on('proxyUnsupported', function(request, proxy) {
logger.error('Unsupported proxy type: '+proxy.type)
})
.on('remoteClose', function(request) {
logger.info('Remote connection ended: '+request)
})
.on('error', function(request, err) {
if(err.syscall == 'getaddrinfo') {
logger.error("Failed to resolve host '"+request.host+"': "+JSON.stringify(err))
} else {
logger.error(JSON.stringify(err)+', request: '+request)
}
})
Socks.server(config.server, function() {
var client = this.remoteAddress+':'+this.remotePort
, isForwarded = false, address
logger.info('New socks connection from '+client)
this
.on('request', function(ad) {
address = ad
logger.debug('Socks request('+address+')'+' from '+client)
//cheat the client that every thing is ok
this.reply(0, this.address())
//Do not need guess request by incoming data
if(address.port === 22 || address.port === 23 || address.port === 443) {
router.forward(Request.socks(this, address.host, address.port, this.remoteAddress, this.remotePort))
isForwarded = true
}
})
.on('data', function(data) {
if(isForwarded) return
router.forward(Request.socks(this, address.host, address.port, this.remoteAddress, this.remotePort, data))
isForwarded = true
})
.on('error', function(err) {
logger.error('Error occurs in client connection('+address.host+':'+address.port+'):'+JSON.stringify(err))
})
.on('end', function() {
logger.debug('Socks connection ended from '+client)
})
})
.on('error', function(err) {
logger.error('Error occurs in socks server:'+JSON.stringify(err))
})