1 # Copyright (C) 2012 W. Trevor King <wking@drexel.edu>
3 # This file is part of pyassuan.
5 # pyassuan is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
10 # pyassuan is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along with
15 # pyassuan. If not, see <http://www.gnu.org/licenses/>.
17 import logging as _logging
20 from . import LOG as _LOG
21 from . import common as _common
22 from . import error as _error
25 class AssuanClient (object):
26 """A single-threaded Assuan client based on the `devolpment suggestions`_
28 .. _development suggestions:
29 http://www.gnupg.org/documentation/manuals/assuan/Client-code.html
31 def __init__(self, name, logger=_LOG, use_sublogger=True,
32 close_on_disconnect=False):
35 logger = _logging.getLogger('{}.{}'.format(logger.name, self.name))
37 self.close_on_disconnect = close_on_disconnect
38 self.input = self.output = None
42 self.logger.info('read from stdin')
43 self.input = _sys.stdin
45 self.logger.info('write to stdout')
46 self.output = _sys.stdout
49 if self.close_on_disconnect:
50 self.logger.info('disconnecting')
54 def raise_error(self, error):
55 self.logger.error(str(error))
58 def read_response(self):
59 line = self.input.readline()
62 _error.AssuanError(message='IPC accept call failed'))
63 if not line.endswith('\n'):
65 _error.AssuanError(message='Invalid response'))
66 line = line[:-1] # remove trailing newline
68 response = _common.Response()
70 response.from_string(line)
71 except _error.AssuanError as e:
72 self.logger.error(str(e))
74 self.logger.info('S: {}'.format(response))
77 def _write_request(self, request):
78 rstring = str(request)
79 self.logger.info('C: {}'.format(rstring))
80 self.output.write(rstring)
81 self.output.write('\n')
87 def make_request(self, request, response=True, expect=['OK']):
88 self._write_request(request=request)
90 return self.get_responses(requests=[request], expect=expect)
92 def get_responses(self, requests=None, expect=['OK']):
93 responses = list(self.responses())
94 if responses[-1].type == 'ERR':
95 eresponse = responses[-1]
96 fields = eresponse.parameters.split(' ', 1)
99 message = fields[1].strip()
102 error = _error.AssuanError(code=code, message=message)
103 if requests is not None:
104 error.requests = requests
105 error.responses = responses
108 assert responses[-1].type in expect, [str(r) for r in responses]
110 for response in responses:
111 if response.type == 'D':
112 data.append(response.parameters)
117 return (responses, data)
121 response = self.read_response()
123 if response.type not in ['S', '#', 'D']:
126 def send_data(self, data=None, response=True, expect=['OK']):
127 """Iterate through requests necessary to send ``data`` to a server.
129 http://www.gnupg.org/documentation/manuals/assuan/Client-requests.html
133 encoded_data = _common.encode(data)
135 stop = min(_common.LINE_LENGTH-4, len(encoded_data)) # 'D ', CR, CL
136 self.logger.debug('sending {} bytes of encoded data'.format(
139 d = encoded_data[start:stop]
140 request = _common.Request(
141 command='D', parameters=encoded_data[start:stop],
143 requests.append(request)
144 self.logger.debug('send {} byte chunk'.format(stop-start))
145 self._write_request(request=request)
147 stop = start + min(_common.LINE_LENGTH-4,
148 len(encoded_data) - start)
149 request = _common.Request('END')
150 requests.append(request)
151 self._write_request(request=request)
153 return self.get_responses(requests=requests, expect=expect)