6 * Note: This plugin is a basic implementation of [RFC4918] WebDAV
8 * Version Control System (VCS) backing WebDAV is recommended instead
9 * and Subversion (svn) is one such VCS supporting WebDAV.
11 * status: *** EXPERIMENTAL *** (and likely insecure encoding/decoding)
15 * TODO: moving props should delete any existing props instead of
16 * preserving any that are not overwritten with UPDATE OR REPLACE
17 * (and, if merging directories, be careful when doing so)
18 * TODO: add proper support for locks with "shared" lockscope
19 * (instead of treating match of any shared lock as sufficient,
20 * even when there are different lockroots)
21 * TODO: does libxml2 xml-decode (html-decode),
22 * or must I do so to normalize input?
23 * TODO: add strict enforcement of property names to be valid XML tags
24 * (or encode as such before putting into database)
25 * & " < >
26 * TODO: should we be using xmlNodeListGetString() or xmlBufNodeDump()
27 * and how does it handle encoding and entity-inlining of external refs?
28 * Must xml decode/encode (normalize) before storing user data in database
29 * if going to add that data verbatim to xml doc returned in queries
30 * TODO: when walking xml nodes, should add checks for "DAV:" namespace
31 * TODO: consider where it might be useful/informative to check
32 * SQLITE_OK != sqlite3_reset() or SQLITE_OK != sqlite3_bind_...() or ...
33 * (in some cases no rows returned is ok, while in other cases it is not)
34 * TODO: Unsupported: !con->conf.follow_symlink is not currently honored;
35 * symlinks are followed. Supporting !con->conf.follow_symlinks would
36 * require operating system support for POSIX.1-2008 *at() commands,
37 * and reworking the mod_webdav code to exclusively operate with *at()
38 * commands, for example, replacing unlink() with unlinkat().
40 * RFE: add config option whether or not to include locktoken and ownerinfo
41 * in PROPFIND lockdiscovery
44 * - incomplete "shared" lock support
45 * - review code for proper decoding/encoding of elements from/to XML and db
46 * - preserve XML info in scope on dead properties, e.g. xml:lang
48 * [RFC4918] 4.3 Property Values
49 * Servers MUST preserve the following XML Information Items (using the
50 * terminology from [REC-XML-INFOSET]) in storage and transmission of dead
52 * [RFC4918] 14.26 set XML Element
53 * The 'set' element MUST contain only a 'prop' element. The elements
54 * contained by the 'prop' element inside the 'set' element MUST specify the
55 * name and value of properties that are set on the resource identified by
56 * Request-URI. If a property already exists, then its value is replaced.
57 * Language tagging information appearing in the scope of the 'prop' element
58 * (in the "xml:lang" attribute, if present) MUST be persistently stored along
59 * with the property, and MUST be subsequently retrievable using PROPFIND.
60 * [RFC4918] F.2 Changes for Server Implementations
61 * Strengthened server requirements for storage of property values, in
62 * particular persistence of language information (xml:lang), whitespace, and
63 * XML namespace information (see Section 4.3).
65 * resource usage containment
66 * - filesystem I/O operations might take a non-trivial amount of time,
67 * blocking the server from responding to other requests during this time.
68 * Potential solution: have a thread dedicated to handling webdav requests
69 * and serialize such requests in each thread dedicated to handling webdav.
70 * (Limit number of such dedicated threads.) Remove write interest from
71 * connection during this period so that server will not trigger any timeout
73 * - recursive directory operations are depth-first and may consume a large
74 * number of file descriptors if the directory hierarchy is deep.
75 * Potential solution: serialize webdav requests into dedicated thread (above)
76 * Potential solution: perform breadth-first directory traversal and pwrite()
77 * directory paths into a temporary file. After reading each directory,
78 * close() the dirhandle and pread() next directory from temporary file.
79 * (Keeping list of directories in memory might result in large memory usage)
80 * - flush response to client (or to intermediate temporary file) at regular
81 * intervals or triggers to avoid response consume large amount of memory
82 * during operations on large collection hierarchies (with lots of nested
85 * beware of security concerns involved in enabling WebDAV
86 * on publicly accessible servers
87 * - (general) [RFC4918] 20 Security Considersations
88 * - (specifically) [RFC4918] 20.6 Implications of XML Entities
89 * - TODO review usage of xml libs for security, resource usage, containment
90 * libxml2 vs expat vs ...
91 * http://xmlbench.sourceforge.net/
92 * http://stackoverflow.com/questions/399704/xml-parser-for-c
93 * http://tibleiz.net/asm-xml/index.html
94 * http://dev.yorhel.nl/yxml
95 * - how might mod_webdav be affected by mod_openssl setting REMOTE_USER?
96 * - when encoding href in responses, also ensure proper XML encoding
97 * (do we need to ENCODING_REL_URI and then ENCODING_MINIMAL_XML?)
98 * - TODO: any (non-numeric) data that goes into database should be encoded
99 * before being sent back to user, not just href. Perhaps anything that
100 * is not an href should be stored in database in XML-encoded form.
102 * consider implementing a set of (reasonable) limits on such things as
103 * - max number of collections
104 * - max number of objects in a collection
105 * - max number of properties per object
106 * - max length of property name
107 * - max length of property value
108 * - max length of locktoken, lockroot, ownerinfo
109 * - max number of locks held by a client, or by an owner
110 * - max number of locks on a resource (shared locks)
114 * - should check return value from sqlite3_reset(stmt) for REPLACE, UPDATE,
115 * DELETE statements (which is when commit occurs and locks are obtained/fail)
116 * - handle SQLITE_BUSY (e.g. other processes modifying db and hold locks)
117 * https://www.sqlite.org/lang_transaction.html
118 * https://www.sqlite.org/rescode.html#busy
119 * https://www.sqlite.org/c3ref/busy_handler.html
120 * https://www.sqlite.org/c3ref/busy_timeout.html
121 * - periodically execute query to delete expired locks
122 * (MOD_WEBDAV_SQLITE_LOCKS_DELETE_EXPIRED)
123 * (should defend against removing locks protecting long-running operations
124 * that are in progress on the server)
125 * - having all requests go through database, including GET and HEAD would allow
126 * for better transactional semantics, instead of the current race conditions
127 * inherent in multiple (and many) filesystem operations. All queries would
128 * go through database, which would map to objects on disk, and copy and move
129 * would simply be database entries to objects with reference counts and
130 * copy-on-write semantics (instead of potential hard-links on disk).
131 * lstat() information could also be stored in database. Right now, if a file
132 * is copied or moved or deleted, the status of the property update in the db
133 * is discarded, whether it succeeds or not, since file operation succeeded.
134 * (Then again, it might also be okay if props do not exist on a given file.)
135 * On the other hand, if everything went through database, then etag could be
136 * stored in database and could be updated upon PUT (or MOVE/COPY/DELETE).
137 * There would also need to be a way to trigger a rescan of filesystem to
138 * bring the database into sync with any out-of-band changes.
143 * - lstat() used instead of stat_cache_*() since the stat_cache might have
144 * expired data, as stat_cache is not invalidated by outside modifications,
145 * such as WebDAV PUT method (unless FAM is used)
147 * - SQLite database can be run in WAL mode (https://sqlite.org/wal.html)
148 * though mod_webdav does not provide a mechanism to configure WAL.
149 * Instead, once lighttpd starts up mod_webdav and creates the database,
150 * set WAL mode on the database from the command and then restart lighttpd.
154 /* linkat() fstatat() unlinkat() fdopendir() NAME_MAX */
155 #if !defined(_XOPEN_SOURCE) || _XOPEN_SOURCE-0 < 700
157 #define _XOPEN_SOURCE 700
159 /* DT_UNKNOWN DTTOIF() */
164 #include "first.h" /* first */
165 #include "sys-mmap.h"
166 #include <sys/types.h>
167 #include <sys/stat.h>
171 #include <stdio.h> /* rename() */
172 #include <stdlib.h> /* strtol() */
174 #include <strings.h> /* strncasecmp() */
175 #include <unistd.h> /* getpid() linkat() rmdir() unlinkat() */
177 #ifndef _D_EXACT_NAMLEN
178 #ifdef _DIRENT_HAVE_D_NAMLEN
179 #define _D_EXACT_NAMLEN(d) ((d)->d_namlen)
181 #define _D_EXACT_NAMLEN(d) (strlen ((d)->d_name))
185 #if defined(HAVE_LIBXML_H) && defined(HAVE_SQLITE3_H)
187 #define USE_PROPPATCH
188 /* minor: libxml2 includes stdlib.h in headers, too */
189 #include <libxml/tree.h>
190 #include <libxml/parser.h>
193 #if defined(HAVE_LIBUUID) && defined(HAVE_UUID_UUID_H)
195 #include <uuid/uuid.h>
198 #endif /* defined(HAVE_LIBXML_H) && defined(HAVE_SQLITE3_H) */
204 #include "http_header.h"
207 #include "connections.h"/* connection_handle_read_post_state() */
209 #include "response.h" /* http_response_redirect_to_directory() */
210 #include "stat_cache.h" /* stat_cache_mimetype_by_ext() */
212 #include "configfile.h"
215 #define http_status_get(con) ((con)->http_status)
216 #define http_status_set_fin(con, code) ((con)->file_finished = 1, \
217 (con)->mode = DIRECT, \
218 (con)->http_status = (code))
219 #define http_status_set(con, code) ((con)->http_status = (code))
220 #define http_status_unset(con) ((con)->http_status = 0)
221 #define http_status_is_set(con) (0 != (con)->http_status)
223 __attribute_noinline__
224 static int http_status_set_error (connection
*con
, int status
) {
225 return http_status_set_fin(con
, status
);
228 typedef physical physical_st
;
230 INIT_FUNC(mod_webdav_init
);
231 FREE_FUNC(mod_webdav_free
);
232 SETDEFAULTS_FUNC(mod_webdav_set_defaults
);
233 SERVER_FUNC(mod_webdav_worker_init
);
234 URIHANDLER_FUNC(mod_webdav_uri_handler
);
235 PHYSICALPATH_FUNC(mod_webdav_physical_handler
);
236 SUBREQUEST_FUNC(mod_webdav_subrequest_handler
);
237 CONNECTION_FUNC(mod_webdav_handle_reset
);
239 int mod_webdav_plugin_init(plugin
*p
);
240 int mod_webdav_plugin_init(plugin
*p
) {
241 p
->version
= LIGHTTPD_VERSION_ID
;
242 p
->name
= buffer_init_string("webdav");
244 p
->init
= mod_webdav_init
;
245 p
->cleanup
= mod_webdav_free
;
246 p
->set_defaults
= mod_webdav_set_defaults
;
247 p
->worker_init
= mod_webdav_worker_init
;
248 p
->handle_uri_clean
= mod_webdav_uri_handler
;
249 p
->handle_physical
= mod_webdav_physical_handler
;
250 p
->handle_subrequest
= mod_webdav_subrequest_handler
;
251 p
->connection_reset
= mod_webdav_handle_reset
;
259 #define WEBDAV_FILE_MODE S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH
260 #define WEBDAV_DIR_MODE S_IRWXU|S_IRWXG|S_IRWXO
262 #define WEBDAV_FLAG_LC_NAMES 0x01
263 #define WEBDAV_FLAG_OVERWRITE 0x02
264 #define WEBDAV_FLAG_MOVE_RENAME 0x04
265 #define WEBDAV_FLAG_COPY_LINK 0x08
266 #define WEBDAV_FLAG_MOVE_XDEV 0x10
267 #define WEBDAV_FLAG_COPY_XDEV 0x20
269 #define webdav_xmlstrcmp_fixed(s, fixed) \
270 strncmp((const char *)(s), (fixed), sizeof(fixed))
272 #include <ctype.h> /* isupper() tolower() */
274 webdav_str_len_to_lower (char * const restrict s
, const uint32_t len
)
276 /*(caller must ensure that len not truncated to (int);
277 * for current intended use, NAME_MAX typically <= 255)*/
278 for (int i
= 0; i
< (int)len
; ++i
) {
280 s
[i
] = tolower(s
[i
]);
287 sqlite3_stmt
*stmt_props_select_propnames
;
288 sqlite3_stmt
*stmt_props_select_props
;
289 sqlite3_stmt
*stmt_props_select_prop
;
290 sqlite3_stmt
*stmt_props_update_prop
;
291 sqlite3_stmt
*stmt_props_delete_prop
;
293 sqlite3_stmt
*stmt_props_copy
;
294 sqlite3_stmt
*stmt_props_move
;
295 sqlite3_stmt
*stmt_props_move_col
;
296 sqlite3_stmt
*stmt_props_delete
;
298 sqlite3_stmt
*stmt_locks_acquire
;
299 sqlite3_stmt
*stmt_locks_refresh
;
300 sqlite3_stmt
*stmt_locks_release
;
301 sqlite3_stmt
*stmt_locks_read
;
302 sqlite3_stmt
*stmt_locks_read_uri
;
303 sqlite3_stmt
*stmt_locks_read_uri_infinity
;
304 sqlite3_stmt
*stmt_locks_read_uri_members
;
305 sqlite3_stmt
*stmt_locks_delete_uri
;
306 sqlite3_stmt
*stmt_locks_delete_uri_col
;
312 /* plugin config for all request/connections */
315 int config_context_idx
;
317 unsigned short enabled
;
318 unsigned short is_readonly
;
319 unsigned short log_xml
;
320 unsigned short deprecated_unsafe_partial_put_compat
;
325 buffer
*sqlite_db_name
; /* not used after worker init */
332 plugin_config
**config_storage
;
336 /* init the plugin data */
337 INIT_FUNC(mod_webdav_init
) {
338 return calloc(1, sizeof(plugin_data
));
342 /* destroy the plugin data */
343 FREE_FUNC(mod_webdav_free
) {
344 plugin_data
*p
= (plugin_data
*)p_d
;
345 if (!p
) return HANDLER_GO_ON
;
347 if (p
->config_storage
) {
349 for (int i
= 0; i
< p
->nconfig
; ++i
) {
350 plugin_config
* const s
= p
->config_storage
[i
];
351 if (NULL
== s
) continue;
352 buffer_free(s
->sqlite_db_name
);
355 sql_config
* const sql
= s
->sql
;
356 if (!sql
|| !sql
->sqlh
) {
361 sqlite3_finalize(sql
->stmt_props_select_propnames
);
362 sqlite3_finalize(sql
->stmt_props_select_props
);
363 sqlite3_finalize(sql
->stmt_props_select_prop
);
364 sqlite3_finalize(sql
->stmt_props_update_prop
);
365 sqlite3_finalize(sql
->stmt_props_delete_prop
);
366 sqlite3_finalize(sql
->stmt_props_copy
);
367 sqlite3_finalize(sql
->stmt_props_move
);
368 sqlite3_finalize(sql
->stmt_props_move_col
);
369 sqlite3_finalize(sql
->stmt_props_delete
);
371 sqlite3_finalize(sql
->stmt_locks_acquire
);
372 sqlite3_finalize(sql
->stmt_locks_refresh
);
373 sqlite3_finalize(sql
->stmt_locks_release
);
374 sqlite3_finalize(sql
->stmt_locks_read
);
375 sqlite3_finalize(sql
->stmt_locks_read_uri
);
376 sqlite3_finalize(sql
->stmt_locks_read_uri_infinity
);
377 sqlite3_finalize(sql
->stmt_locks_read_uri_members
);
378 sqlite3_finalize(sql
->stmt_locks_delete_uri
);
379 sqlite3_finalize(sql
->stmt_locks_delete_uri_col
);
380 sqlite3_close(sql
->sqlh
);
384 free(p
->config_storage
);
390 return HANDLER_GO_ON
;
395 static handler_t
mod_webdav_sqlite3_init (plugin_config
* restrict s
, log_error_st
*errh
);
397 /* handle plugin config and check values */
398 SETDEFAULTS_FUNC(mod_webdav_set_defaults
) {
401 int sqlrc
= sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
);
402 if (sqlrc
!= SQLITE_OK
) {
403 log_error(srv
->errh
, __FILE__
, __LINE__
, "sqlite3_config(): %s",
404 sqlite3_errstr(sqlrc
));
405 /*(performance option since our use is not threaded; not fatal)*/
406 /*return HANDLER_ERROR;*/
410 config_values_t cv
[] = {
411 { "webdav.activate", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
},
412 { "webdav.is-readonly", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
},
413 { "webdav.log-xml", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
},
414 { "webdav.sqlite-db-name", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
},
415 { "webdav.opts", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
},
417 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
420 plugin_data
* const p
= (plugin_data
*)p_d
;
421 p
->config_storage
= calloc(srv
->config_context
->used
, sizeof(plugin_config
*));
422 force_assert(p
->config_storage
);
424 const size_t n_context
= p
->nconfig
= srv
->config_context
->used
;
425 for (size_t i
= 0; i
< n_context
; ++i
) {
426 data_config
const *config
=
427 (data_config
const *)srv
->config_context
->data
[i
];
428 plugin_config
* const restrict s
= calloc(1, sizeof(plugin_config
));
430 p
->config_storage
[i
] = s
;
431 s
->sqlite_db_name
= buffer_init();
432 s
->opts
= array_init();
434 cv
[0].destination
= &(s
->enabled
);
435 cv
[1].destination
= &(s
->is_readonly
);
436 cv
[2].destination
= &(s
->log_xml
);
437 cv
[3].destination
= s
->sqlite_db_name
;
438 cv
[4].destination
= s
->opts
;
440 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
441 return HANDLER_ERROR
;
444 if (!buffer_is_empty(s
->sqlite_db_name
)) {
445 if (mod_webdav_sqlite3_init(s
, srv
->errh
) == HANDLER_ERROR
)
446 return HANDLER_ERROR
;
449 for (size_t j
= 0, used
= s
->opts
->used
; j
< used
; ++j
) {
450 data_string
*ds
= (data_string
*)s
->opts
->data
[j
];
451 if (buffer_is_equal_string(ds
->key
,
452 CONST_STR_LEN("deprecated-unsafe-partial-put"))
453 && buffer_is_equal_string(ds
->value
, CONST_STR_LEN("enable"))) {
454 s
->deprecated_unsafe_partial_put_compat
= 1;
457 log_error(srv
->errh
, __FILE__
, __LINE__
,
458 "unrecognized webdav.opts: %.*s",
459 BUFFER_INTLEN_PTR(ds
->key
));
460 return HANDLER_ERROR
;
464 p
->config_storage
[0]->srv
= srv
;
465 p
->config_storage
[0]->tmpb
= srv
->tmp_buf
;
468 return HANDLER_GO_ON
;
472 #define PATCH_OPTION(x) pconf->x = s->x;
474 mod_webdav_patch_connection (server
* const restrict srv
,
475 connection
* const restrict con
,
476 const plugin_data
* const restrict p
,
477 plugin_config
* const restrict pconf
)
479 const plugin_config
*s
= p
->config_storage
[0];
480 memcpy(pconf
, s
, sizeof(*s
));
481 data_config
** const restrict context_data
=
482 (data_config
**)srv
->config_context
->data
;
484 for (size_t i
= 1; i
< srv
->config_context
->used
; ++i
) {
485 data_config
* const dc
= context_data
[i
];
486 if (!config_check_cond(srv
, con
, dc
))
487 continue; /* condition did not match */
489 s
= p
->config_storage
[i
];
492 for (size_t j
= 0; j
< dc
->value
->used
; ++j
) {
493 data_unset
*du
= dc
->value
->data
[j
];
494 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("webdav.activate"))) {
495 PATCH_OPTION(enabled
);
496 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("webdav.is-readonly"))) {
497 PATCH_OPTION(is_readonly
);
498 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("webdav.log-xml"))) {
499 PATCH_OPTION(log_xml
);
501 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("webdav.sqlite-db-name"))) {
504 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("webdav.opts"))) {
505 PATCH_OPTION(deprecated_unsafe_partial_put_compat
);
512 URIHANDLER_FUNC(mod_webdav_uri_handler
)
515 if (con
->request
.http_method
!= HTTP_METHOD_OPTIONS
)
516 return HANDLER_GO_ON
;
519 mod_webdav_patch_connection(srv
, con
, (plugin_data
*)p_d
, &pconf
);
520 if (!pconf
.enabled
) return HANDLER_GO_ON
;
522 /* [RFC4918] 18 DAV Compliance Classes */
523 http_header_response_set(con
, HTTP_HEADER_OTHER
,
524 CONST_STR_LEN("DAV"),
526 CONST_STR_LEN("1,2,3")
532 /* instruct MS Office Web Folders to use DAV
533 * (instead of MS FrontPage Extensions)
534 * http://www.zorched.net/2006/03/01/more-webdav-tips-tricks-and-bugs/ */
535 http_header_response_set(con
, HTTP_HEADER_OTHER
,
536 CONST_STR_LEN("MS-Author-Via"),
537 CONST_STR_LEN("DAV"));
539 if (pconf
.is_readonly
)
540 http_header_response_append(con
, HTTP_HEADER_OTHER
,
541 CONST_STR_LEN("Allow"),
542 CONST_STR_LEN("PROPFIND"));
544 http_header_response_append(con
, HTTP_HEADER_OTHER
,
545 CONST_STR_LEN("Allow"),
549 "PROPFIND, DELETE, MKCOL, PUT, MOVE, COPY, PROPPATCH, LOCK, UNLOCK")
552 "PROPFIND, DELETE, MKCOL, PUT, MOVE, COPY, PROPPATCH")
556 "PROPFIND, DELETE, MKCOL, PUT, MOVE, COPY")
560 return HANDLER_GO_ON
;
566 typedef struct webdav_lockdata
{
571 const buffer
*lockscope
; /* future: might use enum, store int in db */
572 const buffer
*locktype
; /* future: might use enum, store int in db */
574 int timeout
; /* offset from now, not absolute time_t */
577 typedef struct { const char *ptr
; uint32_t used
; uint32_t size
; } tagb
;
579 static const tagb lockscope_exclusive
=
580 { "exclusive", sizeof("exclusive"), 0 };
581 static const tagb lockscope_shared
=
582 { "shared", sizeof("shared"), 0 };
583 static const tagb locktype_write
=
584 { "write", sizeof("write"), 0 };
593 } webdav_property_name
;
596 webdav_property_name
*ptr
;
599 } webdav_property_names
;
602 * http://www.w3.org/TR/1998/NOTE-XML-data-0105/
603 * The datatype attribute "dt" is defined in the namespace named
604 * "urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/".
605 * (See the XML Namespaces Note at the W3C site for details of namespaces.)
606 * The full URN of the attribute is
607 * "urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/dt".
608 * http://www.w3.org/TR/1998/NOTE-xml-names-0119
609 * http://www.w3.org/TR/1998/WD-xml-names-19980327
610 * http://lists.xml.org/archives/xml-dev/200101/msg00924.html
611 * http://lists.xml.org/archives/xml-dev/200101/msg00929.html
612 * http://lists.xml.org/archives/xml-dev/200101/msg00930.html
613 * (Microsoft) Namespace Guidelines
614 * https://msdn.microsoft.com/en-us/library/ms879470%28v=exchg.65%29.aspx
615 * (Microsoft) XML Persistence Format
616 * https://msdn.microsoft.com/en-us/library/ms676547%28v=vs.85%29.aspx
617 * http://www.xml.com/pub/a/2002/06/26/vocabularies.html
618 * The "Uuid" namespaces is the namespace
619 * "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882",
620 * mainly found in association with the MS Office
621 * namespace on the http://www.omg.org website.
622 * http://www.data2type.de/en/xml-xslt-xslfo/wordml/wordml-introduction/the-root-element/
623 * xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
624 * By using the prefix dt, the namespace declares an attribute which
625 * determines the data type of a value. The name of the underlying schema
626 * is dt.xsd and it can be found in the folder for Excel schemas.
628 #define MOD_WEBDAV_XMLNS_NS0 "xmlns:ns0=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\""
632 webdav_xml_doctype (buffer
* const b
, connection
* const con
)
634 http_header_response_set(con
, HTTP_HEADER_CONTENT_TYPE
,
635 CONST_STR_LEN("Content-Type"),
636 CONST_STR_LEN("application/xml; charset=\"utf-8\""));
638 buffer_copy_string_len(b
, CONST_STR_LEN(
639 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"));
644 webdav_xml_prop (buffer
* const b
,
645 const webdav_property_name
* const prop
,
646 const char * const value
, const uint32_t vlen
)
648 buffer_append_string_len(b
, CONST_STR_LEN("<"));
649 buffer_append_string_len(b
, prop
->name
, prop
->namelen
);
650 buffer_append_string_len(b
, CONST_STR_LEN(" xmlns=\""));
651 buffer_append_string_len(b
, prop
->ns
, prop
->nslen
);
653 buffer_append_string_len(b
, CONST_STR_LEN("\"/>"));
656 buffer_append_string_len(b
, CONST_STR_LEN("\">"));
657 buffer_append_string_len(b
, value
, vlen
);
658 buffer_append_string_len(b
, CONST_STR_LEN("</"));
659 buffer_append_string_len(b
, prop
->name
, prop
->namelen
);
660 buffer_append_string_len(b
, CONST_STR_LEN(">"));
667 webdav_xml_href_raw (buffer
* const b
, const buffer
* const href
)
669 buffer_append_string_len(b
, CONST_STR_LEN(
671 buffer_append_string_len(b
, CONST_BUF_LEN(href
));
672 buffer_append_string_len(b
, CONST_STR_LEN(
679 webdav_xml_href (buffer
* const b
, const buffer
* const href
)
681 buffer_append_string_len(b
, CONST_STR_LEN(
683 buffer_append_string_encoded(b
, CONST_BUF_LEN(href
), ENCODING_REL_URI
);
684 buffer_append_string_len(b
, CONST_STR_LEN(
690 webdav_xml_status (buffer
* const b
, const int status
)
692 buffer_append_string_len(b
, CONST_STR_LEN(
693 "<D:status>HTTP/1.1 "));
694 http_status_append(b
, status
);
695 buffer_append_string_len(b
, CONST_STR_LEN(
703 webdav_xml_propstat_protected (buffer
* const b
, const char * const propname
,
704 const uint32_t len
, const int status
)
706 buffer_append_string_len(b
, CONST_STR_LEN(
709 buffer_append_string_len(b
, propname
, len
);
710 buffer_append_string_len(b
, CONST_STR_LEN(
712 "<D:error><DAV:cannot-modify-protected-property/></D:error>\n"));
713 webdav_xml_status(b
, status
); /* 403 */
714 buffer_append_string_len(b
, CONST_STR_LEN(
723 webdav_xml_propstat_status (buffer
* const b
, const char * const ns
,
724 const char * const name
, const int status
)
726 buffer_append_string_len(b
, CONST_STR_LEN(
729 buffer_append_string(b
, ns
);
730 buffer_append_string(b
, name
);
731 buffer_append_string_len(b
, CONST_STR_LEN(
733 webdav_xml_status(b
, status
);
734 buffer_append_string_len(b
, CONST_STR_LEN(
741 webdav_xml_propstat (buffer
* const b
, buffer
* const value
, const int status
)
743 buffer_append_string_len(b
, CONST_STR_LEN(
746 buffer_append_string_buffer(b
, value
);
747 buffer_append_string_len(b
, CONST_STR_LEN(
749 webdav_xml_status(b
, status
);
750 buffer_append_string_len(b
, CONST_STR_LEN(
757 webdav_xml_response_status (buffer
* const b
,
758 const buffer
* const href
,
761 buffer_append_string_len(b
, CONST_STR_LEN(
763 webdav_xml_href(b
, href
);
764 webdav_xml_status(b
, status
);
765 buffer_append_string_len(b
, CONST_STR_LEN(
772 webdav_xml_activelock (buffer
* const b
,
773 const webdav_lockdata
* const lockdata
,
774 const char * const tbuf
, uint32_t tbuf_len
)
776 buffer_append_string_len(b
, CONST_STR_LEN(
780 buffer_append_string_buffer(b
, lockdata
->lockscope
);
781 buffer_append_string_len(b
, CONST_STR_LEN(
786 buffer_append_string_buffer(b
, lockdata
->locktype
);
787 buffer_append_string_len(b
, CONST_STR_LEN(
791 if (0 == lockdata
->depth
)
792 buffer_append_string_len(b
, CONST_STR_LEN("0"));
794 buffer_append_string_len(b
, CONST_STR_LEN("infinity"));
795 buffer_append_string_len(b
, CONST_STR_LEN(
799 buffer_append_string_len(b
, tbuf
, tbuf_len
); /* "Second-..." */
801 buffer_append_string_len(b
, CONST_STR_LEN("Second-"));
802 buffer_append_int(b
, lockdata
->timeout
);
804 buffer_append_string_len(b
, CONST_STR_LEN(
807 if (!buffer_string_is_empty(&lockdata
->ownerinfo
))
808 buffer_append_string_buffer(b
, &lockdata
->ownerinfo
);
809 buffer_append_string_len(b
, CONST_STR_LEN(
812 webdav_xml_href_raw(b
, &lockdata
->locktoken
); /*(as-is; not URL-encoded)*/
813 buffer_append_string_len(b
, CONST_STR_LEN(
816 webdav_xml_href(b
, &lockdata
->lockroot
);
817 buffer_append_string_len(b
, CONST_STR_LEN(
819 "</D:activelock>\n"));
825 webdav_xml_doc_multistatus (connection
* const con
,
826 const plugin_config
* const pconf
,
829 http_status_set_fin(con
, 207); /* Multi-status */
831 buffer
* const b
= /*(optimization; buf extended as needed)*/
832 chunkqueue_append_buffer_open_sz(con
->write_queue
, 128 + ms
->used
);
834 webdav_xml_doctype(b
, con
);
835 buffer_append_string_len(b
, CONST_STR_LEN(
836 "<D:multistatus xmlns:D=\"DAV:\">\n"));
837 buffer_append_string_buffer(b
, ms
);
838 buffer_append_string_len(b
, CONST_STR_LEN(
839 "</D:multistatus>\n"));
842 log_error(con
->errh
, __FILE__
, __LINE__
,
843 "XML-response-body: %.*s", BUFFER_INTLEN_PTR(b
));
845 chunkqueue_append_buffer_commit(con
->write_queue
);
851 webdav_xml_doc_multistatus_response (connection
* const con
,
852 const plugin_config
* const pconf
,
855 http_status_set_fin(con
, 207); /* Multi-status */
857 buffer
* const b
= /*(optimization; buf extended as needed)*/
858 chunkqueue_append_buffer_open_sz(con
->write_queue
, 128 + ms
->used
);
860 webdav_xml_doctype(b
, con
);
861 buffer_append_string_len(b
, CONST_STR_LEN(
862 "<D:multistatus xmlns:D=\"DAV:\">\n"
864 webdav_xml_href(b
, con
->physical
.rel_path
);
865 buffer_append_string_buffer(b
, ms
);
866 buffer_append_string_len(b
, CONST_STR_LEN(
868 "</D:multistatus>\n"));
871 log_error(con
->errh
, __FILE__
, __LINE__
,
872 "XML-response-body: %.*s", BUFFER_INTLEN_PTR(b
));
874 chunkqueue_append_buffer_commit(con
->write_queue
);
881 webdav_xml_doc_lock_acquired (connection
* const con
,
882 const plugin_config
* const pconf
,
883 const webdav_lockdata
* const lockdata
)
885 /*(http_status is set by caller to 200 OK or 201 Created)*/
887 char tbuf
[32] = "Second-";
888 li_itostrn(tbuf
+sizeof("Second-")-1, sizeof(tbuf
)-(sizeof("Second-")-1),
890 const uint32_t tbuf_len
= strlen(tbuf
);
891 http_header_response_set(con
, HTTP_HEADER_OTHER
,
892 CONST_STR_LEN("Timeout"),
896 chunkqueue_append_buffer_open_sz(con
->write_queue
, 1024);
898 webdav_xml_doctype(b
, con
);
899 buffer_append_string_len(b
, CONST_STR_LEN(
900 "<D:prop xmlns:D=\"DAV:\">\n"
901 "<D:lockdiscovery>\n"));
902 webdav_xml_activelock(b
, lockdata
, tbuf
, tbuf_len
);
903 buffer_append_string_len(b
, CONST_STR_LEN(
904 "</D:lockdiscovery>\n"
908 log_error(con
->errh
, __FILE__
, __LINE__
,
909 "XML-response-body: %.*s", BUFFER_INTLEN_PTR(b
));
911 chunkqueue_append_buffer_commit(con
->write_queue
);
917 * [RFC4918] 16 Precondition/Postcondition XML Elements
923 * "<D:error><DAV:cannot-modify-protected-property/></D:error>"
926 * "<D:error><DAV:no-external-entities/></D:error>"
929 * "<D:error><DAV:preserved-live-properties/></D:error>"
935 webdav_xml_doc_error_propfind_finite_depth (connection
* const con
)
937 http_status_set(con
, 403); /* Forbidden */
938 con
->file_finished
= 1;
941 chunkqueue_append_buffer_open_sz(con
->write_queue
, 256);
942 webdav_xml_doctype(b
, con
);
943 buffer_append_string_len(b
, CONST_STR_LEN(
944 "<D:error><DAV:propfind-finite-depth/></D:error>\n"));
945 chunkqueue_append_buffer_commit(con
->write_queue
);
952 webdav_xml_doc_error_lock_token_matches_request_uri (connection
* const con
)
954 http_status_set(con
, 409); /* Conflict */
955 con
->file_finished
= 1;
958 chunkqueue_append_buffer_open_sz(con
->write_queue
, 256);
959 webdav_xml_doctype(b
, con
);
960 buffer_append_string_len(b
, CONST_STR_LEN(
961 "<D:error><DAV:lock-token-matches-request-uri/></D:error>\n"));
962 chunkqueue_append_buffer_commit(con
->write_queue
);
970 webdav_xml_doc_423_locked (connection
* const con
, buffer
* const hrefs
,
971 const char * const errtag
, const uint32_t errtaglen
)
973 http_status_set(con
, 423); /* Locked */
974 con
->file_finished
= 1;
976 buffer
* const b
= /*(optimization; buf extended as needed)*/
977 chunkqueue_append_buffer_open_sz(con
->write_queue
, 256 + hrefs
->used
);
979 webdav_xml_doctype(b
, con
);
980 buffer_append_string_len(b
, CONST_STR_LEN(
981 "<D:error xmlns:D=\"DAV:\">\n"
983 buffer_append_string_len(b
, errtag
, errtaglen
);
984 buffer_append_string_len(b
, CONST_STR_LEN(
986 buffer_append_string_buffer(b
, hrefs
);
987 buffer_append_string_len(b
, CONST_STR_LEN(
989 buffer_append_string_len(b
, errtag
, errtaglen
);
990 buffer_append_string_len(b
, CONST_STR_LEN(
994 chunkqueue_append_buffer_commit(con
->write_queue
);
1002 webdav_xml_doc_error_lock_token_submitted (connection
* const con
,
1003 buffer
* const hrefs
)
1005 webdav_xml_doc_423_locked(con
, hrefs
,
1006 CONST_STR_LEN("lock-token-submitted"));
1014 webdav_xml_doc_error_no_conflicting_lock (connection
* const con
,
1015 buffer
* const hrefs
)
1017 webdav_xml_doc_423_locked(con
, hrefs
,
1018 CONST_STR_LEN("no-conflicting-lock"));
1023 #ifdef USE_PROPPATCH
1025 #define MOD_WEBDAV_SQLITE_CREATE_TABLE_PROPERTIES \
1026 "CREATE TABLE IF NOT EXISTS properties (" \
1027 " resource TEXT NOT NULL," \
1028 " prop TEXT NOT NULL," \
1029 " ns TEXT NOT NULL," \
1030 " value TEXT NOT NULL," \
1031 " PRIMARY KEY(resource, prop, ns))"
1033 #define MOD_WEBDAV_SQLITE_CREATE_TABLE_LOCKS \
1034 "CREATE TABLE IF NOT EXISTS locks (" \
1035 " locktoken TEXT NOT NULL," \
1036 " resource TEXT NOT NULL," \
1037 " lockscope TEXT NOT NULL," \
1038 " locktype TEXT NOT NULL," \
1039 " owner TEXT NOT NULL," \
1040 " ownerinfo TEXT NOT NULL," \
1041 " depth INT NOT NULL," \
1042 " timeout TIMESTAMP NOT NULL," \
1043 " PRIMARY KEY(locktoken))"
1045 #define MOD_WEBDAV_SQLITE_PROPS_SELECT_PROPNAMES \
1046 "SELECT prop, ns FROM properties WHERE resource = ?"
1048 #define MOD_WEBDAV_SQLITE_PROPS_SELECT_PROP \
1049 "SELECT value FROM properties WHERE resource = ? AND prop = ? AND ns = ?"
1051 #define MOD_WEBDAV_SQLITE_PROPS_SELECT_PROPS \
1052 "SELECT prop, ns, value FROM properties WHERE resource = ?"
1054 #define MOD_WEBDAV_SQLITE_PROPS_UPDATE_PROP \
1055 "REPLACE INTO properties (resource, prop, ns, value) VALUES (?, ?, ?, ?)"
1057 #define MOD_WEBDAV_SQLITE_PROPS_DELETE_PROP \
1058 "DELETE FROM properties WHERE resource = ? AND prop = ? AND ns = ?"
1060 #define MOD_WEBDAV_SQLITE_PROPS_DELETE \
1061 "DELETE FROM properties WHERE resource = ?"
1063 #define MOD_WEBDAV_SQLITE_PROPS_COPY \
1064 "INSERT INTO properties" \
1065 " SELECT ?, prop, ns, value FROM properties WHERE resource = ?"
1067 #define MOD_WEBDAV_SQLITE_PROPS_MOVE \
1068 "UPDATE OR REPLACE properties SET resource = ? WHERE resource = ?"
1070 #define MOD_WEBDAV_SQLITE_PROPS_MOVE_COL \
1071 "UPDATE OR REPLACE properties SET resource = ? || SUBSTR(resource, ?)" \
1072 " WHERE SUBSTR(resource, 1, ?) = ?"
1074 #define MOD_WEBDAV_SQLITE_LOCKS_ACQUIRE \
1075 "INSERT INTO locks" \
1076 " (locktoken,resource,lockscope,locktype,owner,ownerinfo,depth,timeout)" \
1077 " VALUES (?,?,?,?,?,?,?, CURRENT_TIME + ?)"
1079 #define MOD_WEBDAV_SQLITE_LOCKS_REFRESH \
1080 "UPDATE locks SET timeout = CURRENT_TIME + ? WHERE locktoken = ?"
1082 #define MOD_WEBDAV_SQLITE_LOCKS_RELEASE \
1083 "DELETE FROM locks WHERE locktoken = ?"
1085 #define MOD_WEBDAV_SQLITE_LOCKS_READ \
1086 "SELECT resource, owner, depth" \
1087 " FROM locks WHERE locktoken = ?"
1089 #define MOD_WEBDAV_SQLITE_LOCKS_READ_URI \
1091 " locktoken,resource,lockscope,locktype,owner,ownerinfo,depth," \
1092 "timeout - CURRENT_TIME" \
1093 " FROM locks WHERE resource = ?"
1095 #define MOD_WEBDAV_SQLITE_LOCKS_READ_URI_INFINITY \
1097 " locktoken,resource,lockscope,locktype,owner,ownerinfo,depth," \
1098 "timeout - CURRENT_TIME" \
1100 " WHERE depth = -1 AND resource = SUBSTR(?, 1, LENGTH(resource))"
1102 #define MOD_WEBDAV_SQLITE_LOCKS_READ_URI_MEMBERS \
1104 " locktoken,resource,lockscope,locktype,owner,ownerinfo,depth," \
1105 "timeout - CURRENT_TIME" \
1106 " FROM locks WHERE SUBSTR(resource, 1, ?) = ?"
1108 #define MOD_WEBDAV_SQLITE_LOCKS_DELETE_URI \
1109 "DELETE FROM locks WHERE resource = ?"
1111 #define MOD_WEBDAV_SQLITE_LOCKS_DELETE_URI_COL \
1112 "DELETE FROM locks WHERE SUBSTR(resource, 1, ?) = ?"
1113 /*"DELETE FROM locks WHERE locktoken LIKE ? || '%'"*/
1115 /*(not currently used)*/
1116 #define MOD_WEBDAV_SQLITE_LOCKS_DELETE_EXPIRED \
1117 "DELETE FROM locks WHERE timeout < CURRENT_TIME"
1119 #endif /* USE_PROPPATCH */
1124 mod_webdav_sqlite3_init (plugin_config
* const restrict s
,
1125 log_error_st
* const errh
)
1127 #ifndef USE_PROPPATCH
1129 log_error(errh
, __FILE__
, __LINE__
,
1130 "Sorry, no sqlite3 and libxml2 support include, "
1131 "compile with --with-webdav-props");
1133 return HANDLER_ERROR
;
1135 #else /* USE_PROPPATCH */
1137 /*(expects (plugin_config *s) (log_error_st *errh) (char *err))*/
1138 #define MOD_WEBDAV_SQLITE_CREATE_TABLE(query, label) \
1139 if (sqlite3_exec(sql->sqlh, query, NULL, NULL, &err) != SQLITE_OK) { \
1140 if (0 != strcmp(err, "table " label " already exists")) { \
1141 log_error(errh, __FILE__, __LINE__, \
1142 "create table " label ": %s", err); \
1143 sqlite3_free(err); \
1144 return HANDLER_ERROR; \
1146 sqlite3_free(err); \
1149 sql_config
* const sql
= s
->sql
= (sql_config
*)calloc(1, sizeof(*sql
));
1151 int sqlrc
= sqlite3_open_v2(s
->sqlite_db_name
->ptr
, &sql
->sqlh
,
1152 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, NULL
);
1153 if (sqlrc
!= SQLITE_OK
) {
1154 log_error(errh
, __FILE__
, __LINE__
, "sqlite3_open() '%.*s': %s",
1155 BUFFER_INTLEN_PTR(s
->sqlite_db_name
),
1157 ? sqlite3_errmsg(sql
->sqlh
)
1158 : sqlite3_errstr(sqlrc
));
1159 return HANDLER_ERROR
;
1163 MOD_WEBDAV_SQLITE_CREATE_TABLE( MOD_WEBDAV_SQLITE_CREATE_TABLE_PROPERTIES
,
1165 MOD_WEBDAV_SQLITE_CREATE_TABLE( MOD_WEBDAV_SQLITE_CREATE_TABLE_LOCKS
,
1168 /* add ownerinfo column to locks table (update older mod_webdav sqlite db)
1169 * (could check if 'PRAGMA user_version;' is 0, add column, and increment)*/
1170 #define MOD_WEBDAV_SQLITE_SELECT_LOCKS_OWNERINFO_TEST \
1171 "SELECT COUNT(*) FROM locks WHERE ownerinfo = \"\""
1172 #define MOD_WEBDAV_SQLITE_ALTER_TABLE_LOCKS \
1173 "ALTER TABLE locks ADD COLUMN ownerinfo TEXT NOT NULL DEFAULT \"\""
1174 if (sqlite3_exec(sql
->sqlh
, MOD_WEBDAV_SQLITE_SELECT_LOCKS_OWNERINFO_TEST
,
1175 NULL
, NULL
, &err
) != SQLITE_OK
) {
1176 sqlite3_free(err
); /* "no such column: ownerinfo" */
1177 if (sqlite3_exec(sql
->sqlh
, MOD_WEBDAV_SQLITE_ALTER_TABLE_LOCKS
,
1178 NULL
, NULL
, &err
) != SQLITE_OK
) {
1179 log_error(errh
, __FILE__
, __LINE__
, "alter table locks: %s", err
);
1181 return HANDLER_ERROR
;
1185 sqlite3_close(sql
->sqlh
);
1188 return HANDLER_GO_ON
;
1190 #endif /* USE_PROPPATCH */
1194 #ifdef USE_PROPPATCH
1197 mod_webdav_sqlite3_prep (sql_config
* const restrict sql
,
1198 const buffer
* const sqlite_db_name
,
1199 log_error_st
* const errh
)
1201 /*(expects (plugin_config *s) (log_error_st *errh))*/
1202 #define MOD_WEBDAV_SQLITE_PREPARE_STMT(query, stmt) \
1203 if (sqlite3_prepare_v2(sql->sqlh, query, sizeof(query)-1, &stmt, NULL) \
1205 log_error(errh, __FILE__, __LINE__, "sqlite3_prepare_v2(): %s", \
1206 sqlite3_errmsg(sql->sqlh)); \
1207 return HANDLER_ERROR; \
1210 int sqlrc
= sqlite3_open_v2(sqlite_db_name
->ptr
, &sql
->sqlh
,
1211 SQLITE_OPEN_READWRITE
, NULL
);
1212 if (sqlrc
!= SQLITE_OK
) {
1213 log_error(errh
, __FILE__
, __LINE__
, "sqlite3_open() '%.*s': %s",
1214 BUFFER_INTLEN_PTR(sqlite_db_name
),
1216 ? sqlite3_errmsg(sql
->sqlh
)
1217 : sqlite3_errstr(sqlrc
));
1218 return HANDLER_ERROR
;
1221 /* future: perhaps not all statements should be prepared;
1222 * infrequently executed statements could be run with sqlite3_exec(),
1223 * or prepared and finalized on each use, as needed */
1225 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_SELECT_PROPNAMES
,
1226 sql
->stmt_props_select_propnames
);
1227 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_SELECT_PROPS
,
1228 sql
->stmt_props_select_props
);
1229 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_SELECT_PROP
,
1230 sql
->stmt_props_select_prop
);
1231 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_UPDATE_PROP
,
1232 sql
->stmt_props_update_prop
);
1233 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_DELETE_PROP
,
1234 sql
->stmt_props_delete_prop
);
1235 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_COPY
,
1236 sql
->stmt_props_copy
);
1237 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_MOVE
,
1238 sql
->stmt_props_move
);
1239 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_MOVE_COL
,
1240 sql
->stmt_props_move_col
);
1241 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_PROPS_DELETE
,
1242 sql
->stmt_props_delete
);
1243 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_ACQUIRE
,
1244 sql
->stmt_locks_acquire
);
1245 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_REFRESH
,
1246 sql
->stmt_locks_refresh
);
1247 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_RELEASE
,
1248 sql
->stmt_locks_release
);
1249 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_READ
,
1250 sql
->stmt_locks_read
);
1251 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_READ_URI
,
1252 sql
->stmt_locks_read_uri
);
1253 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_READ_URI_INFINITY
,
1254 sql
->stmt_locks_read_uri_infinity
);
1255 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_READ_URI_MEMBERS
,
1256 sql
->stmt_locks_read_uri_members
);
1257 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_DELETE_URI
,
1258 sql
->stmt_locks_delete_uri
);
1259 MOD_WEBDAV_SQLITE_PREPARE_STMT( MOD_WEBDAV_SQLITE_LOCKS_DELETE_URI_COL
,
1260 sql
->stmt_locks_delete_uri_col
);
1262 return HANDLER_GO_ON
;
1265 #endif /* USE_PROPPATCH */
1268 SERVER_FUNC(mod_webdav_worker_init
)
1270 #ifdef USE_PROPPATCH
1271 /* open sqlite databases and prepare SQL statements in each worker process
1273 * https://www.sqlite.org/faq.html
1274 * Under Unix, you should not carry an open SQLite database
1275 * across a fork() system call into the child process.
1277 plugin_data
* const p
= (plugin_data
*)p_d
;
1278 plugin_config
*s
= p
->config_storage
[0];
1279 for (int n_context
= p
->nconfig
+1; --n_context
; ++s
) {
1280 if (!buffer_is_empty(s
->sqlite_db_name
)
1281 && mod_webdav_sqlite3_prep(s
->sql
, s
->sqlite_db_name
, srv
->errh
)
1283 return HANDLER_ERROR
;
1288 #endif /* USE_PROPPATCH */
1289 return HANDLER_GO_ON
;
1293 #ifdef USE_PROPPATCH
1295 webdav_db_transaction (const plugin_config
* const pconf
,
1296 const char * const action
)
1301 if (SQLITE_OK
== sqlite3_exec(pconf
->sql
->sqlh
, action
, NULL
, NULL
, &err
))
1305 fprintf(stderr
, "%s: %s: %s\n", __func__
, action
, err
);
1306 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1307 "%s: %s: %s\n", __func__
, action
, err
);
1314 #define webdav_db_transaction_begin(pconf) \
1315 webdav_db_transaction(pconf, "BEGIN;")
1317 #define webdav_db_transaction_begin_immediate(pconf) \
1318 webdav_db_transaction(pconf, "BEGIN IMMEDIATE;")
1320 #define webdav_db_transaction_commit(pconf) \
1321 webdav_db_transaction(pconf, "COMMIT;")
1323 #define webdav_db_transaction_rollback(pconf) \
1324 webdav_db_transaction(pconf, "ROLLBACK;")
1328 #define webdav_db_transaction_begin(pconf) 1
1329 #define webdav_db_transaction_begin_immediate(pconf) 1
1330 #define webdav_db_transaction_commit(pconf) 1
1331 #define webdav_db_transaction_rollback(pconf) 1
1338 webdav_lock_match (const plugin_config
* const pconf
,
1339 const webdav_lockdata
* const lockdata
)
1343 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_locks_read
;
1348 stmt
, 1, CONST_BUF_LEN(&lockdata
->locktoken
), SQLITE_STATIC
);
1350 int status
= -1; /* if lock does not exist */
1351 if (SQLITE_ROW
== sqlite3_step(stmt
)) {
1352 const char *text
= (char *)sqlite3_column_text(stmt
, 0); /* resource */
1353 uint32_t text_len
= (uint32_t) sqlite3_column_bytes(stmt
, 0);
1354 if (text_len
< lockdata
->lockroot
.used
1355 && 0 == memcmp(lockdata
->lockroot
.ptr
, text
, text_len
)
1356 && (text_len
== lockdata
->lockroot
.used
-1
1357 || -1 == sqlite3_column_int(stmt
, 2))) { /* depth */
1358 text
= (char *)sqlite3_column_text(stmt
, 1); /* owner */
1359 text_len
= (uint32_t)sqlite3_column_bytes(stmt
, 1);
1360 if (0 == text_len
/*(if no auth required to lock; not recommended)*/
1361 || buffer_is_equal_string(lockdata
->owner
, text
, text_len
))
1362 status
= 0; /* success; lock match */
1364 /*(future: might check if owner is a privileged admin user)*/
1365 status
= -3; /* not lock owner; not authorized */
1369 status
= -2; /* URI is not in scope of lock */
1372 sqlite3_reset(stmt
);
1375 * 0 lock exists and uri in scope and owner is privileged/owns lock
1376 * -1 lock does not exist
1377 * -2 URI is not in scope of lock
1378 * -3 owner does not own lock/is not privileged
1387 webdav_lock_activelocks_lockdata (sqlite3_stmt
* const stmt
,
1388 webdav_lockdata
* const lockdata
)
1390 lockdata
->locktoken
.ptr
= (char *)sqlite3_column_text(stmt
, 0);
1391 lockdata
->locktoken
.used
= sqlite3_column_bytes(stmt
, 0);
1392 lockdata
->lockroot
.ptr
= (char *)sqlite3_column_text(stmt
, 1);
1393 lockdata
->lockroot
.used
= sqlite3_column_bytes(stmt
, 1);
1394 lockdata
->lockscope
=
1395 (sqlite3_column_bytes(stmt
, 2) == (int)sizeof("exclusive")-1)
1396 ? (const buffer
*)&lockscope_exclusive
1397 : (const buffer
*)&lockscope_shared
;
1398 lockdata
->locktype
= (const buffer
*)&locktype_write
;
1399 lockdata
->owner
->ptr
= (char *)sqlite3_column_text(stmt
, 4);
1400 lockdata
->owner
->used
= sqlite3_column_bytes(stmt
, 4);
1401 lockdata
->ownerinfo
.ptr
= (char *)sqlite3_column_text(stmt
, 5);
1402 lockdata
->ownerinfo
.used
= sqlite3_column_bytes(stmt
, 5);
1403 lockdata
->depth
= sqlite3_column_int(stmt
, 6);
1404 lockdata
->timeout
= sqlite3_column_int(stmt
, 7);
1406 if (lockdata
->locktoken
.used
) ++lockdata
->locktoken
.used
;
1407 if (lockdata
->lockroot
.used
) ++lockdata
->lockroot
.used
;
1408 if (lockdata
->owner
->used
) ++lockdata
->owner
->used
;
1409 if (lockdata
->ownerinfo
.used
) ++lockdata
->ownerinfo
.used
;
1414 void webdav_lock_activelocks_cb(void * const vdata
,
1415 const webdav_lockdata
* const lockdata
);
1418 webdav_lock_activelocks (const plugin_config
* const pconf
,
1419 const buffer
* const uri
,
1420 const int expand_checks
,
1421 webdav_lock_activelocks_cb
* const lock_cb
,
1424 webdav_lockdata lockdata
;
1425 buffer owner
= { NULL
, 0, 0 };
1426 lockdata
.locktoken
.size
= 0;
1427 lockdata
.lockroot
.size
= 0;
1428 lockdata
.ownerinfo
.size
= 0;
1429 lockdata
.owner
= &owner
;
1434 /* check for locks with Depth: 0 (and Depth: infinity if 0==expand_checks)*/
1435 sqlite3_stmt
*stmt
= pconf
->sql
->stmt_locks_read_uri
;
1436 if (!stmt
|| !pconf
->sql
->stmt_locks_read_uri_infinity
1437 || !pconf
->sql
->stmt_locks_read_uri_members
)
1440 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1442 while (SQLITE_ROW
== sqlite3_step(stmt
)) {
1443 /* (avoid duplication with query below if infinity lock on collection)
1444 * (infinity locks are rejected on non-collections elsewhere) */
1445 if (0 != expand_checks
&& -1 == sqlite3_column_int(stmt
, 6) /*depth*/)
1448 webdav_lock_activelocks_lockdata(stmt
, &lockdata
);
1449 if (lockdata
.timeout
> 0)
1450 lock_cb(vdata
, &lockdata
);
1453 sqlite3_reset(stmt
);
1455 if (0 == expand_checks
)
1458 /* check for locks with Depth: infinity
1459 * (i.e. collections: self (if collection) or containing collections) */
1460 stmt
= pconf
->sql
->stmt_locks_read_uri_infinity
;
1462 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1464 while (SQLITE_ROW
== sqlite3_step(stmt
)) {
1465 webdav_lock_activelocks_lockdata(stmt
, &lockdata
);
1466 if (lockdata
.timeout
> 0)
1467 lock_cb(vdata
, &lockdata
);
1470 sqlite3_reset(stmt
);
1472 if (1 == expand_checks
)
1476 force_assert(0 != uri
->used
);
1479 /* check for locks on members within (internal to) collection */
1480 stmt
= pconf
->sql
->stmt_locks_read_uri_members
;
1482 sqlite3_bind_int( stmt
, 1, (int)uri
->used
-1);
1483 sqlite3_bind_text(stmt
, 2, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1485 while (SQLITE_ROW
== sqlite3_step(stmt
)) {
1486 /* (avoid duplication with query above for exact resource match) */
1487 if (uri
->used
-1 == (uint32_t)sqlite3_column_bytes(stmt
, 1) /*resource*/)
1490 webdav_lock_activelocks_lockdata(stmt
, &lockdata
);
1491 if (lockdata
.timeout
> 0)
1492 lock_cb(vdata
, &lockdata
);
1495 sqlite3_reset(stmt
);
1501 webdav_lock_delete_uri (const plugin_config
* const pconf
,
1502 const buffer
* const uri
)
1508 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_locks_delete_uri
;
1512 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1515 while (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1518 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1519 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1520 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1524 sqlite3_reset(stmt
);
1537 webdav_lock_delete_uri_col (const plugin_config
* const pconf
,
1538 const buffer
* const uri
)
1544 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_locks_delete_uri_col
;
1549 force_assert(0 != uri
->used
);
1552 sqlite3_bind_int( stmt
, 1, (int)uri
->used
-1);
1553 sqlite3_bind_text(stmt
, 2, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1556 while (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1559 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1560 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1561 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1565 sqlite3_reset(stmt
);
1579 webdav_lock_acquire (const plugin_config
* const pconf
,
1580 const webdav_lockdata
* const lockdata
)
1584 * only lockscope:"exclusive" and locktype:"write" currently supported,
1585 * so inserting strings into database is extraneous, and anyway should
1586 * be enums instead of strings, since there are limited supported values
1591 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_locks_acquire
;
1596 stmt
, 1, CONST_BUF_LEN(&lockdata
->locktoken
), SQLITE_STATIC
);
1598 stmt
, 2, CONST_BUF_LEN(&lockdata
->lockroot
), SQLITE_STATIC
);
1600 stmt
, 3, CONST_BUF_LEN(lockdata
->lockscope
), SQLITE_STATIC
);
1602 stmt
, 4, CONST_BUF_LEN(lockdata
->locktype
), SQLITE_STATIC
);
1603 if (lockdata
->owner
->used
)
1605 stmt
, 5, CONST_BUF_LEN(lockdata
->owner
), SQLITE_STATIC
);
1608 stmt
, 5, CONST_STR_LEN(""), SQLITE_STATIC
);
1609 if (lockdata
->ownerinfo
.used
)
1611 stmt
, 6, CONST_BUF_LEN(&lockdata
->ownerinfo
), SQLITE_STATIC
);
1614 stmt
, 6, CONST_STR_LEN(""), SQLITE_STATIC
);
1616 stmt
, 7, lockdata
->depth
);
1618 stmt
, 8, lockdata
->timeout
);
1621 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1624 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1625 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1626 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1630 sqlite3_reset(stmt
);
1639 webdav_lock_refresh (const plugin_config
* const pconf
,
1640 webdav_lockdata
* const lockdata
)
1644 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_locks_refresh
;
1648 const buffer
* const locktoken
= &lockdata
->locktoken
;
1649 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(locktoken
), SQLITE_STATIC
);
1650 sqlite3_bind_int( stmt
, 2, lockdata
->timeout
);
1653 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1656 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1657 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1658 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1662 sqlite3_reset(stmt
);
1664 /*(future: fill in lockscope, locktype, depth from database)*/
1673 webdav_lock_release (const plugin_config
* const pconf
,
1674 const webdav_lockdata
* const lockdata
)
1678 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_locks_release
;
1683 stmt
, 1, CONST_BUF_LEN(&lockdata
->locktoken
), SQLITE_STATIC
);
1686 if (SQLITE_DONE
== sqlite3_step(stmt
))
1687 status
= (0 != sqlite3_changes(pconf
->sql
->sqlh
));
1690 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1691 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1692 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1696 sqlite3_reset(stmt
);
1704 webdav_prop_move_uri (const plugin_config
* const pconf
,
1705 const buffer
* const src
,
1706 const buffer
* const dst
)
1708 #ifdef USE_PROPPATCH
1711 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_move
;
1715 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(dst
), SQLITE_STATIC
);
1716 sqlite3_bind_text(stmt
, 2, CONST_BUF_LEN(src
), SQLITE_STATIC
);
1718 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1720 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1721 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1722 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1726 sqlite3_reset(stmt
);
1739 webdav_prop_move_uri_col (const plugin_config
* const pconf
,
1740 const buffer
* const src
,
1741 const buffer
* const dst
)
1743 #ifdef USE_PROPPATCH
1746 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_move_col
;
1751 force_assert(0 != src
->used
);
1754 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(dst
), SQLITE_STATIC
);
1755 sqlite3_bind_int( stmt
, 2, (int)src
->used
);
1756 sqlite3_bind_int( stmt
, 3, (int)src
->used
-1);
1757 sqlite3_bind_text(stmt
, 4, CONST_BUF_LEN(src
), SQLITE_STATIC
);
1759 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1761 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1762 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1763 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1767 sqlite3_reset(stmt
);
1780 webdav_prop_delete_uri (const plugin_config
* const pconf
,
1781 const buffer
* const uri
)
1783 #ifdef USE_PROPPATCH
1786 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_delete
;
1790 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1792 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1794 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1795 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1796 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1800 sqlite3_reset(stmt
);
1812 webdav_prop_copy_uri (const plugin_config
* const pconf
,
1813 const buffer
* const src
,
1814 const buffer
* const dst
)
1816 #ifdef USE_PROPPATCH
1819 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_copy
;
1823 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(dst
), SQLITE_STATIC
);
1824 sqlite3_bind_text(stmt
, 2, CONST_BUF_LEN(src
), SQLITE_STATIC
);
1826 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1828 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1829 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1830 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1834 sqlite3_reset(stmt
);
1846 #ifdef USE_PROPPATCH
1848 webdav_prop_delete (const plugin_config
* const pconf
,
1849 const buffer
* const uri
,
1850 const char * const prop_name
,
1851 const char * const prop_ns
)
1855 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_delete_prop
;
1859 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1860 sqlite3_bind_text(stmt
, 2, prop_name
, strlen(prop_name
), SQLITE_STATIC
);
1861 sqlite3_bind_text(stmt
, 3, prop_ns
, strlen(prop_ns
), SQLITE_STATIC
);
1863 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1865 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1866 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1867 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1871 sqlite3_reset(stmt
);
1878 #ifdef USE_PROPPATCH
1880 webdav_prop_update (const plugin_config
* const pconf
,
1881 const buffer
* const uri
,
1882 const char * const prop_name
,
1883 const char * const prop_ns
,
1884 const char * const prop_value
)
1888 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_update_prop
;
1892 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1893 sqlite3_bind_text(stmt
, 2, prop_name
, strlen(prop_name
), SQLITE_STATIC
);
1894 sqlite3_bind_text(stmt
, 3, prop_ns
, strlen(prop_ns
), SQLITE_STATIC
);
1895 sqlite3_bind_text(stmt
, 4, prop_value
, strlen(prop_value
), SQLITE_STATIC
);
1897 if (SQLITE_DONE
!= sqlite3_step(stmt
)) {
1899 fprintf(stderr
, "%s: %s\n", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1900 log_error(pconf
->errh
, __FILE__
, __LINE__
,
1901 "%s: %s", __func__
, sqlite3_errmsg(pconf
->sql
->sqlh
));
1905 sqlite3_reset(stmt
);
1913 webdav_prop_select_prop (const plugin_config
* const pconf
,
1914 const buffer
* const uri
,
1915 const webdav_property_name
* const prop
,
1918 #ifdef USE_PROPPATCH
1921 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_select_prop
;
1923 return -1; /* not found */
1925 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1926 sqlite3_bind_text(stmt
, 2, prop
->name
, prop
->namelen
, SQLITE_STATIC
);
1927 sqlite3_bind_text(stmt
, 3, prop
->ns
, prop
->nslen
, SQLITE_STATIC
);
1929 if (SQLITE_ROW
== sqlite3_step(stmt
)) {
1930 webdav_xml_prop(b
, prop
, (char *)sqlite3_column_text(stmt
, 0),
1931 (uint32_t)sqlite3_column_bytes(stmt
, 0));
1932 sqlite3_reset(stmt
);
1933 return 0; /* found */
1935 sqlite3_reset(stmt
);
1942 return -1; /* not found */
1947 webdav_prop_select_props (const plugin_config
* const pconf
,
1948 const buffer
* const uri
,
1951 #ifdef USE_PROPPATCH
1954 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_select_props
;
1958 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1960 while (SQLITE_ROW
== sqlite3_step(stmt
)) {
1961 webdav_property_name prop
;
1962 prop
.ns
= (char *)sqlite3_column_text(stmt
, 1);
1963 prop
.name
= (char *)sqlite3_column_text(stmt
, 0);
1964 prop
.nslen
= (uint32_t)sqlite3_column_bytes(stmt
, 1);
1965 prop
.namelen
= (uint32_t)sqlite3_column_bytes(stmt
, 0);
1966 webdav_xml_prop(b
, &prop
, (char *)sqlite3_column_text(stmt
, 2),
1967 (uint32_t)sqlite3_column_bytes(stmt
, 2));
1970 sqlite3_reset(stmt
);
1980 webdav_prop_select_propnames (const plugin_config
* const pconf
,
1981 const buffer
* const uri
,
1984 #ifdef USE_PROPPATCH
1987 sqlite3_stmt
* const stmt
= pconf
->sql
->stmt_props_select_propnames
;
1991 /* get all property names (EMPTY) */
1992 sqlite3_bind_text(stmt
, 1, CONST_BUF_LEN(uri
), SQLITE_STATIC
);
1994 while (SQLITE_ROW
== sqlite3_step(stmt
)) {
1995 webdav_property_name prop
;
1996 prop
.ns
= (char *)sqlite3_column_text(stmt
, 1);
1997 prop
.name
= (char *)sqlite3_column_text(stmt
, 0);
1998 prop
.nslen
= (uint32_t)sqlite3_column_bytes(stmt
, 1);
1999 prop
.namelen
= (uint32_t)sqlite3_column_bytes(stmt
, 0);
2000 webdav_xml_prop(b
, &prop
, NULL
, 0);
2003 sqlite3_reset(stmt
);
2015 #if defined(__APPLE__) && defined(__MACH__)
2016 #include <copyfile.h> /* fcopyfile() *//* OS X 10.5+ */
2019 #include <libelftc.h> /* elftc_copyfile() */
2022 #include <sys/sendfile.h> /* sendfile() */
2025 /* file copy (blocking)
2026 * fds should point to regular files (S_ISREG()) (not dir, symlink, or other)
2027 * fds should not have O_NONBLOCK flag set
2028 * (unless O_NONBLOCK not relevant for files on a given operating system)
2029 * isz should be size of input file, and is a param to avoid extra fstat()
2030 * since size is needed for Linux sendfile(), as well as posix_fadvise().
2031 * caller should handler fchmod() and copying extended attribute, if desired
2033 __attribute_noinline__
2035 webdav_fcopyfile_sz (int ifd
, int ofd
, off_t isz
)
2038 /* Windows CopyFile() not usable here; operates on filenames, not fds */
2040 /*(file descriptors to *regular files* on most OS ignore O_NONBLOCK)*/
2041 /*fcntl(ifd, F_SETFL, fcntl(ifd, F_GETFL, 0) & ~O_NONBLOCK);*/
2042 /*fcntl(ofd, F_SETFL, fcntl(ofd, F_GETFL, 0) & ~O_NONBLOCK);*/
2045 #if defined(__APPLE__) && defined(__MACH__)
2046 if (0 == fcopyfile(ifd
, ofd
, NULL
, COPYFILE_ALL
))
2049 lseek(ifd
, 0, SEEK_SET
);
2050 lseek(ofd
, 0, SEEK_SET
);
2055 if (0 == elftc_copyfile(ifd
, ofd
))
2058 lseek(ifd
, 0, SEEK_SET
);
2059 lseek(ofd
, 0, SEEK_SET
);
2063 #ifdef __linux__ /* Linux 2.6.33+ sendfile() supports file-to-file copy */
2065 while (offset
< isz
&& sendfile(ifd
,ofd
,&offset
,(size_t)(isz
-offset
)) >= 0);
2069 /*lseek(ifd, 0, SEEK_SET);*/ /*(ifd offset not modified due to &offset arg)*/
2070 lseek(ofd
, 0, SEEK_SET
);
2076 ssize_t rd
, wr
, off
;
2080 rd
= read(ifd
, buf
, sizeof(buf
));
2081 } while (-1 == rd
&& errno
== EINTR
);
2082 if (rd
< 0) return rd
;
2086 wr
= write(ofd
, buf
+off
, (size_t)(rd
-off
));
2087 } while (wr
>= 0 ? (off
+= wr
) != rd
: errno
== EINTR
);
2088 if (wr
< 0) return -1;
2095 webdav_if_match_or_unmodified_since (connection
* const con
, struct stat
*st
)
2097 buffer
*im
= (0 != con
->etag_flags
)
2098 ? http_header_request_get(con
, HTTP_HEADER_OTHER
,
2099 CONST_STR_LEN("If-Match"))
2102 buffer
*inm
= (0 != con
->etag_flags
)
2103 ? http_header_request_get(con
, HTTP_HEADER_IF_NONE_MATCH
,
2104 CONST_STR_LEN("If-None-Match"))
2108 http_header_request_get(con
, HTTP_HEADER_OTHER
,
2109 CONST_STR_LEN("If-Unmodified-Since"));
2111 if (NULL
== im
&& NULL
== inm
&& NULL
== ius
) return 0;
2115 st
= (0 == lstat(con
->physical
.path
->ptr
, &stp
)) ? &stp
: NULL
;
2117 buffer
*etagb
= con
->physical
.etag
;
2118 if (NULL
!= st
&& (NULL
!= im
|| NULL
!= inm
)) {
2119 etag_create(etagb
, st
, con
->etag_flags
);
2120 etag_mutate(etagb
, etagb
);
2124 if (NULL
== st
|| !etag_is_equal(etagb
, im
->ptr
, 0))
2125 return 412; /* Precondition Failed */
2130 ? !buffer_is_equal_string(inm
,CONST_STR_LEN("*"))
2131 || (errno
!= ENOENT
&& errno
!= ENOTDIR
)
2132 : etag_is_equal(etagb
, inm
->ptr
, 0))
2133 return 412; /* Precondition Failed */
2138 return 412; /* Precondition Failed */
2139 struct tm itm
, *ftm
= gmtime(&st
->st_mtime
);
2140 if (NULL
== strptime(ius
->ptr
, "%a, %d %b %Y %H:%M:%S GMT", &itm
)
2141 || mktime(ftm
) > mktime(&itm
)) { /* timegm() not standard */
2142 return 412; /* Precondition Failed */
2151 webdav_response_etag (server
*srv
, connection
* const con
, struct stat
*st
)
2153 if (0 != con
->etag_flags
) {
2154 buffer
*etagb
= con
->physical
.etag
;
2155 etag_create(etagb
, st
, con
->etag_flags
);
2156 stat_cache_update_entry(srv
,CONST_BUF_LEN(con
->physical
.path
),st
,etagb
);
2157 etag_mutate(etagb
, etagb
);
2158 http_header_response_set(con
, HTTP_HEADER_ETAG
,
2159 CONST_STR_LEN("ETag"),
2160 CONST_BUF_LEN(etagb
));
2166 webdav_parse_Depth (connection
* const con
)
2168 /* Depth = "Depth" ":" ("0" | "1" | "infinity") */
2169 const buffer
* const h
=
2170 http_header_request_get(con
, HTTP_HEADER_OTHER
, CONST_STR_LEN("Depth"));
2172 /* (leading LWS is removed during header parsing in request.c) */
2176 /*case 'i':*/ /* e.g. "infinity" */
2177 /*case 'I':*/ /* e.g. "Infinity" */
2178 default: return -1;/* treat not-'0' and not-'1' as "infinity" */
2182 return -1; /* default value is -1 to represent "infinity" */
2187 webdav_unlinkat (const plugin_config
* const pconf
, const buffer
* const uri
,
2188 const int dfd
, const char * const d_name
, size_t len
)
2190 if (0 == unlinkat(dfd
, d_name
, 0)) {
2191 stat_cache_delete_entry(pconf
->srv
, d_name
, len
);
2192 return webdav_prop_delete_uri(pconf
, uri
);
2196 case EACCES
: case EPERM
: return 403; /* Forbidden */
2197 case ENOENT
: return 404; /* Not Found */
2198 default: return 501; /* Not Implemented */
2204 webdav_delete_file (const plugin_config
* const pconf
,
2205 const physical_st
* const dst
)
2207 if (0 == unlink(dst
->path
->ptr
)) {
2208 stat_cache_delete_entry(pconf
->srv
, CONST_BUF_LEN(dst
->path
));
2209 return webdav_prop_delete_uri(pconf
, dst
->rel_path
);
2213 case EACCES
: case EPERM
: return 403; /* Forbidden */
2214 case ENOENT
: return 404; /* Not Found */
2215 default: return 501; /* Not Implemented */
2221 webdav_delete_dir (const plugin_config
* const pconf
,
2222 physical_st
* const dst
,
2226 int multi_status
= 0;
2227 const int dfd
= fdevent_open_dirname(dst
->path
->ptr
, 0);
2228 DIR * const dir
= (dfd
>= 0) ? fdopendir(dfd
) : NULL
;
2230 if (dfd
>= 0) close(dfd
);
2231 webdav_xml_response_status(b
, dst
->rel_path
, 403);
2235 /* dst is modified in place to extend path,
2236 * so be sure to restore to base each loop iter */
2237 const uint32_t dst_path_used
= dst
->path
->used
;
2238 const uint32_t dst_rel_path_used
= dst
->rel_path
->used
;
2241 while (NULL
!= (de
= readdir(dir
))) {
2242 if (de
->d_name
[0] == '.'
2243 && (de
->d_name
[1] == '\0'
2244 || (de
->d_name
[1] == '.' && de
->d_name
[2] == '\0')))
2245 continue; /* ignore "." and ".." */
2247 #ifdef _DIRENT_HAVE_D_TYPE
2248 if (de
->d_type
!= DT_UNKNOWN
)
2249 s_isdir
= (de
->d_type
== DT_DIR
);
2254 if (0 != fstatat(dfd
, de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
))
2255 continue; /* file *just* disappeared? */
2256 /* parent rmdir() will fail later if file still exists
2257 * and fstatat() failed for other reasons */
2258 s_isdir
= S_ISDIR(st
.st_mode
);
2261 const uint32_t len
= (uint32_t) _D_EXACT_NAMLEN(de
);
2262 if (flags
& WEBDAV_FLAG_LC_NAMES
) /*(needed at least for rel_path)*/
2263 webdav_str_len_to_lower(de
->d_name
, len
);
2264 buffer_append_string_len(dst
->path
, de
->d_name
, len
);
2265 buffer_append_string_len(dst
->rel_path
, de
->d_name
, len
);
2268 buffer_append_string_len(dst
->path
, CONST_STR_LEN("/"));
2269 buffer_append_string_len(dst
->rel_path
, CONST_STR_LEN("/"));
2270 multi_status
|= webdav_delete_dir(pconf
, dst
, b
, flags
);
2274 webdav_unlinkat(pconf
, dst
->rel_path
, dfd
, de
->d_name
, len
);
2276 webdav_xml_response_status(b
, dst
->rel_path
, status
);
2281 dst
->path
->ptr
[ (dst
->path
->used
= dst_path_used
) -1] = '\0';
2282 dst
->rel_path
->ptr
[(dst
->rel_path
->used
= dst_rel_path_used
)-1] = '\0';
2286 if (0 == multi_status
) {
2288 if (0 == rmdir(dst
->path
->ptr
))
2289 rmdir_status
= webdav_prop_delete_uri(pconf
, dst
->rel_path
);
2293 case EPERM
: rmdir_status
= 403; break; /* Forbidden */
2294 case ENOENT
: rmdir_status
= 404; break; /* Not Found */
2295 default: rmdir_status
= 501; break; /* Not Implemented */
2298 if (0 != rmdir_status
) {
2299 webdav_xml_response_status(b
, dst
->rel_path
, rmdir_status
);
2304 return multi_status
;
2309 webdav_linktmp_rename (const plugin_config
* const pconf
,
2310 const buffer
* const src
,
2311 const buffer
* const dst
)
2313 buffer
* const tmpb
= pconf
->tmpb
;
2314 int rc
= -1; /*(not zero)*/
2316 buffer_copy_buffer(tmpb
, dst
);
2317 buffer_append_string_len(tmpb
, CONST_STR_LEN("."));
2318 buffer_append_int(tmpb
, (long)getpid());
2319 buffer_append_string_len(tmpb
, CONST_STR_LEN("."));
2320 buffer_append_uint_hex_lc(tmpb
, (uintptr_t)pconf
); /*(stack/heap addr)*/
2321 buffer_append_string_len(tmpb
, CONST_STR_LEN("~"));
2322 if (buffer_string_length(tmpb
) < PATH_MAX
2323 && 0 == linkat(AT_FDCWD
, src
->ptr
, AT_FDCWD
, tmpb
->ptr
, 0)) {
2325 rc
= rename(tmpb
->ptr
, dst
->ptr
);
2327 /* unconditionally unlink() src if rename() succeeds, just in case
2328 * dst previously existed and was already hard-linked to src. From
2329 * 'man -s 2 rename':
2330 * If oldpath and newpath are existing hard links referring to the
2331 * same file, then rename() does nothing, and returns a success
2333 * This introduces a small race condition between the rename() and
2334 * unlink() should new file have been created at src in the middle,
2335 * though unlikely if locks are used since locks have not yet been
2344 webdav_copytmp_rename (const plugin_config
* const pconf
,
2345 const physical_st
* const src
,
2346 const physical_st
* const dst
,
2347 const int overwrite
)
2349 buffer
* const tmpb
= pconf
->tmpb
;
2350 buffer_copy_buffer(tmpb
, dst
->path
);
2351 buffer_append_string_len(tmpb
, CONST_STR_LEN("."));
2352 buffer_append_int(tmpb
, (long)getpid());
2353 buffer_append_string_len(tmpb
, CONST_STR_LEN("."));
2354 buffer_append_uint_hex_lc(tmpb
, (uintptr_t)pconf
); /*(stack/heap addr)*/
2355 buffer_append_string_len(tmpb
, CONST_STR_LEN("~"));
2356 if (buffer_string_length(tmpb
) >= PATH_MAX
)
2357 return 414; /* URI Too Long */
2359 /* code does not currently support symlinks in webdav collections;
2360 * disallow symlinks as target when opening src and dst */
2362 const int ifd
= fdevent_open_cloexec(src
->path
->ptr
, 0, O_RDONLY
, 0);
2364 return 403; /* Forbidden */
2365 if (0 != fstat(ifd
, &st
) || !S_ISREG(st
.st_mode
)) {
2367 return 403; /* Forbidden */
2369 const int ofd
= fdevent_open_cloexec(tmpb
->ptr
, 0,
2370 O_WRONLY
| O_CREAT
| O_EXCL
| O_TRUNC
,
2374 return 403; /* Forbidden */
2377 /* perform *blocking* copy (not O_NONBLOCK);
2378 * blocks server from doing any other work until after copy completes
2379 * (should reach here only if unable to use link() and rename()
2380 * due to copy/move crossing device boundaries within the workspace) */
2381 int rc
= webdav_fcopyfile_sz(ifd
, ofd
, st
.st_size
);
2384 const int wc
= close(ofd
);
2386 if (0 != rc
|| 0 != wc
) {
2387 /* error reading or writing files */
2388 rc
= (0 != wc
&& wc
== ENOSPC
) ? 507 : 403;
2393 #ifndef RENAME_NOREPLACE /*(renameat2() not well-supported yet)*/
2396 if (0 == lstat(dst
->path
->ptr
, &stb
) || errno
!= ENOENT
)
2397 return 412; /* Precondition Failed */
2398 /* TOC-TOU race between lstat() and rename(),
2399 * but this is reasonable attempt to not overwrite existing entity */
2401 if (0 == rename(tmpb
->ptr
, dst
->path
->ptr
))
2403 if (0 == renameat2(AT_FDCWD
, tmpb
->ptr
,
2404 AT_FDCWD
, dst
->path
->ptr
,
2405 overwrite
? 0 : RENAME_NOREPLACE
))
2408 /* unconditional stat cache deletion
2409 * (not worth extra syscall/race to detect overwritten or not) */
2410 stat_cache_delete_entry(pconf
->srv
, CONST_BUF_LEN(dst
->path
));
2414 const int errnum
= errno
;
2419 case EISDIR
: return 409; /* Conflict */
2420 case EEXIST
: return 412; /* Precondition Failed */
2421 default: return 403; /* Forbidden */
2428 webdav_copymove_file (const plugin_config
* const pconf
,
2429 const physical_st
* const src
,
2430 const physical_st
* const dst
,
2433 const int overwrite
= (*flags
& WEBDAV_FLAG_OVERWRITE
);
2434 if (*flags
& WEBDAV_FLAG_MOVE_RENAME
) {
2435 #ifndef RENAME_NOREPLACE /*(renameat2() not well-supported yet)*/
2438 if (0 == lstat(dst
->path
->ptr
, &st
) || errno
!= ENOENT
)
2439 return 412; /* Precondition Failed */
2440 /* TOC-TOU race between lstat() and rename(),
2441 * but this is reasonable attempt to not overwrite existing entity*/
2443 if (0 == rename(src
->path
->ptr
, dst
->path
->ptr
))
2445 if (0 == renameat2(AT_FDCWD
, src
->path
->ptr
,
2446 AT_FDCWD
, dst
->path
->ptr
,
2447 overwrite
? 0 : RENAME_NOREPLACE
))
2450 /* unconditionally unlink() src if rename() succeeds, just in case
2451 * dst previously existed and was already hard-linked to src. From
2452 * 'man -s 2 rename':
2453 * If oldpath and newpath are existing hard links referring to the
2454 * same file, then rename() does nothing, and returns a success
2456 * This introduces a small race condition between the rename() and
2457 * unlink() should new file have been created at src in the middle,
2458 * though unlikely if locks are used since locks have not yet been
2460 if (overwrite
) unlink(src
->path
->ptr
);
2461 /* unconditional stat cache deletion
2462 * (not worth extra syscall/race to detect overwritten or not) */
2463 stat_cache_delete_entry(pconf
->srv
, CONST_BUF_LEN(dst
->path
));
2464 stat_cache_delete_entry(pconf
->srv
, CONST_BUF_LEN(src
->path
));
2465 webdav_prop_move_uri(pconf
, src
->rel_path
, dst
->rel_path
);
2468 else if (errno
== EEXIST
)
2469 return 412; /* Precondition Failed */
2471 else if (*flags
& WEBDAV_FLAG_COPY_LINK
) {
2472 if (0 == linkat(AT_FDCWD
, src
->path
->ptr
, AT_FDCWD
, dst
->path
->ptr
, 0)){
2473 webdav_prop_copy_uri(pconf
, src
->rel_path
, dst
->rel_path
);
2476 else if (errno
== EEXIST
) {
2478 return 412; /* Precondition Failed */
2479 if (0 == webdav_linktmp_rename(pconf
, src
->path
, dst
->path
)) {
2480 webdav_prop_copy_uri(pconf
, src
->rel_path
, dst
->rel_path
);
2484 else if (errno
== EXDEV
) {
2485 *flags
&= ~WEBDAV_FLAG_COPY_LINK
;
2486 *flags
|= WEBDAV_FLAG_COPY_XDEV
;
2490 /* link() or rename() failed; fall back to copy to tempfile and rename() */
2491 int status
= webdav_copytmp_rename(pconf
, src
, dst
, overwrite
);
2493 webdav_prop_copy_uri(pconf
, src
->rel_path
, dst
->rel_path
);
2494 if (*flags
& (WEBDAV_FLAG_MOVE_RENAME
|WEBDAV_FLAG_MOVE_XDEV
))
2495 webdav_delete_file(pconf
, src
);
2496 /*(copy successful, but how should we report if delete fails?)*/
2503 webdav_mkdir (const plugin_config
* const pconf
,
2504 const physical_st
* const dst
,
2505 const int overwrite
)
2507 if (0 == mkdir(dst
->path
->ptr
, WEBDAV_DIR_MODE
))
2512 case ENOTDIR
: break;
2513 case ENOENT
: return 409; /* Conflict */
2515 default: return 403; /* Forbidden */
2518 /* [RFC4918] 9.3.1 MKCOL Status Codes
2519 * 405 (Method Not Allowed) -
2520 * MKCOL can only be executed on an unmapped URL.
2522 if (overwrite
< 0) /*(mod_webdav_mkcol() passes overwrite = -1)*/
2523 return (errno
!= ENOTDIR
)
2524 ? 405 /* Method Not Allowed */
2525 : 409; /* Conflict */
2528 force_assert(2 <= dst
->path
->used
);
2529 force_assert(2 <= dst
->rel_path
->used
);
2534 dst
->path
->ptr
[dst
->path
->used
-2] = '\0'; /*(trailing slash)*/
2535 status
= lstat(dst
->path
->ptr
, &st
);
2536 dst
->path
->ptr
[dst
->path
->used
-2] = '/'; /*(restore slash)*/
2537 if (0 != status
) /* still ENOTDIR or *just* disappeared */
2538 return 409; /* Conflict */
2540 if (!overwrite
) /* copying into a non-dir ? */
2541 return 409; /* Conflict */
2543 if (S_ISDIR(st
.st_mode
))
2546 dst
->path
->ptr
[dst
->path
->used
-2] = '\0'; /*(trailing slash)*/
2547 dst
->rel_path
->ptr
[dst
->rel_path
->used
-2] = '\0';
2548 status
= webdav_delete_file(pconf
, dst
);
2549 dst
->path
->ptr
[dst
->path
->used
-2] = '/'; /*(restore slash)*/
2550 dst
->rel_path
->ptr
[dst
->rel_path
->used
-2] = '/';
2554 return (0 == mkdir(dst
->path
->ptr
, WEBDAV_DIR_MODE
))
2556 : 409; /* Conflict */
2561 webdav_copymove_dir (const plugin_config
* const pconf
,
2562 physical_st
* const src
,
2563 physical_st
* const dst
,
2567 /* NOTE: merging collections is NON-CONFORMANT behavior
2568 * (specified in [RFC4918])
2570 * However, merging collections during COPY/MOVE might be expected behavior
2571 * by client, as merging is the behavior of unix cp -r (recursive copy) as
2572 * well as how Microsoft Windows Explorer performs folder copies.
2574 * [RFC4918] 9.8.4 COPY and Overwriting Destination Resources
2575 * When a collection is overwritten, the membership of the destination
2576 * collection after the successful COPY request MUST be the same
2577 * membership as the source collection immediately before the COPY. Thus,
2578 * merging the membership of the source and destination collections
2579 * together in the destination is not a compliant behavior.
2580 * [Ed: strange how non-compliance statement is immediately followed by:]
2581 * In general, if clients require the state of the destination URL to be
2582 * wiped out prior to a COPY (e.g., to force live properties to be reset),
2583 * then the client could send a DELETE to the destination before the COPY
2584 * request to ensure this reset.
2585 * [Ed: if non-compliant merge behavior is the default here, and were it to
2586 * not be desired by client, client could send a DELETE to the destination
2587 * before issuing COPY. There is no easy way to obtain merge behavior
2588 * (were it not the non-compliant default here) unless the client recurses
2589 * into the source and destination, and creates a list of objects that need
2590 * to be copied. This could fail or miss files due to racing with other
2591 * clients. All of this might forget to emphasize that wiping out an
2592 * existing destination collection (a recursive operation) is dangerous and
2593 * would happen if the client set Overwrite: T or omitted setting Overwrite
2594 * since Overwrite: T is default (client must explicitly set Overwrite: F)]
2595 * [RFC4918] 9.9.3 MOVE and the Overwrite Header
2596 * If a resource exists at the destination and the Overwrite header is
2597 * "T", then prior to performing the move, the server MUST perform a
2598 * DELETE with "Depth: infinity" on the destination resource. If the
2599 * Overwrite header is set to "F", then the operation will fail.
2602 /* NOTE: aborting if 507 Insufficient Storage is NON-CONFORMANT behavior
2603 * [RFC4918] specifies that as much as possible of COPY or MOVE
2604 * should be completed.
2607 /* ??? upon encountering errors, should src->rel_path or dst->rel_path
2608 * be used in XML error ??? */
2614 int make_destdir
= 1;
2615 const int overwrite
= (flags
& WEBDAV_FLAG_OVERWRITE
);
2616 if (flags
& WEBDAV_FLAG_MOVE_RENAME
) {
2617 #ifndef RENAME_NOREPLACE /*(renameat2() not well-supported yet)*/
2619 if (0 == lstat(dst
->path
->ptr
, &st
) || errno
!= ENOENT
) {
2620 webdav_xml_response_status(b
, src
->rel_path
, 412);
2621 return 412; /* Precondition Failed */
2623 /* TOC-TOU race between lstat() and rename(),
2624 * but this is reasonable attempt to not overwrite existing entity*/
2626 if (0 == rename(src
->path
->ptr
, dst
->path
->ptr
))
2628 if (0 == renameat2(AT_FDCWD
, src
->path
->ptr
,
2629 AT_FDCWD
, dst
->path
->ptr
,
2630 overwrite
? 0 : RENAME_NOREPLACE
))
2633 webdav_prop_move_uri_col(pconf
, src
->rel_path
, dst
->rel_path
);
2641 webdav_xml_response_status(b
, src
->rel_path
, 412);
2642 return 412; /* Precondition Failed */
2648 webdav_xml_response_status(b
, src
->rel_path
, 409);
2649 return 409; /* Conflict */
2653 force_assert(2 <= dst
->path
->used
);
2656 dst
->path
->ptr
[dst
->path
->used
-2] = '\0'; /*(trailing slash)*/
2657 status
= lstat(dst
->path
->ptr
, &st
);
2658 dst
->path
->ptr
[dst
->path
->used
-2] = '/'; /*(restore slash)*/
2660 if (S_ISDIR(st
.st_mode
)) {
2666 force_assert(2 <= dst
->rel_path
->used
);
2669 dst
->path
->ptr
[dst
->path
->used
-2] = '\0'; /*(remove slash)*/
2670 dst
->rel_path
->ptr
[dst
->rel_path
->used
-2] = '\0';
2671 status
= webdav_delete_file(pconf
, dst
);
2672 dst
->path
->ptr
[dst
->path
->used
-2] = '/'; /*(restore slash)*/
2673 dst
->rel_path
->ptr
[dst
->rel_path
->used
-2] = '/';
2675 webdav_xml_response_status(b
, src
->rel_path
, status
);
2679 if (0 == rename(src
->path
->ptr
, dst
->path
->ptr
)) {
2680 webdav_prop_move_uri_col(pconf
, src
->rel_path
,
2687 flags
&= ~WEBDAV_FLAG_MOVE_RENAME
;
2688 flags
|= WEBDAV_FLAG_MOVE_XDEV
;
2689 /* (if overwrite, then could switch to WEBDAV_FLAG_COPY_XDEV
2690 * and set a flag so that before returning from this routine,
2691 * directory is deleted recursively, instead of deleting each
2692 * file after each copy. Only reliable if overwrite is set
2693 * since if it is not set, an error would leave file copies in
2694 * two places and would be difficult to recover if !overwrite)
2695 * (collections typically do not cross devices, so this is not
2696 * expected to be a common case) */
2705 if (0 != (status
= webdav_mkdir(pconf
, dst
, overwrite
))) {
2706 webdav_xml_response_status(b
, src
->rel_path
, status
);
2711 webdav_prop_copy_uri(pconf
, src
->rel_path
, dst
->rel_path
);
2713 /* copy from src to dst (and, if move, then delete src)
2714 * src and dst are modified in place to extend path,
2715 * so be sure to restore to base each loop iter */
2717 const uint32_t src_path_used
= src
->path
->used
;
2718 const uint32_t src_rel_path_used
= src
->rel_path
->used
;
2719 const uint32_t dst_path_used
= dst
->path
->used
;
2720 const uint32_t dst_rel_path_used
= dst
->rel_path
->used
;
2722 dfd
= fdevent_open_dirname(src
->path
->ptr
, 0);
2723 DIR * const srcdir
= (dfd
>= 0) ? fdopendir(dfd
) : NULL
;
2724 if (NULL
== srcdir
) {
2725 if (dfd
>= 0) close(dfd
);
2726 webdav_xml_response_status(b
, src
->rel_path
, 403);
2727 return 403; /* Forbidden */
2730 int multi_status
= 0;
2732 while (NULL
!= (de
= readdir(srcdir
))) {
2733 if (de
->d_name
[0] == '.'
2734 && (de
->d_name
[1] == '\0'
2735 || (de
->d_name
[1] == '.' && de
->d_name
[2] == '\0')))
2736 continue; /* ignore "." and ".." */
2738 #ifdef _DIRENT_HAVE_D_TYPE
2739 if (de
->d_type
!= DT_UNKNOWN
)
2740 d_type
= DTTOIF(de
->d_type
);
2744 if (0 != fstatat(dfd
, de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
))
2745 continue; /* file *just* disappeared? */
2746 d_type
= st
.st_mode
;
2749 const uint32_t len
= (uint32_t) _D_EXACT_NAMLEN(de
);
2750 if (flags
& WEBDAV_FLAG_LC_NAMES
) /*(needed at least for rel_path)*/
2751 webdav_str_len_to_lower(de
->d_name
, len
);
2753 buffer_append_string_len(src
->path
, de
->d_name
, len
);
2754 buffer_append_string_len(dst
->path
, de
->d_name
, len
);
2755 buffer_append_string_len(src
->rel_path
, de
->d_name
, len
);
2756 buffer_append_string_len(dst
->rel_path
, de
->d_name
, len
);
2758 if (S_ISDIR(d_type
)) { /* recursive call; depth first */
2759 buffer_append_string_len(src
->path
, CONST_STR_LEN("/"));
2760 buffer_append_string_len(dst
->path
, CONST_STR_LEN("/"));
2761 buffer_append_string_len(src
->rel_path
, CONST_STR_LEN("/"));
2762 buffer_append_string_len(dst
->rel_path
, CONST_STR_LEN("/"));
2763 status
= webdav_copymove_dir(pconf
, src
, dst
, b
, flags
);
2767 else if (S_ISREG(d_type
)) {
2768 status
= webdav_copymove_file(pconf
, src
, dst
, &flags
);
2770 webdav_xml_response_status(b
, src
->rel_path
, status
);
2773 else if (S_ISLNK(d_type
)) {
2774 /*(might entertain support in future, including readlink()
2775 * and changing dst symlink to be relative to new location.
2776 * (or, if absolute to the old location, then absolute to new)
2777 * Be sure to hard-link using linkat() w/o AT_SYMLINK_FOLLOW)*/
2781 src
->path
->ptr
[ (src
->path
->used
= src_path_used
) -1] = '\0';
2782 src
->rel_path
->ptr
[(src
->rel_path
->used
= src_rel_path_used
)-1] = '\0';
2783 dst
->path
->ptr
[ (dst
->path
->used
= dst_path_used
) -1] = '\0';
2784 dst
->rel_path
->ptr
[(dst
->rel_path
->used
= dst_rel_path_used
)-1] = '\0';
2786 if (507 == status
) {
2787 multi_status
= 507; /* Insufficient Storage */
2793 if (0 == multi_status
) {
2794 if (flags
& (WEBDAV_FLAG_MOVE_RENAME
|WEBDAV_FLAG_MOVE_XDEV
)) {
2795 status
= webdav_delete_dir(pconf
, src
, b
, flags
); /* content */
2797 webdav_xml_response_status(b
, src
->rel_path
, status
);
2803 return multi_status
;
2807 typedef struct webdav_propfind_bufs
{
2808 connection
* restrict con
;
2809 const plugin_config
* restrict pconf
;
2810 physical_st
* restrict dst
;
2811 buffer
* restrict b
;
2812 buffer
* restrict b_200
;
2813 buffer
* restrict b_404
;
2814 webdav_property_names proplist
;
2820 } webdav_propfind_bufs
;
2823 enum webdav_live_props_e
{
2824 WEBDAV_PROP_UNSET
= -1 /* (enum value to avoid compiler warning)*/
2825 ,WEBDAV_PROP_ALL
= 0 /* (ALL not really a prop; internal use) */
2826 /*,WEBDAV_PROP_CREATIONDATE*/ /* (located in database, if present) */
2827 /*,WEBDAV_PROP_DISPLAYNAME*/ /* (located in database, if present) */
2828 /*,WEBDAV_PROP_GETCONTENTLANGUAGE*/ /* (located in database, if present) */
2829 ,WEBDAV_PROP_GETCONTENTLENGTH
2830 ,WEBDAV_PROP_GETCONTENTTYPE
2831 ,WEBDAV_PROP_GETETAG
2832 ,WEBDAV_PROP_GETLASTMODIFIED
2833 /*,WEBDAV_PROP_LOCKDISCOVERY*/ /* (located in database, if present) */
2834 ,WEBDAV_PROP_RESOURCETYPE
2835 /*,WEBDAV_PROP_SOURCE*/ /* not implemented; removed in RFC4918 */
2836 ,WEBDAV_PROP_SUPPORTEDLOCK
2840 #ifdef USE_PROPPATCH
2842 struct live_prop_list
{
2845 enum webdav_live_props_e pnum
;
2848 static const struct live_prop_list live_properties
[] = { /*(namespace "DAV:")*/
2849 /* { CONST_STR_LEN("creationdate"), WEBDAV_PROP_CREATIONDATE }*/
2850 /*,{ CONST_STR_LEN("displayname"), WEBDAV_PROP_DISPLAYNAME }*/
2851 /*,{ CONST_STR_LEN("getcontentlanguage"), WEBDAV_PROP_GETCONTENTLANGUAGE}*/
2852 { CONST_STR_LEN("getcontentlength"), WEBDAV_PROP_GETCONTENTLENGTH
}
2853 ,{ CONST_STR_LEN("getcontenttype"), WEBDAV_PROP_GETCONTENTTYPE
}
2854 ,{ CONST_STR_LEN("getetag"), WEBDAV_PROP_GETETAG
}
2855 ,{ CONST_STR_LEN("getlastmodified"), WEBDAV_PROP_GETLASTMODIFIED
}
2857 /*,{ CONST_STR_LEN("lockdiscovery"), WEBDAV_PROP_LOCKDISCOVERY }*/
2859 ,{ CONST_STR_LEN("resourcetype"), WEBDAV_PROP_RESOURCETYPE
}
2860 /*,{ CONST_STR_LEN("source"), WEBDAV_PROP_SOURCE }*/
2862 ,{ CONST_STR_LEN("supportedlock"), WEBDAV_PROP_SUPPORTEDLOCK
}
2865 ,{ NULL
, 0, WEBDAV_PROP_UNSET
}
2868 /* protected live properties
2869 * (must also protect creationdate and lockdiscovery in database) */
2870 static const struct live_prop_list protected_props
[] = { /*(namespace "DAV:")*/
2871 { CONST_STR_LEN("creationdate"), WEBDAV_PROP_UNSET
2872 /*WEBDAV_PROP_CREATIONDATE*/ }
2873 /*,{ CONST_STR_LEN("displayname"), WEBDAV_PROP_DISPLAYNAME }*/
2874 /*,{ CONST_STR_LEN("getcontentlanguage"), WEBDAV_PROP_GETCONTENTLANGUAGE}*/
2875 ,{ CONST_STR_LEN("getcontentlength"), WEBDAV_PROP_GETCONTENTLENGTH
}
2876 ,{ CONST_STR_LEN("getcontenttype"), WEBDAV_PROP_GETCONTENTTYPE
}
2877 ,{ CONST_STR_LEN("getetag"), WEBDAV_PROP_GETETAG
}
2878 ,{ CONST_STR_LEN("getlastmodified"), WEBDAV_PROP_GETLASTMODIFIED
}
2879 ,{ CONST_STR_LEN("lockdiscovery"), WEBDAV_PROP_UNSET
2880 /*WEBDAV_PROP_LOCKDISCOVERY*/ }
2881 ,{ CONST_STR_LEN("resourcetype"), WEBDAV_PROP_RESOURCETYPE
}
2882 /*,{ CONST_STR_LEN("source"), WEBDAV_PROP_SOURCE }*/
2883 ,{ CONST_STR_LEN("supportedlock"), WEBDAV_PROP_SUPPORTEDLOCK
}
2885 ,{ NULL
, 0, WEBDAV_PROP_UNSET
}
2892 webdav_propfind_live_props (const webdav_propfind_bufs
* const restrict pb
,
2893 const enum webdav_live_props_e pnum
)
2895 buffer
* const restrict b
= pb
->b_200
;
2897 case WEBDAV_PROP_ALL
:
2899 /*case WEBDAV_PROP_CREATIONDATE:*/ /* (located in database, if present)*/
2901 case WEBDAV_PROP_CREATIONDATE
: {
2903 * defined by POSIX.1-2008 as last file status change timestamp
2904 * and is no long create-time (as it may have been on older filesystems)
2905 * Therefore, this should return Not Found.
2906 * [RFC4918] 15.1 creationdate Property
2907 * The DAV:creationdate property SHOULD be defined on all DAV
2908 * compliant resources. If present, it contains a timestamp of the
2909 * moment when the resource was created. Servers that are incapable
2910 * of persistently recording the creation date SHOULD instead leave
2911 * it undefined (i.e. report "Not Found").
2912 * (future: might store creationdate in database when PUT creates file
2913 * or LOCK creates empty file, or MKCOL creates collection (dir),
2914 * i.e. wherever the status is 201 Created)
2917 char ctime_buf
[sizeof("2005-08-18T07:27:16Z")];
2918 if (__builtin_expect( (NULL
!= gmtime_r(&pb
->st
.st_ctime
, &tm
)), 1)) {
2919 buffer_append_string_len(b
, CONST_STR_LEN(
2920 "<D:creationdate ns0:dt=\"dateTime.tz\">"));
2921 buffer_append_string_len(b
, ctime_buf
,
2922 strftime(ctime_buf
, sizeof(ctime_buf
),
2923 "%Y-%m-%dT%TZ", &tm
));
2924 buffer_append_string_len(b
, CONST_STR_LEN(
2925 "</D:creationdate>"));
2927 else if (pnum
!= WEBDAV_PROP_ALL
)
2928 return -1; /* invalid; report 'not found' */
2929 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
2930 __attribute_fallthrough__
2933 /*case WEBDAV_PROP_DISPLAYNAME:*/ /* (located in database, if present)*/
2934 /*case WEBDAV_PROP_GETCONTENTLANGUAGE:*/ /* (located in db, if present)*/
2936 case WEBDAV_PROP_GETCONTENTLANGUAGE
:
2937 /* [RFC4918] 15.3 getcontentlanguage Property
2938 * SHOULD NOT be protected, so that clients can reset the language.
2940 * The DAV:getcontentlanguage property MUST be defined on any
2941 * DAV-compliant resource that returns the Content-Language header on
2943 * (future: server does not currently set Content-Language and this
2944 * module would need to somehow find out if another module set it)
2946 buffer_append_string_len(b
, CONST_STR_LEN(
2947 "<D:getcontentlanguage>en</D:getcontentlanguage>"));
2948 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
2949 __attribute_fallthrough__
2951 case WEBDAV_PROP_GETCONTENTLENGTH
:
2952 buffer_append_string_len(b
, CONST_STR_LEN(
2953 "<D:getcontentlength>"));
2954 buffer_append_int(b
, pb
->st
.st_size
);
2955 buffer_append_string_len(b
, CONST_STR_LEN(
2956 "</D:getcontentlength>"));
2957 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
2958 __attribute_fallthrough__
2959 case WEBDAV_PROP_GETCONTENTTYPE
:
2960 /* [RFC4918] 15.5 getcontenttype Property
2961 * Potentially protected if the server prefers to assign content types
2962 * on its own (see also discussion in Section 9.7.1).
2963 * (server currently assigns content types)
2965 * [RFC4918] 15 DAV Properties
2966 * For properties defined based on HTTP GET response headers
2967 * (DAV:get*), the header value could include LWS as defined
2968 * in [RFC2616], Section 4.2. Server implementors SHOULD strip
2969 * LWS from these values before using as WebDAV property
2971 * e.g. application/xml;charset="utf-8"
2972 * instead of: application/xml; charset="utf-8"
2973 * (documentation-only; no check is done here to remove LWS)
2975 if (S_ISDIR(pb
->st
.st_mode
)) {
2976 buffer_append_string_len(b
, CONST_STR_LEN(
2977 "<D:getcontenttype>httpd/unix-directory</D:getcontenttype>"));
2980 /* provide content type by extension
2981 * Note: not currently supporting filesystem xattr */
2983 stat_cache_mimetype_by_ext(pb
->con
, CONST_BUF_LEN(pb
->dst
->path
));
2985 buffer_append_string_len(b
, CONST_STR_LEN(
2986 "<D:getcontenttype>"));
2987 buffer_append_string_buffer(b
, ct
);
2988 buffer_append_string_len(b
, CONST_STR_LEN(
2989 "</D:getcontenttype>"));
2992 if (pnum
!= WEBDAV_PROP_ALL
)
2993 return -1; /* invalid; report 'not found' */
2996 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
2997 __attribute_fallthrough__
2998 case WEBDAV_PROP_GETETAG
:
2999 if (0 != pb
->con
->etag_flags
) {
3000 buffer
*etagb
= pb
->con
->physical
.etag
;
3001 etag_create(etagb
, &pb
->st
, pb
->con
->etag_flags
);
3002 etag_mutate(etagb
, etagb
);
3003 buffer_append_string_len(b
, CONST_STR_LEN(
3005 buffer_append_string_buffer(b
, etagb
);
3006 buffer_append_string_len(b
, CONST_STR_LEN(
3008 buffer_clear(etagb
);
3010 else if (pnum
!= WEBDAV_PROP_ALL
)
3011 return -1; /* invalid; report 'not found' */
3012 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
3013 __attribute_fallthrough__
3014 case WEBDAV_PROP_GETLASTMODIFIED
:
3016 buffer_append_string_len(b
, CONST_STR_LEN(
3017 "<D:getlastmodified ns0:dt=\"dateTime.rfc1123\">"));
3018 buffer_append_strftime(b
, "%a, %d %b %Y %H:%M:%S GMT",
3019 gmtime(&pb
->st
.st_mtime
));
3020 buffer_append_string_len(b
, CONST_STR_LEN(
3021 "</D:getlastmodified>"));
3023 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
3024 __attribute_fallthrough__
3027 case WEBDAV_PROP_LOCKDISCOVERY
:
3028 /* database query for locks occurs in webdav_propfind_resource_props()*/
3029 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
3030 __attribute_fallthrough__
3033 case WEBDAV_PROP_RESOURCETYPE
:
3034 if (S_ISDIR(pb
->st
.st_mode
))
3035 buffer_append_string_len(b
, CONST_STR_LEN(
3036 "<D:resourcetype><D:collection/></D:resourcetype>"));
3038 buffer_append_string_len(b
, CONST_STR_LEN(
3039 "<D:resourcetype/>"));
3040 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
3041 __attribute_fallthrough__
3042 /*case WEBDAV_PROP_SOURCE:*/ /* not impl; removed in RFC4918 */
3044 case WEBDAV_PROP_SUPPORTEDLOCK
:
3045 buffer_append_string_len(b
, CONST_STR_LEN(
3048 "<D:lockscope><D:exclusive/></D:lockscope>"
3049 "<D:locktype><D:write/></D:locktype>"
3052 "<D:lockscope><D:shared/></D:lockscope>"
3053 "<D:locktype><D:write/></D:locktype>"
3055 "</D:supportedlock>"));
3056 if (pnum
!= WEBDAV_PROP_ALL
) return 0;/* found *//*(else fall through)*/
3057 __attribute_fallthrough__
3059 default: /* WEBDAV_PROP_UNSET */
3060 return -1; /* not found */
3062 return 0; /* found (WEBDAV_PROP_ALL) */
3068 webdav_propfind_lockdiscovery_cb (void * const vdata
,
3069 const webdav_lockdata
* const lockdata
)
3071 webdav_xml_activelock((buffer
*)vdata
, lockdata
, NULL
, 0);
3077 webdav_propfind_resource_props (const webdav_propfind_bufs
* const restrict pb
)
3079 const webdav_property_names
* const props
= &pb
->proplist
;
3080 if (props
->used
) { /* "props" or "allprop"+"include" */
3081 const webdav_property_name
*prop
= props
->ptr
;
3082 for (int i
= 0; i
< props
->used
; ++i
, ++prop
) {
3083 if (NULL
== prop
->name
/*(flag indicating prop is live prop enum)*/
3084 ? 0 == webdav_propfind_live_props(pb
, (enum webdav_live_props_e
)
3086 : 0 == webdav_prop_select_prop(pb
->pconf
, pb
->dst
->rel_path
,
3090 /*(error obtaining prop if reached)*/
3091 webdav_xml_prop(pb
->b_404
, prop
, NULL
, 0);
3096 webdav_propfind_live_props(pb
, WEBDAV_PROP_ALL
);
3097 webdav_prop_select_props(pb
->pconf
, pb
->dst
->rel_path
, pb
->b_200
);
3101 if (pb
->lockdiscovery
) {
3102 /* pb->lockdiscovery > 0:
3103 * report locks resource or containing (parent) collections
3104 * pb->lockdiscovery < 0:
3105 * report only those locks on specific resource
3106 * While this is not compliant with RFC, it may reduces quite a bit of
3107 * redundancy for propfind on Depth: 1 and Depth: infinity when there
3108 * are locks on parent collections. The client receiving this propfind
3109 * XML response should easily know that locks on collections apply to
3110 * the members of those collections and to further nested collections
3112 * future: might be many, many fewer database queries if make a single
3113 * query for the locks in the collection directory tree and parse the
3114 * results, rather than querying the database for each resource */
3115 buffer_append_string_len(pb
->b_200
, CONST_STR_LEN(
3116 "<D:lockdiscovery>"));
3117 webdav_lock_activelocks(pb
->pconf
, pb
->dst
->rel_path
,
3118 (pb
->lockdiscovery
> 0),
3119 webdav_propfind_lockdiscovery_cb
, pb
->b_200
);
3120 buffer_append_string_len(pb
->b_200
, CONST_STR_LEN(
3121 "</D:lockdiscovery>"));
3128 webdav_propfind_resource_propnames (const webdav_propfind_bufs
*
3131 static const char live_propnames
[] =
3132 "<getcontentlength/>\n"
3133 "<getcontenttype/>\n"
3135 "<getlastmodified/>\n"
3138 "<supportedlock/>\n"
3139 "<lockdiscovery/>\n"
3142 /* list live_properties which are not in database, plus "lockdiscovery" */
3143 buffer_append_string_len(pb
->b_200
,live_propnames
,sizeof(live_propnames
)-1);
3145 /* list properties in database 'properties' table for resource */
3146 webdav_prop_select_propnames(pb
->pconf
, pb
->dst
->rel_path
, pb
->b_200
);
3152 webdav_propfind_resource_403 (const webdav_propfind_bufs
* const restrict pb
)
3154 buffer
* const restrict b
= pb
->b
;
3155 buffer_append_string_len(b
, CONST_STR_LEN(
3157 webdav_xml_href(b
, pb
->dst
->rel_path
);
3158 buffer_append_string_len(b
, CONST_STR_LEN(
3160 webdav_xml_status(b
, 403); /* Forbidden */
3161 buffer_append_string_len(b
, CONST_STR_LEN(
3163 "</D:response>\n"));
3168 webdav_propfind_resource (const webdav_propfind_bufs
* const restrict pb
)
3170 buffer_clear(pb
->b_200
);
3171 buffer_clear(pb
->b_404
);
3174 webdav_propfind_resource_props(pb
);
3176 webdav_propfind_resource_propnames(pb
);
3178 /* buffer could get very large for large directory (or Depth: infinity)
3179 * attempt to allocate in 8K chunks, rather than default realloc in
3180 * 64-byte chunks (see buffer.h) which will lead to exponentially more
3181 * expensive copy behavior as buffer is resized over and over and over
3183 * future: avoid (potential) excessive memory usage by accumulating output
3186 buffer
* const restrict b
= pb
->b
;
3187 buffer
* const restrict b_200
= pb
->b_200
;
3188 buffer
* const restrict b_404
= pb
->b_404
;
3189 if (b
->size
- b
->used
< b_200
->used
+ b_404
->used
+ 1024) {
3190 size_t sz
= b
->used
+ BUFFER_MAX_REUSE_SIZE
3191 + b_200
->used
+ b_404
->used
+ 1024;
3192 /*(optimization; buffer is extended as needed)*/
3193 buffer_string_prepare_append(b
, sz
& (BUFFER_MAX_REUSE_SIZE
-1));
3196 buffer_append_string_len(b
, CONST_STR_LEN(
3198 webdav_xml_href(b
, pb
->dst
->rel_path
);
3199 if (b_200
->used
> 1) /* !unset and !blank */
3200 webdav_xml_propstat(b
, b_200
, 200);
3201 if (b_404
->used
> 1) /* !unset and !blank */
3202 webdav_xml_propstat(b
, b_404
, 404);
3203 buffer_append_string_len(b
, CONST_STR_LEN(
3204 "</D:response>\n"));
3209 webdav_propfind_dir (webdav_propfind_bufs
* const restrict pb
)
3211 const physical_st
* const dst
= pb
->dst
;
3212 const int dfd
= fdevent_open_dirname(dst
->path
->ptr
, 0);
3213 DIR * const dir
= (dfd
>= 0) ? fdopendir(dfd
) : NULL
;
3216 if (dfd
>= 0) close(dfd
);
3217 if (errnum
!= ENOENT
)
3218 webdav_propfind_resource_403(pb
); /* Forbidden */
3222 webdav_propfind_resource(pb
);
3224 if (pb
->lockdiscovery
> 0)
3225 pb
->lockdiscovery
= -pb
->lockdiscovery
; /*(check locks on node only)*/
3227 /* dst is modified in place to extend path,
3228 * so be sure to restore to base each loop iter */
3229 const uint32_t dst_path_used
= dst
->path
->used
;
3230 const uint32_t dst_rel_path_used
= dst
->rel_path
->used
;
3232 (pb
->con
->conf
.force_lowercase_filenames
? WEBDAV_FLAG_LC_NAMES
: 0);
3234 while (NULL
!= (de
= readdir(dir
))) {
3235 if (de
->d_name
[0] == '.'
3236 && (de
->d_name
[1] == '\0'
3237 || (de
->d_name
[1] == '.' && de
->d_name
[2] == '\0')))
3238 continue; /* ignore "." and ".." */
3240 if (0 != fstatat(dfd
, de
->d_name
, &pb
->st
, AT_SYMLINK_NOFOLLOW
))
3241 continue; /* file *just* disappeared? */
3243 const uint32_t len
= (uint32_t) _D_EXACT_NAMLEN(de
);
3244 if (flags
& WEBDAV_FLAG_LC_NAMES
) /*(needed by rel_path)*/
3245 webdav_str_len_to_lower(de
->d_name
, len
);
3246 buffer_append_string_len(dst
->path
, de
->d_name
, len
);
3247 buffer_append_string_len(dst
->rel_path
, de
->d_name
, len
);
3248 if (S_ISDIR(pb
->st
.st_mode
)) {
3249 buffer_append_string_len(dst
->path
, CONST_STR_LEN("/"));
3250 buffer_append_string_len(dst
->rel_path
, CONST_STR_LEN("/"));
3253 if (S_ISDIR(pb
->st
.st_mode
) && -1 == pb
->depth
)
3254 webdav_propfind_dir(pb
); /* recurse */
3256 webdav_propfind_resource(pb
);
3258 dst
->path
->ptr
[ (dst
->path
->used
= dst_path_used
) -1] = '\0';
3259 dst
->rel_path
->ptr
[(dst
->rel_path
->used
= dst_rel_path_used
)-1] = '\0';
3266 webdav_open_chunk_file_rd (chunk
* const c
)
3268 if (c
->file
.fd
< 0) /* open file if not already open *//*permit symlink*/
3269 c
->file
.fd
= fdevent_open_cloexec(c
->mem
->ptr
, 1, O_RDONLY
, 0);
3275 webdav_mmap_file_rd (void ** const addr
, const size_t length
,
3276 const int fd
, const off_t offset
)
3278 /*(caller must ensure offset is properly aligned to mmap requirements)*/
3281 *addr
= NULL
; /*(something other than MAP_FAILED)*/
3287 *addr
= mmap(NULL
, length
, PROT_READ
, MAP_SHARED
, fd
, offset
);
3288 if (*addr
== MAP_FAILED
&& errno
== EINVAL
)
3289 *addr
= mmap(NULL
, length
, PROT_READ
, MAP_PRIVATE
, fd
, offset
);
3290 return (*addr
!= MAP_FAILED
? 0 : -1);
3301 webdav_mmap_file_chunk (chunk
* const c
)
3303 /*(request body provided in temporary file, so ok to mmap().
3304 * Otherwise, must check defined(ENABLE_MMAP)) */
3305 /* chunk_reset() or chunk_free() will clean up mmap'd chunk */
3306 /* close c->file.fd only faster mmap() succeeds, since it will not
3307 * be able to be re-opened if it was a tmpfile that was unlinked */
3308 /*assert(c->type == FILE_CHUNK);*/
3309 if (MAP_FAILED
!= c
->file
.mmap
.start
)
3310 return c
->file
.mmap
.start
+ c
->offset
;
3312 if (webdav_open_chunk_file_rd(c
) < 0)
3315 webdav_mmap_file_rd((void **)&c
->file
.mmap
.start
, (size_t)c
->file
.length
,
3318 if (MAP_FAILED
== c
->file
.mmap
.start
)
3323 c
->file
.mmap
.length
= c
->file
.length
;
3324 return c
->file
.mmap
.start
+ c
->offset
;
3328 #if defined(USE_PROPPATCH) || defined(USE_LOCKS)
3329 __attribute_noinline__
3331 webdav_parse_chunkqueue (connection
* const con
,
3332 const plugin_config
* const pconf
)
3334 /* read the chunks in to the XML document */
3335 xmlParserCtxtPtr ctxt
= xmlCreatePushParserCtxt(NULL
, NULL
, NULL
, 0, NULL
);
3336 /* XXX: evaluate adding more xmlParserOptions */
3337 xmlCtxtUseOptions(ctxt
, XML_PARSE_NOERROR
| XML_PARSE_NOWARNING
3338 | XML_PARSE_PEDANTIC
| XML_PARSE_NONET
);
3340 chunkqueue
* const cq
= con
->request_content_queue
;
3341 size_t weWant
= cq
->bytes_in
- cq
->bytes_out
;
3342 int err
= XML_ERR_OK
;
3346 chunk
*c
= cq
->first
;
3349 force_assert(0 == weWant
|| c
!= NULL
);
3352 if (c
->type
== MEM_CHUNK
) {
3353 xmlstr
= c
->mem
->ptr
+ c
->offset
;
3354 weHave
= buffer_string_length(c
->mem
) - c
->offset
;
3356 else if (c
->type
== FILE_CHUNK
) {
3357 xmlstr
= webdav_mmap_file_chunk(c
);
3358 /*xmlstr = c->file.mmap.start + c->offset;*/
3359 if (NULL
!= xmlstr
) {
3360 weHave
= c
->file
.length
- c
->offset
;
3364 case ENOSYS
: case ENODEV
: case EINVAL
: break;
3366 log_perror(con
->errh
, __FILE__
, __LINE__
,
3367 "open() or mmap() '%*.s'",
3368 BUFFER_INTLEN_PTR(c
->mem
));
3370 if (webdav_open_chunk_file_rd(c
) < 0) {
3371 log_perror(con
->errh
, __FILE__
, __LINE__
,
3373 BUFFER_INTLEN_PTR(c
->mem
));
3374 err
= XML_IO_UNKNOWN
;
3379 if (-1 ==lseek(c
->file
.fd
,c
->file
.start
+c
->offset
,SEEK_SET
))
3381 off_t len
= c
->file
.length
- c
->offset
;
3382 if (len
> (off_t
)sizeof(buf
)) len
= (off_t
)sizeof(buf
);
3383 rd
= read(c
->file
.fd
, buf
, (size_t)len
);
3384 } while (-1 == rd
&& errno
== EINTR
);
3387 weHave
= (size_t)rd
;
3390 log_perror(con
->errh
, __FILE__
, __LINE__
,
3392 BUFFER_INTLEN_PTR(c
->mem
));
3393 err
= XML_IO_UNKNOWN
;
3399 log_error(con
->errh
, __FILE__
, __LINE__
,
3400 "unrecognized chunk type: %d", c
->type
);
3401 err
= XML_IO_UNKNOWN
;
3405 if (weHave
> weWant
) weHave
= weWant
;
3408 log_error(con
->errh
, __FILE__
, __LINE__
,
3409 "XML-request-body: %.*s", (int)weHave
, xmlstr
);
3411 if (XML_ERR_OK
!= (err
= xmlParseChunk(ctxt
, xmlstr
, weHave
, 0))) {
3412 log_error(con
->errh
, __FILE__
, __LINE__
,
3413 "xmlParseChunk failed at: %lld %zu %d",
3414 (long long int)cq
->bytes_out
, weHave
, err
);
3419 chunkqueue_mark_written(cq
, weHave
);
3420 chunkqueue_remove_finished_chunks(cq
);
3423 if (XML_ERR_OK
== err
) {
3424 switch ((err
= xmlParseChunk(ctxt
, 0, 0, 1))) {
3425 case XML_ERR_DOCUMENT_END
:
3427 if (ctxt
->wellFormed
) {
3428 xmlDoc
* const xml
= ctxt
->myDoc
;
3429 xmlFreeParserCtxt(ctxt
);
3434 log_error(con
->errh
, __FILE__
, __LINE__
,
3435 "xmlParseChunk failed at final packet: %d", err
);
3440 xmlFreeDoc(ctxt
->myDoc
);
3441 xmlFreeParserCtxt(ctxt
);
3449 struct webdav_lock_token_submitted_st
{
3453 const buffer
*authn_user
;
3462 webdav_lock_token_submitted_cb (void * const vdata
,
3463 const webdav_lockdata
* const lockdata
)
3465 /* RFE: improve support for shared locks
3466 * (instead of treating match of any shared lock as sufficient,
3467 * even when there are different lockroots)
3468 * keep track of matched shared locks and unmatched shared locks and
3469 * ensure that each lockroot with shared locks has at least one match
3470 * (Will need to allocate strings for each URI with shared lock and keep
3471 * track whether or not a shared lock has been matched for that URI.
3472 * After walking all locks, must walk looking for unmatched URIs,
3473 * and must free these strings) */
3475 /* [RFC4918] 6.4 Lock Creator and Privileges
3476 * When a locked resource is modified, a server MUST check that the
3477 * authenticated principal matches the lock creator (in addition to
3478 * checking for valid lock token submission).
3481 struct webdav_lock_token_submitted_st
* const cbdata
=
3482 (struct webdav_lock_token_submitted_st
*)vdata
;
3483 const buffer
* const locktoken
= &lockdata
->locktoken
;
3484 const int shared
= (lockdata
->lockscope
->used
!= sizeof("exclusive"));
3487 if (shared
) ++cbdata
->slocks
;
3489 for (int i
= 0; i
< cbdata
->used
; ++i
) {
3490 const buffer
* const token
= &cbdata
->tokens
[i
];
3491 /* locktoken match (locktoken not '\0' terminated) */
3492 if (buffer_is_equal_string(token
, CONST_BUF_LEN(locktoken
))) {
3493 /*(0 length owner if no auth required to lock; not recommended)*/
3494 if (buffer_string_is_empty(lockdata
->owner
)/*no lock owner;match*/
3495 || buffer_is_equal_string(cbdata
->authn_user
,
3496 CONST_BUF_LEN(lockdata
->owner
))) {
3497 if (shared
) ++cbdata
->smatch
;
3498 return; /* authenticated lock owner match */
3503 /* no match with lock tokens in request */
3505 webdav_xml_href(cbdata
->b
, &lockdata
->lockroot
);
3510 * check if request provides necessary locks to access the resource
3513 webdav_has_lock (connection
* const con
,
3514 const plugin_config
* const pconf
,
3515 const buffer
* const uri
)
3517 /* Note with regard to exclusive locks on collections: client should not be
3518 * able to obtain an exclusive lock on a collection if there are existing
3519 * locks on resource members inside the collection. Therefore, there is no
3520 * need to check here for locks on resource members inside collections.
3521 * (This ignores the possibility that an admin or some other privileged
3522 * or out-of-band process has added locks in spite of lock on collection.)
3523 * Revisit to properly support shared locks. */
3525 struct webdav_lock_token_submitted_st cbdata
;
3526 cbdata
.b
= buffer_init();
3527 cbdata
.tokens
= NULL
;
3534 /* XXX: maybe add config switch to require that authentication occurred? */
3535 buffer owner
= { NULL
, 0, 0 };/*owner (not authenticated)(auth_user unset)*/
3536 data_string
* const authn_user
= (data_string
*)
3537 array_get_element_klen(con
->environment
,
3538 CONST_STR_LEN("REMOTE_USER"));
3539 cbdata
.authn_user
= authn_user
? authn_user
->value
: &owner
;
3541 const buffer
* const h
=
3542 http_header_request_get(con
, HTTP_HEADER_OTHER
, CONST_STR_LEN("If"));
3544 if (!buffer_is_empty(h
)) {
3545 /* parse "If" request header for submitted lock tokens
3546 * While the below not a pedantic, validating parse, if the header
3547 * is non-conformant or contains unencoded characters, the result
3548 * will be misidentified or ignored lock tokens, which will result
3549 * in fail closed -- secure default behavior -- if those lock
3550 * tokens are required. It is highly unlikely that misparsing the "If"
3551 * request header will result in a valid lock token since lock tokens
3552 * should be unique, and opaquelocktoken should be globally unique */
3556 while (*p
== ' ' || *p
== '\t') ++p
;
3557 if (*p
== '<') { /* Resource-Tag */
3558 do { ++p
; } while (*p
!= '>' && *p
!= '\0');
3559 if (*p
== '\0') break;
3560 do { ++p
; } while (*p
== ' ' || *p
== '\t');
3564 while (*p
!= '(' && *p
!= '\0') ++p
;
3566 /* begin List in No-tag-list or Tagged-list
3567 * List = "(" 1*Condition ")"
3568 * Condition = ["Not"] (State-token | "[" entity-tag "]")
3571 while (*p
!= '\0' && *++p
!= ')') {
3572 while (*p
== ' ' || *p
== '\t') ++p
;
3573 if ( (p
[0] & 0xdf) == 'N'
3574 && (p
[1] & 0xdf) == 'O'
3575 && (p
[2] & 0xdf) == 'T') {
3578 while (*p
== ' ' || *p
== '\t') ++p
;
3580 if (*p
!= '<') { /* '<' begins State-token (Coded-URL) */
3581 if (*p
!= '[') break; /* invalid syntax */
3582 /* '[' and ']' wrap entity-tag */
3584 do { ++p
; } while (*p
!= ']' && *p
!= '\0');
3585 if (*p
!= ']') break; /* invalid syntax */
3586 if (p
== etag
) continue; /* ignore entity-tag if empty */
3587 if (notflag
) continue;/* ignore entity-tag in NOT context */
3588 if (0 == con
->etag_flags
) continue; /* ignore entity-tag */
3590 if (0 != lstat(con
->physical
.path
->ptr
, &st
)) {
3591 http_status_set_error(con
,412);/* Precondition Failed */
3594 if (S_ISDIR(st
.st_mode
)) continue;/*we ignore etag if dir*/
3595 buffer
*etagb
= con
->physical
.etag
;
3596 etag_create(etagb
, &st
, con
->etag_flags
);
3597 etag_mutate(etagb
, etagb
);
3599 int ematch
= etag_is_equal(etagb
, etag
, 0);
3602 http_status_set_error(con
,412);/* Precondition Failed */
3609 && 0 == strncmp(p
, "<DAV:no-lock>",
3610 sizeof("<DAV:no-lock>")-1)) {
3612 http_status_set_error(con
,412);/* Precondition Failed */
3615 p
+= sizeof("<DAV:no-lock>")-2; /* point p to '>' */
3619 /* State-token (Coded-URL)
3620 * Coded-URL = "<" absolute-URI ">"
3621 * ; No linear whitespace (LWS) allowed in Coded-URL
3622 * ; absolute-URI defined in RFC 3986, Section 4.3
3624 if (cbdata
.size
== cbdata
.used
) {
3625 if (cbdata
.size
== 16) { /* arbitrary limit */
3626 http_status_set_error(con
, 400); /* Bad Request */
3630 realloc(cbdata
.tokens
, sizeof(*(cbdata
.tokens
)) * 16);
3631 force_assert(cbdata
.tokens
); /*(see above limit)*/
3633 cbdata
.tokens
[cbdata
.used
].ptr
= p
+1;
3635 do { ++p
; } while (*p
!= '>' && *p
!= '\0');
3636 if (*p
== '\0') break; /* (*p != '>') */
3638 cbdata
.tokens
[cbdata
.used
].used
=
3639 (uint32_t)(p
- cbdata
.tokens
[cbdata
.used
].ptr
+ 1);
3642 } while (*p
++ == ')'); /* end of List in No-tag-list or Tagged-list */
3645 webdav_lock_activelocks(pconf
, uri
, 1,
3646 webdav_lock_token_submitted_cb
, &cbdata
);
3648 if (NULL
!= cbdata
.tokens
)
3649 free(cbdata
.tokens
);
3653 if (0 != cbdata
.b
->used
)
3655 else if (0 == cbdata
.nlocks
) { /* resource is not locked at all */
3656 /* error if lock provided on source and no locks present on source;
3657 * not error if no locks on Destination, but "If" provided for source */
3658 if (cbdata
.used
&& uri
== con
->physical
.rel_path
) {
3660 http_status_set_error(con
, 412); /* Precondition Failed */
3662 #if 0 /*(treat no locks as if caller is holding an appropriate lock)*/
3665 webdav_xml_href(cbdata
.b
, uri
);
3670 /*(XXX: overly simplistic shared lock matching allows any match of shared
3671 * locks even when there are shared locks on multiple different lockroots.
3672 * Failure is misreported since unmatched shared locks are not added to
3674 if (cbdata
.slocks
&& !cbdata
.smatch
)
3678 webdav_xml_doc_error_lock_token_submitted(con
, cbdata
.b
);
3680 buffer_free(cbdata
.b
);
3682 return (has_lock
> 0);
3685 #else /* ! defined(USE_LOCKS) */
3687 #define webdav_has_lock(con, pconf, uri) 1
3689 #endif /* ! defined(USE_LOCKS) */
3693 mod_webdav_propfind (connection
* const con
, const plugin_config
* const pconf
)
3695 if (con
->request
.content_length
) {
3696 #ifdef USE_PROPPATCH
3697 if (con
->state
== CON_STATE_READ_POST
) {
3698 handler_t rc
= connection_handle_read_post_state(pconf
->srv
, con
);
3699 if (rc
!= HANDLER_GO_ON
) return rc
;
3702 /* PROPFIND is idempotent and safe, so even if parsing XML input is not
3703 * supported, live properties can still be produced, so treat as allprop
3704 * request. NOTE: this behavior is NOT RFC CONFORMANT (and, well, if
3705 * compiled without XML support, this WebDAV implementation is already
3706 * non-compliant since it is missing support for XML request body).
3707 * RFC-compliant behavior would reject an ignored request body with
3708 * 415 Unsupported Media Type */
3710 http_status_set_error(con
, 415); /* Unsupported Media Type */
3711 return HANDLER_FINISHED
;
3716 webdav_propfind_bufs pb
;
3718 /* [RFC4918] 9.1 PROPFIND Method
3719 * Servers MUST support "0" and "1" depth requests on WebDAV-compliant
3720 * resources and SHOULD support "infinity" requests. In practice, support
3721 * for infinite-depth requests MAY be disabled, due to the performance and
3722 * security concerns associated with this behavior. Servers SHOULD treat
3723 * a request without a Depth header as if a "Depth: infinity" header was
3728 pb
.lockdiscovery
= 0;
3729 pb
.depth
= webdav_parse_Depth(con
);
3731 /* future: might add config option to enable Depth: infinity
3732 * (Depth: infinity is supported if this rejection is removed) */
3733 if (-1 == pb
.depth
) {
3734 webdav_xml_doc_error_propfind_finite_depth(con
);
3735 return HANDLER_FINISHED
;
3738 if (0 != lstat(con
->physical
.path
->ptr
, &pb
.st
)) {
3739 http_status_set_error(con
, (errno
== ENOENT
) ? 404 : 403);
3740 return HANDLER_FINISHED
;
3742 else if (S_ISDIR(pb
.st
.st_mode
)) {
3743 if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] != '/') {
3744 /* set "Content-Location" instead of sending 308 redirect to dir */
3745 if (!http_response_redirect_to_directory(pconf
->srv
, con
, 0))
3746 return HANDLER_FINISHED
;
3747 buffer_append_string_len(con
->physical
.path
, CONST_STR_LEN("/"));
3748 buffer_append_string_len(con
->physical
.rel_path
,CONST_STR_LEN("/"));
3751 else if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] == '/') {
3752 http_status_set_error(con
, 403);
3753 return HANDLER_FINISHED
;
3755 else if (0 != pb
.depth
) {
3756 http_status_set_error(con
, 403);
3757 return HANDLER_FINISHED
;
3760 pb
.proplist
.ptr
= NULL
;
3761 pb
.proplist
.used
= 0;
3762 pb
.proplist
.size
= 0;
3764 #ifdef USE_PROPPATCH
3765 xmlDocPtr xml
= NULL
;
3766 const xmlNode
*rootnode
= NULL
;
3767 if (con
->request
.content_length
) {
3768 if (NULL
== (xml
= webdav_parse_chunkqueue(con
, pconf
))) {
3769 http_status_set_error(con
, 400); /* Bad Request */
3770 return HANDLER_FINISHED
;
3772 rootnode
= xmlDocGetRootElement(xml
);
3775 if (NULL
!= rootnode
3776 && 0 == webdav_xmlstrcmp_fixed(rootnode
->name
, "propfind")) {
3777 for (const xmlNode
*cmd
= rootnode
->children
; cmd
; cmd
= cmd
->next
) {
3778 if (0 == webdav_xmlstrcmp_fixed(cmd
->name
, "allprop"))
3779 pb
.allprop
= pb
.lockdiscovery
= 1;
3780 else if (0 == webdav_xmlstrcmp_fixed(cmd
->name
, "propname"))
3782 else if (0 != webdav_xmlstrcmp_fixed(cmd
->name
, "prop")
3783 && 0 != webdav_xmlstrcmp_fixed(cmd
->name
, "include"))
3786 /* "prop" or "include": get prop by name */
3787 for (const xmlNode
*prop
= cmd
->children
; prop
; prop
= prop
->next
) {
3788 if (prop
->type
== XML_TEXT_NODE
)
3789 continue; /* ignore WS */
3791 if (prop
->ns
&& '\0' == *(char *)prop
->ns
->href
3792 && '\0' != *(char *)prop
->ns
->prefix
) {
3793 log_error(con
->errh
, __FILE__
, __LINE__
,
3794 "no name space for: %s", prop
->name
);
3795 /* 422 Unprocessable Entity */
3796 http_status_set_error(con
, 422);
3797 free(pb
.proplist
.ptr
);
3799 return HANDLER_FINISHED
;
3802 /* add property to requested list */
3803 if (pb
.proplist
.size
== pb
.proplist
.used
) {
3804 if (pb
.proplist
.size
== 32) {
3805 /* arbitrarily chosen limit of 32 */
3806 log_error(con
->errh
, __FILE__
, __LINE__
,
3807 "too many properties in request (> 32)");
3808 http_status_set_error(con
, 400); /* Bad Request */
3809 free(pb
.proplist
.ptr
);
3811 return HANDLER_FINISHED
;
3814 realloc(pb
.proplist
.ptr
, sizeof(*(pb
.proplist
.ptr
)) * 32);
3815 force_assert(pb
.proplist
.ptr
); /*(see above limit)*/
3818 const size_t namelen
= strlen((char *)prop
->name
);
3819 if (prop
->ns
&& 0 == strcmp((char *)prop
->ns
->href
, "DAV:")) {
3820 if (namelen
== sizeof("lockdiscovery")-1
3821 && 0 == memcmp(prop
->name
,
3822 CONST_STR_LEN("lockdiscovery"))) {
3823 pb
.lockdiscovery
= 1;
3826 const struct live_prop_list
*list
= live_properties
;
3827 while (0 != list
->len
3828 && (list
->len
!= namelen
3829 || 0 != memcmp(prop
->name
,list
->prop
,list
->len
)))
3831 if (NULL
!= list
->prop
) {
3832 if (cmd
->name
[0] == 'p') { /* "prop", not "include" */
3833 pb
.proplist
.ptr
[pb
.proplist
.used
].name
= NULL
;
3834 pb
.proplist
.ptr
[pb
.proplist
.used
].namelen
=
3837 } /* (else skip; will already be part of allprop) */
3840 if (cmd
->name
[0] == 'i') /* allprop "include", not "prop" */
3841 continue; /*(all props in db returned with allprop)*/
3842 /* dead props or props in "DAV:" ns not handed above */
3845 /* save pointers directly into parsed xmlDoc
3846 * Therefore, MUST NOT call xmlFreeDoc(xml)
3847 * until also done with pb.proplist */
3848 webdav_property_name
* const propname
=
3849 pb
.proplist
.ptr
+ pb
.proplist
.used
++;
3851 propname
->ns
= (char *)prop
->ns
->href
;
3852 propname
->nslen
= strlen(propname
->ns
);
3856 propname
->nslen
= 0;
3858 propname
->name
= (char *)prop
->name
;
3859 propname
->namelen
= namelen
;
3865 if (NULL
== pb
.proplist
.ptr
&& !pb
.propname
)
3866 pb
.allprop
= pb
.lockdiscovery
= 1;
3870 pb
.dst
= &con
->physical
;
3871 pb
.b
= /*(optimization; buf extended as needed)*/
3872 chunkqueue_append_buffer_open_sz(con
->write_queue
, BUFFER_MAX_REUSE_SIZE
);
3873 pb
.b_200
= buffer_init();
3874 pb
.b_404
= buffer_init();
3876 buffer_string_prepare_copy(pb
.b_200
, BUFFER_MAX_REUSE_SIZE
-1);
3877 buffer_string_prepare_copy(pb
.b_404
, BUFFER_MAX_REUSE_SIZE
-1);
3879 webdav_xml_doctype(pb
.b
, con
);
3880 buffer_append_string_len(pb
.b
, CONST_STR_LEN(
3881 "<D:multistatus xmlns:D=\"DAV:\" " MOD_WEBDAV_XMLNS_NS0
">\n"));
3883 if (0 != pb
.depth
) /*(must be collection or else error returned above)*/
3884 webdav_propfind_dir(&pb
);
3886 webdav_propfind_resource(&pb
);
3888 buffer_append_string_len(pb
.b
, CONST_STR_LEN(
3889 "</D:multistatus>\n"));
3892 log_error(con
->errh
, __FILE__
, __LINE__
, "XML-response-body: %.*s",
3893 BUFFER_INTLEN_PTR(pb
.b
));
3895 http_status_set_fin(con
, 207); /* Multi-status */
3897 buffer_free(pb
.b_404
);
3898 buffer_free(pb
.b_200
);
3899 #ifdef USE_PROPPATCH
3900 if (pb
.proplist
.ptr
)
3901 free(pb
.proplist
.ptr
);
3906 return HANDLER_FINISHED
;
3911 mod_webdav_mkcol (connection
* const con
, const plugin_config
* const pconf
)
3913 const int status
= webdav_mkdir(pconf
, &con
->physical
, -1);
3915 http_status_set_fin(con
, 201); /* Created */
3917 http_status_set_error(con
, status
);
3919 return HANDLER_FINISHED
;
3924 mod_webdav_delete (connection
* const con
, const plugin_config
* const pconf
)
3926 /* reject DELETE if original URI sent with fragment ('litmus' warning) */
3927 if (NULL
!= strchr(con
->request
.orig_uri
->ptr
, '#')) {
3928 http_status_set_error(con
, 403);
3929 return HANDLER_FINISHED
;
3933 if (-1 == lstat(con
->physical
.path
->ptr
, &st
)) {
3934 http_status_set_error(con
, (errno
== ENOENT
) ? 404 : 403);
3935 return HANDLER_FINISHED
;
3938 if (0 != webdav_if_match_or_unmodified_since(con
, &st
)) {
3939 http_status_set_error(con
, 412); /* Precondition Failed */
3940 return HANDLER_FINISHED
;
3943 if (S_ISDIR(st
.st_mode
)) {
3944 if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] != '/') {
3945 #if 0 /*(issues warning for /usr/bin/litmus copymove test)*/
3946 http_response_redirect_to_directory(pconf
->srv
, con
, 308);
3947 return HANDLER_FINISHED
; /* 308 Permanent Redirect */
3948 /* Alternatively, could append '/' to con->physical.path
3949 * and con->physical.rel_path, set Content-Location in
3950 * response headers, and continue to serve the request */
3952 buffer_append_string_len(con
->physical
.path
, CONST_STR_LEN("/"));
3953 buffer_append_string_len(con
->physical
.rel_path
,CONST_STR_LEN("/"));
3954 #if 0 /*(Content-Location not very useful to client after DELETE)*/
3955 /*(? should it be request.uri or orig_uri ?)*/
3956 /*(should be url-encoded path)*/
3957 buffer_append_string_len(con
->request
.uri
, CONST_STR_LEN("/"));
3958 http_header_response_set(con
, HTTP_HEADER_CONTENT_LOCATION
,
3959 CONST_STR_LEN("Content-Location"),
3960 CONST_BUF_LEN(con
->request
.uri
));
3964 /* require "infinity" if Depth request header provided */
3965 if (-1 != webdav_parse_Depth(con
)) {
3966 /* [RFC4918] 9.6.1 DELETE for Collections
3967 * The DELETE method on a collection MUST act as if a
3968 * "Depth: infinity" header was used on it. A client MUST NOT
3969 * submit a Depth header with a DELETE on a collection with any
3970 * value but infinity.
3972 http_status_set_error(con
, 400); /* Bad Request */
3973 return HANDLER_FINISHED
;
3976 buffer
* const ms
= buffer_init(); /* multi-status */
3978 const int flags
= (con
->conf
.force_lowercase_filenames
)
3979 ? WEBDAV_FLAG_LC_NAMES
3981 if (0 == webdav_delete_dir(pconf
, &con
->physical
, ms
, flags
)) {
3982 /* Note: this does not destroy locks if an error occurs,
3983 * which is not a problem if lock is only on the collection
3984 * being moved, but might need finer updates if there are
3985 * locks on internal elements that are successfully deleted */
3986 webdav_lock_delete_uri_col(pconf
, con
->physical
.rel_path
);
3987 http_status_set_fin(con
, 204); /* No Content */
3990 webdav_xml_doc_multistatus(con
, pconf
, ms
); /* 207 Multi-status */
3994 /* invalidate stat cache of src if DELETE, whether or not successful */
3995 stat_cache_delete_dir(pconf
->srv
, CONST_BUF_LEN(con
->physical
.path
));
3997 else if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] == '/')
3998 http_status_set_error(con
, 403);
4000 const int status
= webdav_delete_file(pconf
, &con
->physical
);
4002 webdav_lock_delete_uri(pconf
, con
->physical
.rel_path
);
4003 http_status_set_fin(con
, 204); /* No Content */
4006 http_status_set_error(con
, status
);
4009 return HANDLER_FINISHED
;
4014 mod_webdav_write_cq_first_chunk (connection
* const con
, chunkqueue
* const cq
,
4017 /* (Note: copying might take some time, temporarily pausing server) */
4018 chunk
*c
= cq
->first
;
4023 if (NULL
!= webdav_mmap_file_chunk(c
)) {
4025 wr
= write(fd
, c
->file
.mmap
.start
+c
->offset
,
4026 c
->file
.length
- c
->offset
);
4027 } while (-1 == wr
&& errno
== EINTR
);
4032 case ENOSYS
: case ENODEV
: case EINVAL
: break;
4034 log_perror(con
->errh
, __FILE__
, __LINE__
,
4035 "open() or mmap() '%*.s'",
4036 BUFFER_INTLEN_PTR(c
->mem
));
4039 if (webdav_open_chunk_file_rd(c
) < 0) {
4040 http_status_set_error(con
, 500); /* Internal Server Error */
4046 if (-1 == lseek(c
->file
.fd
, c
->file
.start
+c
->offset
, SEEK_SET
))
4048 off_t len
= c
->file
.length
- c
->offset
;
4049 if (len
> (off_t
)sizeof(buf
)) len
= (off_t
)sizeof(buf
);
4050 rd
= read(c
->file
.fd
, buf
, (size_t)len
);
4051 } while (-1 == rd
&& errno
== EINTR
);
4054 wr
= write(fd
, buf
, (size_t)rd
);
4055 } while (-1 == wr
&& errno
== EINTR
);
4059 log_perror(con
->errh
, __FILE__
, __LINE__
,
4061 BUFFER_INTLEN_PTR(c
->mem
));
4062 http_status_set_error(con
, 500); /* Internal Server Error */
4068 wr
= write(fd
, c
->mem
->ptr
+ c
->offset
,
4069 buffer_string_length(c
->mem
) - c
->offset
);
4070 } while (-1 == wr
&& errno
== EINTR
);
4075 chunkqueue_mark_written(cq
, wr
);
4076 chunkqueue_remove_finished_chunks(cq
);
4079 http_status_set_error(con
, (errno
== ENOSPC
) ? 507 : 403);
4085 __attribute_noinline__
4087 mod_webdav_write_cq (connection
* const con
, chunkqueue
* const cq
, const int fd
)
4089 chunkqueue_remove_finished_chunks(cq
);
4090 while (!chunkqueue_is_empty(cq
)) {
4091 if (mod_webdav_write_cq_first_chunk(con
, cq
, fd
) < 0) return 0;
4097 #if (defined(__linux__) || defined(__CYGWIN__)) && defined(O_TMPFILE)
4099 mod_webdav_write_single_file_chunk (connection
* const con
, chunkqueue
* const cq
)
4101 /* cq might have mem chunks after initial tempfile chunk
4102 * due to chunkqueue_steal() if request body is small */
4103 /*assert(cq->first->type == FILE_CHUNK);*/
4104 /*assert(cq->first->next != NULL);*/
4105 chunk
* const c
= cq
->first
;
4106 cq
->first
= c
->next
;
4107 if (mod_webdav_write_cq(con
, cq
, c
->file
.fd
)) {
4108 /*assert(cq->first == NULL);*/
4110 cq
->first
= cq
->last
= c
;
4114 /*assert(cq->first != NULL);*/
4115 c
->next
= cq
->first
;
4124 mod_webdav_put_0 (connection
* const con
, const plugin_config
* const pconf
)
4126 if (0 != webdav_if_match_or_unmodified_since(con
, NULL
)) {
4127 http_status_set_error(con
, 412); /* Precondition Failed */
4128 return HANDLER_FINISHED
;
4131 /* special-case PUT 0-length file */
4133 fd
= fdevent_open_cloexec(con
->physical
.path
->ptr
, 0,
4134 O_WRONLY
| O_CREAT
| O_EXCL
| O_TRUNC
,
4137 if (0 != con
->etag_flags
) {
4138 /*(skip sending etag if fstat() error; not expected)*/
4140 if (0 == fstat(fd
, &st
)) webdav_response_etag(pconf
->srv
, con
, &st
);
4143 http_status_set_fin(con
, 201); /* Created */
4144 return HANDLER_FINISHED
;
4146 else if (errno
== EISDIR
) {
4147 http_status_set_error(con
, 405); /* Method Not Allowed */
4148 return HANDLER_FINISHED
;
4152 webdav_delete_file(pconf
, &con
->physical
); /*(ignore result)*/
4153 /*(attempt unlink(); target might be symlink
4154 * and above O_NOFOLLOW resulted in ELOOP)*/
4156 fd
= fdevent_open_cloexec(con
->physical
.path
->ptr
, 0,
4157 O_WRONLY
| O_CREAT
| O_TRUNC
,
4161 http_status_set_fin(con
, 204); /* No Content */
4162 return HANDLER_FINISHED
;
4165 http_status_set_error(con
, 500); /* Internal Server Error */
4166 return HANDLER_FINISHED
;
4171 mod_webdav_put_prep (connection
* const con
, const plugin_config
* const pconf
)
4173 if (NULL
!= http_header_request_get(con
, HTTP_HEADER_OTHER
,
4174 CONST_STR_LEN("Content-Range"))) {
4175 if (pconf
->deprecated_unsafe_partial_put_compat
) return HANDLER_GO_ON
;
4176 /* [RFC7231] 4.3.4 PUT
4177 * An origin server that allows PUT on a given target resource MUST
4178 * send a 400 (Bad Request) response to a PUT request that contains a
4179 * Content-Range header field (Section 4.2 of [RFC7233]), since the
4180 * payload is likely to be partial content that has been mistakenly
4181 * PUT as a full representation.
4183 http_status_set_error(con
, 400); /* Bad Request */
4184 return HANDLER_FINISHED
;
4187 const uint32_t used
= con
->physical
.path
->used
;
4188 char *slash
= con
->physical
.path
->ptr
+ used
- 2;
4189 if (*slash
== '/') { /* disallow PUT on a collection (path ends in '/') */
4190 http_status_set_error(con
, 400); /* Bad Request */
4191 return HANDLER_FINISHED
;
4194 /* special-case PUT 0-length file */
4195 if (0 == con
->request
.content_length
)
4196 return mod_webdav_put_0(con
, pconf
);
4198 /* Create temporary file in target directory (to store reqbody as received)
4199 * Temporary file is unlinked so that if receiving reqbody fails,
4200 * temp file is automatically cleaned up when fd is closed.
4201 * While being received, temporary file is not part of directory listings.
4202 * While this might result in extra copying, it is simple and robust. */
4204 size_t len
= buffer_string_length(con
->physical
.path
);
4205 #if (defined(__linux__) || defined(__CYGWIN__)) && defined(O_TMPFILE)
4206 slash
= memrchr(con
->physical
.path
->ptr
, '/', len
);
4207 if (slash
== con
->physical
.path
->ptr
) slash
= NULL
;
4208 if (slash
) *slash
= '\0';
4209 fd
= fdevent_open_cloexec(con
->physical
.path
->ptr
, 1,
4210 O_RDWR
| O_TMPFILE
| O_APPEND
, WEBDAV_FILE_MODE
);
4211 if (slash
) *slash
= '/';
4215 buffer_append_string_len(con
->physical
.path
, CONST_STR_LEN("-XXXXXX"));
4216 fd
= fdevent_mkstemp_append(con
->physical
.path
->ptr
);
4217 if (fd
>= 0) unlink(con
->physical
.path
->ptr
);
4218 buffer_string_set_length(con
->physical
.path
, len
);
4221 http_status_set_error(con
, 500); /* Internal Server Error */
4222 return HANDLER_FINISHED
;
4225 /* copy all chunks even though expecting (at most) single MEM_CHUNK chunk
4226 * (still, loop on partial writes)
4227 * (Note: copying might take some time, temporarily pausing server)
4228 * (error status is set if error occurs) */
4229 chunkqueue
* const cq
= con
->request_content_queue
;
4230 off_t cqlen
= chunkqueue_length(cq
);
4231 if (!mod_webdav_write_cq(con
, cq
, fd
)) {
4233 return HANDLER_FINISHED
;
4236 chunkqueue_reset(cq
);
4237 if (0 != cqlen
) /*(con->physical.path copied, then c->mem cleared below)*/
4238 chunkqueue_append_file_fd(cq
, con
->physical
.path
, fd
, 0, cqlen
);
4240 /*(must be non-zero for fd to be appended, then reset to 0-length)*/
4241 chunkqueue_append_file_fd(cq
, con
->physical
.path
, fd
, 0, 1);
4242 cq
->last
->file
.length
= 0;
4245 buffer_clear(cq
->last
->mem
); /* file already unlink()ed */
4246 chunkqueue_set_tempdirs(cq
, cq
->tempdirs
, INTMAX_MAX
);
4247 cq
->last
->file
.is_temp
= 1;
4249 return HANDLER_GO_ON
;
4253 #if (defined(__linux__) || defined(__CYGWIN__)) && defined(O_TMPFILE)
4255 mod_webdav_put_linkat_rename (connection
* const con
,
4256 const plugin_config
* const pconf
,
4257 const char * const pathtemp
)
4259 chunkqueue
* const cq
= con
->request_content_queue
;
4260 chunk
*c
= cq
->first
;
4262 char pathproc
[32] = "/proc/self/fd/";
4263 li_itostrn(pathproc
+sizeof("/proc/self/fd/")-1,
4264 sizeof(pathproc
)-(sizeof("/proc/self/fd/")-1), (long)c
->file
.fd
);
4265 if (0 == linkat(AT_FDCWD
, pathproc
, AT_FDCWD
, pathtemp
, AT_SYMLINK_FOLLOW
)){
4267 #ifdef RENAME_NOREPLACE /*(renameat2() not well-supported yet)*/
4268 if (0 == renameat2(AT_FDCWD
, pathtemp
,
4269 AT_FDCWD
, con
->physical
.path
->ptr
, RENAME_NOREPLACE
))
4270 http_status_set_fin(con
, 201); /* Created */
4271 else if (0 == rename(pathtemp
, con
->physical
.path
->ptr
))
4272 http_status_set_fin(con
, 204); /* No Content */ /*(replaced)*/
4275 http_status_set_fin(con
, 0 == lstat(con
->physical
.path
->ptr
, &st
)
4276 ? 204 /* No Content */
4277 : 201); /* Created */
4278 if (0 != rename(pathtemp
, con
->physical
.path
->ptr
))
4281 if (errno
== EISDIR
)
4282 http_status_set_error(con
, 405); /* Method Not Allowed */
4284 http_status_set_error(con
, 403); /* Forbidden */
4288 if (0 != con
->etag_flags
&& http_status_get(con
) < 300) { /*(201, 204)*/
4289 /*(skip sending etag if fstat() error; not expected)*/
4290 if (0 == fstat(c
->file
.fd
, &st
))
4291 webdav_response_etag(pconf
->srv
, con
, &st
);
4294 chunkqueue_mark_written(cq
, c
->file
.length
);
4295 chunkqueue_remove_finished_chunks(cq
);
4306 mod_webdav_put_deprecated_unsafe_partial_put_compat (connection
* const con
,
4307 const plugin_config
*pconf
,
4308 const buffer
* const h
)
4310 /* historical code performed very limited range parse (repeated here) */
4311 /* we only support <num>- ... */
4312 const char *num
= h
->ptr
;
4315 if (0 != strncmp(num
, "bytes", sizeof("bytes")-1)) {
4316 http_status_set_error(con
, 501); /* Not Implemented */
4317 return HANDLER_FINISHED
;
4319 num
+= 5; /* +5 for "bytes" */
4320 offset
= strtoll(num
, &err
, 10); /*(strtoll() ignores leading whitespace)*/
4321 if (num
== err
|| *err
!= '-' || offset
< 0) {
4322 http_status_set_error(con
, 501); /* Not Implemented */
4323 return HANDLER_FINISHED
;
4326 const int fd
= fdevent_open_cloexec(con
->physical
.path
->ptr
, 0,
4327 O_WRONLY
, WEBDAV_FILE_MODE
);
4329 http_status_set_error(con
, (errno
== ENOENT
) ? 404 : 403);
4330 return HANDLER_FINISHED
;
4333 if (-1 == lseek(fd
, offset
, SEEK_SET
)) {
4335 http_status_set_error(con
, 500); /* Internal Server Error */
4336 return HANDLER_FINISHED
;
4339 /* copy all chunks even though expecting single chunk
4340 * (still, loop on partial writes)
4341 * (Note: copying might take some time, temporarily pausing server)
4342 * (error status is set if error occurs) */
4343 mod_webdav_write_cq(con
, con
->request_content_queue
, fd
);
4346 if (0 != con
->etag_flags
&& !http_status_is_set(con
)) {
4347 /*(skip sending etag if fstat() error; not expected)*/
4348 if (0 != fstat(fd
, &st
)) con
->etag_flags
= 0;
4351 const int wc
= close(fd
);
4352 if (0 != wc
&& !http_status_is_set(con
))
4353 http_status_set_error(con
, (errno
== ENOSPC
) ? 507 : 403);
4355 if (!http_status_is_set(con
)) {
4356 http_status_set_fin(con
, 204); /* No Content */
4357 if (0 != con
->etag_flags
) webdav_response_etag(pconf
->srv
, con
, &st
);
4360 return HANDLER_FINISHED
;
4365 mod_webdav_put (connection
* const con
, const plugin_config
* const pconf
)
4367 if (con
->state
== CON_STATE_READ_POST
) {
4368 int first_read
= chunkqueue_is_empty(con
->request_content_queue
);
4369 handler_t rc
= connection_handle_read_post_state(pconf
->srv
, con
);
4370 if (rc
!= HANDLER_GO_ON
) {
4371 if (first_read
&& rc
== HANDLER_WAIT_FOR_EVENT
4372 && 0 != webdav_if_match_or_unmodified_since(con
, NULL
)) {
4373 http_status_set_error(con
, 412); /* Precondition Failed */
4374 return HANDLER_FINISHED
;
4380 if (0 != webdav_if_match_or_unmodified_since(con
, NULL
)) {
4381 http_status_set_error(con
, 412); /* Precondition Failed */
4382 return HANDLER_FINISHED
;
4385 if (pconf
->deprecated_unsafe_partial_put_compat
) {
4386 const buffer
* const h
=
4387 http_header_request_get(con
, HTTP_HEADER_OTHER
,
4388 CONST_STR_LEN("Content-Range"));
4391 mod_webdav_put_deprecated_unsafe_partial_put_compat(con
,pconf
,h
);
4394 /* construct temporary filename in same directory as target
4395 * (expect cq contains exactly one chunk:
4396 * the temporary FILE_CHUNK created in mod_webdav_put_prep())
4397 * (do not reuse c->mem buffer; if tmpfile was unlinked, c->mem is blank)
4398 * (since temporary file was unlinked, no guarantee of unique name,
4399 * so add pid and fd to avoid conflict with an unlikely parallel
4400 * PUT request being handled by same server pid (presumably by
4401 * same client using same lock token)) */
4402 chunkqueue
* const cq
= con
->request_content_queue
;
4403 chunk
*c
= cq
->first
;
4405 /* future: might support client specifying getcontenttype property
4406 * using Content-Type request header. However, [RFC4918] 9.7.1 notes:
4407 * Many servers do not allow configuring the Content-Type on a
4408 * per-resource basis in the first place. Thus, clients can't always
4409 * rely on the ability to directly influence the content type by
4410 * including a Content-Type request header
4413 /*(similar to beginning of webdav_linktmp_rename())*/
4414 buffer
* const tmpb
= pconf
->tmpb
;
4415 buffer_copy_buffer(tmpb
, con
->physical
.path
);
4416 buffer_append_string_len(tmpb
, CONST_STR_LEN("."));
4417 buffer_append_int(tmpb
, (long)getpid());
4418 buffer_append_string_len(tmpb
, CONST_STR_LEN("."));
4419 if (c
->type
== MEM_CHUNK
)
4420 buffer_append_uint_hex_lc(tmpb
, (uintptr_t)pconf
); /*(stack/heap addr)*/
4422 buffer_append_int(tmpb
, (long)c
->file
.fd
);
4423 buffer_append_string_len(tmpb
, CONST_STR_LEN("~"));
4425 if (buffer_string_length(tmpb
) >= PATH_MAX
) { /*(temp file path too long)*/
4426 http_status_set_error(con
, 500); /* Internal Server Error */
4427 return HANDLER_FINISHED
;
4430 const char *pathtemp
= tmpb
->ptr
;
4432 #if (defined(__linux__) || defined(__CYGWIN__)) && defined(O_TMPFILE)
4433 if (c
->type
== FILE_CHUNK
) { /*(reqbody contained in single tempfile)*/
4434 if (NULL
!= c
->next
) {
4435 /* if request body <= 64k, in-memory chunks might have been
4436 * moved to cq instead of appended to first chunk FILE_CHUNK */
4437 if (!mod_webdav_write_single_file_chunk(con
, cq
))
4438 return HANDLER_FINISHED
;
4440 if (mod_webdav_put_linkat_rename(con
, pconf
, pathtemp
))
4441 return HANDLER_FINISHED
;
4442 /* attempt traditional copy (below) if linkat() failed for any reason */
4446 const int fd
= fdevent_open_cloexec(pathtemp
, 0,
4447 O_WRONLY
| O_CREAT
| O_EXCL
| O_TRUNC
,
4450 http_status_set_error(con
, 500); /* Internal Server Error */
4451 return HANDLER_FINISHED
;
4454 /* copy all chunks even though expecting single chunk
4455 * (still, loop on partial writes)
4456 * (Note: copying might take some time, temporarily pausing server)
4457 * (error status is set if error occurs) */
4458 mod_webdav_write_cq(con
, cq
, fd
);
4461 if (0 != con
->etag_flags
&& !http_status_is_set(con
)) {
4462 /*(skip sending etag if fstat() error; not expected)*/
4463 if (0 != fstat(fd
, &st
)) con
->etag_flags
= 0;
4466 const int wc
= close(fd
);
4467 if (0 != wc
&& !http_status_is_set(con
))
4468 http_status_set_error(con
, (errno
== ENOSPC
) ? 507 : 403);
4470 if (!http_status_is_set(con
)) {
4472 http_status_set_fin(con
, 0 == lstat(con
->physical
.path
->ptr
, &ste
)
4473 ? 204 /* No Content */
4474 : 201); /* Created */
4475 if (0 == rename(pathtemp
, con
->physical
.path
->ptr
)) {
4476 if (0 != con
->etag_flags
) webdav_response_etag(pconf
->srv
,con
,&st
);
4479 if (errno
== EISDIR
)
4480 http_status_set_error(con
, 405); /* Method Not Allowed */
4482 http_status_set_error(con
, 500); /* Internal Server Error */
4489 return HANDLER_FINISHED
;
4494 mod_webdav_copymove_b (connection
* const con
, const plugin_config
* const pconf
, buffer
* const dst_path
, buffer
* const dst_rel_path
)
4496 int flags
= WEBDAV_FLAG_OVERWRITE
/*(default)*/
4497 | (con
->conf
.force_lowercase_filenames
4498 ? WEBDAV_FLAG_LC_NAMES
4500 | (con
->request
.http_method
== HTTP_METHOD_MOVE
4501 ? WEBDAV_FLAG_MOVE_RENAME
4502 : WEBDAV_FLAG_COPY_LINK
);
4504 const buffer
* const h
=
4505 http_header_request_get(con
,HTTP_HEADER_OTHER
,CONST_STR_LEN("Overwrite"));
4508 || ((h
->ptr
[0] & 0xdf) != 'F' && (h
->ptr
[0] & 0xdf) != 'T')) {
4509 http_status_set_error(con
, 400); /* Bad Request */
4510 return HANDLER_FINISHED
;
4512 if ((h
->ptr
[0] & 0xdf) == 'F')
4513 flags
&= ~WEBDAV_FLAG_OVERWRITE
;
4516 /* parse Destination
4518 * http://127.0.0.1:1025/dav/litmus/copydest
4520 * - host has to match Host: header in request
4521 * (or else would need to check that Destination is reachable from server
4522 * and authentication credentials grant privileges on Destination)
4523 * - query string on Destination, if present, is discarded
4525 * NOTE: Destination path is relative to document root and IS NOT re-run
4526 * through other modules on server (such as aliasing or rewrite or userdir)
4528 const buffer
* const destination
=
4529 http_header_request_get(con
, HTTP_HEADER_OTHER
,
4530 CONST_STR_LEN("Destination"));
4531 if (NULL
== destination
) {
4532 http_status_set_error(con
, 400); /* Bad Request */
4533 return HANDLER_FINISHED
;
4536 force_assert(2 <= destination
->used
);
4539 const char *sep
= destination
->ptr
, *start
;
4540 if (*sep
!= '/') { /* path-absolute or absolute-URI form */
4542 sep
= start
+ buffer_string_length(con
->uri
.scheme
);
4543 if (0 != strncmp(start
, con
->uri
.scheme
->ptr
, sep
- start
)
4544 || sep
[0] != ':' || sep
[1] != '/' || sep
[2] != '/') {
4545 http_status_set_error(con
, 400); /* Bad Request */
4546 return HANDLER_FINISHED
;
4550 if (NULL
== (sep
= strchr(start
, '/'))) {
4551 http_status_set_error(con
, 400); /* Bad Request */
4552 return HANDLER_FINISHED
;
4554 if (!buffer_is_equal_string(con
->uri
.authority
, start
, sep
- start
)
4555 /* skip login info (even though it should not be present) */
4556 && (NULL
== (start
= (char *)memchr(start
, '@', sep
- start
))
4557 || (++start
, !buffer_is_equal_string(con
->uri
.authority
,
4558 start
, sep
- start
)))) {
4559 /* not the same host */
4560 http_status_set_error(con
, 502); /* Bad Gateway */
4561 return HANDLER_FINISHED
;
4564 start
= sep
; /* starts with '/' */
4567 dst
.path
= dst_path
;
4568 dst
.rel_path
= dst_rel_path
;
4570 /* destination: remove query string, urldecode, path_simplify
4571 * and (maybe) lowercase for consistent destination URI path */
4572 buffer_copy_string_len(dst_rel_path
, start
,
4573 NULL
== (sep
= strchr(start
, '?'))
4574 ? destination
->ptr
+ destination
->used
-1 - start
4576 if (buffer_string_length(dst_rel_path
) >= PATH_MAX
) {
4577 http_status_set_error(con
, 403); /* Forbidden */
4578 return HANDLER_FINISHED
;
4580 buffer_urldecode_path(dst_rel_path
);
4581 if (!buffer_is_valid_UTF8(dst_rel_path
)) {
4582 /* invalid UTF-8 after url-decode */
4583 http_status_set_error(con
, 400);
4584 return HANDLER_FINISHED
;
4586 buffer_path_simplify(dst_rel_path
, dst_rel_path
);
4587 if (buffer_string_is_empty(dst_rel_path
) || dst_rel_path
->ptr
[0] != '/') {
4588 http_status_set_error(con
, 400);
4589 return HANDLER_FINISHED
;
4592 if (flags
& WEBDAV_FLAG_LC_NAMES
)
4593 buffer_to_lower(dst_rel_path
);
4595 /* Destination physical path
4596 * src con->physical.path might have been remapped with mod_alias.
4597 * (but mod_alias does not modify con->physical.rel_path)
4598 * Find matching prefix to support use of mod_alias to remap webdav root.
4599 * Aliasing of paths underneath the webdav root might not work.
4600 * Likewise, mod_rewrite URL rewriting might thwart this comparison.
4601 * Use mod_redirect instead of mod_alias to remap paths *under* webdav root.
4602 * Use mod_redirect instead of mod_rewrite on *any* parts of path to webdav.
4603 * (Related, use mod_auth to protect webdav root, but avoid attempting to
4604 * use mod_auth on paths underneath webdav root, as Destination is not
4605 * validated with mod_auth)
4607 * tl;dr: webdav paths and webdav properties are managed by mod_webdav,
4608 * so do not modify paths externally or else undefined behavior
4609 * or corruption may occur
4611 * find matching URI prefix (lowercased if WEBDAV_FLAG_LC_NAMES)
4612 * (con->physical.rel_path and dst_rel_path will always match leading '/')
4613 * check if remaining con->physical.rel_path matches suffix of
4614 * con->physical.path so that we can use the prefix to remap
4615 * Destination physical path */
4617 force_assert(0 != con
->physical
.rel_path
->used
);
4621 const char * const p1
= con
->physical
.rel_path
->ptr
;
4622 const char * const p2
= dst_rel_path
->ptr
;
4623 for (i
= 0; p1
[i
] && p1
[i
] == p2
[i
]; ++i
) ;
4624 while (i
!= 0 && p1
[--i
] != '/') ; /* find matching directory path */
4626 remain
= con
->physical
.rel_path
->used
- 1 - i
;
4627 if (con
->physical
.path
->used
- 1 <= remain
) { /*(should not happen)*/
4628 http_status_set_error(con
, 403); /* Forbidden */
4629 return HANDLER_FINISHED
;
4631 if (0 == memcmp(con
->physical
.rel_path
->ptr
+i
, /*(suffix match)*/
4632 con
->physical
.path
->ptr
+ con
->physical
.path
->used
-1-remain
,
4633 remain
)) { /*(suffix match)*/
4635 force_assert(2 <= dst_rel_path
->used
);
4637 buffer_copy_string_len(dst_path
, con
->physical
.path
->ptr
,
4638 con
->physical
.path
->used
- 1 - remain
);
4639 buffer_append_string_len(dst_path
,
4640 dst_rel_path
->ptr
+i
,
4641 dst_rel_path
->used
- 1 - i
);
4642 if (buffer_string_length(dst_path
) >= PATH_MAX
) {
4643 http_status_set_error(con
, 403); /* Forbidden */
4644 return HANDLER_FINISHED
;
4647 else { /*(not expected; some other module mucked with path or rel_path)*/
4648 /* unable to perform physical path remap here;
4649 * assume doc_root/rel_path and no remapping */
4651 force_assert(2 <= con
->physical
.doc_root
->used
);
4652 force_assert(2 <= dst_path
->used
);
4654 buffer_copy_buffer(dst_path
, con
->physical
.doc_root
);
4655 if (dst_path
->ptr
[dst_path
->used
-2] == '/')
4656 --dst_path
->used
; /* since dst_rel_path begins with '/' */
4657 buffer_append_string_buffer(dst_path
, dst_rel_path
);
4658 if (buffer_string_length(dst_rel_path
) >= PATH_MAX
) {
4659 http_status_set_error(con
, 403); /* Forbidden */
4660 return HANDLER_FINISHED
;
4664 if (con
->physical
.path
->used
<= dst_path
->used
4665 && 0 == memcmp(con
->physical
.path
->ptr
, dst_path
->ptr
,
4666 con
->physical
.path
->used
-1)
4667 && (con
->physical
.path
->ptr
[con
->physical
.path
->used
-2] == '/'
4668 || dst_path
->ptr
[con
->physical
.path
->used
-1] == '/'
4669 || dst_path
->ptr
[con
->physical
.path
->used
-1] == '\0')) {
4670 /* dst must not be nested under (or same as) src */
4671 http_status_set_error(con
, 403); /* Forbidden */
4672 return HANDLER_FINISHED
;
4676 if (-1 == lstat(con
->physical
.path
->ptr
, &st
)) {
4677 /* don't known about it yet, unlink will fail too */
4678 http_status_set_error(con
, (errno
== ENOENT
) ? 404 : 403);
4679 return HANDLER_FINISHED
;
4682 if (0 != webdav_if_match_or_unmodified_since(con
, &st
)) {
4683 http_status_set_error(con
, 412); /* Precondition Failed */
4684 return HANDLER_FINISHED
;
4687 if (S_ISDIR(st
.st_mode
)) {
4688 if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] != '/') {
4689 http_response_redirect_to_directory(pconf
->srv
, con
, 308);
4690 return HANDLER_FINISHED
; /* 308 Permanent Redirect */
4691 /* Alternatively, could append '/' to con->physical.path
4692 * and con->physical.rel_path, set Content-Location in
4693 * response headers, and continue to serve the request. */
4696 /* ensure Destination paths end with '/' since dst is a collection */
4698 force_assert(2 <= dst_rel_path
->used
);
4700 if (dst_rel_path
->ptr
[dst_rel_path
->used
- 2] != '/') {
4701 buffer_append_slash(dst_rel_path
);
4702 buffer_append_slash(dst_path
);
4705 /* check for lock on destination (after ensuring dst ends in '/') */
4706 if (!webdav_has_lock(con
, pconf
, dst_rel_path
))
4707 return HANDLER_FINISHED
; /* 423 Locked */
4709 const int depth
= webdav_parse_Depth(con
);
4711 http_status_set_error(con
, 400); /* Bad Request */
4712 return HANDLER_FINISHED
;
4715 if (con
->request
.http_method
== HTTP_METHOD_MOVE
) {
4716 http_status_set_error(con
, 400); /* Bad Request */
4717 return HANDLER_FINISHED
;
4719 /* optionally create collection, then copy properties */
4721 if (0 == lstat(dst_path
->ptr
, &st
)) {
4722 if (S_ISDIR(st
.st_mode
))
4723 status
= 204; /* No Content */
4724 else if (flags
& WEBDAV_FLAG_OVERWRITE
) {
4725 status
= webdav_mkdir(pconf
, &dst
, 1);
4726 if (0 == status
) status
= 204; /* No Content */
4729 status
= 412; /* Precondition Failed */
4731 else if (errno
== ENOENT
) {
4732 status
= webdav_mkdir(pconf
, &dst
,
4733 !!(flags
& WEBDAV_FLAG_OVERWRITE
));
4734 if (0 == status
) status
= 201; /* Created */
4737 status
= 403; /* Forbidden */
4739 http_status_set_fin(con
, status
);
4740 webdav_prop_copy_uri(pconf
,con
->physical
.rel_path
,dst
.rel_path
);
4743 http_status_set_error(con
, status
);
4744 return HANDLER_FINISHED
;
4747 /* ensure destination is not nested in source */
4748 if (dst_rel_path
->ptr
[dst_rel_path
->used
- 2] != '/') {
4749 buffer_append_slash(dst_rel_path
);
4750 buffer_append_slash(dst_path
);
4753 buffer
* const ms
= buffer_init(); /* multi-status */
4754 if (0 == webdav_copymove_dir(pconf
, &con
->physical
, &dst
, ms
, flags
)) {
4755 if (con
->request
.http_method
== HTTP_METHOD_MOVE
)
4756 webdav_lock_delete_uri_col(pconf
, con
->physical
.rel_path
);
4757 /*(requiring lock on destination requires MKCOL create dst first)
4758 *(if no lock support, return 200 OK unconditionally
4759 * instead of 200 OK or 201 Created; not fully RFC-conformant)*/
4760 http_status_set_fin(con
, 200); /* OK */
4763 /* Note: this does not destroy any locks if any error occurs,
4764 * which is not a problem if lock is only on the collection
4765 * being moved, but might need finer updates if there are
4766 * locks on internal elements that are successfully moved */
4767 webdav_xml_doc_multistatus(con
, pconf
, ms
); /* 207 Multi-status */
4770 /* invalidate stat cache of src if MOVE, whether or not successful */
4771 if (con
->request
.http_method
== HTTP_METHOD_MOVE
)
4772 stat_cache_delete_dir(pconf
->srv
,CONST_BUF_LEN(con
->physical
.path
));
4773 return HANDLER_FINISHED
;
4775 else if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] == '/') {
4776 http_status_set_error(con
, 403); /* Forbidden */
4777 return HANDLER_FINISHED
;
4780 /* check if client has lock for destination
4781 * Note: requiring a lock on non-collection means that destination
4782 * should always exist since the issuance of the lock creates the
4783 * resource, so client will always have to provide Overwrite: T
4784 * for direct operations on non-collections (files) */
4785 if (!webdav_has_lock(con
, pconf
, dst_rel_path
))
4786 return HANDLER_FINISHED
; /* 423 Locked */
4788 /* check if destination exists
4789 * (Destination should exist since lock is required,
4790 * and obtaining a lock will create the resource) */
4791 int rc
= lstat(dst_path
->ptr
, &st
);
4792 if (0 == rc
&& S_ISDIR(st
.st_mode
)) {
4794 * append basename to physical path
4795 * future: might set Content-Location if dst_path does not end '/'*/
4796 if (NULL
!= (sep
= strrchr(con
->physical
.path
->ptr
, '/'))) {
4798 force_assert(0 != dst_path
->used
);
4800 size_t len
= con
->physical
.path
->used
- 1
4801 - (sep
- con
->physical
.path
->ptr
);
4802 if (dst_path
->ptr
[dst_path
->used
-1] == '/') {
4803 ++sep
; /*(avoid double-slash in path)*/
4806 buffer_append_string_len(dst_path
, sep
, len
);
4807 buffer_append_string_len(dst_rel_path
, sep
, len
);
4808 if (buffer_string_length(dst_path
) >= PATH_MAX
) {
4809 http_status_set_error(con
, 403); /* Forbidden */
4810 return HANDLER_FINISHED
;
4812 rc
= lstat(dst_path
->ptr
, &st
);
4813 /* target (parent collection) already exists */
4814 http_status_set_fin(con
, 204); /* No Content */
4822 if (http_status_is_set(con
)) break;
4823 /* check that parent collection exists */
4824 if ((slash
= strrchr(dst_path
->ptr
, '/'))) {
4826 if (0 == lstat(dst_path
->ptr
, &st
) && S_ISDIR(st
.st_mode
)) {
4828 /* new entity will be created */
4829 if (!http_status_is_set(con
))
4830 http_status_set_fin(con
, 201); /* Created */
4837 http_status_set_error(con
, 409); /* Conflict */
4838 return HANDLER_FINISHED
;
4841 else if (!(flags
& WEBDAV_FLAG_OVERWRITE
)) {
4842 /* destination exists, but overwrite is not set */
4843 http_status_set_error(con
, 412); /* Precondition Failed */
4844 return HANDLER_FINISHED
;
4846 else if (S_ISDIR(st
.st_mode
)) {
4847 /* destination exists, but is a dir, not a file */
4848 http_status_set_error(con
, 409); /* Conflict */
4849 return HANDLER_FINISHED
;
4851 else { /* resource already exists */
4852 http_status_set_fin(con
, 204); /* No Content */
4855 rc
= webdav_copymove_file(pconf
, &con
->physical
, &dst
, &flags
);
4857 if (con
->request
.http_method
== HTTP_METHOD_MOVE
)
4858 webdav_lock_delete_uri(pconf
, con
->physical
.rel_path
);
4861 http_status_set_error(con
, rc
);
4863 return HANDLER_FINISHED
;
4869 mod_webdav_copymove (connection
* const con
, const plugin_config
* const pconf
)
4871 buffer
*dst_path
= buffer_init();
4872 buffer
*dst_rel_path
= buffer_init();
4873 handler_t rc
= mod_webdav_copymove_b(con
, pconf
, dst_path
, dst_rel_path
);
4874 buffer_free(dst_rel_path
);
4875 buffer_free(dst_path
);
4880 #ifdef USE_PROPPATCH
4882 mod_webdav_proppatch (connection
* const con
, const plugin_config
* const pconf
)
4885 http_header_response_set(con
, HTTP_HEADER_OTHER
,
4886 CONST_STR_LEN("Allow"),
4887 CONST_STR_LEN("GET, HEAD, PROPFIND, DELETE, "
4888 "MKCOL, PUT, MOVE, COPY"));
4889 http_status_set_error(con
, 405); /* Method Not Allowed */
4890 return HANDLER_FINISHED
;
4893 if (0 == con
->request
.content_length
) {
4894 http_status_set_error(con
, 400); /* Bad Request */
4895 return HANDLER_FINISHED
;
4898 if (con
->state
== CON_STATE_READ_POST
) {
4899 handler_t rc
= connection_handle_read_post_state(pconf
->srv
, con
);
4900 if (rc
!= HANDLER_GO_ON
) return rc
;
4904 if (0 != lstat(con
->physical
.path
->ptr
, &st
)) {
4905 http_status_set_error(con
, (errno
== ENOENT
) ? 404 : 403);
4906 return HANDLER_FINISHED
;
4909 if (0 != webdav_if_match_or_unmodified_since(con
, &st
)) {
4910 http_status_set_error(con
, 412); /* Precondition Failed */
4911 return HANDLER_FINISHED
;
4914 if (S_ISDIR(st
.st_mode
)) {
4915 if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] != '/') {
4916 /* set "Content-Location" instead of sending 308 redirect to dir */
4917 if (!http_response_redirect_to_directory(pconf
->srv
, con
, 0))
4918 return HANDLER_FINISHED
;
4919 buffer_append_string_len(con
->physical
.path
, CONST_STR_LEN("/"));
4920 buffer_append_string_len(con
->physical
.rel_path
,CONST_STR_LEN("/"));
4923 else if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] == '/') {
4924 http_status_set_error(con
, 403);
4925 return HANDLER_FINISHED
;
4928 xmlDocPtr
const xml
= webdav_parse_chunkqueue(con
, pconf
);
4930 http_status_set_error(con
, 400); /* Bad Request */
4931 return HANDLER_FINISHED
;
4934 const xmlNode
* const rootnode
= xmlDocGetRootElement(xml
);
4935 if (NULL
== rootnode
4936 || 0 != webdav_xmlstrcmp_fixed(rootnode
->name
, "propertyupdate")) {
4937 http_status_set_error(con
, 422); /* Unprocessable Entity */
4939 return HANDLER_FINISHED
;
4942 if (!webdav_db_transaction_begin_immediate(pconf
)) {
4943 http_status_set_error(con
, 500); /* Internal Server Error */
4945 return HANDLER_FINISHED
;
4948 /* NOTE: selectively providing multi-status response is NON-CONFORMANT
4949 * (specified in [RFC4918])
4950 * However, PROPPATCH is all-or-nothing, so client should be able to
4951 * unequivocably know that all items in PROPPATCH succeeded if it receives
4952 * 204 No Content, or that items that are not listed with a failure status
4953 * in a multi-status response have the status of 424 Failed Dependency,
4954 * without the server having to be explicit. */
4956 /* UPDATE request, we know 'set' and 'remove' */
4957 buffer
*ms
= NULL
; /*(multi-status)*/
4959 for (const xmlNode
*cmd
= rootnode
->children
; cmd
; cmd
= cmd
->next
) {
4960 if (!(update
= (0 == webdav_xmlstrcmp_fixed(cmd
->name
, "set")))) {
4961 if (0 != webdav_xmlstrcmp_fixed(cmd
->name
, "remove"))
4962 continue; /* skip; not "set" or "remove" */
4965 for (const xmlNode
*props
= cmd
->children
; props
; props
= props
->next
) {
4966 if (0 != webdav_xmlstrcmp_fixed(props
->name
, "prop"))
4969 const xmlNode
*prop
= props
->children
;
4970 /* libxml2 will keep those blank (whitespace only) nodes */
4971 while (NULL
!= prop
&& xmlIsBlankNode(prop
))
4975 if (prop
->ns
&& '\0' == *(char *)prop
->ns
->href
4976 && '\0' != *(char *)prop
->ns
->prefix
) {
4977 /* error: missing namespace for property */
4978 log_error(con
->errh
, __FILE__
, __LINE__
,
4979 "no namespace for: %s", prop
->name
);
4980 if (!ms
) ms
= buffer_init(); /* Unprocessable Entity */
4981 webdav_xml_propstat_status(ms
, "", (char *)prop
->name
, 422);
4985 /* XXX: ??? should blank namespace be normalized to "DAV:" ???
4986 * ??? should this also be done in propfind requests ??? */
4988 if (prop
->ns
&& 0 == strcmp((char *)prop
->ns
->href
, "DAV:")) {
4989 const size_t namelen
= strlen((char *)prop
->name
);
4990 const struct live_prop_list
*list
= protected_props
;
4991 while (0 != list
->len
4992 && (list
->len
!= namelen
4993 || 0 != memcmp(prop
->name
, list
->prop
, list
->len
)))
4995 if (NULL
!= list
->prop
) {
4996 /* error <DAV:cannot-modify-protected-property/> */
4997 if (!ms
) ms
= buffer_init();
4998 webdav_xml_propstat_protected(ms
, (char *)prop
->name
,
4999 namelen
, 403); /* Forbidden */
5005 if (!prop
->children
) continue;
5006 char * const propval
= prop
->children
5007 ? (char *)xmlNodeListGetString(xml
, prop
->children
, 0)
5009 webdav_prop_update(pconf
, con
->physical
.rel_path
,
5011 prop
->ns
? (char *)prop
->ns
->href
: "",
5012 propval
? propval
: "");
5016 webdav_prop_delete(pconf
, con
->physical
.rel_path
,
5018 prop
->ns
? (char *)prop
->ns
->href
: "");
5023 ? webdav_db_transaction_commit(pconf
)
5024 : webdav_db_transaction_rollback(pconf
)) {
5026 http_status_set_fin(con
, 204); /* No Content */
5027 else /* 207 Multi-status */
5028 webdav_xml_doc_multistatus_response(con
, pconf
, ms
);
5031 http_status_set_error(con
, 500); /* Internal Server Error */
5037 return HANDLER_FINISHED
;
5043 struct webdav_conflicting_lock_st
{
5044 webdav_lockdata
*lockdata
;
5050 webdav_conflicting_lock_cb (void * const vdata
,
5051 const webdav_lockdata
* const lockdata
)
5053 /* lock is not available if someone else has exclusive lock or if
5054 * client requested exclusive lock and others have shared locks */
5055 struct webdav_conflicting_lock_st
* const cbdata
=
5056 (struct webdav_conflicting_lock_st
*)vdata
;
5057 if (lockdata
->lockscope
->used
== sizeof("exclusive")
5058 || cbdata
->lockdata
->lockscope
->used
== sizeof("exclusive"))
5059 webdav_xml_href(cbdata
->b
, &lockdata
->lockroot
);
5064 mod_webdav_lock (connection
* const con
, const plugin_config
* const pconf
)
5067 * a mac wants to write
5069 * LOCK /dav/expire.txt HTTP/1.1\r\n
5070 * User-Agent: WebDAVFS/1.3 (01308000) Darwin/8.1.0 (Power Macintosh)\r\n
5073 * Timeout: Second-600\r\n
5074 * Content-Type: text/xml; charset=\"utf-8\"\r\n
5075 * Content-Length: 229\r\n
5076 * Connection: keep-alive\r\n
5077 * Host: 192.168.178.23:1025\r\n
5079 * <?xml version=\"1.0\" encoding=\"utf-8\"?>\n
5080 * <D:lockinfo xmlns:D=\"DAV:\">\n
5081 * <D:lockscope><D:exclusive/></D:lockscope>\n
5082 * <D:locktype><D:write/></D:locktype>\n
5084 * <D:href>http://www.apple.com/webdav_fs/</D:href>\n
5089 if (con
->request
.content_length
) {
5090 if (con
->state
== CON_STATE_READ_POST
) {
5091 handler_t rc
= connection_handle_read_post_state(pconf
->srv
, con
);
5092 if (rc
!= HANDLER_GO_ON
) return rc
;
5096 /* XXX: maybe add config switch to require that authentication occurred? */
5097 buffer owner
= { NULL
, 0, 0 };/*owner (not authenticated)(auth_user unset)*/
5098 data_string
* const authn_user
= (data_string
*)
5099 array_get_element_klen(con
->environment
, CONST_STR_LEN("REMOTE_USER"));
5101 /* future: make max timeout configurable (e.g. pconf->lock_timeout_max)
5103 * [RFC4918] 10.7 Timeout Request Header
5104 * The "Second" TimeType specifies the number of seconds that will elapse
5105 * between granting of the lock at the server, and the automatic removal
5106 * of the lock. The timeout value for TimeType "Second" MUST NOT be
5107 * greater than 2^32-1.
5110 webdav_lockdata lockdata
= {
5111 { NULL
, 0, 0 }, /* locktoken */
5112 { con
->physical
.rel_path
->ptr
,con
->physical
.rel_path
->used
,0},/*lockroot*/
5113 { NULL
, 0, 0 }, /* ownerinfo */
5114 (authn_user
? authn_user
->value
: &owner
), /* owner */
5115 NULL
, /* lockscope */
5116 NULL
, /* locktype */
5118 600 /* timeout (arbitrary default lock timeout: 10 minutes) */
5122 http_header_request_get(con
, HTTP_HEADER_OTHER
, CONST_STR_LEN("Timeout"));
5123 if (!buffer_is_empty(h
)) {
5124 /* loosely parse Timeout request header and ignore "infinity" timeout */
5125 /* future: might implement config param for upper limit for timeout */
5126 const char *p
= h
->ptr
;
5128 if ((*p
| 0x20) == 's'
5129 && 0 == strncasecmp(p
, CONST_STR_LEN("second-"))) {
5130 long t
= strtol(p
+sizeof("second-")-1, NULL
, 10);
5131 if (0 < t
&& t
< lockdata
.timeout
)
5132 lockdata
.timeout
= t
> 5 ? t
: 5;
5133 /*(arbitrary min timeout: 5 secs)*/
5134 else if (sizeof(long) != sizeof(int) && t
> INT32_MAX
)
5135 lockdata
.timeout
= INT32_MAX
;
5136 /* while UINT32_MAX is actual limit in RFC4918,
5137 * sqlite more easily supports int, though could be
5138 * changed to use int64 to for the timeout param.
5139 * The "limitation" between timeouts that are many
5140 * *years* long does not really matter in reality. */
5144 else if ((*p
| 0x20) == 'i'
5145 && 0 == strncasecmp(p
, CONST_STR_LEN("infinity"))) {
5146 lockdata
.timeout
= INT32_MAX
;
5150 while (*p
!= ',' && *p
!= '\0') ++p
;
5151 while (*p
== ' ' || *p
== '\t') ++p
;
5152 } while (*p
!= '\0');
5155 if (con
->request
.content_length
) {
5156 lockdata
.depth
= webdav_parse_Depth(con
);
5157 if (1 == lockdata
.depth
) {
5158 /* [RFC4918] 9.10.3 Depth and Locking
5159 * Values other than 0 or infinity MUST NOT be used
5160 * with the Depth header on a LOCK method.
5162 http_status_set_error(con
, 400); /* Bad Request */
5163 return HANDLER_FINISHED
;
5166 xmlDocPtr
const xml
= webdav_parse_chunkqueue(con
, pconf
);
5168 http_status_set_error(con
, 400); /* Bad Request */
5169 return HANDLER_FINISHED
;
5172 const xmlNode
* const rootnode
= xmlDocGetRootElement(xml
);
5173 if (NULL
== rootnode
5174 || 0 != webdav_xmlstrcmp_fixed(rootnode
->name
, "lockinfo")) {
5175 http_status_set_error(con
, 422); /* Unprocessable Entity */
5177 return HANDLER_FINISHED
;
5180 const xmlNode
*lockinfo
= rootnode
->children
;
5181 for (; lockinfo
; lockinfo
= lockinfo
->next
) {
5182 if (0 == webdav_xmlstrcmp_fixed(lockinfo
->name
, "lockscope")) {
5183 const xmlNode
*value
= lockinfo
->children
;
5184 for (; value
; value
= value
->next
) {
5185 if (0 == webdav_xmlstrcmp_fixed(value
->name
, "exclusive"))
5186 lockdata
.lockscope
=(const buffer
*)&lockscope_exclusive
;
5187 else if (0 == webdav_xmlstrcmp_fixed(value
->name
, "shared"))
5188 lockdata
.lockscope
=(const buffer
*)&lockscope_shared
;
5190 lockdata
.lockscope
=NULL
; /* trigger error below loop */
5195 else if (0 == webdav_xmlstrcmp_fixed(lockinfo
->name
, "locktype")) {
5196 const xmlNode
*value
= lockinfo
->children
;
5197 for (; value
; value
= value
->next
) {
5198 if (0 == webdav_xmlstrcmp_fixed(value
->name
, "write"))
5199 lockdata
.locktype
= (const buffer
*)&locktype_write
;
5201 lockdata
.locktype
= NULL
;/* trigger error below loop */
5206 else if (0 == webdav_xmlstrcmp_fixed(lockinfo
->name
, "owner")) {
5207 if (lockinfo
->children
)
5208 lockdata
.ownerinfo
.ptr
=
5209 (char *)xmlNodeListGetString(xml
, lockinfo
->children
, 0);
5210 if (lockdata
.ownerinfo
.ptr
)
5211 lockdata
.ownerinfo
.used
= strlen(lockdata
.ownerinfo
.ptr
)+1;
5215 do { /*(resources are cleaned up after code block)*/
5217 if (NULL
== lockdata
.lockscope
|| NULL
== lockdata
.locktype
) {
5218 /*(missing lockscope and locktype in lock request)*/
5219 http_status_set_error(con
, 422); /* Unprocessable Entity */
5220 break; /* clean up resources and return HANDLER_FINISHED */
5223 /* check lock prior to potentially creating new resource,
5224 * and prior to using entropy to create uuid */
5225 struct webdav_conflicting_lock_st cbdata
;
5226 cbdata
.lockdata
= &lockdata
;
5227 cbdata
.b
= buffer_init();
5228 webdav_lock_activelocks(pconf
, &lockdata
.lockroot
,
5229 (0 == lockdata
.depth
? 1 : -1),
5230 webdav_conflicting_lock_cb
, &cbdata
);
5231 if (0 != cbdata
.b
->used
) {
5233 webdav_xml_doc_error_no_conflicting_lock(con
, cbdata
.b
);
5234 buffer_free(cbdata
.b
);
5235 break; /* clean up resources and return HANDLER_FINISHED */
5237 buffer_free(cbdata
.b
);
5241 if (0 != lstat(con
->physical
.path
->ptr
, &st
)) {
5242 /* [RFC4918] 7.3 Write Locks and Unmapped URLs
5243 * A successful lock request to an unmapped URL MUST result in
5244 * the creation of a locked (non-collection) resource with empty
5247 * The response MUST indicate that a resource was created, by
5248 * use of the "201 Created" response code (a LOCK request to an
5249 * existing resource instead will result in 200 OK).
5250 * [RFC4918] 9.10.4 Locking Unmapped URLs
5251 * A successful LOCK method MUST result in the creation of an
5252 * empty resource that is locked (and that is not a collection)
5253 * when a resource did not previously exist at that URL. Later on,
5254 * the lock may go away but the empty resource remains. Empty
5255 * resources MUST then appear in PROPFIND responses including that
5256 * URL in the response scope. A server MUST respond successfully
5257 * to a GET request to an empty resource, either by using a 204
5258 * No Content response, or by using 200 OK with a Content-Length
5259 * header indicating zero length
5261 * unmapped resource; create empty file
5262 * (open() should fail if path ends in '/', but does not on some OS.
5263 * This is desired behavior since collection should be created
5264 * with MKCOL, and not via LOCK on an unmapped resource) */
5267 && con
->physical
.path
->ptr
[con
->physical
.path
->used
-2] != '/')
5268 ? fdevent_open_cloexec(con
->physical
.path
->ptr
, 0,
5269 O_WRONLY
| O_CREAT
| O_EXCL
| O_TRUNC
,
5273 /*(skip sending etag if fstat() error; not expected)*/
5274 if (0 != fstat(fd
, &st
)) con
->etag_flags
= 0;
5278 else if (errno
!= EEXIST
) {
5279 http_status_set_error(con
, 403); /* Forbidden */
5280 break; /* clean up resources and return HANDLER_FINISHED */
5282 else if (0 != lstat(con
->physical
.path
->ptr
, &st
)) {
5283 http_status_set_error(con
, 403); /* Forbidden */
5284 break; /* clean up resources and return HANDLER_FINISHED */
5286 lockdata
.depth
= 0; /* force Depth: 0 on non-collections */
5290 if (0 != webdav_if_match_or_unmodified_since(con
, &st
)) {
5291 http_status_set_error(con
, 412); /* Precondition Failed */
5292 break; /* clean up resources and return HANDLER_FINISHED */
5298 else if (S_ISDIR(st
.st_mode
)) {
5299 if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] != '/') {
5300 /* 308 Permanent Redirect */
5301 http_response_redirect_to_directory(pconf
->srv
, con
, 308);
5302 break; /* clean up resources and return HANDLER_FINISHED */
5303 /* Alternatively, could append '/' to con->physical.path
5304 * and con->physical.rel_path, set Content-Location in
5305 * response headers, and continue to serve the request */
5308 else if (con
->physical
.path
->ptr
[con
->physical
.path
->used
- 2] == '/') {
5309 http_status_set_error(con
, 403); /* Forbidden */
5310 break; /* clean up resources and return HANDLER_FINISHED */
5312 else if (0 != lockdata
.depth
)
5313 lockdata
.depth
= 0; /* force Depth: 0 on non-collections */
5316 * (uuid_unparse() output is 36 chars + '\0') */
5318 char lockstr
[sizeof("<urn:uuid:>") + 36] = "<urn:uuid:";
5319 lockdata
.locktoken
.ptr
= lockstr
+1; /*(without surrounding <>)*/
5320 lockdata
.locktoken
.used
= sizeof(lockstr
)-2;/*(without surrounding <>)*/
5322 uuid_unparse(id
, lockstr
+sizeof("<urn:uuid:")-1);
5324 /* XXX: consider fix TOC-TOU race condition by starting transaction
5325 * and re-running webdav_lock_activelocks() check before running
5326 * webdav_lock_acquire() (but both routines would need to be modified
5327 * to defer calling sqlite3_reset(stmt) to be part of transaction) */
5328 if (webdav_lock_acquire(pconf
, &lockdata
)) {
5329 lockstr
[sizeof(lockstr
)-2] = '>';
5330 http_header_response_set(con
, HTTP_HEADER_OTHER
,
5331 CONST_STR_LEN("Lock-Token"),
5332 lockstr
, sizeof(lockstr
)-1);
5333 webdav_xml_doc_lock_acquired(con
, pconf
, &lockdata
);
5334 if (0 != con
->etag_flags
&& !S_ISDIR(st
.st_mode
))
5335 webdav_response_etag(pconf
->srv
, con
, &st
);
5336 http_status_set_fin(con
, created
? 201 : 200); /* Created | OK */
5338 else /*(database error obtaining lock)*/
5339 http_status_set_error(con
, 500); /* Internal Server Error */
5341 } while (0); /*(resources are cleaned up after code block)*/
5343 xmlFree(lockdata
.ownerinfo
.ptr
);
5345 return HANDLER_FINISHED
;
5348 h
= http_header_request_get(con
,HTTP_HEADER_OTHER
,CONST_STR_LEN("If"));
5350 || h
->used
< 6 || h
->ptr
[1] != '<' || h
->ptr
[h
->used
-3] != '>') {
5351 /*(rejects value with trailing LWS, even though RFC-permitted)*/
5352 http_status_set_error(con
, 400); /* Bad Request */
5353 return HANDLER_FINISHED
;
5355 /* remove (< >) around token */
5356 lockdata
.locktoken
.ptr
= h
->ptr
+2;
5357 lockdata
.locktoken
.used
= h
->used
-4;
5358 /*(future: fill in from database, though exclusive write lock is the
5359 * only lock supported at the moment)*/
5360 lockdata
.lockscope
= (const buffer
*)&lockscope_exclusive
;
5361 lockdata
.locktype
= (const buffer
*)&locktype_write
;
5364 if (webdav_lock_refresh(pconf
, &lockdata
)) {
5365 webdav_xml_doc_lock_acquired(con
, pconf
, &lockdata
);
5366 http_status_set_fin(con
, 200); /* OK */
5369 http_status_set_error(con
, 412); /* Precondition Failed */
5371 return HANDLER_FINISHED
;
5379 mod_webdav_unlock (connection
* const con
, const plugin_config
* const pconf
)
5381 const buffer
* const h
=
5382 http_header_request_get(con
, HTTP_HEADER_OTHER
,
5383 CONST_STR_LEN("Lock-Token"));
5385 || h
->used
< 4 || h
->ptr
[0] != '<' || h
->ptr
[h
->used
-2] != '>') {
5386 /*(rejects value with trailing LWS, even though RFC-permitted)*/
5387 http_status_set_error(con
, 400); /* Bad Request */
5388 return HANDLER_FINISHED
;
5391 buffer owner
= { NULL
, 0, 0 };/*owner (not authenticated)(auth_user unset)*/
5392 data_string
* const authn_user
= (data_string
*)
5393 array_get_element_klen(con
->environment
, CONST_STR_LEN("REMOTE_USER"));
5395 webdav_lockdata lockdata
= {
5396 { h
->ptr
+1, h
->used
-2, 0 }, /* locktoken (remove < > around token) */
5397 { con
->physical
.rel_path
->ptr
,con
->physical
.rel_path
->used
,0},/*lockroot*/
5398 { NULL
, 0, 0 }, /* ownerinfo (unused for unlock) */
5399 (authn_user
? authn_user
->value
: &owner
), /* owner */
5400 NULL
, /* lockscope (unused for unlock) */
5401 NULL
, /* locktype (unused for unlock) */
5402 0, /* depth (unused for unlock) */
5403 0 /* timeout (unused for unlock) */
5406 /* check URI (lockroot) and depth in scope for locktoken and authorized */
5407 switch (webdav_lock_match(pconf
, &lockdata
)) {
5409 if (webdav_lock_release(pconf
, &lockdata
)) {
5410 http_status_set_fin(con
, 204); /* No Content */
5411 return HANDLER_FINISHED
;
5415 case -1: /* lock does not exist */
5416 case -2: /* URI not in scope of locktoken and depth */
5418 webdav_xml_doc_error_lock_token_matches_request_uri(con
);
5419 return HANDLER_FINISHED
;
5420 case -3: /* not owner/not authorized to remove lock */
5421 http_status_set_error(con
, 403); /* Forbidden */
5422 return HANDLER_FINISHED
;
5428 SUBREQUEST_FUNC(mod_webdav_subrequest_handler
)
5430 const plugin_config
* const pconf
=
5431 (plugin_config
*)con
->plugin_ctx
[((plugin_data
*)p_d
)->id
];
5432 if (NULL
== pconf
) return HANDLER_GO_ON
; /*(should not happen)*/
5435 switch (con
->request
.http_method
) {
5436 case HTTP_METHOD_PROPFIND
:
5437 return mod_webdav_propfind(con
, pconf
);
5438 case HTTP_METHOD_MKCOL
:
5439 return mod_webdav_mkcol(con
, pconf
);
5440 case HTTP_METHOD_DELETE
:
5441 return mod_webdav_delete(con
, pconf
);
5442 case HTTP_METHOD_PUT
:
5443 return mod_webdav_put(con
, pconf
);
5444 case HTTP_METHOD_MOVE
:
5445 case HTTP_METHOD_COPY
:
5446 return mod_webdav_copymove(con
, pconf
);
5447 #ifdef USE_PROPPATCH
5448 case HTTP_METHOD_PROPPATCH
:
5449 return mod_webdav_proppatch(con
, pconf
);
5452 case HTTP_METHOD_LOCK
:
5453 return mod_webdav_lock(con
, pconf
);
5454 case HTTP_METHOD_UNLOCK
:
5455 return mod_webdav_unlock(con
, pconf
);
5458 http_status_set_error(con
, 501); /* Not Implemented */
5459 return HANDLER_FINISHED
;
5464 PHYSICALPATH_FUNC(mod_webdav_physical_handler
)
5466 /* physical path is set up */
5467 /*assert(0 != con->physical.path->used);*/
5469 force_assert(2 <= con
->physical
.path
->used
);
5472 int check_readonly
= 0;
5473 int check_lock_src
= 0;
5474 int reject_reqbody
= 0;
5476 /* check for WebDAV request methods handled by this module */
5477 switch (con
->request
.http_method
) {
5478 case HTTP_METHOD_GET
:
5479 case HTTP_METHOD_HEAD
:
5480 case HTTP_METHOD_POST
:
5482 return HANDLER_GO_ON
;
5483 case HTTP_METHOD_PROPFIND
:
5484 case HTTP_METHOD_LOCK
:
5486 case HTTP_METHOD_UNLOCK
:
5489 case HTTP_METHOD_DELETE
:
5490 case HTTP_METHOD_MOVE
:
5491 reject_reqbody
= 1; /*(fall through)*/ __attribute_fallthrough__
5492 case HTTP_METHOD_PROPPATCH
:
5493 case HTTP_METHOD_PUT
:
5494 check_readonly
= check_lock_src
= 1;
5496 case HTTP_METHOD_COPY
:
5497 case HTTP_METHOD_MKCOL
:
5498 check_readonly
= reject_reqbody
= 1;
5502 plugin_config pconf
;
5503 mod_webdav_patch_connection(srv
, con
, (plugin_data
*)p_d
, &pconf
);
5504 if (!pconf
.enabled
) return HANDLER_GO_ON
;
5506 if (check_readonly
&& pconf
.is_readonly
) {
5507 http_status_set_error(con
, 403); /* Forbidden */
5508 return HANDLER_FINISHED
;
5511 if (reject_reqbody
&& con
->request
.content_length
) {
5512 /* [RFC4918] 8.4 Required Bodies in Requests
5513 * Servers MUST examine all requests for a body, even when a
5514 * body was not expected. In cases where a request body is
5515 * present but would be ignored by a server, the server MUST
5516 * reject the request with 415 (Unsupported Media Type).
5518 http_status_set_error(con
, 415); /* Unsupported Media Type */
5519 return HANDLER_FINISHED
;
5522 if (check_lock_src
&& !webdav_has_lock(con
, &pconf
, con
->physical
.rel_path
))
5523 return HANDLER_FINISHED
; /* 423 Locked */
5525 /* initial setup for methods */
5526 switch (con
->request
.http_method
) {
5527 case HTTP_METHOD_PUT
:
5528 if (mod_webdav_put_prep(con
, &pconf
) == HANDLER_FINISHED
)
5529 return HANDLER_FINISHED
;
5535 con
->mode
= ((plugin_data
*)p_d
)->id
;
5536 con
->conf
.stream_request_body
= 0;
5537 con
->plugin_ctx
[((plugin_data
*)p_d
)->id
] = &pconf
;
5538 const handler_t rc
=
5539 mod_webdav_subrequest_handler(srv
, con
, p_d
); /*p->handle_subrequest()*/
5540 if (rc
== HANDLER_FINISHED
|| rc
== HANDLER_ERROR
)
5541 con
->plugin_ctx
[((plugin_data
*)p_d
)->id
] = NULL
;
5542 else { /* e.g. HANDLER_WAIT_FOR_RD */
5543 plugin_config
* const save_pconf
=
5544 (plugin_config
*)malloc(sizeof(pconf
));
5545 force_assert(save_pconf
);
5546 memcpy(save_pconf
, &pconf
, sizeof(pconf
));
5547 con
->plugin_ctx
[((plugin_data
*)p_d
)->id
] = save_pconf
;
5553 CONNECTION_FUNC(mod_webdav_handle_reset
) {
5554 /* free plugin_config if allocated and saved to per-request storage */
5555 void ** const restrict dptr
= &con
->plugin_ctx
[((plugin_data
*)p_d
)->id
];
5559 chunkqueue_set_tempdirs(con
->request_content_queue
, /* reset sz */
5560 con
->request_content_queue
->tempdirs
, 0);
5563 return HANDLER_GO_ON
;