-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_pool.py
173 lines (157 loc) · 6.18 KB
/
server_pool.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 clowwindy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import logging
import utils
import time
import eventloop
import tcprelay
import udprelay
import asyncdns
import thread
import threading
import sys
import asyncmgr
import Config
import hashlib
import httplib
import urllib
from socket import *
class ServerPool(object):
instance = None
def __init__(self):
utils.check_python()
self.config = utils.get_config(False)
utils.print_shadowsocks()
self.dns_resolver = asyncdns.DNSResolver()
self.mgr = asyncmgr.ServerMgr()
self.tcp_servers_pool = {}
#self.udp_servers_pool = {}
self.loop = eventloop.EventLoop()
thread.start_new_thread(ServerPool._loop, (self.loop, self.dns_resolver, self.mgr))
@staticmethod
def get_instance():
if ServerPool.instance is None:
ServerPool.instance = ServerPool()
return ServerPool.instance
@staticmethod
def _loop(loop, dns_resolver, mgr):
try:
mgr.add_to_loop(loop)
dns_resolver.add_to_loop(loop)
loop.run()
except (KeyboardInterrupt, IOError, OSError) as e:
logging.error(e)
import traceback
traceback.print_exc()
os.exit(0)
def server_is_run(self, port):
port = int(port)
if port in self.tcp_servers_pool:
return True
return False
def new_server(self, port, password):
port = int(port)
logging.info("start server at %d" % port)
try:
udpsock = socket(AF_INET, SOCK_DGRAM)
udpsock.sendto('%s:%s:%s:1' % (Config.MANAGE_PASS, port, password), (Config.MANAGE_BIND_IP, Config.MANAGE_PORT))
udpsock.close()
except Exception, e:
logging.warn(e)
return True
def cb_new_server(self, port, password):
ret = True
port = int(port)
if 'server' in self.config:
if port in self.tcp_servers_pool:
logging.info("server already at %s:%d" % (self.config['server'], port))
return 'this port server is already running'
else:
a_config = self.config.copy()
a_config['server_port'] = port
a_config['password'] = password
try:
logging.info("starting server at %s:%d" % (a_config['server'], port))
tcp_server = tcprelay.TCPRelay(a_config, self.dns_resolver, False)
tcp_server.add_to_loop(self.loop)
self.tcp_servers_pool[port] = tcp_server
#udp_server = udprelay.UDPRelay(a_config, self.dns_resolver, False)
#udp_server.add_to_loop(self.loop)
#self.udp_servers_pool.update({port: udp_server})
except Exception, e:
logging.warn(e)
return True
def del_server(self, port):
port = int(port)
logging.info("del server at %d" % port)
try:
m5 = hashlib.md5()
m5.update(str(port)+"ADSL.2015")
sign = m5.hexdigest()
if Config.API_HOST and Config.API_EVENT_DEL_SERVER :
data = urllib.urlencode({'port': port, 'sign': sign})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection(Config.API_HOST)
conn.request('POST', Config.API_EVENT_DEL_SERVER, data, headers)
conn.getresponse()
conn.close()
udpsock = socket(AF_INET, SOCK_DGRAM)
udpsock.sendto('%s:%s:0:0' % (Config.MANAGE_PASS, port), (Config.MANAGE_BIND_IP, Config.MANAGE_PORT))
udpsock.close()
except Exception, e:
logging.warn(e)
return True
def cb_del_server(self, port):
port = int(port)
if port not in self.tcp_servers_pool:
logging.info("stopped server at %s:%d already stop" % (self.config['server'], port))
else:
logging.info("stopped server at %s:%d" % (self.config['server'], port))
try:
server = self.tcp_servers_pool[port]
del self.tcp_servers_pool[port]
server.destroy()
except Exception, e:
logging.warn(e)
return True
def get_servers_transfer(self):
ret = {}
#this is different thread but safe
servers = self.tcp_servers_pool.copy()
for port in servers.keys():
ret[port] = [servers[port].server_transfer_ul, servers[port].server_transfer_dl]
return ret
if __name__ == '__main__':
port=12345
m5 = hashlib.md5()
m5.update(str(port)+"ADSL.2015")
sign = m5.hexdigest()
data = urllib.urlencode({'port': port, 'sign': sign})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection(Config.API_HOST)
conn.request('POST', Config.API_EVENT_DEL_SERVER, data,headers)
response = conn.getresponse()
print response.read()
conn.close()