-
Notifications
You must be signed in to change notification settings - Fork 7
/
rap.c
1643 lines (1447 loc) · 51 KB
/
rap.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "shared.h"
#include "xml.h"
//#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <dirent.h>
#include <locale.h>
#include <security/pam_appl.h>
#include <stdlib.h>
#define WEBDAV_NAMESPACE "DAV:"
#define EXTENSIONS_NAMESPACE "urn:couling-webdav:"
#define MICROSOFT_NAMESPACE "urn:schemas-microsoft-com:"
#define NEW_FILE_PERMISSIONS 0666
#define NEW_DIR_PREMISSIONS 0777
#define IS_DIR_CHILD(name) ((name)[0] != '.' || ((name)[1] != '\0' && ((name)[1] != '.' || (name)[2] != '\0')))
typedef struct MimeType {
const char * fileExtension;
const char * type;
size_t typeStringSize;
} MimeType;
// Authentication
static int authenticated = 0;
static const char * authenticatedUser;
static const char * pamService;
static const char * chrootPath;
static pam_handle_t *pamh;
// Mime Database.
static size_t mimeFileBufferSize;
static char * mimeFileBuffer;
static MimeType * mimeTypes = NULL;
static int mimeTypeCount = 0;
static MimeType UNKNOWN_MIME_TYPE = {
.fileExtension = "",
.type = "application/octet-stream",
.typeStringSize = sizeof("application/octet-stream") };
static MimeType XML_MIME_TYPE = {
.fileExtension = "",
.type = "application/xml; charset=utf-8",
.typeStringSize = sizeof("application/xml; charset=utf-8") };
static ssize_t respond(RapConstant result) {
Message message = { .mID = result, .fd = -1, .paramCount = 0 };
return sendMessage(RAP_CONTROL_SOCKET, &message);
}
static void normalizeDirName(char * buffer, const char * file, size_t * filePathSize, int isDir) {
memcpy(buffer, file, *filePathSize + 1);
if (isDir && file[*filePathSize - 1] != '/') {
buffer[*filePathSize] = '/';
(*filePathSize)++;
buffer[*filePathSize] = '\0';
}
}
static size_t formatFileSize(char * buffer, size_t bufferSize, off_t size) {
static char * suffix[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB" "EiB", "ZiB", "YiB" };
int magnitude = 0;
off_t tmpSize = size;
while (magnitude < 8 && (tmpSize & 1023) != tmpSize) {
magnitude++;
tmpSize >>= 10;
}
double divisor;
char * format;
if (magnitude > 0) {
divisor = ((off_t) 1) << (magnitude * 10);
if (tmpSize >= 100) {
format = "%.0f %s";
} else if (tmpSize >= 10) {
format = "%.1f %s";
} else {
format = "%.2f %s";
}
} else {
divisor = 1;
format = "%.0f %s";
}
double dsize = size;
dsize /= divisor;
return snprintf(buffer, bufferSize, format, dsize, suffix[magnitude]);
}
//////////
// Mime //
//////////
static int compareExt(const void * a, const void * b) {
return strcasecmp(((MimeType *) a)->fileExtension, ((MimeType *) b)->fileExtension);
}
static MimeType * findMimeType(const char * file) {
if (!file) {
return &UNKNOWN_MIME_TYPE;
}
MimeType type;
type.fileExtension = file + strlen(file) - 1;
while (1) {
if (*type.fileExtension == '/') {
return &UNKNOWN_MIME_TYPE;
} else if (*type.fileExtension == '.') {
type.fileExtension++;
break;
} else {
type.fileExtension--;
if (type.fileExtension < file) {
return &UNKNOWN_MIME_TYPE;
}
}
}
MimeType * result = bsearch(&type, mimeTypes, mimeTypeCount, sizeof(*mimeTypes), &compareExt);
return result ? result : &UNKNOWN_MIME_TYPE;
}
static void initializeMimeTypes(const char * mimeTypesFile) {
// Load Mime file into memory
mimeFileBuffer = loadFileToBuffer(mimeTypesFile, &mimeFileBufferSize);
if (!mimeFileBuffer) {
exit(1);
}
// Parse mimeFile;
char * partStartPtr = mimeFileBuffer;
int found;
char * type = NULL;
do {
found = 0;
// find the start of the part
while (partStartPtr < mimeFileBuffer + mimeFileBufferSize && !found) {
switch (*partStartPtr) {
case '#':
// skip to the end of the line
while (partStartPtr < mimeFileBuffer + mimeFileBufferSize && *partStartPtr != '\n') {
partStartPtr++;
}
// Fall through to incrementing partStartPtr
partStartPtr++;
break;
case ' ':
case '\t':
case '\r':
case '\n':
if (*partStartPtr == '\n') {
type = NULL;
}
partStartPtr++;
break;
default:
found = 1;
break;
}
}
// Find the end of the part
char * partEndPtr = partStartPtr + 1;
found = 0;
while (partEndPtr < mimeFileBuffer + mimeFileBufferSize && !found) {
switch (*partEndPtr) {
case ' ':
case '\t':
case '\r':
case '\n':
if (type == NULL) {
type = partStartPtr;
} else {
mimeTypes = reallocSafe(mimeTypes, sizeof(*mimeTypes) * (mimeTypeCount + 1));
mimeTypes[mimeTypeCount].type = type;
mimeTypes[mimeTypeCount].fileExtension = partStartPtr;
mimeTypes[mimeTypeCount].typeStringSize = partEndPtr - partStartPtr + 1;
mimeTypeCount++;
}
if (*partEndPtr == '\n') {
type = NULL;
}
*partEndPtr = '\0';
found = 1;
break;
default:
partEndPtr++;
break;
}
}
partStartPtr = partEndPtr + 1;
} while (partStartPtr < mimeFileBuffer + mimeFileBufferSize);
qsort(mimeTypes, mimeTypeCount, sizeof(*mimeTypes), &compareExt);
}
//////////////
// End Mime //
//////////////
////////////////////
// Error Response //
////////////////////
static ssize_t writeErrorResponse(RapConstant responseCode, const char * textError, const char * error,
const char * file) {
int pipeEnds[2];
if (pipe(pipeEnds)) {
stdLogError(errno, "Could not create pipe to write content");
return respond(RAP_RESPOND_INTERNAL_ERROR);
}
time_t fileTime;
time(&fileTime);
Message message = { .mID = responseCode, .fd = pipeEnds[PIPE_READ], .paramCount = 2 };
message.params[RAP_PARAM_RESPONSE_DATE] = toMessageParam(fileTime);
message.params[RAP_PARAM_RESPONSE_MIME] = makeMessageParam(XML_MIME_TYPE.type,
XML_MIME_TYPE.typeStringSize);
message.params[RAP_PARAM_RESPONSE_LOCATION] = stringToMessageParam(file);
ssize_t messageResult = sendMessage(RAP_CONTROL_SOCKET, &message);
if (messageResult <= 0) {
close(pipeEnds[PIPE_WRITE]);
return messageResult;
}
// We've set up the pipe and sent read end across so now write the result
xmlTextWriterPtr writer = xmlNewFdTextWriter(pipeEnds[PIPE_WRITE]);
xmlTextWriterStartDocument(writer, "1.0", "utf-8", NULL);
xmlTextWriterStartElementNS(writer, "d", "error", WEBDAV_NAMESPACE);
xmlTextWriterWriteAttributeNS(writer, "xmlns", "x", NULL, EXTENSIONS_NAMESPACE);
if (error) {
xmlTextWriterStartElementNS(writer, "d", error, NULL);
xmlTextWriterStartElementNS(writer, "d", "href", NULL);
xmlTextWriterWriteURL(writer, file);
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
}
if (textError) {
xmlTextWriterStartElementNS(writer, "x", "text-error", NULL);
xmlTextWriterStartElementNS(writer, "x", "href", NULL);
xmlTextWriterWriteURL(writer, file);
xmlTextWriterWriteElementString(writer, "x", "text", textError);
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
}
xmlTextWriterEndElement(writer);
xmlFreeTextWriter(writer);
return messageResult;
}
////////////////////////
// End Error Response //
////////////////////////
//////////
// LOCK //
//////////
typedef struct LockRequest {
int isNewLock;
LockType type;
} LockRequest;
static void parseLockRequest(int fd, LockRequest * lockRequest) {
memset(lockRequest, 0, sizeof(LockRequest));
if (fd == -1) return;
xmlTextReaderPtr reader = xmlReaderForFd(fd, NULL, NULL, XML_PARSE_NOENT);
xmlReaderSuppressErrors(reader);
if (!reader || !stepInto(reader) || !elementMatches(reader, WEBDAV_NAMESPACE, "lockinfo")) {
if (reader) xmlFreeTextReader(reader);
close(fd);
return;
}
lockRequest->isNewLock = 1;
int readResult = stepInto(reader);
while (readResult && xmlTextReaderDepth(reader) == 1) {
if (isNamespaceElement(reader, WEBDAV_NAMESPACE)) {
const char * nodeName = xmlTextReaderConstLocalName(reader);
if (!strcmp(nodeName, "lockscope")) {
readResult = stepInto(reader);
while (readResult && xmlTextReaderDepth(reader) == 2) {
if (isNamespaceElement(reader, WEBDAV_NAMESPACE)) {
nodeName = xmlTextReaderConstLocalName(reader);
if (!strcmp(nodeName, "shared")) {
if (lockRequest->type != LOCK_TYPE_EXCLUSIVE) {
lockRequest->type = LOCK_TYPE_SHARED;
}
} else if (!strcmp(nodeName, "exclusive")) {
lockRequest->type = LOCK_TYPE_EXCLUSIVE;
}
}
readResult = stepOver(reader);
}
} else if (!strcmp(nodeName, "locktype")) {
readResult = stepInto(reader);
while (readResult && xmlTextReaderDepth(reader) == 2) {
if (isNamespaceElement(reader, WEBDAV_NAMESPACE)) {
nodeName = xmlTextReaderConstLocalName(reader);
if (!strcmp(nodeName, "read") && lockRequest->type != LOCK_TYPE_EXCLUSIVE) {
lockRequest->type = LOCK_TYPE_SHARED;
} else if (!strcmp(nodeName, "write")) {
lockRequest->type = LOCK_TYPE_EXCLUSIVE;
}
}
readResult = stepOver(reader);
}
} else {
readResult = stepOver(reader);
}
}
}
// finish up
while (readResult) {
readResult = stepOver(reader);
}
xmlFreeTextReader(reader);
close(fd);
}
static ssize_t writeLockResponse(const char * fileName, LockRequest * request, const char * lockToken,
time_t timeout) {
int pipeEnds[2];
if (pipe(pipeEnds)) {
stdLogError(errno, "Could not create pipe to write content");
return respond(RAP_RESPOND_INTERNAL_ERROR);
}
time_t fileTime;
time(&fileTime);
Message message = { .mID = RAP_RESPOND_OK, .fd = pipeEnds[PIPE_READ], .paramCount = 2 };
message.params[RAP_PARAM_RESPONSE_DATE] = toMessageParam(fileTime);
message.params[RAP_PARAM_RESPONSE_MIME] = makeMessageParam(XML_MIME_TYPE.type,
XML_MIME_TYPE.typeStringSize);
message.params[RAP_PARAM_RESPONSE_LOCATION] = stringToMessageParam(fileName);
ssize_t messageResult = sendMessage(RAP_CONTROL_SOCKET, &message);
if (messageResult <= 0) {
close(pipeEnds[PIPE_WRITE]);
return messageResult;
}
// We've set up the pipe and sent read end across so now write the result
xmlTextWriterPtr writer = xmlNewFdTextWriter(pipeEnds[PIPE_WRITE]);
xmlTextWriterStartDocument(writer, "1.0", "utf-8", NULL);
xmlTextWriterStartElementNS(writer, "d", "prop", WEBDAV_NAMESPACE);
xmlTextWriterStartElementNS(writer, "d", "lockdiscovery", NULL);
xmlTextWriterStartElementNS(writer, "d", "activelock", NULL);
// <d:locktype><d:write></d:locktype>
xmlTextWriterStartElementNS(writer, "d", "locktype", NULL);
xmlTextWriterWriteElementString(writer, "d", (request->type == LOCK_TYPE_EXCLUSIVE ? "write" : "read"),
NULL);
xmlTextWriterEndElement(writer);
// <d:lockscope><d:exclusive></d:lockscope>
xmlTextWriterStartElementNS(writer, "d", "lockscope", NULL);
xmlTextWriterWriteElementString(writer, "d",
(request->type == LOCK_TYPE_EXCLUSIVE ? "exclusive" : "shared"), NULL);
xmlTextWriterEndElement(writer);
// <d:depth>Infinity</d:depth>
xmlTextWriterWriteElementString(writer, "d", "depth", "infinity");
// <d:owner>Bob</d:owner>
xmlTextWriterWriteElementString(writer, "d", "owner", authenticatedUser);
// <d:lockroot><d:href>/foo/bar</d:lockroot></d:href>
xmlTextWriterStartElementNS(writer, "d", "lockroot", NULL);
xmlTextWriterStartElementNS(writer, "d", "href", NULL);
xmlTextWriterWriteURL(writer, fileName);
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
// <d:locktoken><d:href>urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4</d:href></d:locktoken>
xmlTextWriterStartElementNS(writer, "d", "locktoken", NULL);
xmlTextWriterStartElementNS(writer, "d", "href", NULL);
xmlTextWriterWriteFormatString(writer, LOCK_TOKEN_URN_PREFIX "%s", lockToken);
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
xmlTextWriterStartElement(writer, "d:timeout");
xmlTextWriterWriteFormatString(writer, "Second-%d", (int) timeout);
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
xmlFreeTextWriter(writer);
return messageResult;
}
static ssize_t lockFile(Message * message) {
const char * file = messageParamToString(&message->params[RAP_PARAM_REQUEST_FILE]);
LockProvisions providedLock = messageParamTo(LockProvisions, message->params[RAP_PARAM_REQUEST_LOCK]);
//const char * depth = messageParamToString(&message->params[RAP_PARAM_REQUEST_DEPTH]);
//if (depth == NULL) depth = "infinity";
respond(RAP_RESPOND_CONTINUE);
LockRequest lockRequest;
parseLockRequest(message->fd, &lockRequest);
Message interimMessage;
char incomingBuffer[INCOMING_BUFFER_SIZE];
ssize_t ioResponse;
if (lockRequest.isNewLock) {
if (providedLock.source) {
// Lock token must be empty but isn't
stdLogError(0, "lock token \"If\" header provided for new lock");
return writeErrorResponse(RAP_RESPOND_BAD_CLIENT_REQUEST,
"lock token \"If\" header provided for new lock", "lock-token-submitted", file);
}
int openFlags = (lockRequest.type == LOCK_TYPE_EXCLUSIVE ? O_WRONLY | O_CREAT : O_RDONLY);
interimMessage.fd = open(file, openFlags, NEW_FILE_PERMISSIONS);
if (interimMessage.fd == -1) {
int e = errno;
stdLogError(e, "Could not open file for lock %s", file);
switch (e) {
case EACCES:
return writeErrorResponse(RAP_RESPOND_ACCESS_DENIED, strerror(e), NULL, file);
case ENOENT:
return writeErrorResponse(RAP_RESPOND_NOT_FOUND, strerror(e), NULL, file);
default:
return writeErrorResponse(RAP_RESPOND_NOT_FOUND, strerror(e), NULL, file);
}
}
struct stat s;
fstat(interimMessage.fd, &s);
if ((s.st_mode & S_IFMT) != S_IFREG) {
stdLogError(0, "Refusing to lock non-regular file %s", file);
close(interimMessage.fd);
return writeErrorResponse(RAP_RESPOND_CONFLICT, "Refusing to non-regular file", NULL, file);
}
if (flock(interimMessage.fd, lockRequest.type | LOCK_NB) == -1) {
int e = errno;
stdLogError(e, "Could not lock file %s", file);
close(interimMessage.fd);
return writeErrorResponse(RAP_RESPOND_LOCKED, strerror(e), "no-conflicting-lock", file);
}
interimMessage.mID = RAP_INTERIM_RESPOND_LOCK;
interimMessage.paramCount = 2;
interimMessage.params[RAP_PARAM_LOCK_LOCATION] = message->params[RAP_PARAM_REQUEST_FILE];
interimMessage.params[RAP_PARAM_LOCK_TYPE] = toMessageParam(lockRequest.type);
} else {
if (!providedLock.source) {
// Lock token must not be empty
return writeErrorResponse(RAP_RESPOND_BAD_CLIENT_REQUEST,
"No lock tokent submitted for refresh request", "lock-token-submitted", file);
}
interimMessage.mID = RAP_INTERIM_RESPOND_RELOCK;
interimMessage.fd = -1;
interimMessage.paramCount = 1;
interimMessage.params[RAP_PARAM_LOCK_LOCATION] = message->params[RAP_PARAM_REQUEST_FILE];
}
ioResponse = sendRecvMessage(RAP_CONTROL_SOCKET, &interimMessage, incomingBuffer, INCOMING_BUFFER_SIZE);
if (ioResponse <= 0) return ioResponse;
if (interimMessage.mID == RAP_COMPLETE_REQUEST_LOCK) {
const char * lockToken = messageParamToString(&interimMessage.params[RAP_PARAM_LOCK_TOKEN]);
time_t timeout = messageParamTo(time_t, interimMessage.params[RAP_PARAM_LOCK_TIMEOUT]);
return writeLockResponse(file, &lockRequest, lockToken, timeout);
} else {
const char * reason = messageParamToString(&interimMessage.params[RAP_PARAM_ERROR_REASON]);
const char * davReason = messageParamToString(&interimMessage.params[RAP_PARAM_ERROR_DAV_REASON]);
//const char * errorNamespace = messageParamToString(&interimMessage.params[RAP_PARAM_ERROR_NAMESPACE]);
return writeErrorResponse(interimMessage.mID, reason, davReason, file);
}
}
//////////////
// End Lock //
//////////////
//////////////
// PROPFIND //
//////////////
#define PROPFIND_RESOURCE_TYPE "resourcetype"
#define PROPFIND_CREATION_DATE "creationdate"
#define PROPFIND_CONTENT_LENGTH "getcontentlength"
#define PROPFIND_LAST_MODIFIED "getlastmodified"
#define PROPFIND_DISPLAY_NAME "displayname"
#define PROPFIND_CONTENT_TYPE "getcontenttype"
#define PROPFIND_USED_BYTES "quota-used-bytes"
#define PROPFIND_AVAILABLE_BYTES "quota-available-bytes"
#define PROPFIND_ETAG "getetag"
#define PROPFIND_WINDOWS_ATTRIBUTES "Win32FileAttributes"
typedef struct PropertySet {
char creationDate;
char displayName;
char contentLength;
char contentType;
char etag;
char lastModified;
char resourceType;
char usedBytes;
char availableBytes;
char windowsHidden;
} PropertySet;
static int parsePropFind(int fd, PropertySet * properties) {
xmlTextReaderPtr reader = xmlReaderForFd(fd, NULL, NULL, XML_PARSE_NOENT);
xmlReaderSuppressErrors(reader);
int readResult;
if (!reader || !stepInto(reader)) {
stdLogError(0, "could not create xml reader");
if (reader) xmlFreeTextReader(reader);
close(fd);
return 0;
}
if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_NONE) {
// No body has been sent
// so assume the client is asking for everything.
memset(properties, 1, sizeof(*properties));
xmlFreeTextReader(reader);
close(fd);
return 1;
} else {
memset(properties, 0, sizeof(PropertySet));
}
if (!elementMatches(reader, WEBDAV_NAMESPACE, "propfind")) {
stdLogError(0, "Request body was not a propfind document");
xmlFreeTextReader(reader);
close(fd);
return 0;
}
readResult = stepInto(reader);
while (readResult && xmlTextReaderDepth(reader) > 0 && !elementMatches(reader, WEBDAV_NAMESPACE, "prop")) {
stepOver(reader);
}
if (!readResult) {
xmlFreeTextReader(reader);
close(fd);
return 0;
}
readResult = stepInto(reader);
while (readResult && xmlTextReaderDepth(reader) > 1) {
if (!strcmp(xmlTextReaderConstNamespaceUri(reader), WEBDAV_NAMESPACE)) {
const char * nodeName = xmlTextReaderConstLocalName(reader);
if (!strcmp(nodeName, PROPFIND_RESOURCE_TYPE)) {
properties->resourceType = 1;
} else if (!strcmp(nodeName, PROPFIND_CREATION_DATE)) {
properties->creationDate = 1;
} else if (!strcmp(nodeName, PROPFIND_CONTENT_LENGTH)) {
properties->contentLength = 1;
} else if (!strcmp(nodeName, PROPFIND_LAST_MODIFIED)) {
properties->lastModified = 1;
} else if (!strcmp(nodeName, PROPFIND_DISPLAY_NAME)) {
properties->displayName = 1;
} else if (!strcmp(nodeName, PROPFIND_CONTENT_TYPE)) {
properties->contentType = 1;
} else if (!strcmp(nodeName, PROPFIND_AVAILABLE_BYTES)) {
properties->availableBytes = 1;
} else if (!strcmp(nodeName, PROPFIND_USED_BYTES)) {
properties->usedBytes = 1;
} else if (!strcmp(nodeName, PROPFIND_ETAG)) {
properties->etag = 1;
}
} else if (!strcmp(xmlTextReaderConstNamespaceUri(reader), MICROSOFT_NAMESPACE)) {
const char * nodeName = xmlTextReaderConstLocalName(reader);
if (!strcmp(nodeName, PROPFIND_WINDOWS_ATTRIBUTES)) {
properties->windowsHidden = 1;
}
}
readResult = stepOver(reader);
}
readResult = 1;
// finish up
while (stepOver(reader))
// consume the rest of the input
;
xmlFreeTextReader(reader);
close(fd);
return readResult;
}
static void writePropFindResponsePart(const char * fileName, const char * displayName,
PropertySet * properties, struct stat * fileStat, xmlTextWriterPtr writer) {
xmlTextWriterStartElementNS(writer, "d", "response", NULL);
xmlTextWriterStartElementNS(writer, "d", "href", NULL);
xmlTextWriterWriteURL(writer, fileName);
xmlTextWriterEndElement(writer);
xmlTextWriterStartElementNS(writer, "d", "propstat", NULL);
xmlTextWriterStartElementNS(writer, "d", "prop", NULL);
if (properties->etag) {
char buffer[200];
snprintf(buffer, sizeof(buffer), "%lld-%lld", (long long) fileStat->st_size,
(long long) fileStat->st_mtime);
xmlTextWriterWriteElementString(writer, "d", PROPFIND_ETAG, buffer);
}
if (properties->creationDate) {
char buffer[100];
getWebDate(fileStat->st_ctime, buffer, 100);
xmlTextWriterWriteElementString(writer, "d", PROPFIND_CREATION_DATE, buffer);
}
if (properties->lastModified) {
char buffer[100];
getWebDate(fileStat->st_ctime, buffer, 100);
xmlTextWriterWriteElementString(writer, "d", PROPFIND_LAST_MODIFIED, buffer);
}
if (properties->resourceType) {
xmlTextWriterStartElementNS(writer, "d", PROPFIND_RESOURCE_TYPE, NULL);
if ((fileStat->st_mode & S_IFMT) == S_IFDIR) {
xmlTextWriterStartElementNS(writer, "d", "collection", NULL);
xmlTextWriterEndElement(writer);
}
xmlTextWriterEndElement(writer);
}
//if (properties->displayName) {
// xmlTextWriterWriteElementString(writer, PROPFIND_DISPLAY_NAME, displayName);
//}
if ((fileStat->st_mode & S_IFMT) == S_IFDIR) {
struct statvfs fsStat;
if ((properties->availableBytes || properties->usedBytes) && statvfs(fileName, &fsStat) != -1) {
if (properties->availableBytes) {
char buffer[100];
unsigned long long size = fsStat.f_bavail * fsStat.f_bsize;
snprintf(buffer, sizeof(buffer), "%llu", size);
xmlTextWriterWriteElementString(writer, "d", PROPFIND_AVAILABLE_BYTES, buffer);
if (properties->usedBytes) {
size = (fsStat.f_blocks - fsStat.f_bfree) * fsStat.f_bsize;
snprintf(buffer, sizeof(buffer), "%llu", size);
xmlTextWriterWriteElementString(writer, "d", PROPFIND_USED_BYTES, buffer);
}
}
if (properties->usedBytes) {
char buffer[100];
unsigned long long size = (fsStat.f_blocks - fsStat.f_bfree) * fsStat.f_bsize;
snprintf(buffer, sizeof(buffer), "%llu", size);
xmlTextWriterWriteElementString(writer, "d", PROPFIND_USED_BYTES, buffer);
}
// When listing directories we only list this FS space in the directory not its children.
// It's not technically standards compliant but is is not likely to cause a problem in practice.
properties->availableBytes = 0;
properties->usedBytes = 0;
}
if (properties->windowsHidden) {
xmlTextWriterWriteElementString(writer, "z", PROPFIND_WINDOWS_ATTRIBUTES,
displayName[0] == '.' ? "00000012" : "00000010");
}
} else {
if (properties->contentLength) {
char buffer[100];
snprintf(buffer, sizeof(buffer), "%lld", (long long) fileStat->st_size);
xmlTextWriterWriteElementString(writer, "d", PROPFIND_CONTENT_LENGTH, buffer);
}
if (properties->contentType) {
xmlTextWriterWriteElementString(writer, "d", PROPFIND_CONTENT_TYPE, findMimeType(fileName)->type);
}
if (properties->windowsHidden) {
xmlTextWriterWriteElementString(writer, "z", PROPFIND_WINDOWS_ATTRIBUTES,
displayName[0] == '.' ? "00000022" : "00000020");
}
}
xmlTextWriterEndElement(writer);
xmlTextWriterWriteElementString(writer, "d", "status", "HTTP/1.1 200 OK");
xmlTextWriterEndElement(writer);
xmlTextWriterEndElement(writer);
}
static int respondToPropFind(const char * file, LockType lockProvided, PropertySet * properties, int depth) {
size_t fileNameSize = strlen(file);
size_t filePathSize = fileNameSize;
if (fileNameSize > MAX_VARABLY_DEFINED_ARRAY) {
stdLogError(0, "URI was too large to process %zd", fileNameSize);
return writeErrorResponse(RAP_RESPOND_URI_TOO_LARGE, "URI was too large to process", NULL, file);
}
struct stat fileStat;
int fd = open(file, O_RDONLY);
if (fd == -1 || fstat(fd, &fileStat) == -1) {
int e = errno;
if (fd != -1) close(fd);
switch (e) {
case EACCES:
stdLogError(e, "PROPFIND access denied %s %s", authenticatedUser, file);
return writeErrorResponse(RAP_RESPOND_ACCESS_DENIED, strerror(e), NULL, file);
case ENOENT:
default:
stdLogError(e, "PROPFIND not found %s %s", authenticatedUser, file);
return writeErrorResponse(RAP_RESPOND_NOT_FOUND, strerror(e), NULL, file);
}
}
char filePath[filePathSize + 2];
normalizeDirName(filePath, file, &filePathSize, (fileStat.st_mode & S_IFMT) == S_IFDIR);
int pipeEnds[2];
if (pipe(pipeEnds)) {
close(fd);
stdLogError(errno, "Could not create pipe to write content");
return respond(RAP_RESPOND_INTERNAL_ERROR);
}
const char * displayName = &file[fileNameSize - 2];
while (displayName >= file && *displayName != '/') {
displayName--;
}
displayName++;
time_t fileTime;
time(&fileTime);
Message message = { .mID = RAP_RESPOND_MULTISTATUS, .fd = pipeEnds[PIPE_READ], .paramCount = 2 };
message.params[RAP_PARAM_RESPONSE_DATE] = toMessageParam(fileTime);
message.params[RAP_PARAM_RESPONSE_MIME] = makeMessageParam(XML_MIME_TYPE.type,
XML_MIME_TYPE.typeStringSize);
message.params[RAP_PARAM_RESPONSE_LOCATION] = makeMessageParam(filePath, filePathSize + 1);
ssize_t messageResult = sendMessage(RAP_CONTROL_SOCKET, &message);
if (messageResult <= 0) {
freeSafe(filePath);
close(pipeEnds[PIPE_WRITE]);
close(fd);
return messageResult;
}
// We've set up the pipe and sent read end across so now write the result
xmlTextWriterPtr writer = xmlNewFdTextWriter(pipeEnds[PIPE_WRITE]);
DIR * dir;
xmlTextWriterStartDocument(writer, "1.0", "utf-8", NULL);
xmlTextWriterStartElementNS(writer, "d", "multistatus", WEBDAV_NAMESPACE);
xmlTextWriterWriteAttribute(writer, "xmlns:z", MICROSOFT_NAMESPACE);
writePropFindResponsePart(filePath, displayName, properties, &fileStat, writer);
if (depth > 1 && (fileStat.st_mode & S_IFMT) == S_IFDIR && (dir = fdopendir(fd))) {
struct dirent * dp;
char * childFileName = mallocSafe(filePathSize + 257);
size_t maxSize = 255;
memcpy(childFileName, filePath, filePathSize);
while ((dp = readdir(dir)) != NULL) {
if (IS_DIR_CHILD(dp->d_name)) {
size_t nameSize = strlen(dp->d_name);
if (nameSize > maxSize) {
childFileName = reallocSafe(childFileName, filePathSize + nameSize + 2);
maxSize = nameSize;
}
strcpy(childFileName + filePathSize, dp->d_name);
if (!stat(childFileName, &fileStat)) {
if ((fileStat.st_mode & S_IFMT) == S_IFDIR) {
childFileName[filePathSize + nameSize] = '/';
childFileName[filePathSize + nameSize + 1] = '\0';
}
writePropFindResponsePart(childFileName, dp->d_name, properties, &fileStat, writer);
}
}
}
closedir(dir);
freeSafe(childFileName);
} else {
close(fd);
}
xmlTextWriterEndElement(writer);
xmlFreeTextWriter(writer);
return messageResult;
}
static ssize_t propfind(Message * requestMessage) {
if (requestMessage->paramCount != 3) {
stdLogError(0, "PROPFIND request did not provide correct buffers: %d buffer(s)",
requestMessage->paramCount);
close(requestMessage->fd);
return respond(RAP_RESPOND_INTERNAL_ERROR);
}
char * file = messageParamToString(&requestMessage->params[RAP_PARAM_REQUEST_FILE]);
char * depthString = messageParamToString(&requestMessage->params[RAP_PARAM_REQUEST_DEPTH]);
LockProvisions lockProvisions = messageParamTo(LockProvisions,
requestMessage->params[RAP_PARAM_REQUEST_LOCK]);
if (!depthString) depthString = "1";
PropertySet properties;
if (requestMessage->fd == -1) {
memset(&properties, 1, sizeof(properties));
} else {
int ret = respond(RAP_RESPOND_CONTINUE);
if (ret < 0) {
return ret;
}
if (!parsePropFind(requestMessage->fd, &properties)) {
return respond(RAP_RESPOND_BAD_CLIENT_REQUEST);
}
}
return respondToPropFind(file, lockProvisions.source, &properties, (strcmp("0", depthString) ? 2 : 1));
}
//////////////////
// End PROPFIND //
//////////////////
///////////////
// PROPPATCH //
///////////////
static ssize_t proppatch(Message * requestMessage) {
if (requestMessage->fd != -1) {
respond(RAP_RESPOND_CONTINUE);
char buffer[BUFFER_SIZE];
ssize_t bytesRead;
while ((bytesRead = read(requestMessage->fd, buffer, sizeof(buffer))) > 0) {
//ssize_t __attribute__ ((unused)) ignored = write(STDERR_FILENO, buffer, bytesRead);
}
//char c = '\n';
//ssize_t __attribute__ ((unused)) ignored = write(STDOUT_FILENO, &c, 1);
close(requestMessage->fd);
PropertySet p;
memset(&p, 1, sizeof(p));
const char * file = messageParamToString(&requestMessage->params[RAP_PARAM_REQUEST_FILE]);
return respondToPropFind(file, LOCK_TYPE_SHARED, &p, 1);
} else {
return respond(RAP_RESPOND_BAD_CLIENT_REQUEST);
}
}
///////////////////
// End PROPPATCH //
///////////////////
///////////
// MKCOL //
///////////
static ssize_t mkcol(Message * requestMessage) {
if (requestMessage->fd != -1) {
// stdLogError(0, "MKCOL request sent incoming data!");
close(requestMessage->fd);
}
const char * fileName = messageParamToString(&requestMessage->params[RAP_PARAM_REQUEST_FILE]);
if (mkdir(fileName, NEW_DIR_PREMISSIONS) == -1) {
int e = errno;
stdLogError(e, "MKCOL Can not create directory %s", fileName);
switch (e) {
case EACCES:
return writeErrorResponse(RAP_RESPOND_ACCESS_DENIED, strerror(e), NULL, fileName);
case ENOSPC:
case EDQUOT:
return writeErrorResponse(RAP_RESPOND_INSUFFICIENT_STORAGE, strerror(e), NULL, fileName);
case ENOENT:
case EPERM:
case EEXIST:
case ENOTDIR:
default:
return writeErrorResponse(RAP_RESPOND_CONFLICT, strerror(e), NULL, fileName);
}
}
return respond(RAP_RESPOND_CREATED);
}
///////////////
// End MKCOL //
///////////////
//////////
// COPY //
//////////
typedef struct FileCopyData {
struct FileCopyData * next;
const char * source;
const char * target;
size_t sourceNameLength;
size_t targetNameLength;
int type;
} FileCopyData;
static ssize_t copyErrorCleanup(FileCopyData * files, const char * action, const char * source,
const char * target) {
int e = errno;
while (files) {
if (files->type == S_IFDIR) rmdir(files->target);
else unlink(files->target);
FileCopyData * next = files->next;
freeSafe(files);
files = next;
}
stdLogError(e, "Could not %s file %s to %s", action, source, target);
switch (e) {
case EPERM:
case EACCES:
return writeErrorResponse(RAP_RESPOND_ACCESS_DENIED, strerror(e), NULL, source);
case ENOSPC:
case EDQUOT:
return writeErrorResponse(RAP_RESPOND_INSUFFICIENT_STORAGE, strerror(e), NULL, source);
case ENOENT:
case ENOTDIR:
return writeErrorResponse(RAP_RESPOND_NOT_FOUND, strerror(e), NULL, source);
default:
return writeErrorResponse(RAP_RESPOND_CONFLICT, strerror(e), NULL, source);
}
}
// Copies the head of the copied list and pushes more onto this is a direcory.
// If the copy fails the item is popped of the head of the list
// If the copy succeeds and is a file then the list is unchanged except that ->type will be set.
// If the copy succeeds and is a directory then copied child members are added to the head.
static int copyFileRecursive(FileCopyData ** copied) {
// We are given the file to copy at the head of the "copied" list.
FileCopyData * toCopy = *copied;
struct stat fileStat;
if (lstat(toCopy->source, &fileStat) == -1) goto error_exit;
toCopy->type = fileStat.st_mode & S_IFMT;
int mode = fileStat.st_mode & 0777;
switch (toCopy->type) {
case S_IFREG: {
int oldFd = open(toCopy->source, O_RDONLY);
if (oldFd == -1) goto error_exit;
int newFd = open(toCopy->target, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (newFd == -1) {
close(oldFd);
goto error_exit;
}
char readBuffer[BUFFER_SIZE];
ssize_t bytesRead = 0;
ssize_t bytesWritten = 0;
while ((bytesRead == bytesWritten) && ((bytesRead = read(oldFd, readBuffer, BUFFER_SIZE)) > 0)) {
bytesWritten = write(newFd, readBuffer, bytesRead);
}
close(oldFd);
close(newFd);
if (bytesRead != 0) return 0;
chmod(toCopy->target, mode);
break;
}
case S_IFDIR: {
if (mkdir(toCopy->target, 0700) == -1) {
goto error_exit;
} else {
DIR * dir = opendir(toCopy->source);
if (!dir) return 0;
for (struct dirent * entry = readdir(dir); entry; entry = readdir(dir)) {
if (!IS_DIR_CHILD(entry->d_name)) continue;
size_t childNameLength = strlen(entry->d_name);
FileCopyData * childToCopy = mallocSafe(
sizeof(FileCopyData) + toCopy->sourceNameLength + childNameLength
+ toCopy->targetNameLength + childNameLength + 2);
// store the source right after the structure
size_t size = toCopy->sourceNameLength + childNameLength + 1;
char * ptr = (char *) (childToCopy + 1);
memcpy(ptr, toCopy->source, toCopy->sourceNameLength);
ptr[toCopy->sourceNameLength - 1] = '/';
memcpy(ptr + toCopy->sourceNameLength, entry->d_name, childNameLength + 1);
childToCopy->source = ptr;
childToCopy->sourceNameLength = size;
size = toCopy->targetNameLength + childNameLength + 1;
ptr += childToCopy->sourceNameLength;
memcpy(ptr, toCopy->target, toCopy->targetNameLength);
ptr[toCopy->targetNameLength - 1] = '/';
memcpy(ptr + toCopy->targetNameLength, entry->d_name, childNameLength + 1);
childToCopy->target = ptr;
childToCopy->targetNameLength = size;
childToCopy->next = *copied;
*copied = childToCopy;
if (!copyFileRecursive(copied)) {
closedir(dir);
return 0;
}
}
closedir(dir);
chmod(toCopy->target, mode);