doc webdav: more tests in lib, yaml
[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 from string import atoi,split
40 from DAV.errors import *
41 # from DAV.constants import DAV_VERSION_1, DAV_VERSION_2
42
43 def OpenDAVConfig(**kw):
44     class OpenDAV:
45         def __init__(self, **kw):
46             self.__dict__.update(**kw)
47
48         def getboolean(self, word):
49             return self.__dict__.get(word, False)
50
51     class Config:
52         DAV = OpenDAV(**kw)
53
54     return Config()
55
56
57 class DAVHandler(HttpOptions, FixSendError, DAVRequestHandler):
58     verbose = False
59     protocol_version = 'HTTP/1.1'
60     _HTTP_OPTIONS= { 'DAV' : ['1', '2'],
61                     'Allow' : [ 'GET', 'HEAD', 'COPY', 'MOVE', 'POST', 'PUT',
62                             'PROPFIND', 'PROPPATCH', 'OPTIONS', 'MKCOL',
63                             'DELETE', 'TRACE', 'REPORT', ]
64                     }
65
66     def get_userinfo(self,user,pw):
67         return False
68     def _log(self, message):
69         netsvc.Logger().notifyChannel("webdav",netsvc.LOG_DEBUG,message)
70
71     def handle(self):
72         self._init_buffer()
73
74     def finish(self):
75         pass
76
77     def get_db_from_path(self, uri):
78         # interface class will handle all cases.
79         res =  self.IFACE_CLASS.get_db(uri, allow_last=True)
80         return res
81
82     def setup(self):
83         self.davpath = '/'+config.get_misc('webdav','vdir','webdav')
84         addr, port = self.server.server_name, self.server.server_port
85         server_proto = getattr(self.server,'proto', 'http').lower()
86         try:
87             if hasattr(self.request, 'getsockname'):
88                 addr, port = self.request.getsockname()
89         except Exception, e:
90             self.log_error("Cannot calculate own address: %s" , e)
91         # Too early here to use self.headers
92         self.baseuri = "%s://%s:%d/"% (server_proto, addr, port)
93         self.IFACE_CLASS  = openerp_dav_handler(self, self.verbose)
94
95     def copymove(self, CLASS):
96         """ Our uri scheme removes the /webdav/ component from there, so we
97         need to mangle the header, too.
98         """
99         dest = self.headers['Destination']
100         up = urlparse.urlparse(urllib.unquote(self.headers['Destination']))
101         if up.path.startswith(self.davpath):
102             self.headers['Destination'] = up.path[len(self.davpath):]
103         else:
104             raise DAV_Forbidden("Not allowed to copy/move outside webdav path")
105         DAVRequestHandler.copymove(self, CLASS)
106
107     def get_davpath(self):
108         return self.davpath
109
110     def log_message(self, format, *args):
111         netsvc.Logger().notifyChannel('webdav', netsvc.LOG_DEBUG_RPC, format % args)
112
113     def log_error(self, format, *args):
114         netsvc.Logger().notifyChannel('xmlrpc', netsvc.LOG_WARNING, format % args)
115
116     def _prep_OPTIONS(self, opts):
117         ret = opts
118         dc=self.IFACE_CLASS
119         uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
120         uri=urllib.unquote(uri)
121         try:
122             ret = dc.prep_http_options(uri, opts)
123         except DAV_Error, (ec,dd):
124             pass
125         except Exception,e:
126             self.log_error("Error at options: %s", str(e))
127             raise
128         return ret
129
130     def send_response(self, code, message=None):
131         # the BufferingHttpServer will send Connection: close , while
132         # the BaseHTTPRequestHandler will only accept int code.
133         # workaround both of them.
134         BaseHTTPRequestHandler.send_response(self, int(code), message)
135
136     def send_header(self, key, value):
137         if key == 'Connection' and value == 'close':
138             self.close_connection = 1
139         DAVRequestHandler.send_header(self, key, value)
140
141     def send_body(self, DATA, code = None, msg = None, desc = None, ctype='application/octet-stream', headers=None):
142         if headers and 'Connection' in headers:
143             pass
144         elif self.request_version in ('HTTP/1.0', 'HTTP/0.9'):
145             pass
146         elif self.close_connection == 1: # close header already sent
147             pass
148         else:
149             if headers is None:
150                 headers = {}
151             if self.headers.get('Connection',False) == 'Keep-Alive':
152                 headers['Connection'] = 'keep-alive'
153
154         DAVRequestHandler.send_body(self, DATA, code=code, msg=msg, desc=desc,
155                     ctype=ctype, headers=headers)
156
157     def do_PUT(self):
158         dc=self.IFACE_CLASS
159         uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
160         uri=urllib.unquote(uri)
161         # Handle If-Match
162         if self.headers.has_key('If-Match'):
163             test = False
164             etag = None
165
166             for match in self.headers['If-Match'].split(','):
167                 if match == '*':
168                     if dc.exists(uri):
169                         test = True
170                         break
171                 else:
172                     if dc.match_prop(uri, match, "DAV:", "getetag"):
173                         test = True
174                         break
175             if not test:
176                 self._get_body()
177                 self.send_status(412)
178                 return
179
180         # Handle If-None-Match
181         if self.headers.has_key('If-None-Match'):
182             test = True
183             etag = None
184             for match in self.headers['If-None-Match'].split(','):
185                 if match == '*':
186                     if dc.exists(uri):
187                         test = False
188                         break
189                 else:
190                     if dc.match_prop(uri, match, "DAV:", "getetag"):
191                         test = False
192                         break
193             if not test:
194                 self._get_body()
195                 self.send_status(412)
196                 return
197
198         # Handle expect
199         expect = self.headers.get('Expect', '')
200         if (expect.lower() == '100-continue' and
201                 self.protocol_version >= 'HTTP/1.1' and
202                 self.request_version >= 'HTTP/1.1'):
203             self.send_status(100)
204             self._flush()
205
206         # read the body
207         body=self._get_body()
208
209         # locked resources are not allowed to be overwritten
210         if self._l_isLocked(uri):
211             return self.send_body(None, '423', 'Locked', 'Locked')
212
213         ct=None
214         if self.headers.has_key("Content-Type"):
215             ct=self.headers['Content-Type']
216         try:
217             location = dc.put(uri, body, ct)
218         except DAV_Error, (ec,dd):
219             self._logger.warning("Cannot PUT to %s: %s", uri, dd, exc_info=True)
220             return self.send_status(ec)
221
222         headers = {}
223         etag = None
224         if location and isinstance(location, tuple):
225             etag = location[1]
226             location = location[0]
227             # note that we have allowed for > 2 elems
228         if location:
229             headers['Location'] = location
230         else:
231             try:
232                 if not etag:
233                     etag = dc.get_prop(location or uri, "DAV:", "getetag")
234                 if etag:
235                     headers['ETag'] = str(etag)
236             except Exception:
237                 pass
238
239         self.send_body(None, '201', 'Created', '', headers=headers)
240
241     def _get_body(self):
242         body = None
243         if self.headers.has_key("Content-Length"):
244             l=self.headers['Content-Length']
245             body=self.rfile.read(atoi(l))
246         return body
247
248     def do_DELETE(self):
249         try:
250             DAVRequestHandler.do_DELETE(self)
251         except DAV_Error, (ec, dd):
252             return self.send_status(ec)
253
254 from service.http_server import reg_http_service,OpenERPAuthProvider
255
256 class DAVAuthProvider(OpenERPAuthProvider):
257     def authenticate(self, db, user, passwd, client_address):
258         """ authenticate, but also allow the False db, meaning to skip
259             authentication when no db is specified.
260         """
261         if db is False:
262             return True
263         return OpenERPAuthProvider.authenticate(self, db, user, passwd, client_address)
264
265 try:
266
267     if (config.get_misc('webdav','enable',True)):
268         directory = '/'+config.get_misc('webdav','vdir','webdav')
269         handler = DAVHandler
270         verbose = config.get_misc('webdav','verbose',True)
271         handler.debug = config.get_misc('webdav','debug',True)
272         _dc = { 'verbose' : verbose,
273                 'directory' : directory,
274                 'lockemulation' : True,
275                 }
276
277         conf = OpenDAVConfig(**_dc)
278         handler._config = conf
279         reg_http_service(HTTPDir(directory,DAVHandler,DAVAuthProvider()))
280         netsvc.Logger().notifyChannel('webdav', netsvc.LOG_INFO, "WebDAV service registered at path: %s/ "% directory)
281 except Exception, e:
282     logger = netsvc.Logger()
283     logger.notifyChannel('webdav', netsvc.LOG_ERROR, 'Cannot launch webdav: %s' % e)
284
285 #eof
286
287
288