1 # -*- encoding: utf-8 -*-
4 # Copyright P. Christeas <p_christ@hol.gr> 2008,2009
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # garantees and support are strongly adviced to contract a Free Software
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 ###############################################################################
32 from dav_fs import openerp_dav_handler
33 from tools.config import config
34 from DAV.WebDAVServer import DAVRequestHandler
35 from service.websrv_lib import HTTPDir, FixSendError, HttpOptions
36 from BaseHTTPServer import BaseHTTPRequestHandler
40 from string import atoi,split
41 from DAV.errors import *
42 # from DAV.constants import DAV_VERSION_1, DAV_VERSION_2
44 khtml_re = re.compile(r' KHTML/([0-9\.]+) ')
46 def OpenDAVConfig(**kw):
48 def __init__(self, **kw):
49 self.__dict__.update(**kw)
51 def getboolean(self, word):
52 return self.__dict__.get(word, False)
60 class DAVHandler(HttpOptions, FixSendError, DAVRequestHandler):
62 protocol_version = 'HTTP/1.1'
63 _HTTP_OPTIONS= { 'DAV' : ['1', '2'],
64 'Allow' : [ 'GET', 'HEAD', 'COPY', 'MOVE', 'POST', 'PUT',
65 'PROPFIND', 'PROPPATCH', 'OPTIONS', 'MKCOL',
66 'DELETE', 'TRACE', 'REPORT', ]
69 def get_userinfo(self,user,pw):
71 def _log(self, message):
72 netsvc.Logger().notifyChannel("webdav",netsvc.LOG_DEBUG,message)
80 def get_db_from_path(self, uri):
81 # interface class will handle all cases.
82 res = self.IFACE_CLASS.get_db(uri, allow_last=True)
86 self.davpath = '/'+config.get_misc('webdav','vdir','webdav')
87 addr, port = self.server.server_name, self.server.server_port
88 server_proto = getattr(self.server,'proto', 'http').lower()
90 if hasattr(self.request, 'getsockname'):
91 addr, port = self.request.getsockname()
93 self.log_error("Cannot calculate own address: %s" , e)
94 # Too early here to use self.headers
95 self.baseuri = "%s://%s:%d/"% (server_proto, addr, port)
96 self.IFACE_CLASS = openerp_dav_handler(self, self.verbose)
98 def copymove(self, CLASS):
99 """ Our uri scheme removes the /webdav/ component from there, so we
100 need to mangle the header, too.
102 dest = self.headers['Destination']
103 up = urlparse.urlparse(urllib.unquote(self.headers['Destination']))
104 if up.path.startswith(self.davpath):
105 self.headers['Destination'] = up.path[len(self.davpath):]
107 raise DAV_Forbidden("Not allowed to copy/move outside webdav path")
108 DAVRequestHandler.copymove(self, CLASS)
110 def get_davpath(self):
113 def log_message(self, format, *args):
114 netsvc.Logger().notifyChannel('webdav', netsvc.LOG_DEBUG_RPC, format % args)
116 def log_error(self, format, *args):
117 netsvc.Logger().notifyChannel('xmlrpc', netsvc.LOG_WARNING, format % args)
119 def _prep_OPTIONS(self, opts):
122 uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
123 uri=urllib.unquote(uri)
125 ret = dc.prep_http_options(uri, opts)
126 except DAV_Error, (ec,dd):
129 self.log_error("Error at options: %s", str(e))
133 def send_response(self, code, message=None):
134 # the BufferingHttpServer will send Connection: close , while
135 # the BaseHTTPRequestHandler will only accept int code.
136 # workaround both of them.
137 if self.command == 'PROPFIND' and int(code) == 404:
138 kh = khtml_re.search(self.headers.get('User-Agent',''))
139 if kh and (kh.group(1) < '4.5'):
140 # There is an ugly bug in all khtml < 4.5.x, where the 404
141 # response is treated as an immediate error, which would even
142 # break the flow of a subsequent PUT request. At the same time,
143 # the 200 response (rather than 207 with content) is treated
144 # as "path not exist", so we send this instead
145 # https://bugs.kde.org/show_bug.cgi?id=166081
147 BaseHTTPRequestHandler.send_response(self, int(code), message)
149 def send_header(self, key, value):
150 if key == 'Connection' and value == 'close':
151 self.close_connection = 1
152 DAVRequestHandler.send_header(self, key, value)
154 def send_body(self, DATA, code = None, msg = None, desc = None, ctype='application/octet-stream', headers=None):
155 if headers and 'Connection' in headers:
157 elif self.request_version in ('HTTP/1.0', 'HTTP/0.9'):
159 elif self.close_connection == 1: # close header already sent
164 if self.headers.get('Connection',False) == 'Keep-Alive':
165 headers['Connection'] = 'keep-alive'
167 DAVRequestHandler.send_body(self, DATA, code=code, msg=msg, desc=desc,
168 ctype=ctype, headers=headers)
172 uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
173 uri=urllib.unquote(uri)
175 if self.headers.has_key('If-Match'):
179 for match in self.headers['If-Match'].split(','):
185 if dc.match_prop(uri, match, "DAV:", "getetag"):
190 self.send_status(412)
193 # Handle If-None-Match
194 if self.headers.has_key('If-None-Match'):
197 for match in self.headers['If-None-Match'].split(','):
203 if dc.match_prop(uri, match, "DAV:", "getetag"):
208 self.send_status(412)
212 expect = self.headers.get('Expect', '')
213 if (expect.lower() == '100-continue' and
214 self.protocol_version >= 'HTTP/1.1' and
215 self.request_version >= 'HTTP/1.1'):
216 self.send_status(100)
220 body=self._get_body()
222 # locked resources are not allowed to be overwritten
223 if self._l_isLocked(uri):
224 return self.send_body(None, '423', 'Locked', 'Locked')
227 if self.headers.has_key("Content-Type"):
228 ct=self.headers['Content-Type']
230 location = dc.put(uri, body, ct)
231 except DAV_Error, (ec,dd):
232 self.log_error("Cannot PUT to %s: %s", uri, dd)
233 return self.send_status(ec)
237 if location and isinstance(location, tuple):
239 location = location[0]
240 # note that we have allowed for > 2 elems
242 headers['Location'] = location
246 etag = dc.get_prop(location or uri, "DAV:", "getetag")
248 headers['ETag'] = str(etag)
252 self.send_body(None, '201', 'Created', '', headers=headers)
256 if self.headers.has_key("Content-Length"):
257 l=self.headers['Content-Length']
258 body=self.rfile.read(atoi(l))
263 DAVRequestHandler.do_DELETE(self)
264 except DAV_Error, (ec, dd):
265 return self.send_status(ec)
267 from service.http_server import reg_http_service,OpenERPAuthProvider
269 class DAVAuthProvider(OpenERPAuthProvider):
270 def authenticate(self, db, user, passwd, client_address):
271 """ authenticate, but also allow the False db, meaning to skip
272 authentication when no db is specified.
276 return OpenERPAuthProvider.authenticate(self, db, user, passwd, client_address)
280 if (config.get_misc('webdav','enable',True)):
281 directory = '/'+config.get_misc('webdav','vdir','webdav')
283 verbose = config.get_misc('webdav','verbose',True)
284 handler.debug = config.get_misc('webdav','debug',True)
285 _dc = { 'verbose' : verbose,
286 'directory' : directory,
287 'lockemulation' : True,
290 conf = OpenDAVConfig(**_dc)
291 handler._config = conf
292 reg_http_service(HTTPDir(directory,DAVHandler,DAVAuthProvider()))
293 netsvc.Logger().notifyChannel('webdav', netsvc.LOG_INFO, "WebDAV service registered at path: %s/ "% directory)
295 logger = netsvc.Logger()
296 logger.notifyChannel('webdav', netsvc.LOG_ERROR, 'Cannot launch webdav: %s' % e)