1 # -*- encoding: utf-8 -*-
2 ############################################################################9
4 # Copyright P. Christeas <p_christ@hol.gr> 2008-2010
5 # Copyright OpenERP SA, 2010 (http://www.openerp.com )
7 # Disclaimer: Many of the functions below borrow code from the
8 # python-webdav library (http://code.google.com/p/pywebdav/ ),
9 # which they import and override to suit OpenERP functionality.
10 # python-webdav was written by: Simon Pamies <s.pamies@banality.de>
11 # Christian Scholz <mrtopf@webdav.de>
12 # Vince Spicer <vince@vince.ca>
14 # WARNING: This program as such is intended to be used by professional
15 # programmers who take the whole responsability of assessing all potential
16 # consequences resulting from its eventual inadequacies and bugs
17 # End users who are looking for a ready-to-use solution with commercial
18 # garantees and support are strongly adviced to contract a Free Software
21 # This program is Free Software; you can redistribute it and/or
22 # modify it under the terms of the GNU General Public License
23 # as published by the Free Software Foundation; either version 3
24 # of the License, or (at your option) any later version.
26 # This program is distributed in the hope that it will be useful,
27 # but WITHOUT ANY WARRANTY; without even the implied warranty of
28 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 # GNU General Public License for more details.
31 # You should have received a copy of the GNU General Public License
32 # along with this program; if not, write to the Free Software
33 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 ###############################################################################
39 from dav_fs import openerp_dav_handler
40 from tools.config import config
41 from DAV.WebDAVServer import DAVRequestHandler
42 from service import http_server
43 from service.websrv_lib import HTTPDir, FixSendError, HttpOptions
44 from BaseHTTPServer import BaseHTTPRequestHandler
49 from string import atoi
51 from DAV.utils import IfParser, TagList
52 from DAV.errors import DAV_Error, DAV_Forbidden, DAV_NotFound
53 from DAV.propfind import PROPFIND
54 # from DAV.constants import DAV_VERSION_1, DAV_VERSION_2
55 from xml.dom import minidom
56 from redirect import RedirectHTTPHandler
58 khtml_re = re.compile(r' KHTML/([0-9\.]+) ')
60 def OpenDAVConfig(**kw):
62 def __init__(self, **kw):
63 self.__dict__.update(**kw)
65 def getboolean(self, word):
66 return self.__dict__.get(word, False)
74 class DAVHandler(HttpOptions, FixSendError, DAVRequestHandler):
76 _logger = logging.getLogger('webdav')
77 protocol_version = 'HTTP/1.1'
78 _HTTP_OPTIONS= { 'DAV' : ['1', '2'],
79 'Allow' : [ 'GET', 'HEAD', 'COPY', 'MOVE', 'POST', 'PUT',
80 'PROPFIND', 'PROPPATCH', 'OPTIONS', 'MKCOL',
81 'DELETE', 'TRACE', 'REPORT', ]
84 def get_userinfo(self,user,pw):
87 def _log(self, message):
88 self._logger.debug(message)
96 def get_db_from_path(self, uri):
97 # interface class will handle all cases.
98 res = self.IFACE_CLASS.get_db(uri, allow_last=True)
102 self.davpath = '/'+config.get_misc('webdav','vdir','webdav')
103 addr, port = self.server.server_name, self.server.server_port
104 server_proto = getattr(self.server,'proto', 'http').lower()
106 if hasattr(self.request, 'getsockname'):
107 addr, port = self.request.getsockname()
109 self.log_error("Cannot calculate own address: %s" , e)
110 # Too early here to use self.headers
111 self.baseuri = "%s://%s:%d/"% (server_proto, addr, port)
112 self.IFACE_CLASS = openerp_dav_handler(self, self.verbose)
114 def copymove(self, CLASS):
115 """ Our uri scheme removes the /webdav/ component from there, so we
116 need to mangle the header, too.
118 up = urlparse.urlparse(urllib.unquote(self.headers['Destination']))
119 if up.path.startswith(self.davpath):
120 self.headers['Destination'] = up.path[len(self.davpath):]
122 raise DAV_Forbidden("Not allowed to copy/move outside webdav path")
124 DAVRequestHandler.copymove(self, CLASS)
126 def get_davpath(self):
129 def log_message(self, format, *args):
130 self._logger.log(netsvc.logging.DEBUG_RPC,format % args)
132 def log_error(self, format, *args):
133 self._logger.warning(format % args)
135 def _prep_OPTIONS(self, opts):
138 uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
139 uri=urllib.unquote(uri)
141 ret = dc.prep_http_options(uri, opts)
142 except DAV_Error, (ec,dd):
145 self.log_error("Error at options: %s", str(e))
149 def send_response(self, code, message=None):
150 # the BufferingHttpServer will send Connection: close , while
151 # the BaseHTTPRequestHandler will only accept int code.
152 # workaround both of them.
153 if self.command == 'PROPFIND' and int(code) == 404:
154 kh = khtml_re.search(self.headers.get('User-Agent',''))
155 if kh and (kh.group(1) < '4.5'):
156 # There is an ugly bug in all khtml < 4.5.x, where the 404
157 # response is treated as an immediate error, which would even
158 # break the flow of a subsequent PUT request. At the same time,
159 # the 200 response (rather than 207 with content) is treated
160 # as "path not exist", so we send this instead
161 # https://bugs.kde.org/show_bug.cgi?id=166081
163 BaseHTTPRequestHandler.send_response(self, int(code), message)
165 def send_header(self, key, value):
166 if key == 'Connection' and value == 'close':
167 self.close_connection = 1
168 DAVRequestHandler.send_header(self, key, value)
170 def send_body(self, DATA, code = None, msg = None, desc = None, ctype='application/octet-stream', headers=None):
171 if headers and 'Connection' in headers:
173 elif self.request_version in ('HTTP/1.0', 'HTTP/0.9'):
175 elif self.close_connection == 1: # close header already sent
180 if self.headers.get('Connection',False) == 'Keep-Alive':
181 headers['Connection'] = 'keep-alive'
183 DAVRequestHandler.send_body(self, DATA, code=code, msg=msg, desc=desc,
184 ctype=ctype, headers=headers)
188 uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
189 uri=urllib.unquote(uri)
191 if self.headers.has_key('If-Match'):
195 for match in self.headers['If-Match'].split(','):
201 if dc.match_prop(uri, match, "DAV:", "getetag"):
206 self.send_status(412)
209 # Handle If-None-Match
210 if self.headers.has_key('If-None-Match'):
213 for match in self.headers['If-None-Match'].split(','):
219 if dc.match_prop(uri, match, "DAV:", "getetag"):
224 self.send_status(412)
228 expect = self.headers.get('Expect', '')
229 if (expect.lower() == '100-continue' and
230 self.protocol_version >= 'HTTP/1.1' and
231 self.request_version >= 'HTTP/1.1'):
232 self.send_status(100)
236 body=self._get_body()
238 # locked resources are not allowed to be overwritten
239 if self._l_isLocked(uri):
240 return self.send_body(None, '423', 'Locked', 'Locked')
243 if self.headers.has_key("Content-Type"):
244 ct=self.headers['Content-Type']
246 location = dc.put(uri, body, ct)
247 except DAV_Error, (ec,dd):
248 self.log_error("Cannot PUT to %s: %s", uri, dd)
249 return self.send_status(ec)
253 if location and isinstance(location, tuple):
255 location = location[0]
256 # note that we have allowed for > 2 elems
258 headers['Location'] = location
262 etag = dc.get_prop(location or uri, "DAV:", "getetag")
264 headers['ETag'] = str(etag)
268 self.send_body(None, '201', 'Created', '', headers=headers)
272 if self.headers.has_key("Content-Length"):
273 l=self.headers['Content-Length']
274 body=self.rfile.read(atoi(l))
279 DAVRequestHandler.do_DELETE(self)
280 except DAV_Error, (ec, dd):
281 return self.send_status(ec)
284 """ Unlocks given resource """
286 dc = self.IFACE_CLASS
287 self.log_message('UNLOCKing resource %s' % self.headers)
289 uri = urlparse.urljoin(self.get_baseuri(dc), self.path)
290 uri = urllib.unquote(uri)
292 token = self.headers.get('Lock-Token', False)
294 token = token.strip()
295 if token[0] == '<' and token[-1] == '>':
301 return self.send_status(400, 'Bad lock token')
304 res = dc.unlock(uri, token)
305 except DAV_Error, (ec, dd):
306 return self.send_status(ec, dd)
309 self.send_body(None, '204', 'OK', 'Resource unlocked.')
311 # We just differentiate the description, for debugging purposes
312 self.send_body(None, '204', 'OK', 'Resource not locked.')
315 """ Attempt to place a lock on the given resource.
318 dc = self.IFACE_CLASS
321 self.log_message('LOCKing resource %s' % self.headers)
324 if self.headers.has_key('Content-Length'):
325 l = self.headers['Content-Length']
326 body = self.rfile.read(atoi(l))
328 depth = self.headers.get('Depth', 'infinity')
330 uri = urlparse.urljoin(self.get_baseuri(dc), self.path)
331 uri = urllib.unquote(uri)
332 self.log_message('do_LOCK: uri = %s' % uri)
334 ifheader = self.headers.get('If')
337 ldif = IfParser(ifheader)
338 if isinstance(ldif, list):
339 if len(ldif) !=1 or (not isinstance(ldif[0], TagList)) \
340 or len(ldif[0].list) != 1:
341 raise DAV_Error(400, "Cannot accept multiple tokens")
342 ldif = ldif[0].list[0]
343 if ldif[0] == '<' and ldif[-1] == '>':
346 lock_data['token'] = ldif
349 lock_data['refresh'] = True
351 lock_data['refresh'] = False
352 lock_data.update(self._lock_unlock_parse(body))
354 if lock_data['refresh'] and not lock_data.get('token', False):
355 raise DAV_Error(400, 'Lock refresh must specify token')
357 lock_data['depth'] = depth
360 created, data, lock_token = dc.lock(uri, lock_data)
361 except DAV_Error, (ec, dd):
362 return self.send_status(ec, dd)
365 if not lock_data['refresh']:
366 headers['Lock-Token'] = '<%s>' % lock_token
369 self.send_body(data, '201', 'Created', ctype='text/xml', headers=headers)
371 self.send_body(data, '200', 'OK', ctype='text/xml', headers=headers)
373 def _lock_unlock_parse(self, body):
374 # Override the python-webdav function, with some improvements
375 # Unlike the py-webdav one, we also parse the owner minidom elements into
376 # pure pythonic struct.
377 doc = minidom.parseString(body)
381 for info in doc.getElementsByTagNameNS('DAV:', 'lockinfo'):
382 for scope in info.getElementsByTagNameNS('DAV:', 'lockscope'):
383 for scc in scope.childNodes:
384 if scc.nodeType == info.ELEMENT_NODE \
385 and scc.namespaceURI == 'DAV:':
386 data['lockscope'] = scc.localName
388 for ltype in info.getElementsByTagNameNS('DAV:', 'locktype'):
389 for ltc in ltype.childNodes:
390 if ltc.nodeType == info.ELEMENT_NODE \
391 and ltc.namespaceURI == 'DAV:':
392 data['locktype'] = ltc.localName
394 for own in info.getElementsByTagNameNS('DAV:', 'owner'):
395 for ono in own.childNodes:
396 if ono.nodeType == info.TEXT_NODE:
398 owners.append(ono.data)
399 elif ono.nodeType == info.ELEMENT_NODE \
400 and ono.namespaceURI == 'DAV:' \
401 and ono.localName == 'href':
403 for hno in ono.childNodes:
404 if hno.nodeType == info.TEXT_NODE:
406 owners.append(('href','DAV:', href))
409 data['lockowner'] = owners[0]
413 data['lockowner'] = owners
416 from service.http_server import reg_http_service,OpenERPAuthProvider
418 class DAVAuthProvider(OpenERPAuthProvider):
419 def authenticate(self, db, user, passwd, client_address):
420 """ authenticate, but also allow the False db, meaning to skip
421 authentication when no db is specified.
425 return OpenERPAuthProvider.authenticate(self, db, user, passwd, client_address)
428 class dummy_dav_interface(object):
429 """ Dummy dav interface """
432 PROPS={"DAV:" : ('creationdate',
439 M_NS={"DAV:" : "_get_dav", }
441 def __init__(self, parent):
444 def get_propnames(self,uri):
447 def get_prop(self,uri,ns,propname):
448 if self.M_NS.has_key(ns):
452 mname=prefix+"_"+propname.replace('-', '_')
454 m=getattr(self,mname)
457 except AttributeError:
460 def get_data(self, uri, range=None):
463 def _get_dav_creationdate(self,uri):
464 return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
466 def _get_dav_getlastmodified(self,uri):
467 return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
469 def _get_dav_displayname(self, uri):
472 def _get_dav_resourcetype(self, uri):
473 return ('collection', 'DAV:')
475 def exists(self, uri):
476 """ return 1 or None depending on if a resource exists """
477 uri2 = uri.split('/')
480 logging.getLogger('webdav').debug("Requested uri: %s", uri)
483 def is_collection(self, uri):
484 """ return 1 or None depending on if a resource is a collection """
487 class DAVStaticHandler(http_server.StaticHTTPHandler):
488 """ A variant of the Static handler, which will serve dummy DAV requests
491 protocol_version = 'HTTP/1.1'
492 _HTTP_OPTIONS= { 'DAV' : ['1', '2'],
493 'Allow' : [ 'GET', 'HEAD',
494 'PROPFIND', 'OPTIONS', 'REPORT', ]
497 def send_body(self, content, code, message='OK', content_type='text/xml'):
498 self.send_response(int(code), message)
499 self.send_header("Content-Type", content_type)
500 # self.send_header('Connection', 'close')
501 self.send_header('Content-Length', len(content) or 0)
503 if hasattr(self, '_flush'):
506 if self.command != 'HEAD':
507 self.wfile.write(content)
509 def do_PROPFIND(self):
510 """Answer to PROPFIND with generic data.
512 A rough copy of python-webdav's do_PROPFIND, but hacked to work
516 dc = dummy_dav_interface(self)
518 # read the body containing the xml request
519 # iff there is no body then this is an ALLPROP request
521 if self.headers.has_key('Content-Length'):
522 l = self.headers['Content-Length']
523 body = self.rfile.read(atoi(l))
525 path = self.path.rstrip('/')
526 uri = urllib.unquote(path)
528 pf = PROPFIND(uri, dc, self.headers.get('Depth', 'infinity'), body)
531 DATA = '%s\n' % pf.createResponse()
532 except DAV_Error, (ec,dd):
533 return self.send_error(ec,dd)
535 self.log_exception("Cannot PROPFIND")
538 # work around MSIE DAV bug for creation and modified date
539 # taken from Resource.py @ Zope webdav
540 if (self.headers.get('User-Agent') ==
541 'Microsoft Data Access Internet Publishing Provider DAV 1.1'):
542 DATA = DATA.replace('<ns0:getlastmodified xmlns:ns0="DAV:">',
543 '<ns0:getlastmodified xmlns:n="DAV:" xmlns:b="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/" b:dt="dateTime.rfc1123">')
544 DATA = DATA.replace('<ns0:creationdate xmlns:ns0="DAV:">',
545 '<ns0:creationdate xmlns:n="DAV:" xmlns:b="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/" b:dt="dateTime.tz">')
547 self.send_body(DATA, '207','Multi-Status','Multiple responses')
549 def not_get_baseuri(self):
551 if self.headers.has_key('Host'):
552 uparts = list(urlparse.urlparse('/'))
553 uparts[1] = self.headers['Host']
554 baseuri = urlparse.urlunparse(uparts)
557 def get_davpath(self):
563 if (config.get_misc('webdav','enable',True)):
564 directory = '/'+config.get_misc('webdav','vdir','webdav')
566 verbose = config.get_misc('webdav','verbose',True)
567 handler.debug = config.get_misc('webdav','debug',True)
568 _dc = { 'verbose' : verbose,
569 'directory' : directory,
570 'lockemulation' : True,
573 conf = OpenDAVConfig(**_dc)
574 handler._config = conf
575 reg_http_service(HTTPDir(directory,DAVHandler,DAVAuthProvider()))
576 logging.getLogger('webdav').info("WebDAV service registered at path: %s/ "% directory)
578 if not (config.get_misc('webdav', 'no_root_hack', False)):
579 # Now, replace the static http handler with the dav-enabled one.
580 # If a static-http service has been specified for our server, then
581 # read its configuration and use that dir_path.
582 # NOTE: this will _break_ any other service that would be registered
583 # at the root path in future.
585 if config.get_misc('static-http','enable', False):
586 base_path = config.get_misc('static-http', 'base_path', '/')
587 if base_path and base_path == '/':
588 dir_path = config.get_misc('static-http', 'dir_path', False)
590 dir_path = addons.get_module_resource('document_webdav','public_html')
591 # an _ugly_ hack: we put that dir back in tools.config.misc, so that
592 # the StaticHttpHandler can find its dir_path.
593 config.misc.setdefault('static-http',{})['dir_path'] = dir_path
595 if reg_http_service(HTTPDir('/', DAVStaticHandler)):
596 logging.getLogger("web-services").info("WebDAV registered HTTP dir %s for /" % \
600 logging.getLogger('webdav').error('Cannot launch webdav: %s' % e)
603 def init_well_known():
604 reps = RedirectHTTPHandler.redirect_paths
606 num_svcs = config.get_misc('http-well-known', 'num_services', '0')
608 for nsv in range(1, int(num_svcs)+1):
609 uri = config.get_misc('http-well-known', 'service_%d' % nsv, False)
610 path = config.get_misc('http-well-known', 'path_%d' % nsv, False)
611 if not (uri and path):
616 if http_server.reg_http_service(HTTPDir('/.well-known', RedirectHTTPHandler)):
617 logging.getLogger("web-services").info("Registered HTTP redirect handler at /.well-known" )
621 class PrincipalsRedirect(RedirectHTTPHandler):
624 def _find_redirect(self):
625 for b, r in self.redirect_paths.items():
626 if self.path.startswith(b):
627 return r + self.path[len(b):]
630 def init_principals_redirect():
631 """ Some devices like the iPhone will look under /principals/users/xxx for
632 the user's properties. In OpenERP we _cannot_ have a stray /principals/...
633 working path, since we have a database path and the /webdav/ component. So,
634 the best solution is to redirect the url with 301. Luckily, it does work in
635 the device. The trick is that we need to hard-code the database to use, either
636 the one centrally defined in the config, or a "forced" one in the webdav
639 dbname = config.get_misc('webdav', 'principal_dbname', False)
640 if (not dbname) and not config.get_misc('webdav', 'no_principals_redirect', False):
641 dbname = config.get('db_name', False)
643 PrincipalsRedirect.redirect_paths[''] = '/webdav/%s/principals' % dbname
644 reg_http_service(HTTPDir('/principals', PrincipalsRedirect))
645 logging.getLogger("web-services").info(
646 "Registered HTTP redirect handler for /principals to the %s db.",
649 init_principals_redirect()