summaryrefslogtreecommitdiff
path: root/source3/lib/dbwrap_tdb2.c
blob: 9f68ef4a7d63f7018c27737905071c1320732b93 (plain)
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
/*
   Unix SMB/CIFS implementation.

   Database interface wrapper around tdb/ctdb

   Copyright (C) Volker Lendecke 2005-2007
   Copyright (C) Stefan Metzmacher 2008

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "librpc/gen_ndr/ndr_messaging.h"

struct db_tdb2_ctx {
	struct db_context *db;
	const char *name;
	struct tdb_wrap *mtdb;
	const char *mtdb_path;
	bool master_transaction;
	struct {
		int hash_size;
		int tdb_flags;
		int open_flags;
		mode_t mode;
	} open;
	struct tdb_wrap *ltdb;
	const char *ltdb_path;
	bool local_transaction;
	int transaction;
	bool out_of_sync;
	uint32_t lseqnum;
	uint32_t mseqnum;
#define DB_TDB2_MASTER_SEQNUM_KEYSTR "DB_TDB2_MASTER_SEQNUM_KEYSTR"
	TDB_DATA mseqkey;
	uint32_t max_buffer_size;
	uint32_t current_buffer_size;
	struct dbwrap_tdb2_changes changes;
};


static NTSTATUS db_tdb2_store(struct db_record *rec, TDB_DATA data, int flag);
static NTSTATUS db_tdb2_delete(struct db_record *rec);

static void db_tdb2_queue_change(struct db_tdb2_ctx *db_ctx, const TDB_DATA key);
static void db_tdb2_send_notify(struct db_tdb2_ctx *db_ctx);

static struct db_context *db_open_tdb2_ex(TALLOC_CTX *mem_ctx,
					  const char *name,
					  int hash_size, int tdb_flags,
					  int open_flags, mode_t mode,
					  const struct dbwrap_tdb2_changes *chgs);

static int db_tdb2_sync_from_master(struct db_tdb2_ctx *db_ctx,
				    const struct dbwrap_tdb2_changes *changes);

static int db_tdb2_open_master(struct db_tdb2_ctx *db_ctx, bool transaction,
			       const struct dbwrap_tdb2_changes *changes);
static int db_tdb2_commit_local(struct db_tdb2_ctx *db_ctx, uint32_t mseqnum);
static int db_tdb2_close_master(struct db_tdb2_ctx *db_ctx);
static int db_tdb2_transaction_cancel(struct db_context *db);

static void db_tdb2_receive_changes(struct messaging_context *msg,
				    void *private_data,
				    uint32_t msg_type,
				    struct server_id server_id,
				    DATA_BLOB *data);

static struct messaging_context *global_tdb2_msg_ctx;
static bool global_tdb2_msg_ctx_initialized;

void db_tdb2_setup_messaging(struct messaging_context *msg_ctx, bool server)
{
	global_tdb2_msg_ctx = msg_ctx;

	global_tdb2_msg_ctx_initialized = true;

	if (!server) {
		return;
	}

	if (!lp_parm_bool(-1, "dbwrap", "use_tdb2", false)) {
		return;
	}

	messaging_register(msg_ctx, NULL, MSG_DBWRAP_TDB2_CHANGES,
			   db_tdb2_receive_changes);
}

static struct messaging_context *db_tdb2_get_global_messaging_context(void)
{
	struct messaging_context *msg_ctx;

	if (global_tdb2_msg_ctx_initialized) {
		return global_tdb2_msg_ctx;
	}

	msg_ctx = messaging_init(NULL, procid_self(),
				 event_context_init(NULL));

	db_tdb2_setup_messaging(msg_ctx, false);

	return global_tdb2_msg_ctx;
}

struct tdb_fetch_locked_state {
	TALLOC_CTX *mem_ctx;
	struct db_record *result;
};

static int db_tdb2_fetchlock_parse(TDB_DATA key, TDB_DATA data,
				  void *private_data)
{
	struct tdb_fetch_locked_state *state =
		(struct tdb_fetch_locked_state *)private_data;

	state->result = (struct db_record *)talloc_size(
		state->mem_ctx,
		sizeof(struct db_record) + key.dsize + data.dsize);

	if (state->result == NULL) {
		return 0;
	}

	state->result->key.dsize = key.dsize;
	state->result->key.dptr = ((uint8 *)state->result)
		+ sizeof(struct db_record);
	memcpy(state->result->key.dptr, key.dptr, key.dsize);

	state->result->value.dsize = data.dsize;

	if (data.dsize > 0) {
		state->result->value.dptr = state->result->key.dptr+key.dsize;
		memcpy(state->result->value.dptr, data.dptr, data.dsize);
	}
	else {
		state->result->value.dptr = NULL;
	}

	return 0;
}

static struct db_record *db_tdb2_fetch_locked(struct db_context *db,
					      TALLOC_CTX *mem_ctx, TDB_DATA key)
{
	struct db_tdb2_ctx *ctx = talloc_get_type_abort(db->private_data,
							struct db_tdb2_ctx);
	struct tdb_fetch_locked_state state;

	/* Do not accidently allocate/deallocate w/o need when debug level is lower than needed */
	if(DEBUGLEVEL >= 10) {
		char *keystr = hex_encode(NULL, (unsigned char*)key.dptr, key.dsize);
		DEBUG(10, (DEBUGLEVEL > 10
			   ? "Locking key %s\n" : "Locking key %.20s\n",
			   keystr));
		TALLOC_FREE(keystr);
	}

	/*
	 * we only support modifications within a
	 * started transaction.
	 */
	if (ctx->transaction == 0) {
		DEBUG(0, ("db_tdb2_fetch_locked[%s]: no transaction started\n",
			  ctx->name));
		smb_panic("no transaction");
		return NULL;
	}

	state.mem_ctx = mem_ctx;
	state.result = NULL;

	tdb_parse_record(ctx->mtdb->tdb, key, db_tdb2_fetchlock_parse, &state);

	if (state.result == NULL) {
		db_tdb2_fetchlock_parse(key, tdb_null, &state);
	}

	if (state.result == NULL) {
		return NULL;
	}

	state.result->private_data = talloc_reference(state.result, ctx);
	state.result->store = db_tdb2_store;
	state.result->delete_rec = db_tdb2_delete;

	DEBUG(10, ("Allocated locked data 0x%p\n", state.result));

	return state.result;
}

struct tdb_fetch_state {
	TALLOC_CTX *mem_ctx;
	int result;
	TDB_DATA data;
};

static int db_tdb2_fetch_parse(TDB_DATA key, TDB_DATA data,
			       void *private_data)
{
	struct tdb_fetch_state *state =
		(struct tdb_fetch_state *)private_data;

	state->data.dptr = (uint8 *)talloc_memdup(state->mem_ctx, data.dptr,
						  data.dsize);
	if (state->data.dptr == NULL) {
		state->result = -1;
		return 0;
	}

	state->data.dsize = data.dsize;
	return 0;
}

static void db_tdb2_resync_before_read(struct db_tdb2_ctx *db_ctx, TDB_DATA *kbuf)
{
	if (db_ctx->mtdb) {
		return;
	}

	if (!db_ctx->out_of_sync) {
		return;
	}

	/*
	 * this function operates on the local copy,
	 * so hide the DB_TDB2_MASTER_SEQNUM_KEYSTR from the caller.
	 */
	if (kbuf && (db_ctx->mseqkey.dsize == kbuf->dsize) &&
	    (memcmp(db_ctx->mseqkey.dptr, kbuf->dptr, kbuf->dsize) == 0)) {
		return;
	}

	DEBUG(0,("resync_before_read[%s/%s]\n",
		 db_ctx->mtdb_path, db_ctx->ltdb_path));

	db_tdb2_open_master(db_ctx, false, NULL);
	db_tdb2_close_master(db_ctx);
}

static int db_tdb2_fetch(struct db_context *db, TALLOC_CTX *mem_ctx,
			 TDB_DATA key, TDB_DATA *pdata)
{
	struct db_tdb2_ctx *ctx = talloc_get_type_abort(
		db->private_data, struct db_tdb2_ctx);

	struct tdb_fetch_state state;

	db_tdb2_resync_before_read(ctx, &key);

	if (ctx->out_of_sync) {
		DEBUG(0,("out of sync[%s] failing fetch\n",
			 ctx->ltdb_path));
		errno = EIO;
		return -1;
	}

	state.mem_ctx = mem_ctx;
	state.result = 0;
	state.data = tdb_null;

	tdb_parse_record(ctx->ltdb->tdb, key, db_tdb2_fetch_parse, &state);

	if (state.result == -1) {
		return -1;
	}

	*pdata = state.data;
	return 0;
}

static NTSTATUS db_tdb2_store(struct db_record *rec, TDB_DATA data, int flag)
{
	struct db_tdb2_ctx *ctx = talloc_get_type_abort(rec->private_data,
						       struct db_tdb2_ctx);
	int ret;

	/*
	 * This has a bug: We need to replace rec->value for correct
	 * operation, but right now brlock and locking don't use the value
	 * anymore after it was stored.
	 */

	/* first store it to the master copy */
	ret = tdb_store(ctx->mtdb->tdb, rec->key, data, flag);
	if (ret != 0) {
		return NT_STATUS_UNSUCCESSFUL;
	}

	/* then store it to the local copy */
	ret = tdb_store(ctx->ltdb->tdb, rec->key, data, flag);
	if (ret != 0) {
		/* try to restore the old value in the master copy */
		if (rec->value.dptr) {
			tdb_store(ctx->mtdb->tdb, rec->key,
				  rec->value, TDB_REPLACE);
		} else {
			tdb_delete(ctx->mtdb->tdb, rec->key);
		}
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	db_tdb2_queue_change(ctx, rec->key);

	return NT_STATUS_OK;
}

static NTSTATUS db_tdb2_delete(struct db_record *rec)
{
	struct db_tdb2_ctx *ctx = talloc_get_type_abort(rec->private_data,
						       struct db_tdb2_ctx);
	int ret;

	ret = tdb_delete(ctx->mtdb->tdb, rec->key);
	if (ret != 0) {
		if (tdb_error(ctx->mtdb->tdb) == TDB_ERR_NOEXIST) {
			return NT_STATUS_NOT_FOUND;
		}

		return NT_STATUS_UNSUCCESSFUL;
	}

	ret = tdb_delete(ctx->ltdb->tdb, rec->key);
	if (ret != 0) {
		/* try to restore the value in the master copy */
		tdb_store(ctx->mtdb->tdb, rec->key,
			  rec->value, TDB_REPLACE);
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	db_tdb2_queue_change(ctx, rec->key);

	return NT_STATUS_OK;
}

struct db_tdb2_traverse_ctx {
	struct db_tdb2_ctx *db_ctx;
	int (*f)(struct db_record *rec, void *private_data);
	void *private_data;
};

static int db_tdb2_traverse_func(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
				void *private_data)
{
	struct db_tdb2_traverse_ctx *ctx =
		(struct db_tdb2_traverse_ctx *)private_data;
	struct db_record rec;

	/* this function operates on the master copy */

	rec.key = kbuf;
	rec.value = dbuf;
	rec.store = db_tdb2_store;
	rec.delete_rec = db_tdb2_delete;
	rec.private_data = ctx->db_ctx;

	return ctx->f(&rec, ctx->private_data);
}

static int db_tdb2_traverse(struct db_context *db,
			   int (*f)(struct db_record *rec, void *private_data),
			   void *private_data)
{
	struct db_tdb2_ctx *db_ctx =
		talloc_get_type_abort(db->private_data, struct db_tdb2_ctx);
	struct db_tdb2_traverse_ctx ctx;

	/*
	 * we only support modifications within a
	 * started transaction.
	 */
	if (db_ctx->transaction == 0) {
		DEBUG(0, ("db_tdb2_traverse[%s]: no transaction started\n",
			  db_ctx->name));
		smb_panic("no transaction");
		return -1;
	}

	/* here we traverse the master copy */
	ctx.db_ctx = db_ctx;
	ctx.f = f;
	ctx.private_data = private_data;
	return tdb_traverse(db_ctx->mtdb->tdb, db_tdb2_traverse_func, &ctx);
}

static NTSTATUS db_tdb2_store_deny(struct db_record *rec, TDB_DATA data, int flag)
{
	return NT_STATUS_MEDIA_WRITE_PROTECTED;
}

static NTSTATUS db_tdb2_delete_deny(struct db_record *rec)
{
	return NT_STATUS_MEDIA_WRITE_PROTECTED;
}

static int db_tdb2_traverse_read_func(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
				void *private_data)
{
	struct db_tdb2_traverse_ctx *ctx =
		(struct db_tdb2_traverse_ctx *)private_data;
	struct db_record rec;

	/*
	 * this function operates on the local copy,
	 * so hide the DB_TDB2_MASTER_SEQNUM_KEYSTR from the caller.
	 */
	if ((ctx->db_ctx->mseqkey.dsize == kbuf.dsize) &&
	    (memcmp(ctx->db_ctx->mseqkey.dptr, kbuf.dptr, kbuf.dsize) == 0)) {
		return 0;
	}

	rec.key = kbuf;
	rec.value = dbuf;
	rec.store = db_tdb2_store_deny;
	rec.delete_rec = db_tdb2_delete_deny;
	rec.private_data = ctx->db_ctx;

	return ctx->f(&rec, ctx->private_data);
}

static int db_tdb2_traverse_read(struct db_context *db,
			   int (*f)(struct db_record *rec, void *private_data),
			   void *private_data)
{
	struct db_tdb2_ctx *db_ctx =
		talloc_get_type_abort(db->private_data, struct db_tdb2_ctx);
	struct db_tdb2_traverse_ctx ctx;
	int ret;

	db_tdb2_resync_before_read(db_ctx, NULL);

	if (db_ctx->out_of_sync) {
		DEBUG(0,("out of sync[%s] failing traverse_read\n",
			 db_ctx->ltdb_path));
		errno = EIO;
		return -1;
	}

	/* here we traverse the local copy */
	ctx.db_ctx = db_ctx;
	ctx.f = f;
	ctx.private_data = private_data;
	ret = tdb_traverse_read(db_ctx->ltdb->tdb, db_tdb2_traverse_read_func, &ctx);
	if (ret > 0) {
		/* we have filtered one entry */
		ret--;
	}

	return ret;
}

static int db_tdb2_get_seqnum(struct db_context *db)

{
	struct db_tdb2_ctx *db_ctx =
		talloc_get_type_abort(db->private_data, struct db_tdb2_ctx);
	uint32_t nlseq;
	uint32_t nmseq;
	bool ok;

	nlseq = tdb_get_seqnum(db_ctx->ltdb->tdb);

	if (nlseq == db_ctx->lseqnum) {
		return db_ctx->mseqnum;
	}

	ok = tdb_fetch_uint32_byblob(db_ctx->ltdb->tdb,
				     db_ctx->mseqkey,
				     &nmseq);
	if (!ok) {
		/* TODO: what should we do here? */
		return db_ctx->mseqnum;
	}

	db_ctx->lseqnum = nlseq;
	db_ctx->mseqnum = nmseq;

	return db_ctx->mseqnum;
}

static int db_tdb2_transaction_start(struct db_context *db)
{
	struct db_tdb2_ctx *db_ctx =
		talloc_get_type_abort(db->private_data, struct db_tdb2_ctx);
	int ret;

	if (db_ctx->transaction) {
		db_ctx->transaction++;
		return 0;
	}

	/* we need to open the master tdb in order to */
	ret = db_tdb2_open_master(db_ctx, true, NULL);
	if (ret != 0) {
		return ret;
	}

	ret = tdb_transaction_start(db_ctx->ltdb->tdb);
	if (ret != 0) {
		db_tdb2_close_master(db_ctx);
		return ret;
	}

	db_ctx->local_transaction = true;
	db_ctx->transaction = 1;

	return 0;
}

static void db_tdb2_queue_change(struct db_tdb2_ctx *db_ctx, const TDB_DATA key)
{
	size_t size_needed = 4 + key.dsize;
	size_t size_new = db_ctx->current_buffer_size + size_needed;
	uint32_t i;
	DATA_BLOB *keys;

	db_ctx->changes.num_changes++;

	if (db_ctx->changes.num_changes > 1 &&
	    db_ctx->changes.keys == NULL) {
		/*
		 * this means we already overflowed
		 */
		return;
	}

	if (db_ctx->changes.num_changes == 1) {
		db_ctx->changes.old_seqnum = db_ctx->mseqnum;
	}

	for (i=0; i < db_ctx->changes.num_keys; i++) {
		int ret;

		if (key.dsize != db_ctx->changes.keys[i].length) {
			continue;
		}
		ret = memcmp(key.dptr, db_ctx->changes.keys[i].data, key.dsize);
		if (ret != 0) {
			continue;
		}

		/*
		 * the key is already in the list
		 * so we're done
		 */
		return;
	}

	if (db_ctx->max_buffer_size < size_new) {
		goto overflow;
	}

	keys = TALLOC_REALLOC_ARRAY(db_ctx, db_ctx->changes.keys,
				    DATA_BLOB,
				    db_ctx->changes.num_keys + 1);
	if (!keys) {
		goto overflow;
	}
	db_ctx->changes.keys = keys;

	keys[db_ctx->changes.num_keys].data = (uint8_t *)talloc_memdup(keys,
								key.dptr,
								key.dsize);
	if (!keys[db_ctx->changes.num_keys].data) {
		goto overflow;
	}
	keys[db_ctx->changes.num_keys].length = key.dsize;
	db_ctx->changes.num_keys++;
	db_ctx->current_buffer_size = size_new;

	return;

overflow:
	/*
	 * on overflow discard the buffer and let
	 * the others reload the whole tdb
	 */
	db_ctx->current_buffer_size = 0;
	db_ctx->changes.num_keys = 0;
	TALLOC_FREE(db_ctx->changes.keys);
	return;
}

static void db_tdb2_send_notify(struct db_tdb2_ctx *db_ctx)
{
	enum ndr_err_code ndr_err;
	bool ok;
	DATA_BLOB blob;
	struct messaging_context *msg_ctx;
	int num_msgs = 0;
	struct server_id self = procid_self();

	msg_ctx = db_tdb2_get_global_messaging_context();

	db_ctx->changes.name = db_ctx->name;

	DEBUG(10,("%s[%s] size[%u/%u] changes[%u] keys[%u] seqnum[%u=>%u]\n",
		 __FUNCTION__,
		 db_ctx->changes.name,
		 db_ctx->current_buffer_size,
		 db_ctx->max_buffer_size,
		 db_ctx->changes.num_changes,
		 db_ctx->changes.num_keys,
		 db_ctx->changes.old_seqnum,
		 db_ctx->changes.new_seqnum));

	if (db_ctx->changes.num_changes == 0) {
		DEBUG(10,("db_tdb2_send_notify[%s]: no changes\n",
			db_ctx->changes.name));
		goto done;
	}

	if (!msg_ctx) {
		DEBUG(1,("db_tdb2_send_notify[%s]: skipped (no msg ctx)\n",
			db_ctx->changes.name));
		goto done;
	}

	ndr_err = ndr_push_struct_blob(
		&blob, talloc_tos(), &db_ctx->changes,
		(ndr_push_flags_fn_t)ndr_push_dbwrap_tdb2_changes);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		DEBUG(0,("db_tdb2_send_notify[%s]: failed to push changes: %s\n",
			db_ctx->changes.name,
			nt_errstr(ndr_map_error2ntstatus(ndr_err))));
		goto done;
	}

	ok = message_send_all(msg_ctx, MSG_DBWRAP_TDB2_CHANGES,
			      blob.data, blob.length, &num_msgs);
	if (!ok) {
		DEBUG(0,("db_tdb2_send_notify[%s]: failed to send changes\n",
			db_ctx->changes.name));
		goto done;
	}

	DEBUG(10,("db_tdb2_send_notify[%s]: pid %s send %u messages\n",
		db_ctx->name, procid_str_static(&self), num_msgs));

done:
	TALLOC_FREE(db_ctx->changes.keys);
	ZERO_STRUCT(db_ctx->changes);

	return;
}

static void db_tdb2_receive_changes(struct messaging_context *msg,
				    void *private_data,
				    uint32_t msg_type,
				    struct server_id server_id,
				    DATA_BLOB *data)
{
	enum ndr_err_code ndr_err;
	struct dbwrap_tdb2_changes changes;
	struct db_context *db;
	struct server_id self;

	if (procid_is_me(&server_id)) {
		DEBUG(0,("db_tdb2_receive_changes: ignore selfpacket\n"));
		return;
	}

	self = procid_self();

	DEBUG(10,("db_tdb2_receive_changes: from %s to %s\n",
		procid_str(debug_ctx(), &server_id),
		procid_str(debug_ctx(), &self)));

	ndr_err = ndr_pull_struct_blob_all(
		data, talloc_tos(), &changes,
		(ndr_pull_flags_fn_t)ndr_pull_dbwrap_tdb2_changes);
	if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
		DEBUG(0,("db_tdb2_receive_changes: failed to pull changes: %s\n",
			nt_errstr(ndr_map_error2ntstatus(ndr_err))));
		goto done;
	}

	if(DEBUGLEVEL >= 10) {
		NDR_PRINT_DEBUG(dbwrap_tdb2_changes, &changes);
	}

	/* open the db, this will sync it */
	db = db_open_tdb2_ex(talloc_tos(), changes.name, 0,
			     0, O_RDWR, 0600, &changes);
	TALLOC_FREE(db);
done:
	return;
}

static int db_tdb2_transaction_commit(struct db_context *db)
{
	struct db_tdb2_ctx *db_ctx =
		talloc_get_type_abort(db->private_data, struct db_tdb2_ctx);
	int ret;
	uint32_t mseqnum;

	if (db_ctx->transaction == 0) {
		return -1;
	} else if (db_ctx->transaction > 1) {
		db_ctx->transaction--;
		return 0;
	}

	mseqnum = tdb_get_seqnum(db_ctx->mtdb->tdb);
	db_ctx->changes.new_seqnum = mseqnum;

	/* first commit to the master copy */
	ret = tdb_transaction_commit(db_ctx->mtdb->tdb);
	db_ctx->master_transaction = false;
	if (ret != 0) {
		int saved_errno = errno;
		db_tdb2_transaction_cancel(db);
		errno = saved_errno;
		return ret;
	}

	/*
	 * Note: as we've already commited the changes to the master copy
	 * 	 so we ignore errors in the following functions
	 */
	ret = db_tdb2_commit_local(db_ctx, mseqnum);
	if (ret == 0) {
		db_ctx->out_of_sync = false;
	} else {
		db_ctx->out_of_sync = true;
	}

	db_ctx->transaction = 0;

	db_tdb2_close_master(db_ctx);

	db_tdb2_send_notify(db_ctx);

	return 0;
}

static int db_tdb2_transaction_cancel(struct db_context *db)
{
	struct db_tdb2_ctx *db_ctx =
		talloc_get_type_abort(db->private_data, struct db_tdb2_ctx);
	int saved_errno;
	int ret;

	if (db_ctx->transaction == 0) {
		return -1;
	}
	if (db_ctx->transaction > 1) {
		db_ctx->transaction--;
		return 0;
	}

	/* cancel the transaction and close the master copy */
	ret = db_tdb2_close_master(db_ctx);
	saved_errno = errno;

	/* now cancel on the local copy and ignore any error */
	tdb_transaction_cancel(db_ctx->ltdb->tdb);
	db_ctx->local_transaction = false;

	db_ctx->transaction = 0;

	errno = saved_errno;
	return ret;
}

static int db_tdb2_open_master(struct db_tdb2_ctx *db_ctx, bool transaction,
			       const struct dbwrap_tdb2_changes *changes)
{
	int ret;

	db_ctx->mtdb = tdb_wrap_open(db_ctx,
				     db_ctx->mtdb_path,
				     db_ctx->open.hash_size,
				     db_ctx->open.tdb_flags|TDB_NOMMAP|TDB_SEQNUM,
				     db_ctx->open.open_flags,
				     db_ctx->open.mode);
	if (db_ctx->mtdb == NULL) {
		DEBUG(0, ("Could not open master tdb[%s]: %s\n",
			  db_ctx->mtdb_path,
			  strerror(errno)));
		return -1;
	}
	DEBUG(10,("open_master[%s]\n", db_ctx->mtdb_path));

	if (!db_ctx->ltdb) {
		struct stat st;

		if (fstat(tdb_fd(db_ctx->mtdb->tdb), &st) == 0) {
			db_ctx->open.mode = st.st_mode;
		}

		/* make sure the local one uses the same hash size as the master one */
		db_ctx->open.hash_size = tdb_hash_size(db_ctx->mtdb->tdb);

		db_ctx->ltdb = tdb_wrap_open(db_ctx,
					     db_ctx->ltdb_path,
					     db_ctx->open.hash_size,
					     db_ctx->open.tdb_flags|TDB_SEQNUM,
					     db_ctx->open.open_flags|O_CREAT,
					     db_ctx->open.mode);
		if (db_ctx->ltdb == NULL) {
			DEBUG(0, ("Could not open local tdb[%s]: %s\n",
				  db_ctx->ltdb_path,
				  strerror(errno)));
			TALLOC_FREE(db_ctx->mtdb);
			return -1;
		}
		DEBUG(10,("open_local[%s]\n", db_ctx->ltdb_path));
	}

	if (transaction) {
		ret = tdb_transaction_start(db_ctx->mtdb->tdb);
		if (ret != 0) {
			DEBUG(0,("open failed to start transaction[%s]\n",
				 db_ctx->mtdb_path));
			db_tdb2_close_master(db_ctx);
			return ret;
		}
		db_ctx->master_transaction = true;
	}

	ret = db_tdb2_sync_from_master(db_ctx, changes);
	if (ret != 0) {
		DEBUG(0,("open failed to sync from master[%s]\n",
			 db_ctx->ltdb_path));
		db_tdb2_close_master(db_ctx);
		return ret;
	}

	return 0;
}

static int db_tdb2_commit_local(struct db_tdb2_ctx *db_ctx, uint32_t mseqnum)
{
	bool ok;
	int ret;

	/* first fetch the master seqnum */
	db_ctx->mseqnum = mseqnum;

	/* now we try to store the master seqnum in the local tdb */
	ok = tdb_store_uint32_byblob(db_ctx->ltdb->tdb,
				     db_ctx->mseqkey,
				     db_ctx->mseqnum);
	if (!ok) {
		tdb_transaction_cancel(db_ctx->ltdb->tdb);
		db_ctx->local_transaction = false;
		DEBUG(0,("local failed[%s] store mseq[%u]\n",
			 db_ctx->ltdb_path, db_ctx->mseqnum));
		return -1;
	}

	/* now commit all changes to the local tdb */
	ret = tdb_transaction_commit(db_ctx->ltdb->tdb);
	db_ctx->local_transaction = false;
	if (ret != 0) {
		DEBUG(0,("local failed[%s] commit mseq[%u]\n",
			 db_ctx->ltdb_path, db_ctx->mseqnum));
		return ret;
	}

	/*
	 * and update the cached local seqnum this is needed to
	 * let us cache the master seqnum.
	 */
	db_ctx->lseqnum = tdb_get_seqnum(db_ctx->ltdb->tdb);
	DEBUG(10,("local updated[%s] mseq[%u]\n",
		  db_ctx->ltdb_path, db_ctx->mseqnum));

	return 0;
}

static int db_tdb2_close_master(struct db_tdb2_ctx *db_ctx)
{
	if (db_ctx->master_transaction) {
		tdb_transaction_cancel(db_ctx->mtdb->tdb);
	}
	db_ctx->master_transaction = false;
	/* now we can close the master handle */
	TALLOC_FREE(db_ctx->mtdb);

	DEBUG(10,("close_master[%s] ok\n", db_ctx->mtdb_path));
	return 0;
}

static int db_tdb2_traverse_sync_all_func(TDB_CONTEXT *tdb,
					  TDB_DATA kbuf, TDB_DATA dbuf,
					  void *private_data)
{
	struct db_tdb2_traverse_ctx *ctx =
		(struct db_tdb2_traverse_ctx *)private_data;
	uint32_t *seqnum = (uint32_t *)ctx->private_data;
	int ret;

	DEBUG(10,("sync_entry[%s]\n", ctx->db_ctx->mtdb_path));

	/* Do not accidently allocate/deallocate w/o need when debug level is lower than needed */
	if(DEBUGLEVEL >= 10) {
		char *keystr = hex_encode(NULL, (unsigned char*)kbuf.dptr, kbuf.dsize);
		DEBUG(10, (DEBUGLEVEL > 10
			   ? "Locking key %s\n" : "Locking key %.20s\n",
			   keystr));
		TALLOC_FREE(keystr);
	}

	ret = tdb_store(ctx->db_ctx->ltdb->tdb, kbuf, dbuf, TDB_INSERT);
	if (ret != 0) {
		DEBUG(0,("sync_entry[%s] %d: %s\n",
			ctx->db_ctx->ltdb_path, ret,
			tdb_errorstr(ctx->db_ctx->ltdb->tdb)));
		return ret;
	}

	*seqnum = tdb_get_seqnum(ctx->db_ctx->mtdb->tdb);

	return 0;
}

static int db_tdb2_sync_all(struct db_tdb2_ctx *db_ctx, uint32_t *seqnum)
{
	struct db_tdb2_traverse_ctx ctx;
	int ret;

	ret = tdb_wipe_all(db_ctx->ltdb->tdb);
	if (ret != 0) {
		DEBUG(0,("tdb_wipe_all[%s] failed %d: %s\n",
			 db_ctx->ltdb_path, ret,
			 tdb_errorstr(db_ctx->ltdb->tdb)));
		return ret;
	}

	ctx.db_ctx = db_ctx;
	ctx.f = NULL;
	ctx.private_data = seqnum;
	ret = tdb_traverse_read(db_ctx->mtdb->tdb,
				db_tdb2_traverse_sync_all_func,
				&ctx);
	DEBUG(10,("db_tdb2_sync_all[%s] count[%d]\n",
		  db_ctx->mtdb_path, ret));
	if (ret < 0) {
		return ret;
	}

	return 0;
}

static int db_tdb2_sync_changes(struct db_tdb2_ctx *db_ctx,
				const struct dbwrap_tdb2_changes *changes,
				uint32_t *seqnum)
{
	uint32_t cseqnum;
	uint32_t mseqnum;
	uint32_t i;
	int ret;
	bool need_full_sync = false;

	DEBUG(10,("db_tdb2_sync_changes[%s] changes[%u]\n",
		  changes->name, changes->num_changes));
	if(DEBUGLEVEL >= 10) {
		NDR_PRINT_DEBUG(dbwrap_tdb2_changes, discard_const(changes));
	}

	/* for the master tdb for reading */
	ret = tdb_lockall_read(db_ctx->mtdb->tdb);
	if (ret != 0) {
		DEBUG(0,("tdb_lockall_read[%s] %d\n", db_ctx->mtdb_path, ret));
		return ret;
	}

	/* first fetch seqnum we know about */
	cseqnum = db_tdb2_get_seqnum(db_ctx->db);

	/* then fetch the master seqnum */
	mseqnum = tdb_get_seqnum(db_ctx->mtdb->tdb);

	if (cseqnum == mseqnum) {
		DEBUG(10,("db_tdb2_sync_changes[%s] uptodate[%u]\n",
			  db_ctx->mtdb_path, mseqnum));
		/* we hit a race before and now noticed we're uptodate */
		goto done;
	}

	/* now see if the changes describe what we need */
	if (changes->old_seqnum != cseqnum) {
		need_full_sync = true;
	}

	if (changes->new_seqnum != mseqnum) {
		need_full_sync = true;
	}

	/* this was the overflow case */
	if (changes->num_keys == 0) {
		need_full_sync = true;
	}

	if (need_full_sync) {
		tdb_unlockall_read(db_ctx->mtdb->tdb);
		DEBUG(0,("fallback to full sync[%s] seq[%u=>%u] keys[%u]\n",
			db_ctx->ltdb_path, cseqnum, mseqnum,
			changes->num_keys));
		return db_tdb2_sync_all(db_ctx, &mseqnum);
	}

	for (i=0; i < changes->num_keys; i++) {
		const char *op = NULL;
		bool del = false;
		TDB_DATA key;
		TDB_DATA val;

		key.dsize = changes->keys[i].length;
		key.dptr = changes->keys[i].data;

		val = tdb_fetch(db_ctx->mtdb->tdb, key);
		ret = tdb_error(db_ctx->mtdb->tdb);
		if (ret == TDB_ERR_NOEXIST) {
			del = true;
		} else if (ret != 0) {
			DEBUG(0,("sync_changes[%s] failure %d\n",
				 db_ctx->mtdb_path, ret));
			goto failed;
		}

		if (del) {
			op = "delete";
			ret = tdb_delete(db_ctx->ltdb->tdb, key);
			DEBUG(10,("sync_changes[%s] delete key[%u] %d\n",
				  db_ctx->mtdb_path, i, ret));
		} else {
			op = "store";
			ret = tdb_store(db_ctx->ltdb->tdb, key,
					val, TDB_REPLACE);
			DEBUG(10,("sync_changes[%s] store key[%u] %d\n",
				  db_ctx->mtdb_path, i, ret));
		}
		SAFE_FREE(val.dptr);
		if (ret != 0) {
			DEBUG(0,("sync_changes[%s] %s key[%u] failed %d\n",
				 db_ctx->mtdb_path, op, i, ret));
			goto failed;
		}
	}

done:
	tdb_unlockall_read(db_ctx->mtdb->tdb);

	*seqnum = mseqnum;
	return 0;
failed:
	tdb_unlockall_read(db_ctx->mtdb->tdb);
	return ret;
}

static int db_tdb2_sync_from_master(struct db_tdb2_ctx *db_ctx,
				    const struct dbwrap_tdb2_changes *changes)
{
	int ret;
	uint32_t cseqnum;
	uint32_t mseqnum;
	bool force = false;

	/* first fetch seqnum we know about */
	cseqnum = db_tdb2_get_seqnum(db_ctx->db);

	/* then fetch the master seqnum */
	mseqnum = tdb_get_seqnum(db_ctx->mtdb->tdb);

	if (db_ctx->lseqnum == 0) {
		force = true;
	}

	if (!force && cseqnum == mseqnum) {
		DEBUG(10,("uptodate[%s] mseq[%u]\n",
			  db_ctx->ltdb_path, mseqnum));
		/* the local copy is uptodate, close the master db */
		return 0;
	}
	DEBUG(10,("not uptodate[%s] seq[%u=>%u]\n",
		  db_ctx->ltdb_path, cseqnum, mseqnum));

	ret = tdb_transaction_start(db_ctx->ltdb->tdb);
	if (ret != 0) {
		DEBUG(0,("failed to start transaction[%s] %d: %s\n",
			 db_ctx->ltdb_path, ret,
			 tdb_errorstr(db_ctx->ltdb->tdb)));
		db_ctx->out_of_sync = true;
		return ret;
	}
	db_ctx->local_transaction = true;

	if (changes && !force) {
		ret = db_tdb2_sync_changes(db_ctx, changes, &mseqnum);
		if (ret != 0) {
			db_ctx->out_of_sync = true;
			tdb_transaction_cancel(db_ctx->ltdb->tdb);
			db_ctx->local_transaction = false;
			return ret;
		}
	} else {
		ret = db_tdb2_sync_all(db_ctx, &mseqnum);
		if (ret != 0) {
			db_ctx->out_of_sync = true;
			tdb_transaction_cancel(db_ctx->ltdb->tdb);
			db_ctx->local_transaction = false;
			return ret;
		}
	}

	ret = db_tdb2_commit_local(db_ctx, mseqnum);
	if (ret != 0) {
		db_ctx->out_of_sync = true;
		return ret;
	}

	db_ctx->out_of_sync = false;

	return 0;
}

static int db_tdb2_ctx_destructor(struct db_tdb2_ctx *db_tdb2)
{
	db_tdb2_close_master(db_tdb2);
	if (db_tdb2->local_transaction) {
		tdb_transaction_cancel(db_tdb2->ltdb->tdb);
	}
	db_tdb2->local_transaction = false;
	TALLOC_FREE(db_tdb2->ltdb);
	return 0;
}

static struct db_context *db_open_tdb2_ex(TALLOC_CTX *mem_ctx,
					  const char *name,
					  int hash_size, int tdb_flags,
					  int open_flags, mode_t mode,
					  const struct dbwrap_tdb2_changes *chgs)
{
	struct db_context *result = NULL;
	struct db_tdb2_ctx *db_tdb2;
	int ret;
	const char *md;
	const char *ld;
	const char *bn;

	bn = strrchr_m(name, '/');
	if (bn) {
		bn++;
		DEBUG(3,("db_open_tdb2: use basename[%s] of abspath[%s]:\n",
			bn, name));
	} else {
		bn = name;
	}

	md = lp_parm_const_string(-1, "dbwrap_tdb2", "master directory", NULL);
	if (!md) {
		DEBUG(0,("'dbwrap_tdb2:master directory' empty\n"));
		goto fail;
	}

	ld = lp_parm_const_string(-1, "dbwrap_tdb2", "local directory", NULL);
	if (!ld) {
		DEBUG(0,("'dbwrap_tdb2:local directory' empty\n"));
		goto fail;
	}

	result = TALLOC_ZERO_P(mem_ctx, struct db_context);
	if (result == NULL) {
		DEBUG(0, ("talloc failed\n"));
		goto fail;
	}

	result->private_data = db_tdb2 = TALLOC_ZERO_P(result, struct db_tdb2_ctx);
	if (db_tdb2 == NULL) {
		DEBUG(0, ("talloc failed\n"));
		goto fail;
	}

	db_tdb2->db = result;

	db_tdb2->open.hash_size	= hash_size;
	db_tdb2->open.tdb_flags	= tdb_flags;
	db_tdb2->open.open_flags= open_flags;
	db_tdb2->open.mode	= mode;

	db_tdb2->max_buffer_size = lp_parm_ulong(-1, "dbwrap_tdb2",
						 "notify buffer size", 512);

	db_tdb2->name = talloc_strdup(db_tdb2, bn);
	if (db_tdb2->name == NULL) {
		DEBUG(0, ("talloc_strdup failed\n"));
		goto fail;
	}

	db_tdb2->mtdb_path = talloc_asprintf(db_tdb2, "%s/%s",
					     md, bn);
	if (db_tdb2->mtdb_path == NULL) {
		DEBUG(0, ("talloc_asprintf failed\n"));
		goto fail;
	}

	db_tdb2->ltdb_path = talloc_asprintf(db_tdb2, "%s/%s.tdb2",
					     ld, bn);
	if (db_tdb2->ltdb_path == NULL) {
		DEBUG(0, ("talloc_asprintf failed\n"));
		goto fail;
	}

	db_tdb2->mseqkey = string_term_tdb_data(DB_TDB2_MASTER_SEQNUM_KEYSTR);

	/*
	 * this implicit opens the local one if as it's not yet open
	 * it syncs the local copy.
	 */
	ret = db_tdb2_open_master(db_tdb2, false, chgs);
	if (ret != 0) {
		goto fail;
	}

	ret = db_tdb2_close_master(db_tdb2);
	if (ret != 0) {
		goto fail;
	}

	DEBUG(10,("db_open_tdb2[%s] opened with mseq[%u]\n",
		  db_tdb2->name, db_tdb2->mseqnum));

	result->fetch_locked = db_tdb2_fetch_locked;
	result->fetch = db_tdb2_fetch;
	result->traverse = db_tdb2_traverse;
	result->traverse_read = db_tdb2_traverse_read;
	result->get_seqnum = db_tdb2_get_seqnum;
	result->persistent = ((tdb_flags & TDB_CLEAR_IF_FIRST) == 0);
	result->transaction_start = db_tdb2_transaction_start;
	result->transaction_commit = db_tdb2_transaction_commit;
	result->transaction_cancel = db_tdb2_transaction_cancel;

	talloc_set_destructor(db_tdb2, db_tdb2_ctx_destructor);

	return result;

 fail:
	if (result != NULL) {
		TALLOC_FREE(result);
	}
	return NULL;
}

struct db_context *db_open_tdb2(TALLOC_CTX *mem_ctx,
				const char *name,
				int hash_size, int tdb_flags,
				int open_flags, mode_t mode)
{
	return db_open_tdb2_ex(mem_ctx, name, hash_size,
			       tdb_flags, open_flags, mode, NULL);
}