[IMP][REF] Sql-injection changes, remove print statement, some space improvement.
[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
36 import urlparse
37 import urllib
38 from string import atoi,split
39 from DAV.errors import *
40
41 def OpenDAVConfig(**kw):
42     class OpenDAV:
43         def __init__(self, **kw):
44             self.__dict__.update(**kw)
45
46     class Config:
47         DAV = OpenDAV(**kw)
48
49     return Config()
50
51
52 class DAVHandler(FixSendError,DAVRequestHandler):
53     verbose = False
54     
55     def get_userinfo(self,user,pw):
56         return False
57     def _log(self, message):
58         netsvc.Logger().notifyChannel("webdav",netsvc.LOG_DEBUG,message)
59     
60     def handle(self):
61         self._init_buffer()
62
63     def finish(self):
64         pass
65
66     def get_db_from_path(self, uri):
67         if uri or uri == '/':
68             dbs = self.IFACE_CLASS.db_list()
69             res = len(dbs) and dbs[0] or False
70         else:
71             res =  self.IFACE_CLASS.get_db(uri)        
72         return res
73
74     def setup(self):
75         davpath = '/'+config.get_misc('webdav','vdir','webdav')
76         self.baseuri = "http://%s:%d/"% (self.server.server_name, self.server.server_port)
77         self.IFACE_CLASS  = openerp_dav_handler(self, self.verbose)
78         
79     
80     def log_message(self, format, *args):
81         netsvc.Logger().notifyChannel('webdav', netsvc.LOG_DEBUG_RPC, format % args)
82
83     def log_error(self, format, *args):
84         netsvc.Logger().notifyChannel('xmlrpc', netsvc.LOG_WARNING, format % args)
85
86     def do_PUT(self):
87         dc=self.IFACE_CLASS        
88         uri=urlparse.urljoin(self.get_baseuri(dc), self.path)
89         uri=urllib.unquote(uri)
90         # Handle If-Match
91         if self.headers.has_key('If-Match'):
92             test = False
93             etag = None
94             
95             for match in self.headers['If-Match'].split(','):                
96                 if match == '*':
97                     if dc.exists(uri):
98                         test = True
99                         break
100                 else:
101                     if dc.match_prop(uri, match, "DAV:", "getetag"):
102                         test = True
103                         break
104             if not test:
105                 self.send_status(412)
106                 return
107
108         # Handle If-None-Match
109         if self.headers.has_key('If-None-Match'):
110             test = True
111             etag = None            
112             for match in self.headers['If-None-Match'].split(','):
113                 if match == '*':
114                     if dc.exists(uri):
115                         test = False
116                         break
117                 else:
118                     if dc.match_prop(uri, match, "DAV:", "getetag"):
119                         test = False
120                         break
121             if not test:
122                 self.send_status(412)
123                 return
124
125         # Handle expect
126         expect = self.headers.get('Expect', '')
127         if (expect.lower() == '100-continue' and
128                 self.protocol_version >= 'HTTP/1.1' and
129                 self.request_version >= 'HTTP/1.1'):
130             self.send_status(100)
131             self._flush()
132
133         # read the body
134         body=None
135         if self.headers.has_key("Content-Length"):
136             l=self.headers['Content-Length']
137             body=self.rfile.read(atoi(l))
138
139         # locked resources are not allowed to be overwritten
140         if self._l_isLocked(uri):
141             return self.send_body(None, '423', 'Locked', 'Locked')
142
143         ct=None
144         if self.headers.has_key("Content-Type"):
145             ct=self.headers['Content-Type']
146         try:
147             location = dc.put(uri,body,ct)
148         except DAV_Error, (ec,dd):
149             return self.send_status(ec)
150
151         headers = {}
152         if location:
153             headers['Location'] = location
154
155         try:
156             etag = dc.get_prop(location or uri, "DAV:", "getetag")
157             headers['ETag'] = etag
158         except:
159             pass
160
161         self.send_body(None, '201', 'Created', '', headers=headers)
162
163
164 try:
165     from service.http_server import reg_http_service,OpenERPAuthProvider   
166
167     if (config.get_misc('webdav','enable',True)):
168         directory = '/'+config.get_misc('webdav','vdir','webdav') 
169         handler = DAVHandler
170         verbose = config.get_misc('webdav','verbose',True)
171         handler.debug = config.get_misc('webdav','debug',True)
172         _dc = { 'verbose' : verbose,
173                 'directory' : directory,
174                 'lockemulation' : False,
175                     
176                 }
177
178         conf = OpenDAVConfig(**_dc)
179         handler._config = conf
180         reg_http_service(HTTPDir(directory,DAVHandler,OpenERPAuthProvider()))
181         netsvc.Logger().notifyChannel('webdav', netsvc.LOG_INFO, "WebDAV service registered at path: %s/ "% directory)
182 except Exception, e:
183     logger = netsvc.Logger()
184     logger.notifyChannel('webdav', netsvc.LOG_ERROR, 'Cannot launch webdav: %s' % e)
185
186 #eof
187
188
189