51364cb31998727db91539766f5d82a429b09c61
[ikiwiki.git] / plugins / proxy.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # proxy.py — helper for Python-based external (xml-rpc) ikiwiki plugins
5 #
6 # Copyright © 2008      martin f. krafft <madduck@madduck.net>
7 #             2008-2011 Joey Hess <joey@kitenet.net>
8 #             2012      W. Trevor King <wking@tremily.us>
9 #
10 #  Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions
12 # are met:
13 # 1. Redistributions of source code must retain the above copyright
14 #    notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 #    notice, this list of conditions and the following disclaimer in the
17 #    documentation and/or other materials provided with the distribution.
18 # .
19 # THIS SOFTWARE IS PROVIDED BY IKIWIKI AND CONTRIBUTORS ``AS IS''
20 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22 # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
23 # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
26 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29 # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 # SUCH DAMAGE.
31 #
32 __name__ = 'proxy.py'
33 __description__ = 'helper for Python-based external (xml-rpc) ikiwiki plugins'
34 __version__ = '0.2'
35 __author__ = 'martin f. krafft <madduck@madduck.net>'
36 __copyright__ = 'Copyright © ' + __author__
37 __licence__ = 'BSD-2-clause'
38
39 import sys
40 import time
41 import xml.parsers.expat
42 try:  # Python 3
43     import xmlrpc.client as _xmlrpc_client
44 except ImportError:  # Python 2
45     import xmlrpclib as _xmlrpc_client
46 from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
47
48
49 class ParseError (Exception):
50     pass
51
52
53 class PipeliningDetected (Exception):
54     pass
55
56
57 class GoingDown (Exception):
58     pass
59
60
61 class InvalidReturnValue (Exception):
62     pass
63
64
65 class AlreadyImported (Exception):
66     pass
67
68
69 class _IkiWikiExtPluginXMLRPCDispatcher(SimpleXMLRPCDispatcher):
70
71     def __init__(self, allow_none=False, encoding=None):
72         try:
73             SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
74         except TypeError:
75             # see http://bugs.debian.org/470645
76             # python2.4 and before only took one argument
77             SimpleXMLRPCDispatcher.__init__(self)
78
79     def dispatch(self, method, params):
80         return self._dispatch(method, params)
81
82
83 class XMLStreamParser(object):
84
85     def __init__(self):
86         self._parser = xml.parsers.expat.ParserCreate()
87         self._parser.StartElementHandler = self._push_tag
88         self._parser.EndElementHandler = self._pop_tag
89         self._parser.XmlDeclHandler = self._check_pipelining
90         self._reset()
91
92     def _reset(self):
93         self._stack = list()
94         self._acc = r''
95         self._first_tag_received = False
96
97     def _push_tag(self, tag, attrs):
98         self._stack.append(tag)
99         self._first_tag_received = True
100
101     def _pop_tag(self, tag):
102         top = self._stack.pop()
103         if top != tag:
104             raise ParseError(
105                 'expected {} closing tag, got {}'.format(top, tag))
106
107     def _request_complete(self):
108         return self._first_tag_received and len(self._stack) == 0
109
110     def _check_pipelining(self, *args):
111         if self._first_tag_received:
112             raise PipeliningDetected('need a new line between XML documents')
113
114     def parse(self, data):
115         self._parser.Parse(data, False)
116         self._acc += data
117         if self._request_complete():
118             ret = self._acc
119             self._reset()
120             return ret
121
122
123 class _IkiWikiExtPluginXMLRPCHandler(object):
124
125     def __init__(self, debug_fn):
126         self._dispatcher = _IkiWikiExtPluginXMLRPCDispatcher()
127         self.register_function = self._dispatcher.register_function
128         self._debug_fn = debug_fn
129
130     def register_function(self, function, name=None):
131         # will be overwritten by __init__
132         pass
133
134     @staticmethod
135     def _write(out_fd, data):
136         out_fd.write(str(data))
137         out_fd.flush()
138
139     @staticmethod
140     def _read(in_fd):
141         ret = None
142         parser = XMLStreamParser()
143         while True:
144             line = in_fd.readline()
145             if len(line) == 0:
146                 # ikiwiki exited, EOF received
147                 return None
148
149             ret = parser.parse(line)
150             # unless this returns non-None, we need to loop again
151             if ret is not None:
152                 return ret
153
154     def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs):
155         xml = _xmlrpc_client.dumps(sum(kwargs.iteritems(), args), cmd)
156         self._debug_fn("calling ikiwiki procedure `{}': [{}]".format(cmd, xml))
157         _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
158
159         self._debug_fn('reading response from ikiwiki...')
160
161         xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
162         self._debug_fn(
163             'read response to procedure {} from ikiwiki: [{}]'.format(
164                 cmd, xml))
165         if xml is None:
166             # ikiwiki is going down
167             self._debug_fn('ikiwiki is going down, and so are we...')
168             raise GoingDown()
169
170         data = _xmlrpc_client.loads(xml)[0][0]
171         self._debug_fn(
172             'parsed data from response to procedure {}: [{}]'.format(
173                 cmd, data))
174         return data
175
176     def handle_rpc(self, in_fd, out_fd):
177         self._debug_fn('waiting for procedure calls from ikiwiki...')
178         xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
179         if xml is None:
180             # ikiwiki is going down
181             self._debug_fn('ikiwiki is going down, and so are we...')
182             raise GoingDown()
183
184         self._debug_fn(
185             'received procedure call from ikiwiki: [{}]'.format(xml))
186         params, method = _xmlrpc_client.loads(xml)
187         ret = self._dispatcher.dispatch(method, params)
188         xml = _xmlrpc_client.dumps((ret,), methodresponse=True)
189         self._debug_fn(
190                 'sending procedure response to ikiwiki: [{}]'.format(xml))
191         _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
192         return ret
193
194
195 class IkiWikiProcedureProxy(object):
196
197     # how to communicate None to ikiwiki
198     _IKIWIKI_NIL_SENTINEL = {'null':''}
199
200     # sleep during each iteration
201     _LOOP_DELAY = 0.1
202
203     def __init__(self, id, in_fd=sys.stdin, out_fd=sys.stdout, debug_fn=None):
204         self._id = id
205         self._in_fd = in_fd
206         self._out_fd = out_fd
207         self._hooks = list()
208         self._functions = list()
209         self._imported = False
210         if debug_fn is not None:
211             self._debug_fn = debug_fn
212         else:
213             self._debug_fn = lambda s: None
214         self._xmlrpc_handler = _IkiWikiExtPluginXMLRPCHandler(self._debug_fn)
215         self._xmlrpc_handler.register_function(self._importme, name='import')
216
217     def rpc(self, cmd, *args, **kwargs):
218         def subst_none(seq):
219             for i in seq:
220                 if i is None:
221                     yield IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
222                 else:
223                     yield i
224
225         args = list(subst_none(args))
226         kwargs = dict(zip(kwargs.keys(), list(subst_none(kwargs.itervalues()))))
227         ret = self._xmlrpc_handler.send_rpc(cmd, self._in_fd, self._out_fd,
228                                             *args, **kwargs)
229         if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
230             ret = None
231         return ret
232
233     def hook(self, type, function, name=None, id=None, last=False):
234         if self._imported:
235             raise AlreadyImported()
236
237         if name is None:
238             name = function.__name__
239
240         if id is None:
241             id = self._id
242
243         def hook_proxy(*args):
244 #            curpage = args[0]
245 #            kwargs = dict([args[i:i+2] for i in xrange(1, len(args), 2)])
246             ret = function(self, *args)
247             self._debug_fn(
248                     "{} hook `{}' returned: [{}]".format(type, name, ret))
249             if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
250                 raise InvalidReturnValue(
251                     'hook functions are not allowed to return {}'.format(
252                         IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL))
253             if ret is None:
254                 ret = IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
255             return ret
256
257         self._hooks.append((id, type, name, last))
258         self._xmlrpc_handler.register_function(hook_proxy, name=name)
259
260     def inject(self, rname, function, name=None, memoize=True):
261         if self._imported:
262             raise AlreadyImported()
263
264         if name is None:
265             name = function.__name__
266
267         self._functions.append((rname, name, memoize))
268         self._xmlrpc_handler.register_function(function, name=name)
269
270     def getargv(self):
271         return self.rpc('getargv')
272
273     def setargv(self, argv):
274         return self.rpc('setargv', argv)
275
276     def getvar(self, hash, key):
277         return self.rpc('getvar', hash, key)
278
279     def setvar(self, hash, key, value):
280         return self.rpc('setvar', hash, key, value)
281
282     def getstate(self, page, id, key):
283         return self.rpc('getstate', page, id, key)
284
285     def setstate(self, page, id, key, value):
286         return self.rpc('setstate', page, id, key, value)
287
288     def pagespec_match(self, spec):
289         return self.rpc('pagespec_match', spec)
290
291     def error(self, msg):
292         try:
293             self.rpc('error', msg)
294         except IOError as e:
295             if e.errno != 32:
296                 raise
297         import posix
298         sys.exit(posix.EX_SOFTWARE)
299
300     def run(self):
301         try:
302             while True:
303                 ret = self._xmlrpc_handler.handle_rpc(
304                     self._in_fd, self._out_fd)
305                 time.sleep(IkiWikiProcedureProxy._LOOP_DELAY)
306         except GoingDown:
307             return
308
309         except Exception as e:
310             import traceback
311             self.error('uncaught exception: {}\n{}'.format(
312                         e, traceback.format_exc(sys.exc_info()[2])))
313             return
314
315     def _importme(self):
316         self._debug_fn('importing...')
317         for id, type, function, last in self._hooks:
318             self._debug_fn('hooking {}/{} into {} chain...'.format(
319                     id, function, type))
320             self.rpc('hook', id=id, type=type, call=function, last=last)
321         for rname, function, memoize in self._functions:
322             self._debug_fn('injecting {} as {}...'.format(function, rname))
323             self.rpc('inject', name=rname, call=function, memoize=memoize)
324         self._imported = True
325         return IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL