[mod_webdav] create file w/ LOCK request if ENOENT
[lighttpd.git] / src / mod_webdav.c
blob066903d868a96631014768576cd3f5f10001f2c3
1 #include "first.h"
3 #include "base.h"
4 #include "log.h"
5 #include "buffer.h"
6 #include "response.h"
7 #include "connections.h"
9 #include "plugin.h"
11 #include "stream.h"
12 #include "stat_cache.h"
14 #include "sys-mmap.h"
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <ctype.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <assert.h>
26 #include <unistd.h>
27 #include <dirent.h>
29 #if defined(HAVE_LIBXML_H) && defined(HAVE_SQLITE3_H)
30 #define USE_PROPPATCH
31 #include <libxml/tree.h>
32 #include <libxml/parser.h>
34 #include <sqlite3.h>
35 #endif
37 #if defined(HAVE_LIBXML_H) && defined(HAVE_SQLITE3_H) && defined(HAVE_UUID_UUID_H)
38 #define USE_LOCKS
39 #include <uuid/uuid.h>
40 #endif
42 /**
43 * this is a webdav for a lighttpd plugin
45 * at least a very basic one.
46 * - for now it is read-only and we only support PROPFIND
50 #define WEBDAV_FILE_MODE S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
51 #define WEBDAV_DIR_MODE S_IRWXU | S_IRWXG | S_IRWXO
53 /* plugin config for all request/connections */
55 typedef struct {
56 unsigned short enabled;
57 unsigned short is_readonly;
58 unsigned short log_xml;
60 buffer *sqlite_db_name;
61 #ifdef USE_PROPPATCH
62 sqlite3 *sql;
63 sqlite3_stmt *stmt_update_prop;
64 sqlite3_stmt *stmt_delete_prop;
65 sqlite3_stmt *stmt_select_prop;
66 sqlite3_stmt *stmt_select_propnames;
68 sqlite3_stmt *stmt_delete_uri;
69 sqlite3_stmt *stmt_move_uri;
70 sqlite3_stmt *stmt_copy_uri;
72 sqlite3_stmt *stmt_remove_lock;
73 sqlite3_stmt *stmt_create_lock;
74 sqlite3_stmt *stmt_read_lock;
75 sqlite3_stmt *stmt_read_lock_by_uri;
76 sqlite3_stmt *stmt_refresh_lock;
77 #endif
78 } plugin_config;
80 typedef struct {
81 PLUGIN_DATA;
83 buffer *tmp_buf;
84 request_uri uri;
85 physical physical;
87 plugin_config **config_storage;
89 plugin_config conf;
90 } plugin_data;
92 /* init the plugin data */
93 INIT_FUNC(mod_webdav_init) {
94 plugin_data *p;
96 p = calloc(1, sizeof(*p));
98 p->tmp_buf = buffer_init();
100 p->uri.scheme = buffer_init();
101 p->uri.path_raw = buffer_init();
102 p->uri.path = buffer_init();
103 p->uri.authority = buffer_init();
105 p->physical.path = buffer_init();
106 p->physical.rel_path = buffer_init();
107 p->physical.doc_root = buffer_init();
108 p->physical.basedir = buffer_init();
110 return p;
113 /* detroy the plugin data */
114 FREE_FUNC(mod_webdav_free) {
115 plugin_data *p = p_d;
117 UNUSED(srv);
119 if (!p) return HANDLER_GO_ON;
121 if (p->config_storage) {
122 size_t i;
123 for (i = 0; i < srv->config_context->used; i++) {
124 plugin_config *s = p->config_storage[i];
126 if (NULL == s) continue;
128 buffer_free(s->sqlite_db_name);
129 #ifdef USE_PROPPATCH
130 if (s->sql) {
131 sqlite3_finalize(s->stmt_delete_prop);
132 sqlite3_finalize(s->stmt_delete_uri);
133 sqlite3_finalize(s->stmt_copy_uri);
134 sqlite3_finalize(s->stmt_move_uri);
135 sqlite3_finalize(s->stmt_update_prop);
136 sqlite3_finalize(s->stmt_select_prop);
137 sqlite3_finalize(s->stmt_select_propnames);
139 sqlite3_finalize(s->stmt_read_lock);
140 sqlite3_finalize(s->stmt_read_lock_by_uri);
141 sqlite3_finalize(s->stmt_create_lock);
142 sqlite3_finalize(s->stmt_remove_lock);
143 sqlite3_finalize(s->stmt_refresh_lock);
144 sqlite3_close(s->sql);
146 #endif
147 free(s);
149 free(p->config_storage);
152 buffer_free(p->uri.scheme);
153 buffer_free(p->uri.path_raw);
154 buffer_free(p->uri.path);
155 buffer_free(p->uri.authority);
157 buffer_free(p->physical.path);
158 buffer_free(p->physical.rel_path);
159 buffer_free(p->physical.doc_root);
160 buffer_free(p->physical.basedir);
162 buffer_free(p->tmp_buf);
164 free(p);
166 return HANDLER_GO_ON;
169 /* handle plugin config and check values */
171 SETDEFAULTS_FUNC(mod_webdav_set_defaults) {
172 plugin_data *p = p_d;
173 size_t i = 0;
175 config_values_t cv[] = {
176 { "webdav.activate", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
177 { "webdav.is-readonly", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
178 { "webdav.sqlite-db-name", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
179 { "webdav.log-xml", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
180 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
183 if (!p) return HANDLER_ERROR;
185 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
187 for (i = 0; i < srv->config_context->used; i++) {
188 data_config const* config = (data_config const*)srv->config_context->data[i];
189 plugin_config *s;
191 s = calloc(1, sizeof(plugin_config));
192 s->sqlite_db_name = buffer_init();
194 cv[0].destination = &(s->enabled);
195 cv[1].destination = &(s->is_readonly);
196 cv[2].destination = s->sqlite_db_name;
197 cv[3].destination = &(s->log_xml);
199 p->config_storage[i] = s;
201 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
202 return HANDLER_ERROR;
205 if (!buffer_string_is_empty(s->sqlite_db_name)) {
206 #ifdef USE_PROPPATCH
207 const char *next_stmt;
208 char *err;
210 if (SQLITE_OK != sqlite3_open(s->sqlite_db_name->ptr, &(s->sql))) {
211 log_error_write(srv, __FILE__, __LINE__, "sbs", "sqlite3_open failed for",
212 s->sqlite_db_name,
213 sqlite3_errmsg(s->sql));
214 return HANDLER_ERROR;
217 if (SQLITE_OK != sqlite3_exec(s->sql,
218 "CREATE TABLE IF NOT EXISTS properties ("
219 " resource TEXT NOT NULL,"
220 " prop TEXT NOT NULL,"
221 " ns TEXT NOT NULL,"
222 " value TEXT NOT NULL,"
223 " PRIMARY KEY(resource, prop, ns))",
224 NULL, NULL, &err)) {
226 if (0 != strcmp(err, "table properties already exists")) {
227 log_error_write(srv, __FILE__, __LINE__, "ss", "can't open transaction:", err);
228 sqlite3_free(err);
230 return HANDLER_ERROR;
232 sqlite3_free(err);
235 if (SQLITE_OK != sqlite3_exec(s->sql,
236 "CREATE TABLE IF NOT EXISTS locks ("
237 " locktoken TEXT NOT NULL,"
238 " resource TEXT NOT NULL,"
239 " lockscope TEXT NOT NULL,"
240 " locktype TEXT NOT NULL,"
241 " owner TEXT NOT NULL,"
242 " depth INT NOT NULL,"
243 " timeout TIMESTAMP NOT NULL,"
244 " PRIMARY KEY(locktoken))",
245 NULL, NULL, &err)) {
247 if (0 != strcmp(err, "table locks already exists")) {
248 log_error_write(srv, __FILE__, __LINE__, "ss", "can't open transaction:", err);
249 sqlite3_free(err);
251 return HANDLER_ERROR;
253 sqlite3_free(err);
256 if (SQLITE_OK != sqlite3_prepare(s->sql,
257 CONST_STR_LEN("SELECT value FROM properties WHERE resource = ? AND prop = ? AND ns = ?"),
258 &(s->stmt_select_prop), &next_stmt)) {
259 /* prepare failed */
261 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed:", sqlite3_errmsg(s->sql));
262 return HANDLER_ERROR;
265 if (SQLITE_OK != sqlite3_prepare(s->sql,
266 CONST_STR_LEN("SELECT ns, prop FROM properties WHERE resource = ?"),
267 &(s->stmt_select_propnames), &next_stmt)) {
268 /* prepare failed */
270 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed:", sqlite3_errmsg(s->sql));
271 return HANDLER_ERROR;
275 if (SQLITE_OK != sqlite3_prepare(s->sql,
276 CONST_STR_LEN("REPLACE INTO properties (resource, prop, ns, value) VALUES (?, ?, ?, ?)"),
277 &(s->stmt_update_prop), &next_stmt)) {
278 /* prepare failed */
280 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed:", sqlite3_errmsg(s->sql));
281 return HANDLER_ERROR;
284 if (SQLITE_OK != sqlite3_prepare(s->sql,
285 CONST_STR_LEN("DELETE FROM properties WHERE resource = ? AND prop = ? AND ns = ?"),
286 &(s->stmt_delete_prop), &next_stmt)) {
287 /* prepare failed */
288 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
290 return HANDLER_ERROR;
293 if (SQLITE_OK != sqlite3_prepare(s->sql,
294 CONST_STR_LEN("DELETE FROM properties WHERE resource = ?"),
295 &(s->stmt_delete_uri), &next_stmt)) {
296 /* prepare failed */
297 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
299 return HANDLER_ERROR;
302 if (SQLITE_OK != sqlite3_prepare(s->sql,
303 CONST_STR_LEN("INSERT INTO properties SELECT ?, prop, ns, value FROM properties WHERE resource = ?"),
304 &(s->stmt_copy_uri), &next_stmt)) {
305 /* prepare failed */
306 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
308 return HANDLER_ERROR;
311 if (SQLITE_OK != sqlite3_prepare(s->sql,
312 CONST_STR_LEN("UPDATE OR REPLACE properties SET resource = ? WHERE resource = ?"),
313 &(s->stmt_move_uri), &next_stmt)) {
314 /* prepare failed */
315 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
317 return HANDLER_ERROR;
320 /* LOCKS */
322 if (SQLITE_OK != sqlite3_prepare(s->sql,
323 CONST_STR_LEN("INSERT INTO locks (locktoken, resource, lockscope, locktype, owner, depth, timeout) VALUES (?,?,?,?,?,?, CURRENT_TIME + 600)"),
324 &(s->stmt_create_lock), &next_stmt)) {
325 /* prepare failed */
326 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
328 return HANDLER_ERROR;
331 if (SQLITE_OK != sqlite3_prepare(s->sql,
332 CONST_STR_LEN("DELETE FROM locks WHERE locktoken = ?"),
333 &(s->stmt_remove_lock), &next_stmt)) {
334 /* prepare failed */
335 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
337 return HANDLER_ERROR;
340 if (SQLITE_OK != sqlite3_prepare(s->sql,
341 CONST_STR_LEN("SELECT locktoken, resource, lockscope, locktype, owner, depth, timeout FROM locks WHERE locktoken = ?"),
342 &(s->stmt_read_lock), &next_stmt)) {
343 /* prepare failed */
344 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
346 return HANDLER_ERROR;
349 if (SQLITE_OK != sqlite3_prepare(s->sql,
350 CONST_STR_LEN("SELECT locktoken, resource, lockscope, locktype, owner, depth, timeout FROM locks WHERE resource = ?"),
351 &(s->stmt_read_lock_by_uri), &next_stmt)) {
352 /* prepare failed */
353 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
355 return HANDLER_ERROR;
358 if (SQLITE_OK != sqlite3_prepare(s->sql,
359 CONST_STR_LEN("UPDATE locks SET timeout = CURRENT_TIME + 600 WHERE locktoken = ?"),
360 &(s->stmt_refresh_lock), &next_stmt)) {
361 /* prepare failed */
362 log_error_write(srv, __FILE__, __LINE__, "ss", "sqlite3_prepare failed", sqlite3_errmsg(s->sql));
364 return HANDLER_ERROR;
368 #else
369 log_error_write(srv, __FILE__, __LINE__, "s", "Sorry, no sqlite3 and libxml2 support include, compile with --with-webdav-props");
370 return HANDLER_ERROR;
371 #endif
375 return HANDLER_GO_ON;
378 #define PATCH_OPTION(x) \
379 p->conf.x = s->x;
380 static int mod_webdav_patch_connection(server *srv, connection *con, plugin_data *p) {
381 size_t i, j;
382 plugin_config *s = p->config_storage[0];
384 PATCH_OPTION(enabled);
385 PATCH_OPTION(is_readonly);
386 PATCH_OPTION(log_xml);
388 #ifdef USE_PROPPATCH
389 PATCH_OPTION(sql);
390 PATCH_OPTION(stmt_update_prop);
391 PATCH_OPTION(stmt_delete_prop);
392 PATCH_OPTION(stmt_select_prop);
393 PATCH_OPTION(stmt_select_propnames);
395 PATCH_OPTION(stmt_delete_uri);
396 PATCH_OPTION(stmt_move_uri);
397 PATCH_OPTION(stmt_copy_uri);
399 PATCH_OPTION(stmt_remove_lock);
400 PATCH_OPTION(stmt_refresh_lock);
401 PATCH_OPTION(stmt_create_lock);
402 PATCH_OPTION(stmt_read_lock);
403 PATCH_OPTION(stmt_read_lock_by_uri);
404 #endif
405 /* skip the first, the global context */
406 for (i = 1; i < srv->config_context->used; i++) {
407 data_config *dc = (data_config *)srv->config_context->data[i];
408 s = p->config_storage[i];
410 /* condition didn't match */
411 if (!config_check_cond(srv, con, dc)) continue;
413 /* merge config */
414 for (j = 0; j < dc->value->used; j++) {
415 data_unset *du = dc->value->data[j];
417 if (buffer_is_equal_string(du->key, CONST_STR_LEN("webdav.activate"))) {
418 PATCH_OPTION(enabled);
419 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("webdav.is-readonly"))) {
420 PATCH_OPTION(is_readonly);
421 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("webdav.log-xml"))) {
422 PATCH_OPTION(log_xml);
423 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("webdav.sqlite-db-name"))) {
424 #ifdef USE_PROPPATCH
425 PATCH_OPTION(sql);
426 PATCH_OPTION(stmt_update_prop);
427 PATCH_OPTION(stmt_delete_prop);
428 PATCH_OPTION(stmt_select_prop);
429 PATCH_OPTION(stmt_select_propnames);
431 PATCH_OPTION(stmt_delete_uri);
432 PATCH_OPTION(stmt_move_uri);
433 PATCH_OPTION(stmt_copy_uri);
435 PATCH_OPTION(stmt_remove_lock);
436 PATCH_OPTION(stmt_refresh_lock);
437 PATCH_OPTION(stmt_create_lock);
438 PATCH_OPTION(stmt_read_lock);
439 PATCH_OPTION(stmt_read_lock_by_uri);
440 #endif
445 return 0;
448 URIHANDLER_FUNC(mod_webdav_uri_handler) {
449 plugin_data *p = p_d;
451 UNUSED(srv);
453 if (buffer_is_empty(con->uri.path)) return HANDLER_GO_ON;
455 mod_webdav_patch_connection(srv, con, p);
457 if (!p->conf.enabled) return HANDLER_GO_ON;
459 switch (con->request.http_method) {
460 case HTTP_METHOD_OPTIONS:
461 /* we fake a little bit but it makes MS W2k happy and it let's us mount the volume */
462 response_header_overwrite(srv, con, CONST_STR_LEN("DAV"), CONST_STR_LEN("1,2"));
463 response_header_overwrite(srv, con, CONST_STR_LEN("MS-Author-Via"), CONST_STR_LEN("DAV"));
465 if (p->conf.is_readonly) {
466 response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("PROPFIND"));
467 } else {
468 response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("PROPFIND, DELETE, MKCOL, PUT, MOVE, COPY, PROPPATCH, LOCK, UNLOCK"));
470 break;
471 default:
472 break;
475 /* not found */
476 return HANDLER_GO_ON;
478 static int webdav_gen_prop_tag(server *srv, connection *con,
479 char *prop_name,
480 char *prop_ns,
481 char *value,
482 buffer *b) {
484 UNUSED(srv);
485 UNUSED(con);
487 if (value) {
488 buffer_append_string_len(b,CONST_STR_LEN("<"));
489 buffer_append_string(b, prop_name);
490 buffer_append_string_len(b, CONST_STR_LEN(" xmlns=\""));
491 buffer_append_string(b, prop_ns);
492 buffer_append_string_len(b, CONST_STR_LEN("\">"));
494 buffer_append_string(b, value);
496 buffer_append_string_len(b,CONST_STR_LEN("</"));
497 buffer_append_string(b, prop_name);
498 buffer_append_string_len(b, CONST_STR_LEN(">"));
499 } else {
500 buffer_append_string_len(b,CONST_STR_LEN("<"));
501 buffer_append_string(b, prop_name);
502 buffer_append_string_len(b, CONST_STR_LEN(" xmlns=\""));
503 buffer_append_string(b, prop_ns);
504 buffer_append_string_len(b, CONST_STR_LEN("\"/>"));
507 return 0;
511 static int webdav_gen_response_status_tag(server *srv, connection *con, physical *dst, int status, buffer *b) {
512 UNUSED(srv);
514 buffer_append_string_len(b,CONST_STR_LEN("<D:response xmlns:ns0=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\">\n"));
516 buffer_append_string_len(b,CONST_STR_LEN("<D:href>\n"));
517 buffer_append_string_buffer(b, dst->rel_path);
518 buffer_append_string_len(b,CONST_STR_LEN("</D:href>\n"));
519 buffer_append_string_len(b,CONST_STR_LEN("<D:status>\n"));
521 if (con->request.http_version == HTTP_VERSION_1_1) {
522 buffer_copy_string_len(b, CONST_STR_LEN("HTTP/1.1 "));
523 } else {
524 buffer_copy_string_len(b, CONST_STR_LEN("HTTP/1.0 "));
526 buffer_append_int(b, status);
527 buffer_append_string_len(b, CONST_STR_LEN(" "));
528 buffer_append_string(b, get_http_status_name(status));
530 buffer_append_string_len(b,CONST_STR_LEN("</D:status>\n"));
531 buffer_append_string_len(b,CONST_STR_LEN("</D:response>\n"));
533 return 0;
536 static int webdav_delete_file(server *srv, connection *con, plugin_data *p, physical *dst, buffer *b) {
537 int status = 0;
539 /* try to unlink it */
540 if (-1 == unlink(dst->path->ptr)) {
541 switch(errno) {
542 case EACCES:
543 case EPERM:
544 /* 403 */
545 status = 403;
546 break;
547 default:
548 status = 501;
549 break;
551 webdav_gen_response_status_tag(srv, con, dst, status, b);
552 } else {
553 #ifdef USE_PROPPATCH
554 sqlite3_stmt *stmt = p->conf.stmt_delete_uri;
556 if (!stmt) {
557 status = 403;
558 webdav_gen_response_status_tag(srv, con, dst, status, b);
559 } else {
560 sqlite3_reset(stmt);
562 /* bind the values to the insert */
564 sqlite3_bind_text(stmt, 1,
565 CONST_BUF_LEN(dst->rel_path),
566 SQLITE_TRANSIENT);
568 if (SQLITE_DONE != sqlite3_step(stmt)) {
569 /* */
572 #else
573 UNUSED(p);
574 #endif
577 return (status != 0);
580 static int webdav_delete_dir(server *srv, connection *con, plugin_data *p, physical *dst, buffer *b) {
581 DIR *dir;
582 int have_multi_status = 0;
583 physical d;
585 d.path = buffer_init();
586 d.rel_path = buffer_init();
588 if (NULL != (dir = opendir(dst->path->ptr))) {
589 struct dirent *de;
591 while(NULL != (de = readdir(dir))) {
592 struct stat st;
593 int status = 0;
595 if ((de->d_name[0] == '.' && de->d_name[1] == '\0') ||
596 (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0')) {
597 continue;
598 /* ignore the parent dir */
601 buffer_copy_buffer(d.path, dst->path);
602 buffer_append_slash(d.path);
603 buffer_append_string(d.path, de->d_name);
605 buffer_copy_buffer(d.rel_path, dst->rel_path);
606 buffer_append_slash(d.rel_path);
607 buffer_append_string(d.rel_path, de->d_name);
609 /* stat and unlink afterwards */
610 if (-1 == stat(d.path->ptr, &st)) {
611 /* don't about it yet, rmdir will fail too */
612 } else if (S_ISDIR(st.st_mode)) {
613 have_multi_status = webdav_delete_dir(srv, con, p, &d, b);
615 /* try to unlink it */
616 if (-1 == rmdir(d.path->ptr)) {
617 switch(errno) {
618 case EACCES:
619 case EPERM:
620 /* 403 */
621 status = 403;
622 break;
623 default:
624 status = 501;
625 break;
627 have_multi_status = 1;
629 webdav_gen_response_status_tag(srv, con, &d, status, b);
630 } else {
631 #ifdef USE_PROPPATCH
632 sqlite3_stmt *stmt = p->conf.stmt_delete_uri;
634 status = 0;
636 if (stmt) {
637 sqlite3_reset(stmt);
639 /* bind the values to the insert */
641 sqlite3_bind_text(stmt, 1,
642 CONST_BUF_LEN(d.rel_path),
643 SQLITE_TRANSIENT);
645 if (SQLITE_DONE != sqlite3_step(stmt)) {
646 /* */
649 #endif
651 } else {
652 have_multi_status = webdav_delete_file(srv, con, p, &d, b);
655 closedir(dir);
657 buffer_free(d.path);
658 buffer_free(d.rel_path);
661 return have_multi_status;
664 /* don't want to block when open()ing a fifo */
665 #if defined(O_NONBLOCK)
666 # define FIFO_NONBLOCK O_NONBLOCK
667 #else
668 # define FIFO_NONBLOCK 0
669 #endif
671 #ifndef O_BINARY
672 #define O_BINARY 0
673 #endif
675 static int webdav_copy_file(server *srv, connection *con, plugin_data *p, physical *src, physical *dst, int overwrite) {
676 char *data;
677 ssize_t rd, wr, offset;
678 int status = 0, ifd, ofd;
679 UNUSED(srv);
680 UNUSED(con);
682 if (-1 == (ifd = open(src->path->ptr, O_RDONLY | O_BINARY | FIFO_NONBLOCK))) {
683 return 403;
686 if (-1 == (ofd = open(dst->path->ptr, O_WRONLY|O_TRUNC|O_CREAT|(overwrite ? 0 : O_EXCL), WEBDAV_FILE_MODE))) {
687 /* opening the destination failed for some reason */
688 switch(errno) {
689 case EEXIST:
690 status = 412;
691 break;
692 case EISDIR:
693 status = 409;
694 break;
695 case ENOENT:
696 /* at least one part in the middle wasn't existing */
697 status = 409;
698 break;
699 default:
700 status = 403;
701 break;
703 close(ifd);
704 return status;
707 data = malloc(131072);
708 force_assert(data);
710 while (0 < (rd = read(ifd, data, 131072))) {
711 offset = 0;
712 do {
713 wr = write(ofd, data+offset, (size_t)(rd-offset));
714 } while (wr >= 0 ? (offset += wr) != rd : (errno == EINTR));
715 if (-1 == wr) {
716 status = (errno == ENOSPC) ? 507 : 403;
717 break;
721 if (0 != rd && 0 == status) status = 403;
723 free(data);
724 close(ifd);
725 if (0 != close(ofd)) {
726 if (0 == status) status = (errno == ENOSPC) ? 507 : 403;
727 log_error_write(srv, __FILE__, __LINE__, "sbss",
728 "close ", dst->path, "failed: ", strerror(errno));
731 #ifdef USE_PROPPATCH
732 if (0 == status) {
733 /* copy worked fine, copy connected properties */
734 sqlite3_stmt *stmt = p->conf.stmt_copy_uri;
736 if (stmt) {
737 sqlite3_reset(stmt);
739 /* bind the values to the insert */
740 sqlite3_bind_text(stmt, 1,
741 CONST_BUF_LEN(dst->rel_path),
742 SQLITE_TRANSIENT);
744 sqlite3_bind_text(stmt, 2,
745 CONST_BUF_LEN(src->rel_path),
746 SQLITE_TRANSIENT);
748 if (SQLITE_DONE != sqlite3_step(stmt)) {
749 /* */
753 #else
754 UNUSED(p);
755 #endif
756 return status;
759 static int webdav_copy_dir(server *srv, connection *con, plugin_data *p, physical *src, physical *dst, int overwrite) {
760 DIR *srcdir;
761 int status = 0;
763 if (NULL != (srcdir = opendir(src->path->ptr))) {
764 struct dirent *de;
765 physical s, d;
767 s.path = buffer_init();
768 s.rel_path = buffer_init();
770 d.path = buffer_init();
771 d.rel_path = buffer_init();
773 while (NULL != (de = readdir(srcdir))) {
774 struct stat st;
776 if ((de->d_name[0] == '.' && de->d_name[1] == '\0')
777 || (de->d_name[0] == '.' && de->d_name[1] == '.' && de->d_name[2] == '\0')) {
778 continue;
781 buffer_copy_buffer(s.path, src->path);
782 buffer_append_slash(s.path);
783 buffer_append_string(s.path, de->d_name);
785 buffer_copy_buffer(d.path, dst->path);
786 buffer_append_slash(d.path);
787 buffer_append_string(d.path, de->d_name);
789 buffer_copy_buffer(s.rel_path, src->rel_path);
790 buffer_append_slash(s.rel_path);
791 buffer_append_string(s.rel_path, de->d_name);
793 buffer_copy_buffer(d.rel_path, dst->rel_path);
794 buffer_append_slash(d.rel_path);
795 buffer_append_string(d.rel_path, de->d_name);
797 if (-1 == stat(s.path->ptr, &st)) {
798 /* why ? */
799 } else if (S_ISDIR(st.st_mode)) {
800 /* a directory */
801 if (-1 == mkdir(d.path->ptr, WEBDAV_DIR_MODE) &&
802 errno != EEXIST) {
803 /* WTH ? */
804 } else {
805 #ifdef USE_PROPPATCH
806 sqlite3_stmt *stmt = p->conf.stmt_copy_uri;
808 if (0 != (status = webdav_copy_dir(srv, con, p, &s, &d, overwrite))) {
809 break;
811 /* directory is copied, copy the properties too */
813 if (stmt) {
814 sqlite3_reset(stmt);
816 /* bind the values to the insert */
817 sqlite3_bind_text(stmt, 1,
818 CONST_BUF_LEN(dst->rel_path),
819 SQLITE_TRANSIENT);
821 sqlite3_bind_text(stmt, 2,
822 CONST_BUF_LEN(src->rel_path),
823 SQLITE_TRANSIENT);
825 if (SQLITE_DONE != sqlite3_step(stmt)) {
826 /* */
829 #endif
831 } else if (S_ISREG(st.st_mode)) {
832 /* a plain file */
833 if (0 != (status = webdav_copy_file(srv, con, p, &s, &d, overwrite))) {
834 break;
839 buffer_free(s.path);
840 buffer_free(s.rel_path);
841 buffer_free(d.path);
842 buffer_free(d.rel_path);
844 closedir(srcdir);
847 return status;
850 static int webdav_get_live_property(server *srv, connection *con, plugin_data *p, physical *dst, char *prop_name, buffer *b) {
851 stat_cache_entry *sce = NULL;
852 int found = 0;
854 UNUSED(p);
856 if (HANDLER_ERROR != (stat_cache_get_entry(srv, con, dst->path, &sce))) {
857 char ctime_buf[] = "2005-08-18T07:27:16Z";
858 char mtime_buf[] = "Thu, 18 Aug 2005 07:27:16 GMT";
859 size_t k;
861 if (0 == strcmp(prop_name, "resourcetype")) {
862 if (S_ISDIR(sce->st.st_mode)) {
863 buffer_append_string_len(b, CONST_STR_LEN("<D:resourcetype><D:collection/></D:resourcetype>"));
864 found = 1;
866 } else if (0 == strcmp(prop_name, "getcontenttype")) {
867 if (S_ISDIR(sce->st.st_mode)) {
868 buffer_append_string_len(b, CONST_STR_LEN("<D:getcontenttype>httpd/unix-directory</D:getcontenttype>"));
869 found = 1;
870 } else if(S_ISREG(sce->st.st_mode)) {
871 for (k = 0; k < con->conf.mimetypes->used; k++) {
872 data_string *ds = (data_string *)con->conf.mimetypes->data[k];
874 if (buffer_is_empty(ds->key)) continue;
876 if (buffer_is_equal_right_len(dst->path, ds->key, buffer_string_length(ds->key))) {
877 buffer_append_string_len(b,CONST_STR_LEN("<D:getcontenttype>"));
878 buffer_append_string_buffer(b, ds->value);
879 buffer_append_string_len(b, CONST_STR_LEN("</D:getcontenttype>"));
880 found = 1;
882 break;
886 } else if (0 == strcmp(prop_name, "creationdate")) {
887 buffer_append_string_len(b, CONST_STR_LEN("<D:creationdate ns0:dt=\"dateTime.tz\">"));
888 strftime(ctime_buf, sizeof(ctime_buf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&(sce->st.st_ctime)));
889 buffer_append_string(b, ctime_buf);
890 buffer_append_string_len(b, CONST_STR_LEN("</D:creationdate>"));
891 found = 1;
892 } else if (0 == strcmp(prop_name, "getlastmodified")) {
893 buffer_append_string_len(b,CONST_STR_LEN("<D:getlastmodified ns0:dt=\"dateTime.rfc1123\">"));
894 strftime(mtime_buf, sizeof(mtime_buf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&(sce->st.st_mtime)));
895 buffer_append_string(b, mtime_buf);
896 buffer_append_string_len(b, CONST_STR_LEN("</D:getlastmodified>"));
897 found = 1;
898 } else if (0 == strcmp(prop_name, "getcontentlength")) {
899 buffer_append_string_len(b,CONST_STR_LEN("<D:getcontentlength>"));
900 buffer_append_int(b, sce->st.st_size);
901 buffer_append_string_len(b, CONST_STR_LEN("</D:getcontentlength>"));
902 found = 1;
903 } else if (0 == strcmp(prop_name, "getcontentlanguage")) {
904 buffer_append_string_len(b,CONST_STR_LEN("<D:getcontentlanguage>"));
905 buffer_append_string_len(b, CONST_STR_LEN("en"));
906 buffer_append_string_len(b, CONST_STR_LEN("</D:getcontentlanguage>"));
907 found = 1;
908 #ifdef USE_LOCKS
909 } else if (0 == strcmp(prop_name, "supportedlock")) {
910 buffer_append_string_len(b,CONST_STR_LEN("<D:supportedlock>"));
911 buffer_append_string_len(b,CONST_STR_LEN("<D:lockentry>"));
912 buffer_append_string_len(b,CONST_STR_LEN("<D:lockscope><D:exclusive/></D:lockscope>"));
913 buffer_append_string_len(b,CONST_STR_LEN("<D:locktype><D:write/></D:locktype>"));
914 buffer_append_string_len(b,CONST_STR_LEN("</D:lockentry>"));
915 buffer_append_string_len(b, CONST_STR_LEN("</D:supportedlock>"));
916 found = 1;
917 #endif
921 return found ? 0 : -1;
924 static int webdav_get_property(server *srv, connection *con, plugin_data *p, physical *dst, char *prop_name, char *prop_ns, buffer *b) {
925 if (0 == strcmp(prop_ns, "DAV:")) {
926 /* a local 'live' property */
927 return webdav_get_live_property(srv, con, p, dst, prop_name, b);
928 } else {
929 int found = 0;
930 #ifdef USE_PROPPATCH
931 sqlite3_stmt *stmt = p->conf.stmt_select_prop;
933 if (stmt) {
934 /* perhaps it is in sqlite3 */
935 sqlite3_reset(stmt);
937 /* bind the values to the insert */
939 sqlite3_bind_text(stmt, 1,
940 CONST_BUF_LEN(dst->rel_path),
941 SQLITE_TRANSIENT);
942 sqlite3_bind_text(stmt, 2,
943 prop_name,
944 strlen(prop_name),
945 SQLITE_TRANSIENT);
946 sqlite3_bind_text(stmt, 3,
947 prop_ns,
948 strlen(prop_ns),
949 SQLITE_TRANSIENT);
951 /* it is the PK */
952 while (SQLITE_ROW == sqlite3_step(stmt)) {
953 /* there is a row for us, we only expect a single col 'value' */
954 webdav_gen_prop_tag(srv, con, prop_name, prop_ns, (char *)sqlite3_column_text(stmt, 0), b);
955 found = 1;
958 #endif
959 return found ? 0 : -1;
962 /* not found */
963 return -1;
966 typedef struct {
967 char *ns;
968 char *prop;
969 } webdav_property;
971 static webdav_property live_properties[] = {
972 { "DAV:", "creationdate" },
973 { "DAV:", "displayname" },
974 { "DAV:", "getcontentlanguage" },
975 { "DAV:", "getcontentlength" },
976 { "DAV:", "getcontenttype" },
977 { "DAV:", "getetag" },
978 { "DAV:", "getlastmodified" },
979 { "DAV:", "resourcetype" },
980 { "DAV:", "lockdiscovery" },
981 { "DAV:", "source" },
982 #ifdef USE_LOCKS
983 { "DAV:", "supportedlock" },
984 #endif
986 { NULL, NULL }
989 typedef struct {
990 webdav_property **ptr;
992 size_t used;
993 size_t size;
994 } webdav_properties;
996 static int webdav_get_props(server *srv, connection *con, plugin_data *p, physical *dst, webdav_properties *props, buffer *b_200, buffer *b_404) {
997 size_t i;
999 if (props && props->used) {
1000 for (i = 0; i < props->used; i++) {
1001 webdav_property *prop;
1003 prop = props->ptr[i];
1005 if (0 != webdav_get_property(srv, con, p,
1006 dst, prop->prop, prop->ns, b_200)) {
1007 webdav_gen_prop_tag(srv, con, prop->prop, prop->ns, NULL, b_404);
1010 } else {
1011 for (i = 0; live_properties[i].prop; i++) {
1012 /* a local 'live' property */
1013 webdav_get_live_property(srv, con, p, dst, live_properties[i].prop, b_200);
1017 return 0;
1020 #ifdef USE_PROPPATCH
1021 static int webdav_parse_chunkqueue(server *srv, connection *con, plugin_data *p, chunkqueue *cq, xmlDoc **ret_xml) {
1022 xmlParserCtxtPtr ctxt;
1023 xmlDoc *xml;
1024 int res;
1025 int err;
1027 chunk *c;
1029 UNUSED(con);
1031 /* read the chunks in to the XML document */
1032 ctxt = xmlCreatePushParserCtxt(NULL, NULL, NULL, 0, NULL);
1034 for (c = cq->first; cq->bytes_out != cq->bytes_in; c = cq->first) {
1035 size_t weWant = cq->bytes_out - cq->bytes_in;
1036 size_t weHave;
1037 int mapped;
1038 void *data;
1040 switch(c->type) {
1041 case FILE_CHUNK:
1042 weHave = c->file.length - c->offset;
1044 if (weHave > weWant) weHave = weWant;
1046 /* xml chunks are always memory, mmap() is our friend */
1047 mapped = (c->file.mmap.start != MAP_FAILED);
1048 if (mapped) {
1049 data = c->file.mmap.start + c->offset;
1050 } else {
1051 if (-1 == c->file.fd && /* open the file if not already open */
1052 -1 == (c->file.fd = open(c->file.name->ptr, O_RDONLY))) {
1053 log_error_write(srv, __FILE__, __LINE__, "ss", "open failed: ", strerror(errno));
1055 return -1;
1058 if (MAP_FAILED != (c->file.mmap.start = mmap(0, c->file.length, PROT_READ, MAP_PRIVATE, c->file.fd, 0))) {
1059 /* chunk_reset() or chunk_free() will cleanup for us */
1060 c->file.mmap.length = c->file.length;
1061 data = c->file.mmap.start + c->offset;
1062 mapped = 1;
1063 } else {
1064 ssize_t rd;
1065 if (weHave > 65536) weHave = 65536;
1066 data = malloc(weHave);
1067 force_assert(data);
1068 if (-1 == lseek(c->file.fd, c->file.start + c->offset, SEEK_SET)
1069 || 0 > (rd = read(c->file.fd, data, weHave))) {
1070 log_error_write(srv, __FILE__, __LINE__, "ssbd", "lseek/read failed: ",
1071 strerror(errno), c->file.name, c->file.fd);
1072 free(data);
1073 return -1;
1075 weHave = (size_t)rd;
1079 if (XML_ERR_OK != (err = xmlParseChunk(ctxt, data, weHave, 0))) {
1080 log_error_write(srv, __FILE__, __LINE__, "sodd", "xmlParseChunk failed at:", cq->bytes_out, weHave, err);
1083 chunkqueue_mark_written(cq, weHave);
1085 if (!mapped) free(data);
1086 break;
1087 case MEM_CHUNK:
1088 /* append to the buffer */
1089 weHave = buffer_string_length(c->mem) - c->offset;
1091 if (weHave > weWant) weHave = weWant;
1093 if (p->conf.log_xml) {
1094 log_error_write(srv, __FILE__, __LINE__, "ss", "XML-request-body:", c->mem->ptr + c->offset);
1097 if (XML_ERR_OK != (err = xmlParseChunk(ctxt, c->mem->ptr + c->offset, weHave, 0))) {
1098 log_error_write(srv, __FILE__, __LINE__, "sodd", "xmlParseChunk failed at:", cq->bytes_out, weHave, err);
1101 chunkqueue_mark_written(cq, weHave);
1103 break;
1107 switch ((err = xmlParseChunk(ctxt, 0, 0, 1))) {
1108 case XML_ERR_DOCUMENT_END:
1109 case XML_ERR_OK:
1110 break;
1111 default:
1112 log_error_write(srv, __FILE__, __LINE__, "sd", "xmlParseChunk failed at final packet:", err);
1113 break;
1116 xml = ctxt->myDoc;
1117 res = ctxt->wellFormed;
1118 xmlFreeParserCtxt(ctxt);
1120 if (res == 0) {
1121 xmlFreeDoc(xml);
1122 } else {
1123 *ret_xml = xml;
1126 return res;
1128 #endif
1130 #ifdef USE_LOCKS
1131 static int webdav_lockdiscovery(server *srv, connection *con,
1132 buffer *locktoken, const char *lockscope, const char *locktype, int depth) {
1134 buffer *b = buffer_init();
1136 response_header_overwrite(srv, con, CONST_STR_LEN("Lock-Token"), CONST_BUF_LEN(locktoken));
1138 response_header_overwrite(srv, con,
1139 CONST_STR_LEN("Content-Type"),
1140 CONST_STR_LEN("text/xml; charset=\"utf-8\""));
1142 buffer_copy_string_len(b, CONST_STR_LEN("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"));
1144 buffer_append_string_len(b,CONST_STR_LEN("<D:prop xmlns:D=\"DAV:\" xmlns:ns0=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\">\n"));
1145 buffer_append_string_len(b,CONST_STR_LEN("<D:lockdiscovery>\n"));
1146 buffer_append_string_len(b,CONST_STR_LEN("<D:activelock>\n"));
1148 buffer_append_string_len(b,CONST_STR_LEN("<D:lockscope>"));
1149 buffer_append_string_len(b,CONST_STR_LEN("<D:"));
1150 buffer_append_string(b, lockscope);
1151 buffer_append_string_len(b, CONST_STR_LEN("/>"));
1152 buffer_append_string_len(b,CONST_STR_LEN("</D:lockscope>\n"));
1154 buffer_append_string_len(b,CONST_STR_LEN("<D:locktype>"));
1155 buffer_append_string_len(b,CONST_STR_LEN("<D:"));
1156 buffer_append_string(b, locktype);
1157 buffer_append_string_len(b, CONST_STR_LEN("/>"));
1158 buffer_append_string_len(b,CONST_STR_LEN("</D:locktype>\n"));
1160 buffer_append_string_len(b,CONST_STR_LEN("<D:depth>"));
1161 buffer_append_string(b, depth == 0 ? "0" : "infinity");
1162 buffer_append_string_len(b,CONST_STR_LEN("</D:depth>\n"));
1164 buffer_append_string_len(b,CONST_STR_LEN("<D:timeout>"));
1165 buffer_append_string_len(b, CONST_STR_LEN("Second-600"));
1166 buffer_append_string_len(b,CONST_STR_LEN("</D:timeout>\n"));
1168 buffer_append_string_len(b,CONST_STR_LEN("<D:owner>"));
1169 buffer_append_string_len(b,CONST_STR_LEN("</D:owner>\n"));
1171 buffer_append_string_len(b,CONST_STR_LEN("<D:locktoken>"));
1172 buffer_append_string_len(b, CONST_STR_LEN("<D:href>"));
1173 buffer_append_string_buffer(b, locktoken);
1174 buffer_append_string_len(b, CONST_STR_LEN("</D:href>"));
1175 buffer_append_string_len(b,CONST_STR_LEN("</D:locktoken>\n"));
1177 buffer_append_string_len(b,CONST_STR_LEN("</D:activelock>\n"));
1178 buffer_append_string_len(b,CONST_STR_LEN("</D:lockdiscovery>\n"));
1179 buffer_append_string_len(b,CONST_STR_LEN("</D:prop>\n"));
1181 chunkqueue_append_buffer(con->write_queue, b);
1182 buffer_free(b);
1184 return 0;
1186 #endif
1189 * check if resource is having the right locks to access to resource
1194 static int webdav_has_lock(server *srv, connection *con, plugin_data *p, buffer *uri) {
1195 int has_lock = 1;
1197 #ifdef USE_LOCKS
1198 data_string *ds;
1199 UNUSED(srv);
1202 * This implementation is more fake than real
1203 * we need a parser for the If: header to really handle the full scope
1205 * X-Litmus: locks: 11 (owner_modify)
1206 * If: <http://127.0.0.1:1025/dav/litmus/lockme> (<opaquelocktoken:2165478d-0611-49c4-be92-e790d68a38f1>)
1207 * - a tagged check:
1208 * if http://127.0.0.1:1025/dav/litmus/lockme is locked with
1209 * opaquelocktoken:2165478d-0611-49c4-be92-e790d68a38f1, go on
1211 * X-Litmus: locks: 16 (fail_cond_put)
1212 * If: (<DAV:no-lock> ["-1622396671"])
1213 * - untagged:
1214 * go on if the resource has the etag [...] and the lock
1216 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "If"))) {
1217 /* Ooh, ooh. A if tag, now the fun begins.
1219 * this can only work with a real parser
1221 } else {
1222 /* we didn't provided a lock-token -> */
1223 /* if the resource is locked -> 423 */
1225 sqlite3_stmt *stmt = p->conf.stmt_read_lock_by_uri;
1227 sqlite3_reset(stmt);
1229 sqlite3_bind_text(stmt, 1,
1230 CONST_BUF_LEN(uri),
1231 SQLITE_TRANSIENT);
1233 while (SQLITE_ROW == sqlite3_step(stmt)) {
1234 has_lock = 0;
1237 #else
1238 UNUSED(srv);
1239 UNUSED(con);
1240 UNUSED(p);
1241 UNUSED(uri);
1242 #endif
1244 return has_lock;
1248 SUBREQUEST_FUNC(mod_webdav_subrequest_handler_huge) {
1249 plugin_data *p = p_d;
1250 buffer *b;
1251 DIR *dir;
1252 data_string *ds;
1253 int depth = -1; /* (Depth: infinity) */
1254 struct stat st;
1255 buffer *prop_200;
1256 buffer *prop_404;
1257 webdav_properties *req_props;
1258 stat_cache_entry *sce = NULL;
1260 UNUSED(srv);
1262 if (!p->conf.enabled) return HANDLER_GO_ON;
1263 /* physical path is setup */
1264 if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;
1266 /* PROPFIND need them */
1267 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "Depth")) && 1 == buffer_string_length(ds->value)) {
1268 if ('0' == *ds->value->ptr) {
1269 depth = 0;
1270 } else if ('1' == *ds->value->ptr) {
1271 depth = 1;
1273 } /* else treat as Depth: infinity */
1275 switch (con->request.http_method) {
1276 case HTTP_METHOD_PROPFIND:
1277 /* they want to know the properties of the directory */
1278 req_props = NULL;
1280 /* is there a content-body ? */
1282 switch (stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
1283 case HANDLER_ERROR:
1284 if (errno == ENOENT) {
1285 con->http_status = 404;
1286 return HANDLER_FINISHED;
1288 break;
1289 default:
1290 break;
1293 if (S_ISDIR(sce->st.st_mode) && con->physical.path->ptr[buffer_string_length(con->physical.path)-1] != '/') {
1294 http_response_redirect_to_directory(srv, con);
1295 return HANDLER_FINISHED;
1298 #ifdef USE_PROPPATCH
1299 /* any special requests or just allprop ? */
1300 if (con->request.content_length) {
1301 xmlDocPtr xml;
1303 if (con->state == CON_STATE_READ_POST) {
1304 handler_t r = connection_handle_read_post_state(srv, con);
1305 if (r != HANDLER_GO_ON) return r;
1308 if (1 == webdav_parse_chunkqueue(srv, con, p, con->request_content_queue, &xml)) {
1309 xmlNode *rootnode = xmlDocGetRootElement(xml);
1311 force_assert(rootnode);
1313 if (0 == xmlStrcmp(rootnode->name, BAD_CAST "propfind")) {
1314 xmlNode *cmd;
1316 req_props = calloc(1, sizeof(*req_props));
1318 for (cmd = rootnode->children; cmd; cmd = cmd->next) {
1320 if (0 == xmlStrcmp(cmd->name, BAD_CAST "prop")) {
1321 /* get prop by name */
1322 xmlNode *prop;
1324 for (prop = cmd->children; prop; prop = prop->next) {
1325 if (prop->type == XML_TEXT_NODE) continue; /* ignore WS */
1327 if (prop->ns &&
1328 (0 == xmlStrcmp(prop->ns->href, BAD_CAST "")) &&
1329 (0 != xmlStrcmp(prop->ns->prefix, BAD_CAST ""))) {
1330 size_t i;
1331 log_error_write(srv, __FILE__, __LINE__, "ss",
1332 "no name space for:",
1333 prop->name);
1335 xmlFreeDoc(xml);
1337 for (i = 0; i < req_props->used; i++) {
1338 free(req_props->ptr[i]->ns);
1339 free(req_props->ptr[i]->prop);
1340 free(req_props->ptr[i]);
1342 free(req_props->ptr);
1343 free(req_props);
1345 con->http_status = 400;
1346 return HANDLER_FINISHED;
1349 /* add property to requested list */
1350 if (req_props->size == 0) {
1351 req_props->size = 16;
1352 req_props->ptr = malloc(sizeof(*(req_props->ptr)) * req_props->size);
1353 } else if (req_props->used == req_props->size) {
1354 req_props->size += 16;
1355 req_props->ptr = realloc(req_props->ptr, sizeof(*(req_props->ptr)) * req_props->size);
1358 req_props->ptr[req_props->used] = malloc(sizeof(webdav_property));
1359 req_props->ptr[req_props->used]->ns = (char *)xmlStrdup(prop->ns ? prop->ns->href : (xmlChar *)"");
1360 req_props->ptr[req_props->used]->prop = (char *)xmlStrdup(prop->name);
1361 req_props->used++;
1363 } else if (0 == xmlStrcmp(cmd->name, BAD_CAST "propname")) {
1364 sqlite3_stmt *stmt = p->conf.stmt_select_propnames;
1366 if (stmt) {
1367 /* get all property names (EMPTY) */
1368 sqlite3_reset(stmt);
1369 /* bind the values to the insert */
1371 sqlite3_bind_text(stmt, 1,
1372 CONST_BUF_LEN(con->uri.path),
1373 SQLITE_TRANSIENT);
1375 if (SQLITE_DONE != sqlite3_step(stmt)) {
1378 } else if (0 == xmlStrcmp(cmd->name, BAD_CAST "allprop")) {
1379 /* get all properties (EMPTY) */
1384 xmlFreeDoc(xml);
1385 } else {
1386 con->http_status = 400;
1387 return HANDLER_FINISHED;
1390 #endif
1391 con->http_status = 207;
1393 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/xml; charset=\"utf-8\""));
1395 b = buffer_init();
1397 buffer_copy_string_len(b, CONST_STR_LEN("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"));
1399 buffer_append_string_len(b,CONST_STR_LEN("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns0=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\">\n"));
1401 /* allprop */
1403 prop_200 = buffer_init();
1404 prop_404 = buffer_init();
1407 /* Depth: 0 or Depth: 1 */
1408 webdav_get_props(srv, con, p, &(con->physical), req_props, prop_200, prop_404);
1410 buffer_append_string_len(b,CONST_STR_LEN("<D:response>\n"));
1411 buffer_append_string_len(b,CONST_STR_LEN("<D:href>"));
1412 buffer_append_string_buffer(b, con->uri.scheme);
1413 buffer_append_string_len(b,CONST_STR_LEN("://"));
1414 buffer_append_string_buffer(b, con->uri.authority);
1415 buffer_append_string_encoded(b, CONST_BUF_LEN(con->uri.path), ENCODING_REL_URI);
1416 buffer_append_string_len(b,CONST_STR_LEN("</D:href>\n"));
1418 if (!buffer_string_is_empty(prop_200)) {
1419 buffer_append_string_len(b,CONST_STR_LEN("<D:propstat>\n"));
1420 buffer_append_string_len(b,CONST_STR_LEN("<D:prop>\n"));
1422 buffer_append_string_buffer(b, prop_200);
1424 buffer_append_string_len(b,CONST_STR_LEN("</D:prop>\n"));
1426 buffer_append_string_len(b,CONST_STR_LEN("<D:status>HTTP/1.1 200 OK</D:status>\n"));
1428 buffer_append_string_len(b,CONST_STR_LEN("</D:propstat>\n"));
1430 if (!buffer_string_is_empty(prop_404)) {
1431 buffer_append_string_len(b,CONST_STR_LEN("<D:propstat>\n"));
1432 buffer_append_string_len(b,CONST_STR_LEN("<D:prop>\n"));
1434 buffer_append_string_buffer(b, prop_404);
1436 buffer_append_string_len(b,CONST_STR_LEN("</D:prop>\n"));
1438 buffer_append_string_len(b,CONST_STR_LEN("<D:status>HTTP/1.1 404 Not Found</D:status>\n"));
1440 buffer_append_string_len(b,CONST_STR_LEN("</D:propstat>\n"));
1443 buffer_append_string_len(b,CONST_STR_LEN("</D:response>\n"));
1446 if (depth == 1) {
1448 if (NULL != (dir = opendir(con->physical.path->ptr))) {
1449 struct dirent *de;
1450 physical d;
1451 physical *dst = &(con->physical);
1453 d.path = buffer_init();
1454 d.rel_path = buffer_init();
1456 while(NULL != (de = readdir(dir))) {
1457 if (de->d_name[0] == '.' && (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0'))) {
1458 continue;
1459 /* ignore the parent and target dir */
1462 buffer_copy_buffer(d.path, dst->path);
1463 buffer_append_slash(d.path);
1465 buffer_copy_buffer(d.rel_path, dst->rel_path);
1466 buffer_append_slash(d.rel_path);
1468 buffer_append_string(d.path, de->d_name);
1469 buffer_append_string(d.rel_path, de->d_name);
1471 buffer_reset(prop_200);
1472 buffer_reset(prop_404);
1474 webdav_get_props(srv, con, p, &d, req_props, prop_200, prop_404);
1476 buffer_append_string_len(b,CONST_STR_LEN("<D:response>\n"));
1477 buffer_append_string_len(b,CONST_STR_LEN("<D:href>"));
1478 buffer_append_string_buffer(b, con->uri.scheme);
1479 buffer_append_string_len(b,CONST_STR_LEN("://"));
1480 buffer_append_string_buffer(b, con->uri.authority);
1481 buffer_append_string_encoded(b, CONST_BUF_LEN(d.rel_path), ENCODING_REL_URI);
1482 if (0 == stat(d.path->ptr, &st) && S_ISDIR(st.st_mode)) {
1483 /* Append a '/' on subdirectories */
1484 buffer_append_string_len(b,CONST_STR_LEN("/"));
1486 buffer_append_string_len(b,CONST_STR_LEN("</D:href>\n"));
1488 if (!buffer_string_is_empty(prop_200)) {
1489 buffer_append_string_len(b,CONST_STR_LEN("<D:propstat>\n"));
1490 buffer_append_string_len(b,CONST_STR_LEN("<D:prop>\n"));
1492 buffer_append_string_buffer(b, prop_200);
1494 buffer_append_string_len(b,CONST_STR_LEN("</D:prop>\n"));
1496 buffer_append_string_len(b,CONST_STR_LEN("<D:status>HTTP/1.1 200 OK</D:status>\n"));
1498 buffer_append_string_len(b,CONST_STR_LEN("</D:propstat>\n"));
1500 if (!buffer_string_is_empty(prop_404)) {
1501 buffer_append_string_len(b,CONST_STR_LEN("<D:propstat>\n"));
1502 buffer_append_string_len(b,CONST_STR_LEN("<D:prop>\n"));
1504 buffer_append_string_buffer(b, prop_404);
1506 buffer_append_string_len(b,CONST_STR_LEN("</D:prop>\n"));
1508 buffer_append_string_len(b,CONST_STR_LEN("<D:status>HTTP/1.1 404 Not Found</D:status>\n"));
1510 buffer_append_string_len(b,CONST_STR_LEN("</D:propstat>\n"));
1513 buffer_append_string_len(b,CONST_STR_LEN("</D:response>\n"));
1515 closedir(dir);
1516 buffer_free(d.path);
1517 buffer_free(d.rel_path);
1522 if (req_props) {
1523 size_t i;
1524 for (i = 0; i < req_props->used; i++) {
1525 free(req_props->ptr[i]->ns);
1526 free(req_props->ptr[i]->prop);
1527 free(req_props->ptr[i]);
1529 free(req_props->ptr);
1530 free(req_props);
1533 buffer_free(prop_200);
1534 buffer_free(prop_404);
1536 buffer_append_string_len(b,CONST_STR_LEN("</D:multistatus>\n"));
1538 if (p->conf.log_xml) {
1539 log_error_write(srv, __FILE__, __LINE__, "sb", "XML-response-body:", b);
1542 chunkqueue_append_buffer(con->write_queue, b);
1543 buffer_free(b);
1545 con->file_finished = 1;
1547 return HANDLER_FINISHED;
1548 case HTTP_METHOD_MKCOL:
1549 if (p->conf.is_readonly) {
1550 con->http_status = 403;
1551 return HANDLER_FINISHED;
1554 if (con->request.content_length != 0) {
1555 /* we don't support MKCOL with a body */
1556 con->http_status = 415;
1558 return HANDLER_FINISHED;
1561 /* let's create the directory */
1563 if (-1 == mkdir(con->physical.path->ptr, WEBDAV_DIR_MODE)) {
1564 switch(errno) {
1565 case EPERM:
1566 con->http_status = 403;
1567 break;
1568 case ENOENT:
1569 case ENOTDIR:
1570 con->http_status = 409;
1571 break;
1572 case EEXIST:
1573 default:
1574 con->http_status = 405; /* not allowed */
1575 break;
1577 } else {
1578 con->http_status = 201;
1579 con->file_finished = 1;
1582 return HANDLER_FINISHED;
1583 case HTTP_METHOD_DELETE:
1584 if (p->conf.is_readonly) {
1585 con->http_status = 403;
1586 return HANDLER_FINISHED;
1589 /* does the client have a lock for this connection ? */
1590 if (!webdav_has_lock(srv, con, p, con->uri.path)) {
1591 con->http_status = 423;
1592 return HANDLER_FINISHED;
1595 /* stat and unlink afterwards */
1596 if (-1 == stat(con->physical.path->ptr, &st)) {
1597 /* don't about it yet, unlink will fail too */
1598 switch(errno) {
1599 case ENOENT:
1600 con->http_status = 404;
1601 break;
1602 default:
1603 con->http_status = 403;
1604 break;
1606 } else if (S_ISDIR(st.st_mode)) {
1607 buffer *multi_status_resp;
1609 if (con->physical.path->ptr[buffer_string_length(con->physical.path)-1] != '/') {
1610 http_response_redirect_to_directory(srv, con);
1611 return HANDLER_FINISHED;
1614 multi_status_resp = buffer_init();
1616 if (webdav_delete_dir(srv, con, p, &(con->physical), multi_status_resp)) {
1617 /* we got an error somewhere in between, build a 207 */
1618 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/xml; charset=\"utf-8\""));
1620 b = buffer_init();
1622 buffer_copy_string_len(b, CONST_STR_LEN("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"));
1624 buffer_append_string_len(b,CONST_STR_LEN("<D:multistatus xmlns:D=\"DAV:\">\n"));
1626 buffer_append_string_buffer(b, multi_status_resp);
1628 buffer_append_string_len(b,CONST_STR_LEN("</D:multistatus>\n"));
1630 if (p->conf.log_xml) {
1631 log_error_write(srv, __FILE__, __LINE__, "sb", "XML-response-body:", b);
1634 chunkqueue_append_buffer(con->write_queue, b);
1635 buffer_free(b);
1637 con->http_status = 207;
1638 con->file_finished = 1;
1639 } else {
1640 /* everything went fine, remove the directory */
1642 if (-1 == rmdir(con->physical.path->ptr)) {
1643 switch(errno) {
1644 case ENOENT:
1645 con->http_status = 404;
1646 break;
1647 default:
1648 con->http_status = 501;
1649 break;
1651 } else {
1652 con->http_status = 204;
1656 buffer_free(multi_status_resp);
1657 } else if (-1 == unlink(con->physical.path->ptr)) {
1658 switch(errno) {
1659 case EPERM:
1660 con->http_status = 403;
1661 break;
1662 case ENOENT:
1663 con->http_status = 404;
1664 break;
1665 default:
1666 con->http_status = 501;
1667 break;
1669 } else {
1670 con->http_status = 204;
1672 return HANDLER_FINISHED;
1673 case HTTP_METHOD_PUT: {
1674 int fd;
1675 chunkqueue *cq = con->request_content_queue;
1676 chunk *c;
1677 data_string *ds_range;
1679 if (p->conf.is_readonly) {
1680 con->http_status = 403;
1681 return HANDLER_FINISHED;
1684 /* is a exclusive lock set on the source */
1685 /* (check for lock once before potentially reading large input) */
1686 if (0 == cq->bytes_in && !webdav_has_lock(srv, con, p, con->uri.path)) {
1687 con->http_status = 423;
1688 return HANDLER_FINISHED;
1691 if (con->state == CON_STATE_READ_POST) {
1692 handler_t r = connection_handle_read_post_state(srv, con);
1693 if (r != HANDLER_GO_ON) return r;
1696 /* RFC2616 Section 9.6 PUT requires us to send 501 on all Content-* we don't support
1697 * - most important Content-Range
1700 * Example: Content-Range: bytes 100-1037/1038 */
1702 if (NULL != (ds_range = (data_string *)array_get_element(con->request.headers, "Content-Range"))) {
1703 const char *num = ds_range->value->ptr;
1704 off_t offset;
1705 char *err = NULL;
1707 if (0 != strncmp(num, "bytes ", 6)) {
1708 con->http_status = 501; /* not implemented */
1710 return HANDLER_FINISHED;
1713 /* we only support <num>- ... */
1715 num += 6;
1717 /* skip WS */
1718 while (*num == ' ' || *num == '\t') num++;
1720 if (*num == '\0') {
1721 con->http_status = 501; /* not implemented */
1723 return HANDLER_FINISHED;
1726 offset = strtoll(num, &err, 10);
1728 if (*err != '-' || offset < 0) {
1729 con->http_status = 501; /* not implemented */
1731 return HANDLER_FINISHED;
1734 if (-1 == (fd = open(con->physical.path->ptr, O_WRONLY, WEBDAV_FILE_MODE))) {
1735 switch (errno) {
1736 case ENOENT:
1737 con->http_status = 404; /* not found */
1738 break;
1739 default:
1740 con->http_status = 403; /* not found */
1741 break;
1743 return HANDLER_FINISHED;
1746 if (-1 == lseek(fd, offset, SEEK_SET)) {
1747 con->http_status = 501; /* not implemented */
1749 close(fd);
1751 return HANDLER_FINISHED;
1753 con->http_status = 200; /* modified */
1754 } else {
1755 /* take what we have in the request-body and write it to a file */
1757 /* if the file doesn't exist, create it */
1758 if (-1 == (fd = open(con->physical.path->ptr, O_WRONLY|O_TRUNC, WEBDAV_FILE_MODE))) {
1759 if (errno != ENOENT ||
1760 -1 == (fd = open(con->physical.path->ptr, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, WEBDAV_FILE_MODE))) {
1761 /* we can't open the file */
1762 con->http_status = 403;
1764 return HANDLER_FINISHED;
1765 } else {
1766 con->http_status = 201; /* created */
1768 } else {
1769 con->http_status = 200; /* modified */
1773 con->file_finished = 1;
1775 for (c = cq->first; c; c = cq->first) {
1776 int r = 0;
1777 int mapped;
1778 void *data;
1779 size_t dlen;
1781 /* copy all chunks */
1782 switch(c->type) {
1783 case FILE_CHUNK:
1785 mapped = (c->file.mmap.start != MAP_FAILED);
1786 dlen = c->file.length - c->offset;
1787 if (mapped) {
1788 data = c->file.mmap.start + c->offset;
1789 } else {
1790 if (-1 == c->file.fd && /* open the file if not already open */
1791 -1 == (c->file.fd = open(c->file.name->ptr, O_RDONLY))) {
1792 log_error_write(srv, __FILE__, __LINE__, "ss", "open failed: ", strerror(errno));
1793 close(fd);
1794 return HANDLER_ERROR;
1797 if (MAP_FAILED != (c->file.mmap.start = mmap(NULL, c->file.length, PROT_READ, MAP_PRIVATE, c->file.fd, 0))) {
1798 /* chunk_reset() or chunk_free() will cleanup for us */
1799 c->file.mmap.length = c->file.length;
1800 data = c->file.mmap.start + c->offset;
1801 mapped = 1;
1802 } else {
1803 ssize_t rd;
1804 if (dlen > 65536) dlen = 65536;
1805 data = malloc(dlen);
1806 force_assert(data);
1807 if (-1 == lseek(c->file.fd, c->file.start + c->offset, SEEK_SET)
1808 || 0 > (rd = read(c->file.fd, data, dlen))) {
1809 log_error_write(srv, __FILE__, __LINE__, "ssbd", "lseek/read failed: ",
1810 strerror(errno), c->file.name, c->file.fd);
1811 free(data);
1812 close(fd);
1813 return HANDLER_ERROR;
1815 dlen = (size_t)rd;
1820 if ((r = write(fd, data, dlen)) < 0) {
1821 switch(errno) {
1822 case ENOSPC:
1823 con->http_status = 507;
1825 break;
1826 default:
1827 con->http_status = 403;
1828 break;
1832 if (!mapped) free(data);
1833 break;
1834 case MEM_CHUNK:
1835 if ((r = write(fd, c->mem->ptr + c->offset, buffer_string_length(c->mem) - c->offset)) < 0) {
1836 switch(errno) {
1837 case ENOSPC:
1838 con->http_status = 507;
1840 break;
1841 default:
1842 con->http_status = 403;
1843 break;
1846 break;
1849 if (r > 0) {
1850 chunkqueue_mark_written(cq, r);
1851 } else {
1852 break;
1855 if (0 != close(fd)) {
1856 log_error_write(srv, __FILE__, __LINE__, "sbss",
1857 "close ", con->physical.path, "failed: ", strerror(errno));
1858 return HANDLER_ERROR;
1861 return HANDLER_FINISHED;
1863 case HTTP_METHOD_MOVE:
1864 case HTTP_METHOD_COPY: {
1865 buffer *destination = NULL;
1866 char *sep, *sep2, *start;
1867 int overwrite = 1;
1869 if (p->conf.is_readonly) {
1870 con->http_status = 403;
1871 return HANDLER_FINISHED;
1874 /* is a exclusive lock set on the source */
1875 if (con->request.http_method == HTTP_METHOD_MOVE) {
1876 if (!webdav_has_lock(srv, con, p, con->uri.path)) {
1877 con->http_status = 423;
1878 return HANDLER_FINISHED;
1882 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "Destination"))) {
1883 destination = ds->value;
1884 } else {
1885 con->http_status = 400;
1886 return HANDLER_FINISHED;
1889 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "Overwrite"))) {
1890 if (buffer_string_length(ds->value) != 1 ||
1891 (ds->value->ptr[0] != 'F' &&
1892 ds->value->ptr[0] != 'T') ) {
1893 con->http_status = 400;
1894 return HANDLER_FINISHED;
1896 overwrite = (ds->value->ptr[0] == 'F' ? 0 : 1);
1898 /* let's parse the Destination
1900 * http://127.0.0.1:1025/dav/litmus/copydest
1902 * - host has to be the same as the Host: header we got
1903 * - we have to stay inside the document root
1904 * - the query string is thrown away
1905 * */
1907 buffer_reset(p->uri.scheme);
1908 buffer_reset(p->uri.path_raw);
1909 buffer_reset(p->uri.authority);
1911 start = destination->ptr;
1913 if (NULL == (sep = strstr(start, "://"))) {
1914 con->http_status = 400;
1915 return HANDLER_FINISHED;
1917 buffer_copy_string_len(p->uri.scheme, start, sep - start);
1919 start = sep + 3;
1921 if (NULL == (sep = strchr(start, '/'))) {
1922 con->http_status = 400;
1923 return HANDLER_FINISHED;
1925 if (NULL != (sep2 = memchr(start, '@', sep - start))) {
1926 /* skip login information */
1927 start = sep2 + 1;
1929 buffer_copy_string_len(p->uri.authority, start, sep - start);
1931 start = sep + 1;
1933 if (NULL == (sep = strchr(start, '?'))) {
1934 /* no query string, good */
1935 buffer_copy_string(p->uri.path_raw, start);
1936 } else {
1937 buffer_copy_string_len(p->uri.path_raw, start, sep - start);
1940 if (!buffer_is_equal(p->uri.authority, con->uri.authority)) {
1941 /* not the same host */
1942 con->http_status = 502;
1943 return HANDLER_FINISHED;
1946 buffer_copy_buffer(p->tmp_buf, p->uri.path_raw);
1947 buffer_urldecode_path(p->tmp_buf);
1948 buffer_path_simplify(p->uri.path, p->tmp_buf);
1950 /* we now have a URI which is clean. transform it into a physical path */
1951 buffer_copy_buffer(p->physical.doc_root, con->physical.doc_root);
1952 buffer_copy_buffer(p->physical.rel_path, p->uri.path);
1954 if (con->conf.force_lowercase_filenames) {
1955 buffer_to_lower(p->physical.rel_path);
1958 /* Destination physical path
1959 * src con->physical.path might have been remapped with mod_alias.
1960 * (but mod_alias does not modify con->physical.rel_path)
1961 * Find matching prefix to support use of mod_alias to remap webdav root.
1962 * Aliasing of paths underneath the webdav root might not work.
1963 * Likewise, mod_rewrite URL rewriting might thwart this comparison.
1964 * Use mod_redirect instead of mod_alias to remap paths *under* webdav root.
1965 * Use mod_redirect instead of mod_rewrite on *any* parts of path to webdav.
1966 * (Related, use mod_auth to protect webdav root, but avoid attempting to
1967 * use mod_auth on paths underneath webdav root, as Destination is not
1968 * validated with mod_auth)
1970 * tl;dr: webdav paths and webdav properties are managed by mod_webdav,
1971 * so do not modify paths externally or else undefined behavior
1972 * or corruption may occur
1975 /* find matching URI prefix
1976 * check if remaining con->physical.rel_path matches suffix
1977 * of con->physical.basedir so that we can use it to
1978 * remap Destination physical path */
1979 size_t i, remain;
1980 sep = con->uri.path->ptr;
1981 sep2 = p->uri.path->ptr;
1982 for (i = 0; sep[i] && sep[i] == sep2[i]; ++i) ;
1983 if (sep[i] == '\0' && (sep2[i] == '\0' || sep2[i] == '/' || (i > 0 && sep[i-1] == '/'))) {
1984 /* src and dst URI match or dst is nested inside src; invalid COPY or MOVE */
1985 con->http_status = 403;
1986 return HANDLER_FINISHED;
1988 while (i != 0 && sep[--i] != '/') ; /* find matching directory path */
1989 remain = buffer_string_length(con->uri.path) - i;
1990 if (!con->conf.force_lowercase_filenames
1991 ? buffer_is_equal_right_len(con->physical.path, con->physical.rel_path, remain)
1992 :(buffer_string_length(con->physical.path) >= remain
1993 && 0 == strncasecmp(con->physical.path->ptr+buffer_string_length(con->physical.path)-remain, con->physical.rel_path->ptr+i, remain))) {
1994 /* (at this point, p->physical.rel_path is identical to (or lowercased version of) p->uri.path) */
1995 buffer_copy_string_len(p->physical.path, con->physical.path->ptr, buffer_string_length(con->physical.path)-remain);
1996 buffer_append_string_len(p->physical.path, p->physical.rel_path->ptr+i, buffer_string_length(p->physical.rel_path)-i);
1998 buffer_copy_buffer(p->physical.basedir, con->physical.basedir);
1999 buffer_append_slash(p->physical.basedir);
2000 } else {
2001 /* unable to perform physical path remap here;
2002 * assume doc_root/rel_path and no remapping */
2003 buffer_copy_buffer(p->physical.path, p->physical.doc_root);
2004 buffer_append_slash(p->physical.path);
2005 buffer_copy_buffer(p->physical.basedir, p->physical.path);
2007 /* don't add a second / */
2008 if (p->physical.rel_path->ptr[0] == '/') {
2009 buffer_append_string_len(p->physical.path, p->physical.rel_path->ptr + 1, buffer_string_length(p->physical.rel_path) - 1);
2010 } else {
2011 buffer_append_string_buffer(p->physical.path, p->physical.rel_path);
2016 /* let's see if the source is a directory
2017 * if yes, we fail with 501 */
2019 if (-1 == stat(con->physical.path->ptr, &st)) {
2020 /* don't about it yet, unlink will fail too */
2021 switch(errno) {
2022 case ENOENT:
2023 con->http_status = 404;
2024 break;
2025 default:
2026 con->http_status = 403;
2027 break;
2029 } else if (S_ISDIR(st.st_mode)) {
2030 int r;
2031 /* src is a directory */
2033 if (con->physical.path->ptr[buffer_string_length(con->physical.path)-1] != '/') {
2034 http_response_redirect_to_directory(srv, con);
2035 return HANDLER_FINISHED;
2038 if (-1 == stat(p->physical.path->ptr, &st)) {
2039 if (-1 == mkdir(p->physical.path->ptr, WEBDAV_DIR_MODE)) {
2040 con->http_status = 403;
2041 return HANDLER_FINISHED;
2043 } else if (!S_ISDIR(st.st_mode)) {
2044 if (overwrite == 0) {
2045 /* copying into a non-dir ? */
2046 con->http_status = 409;
2047 return HANDLER_FINISHED;
2048 } else {
2049 unlink(p->physical.path->ptr);
2050 if (-1 == mkdir(p->physical.path->ptr, WEBDAV_DIR_MODE)) {
2051 con->http_status = 403;
2052 return HANDLER_FINISHED;
2057 /* copy the content of src to dest */
2058 if (0 != (r = webdav_copy_dir(srv, con, p, &(con->physical), &(p->physical), overwrite))) {
2059 con->http_status = r;
2060 return HANDLER_FINISHED;
2062 if (con->request.http_method == HTTP_METHOD_MOVE) {
2063 b = buffer_init();
2064 webdav_delete_dir(srv, con, p, &(con->physical), b); /* content */
2065 buffer_free(b);
2067 rmdir(con->physical.path->ptr);
2069 con->http_status = 201;
2070 con->file_finished = 1;
2071 } else {
2072 /* it is just a file, good */
2073 int r;
2075 /* does the client have a lock for this connection ? */
2076 if (!webdav_has_lock(srv, con, p, p->uri.path)) {
2077 con->http_status = 423;
2078 return HANDLER_FINISHED;
2081 /* destination exists */
2082 if (0 == (r = stat(p->physical.path->ptr, &st))) {
2083 if (S_ISDIR(st.st_mode)) {
2084 /* file to dir/
2085 * append basename to physical path */
2087 if (NULL != (sep = strrchr(con->physical.path->ptr, '/'))) {
2088 buffer_append_string(p->physical.path, sep);
2089 r = stat(p->physical.path->ptr, &st);
2094 if (-1 == r) {
2095 con->http_status = 201; /* we will create a new one */
2096 con->file_finished = 1;
2098 switch(errno) {
2099 case ENOTDIR:
2100 con->http_status = 409;
2101 return HANDLER_FINISHED;
2103 } else if (overwrite == 0) {
2104 /* destination exists, but overwrite is not set */
2105 con->http_status = 412;
2106 return HANDLER_FINISHED;
2107 } else {
2108 con->http_status = 204; /* resource already existed */
2111 if (con->request.http_method == HTTP_METHOD_MOVE) {
2112 /* try a rename */
2114 if (0 == rename(con->physical.path->ptr, p->physical.path->ptr)) {
2115 #ifdef USE_PROPPATCH
2116 sqlite3_stmt *stmt;
2118 stmt = p->conf.stmt_move_uri;
2119 if (stmt) {
2121 sqlite3_reset(stmt);
2123 /* bind the values to the insert */
2124 sqlite3_bind_text(stmt, 1,
2125 CONST_BUF_LEN(p->uri.path),
2126 SQLITE_TRANSIENT);
2128 sqlite3_bind_text(stmt, 2,
2129 CONST_BUF_LEN(con->uri.path),
2130 SQLITE_TRANSIENT);
2132 if (SQLITE_DONE != sqlite3_step(stmt)) {
2133 log_error_write(srv, __FILE__, __LINE__, "ss", "sql-move failed:", sqlite3_errmsg(p->conf.sql));
2136 #endif
2137 return HANDLER_FINISHED;
2140 /* rename failed, fall back to COPY + DELETE */
2143 if (0 != (r = webdav_copy_file(srv, con, p, &(con->physical), &(p->physical), overwrite))) {
2144 con->http_status = r;
2146 return HANDLER_FINISHED;
2149 if (con->request.http_method == HTTP_METHOD_MOVE) {
2150 b = buffer_init();
2151 webdav_delete_file(srv, con, p, &(con->physical), b);
2152 buffer_free(b);
2156 return HANDLER_FINISHED;
2158 case HTTP_METHOD_PROPPATCH:
2159 if (p->conf.is_readonly) {
2160 con->http_status = 403;
2161 return HANDLER_FINISHED;
2164 if (!webdav_has_lock(srv, con, p, con->uri.path)) {
2165 con->http_status = 423;
2166 return HANDLER_FINISHED;
2169 /* check if destination exists */
2170 if (-1 == stat(con->physical.path->ptr, &st)) {
2171 switch(errno) {
2172 case ENOENT:
2173 con->http_status = 404;
2174 break;
2178 if (S_ISDIR(st.st_mode) && con->physical.path->ptr[buffer_string_length(con->physical.path)-1] != '/') {
2179 http_response_redirect_to_directory(srv, con);
2180 return HANDLER_FINISHED;
2183 #ifdef USE_PROPPATCH
2184 if (con->request.content_length) {
2185 xmlDocPtr xml;
2187 if (con->state == CON_STATE_READ_POST) {
2188 handler_t r = connection_handle_read_post_state(srv, con);
2189 if (r != HANDLER_GO_ON) return r;
2192 if (1 == webdav_parse_chunkqueue(srv, con, p, con->request_content_queue, &xml)) {
2193 xmlNode *rootnode = xmlDocGetRootElement(xml);
2195 if (0 == xmlStrcmp(rootnode->name, BAD_CAST "propertyupdate")) {
2196 xmlNode *cmd;
2197 char *err = NULL;
2198 int empty_ns = 0; /* send 400 on a empty namespace attribute */
2200 /* start response */
2202 if (SQLITE_OK != sqlite3_exec(p->conf.sql, "BEGIN TRANSACTION", NULL, NULL, &err)) {
2203 log_error_write(srv, __FILE__, __LINE__, "ss", "can't open transaction:", err);
2204 sqlite3_free(err);
2206 goto propmatch_cleanup;
2209 /* a UPDATE request, we know 'set' and 'remove' */
2210 for (cmd = rootnode->children; cmd; cmd = cmd->next) {
2211 xmlNode *props;
2212 /* either set or remove */
2214 if ((0 == xmlStrcmp(cmd->name, BAD_CAST "set")) ||
2215 (0 == xmlStrcmp(cmd->name, BAD_CAST "remove"))) {
2217 sqlite3_stmt *stmt;
2219 stmt = (0 == xmlStrcmp(cmd->name, BAD_CAST "remove")) ?
2220 p->conf.stmt_delete_prop : p->conf.stmt_update_prop;
2222 for (props = cmd->children; props; props = props->next) {
2223 if (0 == xmlStrcmp(props->name, BAD_CAST "prop")) {
2224 xmlNode *prop;
2225 char *propval = NULL;
2226 int r;
2228 prop = props->children;
2230 if (prop->ns &&
2231 (0 == xmlStrcmp(prop->ns->href, BAD_CAST "")) &&
2232 (0 != xmlStrcmp(prop->ns->prefix, BAD_CAST ""))) {
2233 log_error_write(srv, __FILE__, __LINE__, "ss",
2234 "no name space for:",
2235 prop->name);
2237 empty_ns = 1;
2238 break;
2241 sqlite3_reset(stmt);
2243 /* bind the values to the insert */
2245 sqlite3_bind_text(stmt, 1,
2246 CONST_BUF_LEN(con->uri.path),
2247 SQLITE_TRANSIENT);
2248 sqlite3_bind_text(stmt, 2,
2249 (char *)prop->name,
2250 strlen((char *)prop->name),
2251 SQLITE_TRANSIENT);
2252 if (prop->ns) {
2253 sqlite3_bind_text(stmt, 3,
2254 (char *)prop->ns->href,
2255 strlen((char *)prop->ns->href),
2256 SQLITE_TRANSIENT);
2257 } else {
2258 sqlite3_bind_text(stmt, 3,
2261 SQLITE_TRANSIENT);
2263 if (stmt == p->conf.stmt_update_prop) {
2264 propval = prop->children
2265 ? (char *)xmlNodeListGetString(xml, prop->children, 0)
2266 : NULL;
2268 sqlite3_bind_text(stmt, 4,
2269 propval ? propval : "",
2270 propval ? strlen(propval) : 0,
2271 SQLITE_TRANSIENT);
2274 if (SQLITE_DONE != (r = sqlite3_step(stmt))) {
2275 log_error_write(srv, __FILE__, __LINE__, "ss",
2276 "sql-set failed:", sqlite3_errmsg(p->conf.sql));
2279 if (propval) xmlFree(propval);
2282 if (empty_ns) break;
2286 if (empty_ns) {
2287 if (SQLITE_OK != sqlite3_exec(p->conf.sql, "ROLLBACK", NULL, NULL, &err)) {
2288 log_error_write(srv, __FILE__, __LINE__, "ss", "can't rollback transaction:", err);
2289 sqlite3_free(err);
2291 goto propmatch_cleanup;
2294 con->http_status = 400;
2295 } else {
2296 if (SQLITE_OK != sqlite3_exec(p->conf.sql, "COMMIT", NULL, NULL, &err)) {
2297 log_error_write(srv, __FILE__, __LINE__, "ss", "can't commit transaction:", err);
2298 sqlite3_free(err);
2300 goto propmatch_cleanup;
2302 con->http_status = 200;
2304 con->file_finished = 1;
2306 return HANDLER_FINISHED;
2309 propmatch_cleanup:
2311 xmlFreeDoc(xml);
2312 } else {
2313 con->http_status = 400;
2314 return HANDLER_FINISHED;
2317 #endif
2318 con->http_status = 501;
2319 return HANDLER_FINISHED;
2320 case HTTP_METHOD_LOCK:
2322 * a mac wants to write
2324 * LOCK /dav/expire.txt HTTP/1.1\r\n
2325 * User-Agent: WebDAVFS/1.3 (01308000) Darwin/8.1.0 (Power Macintosh)\r\n
2326 * Accept: * / *\r\n
2327 * Depth: 0\r\n
2328 * Timeout: Second-600\r\n
2329 * Content-Type: text/xml; charset=\"utf-8\"\r\n
2330 * Content-Length: 229\r\n
2331 * Connection: keep-alive\r\n
2332 * Host: 192.168.178.23:1025\r\n
2333 * \r\n
2334 * <?xml version=\"1.0\" encoding=\"utf-8\"?>\n
2335 * <D:lockinfo xmlns:D=\"DAV:\">\n
2336 * <D:lockscope><D:exclusive/></D:lockscope>\n
2337 * <D:locktype><D:write/></D:locktype>\n
2338 * <D:owner>\n
2339 * <D:href>http://www.apple.com/webdav_fs/</D:href>\n
2340 * </D:owner>\n
2341 * </D:lockinfo>\n
2344 if (depth != 0 && depth != -1) {
2345 con->http_status = 400;
2347 return HANDLER_FINISHED;
2350 #ifdef USE_LOCKS
2351 if (con->request.content_length) {
2352 xmlDocPtr xml;
2353 buffer *hdr_if = NULL;
2354 int created = 0;
2356 if (con->state == CON_STATE_READ_POST) {
2357 handler_t r = connection_handle_read_post_state(srv, con);
2358 if (r != HANDLER_GO_ON) return r;
2361 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "If"))) {
2362 hdr_if = ds->value;
2365 /* we don't support Depth: Infinity on directories */
2366 if (hdr_if == NULL && depth == -1) {
2367 if (0 != stat(con->physical.path->ptr, &st)) {
2368 if (errno == ENOENT) {
2369 int fd = open(con->physical.path->ptr, O_WRONLY|O_CREAT|O_APPEND|O_BINARY|FIFO_NONBLOCK, WEBDAV_FILE_MODE);
2370 if (fd >= 0) {
2371 close(fd);
2372 created = 1;
2373 } else {
2374 log_error_write(srv, __FILE__, __LINE__, "sBss",
2375 "create file", con->physical.path, ":", strerror(errno));
2376 con->http_status = 403; /* Forbidden */
2378 return HANDLER_FINISHED;
2381 } else if (S_ISDIR(st.st_mode)) {
2382 con->http_status = 409; /* Conflict */
2384 return HANDLER_FINISHED;
2388 if (1 == webdav_parse_chunkqueue(srv, con, p, con->request_content_queue, &xml)) {
2389 xmlNode *rootnode = xmlDocGetRootElement(xml);
2391 force_assert(rootnode);
2393 if (0 == xmlStrcmp(rootnode->name, BAD_CAST "lockinfo")) {
2394 xmlNode *lockinfo;
2395 const xmlChar *lockscope = NULL, *locktype = NULL; /* TODO: compiler says unused: *owner = NULL; */
2397 for (lockinfo = rootnode->children; lockinfo; lockinfo = lockinfo->next) {
2398 if (0 == xmlStrcmp(lockinfo->name, BAD_CAST "lockscope")) {
2399 xmlNode *value;
2400 for (value = lockinfo->children; value; value = value->next) {
2401 if ((0 == xmlStrcmp(value->name, BAD_CAST "exclusive")) ||
2402 (0 == xmlStrcmp(value->name, BAD_CAST "shared"))) {
2403 lockscope = value->name;
2404 } else {
2405 con->http_status = 400;
2407 xmlFreeDoc(xml);
2408 return HANDLER_FINISHED;
2411 } else if (0 == xmlStrcmp(lockinfo->name, BAD_CAST "locktype")) {
2412 xmlNode *value;
2413 for (value = lockinfo->children; value; value = value->next) {
2414 if ((0 == xmlStrcmp(value->name, BAD_CAST "write"))) {
2415 locktype = value->name;
2416 } else {
2417 con->http_status = 400;
2419 xmlFreeDoc(xml);
2420 return HANDLER_FINISHED;
2424 } else if (0 == xmlStrcmp(lockinfo->name, BAD_CAST "owner")) {
2428 if (lockscope && locktype) {
2429 sqlite3_stmt *stmt = p->conf.stmt_read_lock_by_uri;
2431 /* is this resourse already locked ? */
2433 /* SELECT locktoken, resource, lockscope, locktype, owner, depth, timeout
2434 * FROM locks
2435 * WHERE resource = ? */
2437 if (stmt) {
2439 sqlite3_reset(stmt);
2441 sqlite3_bind_text(stmt, 1,
2442 CONST_BUF_LEN(p->uri.path),
2443 SQLITE_TRANSIENT);
2445 /* it is the PK */
2446 while (SQLITE_ROW == sqlite3_step(stmt)) {
2447 /* we found a lock
2448 * 1. is it compatible ?
2449 * 2. is it ours */
2450 char *sql_lockscope = (char *)sqlite3_column_text(stmt, 2);
2452 if (strcmp(sql_lockscope, "exclusive")) {
2453 con->http_status = 423;
2454 } else if (0 == xmlStrcmp(lockscope, BAD_CAST "exclusive")) {
2455 /* resourse is locked with a shared lock
2456 * client wants exclusive */
2457 con->http_status = 423;
2460 if (con->http_status == 423) {
2461 xmlFreeDoc(xml);
2462 return HANDLER_FINISHED;
2466 stmt = p->conf.stmt_create_lock;
2467 if (stmt) {
2468 /* create a lock-token */
2469 uuid_t id;
2470 char uuid[37] /* 36 + \0 */;
2472 uuid_generate(id);
2473 uuid_unparse(id, uuid);
2475 buffer_copy_string_len(p->tmp_buf, CONST_STR_LEN("opaquelocktoken:"));
2476 buffer_append_string(p->tmp_buf, uuid);
2478 /* "CREATE TABLE locks ("
2479 * " locktoken TEXT NOT NULL,"
2480 * " resource TEXT NOT NULL,"
2481 * " lockscope TEXT NOT NULL,"
2482 * " locktype TEXT NOT NULL,"
2483 * " owner TEXT NOT NULL,"
2484 * " depth INT NOT NULL,"
2487 sqlite3_reset(stmt);
2489 sqlite3_bind_text(stmt, 1,
2490 CONST_BUF_LEN(p->tmp_buf),
2491 SQLITE_TRANSIENT);
2493 sqlite3_bind_text(stmt, 2,
2494 CONST_BUF_LEN(con->uri.path),
2495 SQLITE_TRANSIENT);
2497 sqlite3_bind_text(stmt, 3,
2498 (const char *)lockscope,
2499 xmlStrlen(lockscope),
2500 SQLITE_TRANSIENT);
2502 sqlite3_bind_text(stmt, 4,
2503 (const char *)locktype,
2504 xmlStrlen(locktype),
2505 SQLITE_TRANSIENT);
2507 /* owner */
2508 sqlite3_bind_text(stmt, 5,
2511 SQLITE_TRANSIENT);
2513 /* depth */
2514 sqlite3_bind_int(stmt, 6,
2515 depth);
2518 if (SQLITE_DONE != sqlite3_step(stmt)) {
2519 log_error_write(srv, __FILE__, __LINE__, "ss",
2520 "create lock:", sqlite3_errmsg(p->conf.sql));
2523 /* looks like we survived */
2524 webdav_lockdiscovery(srv, con, p->tmp_buf, (const char *)lockscope, (const char *)locktype, depth);
2526 con->http_status = created ? 201 : 200;
2527 con->file_finished = 1;
2532 xmlFreeDoc(xml);
2533 return HANDLER_FINISHED;
2534 } else {
2535 con->http_status = 400;
2536 return HANDLER_FINISHED;
2538 } else {
2540 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "If"))) {
2541 buffer *locktoken = ds->value;
2542 sqlite3_stmt *stmt = p->conf.stmt_refresh_lock;
2544 /* remove the < > around the token */
2545 if (buffer_string_length(locktoken) < 5) {
2546 con->http_status = 400;
2548 return HANDLER_FINISHED;
2551 buffer_copy_string_len(p->tmp_buf, locktoken->ptr + 2, buffer_string_length(locktoken) - 4);
2553 sqlite3_reset(stmt);
2555 sqlite3_bind_text(stmt, 1,
2556 CONST_BUF_LEN(p->tmp_buf),
2557 SQLITE_TRANSIENT);
2559 if (SQLITE_DONE != sqlite3_step(stmt)) {
2560 log_error_write(srv, __FILE__, __LINE__, "ss",
2561 "refresh lock:", sqlite3_errmsg(p->conf.sql));
2564 webdav_lockdiscovery(srv, con, p->tmp_buf, "exclusive", "write", 0);
2566 con->http_status = 200;
2567 con->file_finished = 1;
2568 return HANDLER_FINISHED;
2569 } else {
2570 /* we need a lock-token to refresh */
2571 con->http_status = 400;
2573 return HANDLER_FINISHED;
2576 break;
2577 #else
2578 con->http_status = 501;
2579 return HANDLER_FINISHED;
2580 #endif
2581 case HTTP_METHOD_UNLOCK:
2582 #ifdef USE_LOCKS
2583 if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "Lock-Token"))) {
2584 buffer *locktoken = ds->value;
2585 sqlite3_stmt *stmt = p->conf.stmt_remove_lock;
2587 /* remove the < > around the token */
2588 if (buffer_string_length(locktoken) < 3) {
2589 con->http_status = 400;
2591 return HANDLER_FINISHED;
2595 * FIXME:
2597 * if the resourse is locked:
2598 * - by us: unlock
2599 * - by someone else: 401
2600 * if the resource is not locked:
2601 * - 412
2602 * */
2604 buffer_copy_string_len(p->tmp_buf, locktoken->ptr + 1, buffer_string_length(locktoken) - 2);
2606 sqlite3_reset(stmt);
2608 sqlite3_bind_text(stmt, 1,
2609 CONST_BUF_LEN(p->tmp_buf),
2610 SQLITE_TRANSIENT);
2612 sqlite3_bind_text(stmt, 2,
2613 CONST_BUF_LEN(con->uri.path),
2614 SQLITE_TRANSIENT);
2616 if (SQLITE_DONE != sqlite3_step(stmt)) {
2617 log_error_write(srv, __FILE__, __LINE__, "ss",
2618 "remove lock:", sqlite3_errmsg(p->conf.sql));
2621 if (0 == sqlite3_changes(p->conf.sql)) {
2622 con->http_status = 401;
2623 } else {
2624 con->http_status = 204;
2626 return HANDLER_FINISHED;
2627 } else {
2628 /* we need a lock-token to unlock */
2629 con->http_status = 400;
2631 return HANDLER_FINISHED;
2633 break;
2634 #else
2635 con->http_status = 501;
2636 return HANDLER_FINISHED;
2637 #endif
2638 default:
2639 break;
2642 /* not found */
2643 return HANDLER_GO_ON;
2647 SUBREQUEST_FUNC(mod_webdav_subrequest_handler) {
2648 handler_t r;
2649 plugin_data *p = p_d;
2650 if (con->mode != p->id) return HANDLER_GO_ON;
2652 r = mod_webdav_subrequest_handler_huge(srv, con, p_d);
2653 if (con->http_status >= 400) con->mode = DIRECT;
2654 return r;
2658 PHYSICALPATH_FUNC(mod_webdav_physical_handler) {
2659 plugin_data *p = p_d;
2660 if (!p->conf.enabled) return HANDLER_GO_ON;
2662 /* physical path is setup */
2663 if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;
2665 UNUSED(srv);
2667 switch (con->request.http_method) {
2668 case HTTP_METHOD_PROPFIND:
2669 case HTTP_METHOD_PROPPATCH:
2670 case HTTP_METHOD_PUT:
2671 case HTTP_METHOD_COPY:
2672 case HTTP_METHOD_MOVE:
2673 case HTTP_METHOD_MKCOL:
2674 case HTTP_METHOD_DELETE:
2675 case HTTP_METHOD_LOCK:
2676 case HTTP_METHOD_UNLOCK:
2677 con->mode = p->id;
2678 break;
2679 default:
2680 break;
2683 return HANDLER_GO_ON;
2687 /* this function is called at dlopen() time and inits the callbacks */
2689 int mod_webdav_plugin_init(plugin *p);
2690 int mod_webdav_plugin_init(plugin *p) {
2691 p->version = LIGHTTPD_VERSION_ID;
2692 p->name = buffer_init_string("webdav");
2694 p->init = mod_webdav_init;
2695 p->handle_uri_clean = mod_webdav_uri_handler;
2696 p->handle_physical = mod_webdav_physical_handler;
2697 p->handle_subrequest = mod_webdav_subrequest_handler;
2698 p->set_defaults = mod_webdav_set_defaults;
2699 p->cleanup = mod_webdav_free;
2701 p->data = NULL;
2703 return 0;