-
Notifications
You must be signed in to change notification settings - Fork 7
/
webdavd.c
2057 lines (1806 loc) · 63.1 KB
/
webdavd.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
// TODO accept suggested timeout values from clients during LOCK requests
#include "shared.h"
#include "configuration.h"
#include <errno.h>
#include <fcntl.h>
#include <gnutls/abstract.h>
#include <microhttpd.h>
#include <pthread.h>
#include <search.h>
#include <semaphore.h>
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <uuid/uuid.h>
////////////////
// Structures //
////////////////
#define MAX_SESSION_LOCKS 10
typedef char LockToken[37];
typedef struct Lock {
const char * user;
const char * file;
time_t lockAcquired;
LockType type;
int fd;
int useCount;
int released;
LockToken lockToken;
} Lock;
typedef struct MHD_Connection Request;
typedef struct MHD_Response Response;
typedef struct RAP {
// Managed by create / destroy RAP
int pid;
int socketFd;
const char * user;
const char * password;
const char * clientIp;
// Managed by RAP DB
time_t rapCreated;
struct RAP * next;
struct RAP ** prevPtr;
// Managed per request
// This is not really data about the rap at all but storing it here saves allocating an extra structure
int requestWriteDataFd; // Should be closed by uploadComplete()
int requestReadDataFd; // Should be closed by processNewRequest() when sent to the RAP.
int requestResponseAlreadyGiven;
Response * requestResponseObjectAlreadyGiven;
int requestLockCount;
Lock * requestLock[MAX_SESSION_LOCKS];
} RAP;
typedef struct RapList {
RAP * firstRapSession;
} RapList;
typedef struct Header {
const char * key;
const char * value;
} Header;
typedef struct SSLCertificate {
const char * hostname;
int certCount;
gnutls_pcert_st * certs;
gnutls_privkey_t key;
} SSLCertificate;
typedef struct FDResponseData {
int fd;
off_t pos;
off_t offset;
off_t size;
RAP * session;
} FDResponseData;
////////////////////
// End Structures //
////////////////////
// Used as a place holder for failed auth requests which failed due to invalid credentials
static const RAP AUTH_FAILED_RAP = {
.pid = 0,
.socketFd = -1,
.user = "<auth failed>",
.requestWriteDataFd = -1,
.requestReadDataFd = -1,
.requestResponseAlreadyGiven = 401,
.requestLockCount = 0,
.next = NULL,
.prevPtr = NULL };
// Used as a place holder for failed auth requests which failed due to errors
static const RAP AUTH_ERROR_RAP = {
.pid = 0,
.socketFd = -1,
.user = "<auth error>",
.requestWriteDataFd = -1,
.requestReadDataFd = -1,
.requestResponseAlreadyGiven = 500,
.requestLockCount = 0,
.next = NULL,
.prevPtr = NULL };
static pthread_key_t rapDBThreadKey;
static sem_t rapPoolLock;
static RapList rapPool;
#define AUTH_FAILED ( ( RAP *) &AUTH_FAILED_RAP )
#define AUTH_ERROR ( ( RAP *) &AUTH_ERROR_RAP )
#define AUTH_SUCCESS(rap) (rap != AUTH_FAILED && rap != AUTH_ERROR)
static time_t lockExpiryTime;
static int lockReadyForReleaseCount;
static Lock ** readyForRelease;
// TODO create shutdown routine
static int shuttingDown = 0;
#define ACCEPT_HEADER "OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, LOCK, UNLOCK"
static Response * INTERNAL_SERVER_ERROR_PAGE;
static Response * UNAUTHORIZED_PAGE;
static Response * METHOD_NOT_SUPPORTED_PAGE;
static Response * NO_CONTENT_PAGE;
static const char * FORBIDDEN_PAGE;
static const char * NOT_FOUND_PAGE;
static const char * BAD_REQUEST_PAGE;
static const char * INSUFFICIENT_STORAGE_PAGE;
static const char * OPTIONS_PAGE;
static const char * CONFLICT_PAGE;
static const char * OK_PAGE;
static int sslCertificateCount;
static SSLCertificate * sslCertificates = NULL;
static void * rootNode = NULL;
static sem_t lockDBLock;
// All Daemons
// Not sure why we keep these, they're not used for anything
static struct MHD_Daemon **daemons;
#define HEADER_LOCK_TOKEN "Lock-Token"
#define HEADER_DEPTH "Depth"
#define HEADER_TARGET "Destination"
/////////////
// Utility //
/////////////
static void logAccess(int statusCode, const char * method, const char * user, const char * url,
const char * client) {
char t[100];
timeNow(t, sizeof(t));
printf("%s %s %s %d %s %s\n", t, client, user, statusCode, method, url);
fflush(stdout);
}
static void initializeLogs() {
// Error log first
if (config.errorLog) {
int errorLog = open(config.errorLog, O_CREAT | O_APPEND | O_WRONLY | O_CLOEXEC, 420);
if (errorLog == -1 || dup2(errorLog, STDERR_FILENO) == -1) {
stdLogError(errno, "Could not open error log file %s", config.errorLog);
exit(1);
}
close(errorLog);
}
if (config.accessLog) {
int accessLogFd = open(config.accessLog, O_CREAT | O_APPEND | O_WRONLY | O_CLOEXEC, 420);
if (accessLogFd == -1 || dup2(accessLogFd, STDOUT_FILENO) == -1) {
stdLogError(errno, "Could not open access log file %s", config.accessLog);
exit(1);
}
}
}
static void getRequestIP(char * buffer, size_t bufferSize, Request * request) {
const struct sockaddr * addressInfo =
MHD_get_connection_info(request, MHD_CONNECTION_INFO_CLIENT_ADDRESS)->client_addr;
static unsigned char IPV4_PREFIX[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
switch (addressInfo->sa_family) {
case AF_INET: {
struct sockaddr_in * v4Address = (struct sockaddr_in *) addressInfo;
unsigned char * address = (unsigned char *) (&v4Address->sin_addr);
snprintf(buffer, bufferSize, "%d.%d.%d.%d", address[0], address[1], address[2], address[3]);
break;
}
case AF_INET6: {
struct sockaddr_in6 * v6Address = (struct sockaddr_in6 *) addressInfo;
// See RFC 5952 section 4 for formatting rules
// find 0 run
unsigned char * address = (unsigned char *) (&v6Address->sin6_addr);
if (!memcmp(IPV4_PREFIX, address, sizeof(IPV4_PREFIX))) {
snprintf(buffer, bufferSize, "%d.%d.%d.%d", address[sizeof(IPV4_PREFIX)],
address[sizeof(IPV4_PREFIX) + 1], address[sizeof(IPV4_PREFIX) + 2],
address[sizeof(IPV4_PREFIX) + 3]);
break;
}
unsigned char * longestRun = NULL;
int longestRunSize = 0;
unsigned char * currentRun = NULL;
int currentRunSize = 0;
for (int i = 0; i < 16; i += 2) {
if (*(address + i) == 0 && *(address + i + 1) == 0) {
if (currentRunSize == 0) {
currentRunSize = 2;
currentRun = (address + i);
} else {
currentRunSize += 2;
if (currentRunSize > longestRunSize) {
longestRun = currentRun;
longestRunSize = currentRunSize;
}
}
} else {
currentRunSize = 0;
}
}
int bytesWritten;
if (longestRunSize == 16) {
bytesWritten = snprintf(buffer, bufferSize, "::");
buffer += bytesWritten;
bufferSize -= bytesWritten;
} else {
for (int i = 0; i < 16; i += 2) {
if (&address[i] == longestRun) {
bytesWritten = snprintf(buffer, bufferSize, i > 0 ? ":" : "::");
buffer += bytesWritten;
bufferSize -= bytesWritten;
i += longestRunSize - 2;
} else {
if (*(address + i) == 0) {
bytesWritten = snprintf(buffer, bufferSize, "%x%s", *(address + i + 1),
i < 14 ? ":" : "");
buffer += bytesWritten;
bufferSize -= bytesWritten;
} else {
bytesWritten = snprintf(buffer, bufferSize, "%x%02x%s", *(address + i),
*(address + i + 1), i < 14 ? ":" : "");
buffer += bytesWritten;
bufferSize -= bytesWritten;
}
}
}
}
break;
}
default:
snprintf(buffer, bufferSize, "<unknown address>");
}
}
static int filterGetHeader(Header * header, enum MHD_ValueKind kind, const char *key, const char *value) {
if (!strcmp(key, header->key)) {
header->value = value;
return MHD_NO;
}
return MHD_YES;
}
static const char * getHeader(Request *request, const char * headerKey) {
Header header = { .key = headerKey, .value = NULL };
MHD_get_connection_values(request, MHD_HEADER_KIND, (MHD_KeyValueIterator) &filterGetHeader, &header);
return header.value;
}
static int requestHasData(Request *request) {
if (getHeader(request, "Content-Length")) {
return 1;
} else {
const char * te = getHeader(request, "Transfer-Encoding");
return te && !strcmp(te, "chunked");
}
}
static void parseHeaderFilePath(char * resultBuffer, size_t urlLength, const char * url) {
if (url[0] != '/') {
// Find the start of the path (after the http://domain.tld/)
int count = 0;
size_t start = 1;
while (start < urlLength && (url[start] == '/' ? ++count : count) < 3) {
start++;
}
url += start;
urlLength -= start;
}
// Decode the % encoded characters
size_t read = 0;
size_t write = 0;
while (read < urlLength) {
if (url[read] != '%' || read >= urlLength - 2) {
resultBuffer[write++] = url[read++];
} else {
unsigned char c;
unsigned char c1 = url[read + 1];
if (c1 >= '0' && c1 <= '9') c = ((c1 - '0') << 4);
else if (c1 >= 'a' && c1 <= 'f') c = ((c1 - 'a' + 10) << 4);
else if (c1 >= 'A' && c1 <= 'F') c = ((c1 - 'A' + 10) << 4);
else {
resultBuffer[write++] = url[read++];
continue;
}
c1 = url[read + 2];
if (c1 >= '0' && c1 <= '9') c |= c1 - '0';
else if (c1 >= 'a' && c1 <= 'f') c |= c1 - 'a' + 10;
else if (c1 >= 'A' && c1 <= 'F') c |= c1 - 'A' + 10;
else {
resultBuffer[write++] = url[read++];
continue;
}
resultBuffer[write++] = c;
read += 3;
}
}
resultBuffer[write] = '\0';
}
/////////////////
// End Utility //
/////////////////
////////////////////
// RAP Processing //
////////////////////
static time_t getExpiryTime() {
time_t expires;
time(&expires);
expires -= config.rapMaxSessionLife;
return expires;
}
static int forkRapProcess(const char * path, int * newSockFd) {
// Create unix domain socket for
int sockFd[2];
int result = socketpair(PF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockFd);
if (result != 0) {
stdLogError(errno, "Could not create socket pair");
return 0;
}
// We set this timeout so that a hung RAP will eventually clean itself up
struct timeval timeout;
timeout.tv_sec = config.rapTimeoutRead;
timeout.tv_usec = 0;
if (setsockopt(sockFd[PARENT_SOCKET], SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
stdLogError(errno, "Could not set timeout");
close(sockFd[PARENT_SOCKET]);
close(sockFd[CHILD_SOCKET]);
return 0;
}
result = fork();
if (result) {
// parent
close(sockFd[CHILD_SOCKET]);
if (result != -1) {
*newSockFd = sockFd[PARENT_SOCKET];
//stdLog("New RAP %d on %d", result, sockFd[0]);
return result;
} else {
// fork failed so close parent pipes and return non-zero
close(sockFd[PARENT_SOCKET]);
stdLogError(errno, "Could not fork");
return 0;
}
} else {
// child
close(sockFd[PARENT_SOCKET]);
if (sockFd[CHILD_SOCKET] == RAP_CONTROL_SOCKET) {
// If by some chance this socket has opened as pre-defined RAP_CONTROL_SOCKET we
// won't dup2 but we do need to remove the close-on-exec flag
int flags = fcntl(sockFd[CHILD_SOCKET], F_GETFD);
if (fcntl(sockFd[CHILD_SOCKET], F_SETFD, flags & ~FD_CLOEXEC) == -1) {
stdLogError(errno, "Could not clear close-on-exec for control socket", sockFd[CHILD_SOCKET],
(int) RAP_CONTROL_SOCKET);
exit(255);
}
} else {
// Assign the control socket to the correct FD so the RAP can use it
// This previously abused STD_IN and STD_OUT for this but instead we now
// reserve a different FD (3) AKA RAP_CONTROL_SOCKET
if (dup2(sockFd[CHILD_SOCKET], RAP_CONTROL_SOCKET) == -1) {
stdLogError(errno, "Could not assign new socket (%d) to %d", sockFd[CHILD_SOCKET],
(int) RAP_CONTROL_SOCKET);
exit(255);
}
}
char * argv[] = {
(char *) path,
NULL };
execv(path, argv);
stdLogError(errno, "Could not start rap: %s", path);
exit(255);
}
}
static void removeRapFromList(RAP * rapSession) {
*(rapSession->prevPtr) = rapSession->next;
if (rapSession->next != NULL) {
rapSession->next->prevPtr = rapSession->prevPtr;
}
}
static void addRapToList(RapList * list, RAP * rapSession) {
rapSession->next = list->firstRapSession;
list->firstRapSession = rapSession;
rapSession->prevPtr = &list->firstRapSession;
if (rapSession->next) {
rapSession->next->prevPtr = &rapSession->next;
}
}
static void destroyRap(RAP * rapSession) {
if (!AUTH_SUCCESS(rapSession)) {
return;
}
close(rapSession->socketFd);
if (rapSession->requestReadDataFd != -1) {
stdLogError(0, "readDataFd was not properly closed before destroying rap");
close(rapSession->requestReadDataFd);
}
if (rapSession->requestWriteDataFd != -1) {
stdLogError(0, "writeDataFd was not properly closed before destroying rap");
close(rapSession->requestWriteDataFd);
}
freeSafe((void *) rapSession->user);
freeSafe((void *) rapSession->password);
freeSafe((void *) rapSession->clientIp);
removeRapFromList(rapSession);
freeSafe(rapSession);
}
static RAP * createRap(RapList * db, const char * user, const char * password, const char * rhost) {
int socketFd;
int pid = forkRapProcess(config.rapBinary, &socketFd);
if (!pid) {
return AUTH_ERROR;
}
// Send Auth Request
Message message;
message.mID = RAP_REQUEST_AUTHENTICATE;
message.fd = -1;
message.paramCount = 3;
message.params[RAP_PARAM_AUTH_USER] = stringToMessageParam(user);
message.params[RAP_PARAM_AUTH_PASSWORD] = stringToMessageParam(password);
message.params[RAP_PARAM_AUTH_RHOST] = stringToMessageParam(rhost);
if (sendMessage(socketFd, &message) <= 0) {
close(socketFd);
return AUTH_ERROR;
}
// Read Auth Result
char incomingBuffer[INCOMING_BUFFER_SIZE];
ssize_t readResult = recvMessage(socketFd, &message, incomingBuffer, INCOMING_BUFFER_SIZE);
if (readResult <= 0 || message.mID != RAP_RESPOND_OK) {
close(socketFd);
if (readResult < 0) {
stdLogError(0, "Could not read result from RAP ");
return AUTH_ERROR;
} else if (readResult == 0) {
stdLogError(0, "RAP closed socket unexpectedly");
return AUTH_ERROR;
} else {
stdLogError(0, "Access denied for user %s", user);
return AUTH_FAILED;
}
}
// If successfully authenticated then populate the RAP structure and add it to the DB
RAP * newRap = mallocSafe(sizeof(*newRap));
newRap->pid = pid;
newRap->socketFd = socketFd;
newRap->user = copyString(user);
newRap->password = copyString(password);
newRap->clientIp = copyString(rhost);
time(&newRap->rapCreated);
newRap->requestWriteDataFd = -1;
newRap->requestReadDataFd = -1;
addRapToList(db, newRap);
// newRap->responseAlreadyGiven // this is set elsewhere
return newRap;
}
// void releaseRap(RAP * processor) {}
static RAP * acquireRap(const char * user, const char * password, const char * clientIp) {
if (user && password) {
RAP * rap;
time_t expires = getExpiryTime();
RapList * threadRapList = pthread_getspecific(rapDBThreadKey);
if (!threadRapList) {
threadRapList = mallocSafe(sizeof(*threadRapList));
memset(threadRapList, 0, sizeof(*threadRapList));
pthread_setspecific(rapDBThreadKey, threadRapList);
} else {
// Get a rap from this thread's own list
rap = threadRapList->firstRapSession;
while (rap) {
if (rap->rapCreated < expires) {
RAP * raptmp = rap->next;
destroyRap(rap);
rap = raptmp;
} else if (!strcmp(user, rap->user)
&& !strcmp(password, rap->password) /*&& !strcmp(clientIp, rap->clientIp)*/) {
// all requests here will come from the same ip so we don't check it in the above.
return rap;
} else {
rap = rap->next;
}
}
}
// Get a rap from the central pool.
if (sem_wait(&rapPoolLock) == -1) {
stdLogError(errno, "Could not wait for rap pool lock while acquiring rap");
return AUTH_ERROR;
} else {
rap = rapPool.firstRapSession;
while (rap) {
if (rap->rapCreated < expires) {
RAP * raptmp = rap->next;
destroyRap(rap);
rap = raptmp;
} else if (!strcmp(user, rap->user) && !strcmp(password, rap->password)
&& !strcmp(clientIp, rap->clientIp)) {
// We will only re-use sessions in the pool if they are from the same ip
removeRapFromList(rap);
addRapToList(threadRapList, rap);
sem_post(&rapPoolLock);
return rap;
} else {
rap = rap->next;
}
}
sem_post(&rapPoolLock);
}
return createRap(threadRapList, user, password, clientIp);
} else {
stdLogError(0, "Rejecting request without auth");
return AUTH_FAILED;
}
}
#define releaseRap(processor)
static void cleanupAfterRap(int sig, siginfo_t *siginfo, void *context) {
int status;
waitpid(siginfo->si_pid, &status, 0);
if (status == 139) {
stdLogError(0, "RAP %d failed with segmentation fault", siginfo->si_pid);
}
//stdLog("Child finished PID: %d staus: %d", siginfo->si_pid, status);
}
static void deInitializeRapDatabase(void * data) {
RapList * threadRapList = data;
if (threadRapList) {
if (threadRapList->firstRapSession) {
if (sem_wait(&rapPoolLock) == -1) {
stdLogError(errno, "Could not wait for rap pool lock cleaning up thread");
do {
destroyRap(threadRapList->firstRapSession);
} while (threadRapList->firstRapSession != NULL);
} else {
do {
RAP * rap = threadRapList->firstRapSession;
removeRapFromList(rap);
addRapToList(&rapPool, rap);
} while (threadRapList->firstRapSession != NULL);
sem_post(&rapPoolLock);
}
}
freeSafe(threadRapList);
}
}
static void runCleanRapPool() {
time_t expires = getExpiryTime();
if (sem_wait(&rapPoolLock) == -1) {
stdLogError(errno, "Could not wait for rap pool lock while cleaning pool");
return;
} else {
RAP * rap = rapPool.firstRapSession;
while (rap != NULL) {
RAP * next = rap->next;
if (rap->rapCreated < expires) {
destroyRap(rap);
}
rap = next;
}
sem_post(&rapPoolLock);
}
}
static void initializeRapDatabase() {
struct sigaction childCleanup = { .sa_sigaction = &cleanupAfterRap, .sa_flags = SA_SIGINFO };
if (sigaction(SIGCHLD, &childCleanup, NULL) < 0) {
stdLogError(errno, "Could not set handler method for finished child threads");
exit(255);
}
memset(&rapPool, 0, sizeof(rapPool));
sem_init(&rapPoolLock, 0, 1);
pthread_key_create(&rapDBThreadKey, &deInitializeRapDatabase);
}
////////////////////////
// End RAP Processing //
////////////////////////
/////////
// SSL //
/////////
static int sslCertificateCompareHost(const void * a, const void * b) {
SSLCertificate * lhs = (SSLCertificate *) a;
SSLCertificate * rhs = (SSLCertificate *) b;
return strcmp(lhs->hostname, rhs->hostname);
}
static SSLCertificate * findCertificateForHost(const char * hostname) {
SSLCertificate toFind = { .hostname = hostname };
SSLCertificate * found = bsearch(&toFind, sslCertificates, sslCertificateCount, sizeof(*sslCertificates),
&sslCertificateCompareHost);
if (!found) {
char * newHostName = copyString(hostname);
char * wildCardHostName = newHostName;
do {
wildCardHostName++;
if (wildCardHostName[0] == '.') {
wildCardHostName[-1] = '*';
toFind.hostname = &wildCardHostName[-1];
found = bsearch(&toFind, sslCertificates, sslCertificateCount, sizeof(*sslCertificates),
&sslCertificateCompareHost);
}
} while (!found && *wildCardHostName);
freeSafe(newHostName);
}
return found;
}
static int sslSNICallback(gnutls_session_t session, const gnutls_datum_t* req_ca_dn, int nreqs,
const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert,
unsigned int *pcert_length, gnutls_privkey_t * pkey) {
SSLCertificate * found = NULL;
char name[1024];
size_t name_len = sizeof(name) - 1;
unsigned int type;
if (GNUTLS_E_SUCCESS == gnutls_server_name_get(session, name, &name_len, &type, 0)) {
name[name_len] = '\0';
found = findCertificateForHost(name);
}
// Returning certificate
if (!found) {
found = &sslCertificates[0];
}
*pkey = found->key;
*pcert_length = found->certCount;
*pcert = found->certs;
return 0;
}
static int loadSSLCertificateFile(const char * fileName, gnutls_x509_crt_t * x509Certificate,
gnutls_pcert_st * cert) {
size_t fileSize;
gnutls_datum_t certData;
memset(cert, 0, sizeof(*cert));
memset(x509Certificate, 0, sizeof(*x509Certificate));
certData.data = loadFileToBuffer(fileName, &fileSize);
if (!certData.data) {
return -1;
}
certData.size = fileSize;
int ret;
if ((ret = gnutls_x509_crt_init(x509Certificate)) < 0) {
freeSafe(certData.data);
return ret;
}
ret = gnutls_x509_crt_import(*x509Certificate, &certData, GNUTLS_X509_FMT_PEM);
freeSafe(certData.data);
if (ret < 0) {
gnutls_x509_crt_deinit(*x509Certificate);
return ret;
}
if ((ret = gnutls_pcert_import_x509(cert, *x509Certificate, 0)) < 0) {
gnutls_x509_crt_deinit(*x509Certificate);
return ret;
}
return ret;
}
static int loadSSLKeyFile(const char * fileName, gnutls_privkey_t * key) {
size_t fileSize;
gnutls_datum_t keyData;
keyData.data = loadFileToBuffer(fileName, &fileSize);
if (!keyData.data) {
return -1;
}
keyData.size = fileSize;
int ret = gnutls_privkey_init(key);
if (ret < 0) {
freeSafe(keyData.data);
return ret;
}
ret = gnutls_privkey_import_x509_raw(*key, &keyData, GNUTLS_X509_FMT_PEM, NULL, 0);
freeSafe(keyData.data);
if (ret < 0) {
gnutls_privkey_deinit(*key);
}
return ret;
}
static int loadSSLCertificate(SSLConfig * sslConfig) {
// Now load the files in earnest
SSLCertificate newCertificate;
gnutls_x509_crt_t x509Certificate;
int ret;
ret = loadSSLKeyFile(sslConfig->keyFile, &newCertificate.key);
if (ret < 0) {
stdLogError(0, "Could not load %s: %s", sslConfig->keyFile, gnutls_strerror(ret));
return 0;
}
newCertificate.certCount = sslConfig->chainFileCount + 1;
newCertificate.certs = mallocSafe(newCertificate.certCount * (sizeof(*newCertificate.certs)));
for (int i = 0; i < sslConfig->chainFileCount; i++) {
ret = loadSSLCertificateFile(sslConfig->chainFiles[i], &x509Certificate,
&newCertificate.certs[i + 1]);
if (ret < 0) {
stdLogError(0, "Could not load %s: %s", sslConfig->chainFiles[i], gnutls_strerror(ret));
gnutls_privkey_deinit(newCertificate.key);
for (int j = 0; j < i; j++) {
gnutls_pcert_deinit(&newCertificate.certs[j + 1]);
}
freeSafe(newCertificate.certs);
return ret;
}
gnutls_x509_crt_deinit(x509Certificate);
}
ret = loadSSLCertificateFile(sslConfig->certificateFile, &x509Certificate, &newCertificate.certs[0]);
if (ret < 0) {
stdLogError(0, "Could not load %s: %s", sslConfig->certificateFile, gnutls_strerror(ret));
gnutls_privkey_deinit(newCertificate.key);
for (int i = 1; i < newCertificate.certCount; i++) {
gnutls_pcert_deinit(&newCertificate.certs[i]);
}
freeSafe(newCertificate.certs);
}
int found = 0;
for (int i = 0; ret != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; i++) {
char domainName[1024];
int critical = 0;
size_t dataSize = sizeof(domainName);
int sanType = 0;
ret = gnutls_x509_crt_get_subject_alt_name2(x509Certificate, i, domainName, &dataSize, &sanType,
&critical);
if (ret != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE && ret != GNUTLS_E_SHORT_MEMORY_BUFFER
&& sanType == GNUTLS_SAN_DNSNAME) {
stdLog("ssl domain %s --> %s", domainName, sslConfig->certificateFile);
int index = sslCertificateCount++;
sslCertificates = reallocSafe(sslCertificates, sslCertificateCount * (sizeof(*sslCertificates)));
sslCertificates[index] = newCertificate;
sslCertificates[index].hostname = copyString(domainName);
found = 1;
}
}
gnutls_x509_crt_deinit(x509Certificate);
if (!found) {
stdLogError(0, "No subject alternative name found in %s", sslConfig->certificateFile);
gnutls_privkey_deinit(newCertificate.key);
for (int i = 0; i < newCertificate.certCount; i++) {
gnutls_pcert_deinit(&newCertificate.certs[i]);
}
freeSafe(newCertificate.certs);
return -1;
}
return 0;
}
static void initializeSSL() {
for (int i = 0; i < config.sslCertCount; i++) {
if (loadSSLCertificate(&config.sslCerts[i])) {
exit(1);
}
}
qsort(sslCertificates, sslCertificateCount, sizeof(*sslCertificates), &sslCertificateCompareHost);
}
/////////////
// End SSL //
/////////////
///////////
// Locks //
///////////
static int compareLockToken(const void * a, const void * b) {
const Lock * lhs = a;
const Lock * rhs = b;
return strcasecmp(lhs->lockToken, rhs->lockToken);
}
static Lock * findLock(Lock * lockToken) {
Lock ** result = tfind(lockToken, &rootNode, &compareLockToken);
return result ? *result : NULL;
}
static Lock * acquireLock(const char * user, const char * file, LockType lockType, int fd) {
if (lockType != LOCK_TYPE_SHARED && lockType != LOCK_TYPE_EXCLUSIVE) {
stdLogError(0, "acquireLock called with invalid lockType %d", (int) lockType);
return NULL;
}
size_t userSize = strlen(user) + 1;
size_t fileSize = strlen(file) + 1;
size_t bufferSize = sizeof(Lock) + userSize + fileSize;
char * buffer = mallocSafe(bufferSize);
Lock * newLock = (Lock *) buffer;
newLock->user = buffer + sizeof(Lock);
newLock->file = newLock->user + userSize;
uuid_t uuid;
uuid_generate(uuid);
uuid_unparse_lower(uuid, newLock->lockToken);
memcpy((char *) newLock->user, user, userSize);
memcpy((char *) newLock->file, file, fileSize);
time(&newLock->lockAcquired);
newLock->type = lockType;
newLock->fd = fd;
newLock->useCount = 1;
newLock->released = 0;
if (sem_wait(&lockDBLock) == -1) {
stdLogError(errno, "Could not wait for access to lock db");
close(fd);
freeSafe(newLock);
return NULL;
} else {
// Adds the lock to the DB. Despite its odd name tsearch adds the item if it doesnt already exist.
Lock * inDB = *((Lock **) tsearch(newLock, &rootNode, &compareLockToken));
sem_post(&lockDBLock);
if (inDB != newLock) {
// This should never happen, but "should" isn't a term we want to play with.
stdLogError(0, "UUID collision in lock database %s", newLock->lockToken);
close(newLock->fd);
freeSafe(newLock);
return acquireLock(user, file, lockType, fd);
} else {
return newLock;
}
}
}
static int refreshLock(Lock * lock) {
if (sem_wait(&lockDBLock) == -1) {
stdLogError(errno, "Could not wait for access to lock db");
return 0;
}
Lock * foundLock = findLock(lock);
if (foundLock && !foundLock->released) {
time(&foundLock->lockAcquired);
sem_post(&lockDBLock);
return 1;
} else {
sem_post(&lockDBLock);
stdLogError(0, "Could not find lock %s for user %s on file %s", lock->lockToken, lock->user,
lock->file);
return 0;
}
}
static void releaseUnusedLock(Lock * lock) {
lock->useCount--;
if (lock->useCount == 0) {
tdelete(lock, &rootNode, &compareLockToken);
close(lock->fd);
freeSafe(lock);
}
}
static Lock * useLock(const char * lockToken, const char * file, const char * user) {
if (strncmp(lockToken, LOCK_TOKEN_PREFIX, LOCK_TOKEN_PREFIX_LENGTH)) {
stdLogError(0, "Could not find lock %s for user %s on file %s", lockToken, user, file);
return NULL;
}
Lock toFind;
strncpy((char *) toFind.lockToken, lockToken + LOCK_TOKEN_PREFIX_LENGTH, sizeof(toFind.lockToken) - 1);
toFind.lockToken[sizeof(toFind.lockToken) - 1] = '\0';
if (sem_wait(&lockDBLock) == -1) {
stdLogError(errno, "Could not wait for access to lock db");
return NULL;
}
Lock * foundLock = findLock(&toFind);
if (foundLock != NULL && !strcmp(foundLock->user, user) && !strcmp(foundLock->file, file)
&& !foundLock->released) {
foundLock->useCount++;
sem_post(&lockDBLock);
return foundLock;
} else {
sem_post(&lockDBLock);
stdLogError(0, "Could not find lock %s for user %s on file %s", lockToken, user, file);
return NULL;
}
}
static void unuseLock(Lock * lockToken) {
if (sem_wait(&lockDBLock) == -1) {
stdLogError(errno, "Could not wait for access to lock db lock will left in DB after unsuseLock()");
} else {
Lock * foundLock = findLock(lockToken);
if (foundLock) {
releaseUnusedLock(foundLock);
}
sem_post(&lockDBLock);
}
}
static int releaseLock(const char * lockToken, const char * file, const char * user) {
if (strncmp(lockToken, LOCK_TOKEN_PREFIX, LOCK_TOKEN_PREFIX_LENGTH)) {
stdLogError(0, "Could not find lock %s for user %s on file %s", lockToken, user, file);
return 0;
}
Lock toFind;
strncpy((char *) toFind.lockToken, lockToken + LOCK_TOKEN_PREFIX_LENGTH, sizeof(toFind.lockToken) - 1);
toFind.lockToken[sizeof(toFind.lockToken) - 1] = '\0';
if (sem_wait(&lockDBLock) == -1) {
stdLogError(errno, "Could not wait for access to lock db");
return -1;
}
Lock * foundLock = findLock(&toFind);
if (foundLock != NULL && !strcmp(foundLock->user, user) && !strcmp(foundLock->file, file)
&& !foundLock->released) {
foundLock->released = 1;
releaseUnusedLock(foundLock);
sem_post(&lockDBLock);
return 1;
} else {
sem_post(&lockDBLock);
stdLogError(0, "Could not find lock %s for user %s on file %s", lockToken, user, file);
return 0;
}
}
static void cleanAction(const void *nodep, const VISIT which, const int depth) {
switch (which) {