Debian Codegraph @

Framework/Pantomime/CWLocalCacheManager.m

raw
1 /*
2 ** CWLocalCacheManager.m
3 **
4 ** Copyright (c) 2001-2007 Ludovic Marcotte
5 ** Copyright (C) 2013-2020 Riccardo Mottola
6 **
7 ** Author: Ludovic Marcotte <[email protected]>
8 ** Riccardo Mottola <[email protected]>
9 ** Sebastian Reitenbach
10 **
11 **
12 ** This library is free software; you can redistribute it and/or
13 ** modify it under the terms of the GNU Lesser General Public
14 ** License as published by the Free Software Foundation; either
15 ** version 2.1 of the License, or (at your option) any later version.
16 **
17 ** This library is distributed in the hope that it will be useful,
18 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 ** Lesser General Public License for more details.
21 **
22 ** You should have received a copy of the GNU General Public License
23 ** along with this program. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #import <Pantomime/CWLocalCacheManager.h>
27
28 #import <Pantomime/io.h>
29 #import <Pantomime/CWConstants.h>
30 #import <Pantomime/CWFlags.h>
31 #import <Pantomime/CWLocalFolder.h>
32 #import <Pantomime/CWLocalMessage.h>
33 #import <Pantomime/CWParser.h>
34 #import <Pantomime/NSData+Extensions.h>
35
36 #import <Foundation/NSArchiver.h>
37 #import <Foundation/NSException.h>
38 #import <Foundation/NSFileManager.h>
39 #import <Foundation/NSNull.h>
40 #import <Foundation/NSValue.h>
41
42 #include <stdlib.h>
43 #include <string.h>
44 #include <sys/types.h> // For open() and friends.
45 #include <sys/stat.h>
46 #include <fcntl.h>
47 #include <errno.h>
48 #include <unistd.h> // For lseek()
49 #include <netinet/in.h> // For ntohl()
50
51 static unsigned short version = 1;
52
53 //
54 // Cache structure:
55 //
56 // Start length Description
57 //
58 // 0 2 Cache version
59 // 2 4 Number of cache entries
60 // 6 4 Modification date of the underlying mbox file
61 // Modification of the underlying cur/ directory for maildir
62 // [10] 4 File size of the underlying mbox file. This entry does NOT exist for maildir cache.
63 // 14+/10+ Beginning of the first cache entry
64 //
65 // 0 4 Record length, including this field. The record consist of cached message headers / attributes.
66 // 4 4 Flags
67 // 8 4 Date
68 // 12 4+ Position for mbox / Filename for maildir
69 // 16+ 4 Size
70 //
71 //
72 @implementation CWLocalCacheManager
73
74 //
75 //
76 //
77 - (id) initWithPath: (NSString *) thePath folder: (id) theFolder
78 {
79 NSDictionary *attributes;
80 NSUInteger d, s, c;
81 unsigned short int v;
82 BOOL broken;
83
84 self = [super initWithPath: thePath];
85 if (self)
86 {
87 // We get the attributes of the mailbox
88 if ([theFolder type] == PantomimeFormatMbox)
89 {
90 attributes = [[NSFileManager defaultManager] fileAttributesAtPath: [theFolder path] traverseLink: NO];
91 }
92 else
93 {
94 attributes = [[NSFileManager defaultManager] fileAttributesAtPath: [NSString stringWithFormat: @"%@/cur", [theFolder path]]
95 traverseLink: NO];
96 }
97
98 d = (NSUInteger)[[attributes objectForKey: NSFileModificationDate] timeIntervalSince1970];
99 s = (NSUInteger)[[attributes objectForKey: NSFileSize] unsignedLongValue];
100 broken = NO;
101
102 // We get the attribtes of the cache
103 attributes = [[NSFileManager defaultManager] fileAttributesAtPath: thePath traverseLink: NO];
104
105 _folder = theFolder;
106 _count = _modification_date = 0;
107
108 if ((_fd = open([thePath UTF8String], O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0)
109 {
110 AUTORELEASE(self);
111 return nil;
112 }
113
114 if (lseek(_fd, 0L, SEEK_SET) < 0)
115 {
116 AUTORELEASE(self);
117 return nil;
118 }
119
120 // If the cache exists, lets parse it.
121 if ([[attributes objectForKey: NSFileSize] intValue])
122 {
123 v = read_uint16(_fd);
124
125 // HACK: We IGNORE all the previous cache.
126 if (v != version)
127 {
128 //NSLog(@"Ignoring the old cache format.");
129 if (ftruncate(_fd, 0) == -1)
130 {
131
132 if (errno == EACCES || errno == EROFS)
133 NSLog(@"UNABLE TO TRUNCATE CACHE FILE WITH OLD VERSION, NOT WRITABLE");
134 else
135 NSLog(@"UNABLE TO TRUNCATE CACHE FILE WITH OLD VERSION");
136 close(_fd);
137 abort();
138 }
139 [self synchronize];
140 return self;
141 }
142
143 if (read_uint32(_fd, (uint32_t *)&_count) <= 0)
144 {
145 NSLog(@"CWLocalCacheManager initWithPath, error reading _count");
146 broken = YES;
147 }
148 read_uint32(_fd, &_modification_date);
149
150 if ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox)
151 {
152 if (read_uint32(_fd, (uint32_t*)&_size) <= 0)
153 {
154 NSLog(@"CWLocalCacheManager initWithPath: failed to read size");
155 broken = YES;
156 }
157
158 if (s != _size || d != _modification_date) broken = YES;
159 }
160 else
161 {
162 //NSLog(@"Asking enumerator...");
163 c = [[[[NSFileManager defaultManager] enumeratorAtPath: [NSString stringWithFormat: @"%@/cur/", [theFolder path]]] allObjects] count];
164 //NSLog(@"Done! count = %d", c);
165
166 if (c != _count || d != _modification_date) broken = YES;
167 }
168
169 if (broken)
170 {
171 NSDebugLog(@"Broken cache, we must invalidate.");
172 _count = _size = 0;
173 if (ftruncate(_fd, 0) == -1)
174 {
175
176 if (errno == EACCES || errno == EROFS)
177 NSLog(@"UNABLE TO TRUNCATE BROKEN CACHE FILE, NOT WRITABLE");
178 else
179 NSLog(@"UNABLE TO TRUNCATE BROKEN CACHE FILE");
180 close(_fd);
181 abort();
182 }
183 [self synchronize];
184 return self;
185 }
186
187 //NSLog(@"Version = %i date = %d size = %d count = %d", v, d, _size, _count);
188 }
189 else
190 {
191 [self synchronize];
192 }
193 }
194 return self;
195 }
196
197 //
198 //
199 //
200 - (void) dealloc
201 {
202 //NSLog(@"CWLocalCacheManager: -dealloc");
203
204 if (_fd >= 0) close(_fd);
205
206 [super dealloc];
207 }
208
209 //
210 //
211 //
212 - (void) readAllMessages
213 {
214 [self readMessagesInRange:NSMakeRange(0, NSUIntegerMax)];
215 }
216
217 //
218 // If this method is invoked on already initialized messages, we use
219 // the file position or filename field in order to determine if we already
220 // initialized or not the message.
221 //
222 - (void) readMessagesInRange: (NSRange) theRange
223 {
224 CWLocalMessage *aMessage;
225
226 unsigned short int tot;
227 unsigned char *r;
228 NSUInteger begin, end, i;
229
230 begin = theRange.location;
231 end = (NSMaxRange(theRange) <= _count ? NSMaxRange(theRange) : _count);
232
233 if (lseek(_fd, ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox) ? 14L : 10L, SEEK_SET) < 0)
234 {
235 NSLog(@"CWLocalCacheManager readMessagesInRange: lseek failed");
236 abort();
237 }
238
239 //NSLog(@"init from %d to %d, count = %d, size of char %d", begin, end, _count, sizeof(char));
240
241 // We MUST skip the last few bytes...
242 for (i = begin; i < end ; i++)
243 {
244 uint16_t len;
245 cache_record cr;
246 unsigned int record_length;
247 NSString *mailFilename;
248
249
250 // We parse the record length, date, flags, position in file and the size.
251 if (read_uint32(_fd, &record_length) <= 0)
252 {
253 NSLog(@"CWLocalCacheManager readMessagesInRange: failed to read record length (%lu/%lu)", (unsigned long)i, (unsigned long)end);
254 break;
255 }
256
257 r = (unsigned char *)malloc(record_length-4);
258
259 if (read(_fd, r, record_length-4) < 0) { NSLog(@"read failed"); abort(); }
260
261 tot = 0;
262
263 cr.flags = read_uint32_memory(r);
264 tot += 4;
265
266 cr.date = read_uint32_memory(r+4);
267 tot += 4;
268
269 mailFilename= nil;
270 cr.position = 0;
271 if ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox)
272 {
273 cr.position = (long)read_uint32_memory(r+tot);
274 tot += 4;
275 }
276 else
277 {
278 mailFilename = read_string_memory(r+tot, &len);
279 tot += len+2;
280 }
281
282 cr.size = read_uint32_memory(r+tot);
283 tot += 4;
284
285 cr.from = read_data_memory(r+tot, &len);
286 tot += len+2;
287
288 cr.in_reply_to = read_data_memory(r+tot, &len);
289 tot += len+2;
290
291 cr.message_id = read_data_memory(r+tot, &len);
292 tot += len+2;
293
294 cr.references = read_data_memory(r+tot, &len);
295 tot += len+2;
296
297 cr.subject = read_data_memory(r+tot, &len);
298 tot += len+2;
299
300 cr.to = read_data_memory(r+tot, &len);
301 tot += len+2;
302
303 cr.cc = read_data_memory(r+tot, &len);
304
305 // zero unused fields
306 cr.imap_uid = 0;
307 cr.filename = NULL;
308 cr.pop3_uid = NULL;
309
310 aMessage = [[CWLocalMessage alloc] initWithCacheRecord:cr];
311 [aMessage setFolder: _folder];
312
313 if ([aMessage filename] != nil)
314 [aMessage setMailFilename: mailFilename];
315
316 [aMessage setMessageNumber: i+1];
317 [[((CWFolder *)_folder) messages] addObject: aMessage];
318 RELEASE(aMessage);
319
320 free(r);
321 }
322 }
323
324 //
325 // access/mutation methods
326 //
327 - (NSDate *) modificationDate
328 {
329 return [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval) _modification_date];
330 }
331
332 - (void) setModificationDate: (NSDate *) theDate
333 {
334 _modification_date = (unsigned int)[theDate timeIntervalSince1970];
335 }
336
337 //
338 //
339 //
340 - (NSUInteger) fileSize
341 {
342 return _size;
343 }
344
345 - (void) setFileSize: (unsigned int) theSize
346 {
347 _size = theSize;
348 }
349
350 //
351 //
352 //
353 - (BOOL) synchronize
354 {
355 NSDictionary *attributes;
356 CWLocalMessage *aMessage;
357 unsigned int len, flags;
358 NSUInteger i;
359
360 if ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox)
361 {
362 attributes = [[NSFileManager defaultManager] fileAttributesAtPath: [(CWLocalFolder *)_folder path]
363 traverseLink: NO];
364 }
365 else
366 {
367 attributes = [[NSFileManager defaultManager] fileAttributesAtPath: [NSString stringWithFormat: @"%@/cur", [(CWLocalFolder *)_folder path]]
368 traverseLink: NO];
369 }
370
371 _modification_date = (unsigned int)[[attributes objectForKey: NSFileModificationDate] timeIntervalSince1970];
372 _count = [[_folder messages] count];
373
374 if (lseek(_fd, 0L, SEEK_SET) < 0)
375 {
376 NSLog(@"fseek failed");
377 }
378
379 // We write our cache version, count, modification date and size.
380 write_uint16(_fd, version);
381 write_uint32(_fd, (uint32_t)_count);
382 write_uint32(_fd, _modification_date);
383
384 if ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox)
385 {
386 _size = [attributes fileSize];
387 write_uint32(_fd, _size);
388 }
389
390 // We now update the message flags
391 //NSLog(@"Synching flags for mailbox %@, count = %d", [(CWLocalFolder *)_folder path], _count);
392 for (i = 0; i < _count; i++)
393 {
394 if (read_uint32(_fd, &len) <= 0)
395 {
396 NSLog(@"CSWLocalCacheManger synchronize (%lu/%lu)", (unsigned long)i, (unsigned long)_count);
397 break;
398 }
399 //NSLog(@"len = %d", len);
400
401 if ((NSNull *)(aMessage = [[_folder messages] objectAtIndex: i]) != [NSNull null])
402 {
403 flags = ((CWFlags *)[aMessage flags])->flags;
404 write_uint32(_fd, flags);
405 lseek(_fd, (len-8), SEEK_CUR);
406 //NSLog(@"wrote = %d", flags);
407 }
408 else
409 {
410 lseek(_fd, (len-4), SEEK_CUR);
411 }
412 }
413 //NSLog(@"Done!");
414
415 return (fsync(_fd) == 0);
416 }
417
418
419 //
420 //
421 //
422 - (NSUInteger) count
423 {
424 return _count;
425 }
426
427 //
428 //
429 //
430 - (void) writeRecord: (cache_record *) theRecord
431 {
432 unsigned int len;
433
434 if (lseek(_fd, 0L, SEEK_END) < 0)
435 {
436 NSLog(@"COULD NOT LSEEK TO END OF FILE");
437 abort();
438 }
439
440 // We calculate the length of this record (including the
441 // first five fields, which is 20 bytes long and is added
442 // at the very end)
443 len = 0;
444 len += (unsigned int)[theRecord->from length]+2;
445 len += (unsigned int)[theRecord->in_reply_to length]+2;
446 len += (unsigned int)[theRecord->message_id length]+2;
447 len += (unsigned int)[theRecord->references length]+2;
448 len += (unsigned int)[theRecord->subject length]+2;
449 len += (unsigned int)[theRecord->to length]+2;
450 len += (unsigned int)[theRecord->cc length]+2;
451
452 if ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox)
453 {
454 len += 20;
455 }
456 else
457 {
458 len += strlen(theRecord->filename)+2;
459 len += 16;
460 }
461
462 // We write the length of our entry
463 write_uint32(_fd, len);
464
465 // We write the flags, date, position and the size of the message.
466 write_uint32(_fd, theRecord->flags);
467 write_uint32(_fd, theRecord->date);
468
469 if ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox)
470 {
471 write_uint32(_fd, (uint32_t)theRecord->position);
472 }
473 else
474 {
475 write_string(_fd, (unsigned char *)theRecord->filename, (uint16_t)strlen(theRecord->filename));
476 }
477
478 write_uint32(_fd, theRecord->size);
479
480 // We write the read of our cached headers (From, In-Reply-To, Message-ID, References, Subject and To)
481 write_data(_fd, theRecord->from);
482 write_data(_fd, theRecord->in_reply_to);
483 write_data(_fd, theRecord->message_id);
484 write_data(_fd, theRecord->references);
485 write_data(_fd, theRecord->subject);
486 write_data(_fd, theRecord->to);
487 write_data(_fd, theRecord->cc);
488
489 _count++;
490 }
491
492
493 //
494 // For mbox-based and maildir-base cache:
495 //
496 // This method MUST be called after writing the new mbox
497 // on disk but BEFORE we actually removed the deleted
498 // messages from the allMessages ivar.
499 //
500 //
501 - (void) expunge
502 {
503 NSDictionary *attributes;
504 CWLocalMessage *aMessage;
505 off_t cache_size;
506 NSUInteger i;
507 unsigned int flags, len, total_deleted, total_length, type, v;
508 short delta;
509 char *buf;
510
511 //NSLog(@"rewriting cache");
512
513 // We get the current cache size
514 cache_size = lseek(_fd, 0L, SEEK_END);
515
516 if (lseek(_fd, ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox) ? 14L : 10L, SEEK_SET) < 0)
517 {
518 NSLog(@"fseek failed");
519 abort();
520 }
521
522 total_deleted = total_length = 0;
523 type = [(CWLocalFolder *)_folder type];
524
525 //
526 // We alloc a little bit more memory that we really need in
527 // case we have to rewrite the filename for a maildir cache
528 // and the filename length is greater than the previous one.
529 //
530 buf = (char *)malloc(cache_size+[[_folder messages] count]*10);
531 _count = [[_folder messages] count];
532
533 for (i = 0; i < _count; i++)
534 {
535 if (read_uint32(_fd, &len) <= 0)
536 {
537 NSLog(@"CWLocalCacheManager expunge: record length read error (%lu/%lu)", (unsigned long)i, (unsigned long)_count);
538 break;
539 }
540 aMessage = [[_folder messages] objectAtIndex: i];
541 flags = ((CWFlags *)[aMessage flags])->flags;
542 delta = 0;
543
544 if ((flags&PantomimeDeleted) == PantomimeDeleted)
545 {
546 // We skip over that record
547 lseek(_fd, len-4, SEEK_CUR);
548 total_deleted++;
549 //NSLog(@"Skip %d bytes, index %d!", len, i);
550 }
551 else
552 {
553 //
554 // For mbox-based caches, we must update the file position of
555 // our cache entries and also the size of the message in the cache.
556 //
557 if (type == PantomimeFormatMbox)
558 {
559 // We write the rest of the record into the memory
560 if (read(_fd, (buf+total_length+4), len-4) < 0) { NSLog(@"read failed"); abort(); }
561
562 // We update the position in the mailbox file by
563 // overwriting the current value in memory
564 v = htonl([aMessage filePosition]);
565 memcpy((buf+total_length+12), (char *)&v, 4);
566 //NSLog(@"Wrote file position %d", ntohl(v));
567
568 // We update the size of the message by overwriting
569 // the current value in memory
570 v = htonl([aMessage size]);
571 memcpy((buf+total_length+16), (char *)&v, 4);
572 //NSLog(@"Wrote message size %d", ntohl(v));
573 }
574 //
575 // For maildir-based caches, we must update the filename of our
576 // cache entries in case flags were flushed to the disk.
577 //
578 else
579 {
580 unsigned short c0, c1, old_len, r;
581 char *filename;
582 size_t s_len;
583
584 // We read our Flags, Date, and the first two bytes
585 // of our filename into memory.
586 if (read(_fd, (buf+total_length+4), 10) < 0) { NSLog(@"read failed"); abort(); }
587
588 // We read the length of our previous string
589 c0 = *(buf+total_length+12);
590 c1 = *(buf+total_length+13);
591 old_len = ntohs((c1<<8)|c0);
592
593 //NSLog(@"Previous length = %d Filename = |%@|", old_len, [aMessage mailFilename]);
594 filename = (char *)[[aMessage mailFilename] UTF8String];
595 s_len = strlen(filename);
596 delta = s_len-old_len;
597
598 //if (delta != 0) NSLog(@"i = %d delta = %d |%@| s_len = %d", i, delta, [aMessage mailFilename], s_len);
599
600 // We write back our filename
601 r = htons(s_len);
602 memcpy((buf+total_length+12), (char *)&r, 2);
603 memcpy((buf+total_length+14), filename, s_len);
604
605 // We read the rest in our memory. We first skip or old filename string.
606 if (lseek(_fd, old_len, SEEK_CUR) < 0) { NSLog(@"lseek failed"); abort(); }
607 //NSLog(@"must read back into memory %d bytes", len-old_len-14);
608 if (read(_fd, (buf+total_length+s_len+14), len-old_len-14) < 0) { NSLog(@"read failed"); abort(); }
609 //NSLog(@"current file pos after full read %d", lseek(_fd, 0L, SEEK_CUR));
610 }
611
612 // We write back our record length, adjusting its size if we need
613 // to, in the case we are handling a maildir-based cache.
614 len += (unsigned int)delta;
615 v = htonl(len);
616 memcpy((buf+total_length), (char *)&v, 4);
617
618 total_length += len;
619 //NSLog(@"_size = %d total_length = %d", _size, total_length);
620 }
621 }
622
623 if (lseek(_fd, 0L, SEEK_SET) < 0)
624 {
625 NSLog(@"fseek failed");
626 }
627
628 // We write our cache version, count, modification date our new size
629 cache_size = total_length+([(CWLocalFolder *)_folder type] == PantomimeFormatMbox ? 14 : 10);
630 _count -= total_deleted;
631
632 write_uint16(_fd, version);
633 write_uint32(_fd, (uint32_t)_count);
634
635 if ([(CWLocalFolder *)_folder type] == PantomimeFormatMbox)
636 {
637 attributes = [[NSFileManager defaultManager] fileAttributesAtPath: [(CWLocalFolder *)_folder path]
638 traverseLink: NO];
639
640 _modification_date = (unsigned int)[[attributes fileModificationDate] timeIntervalSince1970];
641 _size = (NSUInteger)[attributes fileSize];
642 write_uint32(_fd, _modification_date);
643 write_uint32(_fd, _size);
644 }
645 else
646 {
647 attributes = [[NSFileManager defaultManager] fileAttributesAtPath: [NSString stringWithFormat: @"%@/cur", [(CWLocalFolder *)_folder path]]
648 traverseLink: NO];
649 _modification_date = (unsigned int)[[attributes fileModificationDate] timeIntervalSince1970];
650 _size = 0;
651 write_uint32(_fd, _modification_date);
652 }
653
654 // We write our memory cache
655 if (write(_fd, buf, total_length) != (ssize_t)total_length)
656 {
657 if (errno == EAGAIN)
658 {
659 // Perhaps we could handle this more gracefully?
660 NSLog(@"EXPUNGE CACHE: WRITE OUT ERROR, EAGAIN");
661 }
662 else
663 {
664 NSLog(@"EXPUNGE CACHE: WRITE OUT INCOMPLETE");
665 }
666 abort();
667 }
668
669 //ftruncate(_fd, _size);
670 if (ftruncate(_fd, cache_size) == -1)
671 {
672
673 if (errno == EACCES || errno == EROFS)
674 NSLog(@"UNABLE TO EXPUNGE CACHE, NOT WRITABLE");
675 else if (errno == EFBIG)
676 NSLog(@"UNABLE TO EXPUNGE CACHE, EFBIG");
677 else
678 NSLog(@"UNABLE TO EXPUNGE CACHE");
679 abort();
680 }
681 free(buf);
682
683 //NSLog(@"Done!");
684 }
685 @end