From: W. Trevor King Date: Sun, 7 Oct 2012 19:53:44 +0000 (-0400) Subject: client: add Unix-socket handling to .connect() and .disconnect(). X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=fad28835c3070fa02944c715a1030f3f8d1a33a8;p=pyassuan.git client: add Unix-socket handling to .connect() and .disconnect(). --- diff --git a/bin/get-info.py b/bin/get-info.py index bba87c3..9f0f50f 100755 --- a/bin/get-info.py +++ b/bin/get-info.py @@ -19,8 +19,6 @@ """Simple pinentry program for getting server info. """ -import socket as _socket - from pyassuan import __version__ from pyassuan import client as _client from pyassuan import common as _common @@ -47,11 +45,7 @@ if __name__ == '__main__': client.logger.setLevel(max( logging.DEBUG, client.logger.level - 10*args.verbose)) - socket = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM) - socket.connect(args.filename) - client.input = socket.makefile('rb') - client.output = socket.makefile('wb') - client.connect() + client.connect(socket_path=args.filename) try: response = client.read_response() assert response.type == 'OK', response @@ -68,5 +62,3 @@ if __name__ == '__main__': finally: client.make_request(_common.Request('BYE')) client.disconnect() - socket.shutdown(_socket.SHUT_RDWR) - socket.close() diff --git a/pyassuan/client.py b/pyassuan/client.py index f7e8722..2555ebc 100644 --- a/pyassuan/client.py +++ b/pyassuan/client.py @@ -15,6 +15,7 @@ # pyassuan. If not, see . import logging as _logging +import socket as _socket import sys as _sys from . import LOG as _LOG @@ -35,21 +36,37 @@ class AssuanClient (object): logger = _logging.getLogger('{}.{}'.format(logger.name, self.name)) self.logger = logger self.close_on_disconnect = close_on_disconnect - self.input = self.output = None + self.input = self.output = self.socket = None - def connect(self): - if not self.input: - self.logger.info('read from stdin') - self.input = _sys.stdin.buffer - if not self.output: - self.logger.info('write to stdout') - self.output = _sys.stdout.buffer + def connect(self, socket_path=None): + if socket_path: + self.logger.info( + 'connect to Unix socket at {}'.format(socket_path)) + self.socket = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM) + self.socket.connect(socket_path) + self.input = self.socket.makefile('rb') + self.output = self.socket.makefile('wb') + else: + if not self.input: + self.logger.info('read from stdin') + self.input = _sys.stdin.buffer + if not self.output: + self.logger.info('write to stdout') + self.output = _sys.stdout.buffer def disconnect(self): if self.close_on_disconnect: self.logger.info('disconnecting') - self.input = None - self.output = None + if self.input is not None: + self.input.close() + self.input = None + if self.output is not None: + self.output.close() + self.output = None + if self.socket is not None: + self.socket.shutdown(_socket.SHUT_RDWR) + self.socket.close() + self.socket = None def raise_error(self, error): self.logger.error(str(error))