s3-lsa: Fix static list of luids in our privileges implementation.
[Samba/ekacnet.git] / source4 / lib / ldb / ldb_sqlite3 / ldb_sqlite3.c
blob7dcb1f928507dca48837335c67bc9bb556e3ac34
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));
327 return lsqlite3_tprintf(mem_ctx,
328 "SELECT eid FROM ldb_entry "
329 "WHERE norm_dn = '%q'", cdn);
331 } else {
332 /* A normal query. */
333 return lsqlite3_tprintf(mem_ctx,
334 "SELECT eid FROM ldb_attribute_values "
335 "WHERE norm_attr_name = '%q' "
336 "AND norm_attr_value = '%q'",
337 attr,
338 value.data);
342 case LDB_OP_SUBSTRING:
344 wild_card_string = talloc_strdup(mem_ctx,
345 (t->u.substring.start_with_wildcard)?"*":"");
346 if (wild_card_string == NULL) return NULL;
348 for (i = 0; t->u.substring.chunks[i]; i++) {
349 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
350 t->u.substring.chunks[i]->data);
351 if (wild_card_string == NULL) return NULL;
354 if ( ! t->u.substring.end_with_wildcard ) {
355 /* remove last wildcard */
356 wild_card_string[strlen(wild_card_string) - 1] = '\0';
359 attr = ldb_attr_casefold(mem_ctx, t->u.substring.attr);
360 if (attr == NULL) return NULL;
361 a = ldb_schema_attribute_by_name(ldb, attr);
363 subval.data = (void *)wild_card_string;
364 subval.length = strlen(wild_card_string) + 1;
366 /* Get a canonicalised copy of the data */
367 a->syntax->canonicalise_fn(ldb, mem_ctx, &(subval), &value);
368 if (value.data == NULL) {
369 return NULL;
372 return lsqlite3_tprintf(mem_ctx,
373 "SELECT eid FROM ldb_attribute_values "
374 "WHERE norm_attr_name = '%q' "
375 "AND norm_attr_value GLOB '%q'",
376 attr,
377 value.data);
379 case LDB_OP_GREATER:
380 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
381 if (attr == NULL) return NULL;
382 a = ldb_schema_attribute_by_name(ldb, attr);
384 /* Get a canonicalised copy of the data */
385 a->syntax->canonicalise_fn(ldb, mem_ctx, &(t->u.equality.value), &value);
386 if (value.data == NULL) {
387 return NULL;
390 return lsqlite3_tprintf(mem_ctx,
391 "SELECT eid FROM ldb_attribute_values "
392 "WHERE norm_attr_name = '%q' "
393 "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
394 attr,
395 value.data,
396 attr);
398 case LDB_OP_LESS:
399 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
400 if (attr == NULL) return NULL;
401 a = ldb_schema_attribute_by_name(ldb, attr);
403 /* Get a canonicalised copy of the data */
404 a->syntax->canonicalise_fn(ldb, mem_ctx, &(t->u.equality.value), &value);
405 if (value.data == NULL) {
406 return NULL;
409 return lsqlite3_tprintf(mem_ctx,
410 "SELECT eid FROM ldb_attribute_values "
411 "WHERE norm_attr_name = '%q' "
412 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
413 attr,
414 value.data,
415 attr);
417 case LDB_OP_PRESENT:
418 if (strcasecmp(t->u.present.attr, "dn") == 0) {
419 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
422 attr = ldb_attr_casefold(mem_ctx, t->u.present.attr);
423 if (attr == NULL) return NULL;
425 return lsqlite3_tprintf(mem_ctx,
426 "SELECT eid FROM ldb_attribute_values "
427 "WHERE norm_attr_name = '%q' ",
428 attr);
430 case LDB_OP_APPROX:
431 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
432 if (attr == NULL) return NULL;
433 a = ldb_schema_attribute_by_name(ldb, attr);
435 /* Get a canonicalised copy of the data */
436 a->syntax->canonicalise_fn(ldb, mem_ctx, &(t->u.equality.value), &value);
437 if (value.data == NULL) {
438 return NULL;
441 return lsqlite3_tprintf(mem_ctx,
442 "SELECT eid FROM ldb_attribute_values "
443 "WHERE norm_attr_name = '%q' "
444 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
445 attr,
446 value.data,
447 attr);
449 case LDB_OP_EXTENDED:
450 #warning "work out how to handle bitops"
451 return NULL;
453 default:
454 break;
457 /* should never occur */
458 abort();
459 return NULL;
463 * query_int()
465 * This function is used for the common case of queries that return a single
466 * integer value.
468 * NOTE: If more than one value is returned by the query, all but the first
469 * one will be ignored.
471 static int
472 query_int(const struct lsqlite3_private * lsqlite3,
473 long long * pRet,
474 const char * pSql,
475 ...)
477 int ret;
478 int bLoop;
479 char * p;
480 sqlite3_stmt * pStmt;
481 va_list args;
483 /* Begin access to variable argument list */
484 va_start(args, pSql);
486 /* Format the query */
487 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
488 va_end(args);
489 return SQLITE_NOMEM;
493 * Prepare and execute the SQL statement. Loop allows retrying on
494 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
495 * requiring retrying the operation.
497 for (bLoop = TRUE; bLoop; ) {
499 /* Compile the SQL statement into sqlite virtual machine */
500 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
503 &pStmt,
504 NULL)) == SQLITE_SCHEMA) {
505 if (stmtGetEID != NULL) {
506 sqlite3_finalize(stmtGetEID);
507 stmtGetEID = NULL;
509 continue;
510 } else if (ret != SQLITE_OK) {
511 break;
514 /* One row expected */
515 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
516 if (stmtGetEID != NULL) {
517 sqlite3_finalize(stmtGetEID);
518 stmtGetEID = NULL;
520 (void) sqlite3_finalize(pStmt);
521 continue;
522 } else if (ret != SQLITE_ROW) {
523 (void) sqlite3_finalize(pStmt);
524 break;
527 /* Get the value to be returned */
528 *pRet = sqlite3_column_int64(pStmt, 0);
530 /* Free the virtual machine */
531 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
532 if (stmtGetEID != NULL) {
533 sqlite3_finalize(stmtGetEID);
534 stmtGetEID = NULL;
536 continue;
537 } else if (ret != SQLITE_OK) {
538 (void) sqlite3_finalize(pStmt);
539 break;
543 * Normal condition is only one time through loop. Loop is
544 * rerun in error conditions, via "continue", above.
546 bLoop = FALSE;
549 /* All done with variable argument list */
550 va_end(args);
553 /* Free the memory we allocated for our query string */
554 sqlite3_free(p);
556 return ret;
560 * This is a bad hack to support ldap style comparisons within sqlite.
561 * val is the attribute in the row currently under test
562 * func is the desired test "<=" ">=" "~" ":"
563 * cmp is the value to compare against (eg: "test")
564 * attr is the attribute name the value of which we want to test
567 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
568 sqlite3_value **argv)
570 struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
571 const char *val = (const char *)sqlite3_value_text(argv[0]);
572 const char *func = (const char *)sqlite3_value_text(argv[1]);
573 const char *cmp = (const char *)sqlite3_value_text(argv[2]);
574 const char *attr = (const char *)sqlite3_value_text(argv[3]);
575 const struct ldb_schema_attribute *a;
576 struct ldb_val valX;
577 struct ldb_val valY;
578 int ret;
580 switch (func[0]) {
581 /* greater */
582 case '>': /* >= */
583 a = ldb_schema_attribute_by_name(ldb, attr);
584 valX.data = (uint8_t *)cmp;
585 valX.length = strlen(cmp);
586 valY.data = (uint8_t *)val;
587 valY.length = strlen(val);
588 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
589 if (ret >= 0)
590 sqlite3_result_int(ctx, 1);
591 else
592 sqlite3_result_int(ctx, 0);
593 return;
595 /* lesser */
596 case '<': /* <= */
597 a = ldb_schema_attribute_by_name(ldb, attr);
598 valX.data = (uint8_t *)cmp;
599 valX.length = strlen(cmp);
600 valY.data = (uint8_t *)val;
601 valY.length = strlen(val);
602 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
603 if (ret <= 0)
604 sqlite3_result_int(ctx, 1);
605 else
606 sqlite3_result_int(ctx, 0);
607 return;
609 /* approx */
610 case '~':
611 /* TODO */
612 sqlite3_result_int(ctx, 0);
613 return;
615 /* bitops */
616 case ':':
617 /* TODO */
618 sqlite3_result_int(ctx, 0);
619 return;
621 default:
622 break;
625 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
626 return;
630 /* rename a record */
631 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
633 char *errmsg;
634 int ret;
636 /* execute */
637 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
638 if (ret != SQLITE_OK) {
639 if (errmsg) {
640 printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
641 free(errmsg);
643 return -1;
646 return 0;
649 /* return an eid as result */
650 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
652 long long *eid = (long long *)result;
654 if (col_num != 1) return SQLITE_ABORT;
655 if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
657 *eid = atoll(cols[0]);
658 return SQLITE_OK;
662 * add a single set of ldap message values to a ldb_message
664 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
666 struct ldb_context *ldb;
667 struct lsql_context *ac;
668 struct ldb_message *msg;
669 long long eid;
670 unsigned int i;
671 int ret;
673 ac = talloc_get_type(result, struct lsql_context);
674 ldb = ldb_module_get_ctx(ac->module);
676 /* eid, dn, attr_name, attr_value */
677 if (col_num != 4) return SQLITE_ABORT;
679 eid = atoll(cols[0]);
681 if (ac->ares) {
682 msg = ac->ares->message;
685 if (eid != ac->current_eid) { /* here begin a new entry */
687 /* call the async callback for the last entry
688 * except the first time */
689 if (ac->current_eid != 0) {
690 msg = ldb_msg_canonicalize(ldb, msg);
691 if (!msg) return SQLITE_ABORT;
693 ret = ldb_module_send_entry(ac->req, msg, NULL);
694 if (ret != LDB_SUCCESS) {
695 ac->callback_failed = true;
696 return SQLITE_ABORT;
700 /* start over */
701 ac->ares = talloc_zero(ac, struct ldb_reply);
702 if (!ac->ares) return SQLITE_ABORT;
704 msg = ldb_msg_new(ac->ares);
705 if (!msg) return SQLITE_ABORT;
707 ac->ares->type = LDB_REPLY_ENTRY;
708 ac->current_eid = eid;
711 if (msg->dn == NULL) {
712 msg->dn = ldb_dn_new(msg, ldb, cols[1]);
713 if (msg->dn == NULL)
714 return SQLITE_ABORT;
717 if (ac->attrs) {
718 int found = 0;
719 for (i = 0; ac->attrs[i]; i++) {
720 if (strcasecmp(cols[2], ac->attrs[i]) == 0) {
721 found = 1;
722 break;
725 if (!found) goto done;
728 if (ldb_msg_add_string(msg, cols[2], cols[3]) != 0) {
729 return SQLITE_ABORT;
732 done:
733 ac->ares->message = msg;
734 return SQLITE_OK;
739 * lsqlite3_get_eid()
740 * lsqlite3_get_eid_ndn()
742 * These functions are used for the very common case of retrieving an EID value
743 * given a (normalized) DN.
746 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
748 char *errmsg;
749 char *query;
750 long long eid = -1;
751 long long ret;
753 /* get object eid */
754 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
755 "FROM ldb_entry "
756 "WHERE norm_dn = '%q';", norm_dn);
757 if (query == NULL) return -1;
759 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
760 if (ret != SQLITE_OK) {
761 if (errmsg) {
762 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
763 free(errmsg);
765 return -1;
768 return eid;
771 static long long lsqlite3_get_eid(struct lsqlite3_private *lsqlite3,
772 struct ldb_dn *dn)
774 TALLOC_CTX *local_ctx;
775 long long eid = -1;
776 char *cdn;
778 /* ignore ltdb specials */
779 if (ldb_dn_is_special(dn)) {
780 return -1;
783 /* create a local ctx */
784 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
785 if (local_ctx == NULL) {
786 return -1;
789 cdn = ldb_dn_alloc_casefold(local_ctx, dn);
790 if (!cdn) goto done;
792 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
794 done:
795 talloc_free(local_ctx);
796 return eid;
800 * Interface functions referenced by lsqlite3_ops
803 /* search for matching records, by tree */
804 int lsql_search(struct lsql_context *ctx)
806 struct ldb_module *module = ctx->module;
807 struct ldb_request *req = ctx->req;
808 struct lsqlite3_private *lsqlite3;
809 struct ldb_context *ldb;
810 char *norm_basedn;
811 char *sqlfilter;
812 char *errmsg;
813 char *query = NULL;
814 int ret;
816 ldb = ldb_module_get_ctx(module);
817 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
818 struct lsqlite3_private);
820 if ((( ! ldb_dn_is_valid(req->op.search.base)) ||
821 ldb_dn_is_null(req->op.search.base)) &&
822 (req->op.search.scope == LDB_SCOPE_BASE ||
823 req->op.search.scope == LDB_SCOPE_ONELEVEL)) {
824 return LDB_ERR_OPERATIONS_ERROR;
827 if (req->op.search.base) {
828 norm_basedn = ldb_dn_alloc_casefold(ctx, req->op.search.base);
829 if (norm_basedn == NULL) {
830 return LDB_ERR_OPERATIONS_ERROR;
832 } else norm_basedn = talloc_strdup(ctx, "");
834 /* Convert filter into a series of SQL conditions (constraints) */
835 sqlfilter = parsetree_to_sql(module, ctx, req->op.search.tree);
837 switch(req->op.search.scope) {
838 case LDB_SCOPE_DEFAULT:
839 case LDB_SCOPE_SUBTREE:
840 if (*norm_basedn != '\0') {
841 query = lsqlite3_tprintf(ctx,
842 "SELECT entry.eid,\n"
843 " entry.dn,\n"
844 " av.attr_name,\n"
845 " av.attr_value\n"
846 " FROM ldb_entry AS entry\n"
848 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
849 " ON av.eid = entry.eid\n"
851 " WHERE entry.eid IN\n"
852 " (SELECT DISTINCT ldb_entry.eid\n"
853 " FROM ldb_entry\n"
854 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
855 " OR ldb_entry.norm_dn = '%q')\n"
856 " AND ldb_entry.eid IN\n"
857 " (%s)\n"
858 " )\n"
860 " ORDER BY entry.eid ASC;",
861 norm_basedn,
862 norm_basedn,
863 sqlfilter);
864 } else {
865 query = lsqlite3_tprintf(ctx,
866 "SELECT entry.eid,\n"
867 " entry.dn,\n"
868 " av.attr_name,\n"
869 " av.attr_value\n"
870 " FROM ldb_entry AS entry\n"
872 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
873 " ON av.eid = entry.eid\n"
875 " WHERE entry.eid IN\n"
876 " (SELECT DISTINCT ldb_entry.eid\n"
877 " FROM ldb_entry\n"
878 " WHERE ldb_entry.eid IN\n"
879 " (%s)\n"
880 " )\n"
882 " ORDER BY entry.eid ASC;",
883 sqlfilter);
886 break;
888 case LDB_SCOPE_BASE:
889 query = lsqlite3_tprintf(ctx,
890 "SELECT entry.eid,\n"
891 " entry.dn,\n"
892 " av.attr_name,\n"
893 " av.attr_value\n"
894 " FROM ldb_entry AS entry\n"
896 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
897 " ON av.eid = entry.eid\n"
899 " WHERE entry.eid IN\n"
900 " (SELECT DISTINCT ldb_entry.eid\n"
901 " FROM ldb_entry\n"
902 " WHERE ldb_entry.norm_dn = '%q'\n"
903 " AND ldb_entry.eid IN\n"
904 " (%s)\n"
905 " )\n"
907 " ORDER BY entry.eid ASC;",
908 norm_basedn,
909 sqlfilter);
910 break;
912 case LDB_SCOPE_ONELEVEL:
913 query = lsqlite3_tprintf(ctx,
914 "SELECT entry.eid,\n"
915 " entry.dn,\n"
916 " av.attr_name,\n"
917 " av.attr_value\n"
918 " FROM ldb_entry AS entry\n"
920 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
921 " ON av.eid = entry.eid\n"
923 " WHERE entry.eid IN\n"
924 " (SELECT DISTINCT ldb_entry.eid\n"
925 " FROM ldb_entry\n"
926 " WHERE norm_dn GLOB('*,%q')\n"
927 " AND NOT norm_dn GLOB('*,*,%q')\n"
928 " AND ldb_entry.eid IN\n(%s)\n"
929 " )\n"
931 " ORDER BY entry.eid ASC;",
932 norm_basedn,
933 norm_basedn,
934 sqlfilter);
935 break;
938 if (query == NULL) {
939 return LDB_ERR_OPERATIONS_ERROR;
942 /* * /
943 printf ("%s\n", query);
944 / * */
946 ctx->current_eid = 0;
947 ctx->attrs = req->op.search.attrs;
948 ctx->ares = NULL;
950 ldb_request_set_state(req, LDB_ASYNC_PENDING);
952 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, ctx, &errmsg);
953 if (ret != SQLITE_OK) {
954 if (errmsg) {
955 ldb_set_errstring(ldb, errmsg);
956 free(errmsg);
958 return LDB_ERR_OPERATIONS_ERROR;
961 /* complete the last message if any */
962 if (ctx->ares) {
963 ctx->ares->message = ldb_msg_canonicalize(ldb, ctx->ares->message);
964 if (ctx->ares->message == NULL) {
965 return LDB_ERR_OPERATIONS_ERROR;
968 ret = ldb_module_send_entry(req, ctx->ares->message, NULL);
969 if (ret != LDB_SUCCESS) {
970 return ret;
975 return LDB_SUCCESS;
978 /* add a record */
979 static int lsql_add(struct lsql_context *ctx)
981 struct ldb_module *module = ctx->module;
982 struct ldb_request *req = ctx->req;
983 struct lsqlite3_private *lsqlite3;
984 struct ldb_context *ldb;
985 struct ldb_message *msg = req->op.add.message;
986 long long eid;
987 char *dn, *ndn;
988 char *errmsg;
989 char *query;
990 unsigned int i;
991 int ret;
993 ldb = ldb_module_get_ctx(module);
994 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
995 struct lsqlite3_private);
997 /* See if this is an ltdb special */
998 if (ldb_dn_is_special(msg->dn)) {
1000 struct ldb_dn *c;
1001 c = ldb_dn_new(local_ctx, ldb, "@INDEXLIST");
1002 if (ldb_dn_compare(ldb, msg->dn, c) == 0) {
1003 #warning "should we handle indexes somehow ?"
1004 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1005 goto done;
1008 /* Others return an error */
1009 return LDB_ERR_UNWILLING_TO_PERFORM;
1012 /* create linearized and normalized dns */
1013 dn = ldb_dn_alloc_linearized(ctx, msg->dn);
1014 ndn = ldb_dn_alloc_casefold(ctx, msg->dn);
1015 if (dn == NULL || ndn == NULL) {
1016 return LDB_ERR_OPERATIONS_ERROR;
1019 query = lsqlite3_tprintf(ctx,
1020 /* Add new entry */
1021 "INSERT OR ABORT INTO ldb_entry "
1022 "('dn', 'norm_dn') "
1023 "VALUES ('%q', '%q');",
1024 dn, ndn);
1025 if (query == NULL) {
1026 return LDB_ERR_OPERATIONS_ERROR;
1029 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1030 if (ret != SQLITE_OK) {
1031 if (errmsg) {
1032 ldb_set_errstring(ldb, errmsg);
1033 free(errmsg);
1035 return LDB_ERR_OPERATIONS_ERROR;
1038 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, ctx, ndn);
1039 if (eid == -1) {
1040 return LDB_ERR_OPERATIONS_ERROR;
1043 for (i = 0; i < msg->num_elements; i++) {
1044 const struct ldb_message_element *el = &msg->elements[i];
1045 const struct ldb_schema_attribute *a;
1046 char *attr;
1047 unsigned int j;
1049 /* Get a case-folded copy of the attribute name */
1050 attr = ldb_attr_casefold(ctx, el->name);
1051 if (attr == NULL) {
1052 return LDB_ERR_OPERATIONS_ERROR;
1055 a = ldb_schema_attribute_by_name(ldb, el->name);
1057 if (el->num_value == 0) {
1058 ldb_asprintf_errstring(ldb, "attribute %s on %s specified, but with 0 values (illegal)",
1059 el->name, ldb_dn_get_linearized(msg->dn));
1060 return LDB_ERR_CONSTRAINT_VIOLATION;
1062 if (a && a->flags & LDB_ATTR_FLAG_SINGLE_VALUE) {
1063 if (el->num_values > 1) {
1064 ldb_asprintf_errstring(ldb, "SINGLE-VALUED attribute %s on %s specified more than once",
1065 el->name, ldb_dn_get_linearized(msg->dn));
1066 return LDB_ERR_CONSTRAINT_VIOLATION;
1070 /* For each value of the specified attribute name... */
1071 for (j = 0; j < el->num_values; j++) {
1072 struct ldb_val value;
1073 char *insert;
1075 /* Get a canonicalised copy of the data */
1076 a->syntax->canonicalise_fn(ldb, ctx, &(el->values[j]), &value);
1077 if (value.data == NULL) {
1078 return LDB_ERR_OPERATIONS_ERROR;
1081 insert = lsqlite3_tprintf(ctx,
1082 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1083 "('eid', 'attr_name', 'norm_attr_name',"
1084 " 'attr_value', 'norm_attr_value') "
1085 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1086 eid, el->name, attr,
1087 el->values[j].data, value.data);
1088 if (insert == NULL) {
1089 return LDB_ERR_OPERATIONS_ERROR;
1092 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1093 if (ret != SQLITE_OK) {
1094 if (errmsg) {
1095 ldb_set_errstring(ldb, errmsg);
1096 free(errmsg);
1098 return LDB_ERR_OPERATIONS_ERROR;
1103 return LDB_SUCCESS;
1106 /* modify a record */
1107 static int lsql_modify(struct lsql_context *ctx)
1109 struct ldb_module *module = ctx->module;
1110 struct ldb_request *req = ctx->req;
1111 struct lsqlite3_private *lsqlite3;
1112 struct ldb_context *ldb;
1113 struct ldb_message *msg = req->op.mod.message;
1114 long long eid;
1115 char *errmsg;
1116 unsigned int i;
1117 int ret;
1119 ldb = ldb_module_get_ctx(module);
1120 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1121 struct lsqlite3_private);
1123 /* See if this is an ltdb special */
1124 if (ldb_dn_is_special(msg->dn)) {
1125 /* Others return an error */
1126 return LDB_ERR_UNWILLING_TO_PERFORM;
1129 eid = lsqlite3_get_eid(lsqlite3, msg->dn);
1130 if (eid == -1) {
1131 return LDB_ERR_OPERATIONS_ERROR;
1134 for (i = 0; i < msg->num_elements; i++) {
1135 const struct ldb_message_element *el = &msg->elements[i];
1136 const struct ldb_schema_attribute *a;
1137 int flags = el->flags & LDB_FLAG_MOD_MASK;
1138 char *attr;
1139 char *mod;
1140 unsigned int j;
1142 if (ldb_attr_cmp(el->name, "distinguishedName") == 0) {
1143 ldb_asprintf_errstring(ldb, "it is not permitted to perform a modify on 'distinguishedName' (use rename instead): %s",
1144 ldb_dn_get_linearized(msg->dn));
1145 return LDB_ERR_CONSTRAINT_VIOLATION;
1148 /* Get a case-folded copy of the attribute name */
1149 attr = ldb_attr_casefold(ctx, el->name);
1150 if (attr == NULL) {
1151 return LDB_ERR_OPERATIONS_ERROR;
1154 a = ldb_schema_attribute_by_name(ldb, el->name);
1156 switch (flags) {
1158 case LDB_FLAG_MOD_REPLACE:
1160 if (a && a->flags & LDB_ATTR_FLAG_SINGLE_VALUE) {
1161 if (el->num_values > 1) {
1162 ldb_asprintf_errstring(ldb, "SINGLE-VALUE attribute %s on %s specified more than once",
1163 el->name, ldb_dn_get_linearized(msg->dn));
1164 return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
1168 for (j=0; j<el->num_values; j++) {
1169 if (ldb_msg_find_val(el, &el->values[j]) != &el->values[j]) {
1170 ldb_asprintf_errstring(ldb, "%s: value #%d provided more than once", el->name, j);
1171 return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
1175 /* remove all attributes before adding the replacements */
1176 mod = lsqlite3_tprintf(ctx,
1177 "DELETE FROM ldb_attribute_values "
1178 "WHERE eid = '%lld' "
1179 "AND norm_attr_name = '%q';",
1180 eid, attr);
1181 if (mod == NULL) {
1182 return LDB_ERR_OPERATIONS_ERROR;
1185 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1186 if (ret != SQLITE_OK) {
1187 if (errmsg) {
1188 ldb_set_errstring(ldb, errmsg);
1189 free(errmsg);
1191 return LDB_ERR_OPERATIONS_ERROR;
1194 /* MISSING break is INTENTIONAL */
1196 case LDB_FLAG_MOD_ADD:
1198 if (el->num_values == 0) {
1199 ldb_asprintf_errstring(ldb, "attribute %s on %s specified, but with 0 values (illigal)",
1200 el->name, ldb_dn_get_linearized(msg->dn));
1201 return LDB_ERR_CONSTRAINT_VIOLATION;
1204 if (a && a->flags & LDB_ATTR_FLAG_SINGLE_VALUE) {
1205 if (el->num_values > 1) {
1206 ldb_asprintf_errstring(ldb, "SINGLE-VALUE attribute %s on %s specified more than once",
1207 el->name, ldb_dn_get_linearized(msg->dn));
1208 return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
1212 #warning "We should throw an error if no value is provided!"
1213 /* For each value of the specified attribute name... */
1214 for (j = 0; j < el->num_values; j++) {
1215 struct ldb_val value;
1217 /* Get a canonicalised copy of the data */
1218 a->syntax->canonicalise_fn(ldb, ctx, &(el->values[j]), &value);
1219 if (value.data == NULL) {
1220 return LDB_ERR_OPERATIONS_ERROR;
1223 mod = lsqlite3_tprintf(ctx,
1224 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1225 "('eid', 'attr_name', 'norm_attr_name',"
1226 " 'attr_value', 'norm_attr_value') "
1227 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1228 eid, el->name, attr,
1229 el->values[j].data, value.data);
1231 if (mod == NULL) {
1232 return LDB_ERR_OPERATIONS_ERROR;
1235 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1236 if (ret != SQLITE_OK) {
1237 if (errmsg) {
1238 ldb_set_errstring(ldb, errmsg);
1239 free(errmsg);
1241 return LDB_ERR_OPERATIONS_ERROR;
1245 break;
1247 case LDB_FLAG_MOD_DELETE:
1248 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1249 if (el->num_values == 0) {
1250 mod = lsqlite3_tprintf(ctx,
1251 "DELETE FROM ldb_attribute_values "
1252 "WHERE eid = '%lld' "
1253 "AND norm_attr_name = '%q';",
1254 eid, attr);
1255 if (mod == NULL) {
1256 return LDB_ERR_OPERATIONS_ERROR;
1259 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1260 if (ret != SQLITE_OK) {
1261 if (errmsg) {
1262 ldb_set_errstring(ldb, errmsg);
1263 free(errmsg);
1265 return LDB_ERR_OPERATIONS_ERROR;
1269 /* For each value of the specified attribute name... */
1270 for (j = 0; j < el->num_values; j++) {
1271 struct ldb_val value;
1273 /* Get a canonicalised copy of the data */
1274 a->syntax->canonicalise_fn(ldb, ctx, &(el->values[j]), &value);
1275 if (value.data == NULL) {
1276 return LDB_ERR_OPERATIONS_ERROR;
1279 mod = lsqlite3_tprintf(ctx,
1280 "DELETE FROM ldb_attribute_values "
1281 "WHERE eid = '%lld' "
1282 "AND norm_attr_name = '%q' "
1283 "AND norm_attr_value = '%q';",
1284 eid, attr, value.data);
1286 if (mod == NULL) {
1287 return LDB_ERR_OPERATIONS_ERROR;
1290 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1291 if (ret != SQLITE_OK) {
1292 if (errmsg) {
1293 ldb_set_errstring(ldb, errmsg);
1294 free(errmsg);
1296 return LDB_ERR_OPERATIONS_ERROR;
1300 break;
1304 return LDB_SUCCESS;
1307 /* delete a record */
1308 static int lsql_delete(struct lsql_context *ctx)
1310 struct ldb_module *module = ctx->module;
1311 struct ldb_request *req = ctx->req;
1312 struct lsqlite3_private *lsqlite3;
1313 struct ldb_context *ldb;
1314 long long eid;
1315 char *errmsg;
1316 char *query;
1317 int ret;
1319 ldb = ldb_module_get_ctx(module);
1320 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1321 struct lsqlite3_private);
1323 eid = lsqlite3_get_eid(lsqlite3, req->op.del.dn);
1324 if (eid == -1) {
1325 return LDB_ERR_OPERATIONS_ERROR;
1328 query = lsqlite3_tprintf(ctx,
1329 /* Delete entry */
1330 "DELETE FROM ldb_entry WHERE eid = %lld; "
1331 /* Delete attributes */
1332 "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1333 eid, eid);
1334 if (query == NULL) {
1335 return LDB_ERR_OPERATIONS_ERROR;
1338 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1339 if (ret != SQLITE_OK) {
1340 if (errmsg) {
1341 ldb_set_errstring(ldb, errmsg);
1342 free(errmsg);
1344 return LDB_ERR_OPERATIONS_ERROR;
1347 return LDB_SUCCESS;
1350 /* rename a record */
1351 static int lsql_rename(struct lsql_context *ctx)
1353 struct ldb_module *module = ctx->module;
1354 struct ldb_request *req = ctx->req;
1355 struct lsqlite3_private *lsqlite3;
1356 struct ldb_context *ldb;
1357 char *new_dn, *new_cdn, *old_cdn;
1358 char *errmsg;
1359 char *query;
1360 int ret;
1362 ldb = ldb_module_get_ctx(module);
1363 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1364 struct lsqlite3_private);
1366 /* create linearized and normalized dns */
1367 old_cdn = ldb_dn_alloc_casefold(ctx, req->op.rename.olddn);
1368 new_cdn = ldb_dn_alloc_casefold(ctx, req->op.rename.newdn);
1369 new_dn = ldb_dn_alloc_linearized(ctx, req->op.rename.newdn);
1370 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1371 return LDB_ERR_OPERATIONS_ERROR;
1374 /* build the SQL query */
1375 query = lsqlite3_tprintf(ctx,
1376 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1377 "WHERE norm_dn = '%q';",
1378 new_dn, new_cdn, old_cdn);
1379 if (query == NULL) {
1380 return LDB_ERR_OPERATIONS_ERROR;
1383 /* execute */
1384 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1385 if (ret != SQLITE_OK) {
1386 if (errmsg) {
1387 ldb_set_errstring(ldb, errmsg);
1388 free(errmsg);
1390 return LDB_ERR_OPERATIONS_ERROR;
1393 return LDB_SUCCESS;
1396 static int lsql_start_trans(struct ldb_module * module)
1398 int ret;
1399 char *errmsg;
1400 struct lsqlite3_private *lsqlite3;
1402 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1403 struct lsqlite3_private);
1405 if (lsqlite3->trans_count == 0) {
1406 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1407 if (ret != SQLITE_OK) {
1408 if (errmsg) {
1409 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1410 free(errmsg);
1412 return -1;
1416 lsqlite3->trans_count++;
1418 return 0;
1421 static int lsql_end_trans(struct ldb_module *module)
1423 int ret;
1424 char *errmsg;
1425 struct lsqlite3_private *lsqlite3;
1427 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1428 struct lsqlite3_private);
1430 if (lsqlite3->trans_count > 0) {
1431 lsqlite3->trans_count--;
1432 } else return -1;
1434 if (lsqlite3->trans_count == 0) {
1435 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1436 if (ret != SQLITE_OK) {
1437 if (errmsg) {
1438 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1439 free(errmsg);
1441 return -1;
1445 return 0;
1448 static int lsql_del_trans(struct ldb_module *module)
1450 struct lsqlite3_private *lsqlite3;
1452 lsqlite3 = talloc_get_type(ldb_module_get_private(module),
1453 struct lsqlite3_private);
1455 if (lsqlite3->trans_count > 0) {
1456 lsqlite3->trans_count--;
1457 } else return -1;
1459 if (lsqlite3->trans_count == 0) {
1460 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1463 return -1;
1466 static int destructor(struct lsqlite3_private *lsqlite3)
1468 if (lsqlite3->sqlite) {
1469 sqlite3_close(lsqlite3->sqlite);
1471 return 0;
1474 static void lsql_request_done(struct lsql_context *ctx, int error)
1476 struct ldb_context *ldb;
1477 struct ldb_request *req;
1478 struct ldb_reply *ares;
1480 ldb = ldb_module_get_ctx(ctx->module);
1481 req = ctx->req;
1483 /* if we already returned an error just return */
1484 if (ldb_request_get_status(req) != LDB_SUCCESS) {
1485 return;
1488 ares = talloc_zero(req, struct ldb_reply);
1489 if (!ares) {
1490 ldb_oom(ldb);
1491 req->callback(req, NULL);
1492 return;
1494 ares->type = LDB_REPLY_DONE;
1495 ares->error = error;
1497 req->callback(req, ares);
1500 static void lsql_timeout(struct tevent_context *ev,
1501 struct tevent_timer *te,
1502 struct timeval t,
1503 void *private_data)
1505 struct lsql_context *ctx;
1506 ctx = talloc_get_type(private_data, struct lsql_context);
1508 lsql_request_done(ctx, LDB_ERR_TIME_LIMIT_EXCEEDED);
1511 static void lsql_callback(struct tevent_context *ev,
1512 struct tevent_timer *te,
1513 struct timeval t,
1514 void *private_data)
1516 struct lsql_context *ctx;
1517 int ret;
1519 ctx = talloc_get_type(private_data, struct lsql_context);
1521 switch (ctx->req->operation) {
1522 case LDB_SEARCH:
1523 ret = lsql_search(ctx);
1524 break;
1525 case LDB_ADD:
1526 ret = lsql_add(ctx);
1527 break;
1528 case LDB_MODIFY:
1529 ret = lsql_modify(ctx);
1530 break;
1531 case LDB_DELETE:
1532 ret = lsql_delete(ctx);
1533 break;
1534 case LDB_RENAME:
1535 ret = lsql_rename(ctx);
1536 break;
1537 /* TODO:
1538 case LDB_EXTENDED:
1539 ret = lsql_extended(ctx);
1540 break;
1542 default:
1543 /* no other op supported */
1544 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1547 if (!ctx->callback_failed) {
1548 /* Once we are done, we do not need timeout events */
1549 talloc_free(ctx->timeout_event);
1550 lsql_request_done(ctx, ret);
1554 static int lsql_handle_request(struct ldb_module *module, struct ldb_request *req)
1556 struct ldb_context *ldb;
1557 struct tevent_context *ev;
1558 struct lsql_context *ac;
1559 struct tevent_timer *te;
1560 struct timeval tv;
1562 if (check_critical_controls(req->controls)) {
1563 return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
1566 if (req->starttime == 0 || req->timeout == 0) {
1567 ldb_set_errstring(ldb, "Invalid timeout settings");
1568 return LDB_ERR_TIME_LIMIT_EXCEEDED;
1571 ldb = ldb_module_get_ctx(module);
1572 ev = ldb_get_event_context(ldb);
1574 ac = talloc_zero(req, struct lsql_context);
1575 if (ac == NULL) {
1576 ldb_set_errstring(ldb, "Out of Memory");
1577 return LDB_ERR_OPERATIONS_ERROR;
1580 ac->module = module;
1581 ac->req = req;
1583 tv.tv_sec = 0;
1584 tv.tv_usec = 0;
1585 te = tevent_add_timer(ev, ac, tv, lsql_callback, ac);
1586 if (NULL == te) {
1587 return LDB_ERR_OPERATIONS_ERROR;
1590 tv.tv_sec = req->starttime + req->timeout;
1591 ac->timeout_event = tevent_add_timer(ev, ac, tv, lsql_timeout, ac);
1592 if (NULL == ac->timeout_event) {
1593 return LDB_ERR_OPERATIONS_ERROR;
1596 return LDB_SUCCESS;
1600 * Table of operations for the sqlite3 backend
1602 static const struct ldb_module_ops lsqlite3_ops = {
1603 .name = "sqlite",
1604 .search = lsql_handle_request,
1605 .add = lsql_handle_request,
1606 .modify = lsql_handle_request,
1607 .del = lsql_handle_request,
1608 .rename = lsql_handle_request,
1609 .extended = lsql_handle_request,
1610 .start_transaction = lsql_start_trans,
1611 .end_transaction = lsql_end_trans,
1612 .del_transaction = lsql_del_trans,
1616 * Static functions
1619 static int initialize(struct lsqlite3_private *lsqlite3,
1620 struct ldb_context *ldb, const char *url, int flags)
1622 TALLOC_CTX *local_ctx;
1623 long long queryInt;
1624 int rollback = 0;
1625 char *errmsg;
1626 char *schema;
1627 int ret;
1629 /* create a local ctx */
1630 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1631 if (local_ctx == NULL) {
1632 return -1;
1635 schema = lsqlite3_tprintf(local_ctx,
1638 "CREATE TABLE ldb_info AS "
1639 " SELECT 'LDB' AS database_type,"
1640 " '1.0' AS version;"
1643 * The entry table holds the information about an entry.
1644 * This table is used to obtain the EID of the entry and to
1645 * support scope=one and scope=base. The parent and child
1646 * table is included in the entry table since all the other
1647 * attributes are dependent on EID.
1649 "CREATE TABLE ldb_entry "
1651 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1652 " dn TEXT UNIQUE NOT NULL,"
1653 " norm_dn TEXT UNIQUE NOT NULL"
1654 ");"
1657 "CREATE TABLE ldb_object_classes"
1659 " class_name TEXT PRIMARY KEY,"
1660 " parent_class_name TEXT,"
1661 " tree_key TEXT UNIQUE,"
1662 " max_child_num INTEGER DEFAULT 0"
1663 ");"
1666 * We keep a full listing of attribute/value pairs here
1668 "CREATE TABLE ldb_attribute_values"
1670 " eid INTEGER REFERENCES ldb_entry,"
1671 " attr_name TEXT,"
1672 " norm_attr_name TEXT,"
1673 " attr_value TEXT,"
1674 " norm_attr_value TEXT "
1675 ");"
1679 * Indexes
1681 "CREATE INDEX ldb_attribute_values_eid_idx "
1682 " ON ldb_attribute_values (eid);"
1684 "CREATE INDEX ldb_attribute_values_name_value_idx "
1685 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1690 * Triggers
1693 "CREATE TRIGGER ldb_object_classes_insert_tr"
1694 " AFTER INSERT"
1695 " ON ldb_object_classes"
1696 " FOR EACH ROW"
1697 " BEGIN"
1698 " UPDATE ldb_object_classes"
1699 " SET tree_key = COALESCE(tree_key, "
1700 " ("
1701 " SELECT tree_key || "
1702 " (SELECT base160(max_child_num + 1)"
1703 " FROM ldb_object_classes"
1704 " WHERE class_name = "
1705 " new.parent_class_name)"
1706 " FROM ldb_object_classes "
1707 " WHERE class_name = new.parent_class_name "
1708 " ));"
1709 " UPDATE ldb_object_classes "
1710 " SET max_child_num = max_child_num + 1"
1711 " WHERE class_name = new.parent_class_name;"
1712 " END;"
1715 * Table initialization
1718 "INSERT INTO ldb_object_classes "
1719 " (class_name, tree_key) "
1720 " VALUES "
1721 " ('TOP', '0001');");
1723 /* Skip protocol indicator of url */
1724 if (strncmp(url, "sqlite3://", 10) != 0) {
1725 return SQLITE_MISUSE;
1728 /* Update pointer to just after the protocol indicator */
1729 url += 10;
1731 /* Try to open the (possibly empty/non-existent) database */
1732 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1733 return ret;
1736 /* In case this is a new database, enable auto_vacuum */
1737 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1738 if (ret != SQLITE_OK) {
1739 if (errmsg) {
1740 printf("lsqlite3 initializaion error: %s\n", errmsg);
1741 free(errmsg);
1743 goto failed;
1746 if (flags & LDB_FLG_NOSYNC) {
1747 /* DANGEROUS */
1748 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1749 if (ret != SQLITE_OK) {
1750 if (errmsg) {
1751 printf("lsqlite3 initializaion error: %s\n", errmsg);
1752 free(errmsg);
1754 goto failed;
1758 /* */
1760 /* Establish a busy timeout of 30 seconds */
1761 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1762 30000)) != SQLITE_OK) {
1763 return ret;
1766 /* Create a function, callable from sql, to increment a tree_key */
1767 if ((ret =
1768 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1769 "base160_next", /* function name */
1770 1, /* number of args */
1771 SQLITE_ANY, /* preferred text type */
1772 NULL, /* user data */
1773 base160next_sql, /* called func */
1774 NULL, /* step func */
1775 NULL /* final func */
1776 )) != SQLITE_OK) {
1777 return ret;
1780 /* Create a function, callable from sql, to convert int to base160 */
1781 if ((ret =
1782 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1783 "base160", /* function name */
1784 1, /* number of args */
1785 SQLITE_ANY, /* preferred text type */
1786 NULL, /* user data */
1787 base160_sql, /* called func */
1788 NULL, /* step func */
1789 NULL /* final func */
1790 )) != SQLITE_OK) {
1791 return ret;
1794 /* Create a function, callable from sql, to perform various comparisons */
1795 if ((ret =
1796 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1797 "ldap_compare", /* function name */
1798 4, /* number of args */
1799 SQLITE_ANY, /* preferred text type */
1800 ldb , /* user data */
1801 lsqlite3_compare, /* called func */
1802 NULL, /* step func */
1803 NULL /* final func */
1804 )) != SQLITE_OK) {
1805 return ret;
1808 /* Begin a transaction */
1809 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1810 if (ret != SQLITE_OK) {
1811 if (errmsg) {
1812 printf("lsqlite3: initialization error: %s\n", errmsg);
1813 free(errmsg);
1815 goto failed;
1817 rollback = 1;
1819 /* Determine if this is a new database. No tables means it is. */
1820 if (query_int(lsqlite3,
1821 &queryInt,
1822 "SELECT COUNT(*)\n"
1823 " FROM sqlite_master\n"
1824 " WHERE type = 'table';") != 0) {
1825 goto failed;
1828 if (queryInt == 0) {
1830 * Create the database schema
1832 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1833 if (ret != SQLITE_OK) {
1834 if (errmsg) {
1835 printf("lsqlite3 initializaion error: %s\n", errmsg);
1836 free(errmsg);
1838 goto failed;
1840 } else {
1842 * Ensure that the database we opened is one of ours
1844 if (query_int(lsqlite3,
1845 &queryInt,
1846 "SELECT "
1847 " (SELECT COUNT(*) = 2"
1848 " FROM sqlite_master "
1849 " WHERE type = 'table' "
1850 " AND name IN "
1851 " ("
1852 " 'ldb_entry', "
1853 " 'ldb_object_classes' "
1854 " ) "
1855 " ) "
1856 " AND "
1857 " (SELECT 1 "
1858 " FROM ldb_info "
1859 " WHERE database_type = 'LDB' "
1860 " AND version = '1.0'"
1861 " );") != 0 ||
1862 queryInt != 1) {
1864 /* It's not one that we created. See ya! */
1865 goto failed;
1869 /* Commit the transaction */
1870 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1871 if (ret != SQLITE_OK) {
1872 if (errmsg) {
1873 printf("lsqlite3: iniialization error: %s\n", errmsg);
1874 free(errmsg);
1876 goto failed;
1879 return SQLITE_OK;
1881 failed:
1882 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1883 sqlite3_close(lsqlite3->sqlite);
1884 return -1;
1888 * connect to the database
1890 static int lsqlite3_connect(struct ldb_context *ldb,
1891 const char *url,
1892 unsigned int flags,
1893 const char *options[],
1894 struct ldb_module **_module)
1896 struct ldb_module *module;
1897 struct lsqlite3_private *lsqlite3;
1898 unsigned int i;
1899 int ret;
1901 module = ldb_module_new(ldb, ldb, "ldb_sqlite3 backend", &lsqlite3_ops);
1902 if (!module) return LDB_ERR_OPERATIONS_ERROR;
1904 lsqlite3 = talloc(module, struct lsqlite3_private);
1905 if (!lsqlite3) {
1906 goto failed;
1909 lsqlite3->sqlite = NULL;
1910 lsqlite3->options = NULL;
1911 lsqlite3->trans_count = 0;
1913 ret = initialize(lsqlite3, ldb, url, flags);
1914 if (ret != SQLITE_OK) {
1915 goto failed;
1918 talloc_set_destructor(lsqlite3, destructor);
1920 ldb_module_set_private(module, lsqlite3);
1922 if (options) {
1924 * take a copy of the options array, so we don't have to rely
1925 * on the caller keeping it around (it might be dynamic)
1927 for (i=0;options[i];i++) ;
1929 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1930 if (!lsqlite3->options) {
1931 goto failed;
1934 for (i=0;options[i];i++) {
1936 lsqlite3->options[i+1] = NULL;
1937 lsqlite3->options[i] =
1938 talloc_strdup(lsqlite3->options, options[i]);
1939 if (!lsqlite3->options[i]) {
1940 goto failed;
1945 *_module = module;
1946 return LDB_SUCCESS;
1948 failed:
1949 if (lsqlite3 && lsqlite3->sqlite != NULL) {
1950 (void) sqlite3_close(lsqlite3->sqlite);
1952 talloc_free(lsqlite3);
1953 return LDB_ERR_OPERATIONS_ERROR;
1956 const struct ldb_backend_ops ldb_sqlite3_backend_ops = {
1957 .name = "sqlite3",
1958 .connect_fn = lsqlite3_connect