Python port of ShadowsocksR
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

392 lines
15 KiB

11 years ago
#!/usr/bin/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 time
import socket
import logging
import encrypt
import errno
11 years ago
import eventloop
from common import parse_header
11 years ago
CMD_CONNECT = 1
11 years ago
# local:
# stage 0 init
# stage 1 hello received, hello sent
# stage 4 addr received, reply sent
# stage 5 remote connected
# remote:
# stage 0 init
# stage 4 addr received, reply sent
# stage 5 remote connected
11 years ago
STAGE_INIT = 0
STAGE_HELLO = 1
STAGE_REPLY = 4
STAGE_STREAM = 5
# stream direction
STREAM_UP = 0
STREAM_DOWN = 1
# stream status
11 years ago
STATUS_WAIT_INIT = 0
STATUS_WAIT_READING = 1
STATUS_WAIT_WRITING = 2
11 years ago
STATUS_WAIT_READWRITING = STATUS_WAIT_READING | STATUS_WAIT_WRITING
11 years ago
BUF_SIZE = 8 * 1024
11 years ago
class TCPRelayHandler(object):
11 years ago
def __init__(self, fd_to_handlers, loop, local_sock, config, is_local):
11 years ago
self._fd_to_handlers = fd_to_handlers
self._loop = loop
11 years ago
self._local_sock = local_sock
self._remote_sock = None
11 years ago
self._config = config
self._is_local = is_local
11 years ago
self._stage = STAGE_INIT
11 years ago
self._encryptor = encrypt.Encryptor(config['password'],
config['method'])
self._data_to_write_to_local = []
self._data_to_write_to_remote = []
11 years ago
self._upstream_status = STATUS_WAIT_READING
11 years ago
self._downstream_status = STATUS_WAIT_INIT
11 years ago
fd_to_handlers[local_sock.fileno()] = self
local_sock.setblocking(False)
11 years ago
local_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
11 years ago
loop.add(local_sock, eventloop.POLL_IN | eventloop.POLL_ERR)
11 years ago
11 years ago
def update_stream(self, stream, status):
dirty = False
if stream == STREAM_DOWN:
if self._downstream_status != status:
self._downstream_status = status
dirty = True
elif stream == STREAM_UP:
if self._upstream_status != status:
self._upstream_status = status
dirty = True
if dirty:
if self._local_sock:
event = eventloop.POLL_ERR
11 years ago
if self._downstream_status & STATUS_WAIT_WRITING:
11 years ago
event |= eventloop.POLL_OUT
11 years ago
if self._upstream_status & STATUS_WAIT_READING:
11 years ago
event |= eventloop.POLL_IN
self._loop.modify(self._local_sock, event)
if self._remote_sock:
event = eventloop.POLL_ERR
11 years ago
if self._downstream_status & STATUS_WAIT_READING:
11 years ago
event |= eventloop.POLL_IN
11 years ago
if self._upstream_status & STATUS_WAIT_WRITING:
11 years ago
event |= eventloop.POLL_OUT
self._loop.modify(self._remote_sock, event)
11 years ago
11 years ago
def write_all_to_sock(self, data, sock):
11 years ago
if not data or not sock:
return
uncomplete = False
try:
l = len(data)
s = sock.send(data)
if s < l:
data = data[s:]
uncomplete = True
except (OSError, IOError) as e:
error_no = eventloop.errno_from_exception(e)
if error_no in (errno.EAGAIN, errno.EINPROGRESS):
uncomplete = True
else:
logging.error(e)
self.destroy()
if uncomplete:
if sock == self._local_sock:
self._data_to_write_to_local.append(data)
self.update_stream(STREAM_DOWN, STATUS_WAIT_WRITING)
elif sock == self._remote_sock:
self._data_to_write_to_remote.append(data)
self.update_stream(STREAM_UP, STATUS_WAIT_WRITING)
else:
logging.error('write_all_to_sock:unknown socket')
11 years ago
else:
if sock == self._local_sock:
self.update_stream(STREAM_DOWN, STATUS_WAIT_READING)
elif sock == self._remote_sock:
self.update_stream(STREAM_UP, STATUS_WAIT_READING)
else:
logging.error('write_all_to_sock:unknown socket')
11 years ago
def on_local_read(self):
11 years ago
# TODO update timeout
11 years ago
if not self._local_sock:
return
is_local = self._is_local
11 years ago
data = None
try:
data = self._local_sock.recv(BUF_SIZE)
except (OSError, IOError) as e:
if eventloop.errno_from_exception(e) in \
(errno.ETIMEDOUT, errno.EAGAIN):
return
if not data:
self.destroy()
return
11 years ago
if not is_local:
data = self._encryptor.decrypt(data)
11 years ago
if not data:
return
11 years ago
if self._stage == STAGE_STREAM:
11 years ago
if self._is_local:
data = self._encryptor.encrypt(data)
11 years ago
self.write_all_to_sock(data, self._remote_sock)
11 years ago
return
11 years ago
elif is_local and self._stage == STAGE_INIT:
11 years ago
# TODO check auth method
self.write_all_to_sock('\x05\00', self._local_sock)
11 years ago
self._stage = STAGE_HELLO
11 years ago
return
11 years ago
elif self._stage == STAGE_REPLY:
if is_local:
data = self._encryptor.encrypt(data)
11 years ago
self._data_to_write_to_remote.append(data)
11 years ago
elif (is_local and self._stage == STAGE_HELLO) or \
11 years ago
(not is_local and self._stage == STAGE_INIT):
11 years ago
try:
if is_local:
cmd = ord(data[1])
# TODO check cmd == 1
11 years ago
assert cmd == CMD_CONNECT
11 years ago
# just trim VER CMD RSV
data = data[3:]
header_result = parse_header(data)
if header_result is None:
raise Exception('can not parse header')
addrtype, remote_addr, remote_port, header_length =\
header_result
11 years ago
logging.debug('connecting %s:%d' % (remote_addr, remote_port))
11 years ago
if is_local:
# forward address to remote
self.write_all_to_sock('\x05\x00\x00\x01' +
11 years ago
'\x00\x00\x00\x00\x10\x10',
self._local_sock)
11 years ago
data_to_send = self._encryptor.encrypt(data)
self._data_to_write_to_remote.append(data_to_send)
11 years ago
remote_addr = self._config['server']
remote_port = self._config['server_port']
11 years ago
else:
if len(data) > header_length:
self._data_to_write_to_remote.append(
data[header_length:])
11 years ago
# TODO async DNS
addrs = socket.getaddrinfo(remote_addr, remote_port, 0,
socket.SOCK_STREAM, socket.SOL_TCP)
if len(addrs) == 0:
raise Exception("can't get addrinfo for %s:%d" %
(remote_addr, remote_port))
af, socktype, proto, canonname, sa = addrs[0]
11 years ago
remote_sock = socket.socket(af, socktype, proto)
self._remote_sock = remote_sock
self._fd_to_handlers[remote_sock.fileno()] = self
remote_sock.setblocking(False)
remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
11 years ago
# TODO support TCP fast open
11 years ago
try:
11 years ago
remote_sock.connect(sa)
11 years ago
except (OSError, IOError) as e:
if eventloop.errno_from_exception(e) == errno.EINPROGRESS:
pass
11 years ago
self._loop.add(remote_sock,
11 years ago
eventloop.POLL_ERR | eventloop.POLL_OUT)
11 years ago
11 years ago
self._stage = STAGE_REPLY
self.update_stream(STREAM_UP, STATUS_WAIT_READWRITING)
11 years ago
self.update_stream(STREAM_DOWN, STATUS_WAIT_READING)
11 years ago
return
except Exception:
import traceback
traceback.print_exc()
# TODO use logging when debug completed
self.destroy()
def on_remote_read(self):
11 years ago
# TODO update timeout
data = None
try:
data = self._remote_sock.recv(BUF_SIZE)
except (OSError, IOError) as e:
if eventloop.errno_from_exception(e) in \
(errno.ETIMEDOUT, errno.EAGAIN):
return
if not data:
self.destroy()
return
11 years ago
if self._is_local:
data = self._encryptor.decrypt(data)
11 years ago
else:
data = self._encryptor.encrypt(data)
11 years ago
try:
11 years ago
self.write_all_to_sock(data, self._local_sock)
11 years ago
except Exception:
import traceback
traceback.print_exc()
# TODO use logging when debug completed
self.destroy()
def on_local_write(self):
if self._data_to_write_to_local:
11 years ago
data = ''.join(self._data_to_write_to_local)
self._data_to_write_to_local = []
self.write_all_to_sock(data, self._local_sock)
11 years ago
else:
11 years ago
self.update_stream(STREAM_DOWN, STATUS_WAIT_READING)
11 years ago
def on_remote_write(self):
11 years ago
self._stage = STAGE_STREAM
11 years ago
if self._data_to_write_to_remote:
11 years ago
data = ''.join(self._data_to_write_to_remote)
self._data_to_write_to_remote = []
self.write_all_to_sock(data, self._remote_sock)
11 years ago
else:
11 years ago
self.update_stream(STREAM_UP, STATUS_WAIT_READING)
11 years ago
11 years ago
def on_local_error(self):
11 years ago
logging.error(eventloop.get_sock_error(self._local_sock))
11 years ago
self.destroy()
def on_remote_error(self):
11 years ago
logging.error(eventloop.get_sock_error(self._remote_sock))
11 years ago
self.destroy()
def handle_event(self, sock, event):
# order is important
11 years ago
if sock == self._remote_sock:
11 years ago
if event & eventloop.POLL_IN:
self.on_remote_read()
if event & eventloop.POLL_OUT:
self.on_remote_write()
if event & eventloop.POLL_ERR:
self.on_remote_error()
11 years ago
elif sock == self._local_sock:
if event & eventloop.POLL_IN:
self.on_local_read()
if event & eventloop.POLL_OUT:
self.on_local_write()
if event & eventloop.POLL_ERR:
self.on_local_error()
11 years ago
else:
logging.warn('unknown socket')
def destroy(self):
11 years ago
logging.debug('destroy')
11 years ago
if self._remote_sock:
self._loop.remove(self._remote_sock)
del self._fd_to_handlers[self._remote_sock.fileno()]
11 years ago
self._remote_sock.close()
11 years ago
self._remote_sock = None
if self._local_sock:
self._loop.remove(self._local_sock)
del self._fd_to_handlers[self._local_sock.fileno()]
11 years ago
self._local_sock.close()
11 years ago
self._local_sock = None
11 years ago
class TCPRelay(object):
def __init__(self, config, is_local):
self._config = config
self._is_local = is_local
self._closed = False
11 years ago
self._eventloop = None
11 years ago
self._fd_to_handlers = {}
11 years ago
self._last_time = time.time()
11 years ago
11 years ago
if is_local:
listen_addr = config['local_address']
listen_port = config['local_port']
else:
listen_addr = config['server']
listen_port = config['server_port']
addrs = socket.getaddrinfo(listen_addr, listen_port, 0,
11 years ago
socket.SOCK_STREAM, socket.SOL_TCP)
if len(addrs) == 0:
raise Exception("can't get addrinfo for %s:%d" %
11 years ago
(listen_addr, listen_port))
11 years ago
af, socktype, proto, canonname, sa = addrs[0]
server_socket = socket.socket(af, socktype, proto)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
11 years ago
server_socket.bind(sa)
11 years ago
server_socket.setblocking(False)
11 years ago
server_socket.listen(1024)
11 years ago
self._server_socket = server_socket
11 years ago
def add_to_loop(self, loop):
if self._closed:
raise Exception('already closed')
self._eventloop = loop
loop.add_handler(self._handle_events)
self._eventloop.add(self._server_socket,
11 years ago
eventloop.POLL_IN | eventloop.POLL_ERR)
11 years ago
def _handle_events(self, events):
for sock, fd, event in events:
if sock:
logging.debug('fd %d %s', fd,
eventloop.EVENT_NAMES.get(event, event))
if sock == self._server_socket:
if event & eventloop.POLL_ERR:
# TODO
raise Exception('server_socket error')
try:
logging.debug('accept')
conn = self._server_socket.accept()
TCPRelayHandler(self._fd_to_handlers, self._eventloop,
conn[0], self._config, self._is_local)
except (OSError, IOError) as e:
error_no = eventloop.errno_from_exception(e)
if error_no in (errno.EAGAIN, errno.EINPROGRESS):
continue
else:
logging.error(e)
else:
11 years ago
if sock:
11 years ago
handler = self._fd_to_handlers.get(fd, None)
if handler:
handler.handle_event(sock, event)
11 years ago
else:
11 years ago
logging.warn('poll removed fd')
11 years ago
now = time.time()
11 years ago
if now - self._last_time > 5:
11 years ago
# TODO sweep timeouts
11 years ago
self._last_time = now
11 years ago
def close(self):
self._closed = True
self._server_socket.close()