~ubuntu-dev/ubuntu/lucid/dovecot/lucid-201002101901

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
/* Copyright (c) 2003-2009 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "ioloop.h"
#include "buffer.h"
#include "file-dotlock.h"
#include "nfs-workarounds.h"
#include "read-full.h"
#include "write-full.h"
#include "mmap-util.h"
#include "mail-index-private.h"
#include "mail-index-modseq.h"
#include "mail-transaction-log-private.h"

#define LOG_PREFETCH 1024
#define MEMORY_LOG_NAME "(in-memory transaction log file)"

static void
mail_transaction_log_mark_corrupted(struct mail_transaction_log_file *file)
{
	unsigned int offset =
		offsetof(struct mail_transaction_log_header, indexid);

	if (MAIL_TRANSACTION_LOG_FILE_IN_MEMORY(file))
		return;

	/* indexid=0 marks the log file as corrupted */
	if (pwrite_full(file->fd, &file->hdr.indexid,
			sizeof(file->hdr.indexid), offset) < 0) {
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath, "pwrite()");
	}
}

void
mail_transaction_log_file_set_corrupted(struct mail_transaction_log_file *file,
					const char *fmt, ...)
{
	va_list va;

	file->corrupted = TRUE;
	file->hdr.indexid = 0;
	mail_transaction_log_mark_corrupted(file);

	va_start(va, fmt);
	T_BEGIN {
		mail_index_set_error(file->log->index,
			"Corrupted transaction log file %s seq %u: %s "
			"(sync_offset=%"PRIuUOFF_T")",
			file->filepath, file->hdr.file_seq,
			t_strdup_vprintf(fmt, va), file->sync_offset);
	} T_END;
	va_end(va);
}

struct mail_transaction_log_file *
mail_transaction_log_file_alloc(struct mail_transaction_log *log,
				const char *path)
{
	struct mail_transaction_log_file *file;

	file = i_new(struct mail_transaction_log_file, 1);
	file->log = log;
	file->filepath = i_strdup(path);
	file->fd = -1;
	return file;
}

void mail_transaction_log_file_free(struct mail_transaction_log_file **_file)
{
	struct mail_transaction_log_file *file = *_file;
	struct mail_transaction_log_file **p;
	int old_errno = errno;

	*_file = NULL;

	mail_transaction_log_file_unlock(file);

	for (p = &file->log->files; *p != NULL; p = &(*p)->next) {
		if (*p == file) {
			*p = file->next;
			break;
		}
	}

	if (file == file->log->head)
		file->log->head = NULL;

	if (file->buffer != NULL) 
		buffer_free(&file->buffer);

	if (file->mmap_base != NULL) {
		if (munmap(file->mmap_base, file->mmap_size) < 0) {
			mail_index_file_set_syscall_error(file->log->index,
							  file->filepath,
							  "munmap()");
		}
	}

	if (file->fd != -1) {
		if (close(file->fd) < 0) {
			mail_index_file_set_syscall_error(file->log->index,
							  file->filepath,
							  "close()");
		}
	}

	i_free(file->filepath);
        i_free(file);

        errno = old_errno;
}

static void
mail_transaction_log_file_skip_to_head(struct mail_transaction_log_file *file)
{
	struct mail_transaction_log *log = file->log;
	struct mail_index_map *map = log->index->map;
	const struct mail_index_modseq_header *modseq_hdr;
	uoff_t head_offset;

	if (map == NULL || file->hdr.file_seq != map->hdr.log_file_seq ||
	    map->hdr.log_file_head_offset == 0)
		return;

	/* we can get a valid log offset from index file. initialize
	   sync_offset from it so we don't have to read the whole log
	   file from beginning. */
	head_offset = map->hdr.log_file_head_offset;

	modseq_hdr = mail_index_map_get_modseq_header(map);
	if (head_offset < file->hdr.hdr_size) {
		mail_index_set_error(log->index,
				     "%s: log_file_head_offset too small",
				     log->index->filepath);
		file->sync_offset = file->hdr.hdr_size;
		file->sync_highest_modseq = file->hdr.initial_modseq;
	} else if (modseq_hdr == NULL && file->hdr.initial_modseq == 0) {
		/* modseqs not used yet */
		file->sync_offset = head_offset;
		file->sync_highest_modseq = 0;
	} else if (modseq_hdr == NULL ||
		   modseq_hdr->log_seq != file->hdr.file_seq) {
		/* highest_modseq not synced, start from beginning */
		file->sync_offset = file->hdr.hdr_size;
		file->sync_highest_modseq = file->hdr.initial_modseq;
	} else if (modseq_hdr->log_offset > head_offset) {
		mail_index_set_error(log->index,
				     "%s: modseq_hdr.log_offset too large",
				     log->index->filepath);
		file->sync_offset = file->hdr.hdr_size;
		file->sync_highest_modseq = file->hdr.initial_modseq;
	} else {
		/* start from where we last stopped tracking modseqs */
		file->sync_offset = modseq_hdr->log_offset;
		file->sync_highest_modseq = modseq_hdr->highest_modseq;
	}
	if (file->hdr.file_seq == log->index->map->hdr.log_file_seq) {
		file->saved_tail_offset =
			log->index->map->hdr.log_file_tail_offset;
		file->saved_tail_sync_offset = file->saved_tail_offset;
	}
	if (file->saved_tail_offset > file->max_tail_offset)
		file->max_tail_offset = file->saved_tail_offset;
}

static void
mail_transaction_log_file_add_to_list(struct mail_transaction_log_file *file)
{
	struct mail_transaction_log_file **p;

	file->sync_offset = file->hdr.hdr_size;
	file->sync_highest_modseq = file->hdr.initial_modseq;
	mail_transaction_log_file_skip_to_head(file);

	/* insert it to correct position */
	for (p = &file->log->files; *p != NULL; p = &(*p)->next) {
		if ((*p)->hdr.file_seq > file->hdr.file_seq)
			break;
		i_assert((*p)->hdr.file_seq < file->hdr.file_seq);
	}

	file->next = *p;
	*p = file;
}

static int
mail_transaction_log_init_hdr(struct mail_transaction_log *log,
			      struct mail_transaction_log_header *hdr)
{
	struct mail_index *index = log->index;

	memset(hdr, 0, sizeof(*hdr));
	hdr->major_version = MAIL_TRANSACTION_LOG_MAJOR_VERSION;
	hdr->minor_version = MAIL_TRANSACTION_LOG_MINOR_VERSION;
	hdr->hdr_size = sizeof(struct mail_transaction_log_header);
	hdr->indexid = log->index->indexid;
	hdr->create_stamp = ioloop_time;
#ifndef WORDS_BIGENDIAN
	hdr->compat_flags |= MAIL_INDEX_COMPAT_LITTLE_ENDIAN;
#endif

	if (index->fd != -1) {
		/* not creating index - make sure we have latest header */
		if (!index->mapping) {
			if (mail_index_map(index,
					   MAIL_INDEX_SYNC_HANDLER_HEAD) <= 0)
				return -1;
		} else {
			/* if we got here from mapping, the .log file is
			   corrupted. use whatever values we got from index
			   file */
		}
	}
	if (index->map != NULL) {
		hdr->prev_file_seq = index->map->hdr.log_file_seq;
		hdr->prev_file_offset = index->map->hdr.log_file_head_offset;
		hdr->file_seq = index->map->hdr.log_file_seq + 1;
		hdr->initial_modseq =
			mail_index_map_modseq_get_highest(index->map);
	} else {
		hdr->file_seq = 1;
	}

	if (log->head != NULL) {
		if (hdr->file_seq <= log->head->hdr.file_seq) {
			/* make sure the sequence grows */
			hdr->file_seq = log->head->hdr.file_seq+1;
		}
		if (hdr->initial_modseq < log->head->sync_highest_modseq) {
			/* this should be always up-to-date */
			hdr->initial_modseq = log->head->sync_highest_modseq;
		}
	}
	return 0;
}

struct mail_transaction_log_file *
mail_transaction_log_file_alloc_in_memory(struct mail_transaction_log *log)
{
	struct mail_transaction_log_file *file;

	file = mail_transaction_log_file_alloc(log, MEMORY_LOG_NAME);
	if (mail_transaction_log_init_hdr(log, &file->hdr) < 0) {
		i_free(file);
		return NULL;
	}

	file->buffer = buffer_create_dynamic(default_pool, 4096);
	file->buffer_offset = sizeof(file->hdr);

	mail_transaction_log_file_add_to_list(file);
	return file;
}

static int
mail_transaction_log_file_dotlock(struct mail_transaction_log_file *file)
{
	int ret;

	if (file->log->dotlock_count > 0)
		ret = 1;
	else {
		ret = file_dotlock_create(&file->log->dotlock_settings,
					  file->filepath, 0,
					  &file->log->dotlock);
	}
	if (ret > 0) {
		file->log->dotlock_count++;
		file->locked = TRUE;
		return 0;
	}
	if (ret < 0) {
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath,
						  "file_dotlock_create()");
		return -1;
	}

	mail_index_set_error(file->log->index,
			     "Timeout while waiting for "
			     "dotlock for transaction log file %s",
			     file->filepath);
	file->log->index->index_lock_timeout = TRUE;
	return -1;
}

static int
mail_transaction_log_file_undotlock(struct mail_transaction_log_file *file)
{
	int ret;

	if (--file->log->dotlock_count > 0)
		return 0;

	ret = file_dotlock_delete(&file->log->dotlock);
	if (ret < 0) {
		mail_index_file_set_syscall_error(file->log->index,
			file->filepath, "file_dotlock_delete()");
		return -1;
	}

	if (ret == 0) {
		mail_index_set_error(file->log->index,
			"Dotlock was lost for transaction log file %s",
			file->filepath);
		return -1;
	}
	return 0;
}

int mail_transaction_log_file_lock(struct mail_transaction_log_file *file)
{
	int ret;

	if (file->locked)
		return 0;

	if (MAIL_TRANSACTION_LOG_FILE_IN_MEMORY(file)) {
		file->locked = TRUE;
		return 0;
	}

	if (file->log->index->lock_method == FILE_LOCK_METHOD_DOTLOCK)
		return mail_transaction_log_file_dotlock(file);

	i_assert(file->file_lock == NULL);
	ret = mail_index_lock_fd(file->log->index, file->filepath, file->fd,
				 F_WRLCK, MAIL_TRANSCATION_LOG_LOCK_TIMEOUT,
				 &file->file_lock);
	if (ret > 0) {
		file->locked = TRUE;
		return 0;
	}
	if (ret < 0) {
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath,
						  "mail_index_wait_lock_fd()");
		return -1;
	}

	mail_index_set_error(file->log->index,
		"Timeout while waiting for lock for transaction log file %s",
		file->filepath);
	file->log->index->index_lock_timeout = TRUE;
	return -1;
}

void mail_transaction_log_file_unlock(struct mail_transaction_log_file *file)
{
	if (!file->locked)
		return;

	file->locked = FALSE;

	if (MAIL_TRANSACTION_LOG_FILE_IN_MEMORY(file))
		return;

	if (file->log->index->lock_method == FILE_LOCK_METHOD_DOTLOCK) {
		mail_transaction_log_file_undotlock(file);
		return;
	}

	file_unlock(&file->file_lock);
}

static ssize_t
mail_transaction_log_file_read_header(struct mail_transaction_log_file *file)
{
	ssize_t pos;
	int ret;

	memset(&file->hdr, 0, sizeof(file->hdr));

        /* try to read the whole header, but it's not necessarily an error to
	   read less since the older versions of the log format could be
	   smaller. */
        pos = 0;
	do {
		ret = pread(file->fd, PTR_OFFSET(&file->hdr, pos),
			    sizeof(file->hdr) - pos, pos);
		if (ret > 0)
			pos += ret;
	} while (ret > 0 && pos < (ssize_t)sizeof(file->hdr));
	return ret < 0 ? -1 : pos;
}

static int
mail_transaction_log_file_read_hdr(struct mail_transaction_log_file *file,
				   bool ignore_estale)
{
        struct mail_transaction_log_file *f;
	int ret;

	i_assert(!MAIL_TRANSACTION_LOG_FILE_IN_MEMORY(file));

	if (file->corrupted)
		return 0;

	ret = mail_transaction_log_file_read_header(file);
	if (ret < 0) {
                if (errno != ESTALE || !ignore_estale) {
                        mail_index_file_set_syscall_error(file->log->index,
                                                          file->filepath,
                                                          "pread()");
                }
		return -1;
	}
	if (file->hdr.major_version != MAIL_TRANSACTION_LOG_MAJOR_VERSION) {
		/* incompatible version - fix silently */
		return 0;
	}
	if (ret < MAIL_TRANSACTION_LOG_HEADER_MIN_SIZE) {
		mail_transaction_log_file_set_corrupted(file,
			"unexpected end of file while reading header");
		return 0;
	}

	if (file->hdr.minor_version >= 2 || file->hdr.major_version > 1) {
		/* we have compatibility flags */
		enum mail_index_header_compat_flags compat_flags = 0;

#ifndef WORDS_BIGENDIAN
		compat_flags |= MAIL_INDEX_COMPAT_LITTLE_ENDIAN;
#endif
		if (file->hdr.compat_flags != compat_flags) {
			/* architecture change */
			mail_index_set_error(file->log->index,
					     "Rebuilding index file %s: "
					     "CPU architecture changed",
					     file->log->index->filepath);
			return 0;
		}
	}
	if (file->hdr.hdr_size < MAIL_TRANSACTION_LOG_HEADER_MIN_SIZE) {
		mail_transaction_log_file_set_corrupted(file,
			"Header size too small");
		return 0;
	}
	if (file->hdr.hdr_size < sizeof(file->hdr)) {
		/* @UNSAFE: smaller than we expected - zero out the fields we
		   shouldn't have filled */
		memset(PTR_OFFSET(&file->hdr, file->hdr.hdr_size), 0,
		       sizeof(file->hdr) - file->hdr.hdr_size);
	}

	if (file->hdr.indexid == 0) {
		/* corrupted */
		file->corrupted = TRUE;
		mail_index_set_error(file->log->index,
			"Transaction log file %s: marked corrupted",
			file->filepath);
		return 0;
	}
	if (file->hdr.indexid != file->log->index->indexid) {
		if (file->log->index->indexid != 0 &&
		    !file->log->index->initial_create) {
			/* index file was probably just rebuilt and we don't
			   know about it yet */
			mail_transaction_log_file_set_corrupted(file,
				"indexid changed %u -> %u",
				file->log->index->indexid, file->hdr.indexid);
			return 0;
		}

		/* creating index file. since transaction log is created
		   first, use the indexid in it to create the main index
		   to avoid races. */
		file->log->index->indexid = file->hdr.indexid;
	}

	/* make sure we already don't have a file with the same sequence
	   opened. it shouldn't happen unless the old log file was
	   corrupted. */
	for (f = file->log->files; f != NULL; f = f->next) {
		if (f->hdr.file_seq == file->hdr.file_seq) {
			/* mark the old file corrupted. we can't safely remove
			   it from the list however, so return failure. */
			f->corrupted = TRUE;
			f->hdr.indexid = 0;
			if (strcmp(f->filepath, f->log->head->filepath) != 0) {
				/* only mark .2 corrupted, just to make sure
				   we don't lose any changes from .log in case
				   we're somehow wrong */
				mail_transaction_log_mark_corrupted(f);
				ret = 0;
			} else {
				ret = -1;
			}
			mail_index_set_error(f->log->index,
				"Transaction log %s: "
				"duplicate transaction log sequence (%u)",
				f->filepath, f->hdr.file_seq);
			return ret;
		}
	}

	file->sync_highest_modseq = file->hdr.initial_modseq;
	return 1;
}

static int
mail_transaction_log_file_stat(struct mail_transaction_log_file *file,
			       bool ignore_estale)
{
	struct stat st;

	if (fstat(file->fd, &st) < 0) {
                if (errno != ESTALE || !ignore_estale) {
			mail_index_file_set_syscall_error(file->log->index,
				file->filepath, "fstat()");
                }
		return -1;
	}

	file->st_dev = st.st_dev;
	file->st_ino = st.st_ino;
	file->last_mtime = st.st_mtime;
	file->last_size = st.st_size;
	return 0;
}

static bool
mail_transaction_log_file_is_dupe(struct mail_transaction_log_file *file)
{
	struct mail_transaction_log_file *tmp;

	for (tmp = file->log->files; tmp != NULL; tmp = tmp->next) {
		if (tmp->st_ino == file->st_ino &&
		    CMP_DEV_T(tmp->st_dev, file->st_dev))
			return TRUE;
	}
	return FALSE;
}

static int
mail_transaction_log_file_create2(struct mail_transaction_log_file *file,
				  int new_fd, bool reset,
				  struct dotlock **dotlock)
{
	struct mail_index *index = file->log->index;
	struct stat st;
	const char *path2;
	int fd, ret;
	bool rename_existing;

	if (index->nfs_flush) {
		/* although we check also mtime and file size below, it's done
		   only to fix broken log files. we don't bother flushing
		   attribute cache just for that. */
		nfs_flush_file_handle_cache(file->filepath);
	}

	/* log creation is locked now - see if someone already created it.
	   note that if we're rotating, we need to keep the log locked until
	   the file has been rewritten. and because fcntl() locks are stupid,
	   if we go and open()+close() the file and we had it already opened,
	   its locks are lost. so we use stat() to check if the file has been
	   recreated, although it almost never is. */
	if (reset)
		rename_existing = FALSE;
	else if (nfs_safe_stat(file->filepath, &st) < 0) {
		if (errno != ENOENT) {
			mail_index_file_set_syscall_error(index, file->filepath,
							  "stat()");
			return -1;
		}
		rename_existing = FALSE;
	} else if (st.st_ino == file->st_ino &&
		   CMP_DEV_T(st.st_dev, file->st_dev) &&
		   /* inode/dev checks are enough when we're rotating the file,
		      but not when we're replacing a broken log file */
		   st.st_mtime == file->last_mtime &&
		   (uoff_t)st.st_size == file->last_size) {
		/* no-one else recreated the file */
		rename_existing = TRUE;
	} else {
		/* recreated. use the file if its header is ok */
		fd = nfs_safe_open(file->filepath, O_RDWR);
		if (fd == -1) {
			if (errno != ENOENT) {
				mail_index_file_set_syscall_error(index,
					file->filepath, "open()");
				return -1;
			}
		} else {
			file->fd = fd;
			if (mail_transaction_log_file_read_hdr(file,
							       FALSE) > 0 &&
			    mail_transaction_log_file_stat(file, FALSE) == 0) {
				/* yes, it was ok */
				(void)file_dotlock_delete(dotlock);
				mail_transaction_log_file_add_to_list(file);
				return 0;
			}
			file->fd = -1;
			if (close(fd) < 0) {
				mail_index_file_set_syscall_error(index,
					file->filepath, "close()");
			}
		}
		rename_existing = FALSE;
	}

	if (mail_transaction_log_init_hdr(file->log, &file->hdr) < 0)
		return -1;

	if (reset) {
		file->hdr.prev_file_seq = 0;
		file->hdr.prev_file_offset = 0;
		file->hdr.initial_modseq = 0;
	}

	if (write_full(new_fd, &file->hdr, sizeof(file->hdr)) < 0) {
		mail_index_file_set_syscall_error(index, file->filepath,
						  "write_full()");
		return -1;
	}

	if (index->nfs_flush) {
		/* the header isn't important, so don't bother calling
		   fdatasync() unless NFS is used */
		if (fdatasync(new_fd) < 0) {
			mail_index_file_set_syscall_error(index, file->filepath,
							  "fdatasync()");
			return -1;
		}
	}

	file->fd = new_fd;
	ret = mail_transaction_log_file_stat(file, FALSE);

	if (file->log->head != NULL && file->log->head->locked) {
		/* we'll need to preserve the lock */
		if (mail_transaction_log_file_lock(file) < 0)
			ret = -1;
	}

	/* if we return -1 the dotlock deletion code closes the fd */
	file->fd = -1;
	if (ret < 0)
		return -1;

	/* keep two log files */
	if (rename_existing) {
		/* rename() would be nice and easy way to do this, except then
		   there's a race condition between the rename and
		   file_dotlock_replace(). during that time the log file
		   doesn't exist, which could cause problems. */
		path2 = t_strconcat(file->filepath, ".2", NULL);
		if (unlink(path2) < 0 && errno != ENOENT) {
                        mail_index_set_error(index, "unlink(%s) failed: %m",
					     path2);
			/* try to link() anyway */
		}
		if (nfs_safe_link(file->filepath, path2, FALSE) < 0 &&
		    errno != ENOENT && errno != EEXIST) {
                        mail_index_set_error(index, "link(%s, %s) failed: %m",
					     file->filepath, path2);
			/* ignore the error. we don't care that much about the
			   second log file and we're going to overwrite this
			   first one. */
		}
	}

	if (file_dotlock_replace(dotlock,
				 DOTLOCK_REPLACE_FLAG_DONT_CLOSE_FD) <= 0)
		return -1;

	/* success */
	file->fd = new_fd;
        mail_transaction_log_file_add_to_list(file);
	return 0;
}

int mail_transaction_log_file_create(struct mail_transaction_log_file *file,
				     bool reset)
{
	struct mail_index *index = file->log->index;
	struct dotlock *dotlock;
	mode_t old_mask;
	int fd;

	i_assert(!MAIL_INDEX_IS_IN_MEMORY(index));

	/* With dotlocking we might already have path.lock created, so this
	   filename has to be different. */
	old_mask = umask(index->mode ^ 0666);
	fd = file_dotlock_open(&file->log->new_dotlock_settings,
			       file->filepath, 0, &dotlock);
	umask(old_mask);

	if (fd == -1) {
		mail_index_file_set_syscall_error(index, file->filepath,
						  "file_dotlock_open()");
		return -1;
	}
	mail_index_fchown(index, fd, file_dotlock_get_lock_path(dotlock));

        /* either fd gets used or the dotlock gets deleted and returned fd
           is for the existing file */
        if (mail_transaction_log_file_create2(file, fd, reset, &dotlock) < 0) {
		if (dotlock != NULL)
			(void)file_dotlock_delete(&dotlock);
		return -1;
	}
	return 0;
}

int mail_transaction_log_file_open(struct mail_transaction_log_file *file,
				   bool check_existing)
{
        unsigned int i;
	bool ignore_estale;
	int ret;

        for (i = 0;; i++) {
                file->fd = nfs_safe_open(file->filepath, O_RDWR);
                if (file->fd == -1) {
			if (errno == ENOENT)
				return 0;

			mail_index_file_set_syscall_error(file->log->index,
				file->filepath, "open()");
			return -1;
                }

		ignore_estale = i < MAIL_INDEX_ESTALE_RETRY_COUNT;
		if (mail_transaction_log_file_stat(file, ignore_estale) < 0)
			ret = -1;
		else if (check_existing &&
			 mail_transaction_log_file_is_dupe(file))
			return 0;
		else {
			ret = mail_transaction_log_file_read_hdr(file,
								 ignore_estale);
		}
		if (ret > 0) {
			/* success */
			break;
		}

		if (ret == 0) {
			/* corrupted */
			if (unlink(file->filepath) < 0 && errno != ENOENT) {
				mail_index_set_error(file->log->index,
						     "unlink(%s) failed: %m",
						     file->filepath);
			}
			return 0;
		}
		if (errno != ESTALE ||
		    i == MAIL_INDEX_ESTALE_RETRY_COUNT) {
			/* syscall error */
			return -1;
		}

		/* ESTALE - try again */
        }

	mail_transaction_log_file_add_to_list(file);
	return 1;
}

static int
log_file_track_mailbox_sync_offset_hdr(struct mail_transaction_log_file *file,
				       const void *data, unsigned int size)
{
	const struct mail_transaction_header_update *u = data;
	const struct mail_index_header *ihdr;
	const unsigned int offset_pos =
		offsetof(struct mail_index_header, log_file_tail_offset);
	const unsigned int offset_size = sizeof(ihdr->log_file_tail_offset);
	uint32_t tail_offset;

	i_assert(offset_size == sizeof(tail_offset));

	if (size < sizeof(*u) || size < sizeof(*u) + u->size) {
		mail_transaction_log_file_set_corrupted(file,
			"header update extends beyond record size");
		return -1;
	}

	if (u->offset <= offset_pos &&
	    u->offset + u->size >= offset_pos + offset_size) {
		memcpy(&tail_offset,
		       CONST_PTR_OFFSET(u + 1, offset_pos - u->offset),
		       sizeof(tail_offset));

		if (tail_offset < file->saved_tail_offset) {
			if (file->sync_offset < file->saved_tail_sync_offset) {
				/* saved_tail_offset was already set in header,
				   but we still had to resync the file to find
				   modseqs. ignore this record. */
				return 1;
			}
			mail_index_set_error(file->log->index,
				"Transaction log file %s seq %u: "
				"log_file_tail_offset update shrank it "
				"(%u vs %"PRIuUOFF_T" "
				"sync_offset=%"PRIuUOFF_T")",
				file->filepath, file->hdr.file_seq,
				tail_offset, file->saved_tail_offset,
				file->sync_offset);
		} else {
			file->saved_tail_offset = tail_offset;
			if (tail_offset > file->max_tail_offset)
				file->max_tail_offset = tail_offset;
			return 1;
		}
	}
	return 0;
}

bool
mail_transaction_header_has_modseq(const struct mail_transaction_header *hdr,
				   const void *data,
				   uint64_t cur_modseq)
{
	if (cur_modseq != 0) {
		/* tracking modseqs */
	} else if ((hdr->type & MAIL_TRANSACTION_TYPE_MASK) ==
		   MAIL_TRANSACTION_EXT_INTRO) {
		/* modseqs not tracked yet. see if this is a modseq
		   extension introduction. */
		const struct mail_transaction_ext_intro *intro = data;
		const unsigned int modseq_ext_len =
			strlen(MAIL_INDEX_MODSEQ_EXT_NAME);

		if (intro->name_size == modseq_ext_len &&
		    memcmp(intro + 1, MAIL_INDEX_MODSEQ_EXT_NAME,
			   modseq_ext_len) == 0) {
			/* modseq tracking started */
			return TRUE;
		}
	} else {
		/* not tracking modseqs */
		return FALSE;
	}

	switch (hdr->type & MAIL_TRANSACTION_TYPE_MASK) {
	case MAIL_TRANSACTION_EXPUNGE | MAIL_TRANSACTION_EXPUNGE_PROT:
	case MAIL_TRANSACTION_EXPUNGE_GUID | MAIL_TRANSACTION_EXPUNGE_PROT:
		if ((hdr->type & MAIL_TRANSACTION_EXTERNAL) == 0) {
			/* ignore expunge requests */
			break;
		}
	case MAIL_TRANSACTION_APPEND:
	case MAIL_TRANSACTION_FLAG_UPDATE:
	case MAIL_TRANSACTION_KEYWORD_UPDATE:
	case MAIL_TRANSACTION_KEYWORD_RESET:
	case MAIL_TRANSACTION_UID_UPDATE:
		/* these changes increase modseq */
		return TRUE;
	}
	return FALSE;
}

static struct modseq_cache *
modseq_cache_hit(struct mail_transaction_log_file *file, unsigned int idx)
{
	struct modseq_cache cache;

	if (idx > 0) {
		/* @UNSAFE: move it to top */
		cache = file->modseq_cache[idx];
		memmove(file->modseq_cache + 1, file->modseq_cache,
			sizeof(*file->modseq_cache) * idx);
		file->modseq_cache[0] = cache;
	}
	return &file->modseq_cache[0];
}

static struct modseq_cache *
modseq_cache_get_offset(struct mail_transaction_log_file *file, uoff_t offset)
{
	unsigned int i, best = -1U;

	for (i = 0; i < N_ELEMENTS(file->modseq_cache); i++) {
		if (offset < file->modseq_cache[i].offset)
			continue;

		if (file->modseq_cache[i].offset == 0)
			return NULL;

		if (offset == file->modseq_cache[i].offset) {
			/* exact cache hit */
			return modseq_cache_hit(file, i);
		}

		if (best == -1U ||
		    file->modseq_cache[i].offset <
		    file->modseq_cache[best].offset)
			best = i;
	}
	if (best == -1U)
		return NULL;
	return &file->modseq_cache[best];
}

static struct modseq_cache *
modseq_cache_get_modseq(struct mail_transaction_log_file *file, uint64_t modseq)
{
	unsigned int i, best = -1U;

	for (i = 0; i < N_ELEMENTS(file->modseq_cache); i++) {
		if (modseq < file->modseq_cache[i].highest_modseq)
			continue;

		if (file->modseq_cache[i].offset == 0)
			return NULL;

		if (modseq == file->modseq_cache[i].highest_modseq) {
			/* exact cache hit */
			return modseq_cache_hit(file, i);
		}

		if (best == -1U ||
		    file->modseq_cache[i].highest_modseq <
		    file->modseq_cache[best].highest_modseq)
			best = i;
	}
	if (best == -1U)
		return NULL;
	return &file->modseq_cache[best];
}

static int
log_get_synced_record(struct mail_transaction_log_file *file, uoff_t *offset,
		      const struct mail_transaction_header **hdr_r)
{
	const struct mail_transaction_header *hdr;
	uint32_t trans_size;

	hdr = CONST_PTR_OFFSET(file->buffer->data,
			       *offset - file->buffer_offset);

	/* we've already synced this record at some point. it should
	   be valid. */
	trans_size = mail_index_offset_to_uint32(hdr->size);
	if (trans_size < sizeof(*hdr) ||
	    *offset - file->buffer_offset + trans_size > file->buffer->used) {
		mail_transaction_log_file_set_corrupted(file,
			"Transaction log corrupted unexpectedly at "
			"%"PRIuUOFF_T": Invalid size %u (type=%x)",
			*offset, trans_size, hdr->type);
		return -1;
	}
	*offset += trans_size;
	*hdr_r = hdr;
	return 0;
}

int mail_transaction_log_file_get_highest_modseq_at(
		struct mail_transaction_log_file *file,
		uoff_t offset, uint64_t *highest_modseq_r)
{
	const struct mail_transaction_header *hdr;
	struct modseq_cache *cache;
	uoff_t cur_offset;
	uint64_t cur_modseq;
	int ret;

	i_assert(offset <= file->sync_offset);

	if (offset == file->sync_offset) {
		*highest_modseq_r = file->sync_highest_modseq;
		return 0;
	}

	cache = modseq_cache_get_offset(file, offset);
	if (cache == NULL) {
		/* nothing usable in cache - scan from beginning */
		cur_offset = file->hdr.hdr_size;
		cur_modseq = file->hdr.initial_modseq;
	} else if (cache->offset == offset) {
		/* exact cache hit */
		*highest_modseq_r = cache->highest_modseq;
		return 0;
	} else {
		/* use cache to skip over some records */
		cur_offset = cache->offset;
		cur_modseq = cache->highest_modseq;
	}

	ret = mail_transaction_log_file_map(file, cur_offset, offset);
	if (ret <= 0) {
		if (ret < 0)
			return -1;
		mail_index_set_error(file->log->index,
			"%s: Transaction log corrupted, can't get modseq",
			file->filepath);
		return -1;
	}

	i_assert(cur_offset >= file->buffer_offset);
	i_assert(cur_offset + file->buffer->used >= offset);
	while (cur_offset < offset) {
		if (log_get_synced_record(file, &cur_offset, &hdr) < 0)
			return- 1;
		if (mail_transaction_header_has_modseq(hdr, hdr + 1,
						       cur_modseq))
			cur_modseq++;
	}

	/* @UNSAFE: cache the value */
	memmove(file->modseq_cache + 1, file->modseq_cache,
		sizeof(*file->modseq_cache) *
		(N_ELEMENTS(file->modseq_cache) - 1));
	file->modseq_cache[0].offset = cur_offset;
	file->modseq_cache[0].highest_modseq = cur_modseq;

	*highest_modseq_r = cur_modseq;
	return 0;
}

int mail_transaction_log_file_get_modseq_next_offset(
		struct mail_transaction_log_file *file,
		uint64_t modseq, uoff_t *next_offset_r)
{
	const struct mail_transaction_header *hdr;
	struct modseq_cache *cache;
	uoff_t cur_offset;
	uint64_t cur_modseq;
	int ret;

	if (modseq >= file->sync_highest_modseq) {
		*next_offset_r = file->sync_offset;
		return 0;
	}
	if (modseq == file->hdr.initial_modseq) {
		*next_offset_r = file->hdr.hdr_size;
		return 0;
	}

	cache = modseq_cache_get_modseq(file, modseq);
	if (cache == NULL) {
		/* nothing usable in cache - scan from beginning */
		cur_offset = file->hdr.hdr_size;
		cur_modseq = file->hdr.initial_modseq;
	} else if (cache->highest_modseq == modseq) {
		/* exact cache hit */
		*next_offset_r = cache->offset;
		return 0;
	} else {
		/* use cache to skip over some records */
		cur_offset = cache->offset;
		cur_modseq = cache->highest_modseq;
	}

	ret = mail_transaction_log_file_map(file, cur_offset,
					    file->sync_offset);
	if (ret <= 0) {
		if (ret < 0)
			return -1;
		mail_index_set_error(file->log->index,
			"%s: Transaction log corrupted, can't get modseq",
			file->filepath);
		return -1;
	}

	i_assert(cur_offset >= file->buffer_offset);
	while (cur_offset < file->sync_offset) {
		if (log_get_synced_record(file, &cur_offset, &hdr) < 0)
			return -1;
		if (mail_transaction_header_has_modseq(hdr, hdr + 1,
						       cur_modseq)) {
			if (++cur_modseq == modseq)
				break;
		}
	}
	if (modseq != cur_modseq) {
		/* if we got to sync_offset, cur_modseq should be
		   sync_highest_modseq */
		mail_index_set_error(file->log->index,
			"%s: Transaction log changed unexpectedly, "
			"can't get modseq", file->filepath);
		return -1;
	}

	/* @UNSAFE: cache the value */
	memmove(file->modseq_cache + 1, file->modseq_cache,
		sizeof(*file->modseq_cache) *
		(N_ELEMENTS(file->modseq_cache) - 1));
	file->modseq_cache[0].offset = cur_offset;
	file->modseq_cache[0].highest_modseq = cur_modseq;

	*next_offset_r = cur_offset;
	return 0;
}

static int
log_file_track_sync(struct mail_transaction_log_file *file,
		    const struct mail_transaction_header *hdr,
		    unsigned int trans_size)
{
	const void *data = hdr + 1;
	int ret;

	if (mail_transaction_header_has_modseq(hdr, hdr + 1,
					       file->sync_highest_modseq))
		file->sync_highest_modseq++;
	if ((hdr->type & MAIL_TRANSACTION_EXTERNAL) == 0)
		return 0;

	/* external transactions: */
	if ((hdr->type & MAIL_TRANSACTION_TYPE_MASK) ==
	    MAIL_TRANSACTION_HEADER_UPDATE) {
		/* see if this updates mailbox_sync_offset */
		ret = log_file_track_mailbox_sync_offset_hdr(file, data,
							     trans_size -
							     sizeof(*hdr));
		if (ret != 0)
			return ret < 0 ? -1 : 0;
	}

	if (file->max_tail_offset == file->sync_offset) {
		/* external transactions aren't synced to mailbox. we can
		   update mailbox sync offset to skip this transaction to
		   avoid re-reading it at the next sync. */
		file->max_tail_offset += trans_size;
	}
	return 0;
}

static int
mail_transaction_log_file_sync(struct mail_transaction_log_file *file)
{
        const struct mail_transaction_header *hdr;
	const void *data;
	struct stat st;
	size_t size, avail;
	uint32_t trans_size = 0;

	i_assert(file->sync_offset >= file->buffer_offset);

	data = buffer_get_data(file->buffer, &size);
	while (file->sync_offset - file->buffer_offset + sizeof(*hdr) <= size) {
		hdr = CONST_PTR_OFFSET(data, file->sync_offset -
				       file->buffer_offset);
		trans_size = mail_index_offset_to_uint32(hdr->size);
		if (trans_size == 0) {
			/* unfinished */
			return 1;
		}
		if (trans_size < sizeof(*hdr)) {
			mail_transaction_log_file_set_corrupted(file,
				"hdr.size too small (%u)", trans_size);
			return -1;
		}

		if (file->sync_offset - file->buffer_offset + trans_size > size)
			break;

		/* transaction has been fully written */
		if (log_file_track_sync(file, hdr, trans_size) < 0)
			return -1;

		file->sync_offset += trans_size;
		trans_size = 0;
	}

	if (file->mmap_base != NULL && !file->locked) {
		/* Now that all the mmaped pages have page faulted, check if
		   the file had changed while doing that. Only after the last
		   page has faulted, the size returned by fstat() can be
		   trusted. Otherwise it might point to a page boundary while
		   the next page is still being written.

		   Without this check we might see partial transactions,
		   sometimes causing "Extension record updated without intro
		   prefix" errors. */
		if (fstat(file->fd, &st) < 0) {
			mail_index_file_set_syscall_error(file->log->index,
							  file->filepath,
							  "fstat()");
			return -1;
		}
		if ((uoff_t)st.st_size != file->last_size) {
			file->last_size = st.st_size;
			return 0;
		}
	}

	avail = file->sync_offset - file->buffer_offset;
	if (avail != size) {
		/* There's more data than we could sync at the moment. If the
		   last record's size wasn't valid, we can't know if it will
		   be updated unless we've locked the log. */
		if (trans_size != 0) {
			/* pread()s or the above fstat() check for mmaps should
			   have guaranteed that this doesn't happen */
			mail_transaction_log_file_set_corrupted(file,
				"hdr.size too large (%u)", trans_size);
			return -1;
		} else if (file->locked) {
			mail_transaction_log_file_set_corrupted(file,
				"Unexpected garbage at EOF");
			return -1;
		}

		/* The size field will be updated soon */
		mail_index_flush_read_cache(file->log->index, file->filepath,
					    file->fd, file->locked);
	}

	if (file->next != NULL &&
	    file->hdr.file_seq == file->next->hdr.prev_file_seq &&
	    file->next->hdr.prev_file_offset != file->sync_offset) {
		mail_transaction_log_file_set_corrupted(file,
			"Invalid transaction log size "
			"(%"PRIuUOFF_T" vs %u): %s", file->sync_offset,
			file->log->head->hdr.prev_file_offset, file->filepath);
		return -1;
	}

	return 1;
}

static int
mail_transaction_log_file_insert_read(struct mail_transaction_log_file *file,
				      uoff_t offset)
{
	void *data;
	size_t size;
	ssize_t ret;

	size = file->buffer_offset - offset;
	buffer_copy(file->buffer, size, file->buffer, 0, (size_t)-1);

	data = buffer_get_space_unsafe(file->buffer, 0, size);
	ret = pread_full(file->fd, data, size, offset);
	if (ret > 0) {
		/* success */
		file->buffer_offset -= size;
		return 1;
	}

	/* failure. don't leave ourself to inconsistent state */
	buffer_copy(file->buffer, 0, file->buffer, size, (size_t)-1);
	buffer_set_used_size(file->buffer, file->buffer->used - size);

	if (ret == 0) {
		mail_transaction_log_file_set_corrupted(file, "file shrank");
		return 0;
	} else if (errno == ESTALE) {
		/* log file was deleted in NFS server, fail silently */
		return 0;
	} else {
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath, "pread()");
		return -1;
	}
}

static int
mail_transaction_log_file_read_more(struct mail_transaction_log_file *file)
{
	void *data;
	size_t size;
	uint32_t read_offset;
	ssize_t ret;

	read_offset = file->buffer_offset + buffer_get_used_size(file->buffer);

	do {
		data = buffer_append_space_unsafe(file->buffer, LOG_PREFETCH);
		ret = pread(file->fd, data, LOG_PREFETCH, read_offset);
		if (ret > 0)
			read_offset += ret;

		size = read_offset - file->buffer_offset;
		buffer_set_used_size(file->buffer, size);
	} while (ret > 0 || (ret < 0 && errno == EINTR));

	file->last_size = read_offset;

	if (ret < 0) {
		if (errno == ESTALE) {
			/* log file was deleted in NFS server, fail silently */
			return 0;
		}

		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath, "pread()");
		return -1;
	}
	return 1;
}

static bool
mail_transaction_log_file_need_nfs_flush(struct mail_transaction_log_file *file)
{
	const struct mail_index_header *hdr = &file->log->index->map->hdr;
	uoff_t max_offset = file->last_size;

	if (file->next != NULL &&
	    file->hdr.file_seq == file->next->hdr.prev_file_seq &&
	    file->next->hdr.prev_file_offset != max_offset) {
		/* we already have a newer log file which says that we haven't
		   synced the entire file. */
		return TRUE;
	}

	if (file->hdr.file_seq == hdr->log_file_seq &&
	    max_offset < hdr->log_file_head_offset)
		return TRUE;

	return FALSE;
}

static int
mail_transaction_log_file_read(struct mail_transaction_log_file *file,
			       uoff_t start_offset, bool nfs_flush)
{
	int ret;

	i_assert(file->mmap_base == NULL);

	/* NFS: if file isn't locked, we're optimistic that we can read enough
	   data without flushing attribute cache. if after reading we notice
	   that we really should have read more, flush the cache and try again.
	   if file is locked, the attribute cache was already flushed when
	   refreshing the log. */
	if (file->log->index->nfs_flush && nfs_flush) {
		if (!file->locked)
			nfs_flush_attr_cache_unlocked(file->filepath);
		else {
			nfs_flush_attr_cache_fd_locked(file->filepath,
						       file->fd);
		}
	}

	if (file->buffer != NULL && file->buffer_offset > start_offset) {
		/* we have to insert missing data to beginning of buffer */
		ret = mail_transaction_log_file_insert_read(file, start_offset);
		if (ret <= 0)
			return ret;
	}

	if (file->buffer == NULL) {
		file->buffer =
			buffer_create_dynamic(default_pool, LOG_PREFETCH);
		file->buffer_offset = start_offset;
	}

	if ((ret = mail_transaction_log_file_read_more(file)) <= 0)
		return ret;

	if (file->log->index->nfs_flush && !nfs_flush &&
	    mail_transaction_log_file_need_nfs_flush(file)) {
		/* we didn't read enough data. flush and try again. */
		return mail_transaction_log_file_read(file, start_offset, TRUE);
	}

	if ((ret = mail_transaction_log_file_sync(file)) <= 0) {
		i_assert(ret != 0); /* happens only with mmap */
		return -1;
	}

	i_assert(file->sync_offset >= file->buffer_offset);
	buffer_set_used_size(file->buffer,
			     file->sync_offset - file->buffer_offset);
	return 1;
}

static int
log_file_map_check_offsets(struct mail_transaction_log_file *file,
			   uoff_t start_offset, uoff_t end_offset)
{
	if (start_offset > file->sync_offset) {
		/* broken start offset */
		mail_index_set_error(file->log->index,
			"%s: start_offset (%"PRIuUOFF_T") > "
			"current sync_offset (%"PRIuUOFF_T")",
			file->filepath, start_offset, file->sync_offset);
		return 0;
	}
	if (end_offset != (uoff_t)-1 && end_offset > file->sync_offset) {
		mail_index_set_error(file->log->index,
			"%s: end_offset (%"PRIuUOFF_T") > "
			"current sync_offset (%"PRIuUOFF_T")",
			file->filepath, start_offset, file->sync_offset);
		return 0;
	}

	return 1;
}

static int
mail_transaction_log_file_mmap(struct mail_transaction_log_file *file)
{
	if (file->buffer != NULL) {
		/* in case we just switched to mmaping */
		buffer_free(&file->buffer);
	}
	file->mmap_size = file->last_size;
	file->mmap_base = mmap(NULL, file->mmap_size, PROT_READ, MAP_SHARED,
			       file->fd, 0);
	if (file->mmap_base == MAP_FAILED) {
		file->mmap_base = NULL;
		file->mmap_size = 0;
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath, "mmap()");
		return -1;
	}

	if (file->mmap_size > mmap_get_page_size()) {
		if (madvise(file->mmap_base, file->mmap_size,
			    MADV_SEQUENTIAL) < 0) {
			mail_index_file_set_syscall_error(file->log->index,
				file->filepath, "madvise()");
		}
	}

	file->buffer = buffer_create_const_data(default_pool,
						file->mmap_base,
						file->mmap_size);
	file->buffer_offset = 0;
	return 0;
}

static void
mail_transaction_log_file_munmap(struct mail_transaction_log_file *file)
{
	if (file->mmap_base == NULL)
		return;

	if (munmap(file->mmap_base, file->mmap_size) < 0) {
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath, "munmap()");
	}
	file->mmap_base = NULL;
	file->mmap_size = 0;
	buffer_free(&file->buffer);
}

static int
mail_transaction_log_file_map_mmap(struct mail_transaction_log_file *file,
				   uoff_t start_offset)
{
	struct stat st;
	int ret;

	/* we are going to mmap() this file, but it's not necessarily
	   mmaped currently. */
	i_assert(file->buffer_offset == 0 || file->mmap_base == NULL);
	i_assert(file->mmap_size == 0 || file->mmap_base != NULL);

	if (fstat(file->fd, &st) < 0) {
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath, "fstat()");
		return -1;
	}
	file->last_size = st.st_size;

	if ((uoff_t)st.st_size < file->sync_offset) {
		mail_transaction_log_file_set_corrupted(file,
							"file size shrank");
		return 0;
	}

	if (file->buffer != NULL && file->buffer_offset <= start_offset &&
	    (uoff_t)st.st_size == file->buffer_offset + file->buffer->used) {
		/* we already have the whole file mapped */
		if ((ret = mail_transaction_log_file_sync(file)) < 0)
			return 0;
		if (ret > 0)
			return 1;
		/* size changed, re-mmap */
	}

	do {
		mail_transaction_log_file_munmap(file);

		if (file->last_size - start_offset < mmap_get_page_size()) {
			/* just reading the file is probably faster */
			return mail_transaction_log_file_read(file,
							      start_offset,
							      FALSE);
		}

		if (mail_transaction_log_file_mmap(file) < 0)
			return -1;
		if ((ret = mail_transaction_log_file_sync(file)) < 0)
			return 0;
	} while (ret == 0);

	return 1;
}

int mail_transaction_log_file_map(struct mail_transaction_log_file *file,
				  uoff_t start_offset, uoff_t end_offset)
{
	struct mail_index *index = file->log->index;
	size_t size;
	int ret;

	if (file->hdr.indexid == 0) {
		/* corrupted */
		return 0;
	}

	i_assert(start_offset >= file->hdr.hdr_size);
	i_assert(start_offset <= end_offset);

	if (index->log_locked && file == file->log->head &&
	    end_offset == (uoff_t)-1) {
		/* we're not interested of going further than sync_offset */
		if (log_file_map_check_offsets(file, start_offset,
					       end_offset) == 0)
			return 0;
		i_assert(start_offset <= file->sync_offset);
		end_offset = file->sync_offset;
	}

	if (file->buffer != NULL && file->buffer_offset <= start_offset) {
		/* see if we already have it */
		size = buffer_get_used_size(file->buffer);
		if (file->buffer_offset + size >= end_offset)
			return 1;
	}

	if (MAIL_TRANSACTION_LOG_FILE_IN_MEMORY(file)) {
		if (start_offset < file->buffer_offset) {
			/* we had moved the log to memory but failed to read
			   the beginning of the log file */
			mail_index_set_error(index,
				"%s: Beginning of the log isn't available",
				file->filepath);
			return 0;
		}
		return log_file_map_check_offsets(file, start_offset,
						  end_offset);
	}

	if (start_offset > file->sync_offset)
		mail_transaction_log_file_skip_to_head(file);
	if (start_offset > file->sync_offset) {
		/* although we could just skip over the unwanted data, we have
		   to sync everything so that modseqs are calculated
		   correctly */
		start_offset = file->sync_offset;
	}

	if (!index->mmap_disable)
		ret = mail_transaction_log_file_map_mmap(file, start_offset);
	else {
		mail_transaction_log_file_munmap(file);
		ret = mail_transaction_log_file_read(file, start_offset, FALSE);
	}

	return ret <= 0 ? ret :
		log_file_map_check_offsets(file, start_offset, end_offset);
}

void mail_transaction_log_file_move_to_memory(struct mail_transaction_log_file
					      *file)
{
	buffer_t *buf;

	if (MAIL_TRANSACTION_LOG_FILE_IN_MEMORY(file))
		return;

	if (file->mmap_base != NULL) {
		/* just copy to memory */
		i_assert(file->buffer_offset == 0);

		buf = buffer_create_dynamic(default_pool, file->mmap_size);
		buffer_append(buf, file->mmap_base, file->mmap_size);
		buffer_free(&file->buffer);
		file->buffer = buf;

		/* and lose the mmap */
		if (munmap(file->mmap_base, file->mmap_size) < 0) {
			mail_index_file_set_syscall_error(file->log->index,
							  file->filepath,
							  "munmap()");
		}
		file->mmap_base = NULL;
	} else if (file->buffer_offset != 0) {
		/* we don't have the full log in the memory. read it. */
		(void)mail_transaction_log_file_read(file, 0, FALSE);
	}
	file->last_size = 0;

	if (close(file->fd) < 0) {
		mail_index_file_set_syscall_error(file->log->index,
						  file->filepath, "close()");
	}
	file->fd = -1;

	i_free(file->filepath);
	file->filepath = i_strconcat(file->log->index->filepath,
				     MAIL_TRANSACTION_LOG_SUFFIX, NULL);
}