-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheopen.c
More file actions
610 lines (539 loc) · 16.1 KB
/
cacheopen.c
File metadata and controls
610 lines (539 loc) · 16.1 KB
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
/*
* Copyright 2006-2019 Niklas Edmundsson <nikke@acc.umu.se>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/types.h>
#include <utime.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#ifdef __linux
#include <linux/falloc.h>
#endif /* __linux */
#include "md5.c"
static void cache_hash(const char *it, char *val, int ndepth, int nlength)
{
MD5_CTX context;
char tmp[22];
int i, k, d;
unsigned int x;
static const char enc_table[64] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
MD5Init(&context);
MD5Update(&context, (unsigned char *) it, strlen(it));
MD5Final(&context);
/* encode 128 bits as 22 characters, using a modified uuencoding
* the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
* 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
*/
for (i = 0, k = 0; i < 15; i += 3) {
x = (context.digest[i] << 16) | (context.digest[i + 1] << 8) | context.digest[i + 2];
tmp[k++] = enc_table[x >> 18];
tmp[k++] = enc_table[(x >> 12) & 0x3f];
tmp[k++] = enc_table[(x >> 6) & 0x3f];
tmp[k++] = enc_table[x & 0x3f];
}
/* one byte left */
x = context.digest[15];
tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
tmp[k++] = enc_table[(x << 4) & 0x3f];
/* now split into directory levels */
for (i = k = d = 0; d < ndepth; ++d) {
memcpy(&val[i], &tmp[k], nlength);
k += nlength;
val[i + nlength] = '/';
i += nlength + 1;
}
memcpy(&val[i], &tmp[k], 22 - k);
val[i + 22 - k] = '\0';
}
#define MAX_MKDIR_RETRY 10
static int mkdir_structure(char *path) {
char *p = path + cache_len;
int ret, retry=0;
p = strchr(p, '/');
while(p && *p && retry < MAX_MKDIR_RETRY) {
*p = '\0';
ret = mkdir(path, 0700);
*p = '/';
p++;
if(ret == -1) {
if(errno == ENOENT) {
/* Someone removed the directory tree while we were at it,
redo from start... */
retry++;
p = path + cache_len;
}
else if(errno != EEXIST) {
return(-1);
}
}
p = strchr(p, '/');
}
if(retry >= MAX_MKDIR_RETRY) {
return(-1);
}
return(0);
}
typedef enum copy_status {
COPY_FAIL = -1,
COPY_EXISTS = -2,
COPY_OK = 0
} copy_status;
static int open_new_file(char *destfile,
int (*openfunc)(const char *, int, ...),
int (*statfunc)(const char *, struct stat64 *))
{
int fd;
int flags = O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE;
mode_t mode = S_IRUSR | S_IWUSR;
while(1) {
fd = openfunc(destfile, flags, mode);
if(fd != -1) {
#ifdef DEBUG
fprintf(stderr, "httpcacheopen: open_new_file: Opened %s\n",
destfile);
#endif
return(fd);
}
#ifdef DEBUG
perror("httpcacheopen: open_new_file");
#endif
if(errno == EEXIST) {
struct stat64 st;
if((statfunc(destfile, &st)) == -1) {
if(errno == ENOENT) {
/* Already removed, try again */
continue;
}
else {
return COPY_FAIL;
}
}
if(st.st_mtime < time(NULL) - CACHE_UPDATE_TIMEOUT) {
/* Something stale */
if((unlink(destfile)) == -1) {
if(errno == ENOENT) {
/* Already removed, try again */
continue;
}
else {
return COPY_FAIL;
}
}
}
else {
/* Someone else beat us to this */
return COPY_EXISTS;
}
}
else if(errno == ENOENT) {
/* Directory missing, create and try again */
if((mkdir_structure(destfile)) == -1) {
return COPY_FAIL;
}
}
else {
return COPY_FAIL;
}
}
errno = EFAULT;
return COPY_FAIL;
}
static copy_status copy_file(int srcfd, int srcflags, off64_t len,
time_t mtime, char *destfile,
int (*openfunc)(const char *, int, ...),
int (*statfunc)(const char *, struct stat64 *),
int (*fstat64func)(int filedes, struct stat64 *buf),
ssize_t (*readfunc)(int fd, void *buf, size_t count),
int (*closefunc)(int fd))
{
int destfd, modflags, i, err;
char *buf;
ssize_t amt, wrt, done;
off64_t srcoff, destoff, flushoff;
copy_status rc = COPY_OK;
destfd = open_new_file(destfile, openfunc, statfunc);
if(destfd < 0) {
return(destfd);
}
buf = malloc(CPBUFSIZE);
if(buf == NULL) {
closefunc(destfd);
return(COPY_FAIL);
}
/* Remove nonblocking IO */
modflags = srcflags;
if(srcflags & O_NONBLOCK
) {
modflags &= ~O_NONBLOCK;
if((fcntl(srcfd, F_SETFL, modflags)) == -1) {
#ifdef DEBUG
perror("httpcacheopen: copy_file: Failed changing fileflags");
#endif
modflags = srcflags;
}
#ifdef DEBUG
else {
fprintf(stderr, "httpcacheopen: copy_file: Modified file flags\n");
}
#endif
}
/* We expect sequential IO */
err=posix_fadvise(srcfd, 0, 0, POSIX_FADV_SEQUENTIAL);
if(err) {
#ifdef DEBUG
fprintf(stderr, "posix_fadvise: %s\n", strerror(err));
#endif
}
#ifdef __linux
/* Use Linux fallocate() to preallocate file */
if(len > 0) {
if(fallocate(destfd, FALLOC_FL_KEEP_SIZE, 0, len) != 0) {
#ifdef DEBUG
perror("copy_file: fallocate");
#endif
/* Only choke on relevant errors */
if(errno == EBADF || errno == EIO || errno == ENOSPC) {
rc = COPY_FAIL;
goto exit;
}
}
}
#endif /* __linux */
srcoff=0;
destoff=0;
flushoff=0;
i=0;
while(len > 0) {
if(i++ >= CPCHKINTERVAL) {
struct stat64 st;
i=0;
if(fstat64func(destfd, &st) == -1) {
/* Shouldn't happen, really */
#ifdef DEBUG
perror("copy_file: Unable to fstat destfd");
#endif
rc = COPY_FAIL;
goto exit;
}
if(st.st_nlink == 0) {
/* Destination file deleted, no use to continue */
#ifdef DEBUG
fprintf(stderr, "httpcacheopen: copy_file: destfd unlinked\n");
#endif
rc = COPY_FAIL;
goto exit;
}
}
amt = readfunc(srcfd, buf, CPBUFSIZE);
if(amt == -1) {
if(errno == EINTR) {
continue;
}
#ifdef DEBUG
perror("httpcacheopen: copy_file: read");
#endif
rc = COPY_FAIL;
goto exit;
}
if(amt == 0) {
break;
}
/* We will never need this segment again */
err=posix_fadvise(srcfd, srcoff, amt, POSIX_FADV_DONTNEED);
#ifdef DEBUG
if(err) {
fprintf(stderr, "posix_fadvise: %s\n", strerror(err));
}
#endif
srcoff += amt;
if(len-amt > 0) {
/* Tell kernel that we'll need more segments soon */
err=posix_fadvise(srcfd, srcoff, 2*CPBUFSIZE, POSIX_FADV_WILLNEED);
#ifdef DEBUG
if(err) {
fprintf(stderr, "posix_fadvise: %s\n", strerror(err));
}
#endif
}
done = 0;
while(amt > 0) {
wrt = write(destfd, buf+done, amt);
if(amt == -1) {
if(errno == EINTR) {
continue;
}
#ifdef DEBUG
perror("httpcacheopen: copy_file: write");
#endif
rc = COPY_FAIL;
goto exit;
}
done += wrt;
destoff += wrt;
amt -= wrt;
len -= wrt;
}
if(destoff - flushoff >= CACHE_WRITE_FLUSH_WINDOW) {
/* Start flushing the current write window */
if(sync_file_range(destfd, flushoff, destoff - flushoff,
SYNC_FILE_RANGE_WRITE) != 0)
{
rc = COPY_FAIL;
goto exit;
}
/* Wait for the previous window to be written to disk before
continuing. This is to prevent the disk write queues to be
chock full if incoming data rate is higher than the disks can
handle, which will cause horrible read latencies for other
requests while handling writes for this one */
if(flushoff >= CACHE_WRITE_FLUSH_WINDOW) {
if(sync_file_range(destfd, flushoff-CACHE_WRITE_FLUSH_WINDOW,
CACHE_WRITE_FLUSH_WINDOW,
SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER)
!= 0)
{
rc = COPY_FAIL;
goto exit;
}
}
flushoff = destoff;
}
}
if(len != 0) {
/* Weird, didn't read expected amount */
#ifdef DEBUG
fprintf(stderr, "httpcacheopen: copy_file: len %lld left\n",
(long long)len);
#endif
rc = COPY_FAIL;
goto exit;
}
exit:
free(buf);
if((closefunc(destfd)) == -1) {
#ifdef DEBUG
perror("httpcacheopen: copy_file: close destfd");
#endif
unlink(destfile);
rc = COPY_FAIL;
}
else {
struct utimbuf ut;
/* Set mtime on file to same as source */
ut.actime = time(NULL);
ut.modtime = mtime;
utime(destfile, &ut);
}
lseek64(srcfd, 0, SEEK_SET);
#ifdef __sun
/* OK, we're being lame assuming file was opened with default
behaviour */
directio(srcfd, DIRECTIO_OFF);
#endif /* __sun */
if(srcflags != modflags) {
fcntl(srcfd, F_SETFL, srcflags);
}
return(rc);
}
static int cacheopen_check(const char *path) {
if(strncmp(path, backend_root, backend_len)) {
/* Not a backend file, ignore */
#ifdef DEBUG
fprintf(stderr, "cacheopen: Not a backend file: %s\n", path);
#endif
return -1;
}
return 0;
}
/* Given realst, constructs cachepath. cachepath is assumed to be
large enough */
static void cacheopen_prepare(struct stat64 *realst, char *cachepath)
{
unsigned long long inode, device;
char devinostr[34];
int len;
/* Hash on device:inode to eliminate file duplication. Since we only
can serve plain files we don't have to bother with all the special
cases in mod_disk_cache :) */
device = realst->st_dev; /* Avoid ifdef-hassle with types */
inode = realst->st_ino;
snprintf(devinostr, sizeof(devinostr), "%016llx:%016llx", device, inode);
/* Calculate cachepath. We simply put large files in a separate path
intended to separate the contention point for large and small files */
if(realst->st_size < CACHE_BF_SIZE) {
strcpy(cachepath, cache_root);
len = cache_len;
}
else {
strcpy(cachepath, bfcache_root);
len = bfcache_len;
}
cache_hash(devinostr, cachepath+len, DIRLEVELS, DIRLENGTH);
strcat(cachepath, CACHE_BODY_SUFFIX);
}
typedef enum cacheopen_status {
CACHEOPEN_FAIL = -1,
CACHEOPEN_DECLINED = -2,
CACHEOPEN_STALE = -3
} cacheopen_status;
/* On success, fills in cachest */
static int cacheopen(struct stat64 *cachest, struct stat64 *realst,
int oflag, char *cachepath,
int (*openfunc)(const char *, int, ...),
int (*fstat64func)(int filedes, struct stat64 *buf),
int (*closefunc)(int fd))
{
int cachefd;
/* Only cache regular files larger than 0 bytes */
if(!S_ISREG(realst->st_mode) || realst->st_size == 0) {
return CACHEOPEN_DECLINED;
}
cachefd = openfunc(cachepath, oflag);
if(cachefd == -1) {
#ifdef DEBUG
perror("cacheopen: Unable to open cachepath");
#endif
return CACHEOPEN_FAIL;
}
if(fstat64func(cachefd, cachest) == -1) {
#ifdef DEBUG
perror("cacheopen: Unable to fstat cachefd");
#endif
/* Shouldn't fail, really... */
closefunc(cachefd);
return CACHEOPEN_FAIL;
}
/* FIXME: Use ctime != mtime too */
if(realst->st_mtime > cachest->st_mtime ||
(realst->st_size != cachest->st_size &&
cachest->st_mtime < time(NULL) - CACHE_UPDATE_TIMEOUT))
{
/* Bollocks, the cached file is stale */
closefunc(cachefd);
#ifdef DEBUG
fprintf(stderr, "cacheopen: cached file stale\n");
#endif
return CACHEOPEN_STALE;
}
#ifdef DEBUG
fprintf(stderr, "cacheopen: Success, returning cached fd %d (%s)\n",
cachefd, cachepath);
#endif
return cachefd;
}
#ifdef USE_COPYD
static int copyd_file(char *file,
ssize_t (*readfunc)(int fd, void *buf, size_t count),
int (*closefunc)(int fd))
{
struct sockaddr_un sa;
int rc;
int sock=-1;
struct sigaction oldsig;
char buf[10]; /* Should only get "OK\0" or "FAIL\0" */
ssize_t amt;
#ifdef DEBUG
fprintf(stderr, "copyd_file: file=%s\n", file);
#endif
if(sigaction(SIGPIPE, NULL, &oldsig) == -1) {
#ifdef DEBUG
perror("copyd_file: sigaction get");
#endif
return -1;
}
if(oldsig.sa_flags & SA_SIGINFO || oldsig.sa_handler != SIG_IGN) {
struct sigaction newsig;
/* Ignore those pesky SIGPIPE:s */
newsig.sa_handler = SIG_IGN;
newsig.sa_sigaction = NULL;
sigemptyset(&newsig.sa_mask);
newsig.sa_flags = 0;
if(sigaction(SIGPIPE, &newsig, &oldsig) == -1) {
#ifdef DEBUG
perror("copyd_file: sigaction set");
#endif
return -1;
}
}
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if(sock == -1) {
#ifdef DEBUG
perror("copyd_file: socket");
#endif
rc = -1;
goto err;
}
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, SOCKPATH);
if(connect(sock, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
#ifdef DEBUG
perror("copyd_file: connect");
#endif
rc = -1;
goto err;
}
amt = strlen(file)+1;
rc=write(sock, file, amt);
if(rc != amt) {
#ifdef DEBUG
perror("copyd_file: write");
#endif
goto err;
}
#ifdef DEBUG
fprintf(stderr, "copyd_file: wrote '%s' rc=%d\n", file, rc);
#endif
rc = readfunc(sock, buf, sizeof(buf));
if(rc == -1) {
#ifdef DEBUG
perror("copyd_file: read");
#endif
goto err;
}
else if(rc < 1) {
#ifdef DEBUG
fprintf(stderr, "copyd_file: short read\n");
#endif
rc = -1;
goto err;
}
buf[rc-1] = '\0';
#ifdef DEBUG
fprintf(stderr, "copyd_file: read '%s' rc=%d\n", buf, rc);
#endif
if(!strcmp(buf, "OK")) {
rc = 0;
}
else {
rc = -1;
}
err:
if(sock >= 0) {
closefunc(sock);
}
if(oldsig.sa_flags & SA_SIGINFO || oldsig.sa_handler != SIG_IGN) {
if(sigaction(SIGPIPE, &oldsig, NULL) == -1) {
#ifdef DEBUG
perror("copyd_file: restore sigaction");
#endif
}
}
return rc;
}
#endif /* USE_COPYD */