home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_638 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  11.5 KB  |  347 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __all__ = [
  5.     'Client',
  6.     'Listener',
  7.     'Pipe']
  8. import os
  9. import sys
  10. import socket
  11. import errno
  12. import time
  13. import tempfile
  14. import itertools
  15. import _multiprocessing
  16. from multiprocessing import current_process, AuthenticationError
  17. from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug
  18. from multiprocessing.forking import duplicate, close
  19. BUFSIZE = 8192
  20. _mmap_counter = itertools.count()
  21. default_family = 'AF_INET'
  22. families = [
  23.     'AF_INET']
  24. if hasattr(socket, 'AF_UNIX'):
  25.     default_family = 'AF_UNIX'
  26.     families += [
  27.         'AF_UNIX']
  28.  
  29. if sys.platform == 'win32':
  30.     default_family = 'AF_PIPE'
  31.     families += [
  32.         'AF_PIPE']
  33.  
  34.  
  35. def arbitrary_address(family):
  36.     if family == 'AF_INET':
  37.         return ('localhost', 0)
  38.     if family == 'AF_UNIX':
  39.         return tempfile.mktemp(prefix = 'listener-', dir = get_temp_dir())
  40.     if family == 'AF_PIPE':
  41.         return tempfile.mktemp(prefix = '\\\\.\\pipe\\pyc-%d-%d-' % (os.getpid(), _mmap_counter.next()))
  42.     raise ValueError('unrecognized family')
  43.  
  44.  
  45. def address_type(address):
  46.     if type(address) == tuple:
  47.         return 'AF_INET'
  48.     if type(address) is str and address.startswith('\\\\'):
  49.         return 'AF_PIPE'
  50.     if type(address) is str:
  51.         return 'AF_UNIX'
  52.     raise ValueError('address type of %r unrecognized' % address)
  53.  
  54.  
  55. class Listener(object):
  56.     
  57.     def __init__(self, address = None, family = None, backlog = 1, authkey = None):
  58.         if not family:
  59.             if not address or address_type(address):
  60.                 pass
  61.         family = default_family
  62.         if not address:
  63.             pass
  64.         address = arbitrary_address(family)
  65.         if family == 'AF_PIPE':
  66.             self._listener = PipeListener(address, backlog)
  67.         else:
  68.             self._listener = SocketListener(address, family, backlog)
  69.         if authkey is not None and not isinstance(authkey, bytes):
  70.             raise TypeError, 'authkey should be a byte string'
  71.         not isinstance(authkey, bytes)
  72.         self._authkey = authkey
  73.  
  74.     
  75.     def accept(self):
  76.         c = self._listener.accept()
  77.         if self._authkey:
  78.             deliver_challenge(c, self._authkey)
  79.             answer_challenge(c, self._authkey)
  80.         
  81.         return c
  82.  
  83.     
  84.     def close(self):
  85.         return self._listener.close()
  86.  
  87.     address = property((lambda self: self._listener._address))
  88.     last_accepted = property((lambda self: self._listener._last_accepted))
  89.  
  90.  
  91. def Client(address, family = None, authkey = None):
  92.     if not family:
  93.         pass
  94.     family = address_type(address)
  95.     if family == 'AF_PIPE':
  96.         c = PipeClient(address)
  97.     else:
  98.         c = SocketClient(address)
  99.     if authkey is not None and not isinstance(authkey, bytes):
  100.         raise TypeError, 'authkey should be a byte string'
  101.     not isinstance(authkey, bytes)
  102.     if authkey is not None:
  103.         answer_challenge(c, authkey)
  104.         deliver_challenge(c, authkey)
  105.     
  106.     return c
  107.  
  108. if sys.platform != 'win32':
  109.     
  110.     def Pipe(duplex = True):
  111.         if duplex:
  112.             (s1, s2) = socket.socketpair()
  113.             c1 = _multiprocessing.Connection(os.dup(s1.fileno()))
  114.             c2 = _multiprocessing.Connection(os.dup(s2.fileno()))
  115.             s1.close()
  116.             s2.close()
  117.         else:
  118.             (fd1, fd2) = os.pipe()
  119.             c1 = _multiprocessing.Connection(fd1, writable = False)
  120.             c2 = _multiprocessing.Connection(fd2, readable = False)
  121.         return (c1, c2)
  122.  
  123. else:
  124.     from _multiprocessing import win32
  125.     
  126.     def Pipe(duplex = True):
  127.         address = arbitrary_address('AF_PIPE')
  128.         if duplex:
  129.             openmode = win32.PIPE_ACCESS_DUPLEX
  130.             access = win32.GENERIC_READ | win32.GENERIC_WRITE
  131.             obsize = BUFSIZE
  132.             ibsize = BUFSIZE
  133.         else:
  134.             openmode = win32.PIPE_ACCESS_INBOUND
  135.             access = win32.GENERIC_WRITE
  136.             obsize = 0
  137.             ibsize = BUFSIZE
  138.         h1 = win32.CreateNamedPipe(address, openmode, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL)
  139.         h2 = win32.CreateFile(address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL)
  140.         win32.SetNamedPipeHandleState(h2, win32.PIPE_READMODE_MESSAGE, None, None)
  141.         
  142.         try:
  143.             win32.ConnectNamedPipe(h1, win32.NULL)
  144.         except WindowsError:
  145.             e = None
  146.             if e.args[0] != win32.ERROR_PIPE_CONNECTED:
  147.                 raise 
  148.             e.args[0] != win32.ERROR_PIPE_CONNECTED
  149.  
  150.         c1 = _multiprocessing.PipeConnection(h1, writable = duplex)
  151.         c2 = _multiprocessing.PipeConnection(h2, readable = duplex)
  152.         return (c1, c2)
  153.  
  154.  
  155. class SocketListener(object):
  156.     
  157.     def __init__(self, address, family, backlog = 1):
  158.         self._socket = socket.socket(getattr(socket, family))
  159.         self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  160.         self._socket.bind(address)
  161.         self._socket.listen(backlog)
  162.         self._address = self._socket.getsockname()
  163.         self._family = family
  164.         self._last_accepted = None
  165.         if family == 'AF_UNIX':
  166.             self._unlink = Finalize(self, os.unlink, args = (address,), exitpriority = 0)
  167.         else:
  168.             self._unlink = None
  169.  
  170.     
  171.     def accept(self):
  172.         (s, self._last_accepted) = self._socket.accept()
  173.         fd = duplicate(s.fileno())
  174.         conn = _multiprocessing.Connection(fd)
  175.         s.close()
  176.         return conn
  177.  
  178.     
  179.     def close(self):
  180.         self._socket.close()
  181.         if self._unlink is not None:
  182.             self._unlink()
  183.         
  184.  
  185.  
  186.  
  187. def SocketClient(address):
  188.     family = address_type(address)
  189.     s = socket.socket(getattr(socket, family))
  190.     while None:
  191.         
  192.         try:
  193.             s.connect(address)
  194.         except socket.error:
  195.             e = None
  196.             if e.args[0] != errno.ECONNREFUSED:
  197.                 debug('failed to connect to address %s', address)
  198.                 raise 
  199.             e.args[0] != errno.ECONNREFUSED
  200.             time.sleep(0.01)
  201.             continue
  202.  
  203.         break
  204.         continue
  205.         raise 
  206.         fd = duplicate(s.fileno())
  207.         conn = _multiprocessing.Connection(fd)
  208.         return conn
  209.  
  210. if sys.platform == 'win32':
  211.     
  212.     class PipeListener(object):
  213.         
  214.         def __init__(self, address, backlog = None):
  215.             self._address = address
  216.             handle = win32.CreateNamedPipe(address, win32.PIPE_ACCESS_DUPLEX, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, win32.NMPWAIT_WAIT_FOREVER, win32.NULL)
  217.             self._handle_queue = [
  218.                 handle]
  219.             self._last_accepted = None
  220.             sub_debug('listener created with address=%r', self._address)
  221.             self.close = Finalize(self, PipeListener._finalize_pipe_listener, args = (self._handle_queue, self._address), exitpriority = 0)
  222.  
  223.         
  224.         def accept(self):
  225.             newhandle = win32.CreateNamedPipe(self._address, win32.PIPE_ACCESS_DUPLEX, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, win32.NMPWAIT_WAIT_FOREVER, win32.NULL)
  226.             self._handle_queue.append(newhandle)
  227.             handle = self._handle_queue.pop(0)
  228.             
  229.             try:
  230.                 win32.ConnectNamedPipe(handle, win32.NULL)
  231.             except WindowsError:
  232.                 e = None
  233.                 if e.args[0] != win32.ERROR_PIPE_CONNECTED:
  234.                     raise 
  235.                 e.args[0] != win32.ERROR_PIPE_CONNECTED
  236.  
  237.             return _multiprocessing.PipeConnection(handle)
  238.  
  239.         
  240.         def _finalize_pipe_listener(queue, address):
  241.             sub_debug('closing listener with address=%r', address)
  242.             for handle in queue:
  243.                 close(handle)
  244.             
  245.  
  246.         _finalize_pipe_listener = staticmethod(_finalize_pipe_listener)
  247.  
  248.     
  249.     def PipeClient(address):
  250.         while None:
  251.             
  252.             try:
  253.                 win32.WaitNamedPipe(address, 1000)
  254.                 h = win32.CreateFile(address, win32.GENERIC_READ | win32.GENERIC_WRITE, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL)
  255.             except WindowsError:
  256.                 e = None
  257.                 if e.args[0] not in (win32.ERROR_SEM_TIMEOUT, win32.ERROR_PIPE_BUSY):
  258.                     raise 
  259.                 e.args[0] not in (win32.ERROR_SEM_TIMEOUT, win32.ERROR_PIPE_BUSY)
  260.                 continue
  261.  
  262.             break
  263.             continue
  264.             raise 
  265.             return _multiprocessing.PipeConnection(h)
  266.  
  267.  
  268. MESSAGE_LENGTH = 20
  269. CHALLENGE = '#CHALLENGE#'
  270. WELCOME = '#WELCOME#'
  271. FAILURE = '#FAILURE#'
  272.  
  273. def deliver_challenge(connection, authkey):
  274.     import hmac
  275.     message = os.urandom(MESSAGE_LENGTH)
  276.     connection.send_bytes(CHALLENGE + message)
  277.     digest = hmac.new(authkey, message).digest()
  278.     response = connection.recv_bytes(256)
  279.     if response == digest:
  280.         connection.send_bytes(WELCOME)
  281.     else:
  282.         connection.send_bytes(FAILURE)
  283.         raise AuthenticationError('digest received was wrong')
  284.     return response == digest
  285.  
  286.  
  287. def answer_challenge(connection, authkey):
  288.     import hmac
  289.     message = connection.recv_bytes(256)
  290.     message = message[len(CHALLENGE):]
  291.     digest = hmac.new(authkey, message).digest()
  292.     connection.send_bytes(digest)
  293.     response = connection.recv_bytes(256)
  294.     if response != WELCOME:
  295.         raise AuthenticationError('digest sent was rejected')
  296.     response != WELCOME
  297.  
  298.  
  299. class ConnectionWrapper(object):
  300.     
  301.     def __init__(self, conn, dumps, loads):
  302.         self._conn = conn
  303.         self._dumps = dumps
  304.         self._loads = loads
  305.         for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
  306.             obj = getattr(conn, attr)
  307.             setattr(self, attr, obj)
  308.         
  309.  
  310.     
  311.     def send(self, obj):
  312.         s = self._dumps(obj)
  313.         self._conn.send_bytes(s)
  314.  
  315.     
  316.     def recv(self):
  317.         s = self._conn.recv_bytes()
  318.         return self._loads(s)
  319.  
  320.  
  321.  
  322. def _xml_dumps(obj):
  323.     return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8')
  324.  
  325.  
  326. def _xml_loads(s):
  327.     (obj,) = ()
  328.     method = xmlrpclib.loads(s.decode('utf8'))
  329.     return obj
  330.  
  331.  
  332. class XmlListener(Listener):
  333.     
  334.     def accept(self):
  335.         global xmlrpclib
  336.         import xmlrpclib
  337.         obj = Listener.accept(self)
  338.         return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
  339.  
  340.  
  341.  
  342. def XmlClient(*args, **kwds):
  343.     global xmlrpclib
  344.     import xmlrpclib
  345.     return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
  346.  
  347.