/
request_server.py
1529 lines (1285 loc) · 63 KB
/
request_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# (c) 2009-2017 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav
# Original PyFileServer (c) 2005 Ho Chun Wei.
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
"""
WSGI application that handles one single WebDAV request.
See `Developers info`_ for more information about the WsgiDAV architecture.
.. _`Developers info`: http://wsgidav.readthedocs.org/en/latest/develop.html
"""
from __future__ import print_function
from wsgidav import compat, util, xml_tools
from wsgidav.dav_error import (
HTTP_BAD_GATEWAY,
HTTP_BAD_REQUEST,
HTTP_CONFLICT,
HTTP_CREATED,
HTTP_FAILED_DEPENDENCY,
HTTP_FORBIDDEN,
HTTP_INTERNAL_ERROR,
HTTP_LENGTH_REQUIRED,
HTTP_MEDIATYPE_NOT_SUPPORTED,
HTTP_METHOD_NOT_ALLOWED,
HTTP_NO_CONTENT,
HTTP_NOT_FOUND,
HTTP_NOT_IMPLEMENTED,
HTTP_OK,
HTTP_PRECONDITION_FAILED,
HTTP_RANGE_NOT_SATISFIABLE,
DAVError,
PRECONDITION_CODE_LockTokenMismatch,
PRECONDITION_CODE_PropfindFiniteDepth,
asDAVError,
getHttpStatusString
)
# Trick PyDev to do intellisense and don't produce warnings:
from wsgidav.util import etree # @UnusedImport
if False:
from xml.etree import ElementTree as etree # @Reimport
__docformat__ = "reStructuredText"
_logger = util.getModuleLogger(__name__)
DEFAULT_BLOCK_SIZE = 8192
# ========================================================================
# RequestServer
# ========================================================================
class RequestServer(object):
def __init__(self, davProvider):
self._davProvider = davProvider
self.allowPropfindInfinite = True
self._verbose = 2
self.block_size = DEFAULT_BLOCK_SIZE
util.debug("RequestServer: __init__", module="sc")
self._possible_methods = ["OPTIONS", "HEAD", "GET", "PROPFIND"]
# if self._davProvider.propManager is not None:
# self._possible_methods.extend( [ "PROPFIND" ] )
if not self._davProvider.isReadOnly():
self._possible_methods.extend(
["PUT", "DELETE", "COPY", "MOVE", "MKCOL", "PROPPATCH", "POST"])
# if self._davProvider.propManager is not None:
# self._possible_methods.extend( [ "PROPPATCH" ] )
if self._davProvider.lockManager is not None:
self._possible_methods.extend(["LOCK", "UNLOCK"])
def __del__(self):
util.debug("RequestServer: __del__", module="sc")
def __call__(self, environ, start_response):
assert "wsgidav.verbose" in environ
provider = self._davProvider
# TODO: allow anonymous somehow: this should run, even if http_authenticator middleware
# is not installed
# assert "http_authenticator.username" in environ
if "http_authenticator.username" not in environ:
_logger.info(
"*** missing 'http_authenticator.username' in environ")
environ["wsgidav.username"] = environ.get(
"http_authenticator.username", "anonymous")
requestmethod = environ["REQUEST_METHOD"]
self.block_size = environ["wsgidav.config"].get(
"block_size", DEFAULT_BLOCK_SIZE)
# Convert 'infinity' and 'T'/'F' to a common case
if environ.get("HTTP_DEPTH") is not None:
environ["HTTP_DEPTH"] = environ["HTTP_DEPTH"].lower()
if environ.get("HTTP_OVERWRITE") is not None:
environ["HTTP_OVERWRITE"] = environ["HTTP_OVERWRITE"].upper()
if "HTTP_EXPECT" in environ:
pass
# Dispatch HTTP request methods to 'doMETHOD()' handlers
method = None
if requestmethod in self._possible_methods:
method = getattr(self, "do%s" % requestmethod, None)
if not method:
self._fail(HTTP_METHOD_NOT_ALLOWED)
if environ.get("wsgidav.debug_break"):
pass # Set a break point here
if environ.get("wsgidav.debug_profile"):
from cProfile import Profile
profile = Profile()
res = profile.runcall(provider.customRequestHandler,
environ, start_response, method)
# sort: 0:"calls",1:"time", 2: "cumulative"
profile.print_stats(sort=2)
for v in res:
yield v
if hasattr(res, "close"):
res.close()
return
# Run requesthandler (provider may override, #55)
app_iter = provider.customRequestHandler(environ, start_response, method)
for v in app_iter:
yield v
if hasattr(app_iter, "close"):
app_iter.close()
return
def _fail(self, value, contextinfo=None, srcexception=None, errcondition=None):
"""Wrapper to raise (and log) DAVError."""
util.fail(value, contextinfo, srcexception, errcondition)
def _sendResponse(self, environ, start_response, rootRes, successCode, errorList):
"""Send WSGI response (single or multistatus).
- If errorList is None or [], then <successCode> is send as response.
- If errorList contains a single error with a URL that matches rootRes,
then this error is returned.
- If errorList contains more than one error, then '207 Multi-Status' is
returned.
"""
assert successCode in (HTTP_CREATED, HTTP_NO_CONTENT, HTTP_OK)
if not errorList:
# Status OK
return util.sendStatusResponse(environ, start_response, successCode)
if len(errorList) == 1 and errorList[0][0] == rootRes.getHref():
# Only one error that occurred on the root resource
return util.sendStatusResponse(environ, start_response, errorList[0][1])
# Multiple errors, or error on one single child
multistatusEL = xml_tools.makeMultistatusEL()
for refurl, e in errorList:
# assert refurl.startswith("http:")
assert refurl.startswith("/")
assert isinstance(e, DAVError)
responseEL = etree.SubElement(multistatusEL, "{DAV:}response")
etree.SubElement(responseEL, "{DAV:}href").text = refurl
etree.SubElement(
responseEL, "{DAV:}status").text = "HTTP/1.1 %s" % getHttpStatusString(e)
return util.sendMultiStatusResponse(environ, start_response, multistatusEL)
def _checkWritePermission(self, res, depth, environ):
"""Raise DAVError(HTTP_LOCKED), if res is locked.
If depth=='infinity', we also raise when child resources are locked.
"""
lockMan = self._davProvider.lockManager
if lockMan is None or res is None:
return True
refUrl = res.getRefUrl()
if "wsgidav.conditions.if" not in environ:
util.parseIfHeaderDict(environ)
# raise HTTP_LOCKED if conflict exists
lockMan.checkWritePermission(refUrl, depth,
environ["wsgidav.ifLockTokenList"],
environ["wsgidav.username"])
def _evaluateIfHeaders(self, res, environ):
"""Apply HTTP headers on <path>, raising DAVError if conditions fail.
Add environ['wsgidav.conditions.if'] and environ['wsgidav.ifLockTokenList'].
Handle these headers:
- If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since:
Raising HTTP_PRECONDITION_FAILED or HTTP_NOT_MODIFIED
- If:
Raising HTTP_PRECONDITION_FAILED
@see http://www.webdav.org/specs/rfc4918.html#HEADER_If
@see util.evaluateHTTPConditionals
"""
# Add parsed If header to environ
if "wsgidav.conditions.if" not in environ:
util.parseIfHeaderDict(environ)
# Bail out, if res does not exist
if res is None:
return
ifDict = environ["wsgidav.conditions.if"]
# Raise HTTP_PRECONDITION_FAILED or HTTP_NOT_MODIFIED, if standard
# HTTP condition fails
lastmodified = -1 # nonvalid modified time
entitytag = "[]" # Non-valid entity tag
if res.getLastModified() is not None:
lastmodified = res.getLastModified()
if res.getEtag() is not None:
entitytag = res.getEtag()
if ("HTTP_IF_MODIFIED_SINCE" in environ
or "HTTP_IF_UNMODIFIED_SINCE" in environ
or "HTTP_IF_MATCH" in environ
or "HTTP_IF_NONE_MATCH" in environ):
util.evaluateHTTPConditionals(
res, lastmodified, entitytag, environ)
if "HTTP_IF" not in environ:
return
# Raise HTTP_PRECONDITION_FAILED, if DAV 'If' condition fails
# TODO: handle empty locked resources
# TODO: handle unmapped locked resources
# isnewfile = not provider.exists(mappedpath)
refUrl = res.getRefUrl()
lockMan = self._davProvider.lockManager
locktokenlist = []
if lockMan:
lockList = lockMan.getIndirectUrlLockList(
refUrl, environ["wsgidav.username"])
for lock in lockList:
locktokenlist.append(lock["token"])
if not util.testIfHeaderDict(res, ifDict, refUrl, locktokenlist, entitytag):
self._fail(HTTP_PRECONDITION_FAILED,
"'If' header condition failed.")
return
def doPROPFIND(self, environ, start_response):
"""
TODO: does not yet support If and If HTTP Conditions
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND
"""
path = environ["PATH_INFO"]
res = self._davProvider.getResourceInst(path, environ)
# RFC: By default, the PROPFIND method without a Depth header MUST act
# as if a "Depth: infinity" header was included.
environ.setdefault("HTTP_DEPTH", "infinity")
if not environ["HTTP_DEPTH"] in ("0", "1", "infinity"):
self._fail(HTTP_BAD_REQUEST,
"Invalid Depth header: '%s'." % environ["HTTP_DEPTH"])
if environ["HTTP_DEPTH"] == "infinity" and not self.allowPropfindInfinite:
self._fail(HTTP_FORBIDDEN,
"PROPFIND 'infinite' was disabled for security reasons.",
errcondition=PRECONDITION_CODE_PropfindFiniteDepth)
if res is None:
self._fail(HTTP_NOT_FOUND)
if environ.get("wsgidav.debug_break"):
pass # break point
self._evaluateIfHeaders(res, environ)
# Parse PROPFIND request
requestEL = util.parseXmlBody(environ, allowEmpty=True)
if requestEL is None:
# An empty PROPFIND request body MUST be treated as a request for
# the names and values of all properties.
requestEL = etree.XML(
"<D:propfind xmlns:D='DAV:'><D:allprop/></D:propfind>")
if requestEL.tag != "{DAV:}propfind":
self._fail(HTTP_BAD_REQUEST)
propNameList = []
propFindMode = None
for pfnode in requestEL:
if pfnode.tag == "{DAV:}allprop":
if propFindMode:
# RFC: allprop and propname are mutually exclusive
self._fail(HTTP_BAD_REQUEST)
propFindMode = "allprop"
# TODO: implement <include> option
# elif pfnode.tag == "{DAV:}include":
# if not propFindMode in (None, "allprop"):
# self._fail(HTTP_BAD_REQUEST,
# "<include> element is only valid with 'allprop'.")
# for pfpnode in pfnode:
# propNameList.append(pfpnode.tag)
elif pfnode.tag == "{DAV:}propname":
if propFindMode: # RFC: allprop and propname are mutually exclusive
self._fail(HTTP_BAD_REQUEST)
propFindMode = "propname"
elif pfnode.tag == "{DAV:}prop":
# RFC: allprop and propname are mutually exclusive
if propFindMode not in (None, "named"):
self._fail(HTTP_BAD_REQUEST)
propFindMode = "named"
for pfpnode in pfnode:
propNameList.append(pfpnode.tag)
# --- Build list of resource URIs
reslist = res.getDescendants(depth=environ["HTTP_DEPTH"], addSelf=True)
# if environ["wsgidav.verbose"] >= 3:
# pprint(reslist, indent=4)
multistatusEL = xml_tools.makeMultistatusEL()
responsedescription = []
for child in reslist:
if propFindMode == "allprop":
propList = child.getProperties("allprop")
elif propFindMode == "propname":
propList = child.getProperties("propname")
else:
propList = child.getProperties("named", nameList=propNameList)
href = child.getHref()
util.addPropertyResponse(multistatusEL, href, propList)
if responsedescription:
etree.SubElement(multistatusEL, "{DAV:}responsedescription").text = "\n".join(
responsedescription)
return util.sendMultiStatusResponse(environ, start_response, multistatusEL)
def doPROPPATCH(self, environ, start_response):
"""Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
"""
path = environ["PATH_INFO"]
res = self._davProvider.getResourceInst(path, environ)
# Only accept Depth: 0 (but assume this, if omitted)
environ.setdefault("HTTP_DEPTH", "0")
if environ["HTTP_DEPTH"] != "0":
self._fail(HTTP_BAD_REQUEST, "Depth must be '0'.")
if res is None:
self._fail(HTTP_NOT_FOUND)
self._evaluateIfHeaders(res, environ)
self._checkWritePermission(res, "0", environ)
# Parse request
requestEL = util.parseXmlBody(environ)
if requestEL.tag != "{DAV:}propertyupdate":
self._fail(HTTP_BAD_REQUEST)
# Create a list of update request tuples: (propname, value)
propupdatelist = []
for ppnode in requestEL:
propupdatemethod = None
if ppnode.tag == "{DAV:}remove":
propupdatemethod = "remove"
elif ppnode.tag == "{DAV:}set":
propupdatemethod = "set"
else:
self._fail(HTTP_BAD_REQUEST,
"Unknown tag (expected 'set' or 'remove').")
for propnode in ppnode:
if propnode.tag != "{DAV:}prop":
self._fail(HTTP_BAD_REQUEST,
"Unknown tag (expected 'prop').")
for propertynode in propnode:
propvalue = None
if propupdatemethod == "remove":
propvalue = None # Mark as 'remove'
if len(propertynode) > 0:
# 14.23: All the XML elements in a 'prop' XML
# element inside of a 'remove' XML element MUST be
# empty
self._fail(
HTTP_BAD_REQUEST, "prop element must be empty for 'remove'.")
else:
propvalue = propertynode
propupdatelist.append((propertynode.tag, propvalue))
# Apply updates in SIMULATION MODE and create a result list (propname,
# result)
successflag = True
writeresultlist = []
for (propname, propvalue) in propupdatelist:
try:
res.setPropertyValue(propname, propvalue, dryRun=True)
except Exception as e:
writeresult = asDAVError(e)
else:
writeresult = "200 OK"
writeresultlist.append((propname, writeresult))
successflag = successflag and writeresult == "200 OK"
# Generate response list of 2-tuples (name, value)
# <value> is None on success, or an instance of DAVError
propResponseList = []
responsedescription = []
if not successflag:
# If dry run failed: convert all OK to FAILED_DEPENDENCY.
for (propname, result) in writeresultlist:
if result == "200 OK":
result = DAVError(HTTP_FAILED_DEPENDENCY)
elif isinstance(result, DAVError):
responsedescription.append(result.getUserInfo())
propResponseList.append((propname, result))
else:
# Dry-run succeeded: set properties again, this time in 'real' mode
# In theory, there should be no exceptions thrown here, but this is
# real live...
for (propname, propvalue) in propupdatelist:
try:
res.setPropertyValue(propname, propvalue, dryRun=False)
# Set value to None, so the response xml contains empty
# tags
propResponseList.append((propname, None))
except Exception as e:
e = asDAVError(e)
propResponseList.append((propname, e))
responsedescription.append(e.getUserInfo())
# Generate response XML
multistatusEL = xml_tools.makeMultistatusEL()
# href = util.makeCompleteUrl(environ, path)
href = res.getHref()
util.addPropertyResponse(multistatusEL, href, propResponseList)
if responsedescription:
etree.SubElement(multistatusEL, "{DAV:}responsedescription").text = "\n".join(
responsedescription)
# Send response
return util.sendMultiStatusResponse(environ, start_response, multistatusEL)
def doMKCOL(self, environ, start_response):
"""Handle MKCOL request to create a new collection.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_MKCOL
"""
path = environ["PATH_INFO"]
provider = self._davProvider
# res = provider.getResourceInst(path, environ)
# Do not understand ANY request body entities
if util.getContentLength(environ) != 0:
self._fail(HTTP_MEDIATYPE_NOT_SUPPORTED,
"The server does not handle any body content.")
# Only accept Depth: 0 (but assume this, if omitted)
if environ.setdefault("HTTP_DEPTH", "0") != "0":
self._fail(HTTP_BAD_REQUEST, "Depth must be '0'.")
if provider.exists(path, environ):
self._fail(HTTP_METHOD_NOT_ALLOWED,
"MKCOL can only be executed on an unmapped URL.")
parentRes = provider.getResourceInst(util.getUriParent(path), environ)
if not parentRes or not parentRes.isCollection:
self._fail(HTTP_CONFLICT, "Parent must be an existing collection.")
# TODO: should we check If headers here?
# self._evaluateIfHeaders(res, environ)
# Check for write permissions on the PARENT
self._checkWritePermission(parentRes, "0", environ)
parentRes.createCollection(util.getUriName(path))
return util.sendStatusResponse(environ, start_response, HTTP_CREATED)
def doPOST(self, environ, start_response):
"""
@see http://www.webdav.org/specs/rfc4918.html#METHOD_POST
@see http://stackoverflow.com/a/22606899/19166
"""
self._fail(HTTP_METHOD_NOT_ALLOWED)
def doDELETE(self, environ, start_response):
"""
@see: http://www.webdav.org/specs/rfc4918.html#METHOD_DELETE
"""
path = environ["PATH_INFO"]
provider = self._davProvider
res = provider.getResourceInst(path, environ)
# --- Check request preconditions -------------------------------------
if util.getContentLength(environ) != 0:
self._fail(HTTP_MEDIATYPE_NOT_SUPPORTED,
"The server does not handle any body content.")
if res is None:
self._fail(HTTP_NOT_FOUND)
if res.isCollection:
# Delete over collection
# "The DELETE method on a collection MUST act as if a
# 'Depth: infinity' header was used on it. A client MUST NOT submit
# a Depth header with a DELETE on a collection with any value but
# infinity."
if environ.setdefault("HTTP_DEPTH", "infinity") != "infinity":
self._fail(HTTP_BAD_REQUEST,
"Only Depth: infinity is supported for collections.")
else:
if not environ.setdefault("HTTP_DEPTH", "0") in ("0", "infinity"):
self._fail(HTTP_BAD_REQUEST,
"Only Depth: 0 or infinity are supported for non-collections.")
self._evaluateIfHeaders(res, environ)
# We need write access on the parent collection. Also we check for
# locked children
parentRes = provider.getResourceInst(util.getUriParent(path), environ)
if parentRes:
# self._checkWritePermission(parentRes, environ["HTTP_DEPTH"], environ)
self._checkWritePermission(parentRes, "0", environ)
else:
# self._checkWritePermission(res, environ["HTTP_DEPTH"], environ)
self._checkWritePermission(res, "0", environ)
# --- Let provider handle the request natively ------------------------
# Errors in deletion; [ (<ref-url>, <DAVError>), ... ]
errorList = []
try:
handled = res.handleDelete()
assert handled in (True, False) or type(handled) is list
if type(handled) is list:
errorList = handled
handled = True
except Exception as e:
errorList = [(res.getHref(), asDAVError(e))]
handled = True
if handled:
return self._sendResponse(environ, start_response,
res, HTTP_NO_CONTENT, errorList)
# --- Let provider implement own recursion ----------------------------
# Get a list of all resources (parents after children, so we can remove
# them in that order)
reverseChildList = res.getDescendants(depthFirst=True,
depth=environ["HTTP_DEPTH"],
addSelf=True)
if res.isCollection and res.supportRecursiveDelete():
hasConflicts = False
for childRes in reverseChildList:
try:
self._evaluateIfHeaders(childRes, environ)
self._checkWritePermission(childRes, "0", environ)
except:
hasConflicts = True
break
if not hasConflicts:
try:
errorList = res.delete()
except Exception as e:
errorList = [(res.getHref(), asDAVError(e))]
return self._sendResponse(environ, start_response,
res, HTTP_NO_CONTENT, errorList)
# --- Implement file-by-file processing -------------------------------
# Hidden paths (ancestors of failed deletes) {<path>: True, ...}
ignoreDict = {}
for childRes in reverseChildList:
if childRes.path in ignoreDict:
_logger.debug("Skipping %s (contains error child)" %
childRes.path)
ignoreDict[util.getUriParent(childRes.path)] = ""
continue
try:
# 9.6.1.: Any headers included with delete must be applied in
# processing every resource to be deleted
self._evaluateIfHeaders(childRes, environ)
self._checkWritePermission(childRes, "0", environ)
childRes.delete()
# Double-check, if deletion succeeded
if provider.exists(childRes.path, environ):
raise DAVError(HTTP_INTERNAL_ERROR,
"Resource could not be deleted.")
except Exception as e:
errorList.append((childRes.getHref(), asDAVError(e)))
ignoreDict[util.getUriParent(childRes.path)] = True
# --- Send response ---------------------------------------------------
return self._sendResponse(environ, start_response,
res, HTTP_NO_CONTENT, errorList)
def _streamDataChunked(self, environ):
"""Get the data from a chunked transfer."""
# Chunked Transfer Coding
# http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1
if "Darwin" in environ.get("HTTP_USER_AGENT", "") and \
environ.get("HTTP_X_EXPECTED_ENTITY_LENGTH"):
# Mac Finder, that does not prepend chunk-size + CRLF ,
# like it should to comply with the spec. It sends chunk
# size as integer in a HTTP header instead.
WORKAROUND_CHUNK_LENGTH = True
buf = environ.get("HTTP_X_EXPECTED_ENTITY_LENGTH", "0")
l = int(buf)
else:
WORKAROUND_CHUNK_LENGTH = False
buf = environ["wsgi.input"].readline()
environ["wsgidav.some_input_read"] = 1
if buf == '':
l = 0
else:
l = int(buf, 16)
while l > 0:
buf = environ["wsgi.input"].read(l)
yield buf
if WORKAROUND_CHUNK_LENGTH:
environ["wsgidav.some_input_read"] = 1
# Keep receiving until we read expected size or reach
# EOF
if buf == '':
l = 0
else:
l -= len(buf)
else:
environ["wsgi.input"].readline()
buf = environ["wsgi.input"].readline()
if buf == '':
l = 0
else:
l = int(buf, 16)
environ["wsgidav.all_input_read"] = 1
def _streamData(self, environ, contentlength, block_size):
"""Get the data from a non-chunked transfer."""
if contentlength == 0:
# TODO: review this
# XP and Vista MiniRedir submit PUT with Content-Length 0,
# before LOCK and the real PUT. So we have to accept this.
_logger.info(
"PUT: Content-Length == 0. Creating empty file...")
# elif contentlength < 0:
# # TODO: review this
# # If CONTENT_LENGTH is invalid, we may try to workaround this
# # by reading until the end of the stream. This may block however!
# # The iterator produced small chunks of varying size, but not
# # sure, if we always get everything before it times out.
# _logger.warning("PUT with invalid Content-Length (%s). Trying to read all (this may timeout)..." % environ.get("CONTENT_LENGTH"))
# nb = 0
# try:
# for s in environ["wsgi.input"]:
# environ["wsgidav.some_input_read"] = 1
# _logger.debug("PUT: read from wsgi.input.__iter__, len=%s" % len(s))
# yield s
# nb += len (s)
# except socket.timeout:
# _logger.warning("PUT: input timed out after writing %s bytes" % nb)
# hasErrors = True
else:
assert contentlength > 0
contentremain = contentlength
while contentremain > 0:
n = min(contentremain, block_size)
readbuffer = environ["wsgi.input"].read(n)
# This happens with litmus expect-100 test:
# assert len(readbuffer) > 0, "input.read(%s) returned %s bytes" % (n, len(readbuffer))
if not len(readbuffer) > 0:
util.warn("input.read(%s) returned 0 bytes" % n)
break
environ["wsgidav.some_input_read"] = 1
yield readbuffer
contentremain -= len(readbuffer)
if contentremain == 0:
environ["wsgidav.all_input_read"] = 1
def doPUT(self, environ, start_response):
"""
@see: http://www.webdav.org/specs/rfc4918.html#METHOD_PUT
"""
path = environ["PATH_INFO"]
provider = self._davProvider
res = provider.getResourceInst(path, environ)
parentRes = provider.getResourceInst(util.getUriParent(path), environ)
isnewfile = res is None
# Test for unsupported stuff
if "HTTP_CONTENT_ENCODING" in environ:
util.fail(HTTP_NOT_IMPLEMENTED,
"Content-encoding header is not supported.")
# An origin server that allows PUT on a given target resource MUST send
# a 400 (Bad Request) response to a PUT request that contains a
# Content-Range header field
# (http://tools.ietf.org/html/rfc7231#section-4.3.4)
if "HTTP_CONTENT_RANGE" in environ:
util.fail(HTTP_BAD_REQUEST,
"Content-range header is not allowed on PUT requests.")
if res and res.isCollection:
self._fail(HTTP_METHOD_NOT_ALLOWED, "Cannot PUT to a collection")
elif not parentRes.isCollection: # TODO: allow parentRes==None?
self._fail(HTTP_CONFLICT, "PUT parent must be a collection")
self._evaluateIfHeaders(res, environ)
if isnewfile:
self._checkWritePermission(parentRes, "0", environ)
res = parentRes.createEmptyResource(util.getUriName(path))
else:
self._checkWritePermission(res, "0", environ)
# Start Content Processing
# Content-Length may be 0 or greater. (Set to -1 if missing or invalid.)
# WORKAROUND_BAD_LENGTH = True
try:
contentlength = max(-1, int(environ.get("CONTENT_LENGTH", -1)))
except ValueError:
contentlength = -1
# if contentlength < 0 and not WORKAROUND_BAD_LENGTH:
if (
(contentlength < 0) and
(environ.get("HTTP_TRANSFER_ENCODING", "").lower() != "chunked")
):
# HOTFIX: not fully understood, but MS sends PUT without content-length,
# when creating new files
agent = environ.get("HTTP_USER_AGENT", "")
if "Microsoft-WebDAV-MiniRedir" in agent or "gvfs/" in agent: # issue #10
_logger.warning(
"Setting misssing Content-Length to 0 for MS / gvfs client")
contentlength = 0
else:
util.fail(HTTP_LENGTH_REQUIRED,
"PUT request with invalid Content-Length: (%s)" % environ.get("CONTENT_LENGTH"))
hasErrors = False
try:
if environ.get("HTTP_TRANSFER_ENCODING", "").lower() == "chunked":
data_stream = self._streamDataChunked(environ)
else:
data_stream = self._streamData(environ, contentlength, self.block_size)
fileobj = res.beginWrite(contentType=environ.get("CONTENT_TYPE"))
# Process the data in the body.
# If the fileobj has a writelines() method, give it the data stream.
# If it doesn't, itearate the stream and call write() for each
# iteration. This gives providers more flexibility in how they
# consume the data.
if getattr(fileobj, "writelines", None):
fileobj.writelines(data_stream)
else:
for data in data_stream:
fileobj.write(data)
fileobj.close()
except Exception as e:
res.endWrite(withErrors=True)
_logger.exception("PUT: byte copy failed")
util.fail(e)
res.endWrite(hasErrors)
if isnewfile:
return util.sendStatusResponse(environ, start_response, HTTP_CREATED)
return util.sendStatusResponse(environ, start_response, HTTP_NO_CONTENT)
def doCOPY(self, environ, start_response):
return self._copyOrMove(environ, start_response, False)
def doMOVE(self, environ, start_response):
return self._copyOrMove(environ, start_response, True)
def _copyOrMove(self, environ, start_response, isMove):
"""
@see: http://www.webdav.org/specs/rfc4918.html#METHOD_COPY
@see: http://www.webdav.org/specs/rfc4918.html#METHOD_MOVE
"""
srcPath = environ["PATH_INFO"]
provider = self._davProvider
srcRes = provider.getResourceInst(srcPath, environ)
srcParentRes = provider.getResourceInst(
util.getUriParent(srcPath), environ)
# --- Check source ----------------------------------------------------
if srcRes is None:
self._fail(HTTP_NOT_FOUND)
if "HTTP_DESTINATION" not in environ:
self._fail(HTTP_BAD_REQUEST,
"Missing required Destination header.")
if not environ.setdefault("HTTP_OVERWRITE", "T") in ("T", "F"):
# Overwrite defaults to 'T'
self._fail(HTTP_BAD_REQUEST, "Invalid Overwrite header.")
if util.getContentLength(environ) != 0:
# RFC 2518 defined support for <propertybehavior>.
# This was dropped with RFC 4918.
# Still clients may send it (e.g. DAVExplorer 0.9.1 File-Copy) sends
# <A:propertybehavior xmlns:A="DAV:"> <A:keepalive>*</A:keepalive>
body = environ["wsgi.input"].read(util.getContentLength(environ))
environ["wsgidav.all_input_read"] = 1
_logger.info("Ignored copy/move body: '%s'..." % body[:50])
if srcRes.isCollection:
# The COPY method on a collection without a Depth header MUST act as
# if a Depth header with value "infinity" was included.
# A client may submit a Depth header on a COPY on a collection with
# a value of "0" or "infinity".
environ.setdefault("HTTP_DEPTH", "infinity")
if not environ["HTTP_DEPTH"] in ("0", "infinity"):
self._fail(HTTP_BAD_REQUEST, "Invalid Depth header.")
if isMove and environ["HTTP_DEPTH"] != "infinity":
self._fail(
HTTP_BAD_REQUEST, "Depth header for MOVE collection must be 'infinity'.")
else:
# It's an existing non-collection: assume Depth 0
# Note: litmus 'copymove: 3 (copy_simple)' sends 'infinity' for a
# non-collection resource, so we accept that too
environ.setdefault("HTTP_DEPTH", "0")
if not environ["HTTP_DEPTH"] in ("0", "infinity"):
self._fail(HTTP_BAD_REQUEST, "Invalid Depth header.")
environ["HTTP_DEPTH"] = "0"
# --- Get destination path and check for cross-realm access -----------
# Destination header may be quoted (e.g. DAV Explorer sends unquoted,
# Windows quoted)
destinationHeader = compat.unquote(environ["HTTP_DESTINATION"])
# Return fragments as part of <path>
# Fixes litmus -> running `basic': 9. delete_fragment....... WARNING:
# DELETE removed collection resource withRequest-URI including
# fragment; unsafe
destScheme, destNetloc, destPath, \
_destParams, _destQuery, _destFrag = compat.urlparse(destinationHeader,
allow_fragments=False)
if srcRes.isCollection:
destPath = destPath.rstrip("/") + "/"
if destScheme and destScheme.lower() != environ["wsgi.url_scheme"].lower():
self._fail(HTTP_BAD_GATEWAY,
"Source and destination must have the same scheme.")
elif destNetloc and destNetloc.lower() != environ["HTTP_HOST"].lower():
# TODO: this should consider environ["SERVER_PORT"] also
self._fail(HTTP_BAD_GATEWAY,
"Source and destination must have the same host name.")
elif not destPath.startswith(provider.mountPath + provider.sharePath):
# Inter-realm copying not supported, since its not possible to
# authentication-wise
self._fail(HTTP_BAD_GATEWAY,
"Inter-realm copy/move is not supported.")
destPath = destPath[len(provider.mountPath + provider.sharePath):]
assert destPath.startswith("/")
# destPath is now relative to current mount/share starting with '/'
destRes = provider.getResourceInst(destPath, environ)
destExists = destRes is not None
destParentRes = provider.getResourceInst(
util.getUriParent(destPath), environ)
if not destParentRes or not destParentRes.isCollection:
self._fail(HTTP_CONFLICT,
"Destination parent must be a collection.")
self._evaluateIfHeaders(srcRes, environ)
self._evaluateIfHeaders(destRes, environ)
# Check permissions
# http://www.webdav.org/specs/rfc4918.html#rfc.section.7.4
if isMove:
self._checkWritePermission(srcRes, "infinity", environ)
# Cannot remove members from locked-0 collections
if srcParentRes:
self._checkWritePermission(srcParentRes, "0", environ)
# Cannot create or new members in locked-0 collections
if not destExists:
self._checkWritePermission(destParentRes, "0", environ)
# If target exists, it must not be locked
self._checkWritePermission(destRes, "infinity", environ)
if srcPath == destPath:
self._fail(HTTP_FORBIDDEN, "Cannot copy/move source onto itself")
elif util.isEqualOrChildUri(srcPath, destPath):
self._fail(HTTP_FORBIDDEN, "Cannot copy/move source below itself")
if destExists and environ["HTTP_OVERWRITE"] != "T":
self._fail(HTTP_PRECONDITION_FAILED,
"Destination already exists and Overwrite is set to false")
# --- Let provider handle the request natively ------------------------
# Errors in copy/move; [ (<ref-url>, <DAVError>), ... ]
errorList = []
successCode = HTTP_CREATED
if destExists:
successCode = HTTP_NO_CONTENT
try:
if isMove:
handled = srcRes.handleMove(destPath)
else:
isInfinity = environ["HTTP_DEPTH"] == "infinity"
handled = srcRes.handleCopy(destPath, isInfinity)
assert handled in (True, False) or type(handled) is list
if type(handled) is list:
errorList = handled
handled = True
except Exception as e:
errorList = [(srcRes.getHref(), asDAVError(e))]
handled = True
if handled:
return self._sendResponse(environ, start_response,
srcRes, HTTP_NO_CONTENT, errorList)
# --- Cleanup destination before copy/move ----------------------------
srcList = srcRes.getDescendants(addSelf=True)
srcRootLen = len(srcPath)
destRootLen = len(destPath)
if destExists:
if (isMove
or not destRes.isCollection
or not srcRes.isCollection):
# MOVE:
# If a resource exists at the destination and the Overwrite
# header is "T", then prior to performing the move, the server
# MUST perform a DELETE with "Depth: infinity" on the
# destination resource.
_logger.debug("Remove dest before move: '%s'" % destRes)
destRes.delete()
destRes = None
else:
# COPY collection over collection:
# Remove destination files, that are not part of source, because
# source and dest collections must not be merged (9.8.4).
# This is not the same as deleting the complete dest collection
# before copying, because that would also discard the history of
# existing resources.
reverseDestList = destRes.getDescendants(
depthFirst=True, addSelf=False)
srcPathList = [s.path for s in srcList]
_logger.debug("check srcPathList: %s" % srcPathList)
for dRes in reverseDestList:
_logger.debug(
"check unmatched dest before copy: %s" % dRes)
relUrl = dRes.path[destRootLen:]
sp = srcPath + relUrl
if sp not in srcPathList:
_logger.debug(
"Remove unmatched dest before copy: %s" % dRes)
dRes.delete()
# --- Let provider implement recursive move ---------------------------
# We do this only, if the provider supports it, and no conflicts exist.
# A provider can implement this very efficiently, without allocating
# double memory as a copy/delete approach would.
if isMove and srcRes.supportRecursiveMove(destPath):
hasConflicts = False
for s in srcList:
try:
self._evaluateIfHeaders(s, environ)
except:
hasConflicts = True
break