summaryrefslogtreecommitdiffstats
path: root/ldb/common/ldb.c
blob: c013565da0b3816245844a206563f25f525fdf00 (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
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
/*
   ldb database library

   Copyright (C) Andrew Tridgell  2004
   Copyright (C) Simo Sorce  2005-2008

     ** NOTE! The following LGPL license applies to the ldb
     ** library. This does NOT imply that all of Samba is released
     ** under the LGPL

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

   This library 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
   Lesser General Public License for more details.

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

/*
 *  Name: ldb
 *
 *  Component: ldb core API
 *
 *  Description: core API routines interfacing to ldb backends
 *
 *  Author: Andrew Tridgell
 */

#include "ldb_includes.h"

/*
   initialise a ldb context
   The mem_ctx is required
   The event_ctx is required
*/
struct ldb_context *ldb_init(TALLOC_CTX *mem_ctx, struct event_context *ev_ctx)
{
	struct ldb_context *ldb;
	int ret;

	ldb = talloc_zero(mem_ctx, struct ldb_context);
	/* FIXME: Hack a new event context so that CMD line utilities work
	 * until we have them all converted */
	if (ev_ctx == NULL) {
		ev_ctx = event_context_init(talloc_autofree_context());
	}

	ret = ldb_setup_wellknown_attributes(ldb);
	if (ret != 0) {
		talloc_free(ldb);
		return NULL;
	}

	ldb_set_utf8_default(ldb);
	ldb_set_create_perms(ldb, 0666);
	ldb_set_modules_dir(ldb, LDB_MODULESDIR);
	ldb_set_event_context(ldb, ev_ctx);

	/* TODO: get timeout from options if available there */
	ldb->default_timeout = 300; /* set default to 5 minutes */

	return ldb;
}

/*
  try to autodetect a basedn if none specified. This fixes one of my
  pet hates about ldapsearch, which is that you have to get a long,
  complex basedn right to make any use of it.
*/
void ldb_set_default_dns(struct ldb_context *ldb)
{
	TALLOC_CTX *tmp_ctx;
	int ret;
	struct ldb_result *res;
	struct ldb_dn *tmp_dn=NULL;
	static const char *attrs[] = {
		"rootDomainNamingContext",
		"configurationNamingContext",
		"schemaNamingContext",
		"defaultNamingContext",
		NULL
	};

	tmp_ctx = talloc_new(ldb);
	ret = ldb_search(ldb, tmp_ctx, &res, ldb_dn_new(tmp_ctx, ldb, NULL),
			 LDB_SCOPE_BASE, attrs, "(objectClass=*)");
	if (ret != LDB_SUCCESS) {
		talloc_free(tmp_ctx);
		return;
	}

	if (res->count != 1) {
		talloc_free(tmp_ctx);
		return;
	}

	if (!ldb_get_opaque(ldb, "rootDomainNamingContext")) {
		tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
						 "rootDomainNamingContext");
		ldb_set_opaque(ldb, "rootDomainNamingContext", tmp_dn);
	}

	if (!ldb_get_opaque(ldb, "configurationNamingContext")) {
		tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
						 "configurationNamingContext");
		ldb_set_opaque(ldb, "configurationNamingContext", tmp_dn);
	}

	if (!ldb_get_opaque(ldb, "schemaNamingContext")) {
		tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
						 "schemaNamingContext");
		ldb_set_opaque(ldb, "schemaNamingContext", tmp_dn);
	}

	if (!ldb_get_opaque(ldb, "defaultNamingContext")) {
		tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
						 "defaultNamingContext");
		ldb_set_opaque(ldb, "defaultNamingContext", tmp_dn);
	}

	talloc_free(tmp_ctx);
}

struct ldb_dn *ldb_get_root_basedn(struct ldb_context *ldb)
{
	void *opaque = ldb_get_opaque(ldb, "rootDomainNamingContext");
	return talloc_get_type(opaque, struct ldb_dn);
}

struct ldb_dn *ldb_get_config_basedn(struct ldb_context *ldb)
{
	void *opaque = ldb_get_opaque(ldb, "configurationNamingContext");
	return talloc_get_type(opaque, struct ldb_dn);
}

struct ldb_dn *ldb_get_schema_basedn(struct ldb_context *ldb)
{
	void *opaque = ldb_get_opaque(ldb, "schemaNamingContext");
	return talloc_get_type(opaque, struct ldb_dn);
}

struct ldb_dn *ldb_get_default_basedn(struct ldb_context *ldb)
{
	void *opaque = ldb_get_opaque(ldb, "defaultNamingContext");
	return talloc_get_type(opaque, struct ldb_dn);
}

/*
   connect to a database. The URL can either be one of the following forms
   ldb://path
   ldapi://path

   flags is made up of LDB_FLG_*

   the options are passed uninterpreted to the backend, and are
   backend specific
*/
int ldb_connect(struct ldb_context *ldb, const char *url,
		unsigned int flags, const char *options[])
{
	int ret;
	const char *url2;
	/* We seem to need to do this here, or else some utilities don't
	 * get ldb backends */

	ldb->flags = flags;

	url2 = talloc_strdup(ldb, url);
	if (!url2) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}
	ret = ldb_set_opaque(ldb, "ldb_url", talloc_strdup(ldb, url2));
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = ldb_connect_backend(ldb, url, options, &ldb->modules);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (ldb_load_modules(ldb, options) != LDB_SUCCESS) {
		ldb_debug(ldb, LDB_DEBUG_FATAL,
			  "Unable to load modules for %s: %s\n",
			  url, ldb_errstring(ldb));
		return LDB_ERR_OTHER;
	}

	/* set the default base dn */
	ldb_set_default_dns(ldb);

	return LDB_SUCCESS;
}

void ldb_set_errstring(struct ldb_context *ldb, const char *err_string)
{
	if (ldb->err_string) {
		talloc_free(ldb->err_string);
	}
	ldb->err_string = talloc_strdup(ldb, err_string);
}

void ldb_asprintf_errstring(struct ldb_context *ldb, const char *format, ...)
{
	va_list ap;
	char *old_string = NULL;

	if (ldb->err_string) {
		old_string = ldb->err_string;
	}

	va_start(ap, format);
	ldb->err_string = talloc_vasprintf(ldb, format, ap);
	va_end(ap);
	talloc_free(old_string);
}

void ldb_reset_err_string(struct ldb_context *ldb)
{
	if (ldb->err_string) {
		talloc_free(ldb->err_string);
		ldb->err_string = NULL;
	}
}

#define FIRST_OP(ldb, op) do { \
	module = ldb->modules;					\
	while (module && module->ops->op == NULL) module = module->next; \
	if (module == NULL) {						\
		ldb_asprintf_errstring(ldb, "unable to find module or backend to handle operation: " #op); \
		return LDB_ERR_OPERATIONS_ERROR;			\
	} \
} while (0)

/*
  start a transaction
*/
static int ldb_transaction_start_internal(struct ldb_context *ldb)
{
	struct ldb_module *module;
	int status;
	FIRST_OP(ldb, start_transaction);

	ldb_reset_err_string(ldb);

	status = module->ops->start_transaction(module);
	if (status != LDB_SUCCESS) {
		if (ldb->err_string == NULL) {
			/* no error string was setup by the backend */
			ldb_asprintf_errstring(ldb,
				"ldb transaction start: %s (%d)",
				ldb_strerror(status),
				status);
		}
	}
	return status;
}

/*
  commit a transaction
*/
static int ldb_transaction_commit_internal(struct ldb_context *ldb)
{
	struct ldb_module *module;
	int status;
	FIRST_OP(ldb, end_transaction);

	ldb_reset_err_string(ldb);

	status = module->ops->end_transaction(module);
	if (status != LDB_SUCCESS) {
		if (ldb->err_string == NULL) {
			/* no error string was setup by the backend */
			ldb_asprintf_errstring(ldb,
				"ldb transaction commit: %s (%d)",
				ldb_strerror(status),
				status);
		}
	}
	return status;
}

/*
  cancel a transaction
*/
static int ldb_transaction_cancel_internal(struct ldb_context *ldb)
{
	struct ldb_module *module;
	int status;
	FIRST_OP(ldb, del_transaction);

	status = module->ops->del_transaction(module);
	if (status != LDB_SUCCESS) {
		if (ldb->err_string == NULL) {
			/* no error string was setup by the backend */
			ldb_asprintf_errstring(ldb,
				"ldb transaction cancel: %s (%d)",
				ldb_strerror(status),
				status);
		}
	}
	return status;
}

int ldb_transaction_start(struct ldb_context *ldb)
{
	/* disable autotransactions */
	ldb->transaction_active++;

	return ldb_transaction_start_internal(ldb);
}

int ldb_transaction_commit(struct ldb_context *ldb)
{
	/* renable autotransactions (when we reach 0) */
	if (ldb->transaction_active > 0)
		ldb->transaction_active--;

	return ldb_transaction_commit_internal(ldb);
}

int ldb_transaction_cancel(struct ldb_context *ldb)
{
	/* renable autotransactions (when we reach 0) */
	if (ldb->transaction_active > 0)
		ldb->transaction_active--;

	return ldb_transaction_cancel_internal(ldb);
}

static int ldb_autotransaction_start(struct ldb_context *ldb)
{
	/* explicit transaction active, ignore autotransaction request */
	if (ldb->transaction_active)
		return LDB_SUCCESS;

	return ldb_transaction_start_internal(ldb);
}

static int ldb_autotransaction_commit(struct ldb_context *ldb)
{
	/* explicit transaction active, ignore autotransaction request */
	if (ldb->transaction_active)
		return LDB_SUCCESS;

	return ldb_transaction_commit_internal(ldb);
}

static int ldb_autotransaction_cancel(struct ldb_context *ldb)
{
	/* explicit transaction active, ignore autotransaction request */
	if (ldb->transaction_active)
		return LDB_SUCCESS;

	return ldb_transaction_cancel_internal(ldb);
}

/* autostarts a transacion if none active */
static int ldb_autotransaction_request(struct ldb_context *ldb,
				       struct ldb_request *req)
{
	int ret;

	ret = ldb_autotransaction_start(ldb);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = ldb_request(ldb, req);
	if (ret == LDB_SUCCESS) {
		ret = ldb_wait(req->handle, LDB_WAIT_ALL);
	}

	if (ret == LDB_SUCCESS) {
		return ldb_autotransaction_commit(ldb);
	}
	ldb_autotransaction_cancel(ldb);

	if (ldb->err_string == NULL) {
		/* no error string was setup by the backend */
		ldb_asprintf_errstring(ldb, "%s (%d)", ldb_strerror(ret), ret);
	}

	return ret;
}

int ldb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
{
	struct event_context *ev;

	if (!handle) {
		return LDB_ERR_UNAVAILABLE;
	}

	if (handle->state == LDB_ASYNC_DONE) {
		return handle->status;
	}

	ev = ldb_get_event_context(handle->ldb);
	if (NULL == ev) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	switch (type) {
	case LDB_WAIT_NONE:
		event_loop_once(ev);
		if (handle->state == LDB_ASYNC_DONE ||
		    handle->status != LDB_SUCCESS) {
			return handle->status;
		}
		break;

	case LDB_WAIT_ALL:
		while (handle->state != LDB_ASYNC_DONE) {
			event_loop_once(ev);
			if (handle->status != LDB_SUCCESS) {
				return handle->status;
			}
		}
		return handle->status;
	}

	return LDB_SUCCESS;
}

/* set the specified timeout or, if timeout is 0 set the default timeout */
int ldb_set_timeout(struct ldb_context *ldb,
		    struct ldb_request *req,
		    int timeout)
{
	if (req == NULL) return LDB_ERR_OPERATIONS_ERROR;

	if (timeout != 0) {
		req->timeout = timeout;
	} else {
		req->timeout = ldb->default_timeout;
	}
	req->starttime = time(NULL);

	return LDB_SUCCESS;
}

/* calculates the new timeout based on the previous starttime and timeout */
int ldb_set_timeout_from_prev_req(struct ldb_context *ldb,
				  struct ldb_request *oldreq,
				  struct ldb_request *newreq)
{
	if (newreq == NULL) return LDB_ERR_OPERATIONS_ERROR;

	if (oldreq == NULL) {
		return ldb_set_timeout(ldb, newreq, 0);
	}

	newreq->starttime = oldreq->starttime;
	newreq->timeout = oldreq->timeout;

	return LDB_SUCCESS;
}


/*
   set the permissions for new files to be passed to open() in
   backends that use local files
 */
void ldb_set_create_perms(struct ldb_context *ldb, unsigned int perms)
{
	ldb->create_perms = perms;
}

void ldb_set_event_context(struct ldb_context *ldb, struct event_context *ev)
{
	ldb->ev_ctx = ev;
}

struct event_context * ldb_get_event_context(struct ldb_context *ldb)
{
	return ldb->ev_ctx;
}

/*
  start an ldb request
  NOTE: the request must be a talloc context.
  returns LDB_ERR_* on errors.
*/
int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
{
	struct ldb_module *module;
	int ret;

	if (req->callback == NULL) {
		ldb_set_errstring(ldb, "Requests MUST define callbacks");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	ldb_reset_err_string(ldb);

	/* call the first module in the chain */
	switch (req->operation) {
	case LDB_SEARCH:
		FIRST_OP(ldb, search);
		ret = module->ops->search(module, req);
		break;
	case LDB_ADD:
		FIRST_OP(ldb, add);
		ret = module->ops->add(module, req);
		break;
	case LDB_MODIFY:
		FIRST_OP(ldb, modify);
		ret = module->ops->modify(module, req);
		break;
	case LDB_DELETE:
		FIRST_OP(ldb, del);
		ret = module->ops->del(module, req);
		break;
	case LDB_RENAME:
		FIRST_OP(ldb, rename);
		ret = module->ops->rename(module, req);
		break;
	case LDB_EXTENDED:
		FIRST_OP(ldb, extended);
		ret = module->ops->extended(module, req);
		break;
	default:
		FIRST_OP(ldb, request);
		ret = module->ops->request(module, req);
		break;
	}

	return ret;
}

int ldb_request_done(struct ldb_request *req, int status)
{
	req->handle->state = LDB_ASYNC_DONE;
	req->handle->status = status;
	return status;
}

/*
  search the database given a LDAP-like search expression

  returns an LDB error code

  Use talloc_free to free the ldb_message returned in 'res', if successful

*/
int ldb_search_default_callback(struct ldb_request *req,
				struct ldb_reply *ares)
{
	struct ldb_result *res;
	int n;

	res = talloc_get_type(req->context, struct ldb_result);

	if (!ares) {
		return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
	}
	if (ares->error != LDB_SUCCESS) {
		return ldb_request_done(req, ares->error);
	}

	switch (ares->type) {
	case LDB_REPLY_ENTRY:
		res->msgs = talloc_realloc(res, res->msgs,
					struct ldb_message *, res->count + 2);
		if (! res->msgs) {
			return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
		}

		res->msgs[res->count + 1] = NULL;

		res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
		res->count++;
		break;

	case LDB_REPLY_REFERRAL:
		if (res->refs) {
			for (n = 0; res->refs[n]; n++) /*noop*/ ;
		} else {
			n = 0;
		}

		res->refs = talloc_realloc(res, res->refs, char *, n + 2);
		if (! res->refs) {
			return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
		}

		res->refs[n] = talloc_move(res->refs, &ares->referral);
		res->refs[n + 1] = NULL;
		break;

	case LDB_REPLY_DONE:
		/* TODO: we should really support controls on entries
		 * and referrals too! */
		res->controls = talloc_move(res, &ares->controls);

		/* this is the last message, and means the request is done */
		/* we have to signal and eventual ldb_wait() waiting that the
		 * async request operation was completed */
		return ldb_request_done(req, LDB_SUCCESS);
	}

	talloc_free(ares);
	return LDB_SUCCESS;
}

int ldb_op_default_callback(struct ldb_request *req, struct ldb_reply *ares)
{
	int ret;

	if (!ares) {
		return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
	}

	if (ares->error != LDB_SUCCESS) {
		ret = ares->error;
		talloc_free(ares);
		return ldb_request_done(req, ret);
	}

	if (ares->type != LDB_REPLY_DONE) {
		talloc_free(ares);
		ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
		return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
	}

	talloc_free(ares);
	return ldb_request_done(req, LDB_SUCCESS);
}

int ldb_build_search_req_ex(struct ldb_request **ret_req,
			struct ldb_context *ldb,
			void *mem_ctx,
			struct ldb_dn *base,
	       		enum ldb_scope scope,
			struct ldb_parse_tree *tree,
			const char * const *attrs,
			struct ldb_control **controls,
			void *context,
			ldb_request_callback_t callback,
			struct ldb_request *parent)
{
	struct ldb_request *req;

	*ret_req = NULL;

	req = talloc(mem_ctx, struct ldb_request);
	if (req == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	req->operation = LDB_SEARCH;
	if (base == NULL) {
		req->op.search.base = ldb_dn_new(req, ldb, NULL);
	} else {
		req->op.search.base = base;
	}
	req->op.search.scope = scope;

	req->op.search.tree = tree;
	if (req->op.search.tree == NULL) {
		ldb_set_errstring(ldb, "'tree' can't be NULL");
		talloc_free(req);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	req->op.search.attrs = attrs;
	req->controls = controls;
	req->context = context;
	req->callback = callback;

	ldb_set_timeout_from_prev_req(ldb, parent, req);

	req->handle = ldb_handle_new(req, ldb);
	if (req->handle == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*ret_req = req;
	return LDB_SUCCESS;
}

int ldb_build_search_req(struct ldb_request **ret_req,
			struct ldb_context *ldb,
			void *mem_ctx,
			struct ldb_dn *base,
			enum ldb_scope scope,
			const char *expression,
			const char * const *attrs,
			struct ldb_control **controls,
			void *context,
			ldb_request_callback_t callback,
			struct ldb_request *parent)
{
	struct ldb_parse_tree *tree;
	int ret;

	tree = ldb_parse_tree(mem_ctx, expression);
	if (tree == NULL) {
		ldb_set_errstring(ldb, "Unable to parse search expression");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	ret = ldb_build_search_req_ex(ret_req, ldb, mem_ctx, base,
				      scope, tree, attrs, controls,
				      context, callback, parent);
	if (ret == LDB_SUCCESS) {
		talloc_steal(*ret_req, tree);
	}
	return ret;
}

int ldb_build_add_req(struct ldb_request **ret_req,
			struct ldb_context *ldb,
			void *mem_ctx,
			const struct ldb_message *message,
			struct ldb_control **controls,
			void *context,
			ldb_request_callback_t callback,
			struct ldb_request *parent)
{
	struct ldb_request *req;

	*ret_req = NULL;

	req = talloc(mem_ctx, struct ldb_request);
	if (req == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	req->operation = LDB_ADD;
	req->op.add.message = message;
	req->controls = controls;
	req->context = context;
	req->callback = callback;

	ldb_set_timeout_from_prev_req(ldb, parent, req);

	req->handle = ldb_handle_new(req, ldb);
	if (req->handle == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*ret_req = req;

	return LDB_SUCCESS;
}

int ldb_build_mod_req(struct ldb_request **ret_req,
			struct ldb_context *ldb,
			void *mem_ctx,
			const struct ldb_message *message,
			struct ldb_control **controls,
			void *context,
			ldb_request_callback_t callback,
			struct ldb_request *parent)
{
	struct ldb_request *req;

	*ret_req = NULL;

	req = talloc(mem_ctx, struct ldb_request);
	if (req == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	req->operation = LDB_MODIFY;
	req->op.mod.message = message;
	req->controls = controls;
	req->context = context;
	req->callback = callback;

	ldb_set_timeout_from_prev_req(ldb, parent, req);

	req->handle = ldb_handle_new(req, ldb);
	if (req->handle == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*ret_req = req;

	return LDB_SUCCESS;
}

int ldb_build_del_req(struct ldb_request **ret_req,
			struct ldb_context *ldb,
			void *mem_ctx,
			struct ldb_dn *dn,
			struct ldb_control **controls,
			void *context,
			ldb_request_callback_t callback,
			struct ldb_request *parent)
{
	struct ldb_request *req;

	*ret_req = NULL;

	req = talloc(mem_ctx, struct ldb_request);
	if (req == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	req->operation = LDB_DELETE;
	req->op.del.dn = dn;
	req->controls = controls;
	req->context = context;
	req->callback = callback;

	ldb_set_timeout_from_prev_req(ldb, parent, req);

	req->handle = ldb_handle_new(req, ldb);
	if (req->handle == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*ret_req = req;

	return LDB_SUCCESS;
}

int ldb_build_rename_req(struct ldb_request **ret_req,
			struct ldb_context *ldb,
			void *mem_ctx,
			struct ldb_dn *olddn,
			struct ldb_dn *newdn,
			struct ldb_control **controls,
			void *context,
			ldb_request_callback_t callback,
			struct ldb_request *parent)
{
	struct ldb_request *req;

	*ret_req = NULL;

	req = talloc(mem_ctx, struct ldb_request);
	if (req == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	req->operation = LDB_RENAME;
	req->op.rename.olddn = olddn;
	req->op.rename.newdn = newdn;
	req->controls = controls;
	req->context = context;
	req->callback = callback;

	ldb_set_timeout_from_prev_req(ldb, parent, req);

	req->handle = ldb_handle_new(req, ldb);
	if (req->handle == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*ret_req = req;

	return LDB_SUCCESS;
}

int ldb_extended_default_callback(struct ldb_request *req,
				  struct ldb_reply *ares)
{
	struct ldb_result *res;

	res = talloc_get_type(req->context, struct ldb_result);

	if (!ares) {
		return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
	}
	if (ares->error != LDB_SUCCESS) {
		return ldb_request_done(req, ares->error);
	}

	if (ares->type == LDB_REPLY_DONE) {

		/* TODO: we should really support controls on entries and referrals too! */
		res->extended = talloc_move(res, &ares->response);
		res->controls = talloc_move(res, &ares->controls);

		talloc_free(ares);
		return ldb_request_done(req, LDB_SUCCESS);
	}

	talloc_free(ares);
	ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
	return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
}

int ldb_build_extended_req(struct ldb_request **ret_req,
			   struct ldb_context *ldb,
			   void *mem_ctx,
			   const char *oid,
			   void *data,
			   struct ldb_control **controls,
			   void *context,
			   ldb_request_callback_t callback,
			   struct ldb_request *parent)
{
	struct ldb_request *req;

	*ret_req = NULL;

	req = talloc(mem_ctx, struct ldb_request);
	if (req == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	req->operation = LDB_EXTENDED;
	req->op.extended.oid = oid;
	req->op.extended.data = data;
	req->controls = controls;
	req->context = context;
	req->callback = callback;

	ldb_set_timeout_from_prev_req(ldb, parent, req);

	req->handle = ldb_handle_new(req, ldb);
	if (req->handle == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*ret_req = req;

	return LDB_SUCCESS;
}

int ldb_extended(struct ldb_context *ldb,
		 const char *oid,
		 void *data,
		 struct ldb_result **_res)
{
	struct ldb_request *req;
	int ret;
	struct ldb_result *res;

	*_res = NULL;

	res = talloc_zero(ldb, struct ldb_result);
	if (!res) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	ret = ldb_build_extended_req(&req, ldb, ldb,
				     oid, data, NULL,
				     res, ldb_extended_default_callback,
				     NULL);
	if (ret != LDB_SUCCESS) goto done;

	ldb_set_timeout(ldb, req, 0); /* use default timeout */

	ret = ldb_request(ldb, req);

	if (ret == LDB_SUCCESS) {
		ret = ldb_wait(req->handle, LDB_WAIT_ALL);
	}

	talloc_free(req);

done:
	if (ret != LDB_SUCCESS) {
		talloc_free(res);
	}

	*_res = res;
	return ret;
}

/*
  note that ldb_search() will automatically replace a NULL 'base' value
  with the defaultNamingContext from the rootDSE if available.
*/
int ldb_search(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
		struct ldb_result **result, struct ldb_dn *base,
		enum ldb_scope scope, const char * const *attrs,
		const char *exp_fmt, ...)
{
	struct ldb_request *req;
	struct ldb_result *res;
	char *expression;
	va_list ap;
	int ret;

	expression = NULL;
	*result = NULL;
	req = NULL;

	res = talloc_zero(mem_ctx, struct ldb_result);
	if (!res) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	if (exp_fmt) {
		va_start(ap, exp_fmt);
		expression = talloc_vasprintf(mem_ctx, exp_fmt, ap);
		va_end(ap);

		if (!expression) {
			talloc_free(res);
			return LDB_ERR_OPERATIONS_ERROR;
		}
	}

	ret = ldb_build_search_req(&req, ldb, mem_ctx,
					base?base:ldb_get_default_basedn(ldb),
	       				scope,
					expression,
					attrs,
					NULL,
					res,
					ldb_search_default_callback,
					NULL);

	if (ret != LDB_SUCCESS) goto done;

	ret = ldb_request(ldb, req);

	if (ret == LDB_SUCCESS) {
		ret = ldb_wait(req->handle, LDB_WAIT_ALL);
	}

done:
	if (ret != LDB_SUCCESS) {
		talloc_free(res);
		res = NULL;
	}

	talloc_free(expression);
	talloc_free(req);

	*result = res;
	return ret;
}

/*
  add a record to the database. Will fail if a record with the given class
  and key already exists
*/
int ldb_add(struct ldb_context *ldb,
	    const struct ldb_message *message)
{
	struct ldb_request *req;
	int ret;

	ret = ldb_msg_sanity_check(ldb, message);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = ldb_build_add_req(&req, ldb, ldb,
					message,
					NULL,
					NULL,
					ldb_op_default_callback,
					NULL);

	if (ret != LDB_SUCCESS) return ret;

	/* do request and autostart a transaction */
	ret = ldb_autotransaction_request(ldb, req);

	talloc_free(req);
	return ret;
}

/*
  modify the specified attributes of a record
*/
int ldb_modify(struct ldb_context *ldb,
	       const struct ldb_message *message)
{
	struct ldb_request *req;
	int ret;

	ret = ldb_msg_sanity_check(ldb, message);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = ldb_build_mod_req(&req, ldb, ldb,
					message,
					NULL,
					NULL,
					ldb_op_default_callback,
					NULL);

	if (ret != LDB_SUCCESS) return ret;

	/* do request and autostart a transaction */
	ret = ldb_autotransaction_request(ldb, req);

	talloc_free(req);
	return ret;
}


/*
  delete a record from the database
*/
int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn)
{
	struct ldb_request *req;
	int ret;

	ret = ldb_build_del_req(&req, ldb, ldb,
					dn,
					NULL,
					NULL,
					ldb_op_default_callback,
					NULL);

	if (ret != LDB_SUCCESS) return ret;

	/* do request and autostart a transaction */
	ret = ldb_autotransaction_request(ldb, req);

	talloc_free(req);
	return ret;
}

/*
  rename a record in the database
*/
int ldb_rename(struct ldb_context *ldb,
		struct ldb_dn *olddn, struct ldb_dn *newdn)
{
	struct ldb_request *req;
	int ret;

	ret = ldb_build_rename_req(&req, ldb, ldb,
					olddn,
					newdn,
					NULL,
					NULL,
					ldb_op_default_callback,
					NULL);

	if (ret != LDB_SUCCESS) return ret;

	/* do request and autostart a transaction */
	ret = ldb_autotransaction_request(ldb, req);

	talloc_free(req);
	return ret;
}


/*
  return the global sequence number
*/
int ldb_sequence_number(struct ldb_context *ldb,
			enum ldb_sequence_type type, uint64_t *seq_num)
{
	struct ldb_seqnum_request *seq;
	struct ldb_seqnum_result *seqr;
	struct ldb_result *res;
	TALLOC_CTX *tmp_ctx;
	int ret;

	*seq_num = 0;

	tmp_ctx = talloc_zero(ldb, struct ldb_request);
	if (tmp_ctx == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		return LDB_ERR_OPERATIONS_ERROR;
	}
	seq = talloc_zero(tmp_ctx, struct ldb_seqnum_request);
	if (seq == NULL) {
		ldb_set_errstring(ldb, "Out of Memory");
		ret = LDB_ERR_OPERATIONS_ERROR;
		goto done;
	}
	seq->type = type;

	ret = ldb_extended(ldb, LDB_EXTENDED_SEQUENCE_NUMBER, seq, &res);
	if (ret != LDB_SUCCESS) {
		goto done;
	}
	talloc_steal(tmp_ctx, res);

	if (strcmp(LDB_EXTENDED_SEQUENCE_NUMBER, res->extended->oid) != 0) {
		ldb_set_errstring(ldb, "Invalid OID in reply");
		ret = LDB_ERR_OPERATIONS_ERROR;
		goto done;
	}
	seqr = talloc_get_type(res->extended->data,
				struct ldb_seqnum_result);
	*seq_num = seqr->seq_num;

done:
	talloc_free(tmp_ctx);
	return ret;
}

/*
  return extended error information
*/
const char *ldb_errstring(struct ldb_context *ldb)
{
	if (ldb->err_string) {
		return ldb->err_string;
	}

	return NULL;
}

/*
  return a string explaining what a ldb error constant meancs
*/
const char *ldb_strerror(int ldb_err)
{
	switch (ldb_err) {
	case LDB_SUCCESS:
		return "Success";
	case LDB_ERR_OPERATIONS_ERROR:
		return "Operations error";
	case LDB_ERR_PROTOCOL_ERROR:
		return "Protocol error";
	case LDB_ERR_TIME_LIMIT_EXCEEDED:
		return "Time limit exceeded";
	case LDB_ERR_SIZE_LIMIT_EXCEEDED:
		return "Size limit exceeded";
	case LDB_ERR_COMPARE_FALSE:
		return "Compare false";
	case LDB_ERR_COMPARE_TRUE:
		return "Compare true";
	case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
		return "Auth method not supported";
	case LDB_ERR_STRONG_AUTH_REQUIRED:
		return "Strong auth required";
/* 9 RESERVED */
	case LDB_ERR_REFERRAL:
		return "Referral error";
	case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
		return "Admin limit exceeded";
	case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
		return "Unsupported critical extension";
	case LDB_ERR_CONFIDENTIALITY_REQUIRED:
		return "Confidentiality required";
	case LDB_ERR_SASL_BIND_IN_PROGRESS:
		return "SASL bind in progress";
	case LDB_ERR_NO_SUCH_ATTRIBUTE:
		return "No such attribute";
	case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
		return "Undefined attribute type";
	case LDB_ERR_INAPPROPRIATE_MATCHING:
		return "Inappropriate matching";
	case LDB_ERR_CONSTRAINT_VIOLATION:
		return "Constraint violation";
	case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
		return "Attribute or value exists";
	case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
		return "Invalid attribute syntax";
/* 22-31 unused */
	case LDB_ERR_NO_SUCH_OBJECT:
		return "No such object";
	case LDB_ERR_ALIAS_PROBLEM:
		return "Alias problem";
	case LDB_ERR_INVALID_DN_SYNTAX:
		return "Invalid DN syntax";
/* 35 RESERVED */
	case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
		return "Alias dereferencing problem";
/* 37-47 unused */
	case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
		return "Inappropriate authentication";
	case LDB_ERR_INVALID_CREDENTIALS:
		return "Invalid credentials";
	case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
		return "insufficient access rights";
	case LDB_ERR_BUSY:
		return "Busy";
	case LDB_ERR_UNAVAILABLE:
		return "Unavailable";
	case LDB_ERR_UNWILLING_TO_PERFORM:
		return "Unwilling to perform";
	case LDB_ERR_LOOP_DETECT:
		return "Loop detect";
/* 55-63 unused */
	case LDB_ERR_NAMING_VIOLATION:
		return "Naming violation";
	case LDB_ERR_OBJECT_CLASS_VIOLATION:
		return "Object class violation";
	case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
		return "Not allowed on non-leaf";
	case LDB_ERR_NOT_ALLOWED_ON_RDN:
		return "Not allowed on RDN";
	case LDB_ERR_ENTRY_ALREADY_EXISTS:
		return "Entry already exists";
	case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
		return "Object class mods prohibited";
/* 70 RESERVED FOR CLDAP */
	case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
		return "Affects multiple DSAs";
/* 72-79 unused */
	case LDB_ERR_OTHER:
		return "Other";
	}

	return "Unknown error";
}

/*
  set backend specific opaque parameters
*/
int ldb_set_opaque(struct ldb_context *ldb, const char *name, void *value)
{
	struct ldb_opaque *o;

	/* allow updating an existing value */
	for (o=ldb->opaque;o;o=o->next) {
		if (strcmp(o->name, name) == 0) {
			o->value = value;
			return LDB_SUCCESS;
		}
	}

	o = talloc(ldb, struct ldb_opaque);
	if (o == NULL) {
		ldb_oom(ldb);
		return LDB_ERR_OTHER;
	}
	o->next = ldb->opaque;
	o->name = name;
	o->value = value;
	ldb->opaque = o;
	return LDB_SUCCESS;
}

/*
  get a previously set opaque value
*/
void *ldb_get_opaque(struct ldb_context *ldb, const char *name)
{
	struct ldb_opaque *o;
	for (o=ldb->opaque;o;o=o->next) {
		if (strcmp(o->name, name) == 0) {
			return o->value;
		}
	}
	return NULL;
}