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 """Items common to both the client and server
20 import array as _array
22 import socket as _socket
24 from . import error as _error
27 LINE_LENGTH = 1002 # 1000 + [CR,]LF
28 _ENCODE_PATTERN = '(' + '|'.join(['%', '\r', '\n']) + ')'
29 _ENCODE_STR_REGEXP = _re.compile(_ENCODE_PATTERN)
30 _ENCODE_BYTE_REGEXP = _re.compile(_ENCODE_PATTERN.encode('ascii'))
31 _DECODE_STR_REGEXP = _re.compile('(%[0-9A-Fa-f]{2})')
32 _DECODE_BYTE_REGEXP = _re.compile(b'(%[0-9A-Fa-f]{2})')
33 _REQUEST_REGEXP = _re.compile('^(\w+)( *)(.*)\Z')
39 >>> encode('It grew by 5%!\n')
41 >>> encode(b'It grew by 5%!\n')
42 b'It grew by 5%25!%0A'
44 if isinstance(data, bytes):
45 regexp = _ENCODE_BYTE_REGEXP
47 regexp = _ENCODE_STR_REGEXP
49 lambda x : to_hex(x.group()), data)
54 >>> decode('%22Look out!%22%0AWhere%3F')
56 >>> decode(b'%22Look out!%22%0AWhere%3F')
57 b'"Look out!"\nWhere?'
59 if isinstance(data, bytes):
60 regexp = _DECODE_BYTE_REGEXP
62 regexp = _DECODE_STR_REGEXP
64 lambda x : from_hex(x.group()), data)
76 c = chr(int(code[1:], 16))
77 if isinstance(code, bytes):
91 hx = '%{:02X}'.format(ord(char))
92 if isinstance(char, bytes):
93 hx = hx.encode('ascii')
97 class Request (object):
100 http://www.gnupg.org/documentation/manuals/assuan/Client-requests.html
102 >>> r = Request(command='BYE')
105 >>> r = Request(command='OPTION', parameters='testing at 5%')
107 'OPTION testing at 5%25'
109 b'OPTION testing at 5%25'
110 >>> r.from_bytes(b'BYE')
113 >>> print(r.parameters)
115 >>> r.from_bytes(b'OPTION testing at 5%25')
118 >>> print(r.parameters)
120 >>> r.from_bytes(b' invalid')
121 Traceback (most recent call last):
123 pyassuan.error.AssuanError: 170 Invalid request
124 >>> r.from_bytes(b'in-valid')
125 Traceback (most recent call last):
127 pyassuan.error.AssuanError: 170 Invalid request
129 def __init__(self, command=None, parameters=None, encoded=False):
130 self.command = command
131 self.parameters = parameters
132 self.encoded = encoded
137 encoded_parameters = self.parameters
139 encoded_parameters = encode(self.parameters)
140 return '{} {}'.format(self.command, encoded_parameters)
146 encoded_parameters = self.parameters
148 encoded_parameters = encode(self.parameters)
149 return '{} {}'.format(
150 self.command, encoded_parameters).encode('utf-8')
151 return self.command.encode('utf-8')
153 def from_bytes(self, line):
154 if len(line) > 1000: # TODO: byte-vs-str and newlines?
155 raise _error.AssuanError(message='Line too long')
156 line = str(line, encoding='utf-8')
157 match = _REQUEST_REGEXP.match(line)
159 raise _error.AssuanError(message='Invalid request')
160 self.command = match.group(1)
163 self.parameters = decode(match.group(3))
165 raise _error.AssuanError(message='Invalid request')
167 self.parameters = None
170 class Response (object):
173 http://www.gnupg.org/documentation/manuals/assuan/Server-responses.html
175 >>> r = Response(type='OK')
178 >>> r = Response(type='ERR', parameters='1 General error')
180 'ERR 1 General error'
182 b'ERR 1 General error'
183 >>> r.from_bytes(b'OK')
186 >>> print(r.parameters)
188 >>> r.from_bytes(b'ERR 1 General error')
191 >>> print(r.parameters)
193 >>> r.from_bytes(b' invalid')
194 Traceback (most recent call last):
196 pyassuan.error.AssuanError: 76 Invalid response
197 >>> r.from_bytes(b'in-valid')
198 Traceback (most recent call last):
200 pyassuan.error.AssuanError: 76 Invalid response
211 def __init__(self, type=None, parameters=None):
213 self.parameters = parameters
217 return '{} {}'.format(self.type, encode(self.parameters))
223 return b' '.join((b'D', self.parameters))
225 return '{} {}'.format(
226 self.type, encode(self.parameters)).encode('utf-8')
227 return self.type.encode('utf-8')
229 def from_bytes(self, line):
230 if len(line) > 1000: # TODO: byte-vs-str and newlines?
231 raise _error.AssuanError(message='Line too long')
232 if line.startswith(b'D'):
233 self.command = t = 'D'
235 line = str(line, encoding='utf-8')
240 raise _error.AssuanError(message='Invalid response')
242 if type == 'D': # data
243 self.parameters = decode(line[2:])
244 elif type == '#': # comment
245 self.parameters = decode(line[2:])
247 match = _REQUEST_REGEXP.match(line)
249 raise _error.AssuanError(message='Invalid request')
252 self.parameters = decode(match.group(3))
254 raise _error.AssuanError(message='Invalid request')
256 self.parameters = None
259 def error_response(error):
262 >>> from pyassuan.error import AssuanError
263 >>> error = AssuanError(1)
264 >>> response = error_response(error)
268 return Response(type='ERR', parameters=str(error))
271 def send_fds(socket, msg, fds):
272 """Send a file descriptor over a Unix socket using ``sendmsg``.
274 ``sendmsg`` suport requires Python >= 3.3.
277 http://docs.python.org/dev/library/socket.html#socket.socket.sendmsg
280 http://www.gnupg.org/documentation/manuals/assuan/Client-code.html#function-assuan_005fsendfd
282 return socket.sendmsg(
284 [(_socket.SOL_SOCKET, _socket.SCM_RIGHTS, _array.array('i', fds))])
286 def receive_fds(socket, msglen, maxfds):
287 """Recieve file descriptors using ``recvmsg``.
289 ``recvmsg`` suport requires Python >= 3.3.
291 Code from http://docs.python.org/dev/library/socket.html
294 http://www.gnupg.org/documentation/manuals/assuan/Client-code.html#fun_002dassuan_005freceivedfd
296 fds = _array.array('i') # Array of ints
297 msg,ancdata,flags,addr = socket.recvmsg(
298 msglen, _socket.CMSG_LEN(maxfds * fds.itemsize))
299 for cmsg_level,cmsg_type,cmsg_data in ancdata:
300 if (cmsg_level == _socket.SOL_SOCKET and
301 cmsg_type == _socket.SCM_RIGHTS):
302 # Append data, ignoring any truncated integers at the end.
304 cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
305 return (msg, list(fds))