]> sipb.mit.edu Git - ikiwiki.git/blob - plugins/proxy.py
yes, looks like a bug
[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 try:  # Python 3
47     import xmlrpc.server as _xmlrpc_server
48 except ImportError:  # Python 2
49     import SimpleXMLRPCServer as _xmlrpc_server
50
51
52 class ParseError (Exception):
53     pass
54
55
56 class PipeliningDetected (Exception):
57     pass
58
59
60 class GoingDown (Exception):
61     pass
62
63
64 class InvalidReturnValue (Exception):
65     pass
66
67
68 class AlreadyImported (Exception):
69     pass
70
71
72 class _IkiWikiExtPluginXMLRPCDispatcher(_xmlrpc_server.SimpleXMLRPCDispatcher):
73
74     def __init__(self, allow_none=False, encoding=None):
75         try:
76             _xmlrpc_server.SimpleXMLRPCDispatcher.__init__(
77                 self, allow_none, encoding)
78         except TypeError:
79             # see http://bugs.debian.org/470645
80             # python2.4 and before only took one argument
81             _xmlrpc_server.SimpleXMLRPCDispatcher.__init__(self)
82
83     def dispatch(self, method, params):
84         return self._dispatch(method, params)
85
86
87 class XMLStreamParser(object):
88
89     def __init__(self):
90         self._parser = xml.parsers.expat.ParserCreate()
91         self._parser.StartElementHandler = self._push_tag
92         self._parser.EndElementHandler = self._pop_tag
93         self._parser.XmlDeclHandler = self._check_pipelining
94         self._reset()
95
96     def _reset(self):
97         self._stack = list()
98         self._acc = r''
99         self._first_tag_received = False
100
101     def _push_tag(self, tag, attrs):
102         self._stack.append(tag)
103         self._first_tag_received = True
104
105     def _pop_tag(self, tag):
106         top = self._stack.pop()
107         if top != tag:
108             raise ParseError(
109                 'expected {0} closing tag, got {1}'.format(top, tag))
110
111     def _request_complete(self):
112         return self._first_tag_received and len(self._stack) == 0
113
114     def _check_pipelining(self, *args):
115         if self._first_tag_received:
116             raise PipeliningDetected('need a new line between XML documents')
117
118     def parse(self, data):
119         self._parser.Parse(data, False)
120         self._acc += data
121         if self._request_complete():
122             ret = self._acc
123             self._reset()
124             return ret
125
126
127 class _IkiWikiExtPluginXMLRPCHandler(object):
128
129     def __init__(self, debug_fn):
130         self._dispatcher = _IkiWikiExtPluginXMLRPCDispatcher()
131         self.register_function = self._dispatcher.register_function
132         self._debug_fn = debug_fn
133
134     def register_function(self, function, name=None):
135         # will be overwritten by __init__
136         pass
137
138     @staticmethod
139     def _write(out_fd, data):
140         out_fd.write(str(data))
141         out_fd.flush()
142
143     @staticmethod
144     def _read(in_fd):
145         ret = None
146         parser = XMLStreamParser()
147         while True:
148             line = in_fd.readline()
149             if len(line) == 0:
150                 # ikiwiki exited, EOF received
151                 return None
152
153             ret = parser.parse(line)
154             # unless this returns non-None, we need to loop again
155             if ret is not None:
156                 return ret
157
158     def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs):
159         xml = _xmlrpc_client.dumps(sum(kwargs.items(), args), cmd)
160         self._debug_fn(
161             "calling ikiwiki procedure `{0}': [{1}]".format(cmd, xml))
162         _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml.encode('utf8'))
163
164         self._debug_fn('reading response from ikiwiki...')
165
166         xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd).decode('utf8')
167         self._debug_fn(
168             'read response to procedure {0} from ikiwiki: [{1}]'.format(
169                 cmd, xml))
170         if xml is None:
171             # ikiwiki is going down
172             self._debug_fn('ikiwiki is going down, and so are we...')
173             raise GoingDown()
174
175         data = _xmlrpc_client.loads(xml)[0][0]
176         self._debug_fn(
177             'parsed data from response to procedure {0}: [{1}]'.format(
178                 cmd, repr(data)))
179         return data
180
181     def handle_rpc(self, in_fd, out_fd):
182         self._debug_fn('waiting for procedure calls from ikiwiki...')
183         xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
184         if xml is None:
185             # ikiwiki is going down
186             self._debug_fn('ikiwiki is going down, and so are we...')
187             raise GoingDown()
188
189         self._debug_fn(
190             'received procedure call from ikiwiki: [{0}]'.format(xml))
191         params, method = _xmlrpc_client.loads(xml)
192         ret = self._dispatcher.dispatch(method, params)
193         xml = _xmlrpc_client.dumps((ret,), methodresponse=True)
194         self._debug_fn(
195                 'sending procedure response to ikiwiki: [{0}]'.format(xml))
196         _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
197         return ret
198
199
200 class IkiWikiProcedureProxy(object):
201
202     # how to communicate None to ikiwiki
203     _IKIWIKI_NIL_SENTINEL = {'null':''}
204
205     # sleep during each iteration
206     _LOOP_DELAY = 0.1
207
208     def __init__(self, id, in_fd=sys.stdin, out_fd=sys.stdout, debug_fn=None):
209         self._id = id
210         self._in_fd = in_fd
211         self._out_fd = out_fd
212         self._hooks = list()
213         self._functions = list()
214         self._imported = False
215         if debug_fn is not None:
216             self._debug_fn = debug_fn
217         else:
218             self._debug_fn = lambda s: None
219         self._xmlrpc_handler = _IkiWikiExtPluginXMLRPCHandler(self._debug_fn)
220         self._xmlrpc_handler.register_function(self._importme, name='import')
221
222     def rpc(self, cmd, *args, **kwargs):
223         def subst_none(seq):
224             for i in seq:
225                 if i is None:
226                     yield IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
227                 else:
228                     yield i
229
230         args = list(subst_none(args))
231         kwargs = dict(zip(kwargs.keys(), list(subst_none(kwargs.values()))))
232         ret = self._xmlrpc_handler.send_rpc(cmd, self._in_fd, self._out_fd,
233                                             *args, **kwargs)
234         if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
235             ret = None
236         return ret
237
238     def hook(self, type, function, name=None, id=None, last=False):
239         if self._imported:
240             raise AlreadyImported()
241
242         if name is None:
243             name = function.__name__
244
245         if id is None:
246             id = self._id
247
248         def hook_proxy(*args):
249 #            curpage = args[0]
250 #            kwargs = dict([args[i:i+2] for i in xrange(1, len(args), 2)])
251             ret = function(self, *args)
252             self._debug_fn(
253                     "{0} hook `{1}' returned: [{2}]".format(type, name, repr(ret)))
254             if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
255                 raise InvalidReturnValue(
256                     'hook functions are not allowed to return {0}'.format(
257                         IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL))
258             if ret is None:
259                 ret = IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
260             return ret
261
262         self._hooks.append((id, type, name, last))
263         self._xmlrpc_handler.register_function(hook_proxy, name=name)
264
265     def inject(self, rname, function, name=None, memoize=True):
266         if self._imported:
267             raise AlreadyImported()
268
269         if name is None:
270             name = function.__name__
271
272         self._functions.append((rname, name, memoize))
273         self._xmlrpc_handler.register_function(function, name=name)
274
275     def getargv(self):
276         return self.rpc('getargv')
277
278     def setargv(self, argv):
279         return self.rpc('setargv', argv)
280
281     def getvar(self, hash, key):
282         return self.rpc('getvar', hash, key)
283
284     def setvar(self, hash, key, value):
285         return self.rpc('setvar', hash, key, value)
286
287     def getstate(self, page, id, key):
288         return self.rpc('getstate', page, id, key)
289
290     def setstate(self, page, id, key, value):
291         return self.rpc('setstate', page, id, key, value)
292
293     def pagespec_match(self, spec):
294         return self.rpc('pagespec_match', spec)
295
296     def error(self, msg):
297         try:
298             self.rpc('error', msg)
299         except IOError as e:
300             if e.errno != 32:
301                 raise
302         import posix
303         sys.exit(posix.EX_SOFTWARE)
304
305     def run(self):
306         try:
307             while True:
308                 ret = self._xmlrpc_handler.handle_rpc(
309                     self._in_fd, self._out_fd)
310                 time.sleep(IkiWikiProcedureProxy._LOOP_DELAY)
311         except GoingDown:
312             return
313
314         except Exception as e:
315             import traceback
316             tb = traceback.format_exc()
317             self.error('uncaught exception: {0}\n{1}'.format(e, tb))
318             return
319
320     def _importme(self):
321         self._debug_fn('importing...')
322         for id, type, function, last in self._hooks:
323             self._debug_fn('hooking {0}/{1} into {2} chain...'.format(
324                     id, function, type))
325             self.rpc('hook', id=id, type=type, call=function, last=last)
326         for rname, function, memoize in self._functions:
327             self._debug_fn('injecting {0} as {1}...'.format(function, rname))
328             self.rpc('inject', name=rname, call=function, memoize=memoize)
329         self._imported = True
330         return IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL