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 ###############################################################################
31 from dav_fs import openerp_dav_handler
32 from tools.config import config
33 from DAV.WebDAVServer import DAVRequestHandler
34 from service.websrv_lib import HTTPDir, FixSendError, HttpOptions
35 from BaseHTTPServer import BaseHTTPRequestHandler
39 from string import atoi
40 from DAV.errors import *
41 # from DAV.constants import DAV_VERSION_1, DAV_VERSION_2
43 khtml_re = re.compile(r' KHTML/([0-9\.]+) ')
45 def OpenDAVConfig(**kw):
47 def __init__(self, **kw):
48 self.__dict__.update(**kw)
50 def getboolean(self, word):
51 return self.__dict__.get(word, False)
59 class DAVHandler(HttpOptions, FixSendError, DAVRequestHandler):
61 protocol_version = 'HTTP/1.1'
62 _HTTP_OPTIONS= { 'DAV' : ['1', '2'],
63 'Allow' : [ 'GET', 'HEAD', 'COPY', 'MOVE', 'POST', 'PUT',
64 'PROPFIND', 'PROPPATCH', 'OPTIONS', 'MKCOL',
65 'DELETE', 'TRACE', 'REPORT', ]
68 def get_userinfo(self,user,pw):
70 def _log(self, message):
71 netsvc.Logger().notifyChannel("webdav",netsvc.LOG_DEBUG,message)
79 def get_db_from_path(self, uri):
80 # interface class will handle all cases.
81 res = self.IFACE_CLASS.get_db(uri, allow_last=True)
85 self.davpath = '/'+config.get_misc('webdav','vdir','webdav')
86 addr, port = self.server.server_name, self.server.server_port
87 server_proto = getattr(self.server,'proto', 'http').lower()
89 if hasattr(self.request, 'getsockname'):
90 addr, port = self.request.getsockname()
92 self.log_error("Cannot calculate own address: %s" , e)
93 # Too early here to use self.headers
94 self.baseuri = "%s://%s:%d/"% (server_proto, addr, port)
95 self.IFACE_CLASS = openerp_dav_handler(self, self.verbose)
97 def copymove(self, CLASS):
98 """ Our uri scheme removes the /webdav/ component from there, so we
99 need to mangle the header, too.
101 up = urlparse.urlparse(urllib.unquote(self.headers['Destination']))
102 if up.path.startswith(self.davpath):
103 self.headers['Destination'] = up.path[len(self.davpath):]
105 raise DAV_Forbidden("Not allowed to copy/move outside webdav path")
106 DAVRequestHandler.copymove(self, CLASS)
108 def get_davpath(self):
111 def log_message(self, format, *args):
112 netsvc.Logger().notifyChannel('webdav', netsvc.LOG_DEBUG_RPC, format % args)
114 def log_error(self, format, *args):
115 netsvc.Logger().notifyChannel('xmlrpc', netsvc.LOG_WARNING, format % args)
117 def _prep_OPTIONS(self, opts):
120 uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
121 uri=urllib.unquote(uri)
123 ret = dc.prep_http_options(uri, opts)
124 except DAV_Error, (ec,dd):
127 self.log_error("Error at options: %s", str(e))
131 def send_response(self, code, message=None):
132 # the BufferingHttpServer will send Connection: close , while
133 # the BaseHTTPRequestHandler will only accept int code.
134 # workaround both of them.
135 if self.command == 'PROPFIND' and int(code) == 404:
136 kh = khtml_re.search(self.headers.get('User-Agent',''))
137 if kh and (kh.group(1) < '4.5'):
138 # There is an ugly bug in all khtml < 4.5.x, where the 404
139 # response is treated as an immediate error, which would even
140 # break the flow of a subsequent PUT request. At the same time,
141 # the 200 response (rather than 207 with content) is treated
142 # as "path not exist", so we send this instead
143 # https://bugs.kde.org/show_bug.cgi?id=166081
145 BaseHTTPRequestHandler.send_response(self, int(code), message)
147 def send_header(self, key, value):
148 if key == 'Connection' and value == 'close':
149 self.close_connection = 1
150 DAVRequestHandler.send_header(self, key, value)
152 def send_body(self, DATA, code = None, msg = None, desc = None, ctype='application/octet-stream', headers=None):
153 if headers and 'Connection' in headers:
155 elif self.request_version in ('HTTP/1.0', 'HTTP/0.9'):
157 elif self.close_connection == 1: # close header already sent
162 if self.headers.get('Connection',False) == 'Keep-Alive':
163 headers['Connection'] = 'keep-alive'
165 DAVRequestHandler.send_body(self, DATA, code=code, msg=msg, desc=desc,
166 ctype=ctype, headers=headers)
170 uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
171 uri=urllib.unquote(uri)
173 if self.headers.has_key('If-Match'):
177 for match in self.headers['If-Match'].split(','):
183 if dc.match_prop(uri, match, "DAV:", "getetag"):
188 self.send_status(412)
191 # Handle If-None-Match
192 if self.headers.has_key('If-None-Match'):
195 for match in self.headers['If-None-Match'].split(','):
201 if dc.match_prop(uri, match, "DAV:", "getetag"):
206 self.send_status(412)
210 expect = self.headers.get('Expect', '')
211 if (expect.lower() == '100-continue' and
212 self.protocol_version >= 'HTTP/1.1' and
213 self.request_version >= 'HTTP/1.1'):
214 self.send_status(100)
218 body=self._get_body()
220 # locked resources are not allowed to be overwritten
221 if self._l_isLocked(uri):
222 return self.send_body(None, '423', 'Locked', 'Locked')
225 if self.headers.has_key("Content-Type"):
226 ct=self.headers['Content-Type']
228 location = dc.put(uri, body, ct)
229 except DAV_Error, (ec,dd):
230 self.log_error("Cannot PUT to %s: %s", uri, dd)
231 return self.send_status(ec)
235 if location and isinstance(location, tuple):
237 location = location[0]
238 # note that we have allowed for > 2 elems
240 headers['Location'] = location
244 etag = dc.get_prop(location or uri, "DAV:", "getetag")
246 headers['ETag'] = str(etag)
250 self.send_body(None, '201', 'Created', '', headers=headers)
254 if self.headers.has_key("Content-Length"):
255 l=self.headers['Content-Length']
256 body=self.rfile.read(atoi(l))
261 DAVRequestHandler.do_DELETE(self)
262 except DAV_Error, (ec, dd):
263 return self.send_status(ec)
265 from service.http_server import reg_http_service,OpenERPAuthProvider
267 class DAVAuthProvider(OpenERPAuthProvider):
268 def authenticate(self, db, user, passwd, client_address):
269 """ authenticate, but also allow the False db, meaning to skip
270 authentication when no db is specified.
274 return OpenERPAuthProvider.authenticate(self, db, user, passwd, client_address)
276 from service.http_server import reg_http_service,OpenERPAuthProvider
278 class DAVAuthProvider(OpenERPAuthProvider):
279 def authenticate(self, db, user, passwd, client_address):
280 """ authenticate, but also allow the False db, meaning to skip
281 authentication when no db is specified.
285 return OpenERPAuthProvider.authenticate(self, db, user, passwd, client_address)
289 if (config.get_misc('webdav','enable',True)):
290 directory = '/'+config.get_misc('webdav','vdir','webdav')
292 verbose = config.get_misc('webdav','verbose',True)
293 handler.debug = config.get_misc('webdav','debug',True)
294 _dc = { 'verbose' : verbose,
295 'directory' : directory,
296 'lockemulation' : True,
299 conf = OpenDAVConfig(**_dc)
300 handler._config = conf
301 reg_http_service(HTTPDir(directory,DAVHandler,DAVAuthProvider()))
302 netsvc.Logger().notifyChannel('webdav', netsvc.LOG_INFO, "WebDAV service registered at path: %s/ "% directory)
304 logger = netsvc.Logger()
305 logger.notifyChannel('webdav', netsvc.LOG_ERROR, 'Cannot launch webdav: %s' % e)