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
19 import socket as _socket
21 import threading as _threading
22 import traceback as _traceback
24 from . import LOG as _LOG
25 from . import common as _common
26 from . import error as _error
29 _OPTION_REGEXP = _re.compile('^-?-?([-\w]+)( *)(=?) *(.*?) *\Z')
32 class AssuanServer (object):
33 """A single-threaded Assuan server based on the `devolpment suggestions`_
35 Extend by subclassing and adding ``_handle_XXX`` methods for each
36 command you want to handle.
38 .. _development suggestions:
39 http://www.gnupg.org/documentation/manuals/assuan/Server-code.html
41 def __init__(self, name, logger=_LOG, use_sublogger=True,
42 valid_options=None, strict_options=True,
43 single_request=False, listen_to_quit=False,
44 close_on_disconnect=False):
47 logger = _logging.getLogger('{}.{}'.format(logger.name, self.name))
49 if valid_options is None:
51 self.valid_options = valid_options
52 self.strict_options = strict_options
53 self.single_request = single_request
54 self.listen_to_quit = listen_to_quit
55 self.close_on_disconnect = close_on_disconnect
56 self.input = self.output = None
66 self.logger.info('running')
69 self.handle_requests()
72 self.logger.info('stopping')
76 self.logger.info('read from stdin')
77 self.input = _sys.stdin
79 self.logger.info('write to stdout')
80 self.output = _sys.stdout
83 if self.close_on_disconnect:
84 self.logger.info('disconnecting')
88 def handle_requests(self):
89 self.send_response(_common.Response('OK', 'Your orders please'))
92 line = self.input.readline()
95 if not line.endswith('\n'):
96 self.logger.info('C: {}'.format(line))
97 self.send_error_response(
98 _error.AssuanError(message='Invalid request'))
100 line = line[:-1] # remove the trailing newline
101 self.logger.info('C: {}'.format(line))
102 request = _common.Request()
104 request.from_string(line)
105 except _error.AssuanError as e:
106 self.send_error_response(e)
108 self.handle_request(request)
110 def handle_request(self, request):
113 self, '_handle_{}'.format(request.command))
114 except AttributeError:
115 self.send_error_response(
116 _error.AssuanError(message='Unknown command'))
119 responses = handle(request.parameters)
120 for response in responses:
121 self.send_response(response)
122 except _error.AssuanError as error:
123 self.send_error_response(error)
125 except Exception as e:
127 'exception while executing {}:\n{}'.format(
128 handle, _traceback.format_exc().rstrip()))
129 self.send_error_response(
130 _error.AssuanError(message='Unspecific Assuan server fault'))
133 def send_response(self, response):
134 """For internal use by ``.handle_requests()``
136 rstring = str(response)
137 self.logger.info('S: {}'.format(rstring))
138 self.output.write(rstring)
139 self.output.write('\n')
146 def send_error_response(self, error):
147 """For internal use by ``.handle_requests()``
149 self.send_response(_common.error_response(error))
151 # common commands defined at
152 # http://www.gnupg.org/documentation/manuals/assuan/Client-requests.html
154 def _handle_BYE(self, arg):
155 if self.single_request:
157 yield _common.Response('OK', 'closing connection')
159 def _handle_RESET(self, arg):
162 def _handle_END(self, arg):
163 raise _error.AssuanError(
164 code=175, message='Unknown command (reserved)')
166 def _handle_HELP(self, arg):
167 raise _error.AssuanError(
168 code=175, message='Unknown command (reserved)')
170 def _handle_QUIT(self, arg):
171 if self.listen_to_quit:
173 yield _common.Response('OK', 'stopping the server')
174 raise _error.AssuanError(
175 code=175, message='Unknown command (reserved)')
177 def _handle_OPTION(self, arg):
180 >>> s = AssuanServer(name='test', valid_options=['my-op'])
181 >>> list(s._handle_OPTION('my-op = 1 ')) # doctest: +ELLIPSIS
182 [<pyassuan.common.Response object at ...>]
185 >>> list(s._handle_OPTION('my-op 2')) # doctest: +ELLIPSIS
186 [<pyassuan.common.Response object at ...>]
189 >>> list(s._handle_OPTION('--my-op 3')) # doctest: +ELLIPSIS
190 [<pyassuan.common.Response object at ...>]
193 >>> list(s._handle_OPTION('my-op')) # doctest: +ELLIPSIS
194 [<pyassuan.common.Response object at ...>]
197 >>> list(s._handle_OPTION('inv'))
198 Traceback (most recent call last):
200 pyassuan.error.AssuanError: 174 Unknown option
201 >>> list(s._handle_OPTION('in|valid'))
202 Traceback (most recent call last):
204 pyassuan.error.AssuanError: 90 Invalid parameter
206 match = _OPTION_REGEXP.match(arg)
208 raise _error.AssuanError(message='Invalid parameter')
209 name,space,equal,value = match.groups()
210 if value and not space and not equal:
211 # need either space or equal to separate value
212 raise _error.AssuanError(message='Invalid parameter')
213 if name not in self.valid_options:
214 if self.strict_options:
215 raise _error.AssuanError(message='Unknown option')
217 self.logger.info('skipping invalid option: {}'.format(name))
221 self.options[name] = value
222 yield _common.Response('OK')
224 def _handle_CANCEL(self, arg):
225 raise _error.AssuanError(
226 code=175, message='Unknown command (reserved)')
228 def _handle_AUTH(self, arg):
229 raise _error.AssuanError(
230 code=175, message='Unknown command (reserved)')
233 class AssuanSocketServer (object):
234 """A threaded server spawning ``AssuanServer``\s for each connection
236 def __init__(self, name, socket, server, kwargs={}, max_threads=10,
237 logger=_LOG, use_sublogger=True):
240 logger = _logging.getLogger('{}.{}'.format(logger.name, self.name))
244 assert 'name' not in kwargs, kwargs['name']
245 assert 'logger' not in kwargs, kwargs['logger']
246 kwargs['logger'] = self.logger
247 assert 'use_sublogger' not in kwargs, kwargs['use_sublogger']
248 kwargs['use_sublogger'] = True
249 if 'close_on_disconnect' in kwargs:
250 assert kwargs['close_on_disconnect'] == True, (
251 kwargs['close_on_disconnect'])
253 kwargs['close_on_disconnect'] = True
255 self.max_threads = max_threads
259 self.logger.info('listen on socket')
263 socket,address = self.socket.accept()
264 self.logger.info('connection from {}'.format(address))
265 self.cleanup_threads()
266 if len(threads) > self.max_threads:
267 self.drop_connection(socket, address)
269 'server-thread-{}'.format(thread_index), socket, address)
270 thread_index = (thread_index + 1) % self.max_threads
272 def cleanup_threads(self):
274 while i < len(self.threads):
275 thread = self.threads[i]
277 if thread.is_alive():
278 self.logger.info('joined thread {}'.format(thread.name))
280 thread.socket.shutdown()
281 thread.socket.close()
285 def drop_connection(self, socket, address):
286 self.logger.info('drop connection from {}'.format(address))
287 # TODO: proper error to send to the client?
289 def spawn_thread(self, name, socket, address):
290 server = self.server(name=name, **self.kwargs)
291 server.input = socket.makefile('r')
292 server.output = socket.makefile('w')
293 thread = _threading.Thread(target=server.run, name=name)
295 self.threads.append(thread)