[MERGE]
[odoo/odoo.git] / addons / document_webdav / webdav_server.py
1 # -*- encoding: utf-8 -*-
2
3 #
4 # Copyright P. Christeas <p_christ@hol.gr> 2008,2009
5 #
6 #
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
12 # Service Company
13 #
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.
18 #
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.
23 #
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 ###############################################################################
28
29
30 import netsvc
31 import tools
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
37 import urlparse
38 import urllib
39 import re
40 from string import atoi,split
41 from DAV.errors import *
42 # from DAV.constants import DAV_VERSION_1, DAV_VERSION_2
43
44 khtml_re = re.compile(r' KHTML/([0-9\.]+) ')
45
46 def OpenDAVConfig(**kw):
47     class OpenDAV:
48         def __init__(self, **kw):
49             self.__dict__.update(**kw)
50
51         def getboolean(self, word):
52             return self.__dict__.get(word, False)
53
54     class Config:
55         DAV = OpenDAV(**kw)
56
57     return Config()
58
59
60 class DAVHandler(HttpOptions, FixSendError, DAVRequestHandler):
61     verbose = False
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', ]
67                     }
68
69     def get_userinfo(self,user,pw):
70         return False
71     def _log(self, message):
72         netsvc.Logger().notifyChannel("webdav",netsvc.LOG_DEBUG,message)
73
74     def handle(self):
75         self._init_buffer()
76
77     def finish(self):
78         pass
79
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)
83         return res
84
85     def setup(self):
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()
89         try:
90             if hasattr(self.request, 'getsockname'):
91                 addr, port = self.request.getsockname()
92         except Exception, e:
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)
97
98     def copymove(self, CLASS):
99         """ Our uri scheme removes the /webdav/ component from there, so we
100         need to mangle the header, too.
101         """
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):]
106         else:
107             raise DAV_Forbidden("Not allowed to copy/move outside webdav path")
108         DAVRequestHandler.copymove(self, CLASS)
109
110     def get_davpath(self):
111         return self.davpath
112
113     def log_message(self, format, *args):
114         netsvc.Logger().notifyChannel('webdav', netsvc.LOG_DEBUG_RPC, format % args)
115
116     def log_error(self, format, *args):
117         netsvc.Logger().notifyChannel('xmlrpc', netsvc.LOG_WARNING, format % args)
118
119     def _prep_OPTIONS(self, opts):
120         ret = opts
121         dc=self.IFACE_CLASS
122         uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
123         uri=urllib.unquote(uri)
124         try:
125             ret = dc.prep_http_options(uri, opts)
126         except DAV_Error, (ec,dd):
127             pass
128         except Exception,e:
129             self.log_error("Error at options: %s", str(e))
130             raise
131         return ret
132
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
146                 code = 200
147         BaseHTTPRequestHandler.send_response(self, int(code), message)
148
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)
153
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:
156             pass
157         elif self.request_version in ('HTTP/1.0', 'HTTP/0.9'):
158             pass
159         elif self.close_connection == 1: # close header already sent
160             pass
161         else:
162             if headers is None:
163                 headers = {}
164             if self.headers.get('Connection',False) == 'Keep-Alive':
165                 headers['Connection'] = 'keep-alive'
166
167         DAVRequestHandler.send_body(self, DATA, code=code, msg=msg, desc=desc,
168                     ctype=ctype, headers=headers)
169
170     def do_PUT(self):
171         dc=self.IFACE_CLASS
172         uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
173         uri=urllib.unquote(uri)
174         # Handle If-Match
175         if self.headers.has_key('If-Match'):
176             test = False
177             etag = None
178
179             for match in self.headers['If-Match'].split(','):
180                 if match == '*':
181                     if dc.exists(uri):
182                         test = True
183                         break
184                 else:
185                     if dc.match_prop(uri, match, "DAV:", "getetag"):
186                         test = True
187                         break
188             if not test:
189                 self._get_body()
190                 self.send_status(412)
191                 return
192
193         # Handle If-None-Match
194         if self.headers.has_key('If-None-Match'):
195             test = True
196             etag = None
197             for match in self.headers['If-None-Match'].split(','):
198                 if match == '*':
199                     if dc.exists(uri):
200                         test = False
201                         break
202                 else:
203                     if dc.match_prop(uri, match, "DAV:", "getetag"):
204                         test = False
205                         break
206             if not test:
207                 self._get_body()
208                 self.send_status(412)
209                 return
210
211         # Handle expect
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)
217             self._flush()
218
219         # read the body
220         body=self._get_body()
221
222         # locked resources are not allowed to be overwritten
223         if self._l_isLocked(uri):
224             return self.send_body(None, '423', 'Locked', 'Locked')
225
226         ct=None
227         if self.headers.has_key("Content-Type"):
228             ct=self.headers['Content-Type']
229         try:
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)
234
235         headers = {}
236         etag = None
237         if location and isinstance(location, tuple):
238             etag = location[1]
239             location = location[0]
240             # note that we have allowed for > 2 elems
241         if location:
242             headers['Location'] = location
243         else:
244             try:
245                 if not etag:
246                     etag = dc.get_prop(location or uri, "DAV:", "getetag")
247                 if etag:
248                     headers['ETag'] = str(etag)
249             except Exception:
250                 pass
251
252         self.send_body(None, '201', 'Created', '', headers=headers)
253
254     def _get_body(self):
255         body = None
256         if self.headers.has_key("Content-Length"):
257             l=self.headers['Content-Length']
258             body=self.rfile.read(atoi(l))
259         return body
260
261     def do_DELETE(self):
262         try:
263             DAVRequestHandler.do_DELETE(self)
264         except DAV_Error, (ec, dd):
265             return self.send_status(ec)
266
267 from service.http_server import reg_http_service,OpenERPAuthProvider
268
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.
273         """
274         if db is False:
275             return True
276         return OpenERPAuthProvider.authenticate(self, db, user, passwd, client_address)
277
278 try:
279
280     if (config.get_misc('webdav','enable',True)):
281         directory = '/'+config.get_misc('webdav','vdir','webdav')
282         handler = DAVHandler
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,
288                 }
289
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)
294 except Exception, e:
295     logger = netsvc.Logger()
296     logger.notifyChannel('webdav', netsvc.LOG_ERROR, 'Cannot launch webdav: %s' % e)
297
298 #eof
299
300
301