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