s4:rpc_server: fix DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN negotiation to match Windows
[Samba.git] / lib / ldb / ldb_sqlite3 / ldb_sqlite3.c
blob0f5abf875472d5202bdc0a243690bf03551848d0
1 /*
2 ldb database library
4 Copyright (C) Derrell Lipman 2005
5 Copyright (C) Simo Sorce 2005-2009
7 ** NOTE! The following LGPL license applies to the ldb
8 ** library. This does NOT imply that all of Samba is released
9 ** under the LGPL
11 This library is free software; you can redistribute it and/or
12 modify it under the terms of the GNU Lesser General Public
13 License as published by the Free Software Foundation; either
14 version 3 of the License, or (at your option) any later version.
16 This library is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 Lesser General Public License for more details.
21 You should have received a copy of the GNU Lesser General Public
22 License along with this library; if not, see <http://www.gnu.org/licenses/>.
26 * Name: ldb
28 * Component: ldb sqlite3 backend
30 * Description: core files for SQLITE3 backend
32 * Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
35 #include "ldb_module.h"
37 #include <sqlite3.h>
39 struct lsqlite3_private {
40 int trans_count;
41 char **options;
42 sqlite3 *sqlite;
45 struct lsql_context {
46 struct ldb_module *module;
47 struct ldb_request *req;
49 /* search stuff */
50 long long current_eid;
51 const char * const * attrs;
52 struct ldb_reply *ares;
54 bool callback_failed;
55 struct tevent_timer *timeout_event;
59 * Macros used throughout
62 #ifndef FALSE
63 # define FALSE (0)
64 # define TRUE (! FALSE)
65 #endif
67 #define RESULT_ATTR_TABLE "temp_result_attrs"
70 /* for testing, define to nothing, (create non-temporary table) */
71 #define TEMPTAB "TEMPORARY"
74 * Static variables
76 sqlite3_stmt * stmtGetEID = NULL;
78 static char *lsqlite3_tprintf(TALLOC_CTX *mem_ctx, const char *fmt, ...)
80 char *str, *ret;
81 va_list ap;
83 va_start(ap, fmt);
84 str = sqlite3_vmprintf(fmt, ap);
85 va_end(ap);
87 if (str == NULL) return NULL;
89 ret = talloc_strdup(mem_ctx, str);
90 if (ret == NULL) {
91 sqlite3_free(str);
92 return NULL;
95 sqlite3_free(str);
96 return ret;
99 static char base160tab[161] = {
100 48 ,49 ,50 ,51 ,52 ,53 ,54 ,55 ,56 ,57 , /* 0-9 */
101 58 ,59 ,65 ,66 ,67 ,68 ,69 ,70 ,71 ,72 , /* : ; A-H */
102 73 ,74 ,75 ,76 ,77 ,78 ,79 ,80 ,81 ,82 , /* I-R */
103 83 ,84 ,85 ,86 ,87 ,88 ,89 ,90 ,97 ,98 , /* S-Z , a-b */
104 99 ,100,101,102,103,104,105,106,107,108, /* c-l */
105 109,110,111,112,113,114,115,116,117,118, /* m-v */
106 119,120,121,122,160,161,162,163,164,165, /* w-z, latin1 */
107 166,167,168,169,170,171,172,173,174,175, /* latin1 */
108 176,177,178,179,180,181,182,183,184,185, /* latin1 */
109 186,187,188,189,190,191,192,193,194,195, /* latin1 */
110 196,197,198,199,200,201,202,203,204,205, /* latin1 */
111 206,207,208,209,210,211,212,213,214,215, /* latin1 */
112 216,217,218,219,220,221,222,223,224,225, /* latin1 */
113 226,227,228,229,230,231,232,233,234,235, /* latin1 */
114 236,237,238,239,240,241,242,243,244,245, /* latin1 */
115 246,247,248,249,250,251,252,253,254,255, /* latin1 */
116 '\0'
121 * base160()
123 * Convert an unsigned long integer into a base160 representation of the
124 * number.
126 * Parameters:
127 * val --
128 * value to be converted
130 * result --
131 * character array, 5 bytes long, into which the base160 representation
132 * will be placed. The result will be a four-digit representation of the
133 * number (with leading zeros prepended as necessary), and null
134 * terminated.
136 * Returns:
137 * Nothing
139 static void
140 base160_sql(sqlite3_context * hContext,
141 int argc,
142 sqlite3_value ** argv)
144 int i;
145 long long val;
146 char result[5];
148 val = sqlite3_value_int64(argv[0]);
150 for (i = 3; i >= 0; i--) {
152 result[i] = base160tab[val % 160];
153 val /= 160;
156 result[4] = '\0';
158 sqlite3_result_text(hContext, result, -1, SQLITE_TRANSIENT);
163 * base160next_sql()
165 * This function enhances sqlite by adding a "base160_next()" function which is
166 * accessible via queries.
168 * Retrieve the next-greater number in the base160 sequence for the terminal
169 * tree node (the last four digits). Only one tree level (four digits) is
170 * operated on.
172 * Input:
173 * A character string: either an empty string (in which case no operation is
174 * performed), or a string of base160 digits with a length of a multiple of
175 * four digits.
177 * Output:
178 * Upon return, the trailing four digits (one tree level) will have been
179 * incremented by 1.
181 static void
182 base160next_sql(sqlite3_context * hContext,
183 int argc,
184 sqlite3_value ** argv)
186 int i;
187 int len;
188 char * pTab;
189 char * pBase160 = strdup((const char *)sqlite3_value_text(argv[0]));
190 char * pStart = pBase160;
193 * We need a minimum of four digits, and we will always get a multiple
194 * of four digits.
196 if (pBase160 != NULL &&
197 (len = strlen(pBase160)) >= 4 &&
198 len % 4 == 0) {
200 if (pBase160 == NULL) {
202 sqlite3_result_null(hContext);
203 return;
206 pBase160 += strlen(pBase160) - 1;
208 /* We only carry through four digits: one level in the tree */
209 for (i = 0; i < 4; i++) {
211 /* What base160 value does this digit have? */
212 pTab = strchr(base160tab, *pBase160);
214 /* Is there a carry? */
215 if (pTab < base160tab + sizeof(base160tab) - 1) {
218 * Nope. Just increment this value and we're
219 * done.
221 *pBase160 = *++pTab;
222 break;
223 } else {
226 * There's a carry. This value gets
227 * base160tab[0], we decrement the buffer
228 * pointer to get the next higher-order digit,
229 * and continue in the loop.
231 *pBase160-- = base160tab[0];
235 sqlite3_result_text(hContext,
236 pStart,
237 strlen(pStart),
238 free);
239 } else {
240 sqlite3_result_value(hContext, argv[0]);
241 if (pBase160 != NULL) {
242 free(pBase160);
247 static char *parsetree_to_sql(struct ldb_module *module,
248 void *mem_ctx,
249 const struct ldb_parse_tree *t)
251 struct ldb_context *ldb;
252 const struct ldb_schema_attribute *a;
253 struct ldb_val value, subval;
254 char *wild_card_string;
255 char *child, *tmp;
256 char *ret = NULL;
257 char *attr;
258 unsigned int i;
260 ldb = ldb_module_get_ctx(module);
262 switch(t->operation) {
263 case LDB_OP_AND:
265 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
266 if (tmp == NULL) return NULL;
268 for (i = 1; i < t->u.list.num_elements; i++) {
270 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
271 if (child == NULL) return NULL;
273 tmp = talloc_asprintf_append(tmp, " INTERSECT %s ", child);
274 if (tmp == NULL) return NULL;
277 ret = talloc_asprintf(mem_ctx, "SELECT * FROM ( %s )\n", tmp);
279 return ret;
281 case LDB_OP_OR:
283 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
284 if (tmp == NULL) return NULL;
286 for (i = 1; i < t->u.list.num_elements; i++) {
288 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
289 if (child == NULL) return NULL;
291 tmp = talloc_asprintf_append(tmp, " UNION %s ", child);
292 if (tmp == NULL) return NULL;
295 return talloc_asprintf(mem_ctx, "SELECT * FROM ( %s ) ", tmp);
297 case LDB_OP_NOT:
299 child = parsetree_to_sql(module, mem_ctx, t->u.isnot.child);
300 if (child == NULL) return NULL;
302 return talloc_asprintf(mem_ctx,
303 "SELECT eid FROM ldb_entry "
304 "WHERE eid NOT IN ( %s ) ", child);
306 case LDB_OP_EQUALITY:
308 * For simple searches, we want to retrieve the list of EIDs that
309 * match the criteria.
311 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
312 if (attr == NULL) return NULL;
313 a = ldb_schema_attribute_by_name(ldb, attr);
315 /* Get a canonicalised copy of the data */
316 a->syntax->canonicalise_fn(ldb, mem_ctx, &(t->u.equality.value), &value);
317 if (value.data == NULL) {
318 return NULL;
321 if (strcasecmp(t->u.equality.attr, "dn") == 0) {
322 /* DN query is a special ldb case */
323 const char *cdn = ldb_dn_get_casefold(
324 ldb_dn_new(mem_ctx, ldb,
325 (const char *)value.data));
326 if (cdn == NULL) {
327 return NULL;
330 return lsqlite3_tprintf(mem_ctx,
331 "SELECT eid FROM ldb_entry "
332 "WHERE norm_dn = '%q'", cdn);
334 } else {
335 /* A normal query. */
336 return lsqlite3_tprintf(mem_ctx,
337 "SELECT eid FROM ldb_attribute_values "
338 "WHERE norm_attr_name = '%q' "
339 "AND norm_attr_value = '%q'",
340 attr,
341 value.data);
345 case LDB_OP_SUBSTRING:
347 wild_card_string = talloc_strdup(mem_ctx,
348 (t->u.substring.start_with_wildcard)?"*":"");
349 if (wild_card_string == NULL) return NULL;
351 for (i = 0; t->u.substring.chunks[i]; i++) {
352 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
353 t->u.substring.chunks[i]->data);
354 if (wild_card_string == NULL) return NULL;
357 if ( ! t->u.substring.end_with_wildcard ) {
358 /* remove last wildcard */
359 wild_card_string[strlen(wild_card_string) - 1] = '\0';
362 attr = ldb_attr_casefold(mem_ctx, t->u.substring.attr);
363 if (attr == NULL) return NULL;
364 a = ldb_schema_attribute_by_name(ldb, attr);
366 subval.data = (void *)wild_card_string;
367 subval.length = strlen(wild_card_string) + 1;
369 /* Get a canonicalised copy of the data */
370 a->syntax->canonicalise_fn(ldb, mem_ctx, &(subval), &value);
371 if (value.data == NULL) {
372 return NULL;
375 return lsqlite3_tprintf(mem_ctx,
376 "SELECT eid FROM ldb_attribute_values "
377 "WHERE norm_attr_name = '%q' "
378 "AND norm_attr_value GLOB '%q'",
379 attr,
380 value.data);
382 case LDB_OP_GREATER:
383 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
384 if (attr == NULL) return NULL;
385 a = ldb_schema_attribute_by_name(ldb, attr);
387 /* Get a canonicalised copy of the data */
388 a->syntax->canonicalise_fn(ldb, mem_ctx, &(t->u.equality.value), &value);
389 if (value.data == NULL) {
390 return NULL;
393 return lsqlite3_tprintf(mem_ctx,
394 "SELECT eid FROM ldb_attribute_values "
395 "WHERE norm_attr_name = '%q' "
396 "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
397 attr,
398 value.data,
399 attr);
401 case LDB_OP_LESS:
402 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
403 if (attr == NULL) return NULL;
404 a = ldb_schema_attribute_by_name(ldb, attr);
406 /* Get a canonicalised copy of the data */
407 a->syntax->canonicalise_fn(ldb, mem_ctx, &(t->u.equality.value), &value);
408 if (value.data == NULL) {
409 return NULL;
412 return lsqlite3_tprintf(mem_ctx,
413 "SELECT eid FROM ldb_attribute_values "
414 "WHERE norm_attr_name = '%q' "
415 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
416 attr,
417 value.data,
418 attr);
420 case LDB_OP_PRESENT:
421 if (strcasecmp(t->u.present.attr, "dn") == 0) {
422 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
425 attr = ldb_attr_casefold(mem_ctx, t->u.present.attr);
426 if (attr == NULL) return NULL;
428 return lsqlite3_tprintf(mem_ctx,
429 "SELECT eid FROM ldb_attribute_values "
430 "WHERE norm_attr_name = '%q' ",
431 attr);
433 case LDB_OP_APPROX:
434 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
435 if (attr == NULL) return NULL;
436 a = ldb_schema_attribute_by_name(ldb, attr);
438 /* Get a canonicalised copy of the data */
439 a->syntax->canonicalise_fn(ldb, mem_ctx, &(t->u.equality.value), &value);
440 if (value.data == NULL) {
441 return NULL;
444 return lsqlite3_tprintf(mem_ctx,
445 "SELECT eid FROM ldb_attribute_values "
446 "WHERE norm_attr_name = '%q' "
447 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
448 attr,
449 value.data,
450 attr);
452 case LDB_OP_EXTENDED:
453 #warning "work out how to handle bitops"
454 return NULL;
456 default:
457 break;
460 /* should never occur */
461 abort();
462 return NULL;
466 * query_int()
468 * This function is used for the common case of queries that return a single
469 * integer value.
471 * NOTE: If more than one value is returned by the query, all but the first
472 * one will be ignored.
474 static int
475 query_int(const struct lsqlite3_private * lsqlite3,
476 long long * pRet,
477 const char * pSql,
478 ...)
480 int ret;
481 int bLoop;
482 char * p;
483 sqlite3_stmt * pStmt;
484 va_list args;
486 /* Begin access to variable argument list */
487 va_start(args, pSql);
489 /* Format the query */
490 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
491 va_end(args);
492 return SQLITE_NOMEM;
496 * Prepare and execute the SQL statement. Loop allows retrying on
497 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
498 * requiring retrying the operation.
500 for (bLoop = TRUE; bLoop; ) {
502 /* Compile the SQL statement into sqlite virtual machine */
503 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
506 &pStmt,
507 NULL)) == SQLITE_SCHEMA) {
508 if (stmtGetEID != NULL) {
509 sqlite3_finalize(stmtGetEID);
510 stmtGetEID = NULL;
512 continue;
513 } else if (ret != SQLITE_OK) {
514 break;
517 /* One row expected */
518 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
519 if (stmtGetEID != NULL) {
520 sqlite3_finalize(stmtGetEID);
521 stmtGetEID = NULL;
523 (void) sqlite3_finalize(pStmt);
524 continue;
525 } else if (ret != SQLITE_ROW) {
526 (void) sqlite3_finalize(pStmt);
527 break;
530 /* Get the value to be returned */
531 *pRet = sqlite3_column_int64(pStmt, 0);
533 /* Free the virtual machine */
534 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
535 if (stmtGetEID != NULL) {
536 sqlite3_finalize(stmtGetEID);
537 stmtGetEID = NULL;
539 continue;
540 } else if (ret != SQLITE_OK) {
541 (void) sqlite3_finalize(pStmt);
542 break;
546 * Normal condition is only one time through loop. Loop is
547 * rerun in error conditions, via "continue", above.
549 bLoop = FALSE;
552 /* All done with variable argument list */
553 va_end(args);
556 /* Free the memory we allocated for our query string */
557 sqlite3_free(p);
559 return ret;
563 * This is a bad hack to support ldap style comparisons within sqlite.
564 * val is the attribute in the row currently under test
565 * func is the desired test "<=" ">=" "~" ":"
566 * cmp is the value to compare against (eg: "test")
567 * attr is the attribute name the value of which we want to test
570 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
571 sqlite3_value **argv)
573 struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
574 const char *val = (const char *)sqlite3_value_text(argv[0]);
575 const char *func = (const char *)sqlite3_value_text(argv[1]);
576 const char *cmp = (const char *)sqlite3_value_text(argv[2]);
577 const char *attr = (const char *)sqlite3_value_text(argv[3]);
578 const struct ldb_schema_attribute *a;
579 struct ldb_val valX;
580 struct ldb_val valY;
581 int ret;
583 switch (func[0]) {
584 /* greater */
585 case '>': /* >= */
586 a = ldb_schema_attribute_by_name(ldb, attr);
587 valX.data = (uint8_t *)cmp;
588 valX.length = strlen(cmp);
589 valY.data = (uint8_t *)val;
590 valY.length = strlen(val);
591 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
592 if (ret >= 0)
593 sqlite3_result_int(ctx, 1);
594 else
595 sqlite3_result_int(ctx, 0);
596 return;
598 /* lesser */
599 case '<': /* <= */
600 a = ldb_schema_attribute_by_name(ldb, attr);
601 valX.data = (uint8_t *)cmp;
602 valX.length = strlen(cmp);
603 valY.data = (uint8_t *)val;
604 valY.length = strlen(val);
605 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
606 if (ret <= 0)
607 sqlite3_result_int(ctx, 1);
608 else
609 sqlite3_result_int(ctx, 0);
610 return;
612 /* approx */
613 case '~':
614 /* TODO */
615 sqlite3_result_int(ctx, 0);
616 return;
618 /* bitops */
619 case ':':
620 /* TODO */
621 sqlite3_result_int(ctx, 0);
622 return;
624 default:
625 break;
628 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
629 return;
633 /* rename a record */
634 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
636 char *errmsg;
637 int ret;
639 /* execute */
640 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
641 if (ret != SQLITE_OK) {
642 if (errmsg) {
643 printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
644 free(errmsg);
646 return -1;
649 return 0;
652 /* return an eid as result */
653 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
655 long long *eid = (long long *)result;
657 if (col_num != 1) return SQLITE_ABORT;
658 if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
660 *eid = atoll(cols[0]);
661 return SQLITE_OK;
665 * add a single set of ldap message values to a ldb_message
667 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
669 struct ldb_context *ldb;
670 struct lsql_context *ac;
671 struct ldb_message *msg;
672 long long eid;
673 unsigned int i;
674 int ret;
676 ac = talloc_get_type(result, struct lsql_context);
677 ldb = ldb_module_get_ctx(ac->module);
679 /* eid, dn, attr_name, attr_value */
680 if (col_num != 4) return SQLITE_ABORT;
682 eid = atoll(cols[0]);
684 if (ac->ares) {
685 msg = ac->ares->message;
688 if (eid != ac->current_eid) { /* here begin a new entry */
690 /* call the async callback for the last entry
691 * except the first time */
692 if (ac->current_eid != 0) {
693 ret = ldb_msg_normalize(ldb, ac->req, msg, &msg);
694 if (ret != LDB_SUCCESS) {
695 return SQLITE_ABORT;
698 ret = ldb_module_send_entry(ac->req, msg, NULL);
699 if (ret != LDB_SUCCESS) {
700 ac->callback_failed = true;
701 /* free msg object */
702 TALLOC_FREE(msg);
703 return SQLITE_ABORT;
706 /* free msg object */
707 TALLOC_FREE(msg);
710 /* start over */
711 ac->ares = talloc_zero(ac, struct ldb_reply);
712 if (!ac->ares) return SQLITE_ABORT;
714 msg = ldb_msg_new(ac->ares);
715 if (!msg) return SQLITE_ABORT;
717 ac->ares->type = LDB_REPLY_ENTRY;
718 ac->current_eid = eid;
721 if (msg->dn == NULL) {
722 msg->dn = ldb_dn_new(msg, ldb, cols[1]);
723 if (msg->dn == NULL)
724 return SQLITE_ABORT;
727 if (ac->attrs) {
728 int found = 0;
729 for (i = 0; ac->attrs[i]; i++) {
730 if (strcasecmp(cols[2], ac->attrs[i]) == 0) {
731 found = 1;
732 break;
735 if (!found) goto done;
738 if (ldb_msg_add_string(msg, cols[2], cols[3]) != 0) {
739 return SQLITE_ABORT;
742 done:
743 ac->ares->message = msg;
744 return SQLITE_OK;
749 * lsqlite3_get_eid()
750 * lsqlite3_get_eid_ndn()
752 * These functions are used for the very common case of retrieving an EID value
753 * given a (normalized) DN.
756 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
758 char *errmsg;
759 char *query;
760 long long eid = -1;
761 long long ret;
763 /* get object eid */
764 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
765 "FROM ldb_entry "
766 "WHERE norm_dn = '%q';", norm_dn);
767 if (query == NULL) return -1;
769 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
770 if (ret != SQLITE_OK) {
771 if (errmsg) {
772 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
773 free(errmsg);
775 return -1;
778 return eid;
781 static long long lsqlite3_get_eid(struct lsqlite3_private *lsqlite3,
782 struct ldb_dn *dn)
784 TALLOC_CTX *local_ctx;
785 long long eid = -1;
786 char *cdn;
788 /* ignore ltdb specials */
789 if (ldb_dn_is_special(dn)) {
790 return -1;
793 /* create a local ctx */
794 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
795 if (local_ctx == NULL) {
796 return -1;
799 cdn = ldb_dn_alloc_casefold(local_ctx, dn);
800 if (!cdn) goto done;
802 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
804 done:
805 talloc_free(local_ctx);
806 return eid;
810 * Interface functions referenced by lsqlite3_ops
813 /* search for matching records, by tree */
814 int lsql_search(struct lsql_context *ctx)
816 struct ldb_module *module = ctx->module;
817 struct ldb_request *req = ctx->req;
818 struct lsqlite3_private *lsqlite3;
819 struct ldb_context *ldb;
820 char *norm_basedn;
821 char *sqlfilter;
822 char *errmsg;
823 char *query = NULL;
824 int ret;
826 ldb = ldb_module_get_ctx(module);
827 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
828 struct lsqlite3_private);
830 if ((( ! ldb_dn_is_valid(req->op.search.base)) ||
831 ldb_dn_is_null(req->op.search.base)) &&
832 (req->op.search.scope == LDB_SCOPE_BASE ||
833 req->op.search.scope == LDB_SCOPE_ONELEVEL)) {
834 return LDB_ERR_OPERATIONS_ERROR;
837 if (req->op.search.base) {
838 norm_basedn = ldb_dn_alloc_casefold(ctx, req->op.search.base);
839 if (norm_basedn == NULL) {
840 return LDB_ERR_OPERATIONS_ERROR;
842 } else norm_basedn = talloc_strdup(ctx, "");
844 /* Convert filter into a series of SQL conditions (constraints) */
845 sqlfilter = parsetree_to_sql(module, ctx, req->op.search.tree);
847 switch(req->op.search.scope) {
848 case LDB_SCOPE_DEFAULT:
849 case LDB_SCOPE_SUBTREE:
850 if (*norm_basedn != '\0') {
851 query = lsqlite3_tprintf(ctx,
852 "SELECT entry.eid,\n"
853 " entry.dn,\n"
854 " av.attr_name,\n"
855 " av.attr_value\n"
856 " FROM ldb_entry AS entry\n"
858 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
859 " ON av.eid = entry.eid\n"
861 " WHERE entry.eid IN\n"
862 " (SELECT DISTINCT ldb_entry.eid\n"
863 " FROM ldb_entry\n"
864 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
865 " OR ldb_entry.norm_dn = '%q')\n"
866 " AND ldb_entry.eid IN\n"
867 " (%s)\n"
868 " )\n"
870 " ORDER BY entry.eid ASC;",
871 norm_basedn,
872 norm_basedn,
873 sqlfilter);
874 } else {
875 query = lsqlite3_tprintf(ctx,
876 "SELECT entry.eid,\n"
877 " entry.dn,\n"
878 " av.attr_name,\n"
879 " av.attr_value\n"
880 " FROM ldb_entry AS entry\n"
882 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
883 " ON av.eid = entry.eid\n"
885 " WHERE entry.eid IN\n"
886 " (SELECT DISTINCT ldb_entry.eid\n"
887 " FROM ldb_entry\n"
888 " WHERE ldb_entry.eid IN\n"
889 " (%s)\n"
890 " )\n"
892 " ORDER BY entry.eid ASC;",
893 sqlfilter);
896 break;
898 case LDB_SCOPE_BASE:
899 query = lsqlite3_tprintf(ctx,
900 "SELECT entry.eid,\n"
901 " entry.dn,\n"
902 " av.attr_name,\n"
903 " av.attr_value\n"
904 " FROM ldb_entry AS entry\n"
906 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
907 " ON av.eid = entry.eid\n"
909 " WHERE entry.eid IN\n"
910 " (SELECT DISTINCT ldb_entry.eid\n"
911 " FROM ldb_entry\n"
912 " WHERE ldb_entry.norm_dn = '%q'\n"
913 " AND ldb_entry.eid IN\n"
914 " (%s)\n"
915 " )\n"
917 " ORDER BY entry.eid ASC;",
918 norm_basedn,
919 sqlfilter);
920 break;
922 case LDB_SCOPE_ONELEVEL:
923 query = lsqlite3_tprintf(ctx,
924 "SELECT entry.eid,\n"
925 " entry.dn,\n"
926 " av.attr_name,\n"
927 " av.attr_value\n"
928 " FROM ldb_entry AS entry\n"
930 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
931 " ON av.eid = entry.eid\n"
933 " WHERE entry.eid IN\n"
934 " (SELECT DISTINCT ldb_entry.eid\n"
935 " FROM ldb_entry\n"
936 " WHERE norm_dn GLOB('*,%q')\n"
937 " AND NOT norm_dn GLOB('*,*,%q')\n"
938 " AND ldb_entry.eid IN\n(%s)\n"
939 " )\n"
941 " ORDER BY entry.eid ASC;",
942 norm_basedn,
943 norm_basedn,
944 sqlfilter);
945 break;
948 if (query == NULL) {
949 return LDB_ERR_OPERATIONS_ERROR;
952 /* * /
953 printf ("%s\n", query);
954 / * */
956 ctx->current_eid = 0;
957 ctx->attrs = req->op.search.attrs;
958 ctx->ares = NULL;
960 ldb_request_set_state(req, LDB_ASYNC_PENDING);
962 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, ctx, &errmsg);
963 if (ret != SQLITE_OK) {
964 if (errmsg) {
965 ldb_set_errstring(ldb, errmsg);
966 free(errmsg);
968 return LDB_ERR_OPERATIONS_ERROR;
971 /* complete the last message if any */
972 if (ctx->ares) {
973 ret = ldb_msg_normalize(ldb, ctx->ares,
974 ctx->ares->message,
975 &ctx->ares->message);
976 if (ret != LDB_SUCCESS) {
977 return LDB_ERR_OPERATIONS_ERROR;
980 ret = ldb_module_send_entry(req, ctx->ares->message, NULL);
981 if (ret != LDB_SUCCESS) {
982 return ret;
987 return LDB_SUCCESS;
990 /* add a record */
991 static int lsql_add(struct lsql_context *ctx)
993 struct ldb_module *module = ctx->module;
994 struct ldb_request *req = ctx->req;
995 struct lsqlite3_private *lsqlite3;
996 struct ldb_context *ldb;
997 struct ldb_message *msg = req->op.add.message;
998 long long eid;
999 char *dn, *ndn;
1000 char *errmsg;
1001 char *query;
1002 unsigned int i;
1003 int ret;
1005 ldb = ldb_module_get_ctx(module);
1006 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1007 struct lsqlite3_private);
1009 /* See if this is an ltdb special */
1010 if (ldb_dn_is_special(msg->dn)) {
1012 struct ldb_dn *c;
1013 c = ldb_dn_new(local_ctx, ldb, "@INDEXLIST");
1014 if (ldb_dn_compare(ldb, msg->dn, c) == 0) {
1015 #warning "should we handle indexes somehow ?"
1016 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1017 goto done;
1020 /* Others return an error */
1021 return LDB_ERR_UNWILLING_TO_PERFORM;
1024 /* create linearized and normalized dns */
1025 dn = ldb_dn_alloc_linearized(ctx, msg->dn);
1026 ndn = ldb_dn_alloc_casefold(ctx, msg->dn);
1027 if (dn == NULL || ndn == NULL) {
1028 return LDB_ERR_OPERATIONS_ERROR;
1031 query = lsqlite3_tprintf(ctx,
1032 /* Add new entry */
1033 "INSERT OR ABORT INTO ldb_entry "
1034 "('dn', 'norm_dn') "
1035 "VALUES ('%q', '%q');",
1036 dn, ndn);
1037 if (query == NULL) {
1038 return LDB_ERR_OPERATIONS_ERROR;
1041 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1042 if (ret != SQLITE_OK) {
1043 if (errmsg) {
1044 ldb_set_errstring(ldb, errmsg);
1045 free(errmsg);
1047 return LDB_ERR_OPERATIONS_ERROR;
1050 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, ctx, ndn);
1051 if (eid == -1) {
1052 return LDB_ERR_OPERATIONS_ERROR;
1055 for (i = 0; i < msg->num_elements; i++) {
1056 const struct ldb_message_element *el = &msg->elements[i];
1057 const struct ldb_schema_attribute *a;
1058 char *attr;
1059 unsigned int j;
1061 /* Get a case-folded copy of the attribute name */
1062 attr = ldb_attr_casefold(ctx, el->name);
1063 if (attr == NULL) {
1064 return LDB_ERR_OPERATIONS_ERROR;
1067 a = ldb_schema_attribute_by_name(ldb, el->name);
1069 if (el->num_value == 0) {
1070 ldb_asprintf_errstring(ldb, "attribute %s on %s specified, but with 0 values (illegal)",
1071 el->name, ldb_dn_get_linearized(msg->dn));
1072 return LDB_ERR_CONSTRAINT_VIOLATION;
1075 /* For each value of the specified attribute name... */
1076 for (j = 0; j < el->num_values; j++) {
1077 struct ldb_val value;
1078 char *insert;
1080 /* Get a canonicalised copy of the data */
1081 a->syntax->canonicalise_fn(ldb, ctx, &(el->values[j]), &value);
1082 if (value.data == NULL) {
1083 return LDB_ERR_OPERATIONS_ERROR;
1086 insert = lsqlite3_tprintf(ctx,
1087 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1088 "('eid', 'attr_name', 'norm_attr_name',"
1089 " 'attr_value', 'norm_attr_value') "
1090 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1091 eid, el->name, attr,
1092 el->values[j].data, value.data);
1093 if (insert == NULL) {
1094 return LDB_ERR_OPERATIONS_ERROR;
1097 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1098 if (ret != SQLITE_OK) {
1099 if (errmsg) {
1100 ldb_set_errstring(ldb, errmsg);
1101 free(errmsg);
1103 return LDB_ERR_OPERATIONS_ERROR;
1108 return LDB_SUCCESS;
1111 /* modify a record */
1112 static int lsql_modify(struct lsql_context *ctx)
1114 struct ldb_module *module = ctx->module;
1115 struct ldb_request *req = ctx->req;
1116 struct lsqlite3_private *lsqlite3;
1117 struct ldb_context *ldb;
1118 struct ldb_message *msg = req->op.mod.message;
1119 long long eid;
1120 char *errmsg;
1121 unsigned int i;
1122 int ret;
1124 ldb = ldb_module_get_ctx(module);
1125 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1126 struct lsqlite3_private);
1128 /* See if this is an ltdb special */
1129 if (ldb_dn_is_special(msg->dn)) {
1130 /* Others return an error */
1131 return LDB_ERR_UNWILLING_TO_PERFORM;
1134 eid = lsqlite3_get_eid(lsqlite3, msg->dn);
1135 if (eid == -1) {
1136 return LDB_ERR_OPERATIONS_ERROR;
1139 for (i = 0; i < msg->num_elements; i++) {
1140 const struct ldb_message_element *el = &msg->elements[i];
1141 const struct ldb_schema_attribute *a;
1142 unsigned int flags = el->flags & LDB_FLAG_MOD_MASK;
1143 char *attr;
1144 char *mod;
1145 unsigned int j;
1147 /* Get a case-folded copy of the attribute name */
1148 attr = ldb_attr_casefold(ctx, el->name);
1149 if (attr == NULL) {
1150 return LDB_ERR_OPERATIONS_ERROR;
1153 a = ldb_schema_attribute_by_name(ldb, el->name);
1155 switch (flags) {
1157 case LDB_FLAG_MOD_REPLACE:
1158 struct ldb_val *duplicate = NULL;
1160 ret = ldb_msg_find_duplicate_val(ldb, el, el,
1161 &duplicate, 0);
1162 if (ret != LDB_SUCCESS) {
1163 return ret;
1165 if (duplicate != NULL) {
1166 ldb_asprintf_errstring(
1167 ldb,
1168 "attribute '%s': value '%.*s' "
1169 "on '%s' provided more than "
1170 "once in REPLACE",
1171 el->name,
1172 (int)duplicate->length,
1173 duplicate->data,
1174 ldb_dn_get_linearized(msg2->dn));
1175 return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
1178 /* remove all attributes before adding the replacements */
1179 mod = lsqlite3_tprintf(ctx,
1180 "DELETE FROM ldb_attribute_values "
1181 "WHERE eid = '%lld' "
1182 "AND norm_attr_name = '%q';",
1183 eid, attr);
1184 if (mod == NULL) {
1185 return LDB_ERR_OPERATIONS_ERROR;
1188 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1189 if (ret != SQLITE_OK) {
1190 if (errmsg) {
1191 ldb_set_errstring(ldb, errmsg);
1192 free(errmsg);
1194 return LDB_ERR_OPERATIONS_ERROR;
1197 /* MISSING break is INTENTIONAL */
1199 case LDB_FLAG_MOD_ADD:
1201 if (el->num_values == 0) {
1202 ldb_asprintf_errstring(ldb, "attribute %s on %s specified, but with 0 values (illigal)",
1203 el->name, ldb_dn_get_linearized(msg->dn));
1204 return LDB_ERR_CONSTRAINT_VIOLATION;
1207 /* For each value of the specified attribute name... */
1208 for (j = 0; j < el->num_values; j++) {
1209 struct ldb_val value;
1211 /* Get a canonicalised copy of the data */
1212 a->syntax->canonicalise_fn(ldb, ctx, &(el->values[j]), &value);
1213 if (value.data == NULL) {
1214 return LDB_ERR_OPERATIONS_ERROR;
1217 mod = lsqlite3_tprintf(ctx,
1218 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1219 "('eid', 'attr_name', 'norm_attr_name',"
1220 " 'attr_value', 'norm_attr_value') "
1221 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1222 eid, el->name, attr,
1223 el->values[j].data, value.data);
1225 if (mod == NULL) {
1226 return LDB_ERR_OPERATIONS_ERROR;
1229 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1230 if (ret != SQLITE_OK) {
1231 if (errmsg) {
1232 ldb_set_errstring(ldb, errmsg);
1233 free(errmsg);
1235 return LDB_ERR_OPERATIONS_ERROR;
1239 break;
1241 case LDB_FLAG_MOD_DELETE:
1242 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1243 if (el->num_values == 0) {
1244 mod = lsqlite3_tprintf(ctx,
1245 "DELETE FROM ldb_attribute_values "
1246 "WHERE eid = '%lld' "
1247 "AND norm_attr_name = '%q';",
1248 eid, attr);
1249 if (mod == NULL) {
1250 return LDB_ERR_OPERATIONS_ERROR;
1253 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1254 if (ret != SQLITE_OK) {
1255 if (errmsg) {
1256 ldb_set_errstring(ldb, errmsg);
1257 free(errmsg);
1259 return LDB_ERR_OPERATIONS_ERROR;
1263 /* For each value of the specified attribute name... */
1264 for (j = 0; j < el->num_values; j++) {
1265 struct ldb_val value;
1267 /* Get a canonicalised copy of the data */
1268 a->syntax->canonicalise_fn(ldb, ctx, &(el->values[j]), &value);
1269 if (value.data == NULL) {
1270 return LDB_ERR_OPERATIONS_ERROR;
1273 mod = lsqlite3_tprintf(ctx,
1274 "DELETE FROM ldb_attribute_values "
1275 "WHERE eid = '%lld' "
1276 "AND norm_attr_name = '%q' "
1277 "AND norm_attr_value = '%q';",
1278 eid, attr, value.data);
1280 if (mod == NULL) {
1281 return LDB_ERR_OPERATIONS_ERROR;
1284 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1285 if (ret != SQLITE_OK) {
1286 if (errmsg) {
1287 ldb_set_errstring(ldb, errmsg);
1288 free(errmsg);
1290 return LDB_ERR_OPERATIONS_ERROR;
1294 break;
1298 return LDB_SUCCESS;
1301 /* delete a record */
1302 static int lsql_delete(struct lsql_context *ctx)
1304 struct ldb_module *module = ctx->module;
1305 struct ldb_request *req = ctx->req;
1306 struct lsqlite3_private *lsqlite3;
1307 struct ldb_context *ldb;
1308 long long eid;
1309 char *errmsg;
1310 char *query;
1311 int ret;
1313 ldb = ldb_module_get_ctx(module);
1314 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1315 struct lsqlite3_private);
1317 eid = lsqlite3_get_eid(lsqlite3, req->op.del.dn);
1318 if (eid == -1) {
1319 return LDB_ERR_OPERATIONS_ERROR;
1322 query = lsqlite3_tprintf(ctx,
1323 /* Delete entry */
1324 "DELETE FROM ldb_entry WHERE eid = %lld; "
1325 /* Delete attributes */
1326 "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1327 eid, eid);
1328 if (query == NULL) {
1329 return LDB_ERR_OPERATIONS_ERROR;
1332 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1333 if (ret != SQLITE_OK) {
1334 if (errmsg) {
1335 ldb_set_errstring(ldb, errmsg);
1336 free(errmsg);
1338 return LDB_ERR_OPERATIONS_ERROR;
1341 return LDB_SUCCESS;
1344 /* rename a record */
1345 static int lsql_rename(struct lsql_context *ctx)
1347 struct ldb_module *module = ctx->module;
1348 struct ldb_request *req = ctx->req;
1349 struct lsqlite3_private *lsqlite3;
1350 struct ldb_context *ldb;
1351 char *new_dn, *new_cdn, *old_cdn;
1352 char *errmsg;
1353 char *query;
1354 int ret;
1356 ldb = ldb_module_get_ctx(module);
1357 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1358 struct lsqlite3_private);
1360 /* create linearized and normalized dns */
1361 old_cdn = ldb_dn_alloc_casefold(ctx, req->op.rename.olddn);
1362 new_cdn = ldb_dn_alloc_casefold(ctx, req->op.rename.newdn);
1363 new_dn = ldb_dn_alloc_linearized(ctx, req->op.rename.newdn);
1364 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1365 return LDB_ERR_OPERATIONS_ERROR;
1368 /* build the SQL query */
1369 query = lsqlite3_tprintf(ctx,
1370 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1371 "WHERE norm_dn = '%q';",
1372 new_dn, new_cdn, old_cdn);
1373 if (query == NULL) {
1374 return LDB_ERR_OPERATIONS_ERROR;
1377 /* execute */
1378 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1379 if (ret != SQLITE_OK) {
1380 if (errmsg) {
1381 ldb_set_errstring(ldb, errmsg);
1382 free(errmsg);
1384 return LDB_ERR_OPERATIONS_ERROR;
1387 return LDB_SUCCESS;
1390 static int lsql_start_trans(struct ldb_module * module)
1392 int ret;
1393 char *errmsg;
1394 struct lsqlite3_private *lsqlite3;
1396 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1397 struct lsqlite3_private);
1399 if (lsqlite3->trans_count == 0) {
1400 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1401 if (ret != SQLITE_OK) {
1402 if (errmsg) {
1403 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1404 free(errmsg);
1406 return -1;
1410 lsqlite3->trans_count++;
1412 return 0;
1415 static int lsql_end_trans(struct ldb_module *module)
1417 int ret;
1418 char *errmsg;
1419 struct lsqlite3_private *lsqlite3;
1421 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1422 struct lsqlite3_private);
1424 if (lsqlite3->trans_count > 0) {
1425 lsqlite3->trans_count--;
1426 } else return -1;
1428 if (lsqlite3->trans_count == 0) {
1429 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1430 if (ret != SQLITE_OK) {
1431 if (errmsg) {
1432 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1433 free(errmsg);
1435 return -1;
1439 return 0;
1442 static int lsql_del_trans(struct ldb_module *module)
1444 struct lsqlite3_private *lsqlite3;
1446 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1447 struct lsqlite3_private);
1449 if (lsqlite3->trans_count > 0) {
1450 lsqlite3->trans_count--;
1451 } else return -1;
1453 if (lsqlite3->trans_count == 0) {
1454 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1457 return -1;
1460 static int destructor(struct lsqlite3_private *lsqlite3)
1462 if (lsqlite3->sqlite) {
1463 sqlite3_close(lsqlite3->sqlite);
1465 return 0;
1468 static void lsql_request_done(struct lsql_context *ctx, int error)
1470 struct ldb_context *ldb;
1471 struct ldb_request *req;
1472 struct ldb_reply *ares;
1474 ldb = ldb_module_get_ctx(ctx->module);
1475 req = ctx->req;
1477 /* if we already returned an error just return */
1478 if (ldb_request_get_status(req) != LDB_SUCCESS) {
1479 return;
1482 ares = talloc_zero(req, struct ldb_reply);
1483 if (!ares) {
1484 ldb_oom(ldb);
1485 req->callback(req, NULL);
1486 return;
1488 ares->type = LDB_REPLY_DONE;
1489 ares->error = error;
1491 req->callback(req, ares);
1494 static void lsql_timeout(struct tevent_context *ev,
1495 struct tevent_timer *te,
1496 struct timeval t,
1497 void *private_data)
1499 struct lsql_context *ctx;
1500 ctx = talloc_get_type(private_data, struct lsql_context);
1502 lsql_request_done(ctx, LDB_ERR_TIME_LIMIT_EXCEEDED);
1505 static void lsql_callback(struct tevent_context *ev,
1506 struct tevent_timer *te,
1507 struct timeval t,
1508 void *private_data)
1510 struct lsql_context *ctx;
1511 int ret;
1513 ctx = talloc_get_type(private_data, struct lsql_context);
1515 switch (ctx->req->operation) {
1516 case LDB_SEARCH:
1517 ret = lsql_search(ctx);
1518 break;
1519 case LDB_ADD:
1520 ret = lsql_add(ctx);
1521 break;
1522 case LDB_MODIFY:
1523 ret = lsql_modify(ctx);
1524 break;
1525 case LDB_DELETE:
1526 ret = lsql_delete(ctx);
1527 break;
1528 case LDB_RENAME:
1529 ret = lsql_rename(ctx);
1530 break;
1531 /* TODO:
1532 case LDB_EXTENDED:
1533 ret = lsql_extended(ctx);
1534 break;
1536 default:
1537 /* no other op supported */
1538 ret = LDB_ERR_PROTOCOL_ERROR;
1541 if (!ctx->callback_failed) {
1542 /* Once we are done, we do not need timeout events */
1543 talloc_free(ctx->timeout_event);
1544 lsql_request_done(ctx, ret);
1548 static int lsql_handle_request(struct ldb_module *module, struct ldb_request *req)
1550 struct ldb_context *ldb;
1551 struct tevent_context *ev;
1552 struct lsql_context *ac;
1553 struct tevent_timer *te;
1554 struct timeval tv;
1556 if (ldb_check_critical_controls(req->controls)) {
1557 return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
1560 if (req->starttime == 0 || req->timeout == 0) {
1561 ldb_set_errstring(ldb, "Invalid timeout settings");
1562 return LDB_ERR_TIME_LIMIT_EXCEEDED;
1565 ldb = ldb_module_get_ctx(module);
1566 ev = ldb_get_event_context(ldb);
1568 ac = talloc_zero(req, struct lsql_context);
1569 if (ac == NULL) {
1570 ldb_set_errstring(ldb, "Out of Memory");
1571 return LDB_ERR_OPERATIONS_ERROR;
1574 ac->module = module;
1575 ac->req = req;
1577 tv.tv_sec = 0;
1578 tv.tv_usec = 0;
1579 te = tevent_add_timer(ev, ac, tv, lsql_callback, ac);
1580 if (NULL == te) {
1581 return LDB_ERR_OPERATIONS_ERROR;
1584 if (req->timeout > 0) {
1585 tv.tv_sec = req->starttime + req->timeout;
1586 tv.tv_usec = 0;
1587 ac->timeout_event = tevent_add_timer(ev, ac, tv, lsql_timeout, ac);
1588 if (NULL == ac->timeout_event) {
1589 return LDB_ERR_OPERATIONS_ERROR;
1593 return LDB_SUCCESS;
1597 * Table of operations for the sqlite3 backend
1599 static const struct ldb_module_ops lsqlite3_ops = {
1600 .name = "sqlite",
1601 .search = lsql_handle_request,
1602 .add = lsql_handle_request,
1603 .modify = lsql_handle_request,
1604 .del = lsql_handle_request,
1605 .rename = lsql_handle_request,
1606 .extended = lsql_handle_request,
1607 .start_transaction = lsql_start_trans,
1608 .end_transaction = lsql_end_trans,
1609 .del_transaction = lsql_del_trans,
1613 * Static functions
1616 static int initialize(struct lsqlite3_private *lsqlite3,
1617 struct ldb_context *ldb, const char *url,
1618 unsigned int flags)
1620 TALLOC_CTX *local_ctx;
1621 long long queryInt;
1622 int rollback = 0;
1623 char *errmsg;
1624 char *schema;
1625 int ret;
1627 /* create a local ctx */
1628 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1629 if (local_ctx == NULL) {
1630 return -1;
1633 schema = lsqlite3_tprintf(local_ctx,
1636 "CREATE TABLE ldb_info AS "
1637 " SELECT 'LDB' AS database_type,"
1638 " '1.0' AS version;"
1641 * The entry table holds the information about an entry.
1642 * This table is used to obtain the EID of the entry and to
1643 * support scope=one and scope=base. The parent and child
1644 * table is included in the entry table since all the other
1645 * attributes are dependent on EID.
1647 "CREATE TABLE ldb_entry "
1649 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1650 " dn TEXT UNIQUE NOT NULL,"
1651 " norm_dn TEXT UNIQUE NOT NULL"
1652 ");"
1655 "CREATE TABLE ldb_object_classes"
1657 " class_name TEXT PRIMARY KEY,"
1658 " parent_class_name TEXT,"
1659 " tree_key TEXT UNIQUE,"
1660 " max_child_num INTEGER DEFAULT 0"
1661 ");"
1664 * We keep a full listing of attribute/value pairs here
1666 "CREATE TABLE ldb_attribute_values"
1668 " eid INTEGER REFERENCES ldb_entry,"
1669 " attr_name TEXT,"
1670 " norm_attr_name TEXT,"
1671 " attr_value TEXT,"
1672 " norm_attr_value TEXT "
1673 ");"
1677 * Indexes
1679 "CREATE INDEX ldb_attribute_values_eid_idx "
1680 " ON ldb_attribute_values (eid);"
1682 "CREATE INDEX ldb_attribute_values_name_value_idx "
1683 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1688 * Triggers
1691 "CREATE TRIGGER ldb_object_classes_insert_tr"
1692 " AFTER INSERT"
1693 " ON ldb_object_classes"
1694 " FOR EACH ROW"
1695 " BEGIN"
1696 " UPDATE ldb_object_classes"
1697 " SET tree_key = COALESCE(tree_key, "
1698 " ("
1699 " SELECT tree_key || "
1700 " (SELECT base160(max_child_num + 1)"
1701 " FROM ldb_object_classes"
1702 " WHERE class_name = "
1703 " new.parent_class_name)"
1704 " FROM ldb_object_classes "
1705 " WHERE class_name = new.parent_class_name "
1706 " ));"
1707 " UPDATE ldb_object_classes "
1708 " SET max_child_num = max_child_num + 1"
1709 " WHERE class_name = new.parent_class_name;"
1710 " END;"
1713 * Table initialization
1716 "INSERT INTO ldb_object_classes "
1717 " (class_name, tree_key) "
1718 " VALUES "
1719 " ('TOP', '0001');");
1721 /* Skip protocol indicator of url */
1722 if (strncmp(url, "sqlite3://", 10) != 0) {
1723 return SQLITE_MISUSE;
1726 /* Update pointer to just after the protocol indicator */
1727 url += 10;
1729 /* Try to open the (possibly empty/non-existent) database */
1730 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1731 return ret;
1734 /* In case this is a new database, enable auto_vacuum */
1735 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1736 if (ret != SQLITE_OK) {
1737 if (errmsg) {
1738 printf("lsqlite3 initializaion error: %s\n", errmsg);
1739 free(errmsg);
1741 goto failed;
1744 if (flags & LDB_FLG_NOSYNC) {
1745 /* DANGEROUS */
1746 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1747 if (ret != SQLITE_OK) {
1748 if (errmsg) {
1749 printf("lsqlite3 initializaion error: %s\n", errmsg);
1750 free(errmsg);
1752 goto failed;
1756 /* */
1758 /* Establish a busy timeout of 30 seconds */
1759 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1760 30000)) != SQLITE_OK) {
1761 return ret;
1764 /* Create a function, callable from sql, to increment a tree_key */
1765 if ((ret =
1766 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1767 "base160_next", /* function name */
1768 1, /* number of args */
1769 SQLITE_ANY, /* preferred text type */
1770 NULL, /* user data */
1771 base160next_sql, /* called func */
1772 NULL, /* step func */
1773 NULL /* final func */
1774 )) != SQLITE_OK) {
1775 return ret;
1778 /* Create a function, callable from sql, to convert int to base160 */
1779 if ((ret =
1780 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1781 "base160", /* function name */
1782 1, /* number of args */
1783 SQLITE_ANY, /* preferred text type */
1784 NULL, /* user data */
1785 base160_sql, /* called func */
1786 NULL, /* step func */
1787 NULL /* final func */
1788 )) != SQLITE_OK) {
1789 return ret;
1792 /* Create a function, callable from sql, to perform various comparisons */
1793 if ((ret =
1794 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1795 "ldap_compare", /* function name */
1796 4, /* number of args */
1797 SQLITE_ANY, /* preferred text type */
1798 ldb , /* user data */
1799 lsqlite3_compare, /* called func */
1800 NULL, /* step func */
1801 NULL /* final func */
1802 )) != SQLITE_OK) {
1803 return ret;
1806 /* Begin a transaction */
1807 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1808 if (ret != SQLITE_OK) {
1809 if (errmsg) {
1810 printf("lsqlite3: initialization error: %s\n", errmsg);
1811 free(errmsg);
1813 goto failed;
1815 rollback = 1;
1817 /* Determine if this is a new database. No tables means it is. */
1818 if (query_int(lsqlite3,
1819 &queryInt,
1820 "SELECT COUNT(*)\n"
1821 " FROM sqlite_master\n"
1822 " WHERE type = 'table';") != 0) {
1823 goto failed;
1826 if (queryInt == 0) {
1828 * Create the database schema
1830 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1831 if (ret != SQLITE_OK) {
1832 if (errmsg) {
1833 printf("lsqlite3 initializaion error: %s\n", errmsg);
1834 free(errmsg);
1836 goto failed;
1838 } else {
1840 * Ensure that the database we opened is one of ours
1842 if (query_int(lsqlite3,
1843 &queryInt,
1844 "SELECT "
1845 " (SELECT COUNT(*) = 2"
1846 " FROM sqlite_master "
1847 " WHERE type = 'table' "
1848 " AND name IN "
1849 " ("
1850 " 'ldb_entry', "
1851 " 'ldb_object_classes' "
1852 " ) "
1853 " ) "
1854 " AND "
1855 " (SELECT 1 "
1856 " FROM ldb_info "
1857 " WHERE database_type = 'LDB' "
1858 " AND version = '1.0'"
1859 " );") != 0 ||
1860 queryInt != 1) {
1862 /* It's not one that we created. See ya! */
1863 goto failed;
1867 /* Commit the transaction */
1868 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1869 if (ret != SQLITE_OK) {
1870 if (errmsg) {
1871 printf("lsqlite3: iniialization error: %s\n", errmsg);
1872 free(errmsg);
1874 goto failed;
1877 return SQLITE_OK;
1879 failed:
1880 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1881 sqlite3_close(lsqlite3->sqlite);
1882 return -1;
1886 * connect to the database
1888 static int lsqlite3_connect(struct ldb_context *ldb,
1889 const char *url,
1890 unsigned int flags,
1891 const char *options[],
1892 struct ldb_module **_module)
1894 struct ldb_module *module;
1895 struct lsqlite3_private *lsqlite3;
1896 unsigned int i;
1897 int ret;
1899 module = ldb_module_new(ldb, ldb, "ldb_sqlite3 backend", &lsqlite3_ops);
1900 if (!module) return LDB_ERR_OPERATIONS_ERROR;
1902 lsqlite3 = talloc(module, struct lsqlite3_private);
1903 if (!lsqlite3) {
1904 goto failed;
1907 lsqlite3->sqlite = NULL;
1908 lsqlite3->options = NULL;
1909 lsqlite3->trans_count = 0;
1911 ret = initialize(lsqlite3, ldb, url, flags);
1912 if (ret != SQLITE_OK) {
1913 goto failed;
1916 talloc_set_destructor(lsqlite3, destructor);
1918 ldb_module_set_private(module, lsqlite3);
1920 if (options) {
1922 * take a copy of the options array, so we don't have to rely
1923 * on the caller keeping it around (it might be dynamic)
1925 for (i=0;options[i];i++) ;
1927 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1928 if (!lsqlite3->options) {
1929 goto failed;
1932 for (i=0;options[i];i++) {
1934 lsqlite3->options[i+1] = NULL;
1935 lsqlite3->options[i] =
1936 talloc_strdup(lsqlite3->options, options[i]);
1937 if (!lsqlite3->options[i]) {
1938 goto failed;
1943 *_module = module;
1944 return LDB_SUCCESS;
1946 failed:
1947 if (lsqlite3 && lsqlite3->sqlite != NULL) {
1948 (void) sqlite3_close(lsqlite3->sqlite);
1950 talloc_free(lsqlite3);
1951 return LDB_ERR_OPERATIONS_ERROR;
1954 int ldb_sqlite3_init(const char *version)
1956 LDB_MODULE_CHECK_VERSION(version);
1957 return ldb_register_backend("sqlite3", lsqlite3_connect, false);