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.

259 lines
7.4 KiB

11 years ago
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013-2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
11 years ago
#
# http://www.apache.org/licenses/LICENSE-2.0
11 years ago
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
11 years ago
# from ssloop
# https://github.com/clowwindy/ssloop
from __future__ import absolute_import, division, print_function, \
with_statement
11 years ago
11 years ago
import os
11 years ago
import socket
11 years ago
import select
11 years ago
import errno
import logging
11 years ago
from collections import defaultdict
11 years ago
__all__ = ['EventLoop', 'POLL_NULL', 'POLL_IN', 'POLL_OUT', 'POLL_ERR',
11 years ago
'POLL_HUP', 'POLL_NVAL', 'EVENT_NAMES']
11 years ago
11 years ago
POLL_NULL = 0x00
POLL_IN = 0x01
POLL_OUT = 0x04
POLL_ERR = 0x08
POLL_HUP = 0x10
POLL_NVAL = 0x20
11 years ago
11 years ago
EVENT_NAMES = {
POLL_NULL: 'POLL_NULL',
POLL_IN: 'POLL_IN',
POLL_OUT: 'POLL_OUT',
POLL_ERR: 'POLL_ERR',
POLL_HUP: 'POLL_HUP',
POLL_NVAL: 'POLL_NVAL',
}
11 years ago
class EpollLoop(object):
def __init__(self):
self._epoll = select.epoll()
def poll(self, timeout):
return self._epoll.poll(timeout)
def add_fd(self, fd, mode):
self._epoll.register(fd, mode)
def remove_fd(self, fd):
self._epoll.unregister(fd)
def modify_fd(self, fd, mode):
self._epoll.modify(fd, mode)
class KqueueLoop(object):
MAX_EVENTS = 1024
def __init__(self):
self._kqueue = select.kqueue()
self._fds = {}
def _control(self, fd, mode, flags):
events = []
11 years ago
if mode & POLL_IN:
11 years ago
events.append(select.kevent(fd, select.KQ_FILTER_READ, flags))
11 years ago
if mode & POLL_OUT:
11 years ago
events.append(select.kevent(fd, select.KQ_FILTER_WRITE, flags))
for e in events:
self._kqueue.control([e], 0)
def poll(self, timeout):
if timeout < 0:
timeout = None # kqueue behaviour
events = self._kqueue.control(None, KqueueLoop.MAX_EVENTS, timeout)
11 years ago
results = defaultdict(lambda: POLL_NULL)
11 years ago
for e in events:
fd = e.ident
if e.filter == select.KQ_FILTER_READ:
11 years ago
results[fd] |= POLL_IN
11 years ago
elif e.filter == select.KQ_FILTER_WRITE:
11 years ago
results[fd] |= POLL_OUT
return results.items()
11 years ago
def add_fd(self, fd, mode):
self._fds[fd] = mode
self._control(fd, mode, select.KQ_EV_ADD)
def remove_fd(self, fd):
self._control(fd, self._fds[fd], select.KQ_EV_DELETE)
del self._fds[fd]
def modify_fd(self, fd, mode):
self.remove_fd(fd)
self.add_fd(fd, mode)
class SelectLoop(object):
def __init__(self):
self._r_list = set()
self._w_list = set()
self._x_list = set()
def poll(self, timeout):
r, w, x = select.select(self._r_list, self._w_list, self._x_list,
timeout)
11 years ago
results = defaultdict(lambda: POLL_NULL)
for p in [(r, POLL_IN), (w, POLL_OUT), (x, POLL_ERR)]:
11 years ago
for fd in p[0]:
results[fd] |= p[1]
return results.items()
def add_fd(self, fd, mode):
11 years ago
if mode & POLL_IN:
11 years ago
self._r_list.add(fd)
11 years ago
if mode & POLL_OUT:
11 years ago
self._w_list.add(fd)
11 years ago
if mode & POLL_ERR:
11 years ago
self._x_list.add(fd)
def remove_fd(self, fd):
if fd in self._r_list:
self._r_list.remove(fd)
if fd in self._w_list:
self._w_list.remove(fd)
if fd in self._x_list:
self._x_list.remove(fd)
def modify_fd(self, fd, mode):
self.remove_fd(fd)
self.add_fd(fd, mode)
11 years ago
class EventLoop(object):
def __init__(self):
self._iterating = False
11 years ago
if hasattr(select, 'epoll'):
self._impl = EpollLoop()
11 years ago
model = 'epoll'
11 years ago
elif hasattr(select, 'kqueue'):
self._impl = KqueueLoop()
11 years ago
model = 'kqueue'
11 years ago
elif hasattr(select, 'select'):
self._impl = SelectLoop()
11 years ago
model = 'select'
11 years ago
else:
raise Exception('can not find any available functions in select '
'package')
11 years ago
self._fd_to_f = {}
11 years ago
self._handlers = []
self._ref_handlers = []
self._handlers_to_remove = []
11 years ago
logging.debug('using event model: %s', model)
11 years ago
11 years ago
def poll(self, timeout=None):
events = self._impl.poll(timeout)
11 years ago
return [(self._fd_to_f[fd], fd, event) for fd, event in events]
11 years ago
def add(self, f, mode):
fd = f.fileno()
11 years ago
self._fd_to_f[fd] = f
11 years ago
self._impl.add_fd(fd, mode)
def remove(self, f):
fd = f.fileno()
del self._fd_to_f[fd]
11 years ago
self._impl.remove_fd(fd)
def modify(self, f, mode):
fd = f.fileno()
self._impl.modify_fd(fd, mode)
11 years ago
def add_handler(self, handler, ref=True):
11 years ago
self._handlers.append(handler)
if ref:
# when all ref handlers are removed, loop stops
self._ref_handlers.append(handler)
def remove_handler(self, handler):
if handler in self._ref_handlers:
self._ref_handlers.remove(handler)
if self._iterating:
self._handlers_to_remove.append(handler)
else:
self._handlers.remove(handler)
11 years ago
def run(self):
events = []
while self._ref_handlers:
11 years ago
try:
events = self.poll(1)
except (OSError, IOError) as e:
if errno_from_exception(e) in (errno.EPIPE, errno.EINTR):
# EPIPE: Happens when the client closes the connection
# EINTR: Happens when received a signal
# handles them as soon as possible
logging.debug('poll:%s', e)
11 years ago
else:
11 years ago
logging.error('poll:%s', e)
11 years ago
import traceback
traceback.print_exc()
11 years ago
continue
self._iterating = True
11 years ago
for handler in self._handlers:
# TODO when there are a lot of handlers
try:
handler(events)
except (OSError, IOError) as e:
logging.error(e)
11 years ago
import traceback
traceback.print_exc()
if self._handlers_to_remove:
for handler in self._handlers_to_remove:
self._handlers.remove(handler)
self._handlers_to_remove = []
self._iterating = False
11 years ago
11 years ago
# from tornado
def errno_from_exception(e):
"""Provides the errno from an Exception object.
There are cases that the errno attribute was not set so we pull
the errno out of the args but if someone instatiates an Exception
without any args you will get a tuple error. So this function
abstracts all that behavior to give you a safe way to get the
errno.
"""
if hasattr(e, 'errno'):
return e.errno
elif e.args:
return e.args[0]
else:
return None
11 years ago
# from tornado
def get_sock_error(sock):
11 years ago
error_number = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
return socket.error(error_number, os.strerror(error_number))