4 Copyright (C) Derrell Lipman 2005
5 Copyright (C) Simo Sorce 2005
7 ** NOTE! The following LGPL license applies to the ldb
8 ** library. This does NOT imply that all of Samba is released
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 2 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, write to the Free Software
23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 * Component: ldb sqlite3 backend
31 * Description: core files for SQLITE3 backend
33 * Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
37 #include "ldb/include/includes.h"
39 #include "ldb/ldb_sqlite3/ldb_sqlite3.h"
42 * Macros used throughout
47 # define TRUE (! FALSE)
50 #define RESULT_ATTR_TABLE "temp_result_attrs"
52 //#define TEMPTAB /* for testing, create non-temporary table */
53 #define TEMPTAB "TEMPORARY"
58 sqlite3_stmt * stmtGetEID = NULL;
60 static char *lsqlite3_tprintf(TALLOC_CTX *mem_ctx, const char *fmt, ...)
66 str = sqlite3_vmprintf(fmt, ap);
69 if (str == NULL) return NULL;
71 ret = talloc_strdup(mem_ctx, str);
81 static unsigned char base160tab[161] = {
82 48 ,49 ,50 ,51 ,52 ,53 ,54 ,55 ,56 ,57 , /* 0-9 */
83 58 ,59 ,65 ,66 ,67 ,68 ,69 ,70 ,71 ,72 , /* : ; A-H */
84 73 ,74 ,75 ,76 ,77 ,78 ,79 ,80 ,81 ,82 , /* I-R */
85 83 ,84 ,85 ,86 ,87 ,88 ,89 ,90 ,97 ,98 , /* S-Z , a-b */
86 99 ,100,101,102,103,104,105,106,107,108, /* c-l */
87 109,110,111,112,113,114,115,116,117,118, /* m-v */
88 119,120,121,122,160,161,162,163,164,165, /* w-z, latin1 */
89 166,167,168,169,170,171,172,173,174,175, /* latin1 */
90 176,177,178,179,180,181,182,183,184,185, /* latin1 */
91 186,187,188,189,190,191,192,193,194,195, /* latin1 */
92 196,197,198,199,200,201,202,203,204,205, /* latin1 */
93 206,207,208,209,210,211,212,213,214,215, /* latin1 */
94 216,217,218,219,220,221,222,223,224,225, /* latin1 */
95 226,227,228,229,230,231,232,233,234,235, /* latin1 */
96 236,237,238,239,240,241,242,243,244,245, /* latin1 */
97 246,247,248,249,250,251,252,253,254,255, /* latin1 */
105 * Convert an unsigned long integer into a base160 representation of the
110 * value to be converted
113 * character array, 5 bytes long, into which the base160 representation
114 * will be placed. The result will be a four-digit representation of the
115 * number (with leading zeros prepended as necessary), and null
122 base160_sql(sqlite3_context * hContext,
124 sqlite3_value ** argv)
130 val = sqlite3_value_int64(argv[0]);
132 for (i = 3; i >= 0; i--) {
134 result[i] = base160tab[val % 160];
140 sqlite3_result_text(hContext, result, -1, SQLITE_TRANSIENT);
147 * This function enhances sqlite by adding a "base160_next()" function which is
148 * accessible via queries.
150 * Retrieve the next-greater number in the base160 sequence for the terminal
151 * tree node (the last four digits). Only one tree level (four digits) is
155 * A character string: either an empty string (in which case no operation is
156 * performed), or a string of base160 digits with a length of a multiple of
160 * Upon return, the trailing four digits (one tree level) will have been
164 base160next_sql(sqlite3_context * hContext,
166 sqlite3_value ** argv)
170 unsigned char * pTab;
171 unsigned char * pBase160 =
172 strdup(sqlite3_value_text(argv[0]));
173 unsigned char * pStart = pBase160;
176 * We need a minimum of four digits, and we will always get a multiple
179 if (pBase160 != NULL &&
180 (len = strlen(pBase160)) >= 4 &&
183 if (pBase160 == NULL) {
185 sqlite3_result_null(hContext);
189 pBase160 += strlen(pBase160) - 1;
191 /* We only carry through four digits: one level in the tree */
192 for (i = 0; i < 4; i++) {
194 /* What base160 value does this digit have? */
195 pTab = strchr(base160tab, *pBase160);
197 /* Is there a carry? */
198 if (pTab < base160tab + sizeof(base160tab) - 1) {
201 * Nope. Just increment this value and we're
209 * There's a carry. This value gets
210 * base160tab[0], we decrement the buffer
211 * pointer to get the next higher-order digit,
212 * and continue in the loop.
214 *pBase160-- = base160tab[0];
218 sqlite3_result_text(hContext,
223 sqlite3_result_value(hContext, argv[0]);
224 if (pBase160 != NULL) {
230 static char *parsetree_to_sql(struct ldb_module *module,
232 const struct ldb_parse_tree *t)
234 const struct ldb_attrib_handler *h;
235 struct ldb_val value, subval;
236 char *wild_card_string;
243 switch(t->operation) {
246 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
247 if (tmp == NULL) return NULL;
249 for (i = 1; i < t->u.list.num_elements; i++) {
251 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
252 if (child == NULL) return NULL;
254 tmp = talloc_asprintf_append(tmp, " INTERSECT %s ", child);
255 if (tmp == NULL) return NULL;
258 ret = talloc_asprintf(mem_ctx, "SELECT * FROM ( %s )\n", tmp);
264 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
265 if (tmp == NULL) return NULL;
267 for (i = 1; i < t->u.list.num_elements; i++) {
269 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
270 if (child == NULL) return NULL;
272 tmp = talloc_asprintf_append(tmp, " UNION %s ", child);
273 if (tmp == NULL) return NULL;
276 return talloc_asprintf(mem_ctx, "SELECT * FROM ( %s ) ", tmp);
280 child = parsetree_to_sql(module, mem_ctx, t->u.isnot.child);
281 if (child == NULL) return NULL;
283 return talloc_asprintf(mem_ctx,
284 "SELECT eid FROM ldb_entry "
285 "WHERE eid NOT IN ( %s ) ", child);
287 case LDB_OP_EQUALITY:
289 * For simple searches, we want to retrieve the list of EIDs that
290 * match the criteria.
292 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
293 if (attr == NULL) return NULL;
294 h = ldb_attrib_handler(module->ldb, attr);
296 /* Get a canonicalised copy of the data */
297 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
298 if (value.data == NULL) {
302 if (strcasecmp(t->u.equality.attr, "objectclass") == 0) {
304 * For object classes, we want to search for all objectclasses
305 * that are subclasses as well.
307 return lsqlite3_tprintf(mem_ctx,
308 "SELECT eid FROM ldb_attribute_values\n"
309 "WHERE norm_attr_name = 'OBJECTCLASS' "
310 "AND norm_attr_value IN\n"
311 " (SELECT class_name FROM ldb_object_classes\n"
312 " WHERE tree_key GLOB\n"
313 " (SELECT tree_key FROM ldb_object_classes\n"
314 " WHERE class_name = '%q'\n"
318 } else if (strcasecmp(t->u.equality.attr, "dn") == 0) {
319 /* DN query is a special ldb case */
320 char *cdn = ldb_dn_linearize_casefold(module->ldb,
321 ldb_dn_explode(module->ldb,
324 return lsqlite3_tprintf(mem_ctx,
325 "SELECT eid FROM ldb_entry "
326 "WHERE norm_dn = '%q'", cdn);
329 /* A normal query. */
330 return lsqlite3_tprintf(mem_ctx,
331 "SELECT eid FROM ldb_attribute_values "
332 "WHERE norm_attr_name = '%q' "
333 "AND norm_attr_value = '%q'",
339 case LDB_OP_SUBSTRING:
341 wild_card_string = talloc_strdup(mem_ctx,
342 (t->u.substring.start_with_wildcard)?"*":"");
343 if (wild_card_string == NULL) return NULL;
345 for (i = 0; t->u.substring.chunks[i]; i++) {
346 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
347 t->u.substring.chunks[i]->data);
348 if (wild_card_string == NULL) return NULL;
351 if ( ! t->u.substring.end_with_wildcard ) {
352 /* remove last wildcard */
353 wild_card_string[strlen(wild_card_string) - 1] = '\0';
356 attr = ldb_casefold(mem_ctx, t->u.substring.attr);
357 if (attr == NULL) return NULL;
358 h = ldb_attrib_handler(module->ldb, attr);
360 subval.data = wild_card_string;
361 subval.length = strlen(wild_card_string) + 1;
363 /* Get a canonicalised copy of the data */
364 h->canonicalise_fn(module->ldb, mem_ctx, &(subval), &value);
365 if (value.data == NULL) {
369 return lsqlite3_tprintf(mem_ctx,
370 "SELECT eid FROM ldb_attribute_values "
371 "WHERE norm_attr_name = '%q' "
372 "AND norm_attr_value GLOB '%q'",
377 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
378 if (attr == NULL) return NULL;
379 h = ldb_attrib_handler(module->ldb, attr);
381 /* Get a canonicalised copy of the data */
382 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
383 if (value.data == NULL) {
387 return lsqlite3_tprintf(mem_ctx,
388 "SELECT eid FROM ldb_attribute_values "
389 "WHERE norm_attr_name = '%q' "
390 "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
396 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
397 if (attr == NULL) return NULL;
398 h = ldb_attrib_handler(module->ldb, attr);
400 /* Get a canonicalised copy of the data */
401 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
402 if (value.data == NULL) {
406 return lsqlite3_tprintf(mem_ctx,
407 "SELECT eid FROM ldb_attribute_values "
408 "WHERE norm_attr_name = '%q' "
409 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
415 if (strcasecmp(t->u.present.attr, "dn") == 0) {
416 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
419 attr = ldb_casefold(mem_ctx, t->u.present.attr);
420 if (attr == NULL) return NULL;
422 return lsqlite3_tprintf(mem_ctx,
423 "SELECT eid FROM ldb_attribute_values "
424 "WHERE norm_attr_name = '%q' ",
428 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
429 if (attr == NULL) return NULL;
430 h = ldb_attrib_handler(module->ldb, attr);
432 /* Get a canonicalised copy of the data */
433 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
434 if (value.data == NULL) {
438 return lsqlite3_tprintf(mem_ctx,
439 "SELECT eid FROM ldb_attribute_values "
440 "WHERE norm_attr_name = '%q' "
441 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
446 case LDB_OP_EXTENDED:
447 #warning "work out how to handle bitops"
454 /* should never occur */
462 * This function is used for the common case of queries that return a single
465 * NOTE: If more than one value is returned by the query, all but the first
466 * one will be ignored.
469 query_int(const struct lsqlite3_private * lsqlite3,
477 sqlite3_stmt * pStmt;
480 /* Begin access to variable argument list */
481 va_start(args, pSql);
483 /* Format the query */
484 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
489 * Prepare and execute the SQL statement. Loop allows retrying on
490 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
491 * requiring retrying the operation.
493 for (bLoop = TRUE; bLoop; ) {
495 /* Compile the SQL statement into sqlite virtual machine */
496 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
500 NULL)) == SQLITE_SCHEMA) {
501 if (stmtGetEID != NULL) {
502 sqlite3_finalize(stmtGetEID);
506 } else if (ret != SQLITE_OK) {
510 /* One row expected */
511 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
512 if (stmtGetEID != NULL) {
513 sqlite3_finalize(stmtGetEID);
516 (void) sqlite3_finalize(pStmt);
518 } else if (ret != SQLITE_ROW) {
519 (void) sqlite3_finalize(pStmt);
523 /* Get the value to be returned */
524 *pRet = sqlite3_column_int64(pStmt, 0);
526 /* Free the virtual machine */
527 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
528 if (stmtGetEID != NULL) {
529 sqlite3_finalize(stmtGetEID);
533 } else if (ret != SQLITE_OK) {
534 (void) sqlite3_finalize(pStmt);
539 * Normal condition is only one time through loop. Loop is
540 * rerun in error conditions, via "continue", above.
545 /* All done with variable argument list */
549 /* Free the memory we allocated for our query string */
556 * This is a bad hack to support ldap style comparisons whithin sqlite.
557 * val is the attribute in the row currently under test
558 * func is the desired test "<=" ">=" "~" ":"
559 * cmp is the value to compare against (eg: "test")
560 * attr is the attribute name the value of which we want to test
563 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
564 sqlite3_value **argv)
566 struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
567 const unsigned char *val = sqlite3_value_text(argv[0]);
568 const unsigned char *func = sqlite3_value_text(argv[1]);
569 const unsigned char *cmp = sqlite3_value_text(argv[2]);
570 const unsigned char *attr = sqlite3_value_text(argv[3]);
571 const struct ldb_attrib_handler *h;
579 h = ldb_attrib_handler(ldb, attr);
581 valX.length = strlen(cmp);
583 valY.length = strlen(val);
584 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
586 sqlite3_result_int(ctx, 1);
588 sqlite3_result_int(ctx, 0);
593 h = ldb_attrib_handler(ldb, attr);
595 valX.length = strlen(cmp);
597 valY.length = strlen(val);
598 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
600 sqlite3_result_int(ctx, 1);
602 sqlite3_result_int(ctx, 0);
608 sqlite3_result_int(ctx, 0);
614 sqlite3_result_int(ctx, 0);
621 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
626 /* rename a record */
627 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
633 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
634 if (ret != SQLITE_OK) {
636 printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
645 /* return an eid as result */
646 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
648 long long *eid = (long long *)result;
650 if (col_num != 1) return SQLITE_ABORT;
651 if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
653 *eid = atoll(cols[0]);
657 struct lsqlite3_msgs {
659 struct ldb_message **msgs;
660 long long current_eid;
661 const char * const * attrs;
666 * add a single set of ldap message values to a ldb_message
669 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
671 struct lsqlite3_msgs *msgs = (struct lsqlite3_msgs *)result;
672 struct ldb_message *msg;
676 /* eid, dn, attr_name, attr_value */
677 if (col_num != 4) return SQLITE_ABORT;
679 eid = atoll(cols[0]);
681 if (eid != msgs->current_eid) {
682 msgs->msgs = talloc_realloc(msgs->mem_ctx,
684 struct ldb_message *,
686 if (msgs->msgs == NULL) return SQLITE_ABORT;
688 msgs->msgs[msgs->count] = talloc(msgs->msgs, struct ldb_message);
689 if (msgs->msgs[msgs->count] == NULL) return SQLITE_ABORT;
691 msgs->msgs[msgs->count]->dn = NULL;
692 msgs->msgs[msgs->count]->num_elements = 0;
693 msgs->msgs[msgs->count]->elements = NULL;
694 msgs->msgs[msgs->count]->private_data = NULL;
697 msgs->current_eid = eid;
700 msg = msgs->msgs[msgs->count -1];
702 if (msg->dn == NULL) {
703 msg->dn = ldb_dn_explode(msg, cols[1]);
704 if (msg->dn == NULL) return SQLITE_ABORT;
709 for (i = 0; msgs->attrs[i]; i++) {
710 if (strcasecmp(cols[2], msgs->attrs[i]) == 0) {
715 if (!found) return 0;
718 msg->elements = talloc_realloc(msg,
720 struct ldb_message_element,
721 msg->num_elements + 1);
722 if (msg->elements == NULL) return SQLITE_ABORT;
724 msg->elements[msg->num_elements].flags = 0;
725 msg->elements[msg->num_elements].name = talloc_strdup(msg->elements, cols[2]);
726 if (msg->elements[msg->num_elements].name == NULL) return SQLITE_ABORT;
728 msg->elements[msg->num_elements].num_values = 1;
729 msg->elements[msg->num_elements].values = talloc_array(msg->elements,
731 if (msg->elements[msg->num_elements].values == NULL) return SQLITE_ABORT;
733 msg->elements[msg->num_elements].values[0].length = strlen(cols[3]);
734 msg->elements[msg->num_elements].values[0].data = talloc_strdup(msg->elements, cols[3]);
735 if (msg->elements[msg->num_elements].values[0].data == NULL) return SQLITE_ABORT;
745 * lsqlite3_get_eid_ndn()
747 * These functions are used for the very common case of retrieving an EID value
748 * given a (normalized) DN.
751 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
759 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
761 "WHERE norm_dn = '%q';", norm_dn);
762 if (query == NULL) return -1;
764 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
765 if (ret != SQLITE_OK) {
767 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
776 static long long lsqlite3_get_eid(struct ldb_module *module, const struct ldb_dn *dn)
778 TALLOC_CTX *local_ctx;
779 struct lsqlite3_private *lsqlite3 = module->private_data;
783 /* ignore ltdb specials */
784 if (ldb_dn_is_special(dn)) {
788 /* create a local ctx */
789 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
790 if (local_ctx == NULL) {
794 cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, dn));
797 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
800 talloc_free(local_ctx);
805 * Interface functions referenced by lsqlite3_ops
808 /* search for matching records, by tree */
809 static int lsqlite3_search_bytree(struct ldb_module * module, const struct ldb_dn* basedn,
810 enum ldb_scope scope, struct ldb_parse_tree * tree,
811 const char * const * attrs, struct ldb_result ** res)
813 TALLOC_CTX *local_ctx;
814 struct lsqlite3_private *lsqlite3 = module->private_data;
815 struct lsqlite3_msgs msgs;
822 /* create a local ctx */
823 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_search_bytree local context");
824 if (local_ctx == NULL) {
829 norm_basedn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, basedn));
830 if (norm_basedn == NULL) {
831 ret = LDB_ERR_INVALID_DN_SYNTAX;
834 } else norm_basedn = talloc_strdup(local_ctx, "");
836 if (*norm_basedn == '\0' &&
837 (scope == LDB_SCOPE_BASE || scope == LDB_SCOPE_ONELEVEL)) {
838 ret = LDB_ERR_UNWILLING_TO_PERFORM;
842 /* Convert filter into a series of SQL conditions (constraints) */
843 sqlfilter = parsetree_to_sql(module, local_ctx, tree);
846 case LDB_SCOPE_DEFAULT:
847 case LDB_SCOPE_SUBTREE:
848 if (*norm_basedn != '\0') {
849 query = lsqlite3_tprintf(local_ctx,
850 "SELECT entry.eid,\n"
854 " FROM ldb_entry AS entry\n"
856 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
857 " ON av.eid = entry.eid\n"
859 " WHERE entry.eid IN\n"
860 " (SELECT DISTINCT ldb_entry.eid\n"
862 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
863 " OR ldb_entry.norm_dn = '%q')\n"
864 " AND ldb_entry.eid IN\n"
868 " ORDER BY entry.eid ASC;",
873 query = lsqlite3_tprintf(local_ctx,
874 "SELECT entry.eid,\n"
878 " FROM ldb_entry AS entry\n"
880 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
881 " ON av.eid = entry.eid\n"
883 " WHERE entry.eid IN\n"
884 " (SELECT DISTINCT ldb_entry.eid\n"
886 " WHERE ldb_entry.eid IN\n"
890 " ORDER BY entry.eid ASC;",
897 query = lsqlite3_tprintf(local_ctx,
898 "SELECT entry.eid,\n"
902 " FROM ldb_entry AS entry\n"
904 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
905 " ON av.eid = entry.eid\n"
907 " WHERE entry.eid IN\n"
908 " (SELECT DISTINCT ldb_entry.eid\n"
910 " WHERE ldb_entry.norm_dn = '%q'\n"
911 " AND ldb_entry.eid IN\n"
915 " ORDER BY entry.eid ASC;",
920 case LDB_SCOPE_ONELEVEL:
921 query = lsqlite3_tprintf(local_ctx,
922 "SELECT entry.eid,\n"
926 " FROM ldb_entry AS entry\n"
928 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
929 " ON av.eid = entry.eid\n"
931 " WHERE entry.eid IN\n"
932 " (SELECT DISTINCT ldb_entry.eid\n"
934 " WHERE norm_dn GLOB('*,%q')\n"
935 " AND NOT norm_dn GLOB('*,*,%q')\n"
936 " AND ldb_entry.eid IN\n(%s)\n"
939 " ORDER BY entry.eid ASC;",
952 printf ("%s\n", query);
957 msgs.current_eid = 0;
958 msgs.mem_ctx = local_ctx;
961 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, &msgs, &errmsg);
962 if (ret != SQLITE_OK) {
964 ldb_set_errstring(module, talloc_strdup(module, errmsg));
971 for (i = 0; i < msgs.count; i++) {
972 msgs.msgs[i] = ldb_msg_canonicalize(module->ldb, msgs.msgs[i]);
973 if (msgs.msgs[i] == NULL) {
978 *res = talloc(module, struct ldb_result);
983 (*res)->msgs = talloc_steal(*res, msgs.msgs);
984 (*res)->count = msgs.count;
985 (*res)->controls = NULL;
987 talloc_free(local_ctx);
990 /* If error, return error code; otherwise return number of results */
992 talloc_free(local_ctx);
993 return LDB_ERR_OTHER;
998 static int lsqlite3_add(struct ldb_module *module, const struct ldb_message *msg)
1000 TALLOC_CTX *local_ctx;
1001 struct lsqlite3_private *lsqlite3 = module->private_data;
1009 /* create a local ctx */
1010 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_add local context");
1011 if (local_ctx == NULL) {
1012 return LDB_ERR_OTHER;
1015 /* See if this is an ltdb special */
1016 if (ldb_dn_is_special(msg->dn)) {
1019 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1020 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1021 #warning "insert subclasses into object class tree"
1022 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1027 c = ldb_dn_explode(local_ctx, "@INDEXLIST");
1028 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1029 #warning "should we handle indexes somehow ?"
1033 /* Others are implicitly ignored */
1037 /* create linearized and normalized dns */
1038 dn = ldb_dn_linearize(local_ctx, msg->dn);
1039 ndn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, msg->dn));
1040 if (dn == NULL || ndn == NULL) {
1041 ret = LDB_ERR_OTHER;
1045 query = lsqlite3_tprintf(local_ctx,
1047 "INSERT OR ABORT INTO ldb_entry "
1048 "('dn', 'norm_dn') "
1049 "VALUES ('%q', '%q');",
1051 if (query == NULL) {
1052 ret = LDB_ERR_OTHER;
1056 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1057 if (ret != SQLITE_OK) {
1059 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1062 ret = LDB_ERR_OTHER;
1066 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, ndn);
1068 ret = LDB_ERR_OTHER;
1072 for (i = 0; i < msg->num_elements; i++) {
1073 const struct ldb_message_element *el = &msg->elements[i];
1074 const struct ldb_attrib_handler *h;
1078 /* Get a case-folded copy of the attribute name */
1079 attr = ldb_casefold(local_ctx, el->name);
1081 ret = LDB_ERR_OTHER;
1085 h = ldb_attrib_handler(module->ldb, el->name);
1087 /* For each value of the specified attribute name... */
1088 for (j = 0; j < el->num_values; j++) {
1089 struct ldb_val value;
1092 /* Get a canonicalised copy of the data */
1093 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1094 if (value.data == NULL) {
1095 ret = LDB_ERR_OTHER;
1099 insert = lsqlite3_tprintf(local_ctx,
1100 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1101 "('eid', 'attr_name', 'norm_attr_name',"
1102 " 'attr_value', 'norm_attr_value') "
1103 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1104 eid, el->name, attr,
1105 el->values[j].data, value.data);
1106 if (insert == NULL) {
1107 ret = LDB_ERR_OTHER;
1111 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1112 if (ret != SQLITE_OK) {
1114 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1117 ret = LDB_ERR_OTHER;
1123 talloc_free(local_ctx);
1127 talloc_free(local_ctx);
1132 /* modify a record */
1133 static int lsqlite3_modify(struct ldb_module *module, const struct ldb_message *msg)
1135 TALLOC_CTX *local_ctx;
1136 struct lsqlite3_private *lsqlite3 = module->private_data;
1142 /* create a local ctx */
1143 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_modify local context");
1144 if (local_ctx == NULL) {
1145 return LDB_ERR_OTHER;
1148 /* See if this is an ltdb special */
1149 if (ldb_dn_is_special(msg->dn)) {
1152 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1153 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1154 #warning "modify subclasses into object class tree"
1155 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1159 /* Others are implicitly ignored */
1163 eid = lsqlite3_get_eid(module, msg->dn);
1165 ret = LDB_ERR_OTHER;
1169 for (i = 0; i < msg->num_elements; i++) {
1170 const struct ldb_message_element *el = &msg->elements[i];
1171 const struct ldb_attrib_handler *h;
1172 int flags = el->flags & LDB_FLAG_MOD_MASK;
1177 /* Get a case-folded copy of the attribute name */
1178 attr = ldb_casefold(local_ctx, el->name);
1180 ret = LDB_ERR_OTHER;
1184 h = ldb_attrib_handler(module->ldb, el->name);
1188 case LDB_FLAG_MOD_REPLACE:
1190 /* remove all attributes before adding the replacements */
1191 mod = lsqlite3_tprintf(local_ctx,
1192 "DELETE FROM ldb_attribute_values "
1193 "WHERE eid = '%lld' "
1194 "AND norm_attr_name = '%q';",
1197 ret = LDB_ERR_OTHER;
1201 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1202 if (ret != SQLITE_OK) {
1204 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1207 ret = LDB_ERR_OTHER;
1211 /* MISSING break is INTENTIONAL */
1213 case LDB_FLAG_MOD_ADD:
1214 #warning "We should throw an error if no value is provided!"
1215 /* For each value of the specified attribute name... */
1216 for (j = 0; j < el->num_values; j++) {
1217 struct ldb_val value;
1219 /* Get a canonicalised copy of the data */
1220 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1221 if (value.data == NULL) {
1222 ret = LDB_ERR_OTHER;
1226 mod = lsqlite3_tprintf(local_ctx,
1227 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1228 "('eid', 'attr_name', 'norm_attr_name',"
1229 " 'attr_value', 'norm_attr_value') "
1230 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1231 eid, el->name, attr,
1232 el->values[j].data, value.data);
1235 ret = LDB_ERR_OTHER;
1239 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1240 if (ret != SQLITE_OK) {
1242 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1245 ret = LDB_ERR_OTHER;
1252 case LDB_FLAG_MOD_DELETE:
1253 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1254 if (el->num_values == 0) {
1255 mod = lsqlite3_tprintf(local_ctx,
1256 "DELETE FROM ldb_attribute_values "
1257 "WHERE eid = '%lld' "
1258 "AND norm_attr_name = '%q';",
1261 ret = LDB_ERR_OTHER;
1265 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1266 if (ret != SQLITE_OK) {
1268 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1271 ret = LDB_ERR_OTHER;
1276 /* For each value of the specified attribute name... */
1277 for (j = 0; j < el->num_values; j++) {
1278 struct ldb_val value;
1280 /* Get a canonicalised copy of the data */
1281 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1282 if (value.data == NULL) {
1283 ret = LDB_ERR_OTHER;
1287 mod = lsqlite3_tprintf(local_ctx,
1288 "DELETE FROM ldb_attribute_values "
1289 "WHERE eid = '%lld' "
1290 "AND norm_attr_name = '%q' "
1291 "AND norm_attr_value = '%q';",
1292 eid, attr, value.data);
1295 ret = LDB_ERR_OTHER;
1299 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1300 if (ret != SQLITE_OK) {
1302 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1305 ret = LDB_ERR_OTHER;
1314 talloc_free(local_ctx);
1318 talloc_free(local_ctx);
1322 /* delete a record */
1323 static int lsqlite3_delete(struct ldb_module *module, const struct ldb_dn *dn)
1325 TALLOC_CTX *local_ctx;
1326 struct lsqlite3_private *lsqlite3 = module->private_data;
1332 /* ignore ltdb specials */
1333 if (ldb_dn_is_special(dn)) {
1337 /* create a local ctx */
1338 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_delete local context");
1339 if (local_ctx == NULL) {
1340 return LDB_ERR_OTHER;
1343 eid = lsqlite3_get_eid(module, dn);
1345 ret = LDB_ERR_OTHER;
1349 query = lsqlite3_tprintf(local_ctx,
1351 "DELETE FROM ldb_entry WHERE eid = %lld; "
1352 /* Delete attributes */
1353 "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1355 if (query == NULL) {
1356 ret = LDB_ERR_OTHER;
1360 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1361 if (ret != SQLITE_OK) {
1363 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1366 ret = LDB_ERR_OTHER;
1370 talloc_free(local_ctx);
1374 talloc_free(local_ctx);
1378 /* rename a record */
1379 static int lsqlite3_rename(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
1381 TALLOC_CTX *local_ctx;
1382 struct lsqlite3_private *lsqlite3 = module->private_data;
1383 char *new_dn, *new_cdn, *old_cdn;
1388 /* ignore ltdb specials */
1389 if (ldb_dn_is_special(olddn) || ldb_dn_is_special(newdn)) {
1393 /* create a local ctx */
1394 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1395 if (local_ctx == NULL) {
1396 return LDB_ERR_OTHER;
1399 /* create linearized and normalized dns */
1400 old_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, olddn));
1401 new_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, newdn));
1402 new_dn = ldb_dn_linearize(local_ctx, newdn);
1403 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1404 ret = LDB_ERR_OTHER;
1408 /* build the SQL query */
1409 query = lsqlite3_tprintf(local_ctx,
1410 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1411 "WHERE norm_dn = '%q';",
1412 new_dn, new_cdn, old_cdn);
1413 if (query == NULL) {
1414 ret = LDB_ERR_OTHER;
1419 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1420 if (ret != SQLITE_OK) {
1422 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1425 ret = LDB_ERR_OTHER;
1429 /* clean up and exit */
1430 talloc_free(local_ctx);
1434 talloc_free(local_ctx);
1438 static int lsqlite3_start_trans(struct ldb_module * module)
1442 struct lsqlite3_private * lsqlite3 = module->private_data;
1444 if (lsqlite3->trans_count == 0) {
1445 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1446 if (ret != SQLITE_OK) {
1448 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1455 lsqlite3->trans_count++;
1460 static int lsqlite3_end_trans(struct ldb_module *module)
1464 struct lsqlite3_private *lsqlite3 = module->private_data;
1466 if (lsqlite3->trans_count > 0) {
1467 lsqlite3->trans_count--;
1470 if (lsqlite3->trans_count == 0) {
1471 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1472 if (ret != SQLITE_OK) {
1474 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1484 static int lsqlite3_del_trans(struct ldb_module *module)
1486 struct lsqlite3_private *lsqlite3 = module->private_data;
1488 if (lsqlite3->trans_count > 0) {
1489 lsqlite3->trans_count--;
1492 if (lsqlite3->trans_count == 0) {
1493 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1503 static int initialize(struct lsqlite3_private *lsqlite3,
1504 struct ldb_context *ldb, const char *url, int flags)
1506 TALLOC_CTX *local_ctx;
1513 /* create a local ctx */
1514 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1515 if (local_ctx == NULL) {
1519 schema = lsqlite3_tprintf(local_ctx,
1522 "CREATE TABLE ldb_info AS "
1523 " SELECT 'LDB' AS database_type,"
1524 " '1.0' AS version;"
1527 * The entry table holds the information about an entry.
1528 * This table is used to obtain the EID of the entry and to
1529 * support scope=one and scope=base. The parent and child
1530 * table is included in the entry table since all the other
1531 * attributes are dependent on EID.
1533 "CREATE TABLE ldb_entry "
1535 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1536 " dn TEXT UNIQUE NOT NULL,"
1537 " norm_dn TEXT UNIQUE NOT NULL"
1541 "CREATE TABLE ldb_object_classes"
1543 " class_name TEXT PRIMARY KEY,"
1544 " parent_class_name TEXT,"
1545 " tree_key TEXT UNIQUE,"
1546 " max_child_num INTEGER DEFAULT 0"
1550 * We keep a full listing of attribute/value pairs here
1552 "CREATE TABLE ldb_attribute_values"
1554 " eid INTEGER REFERENCES ldb_entry,"
1556 " norm_attr_name TEXT,"
1558 " norm_attr_value TEXT "
1565 "CREATE INDEX ldb_attribute_values_eid_idx "
1566 " ON ldb_attribute_values (eid);"
1568 "CREATE INDEX ldb_attribute_values_name_value_idx "
1569 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1577 "CREATE TRIGGER ldb_object_classes_insert_tr"
1579 " ON ldb_object_classes"
1582 " UPDATE ldb_object_classes"
1583 " SET tree_key = COALESCE(tree_key, "
1585 " SELECT tree_key || "
1586 " (SELECT base160(max_child_num + 1)"
1587 " FROM ldb_object_classes"
1588 " WHERE class_name = "
1589 " new.parent_class_name)"
1590 " FROM ldb_object_classes "
1591 " WHERE class_name = new.parent_class_name "
1593 " UPDATE ldb_object_classes "
1594 " SET max_child_num = max_child_num + 1"
1595 " WHERE class_name = new.parent_class_name;"
1599 * Table initialization
1602 "INSERT INTO ldb_object_classes "
1603 " (class_name, tree_key) "
1605 " ('TOP', '0001');");
1607 /* Skip protocol indicator of url */
1608 if (strncmp(url, "sqlite://", 9) != 0) {
1609 return SQLITE_MISUSE;
1612 /* Update pointer to just after the protocol indicator */
1615 /* Try to open the (possibly empty/non-existent) database */
1616 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1620 /* In case this is a new database, enable auto_vacuum */
1621 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1622 if (ret != SQLITE_OK) {
1624 printf("lsqlite3 initializaion error: %s\n", errmsg);
1630 if (flags & LDB_FLG_NOSYNC) {
1632 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1633 if (ret != SQLITE_OK) {
1635 printf("lsqlite3 initializaion error: %s\n", errmsg);
1644 /* Establish a busy timeout of 30 seconds */
1645 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1646 30000)) != SQLITE_OK) {
1650 /* Create a function, callable from sql, to increment a tree_key */
1652 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1653 "base160_next", /* function name */
1654 1, /* number of args */
1655 SQLITE_ANY, /* preferred text type */
1656 NULL, /* user data */
1657 base160next_sql, /* called func */
1658 NULL, /* step func */
1659 NULL /* final func */
1664 /* Create a function, callable from sql, to convert int to base160 */
1666 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1667 "base160", /* function name */
1668 1, /* number of args */
1669 SQLITE_ANY, /* preferred text type */
1670 NULL, /* user data */
1671 base160_sql, /* called func */
1672 NULL, /* step func */
1673 NULL /* final func */
1678 /* Create a function, callable from sql, to perform various comparisons */
1680 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1681 "ldap_compare", /* function name */
1682 4, /* number of args */
1683 SQLITE_ANY, /* preferred text type */
1684 ldb , /* user data */
1685 lsqlite3_compare, /* called func */
1686 NULL, /* step func */
1687 NULL /* final func */
1692 /* Begin a transaction */
1693 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1694 if (ret != SQLITE_OK) {
1696 printf("lsqlite3: initialization error: %s\n", errmsg);
1703 /* Determine if this is a new database. No tables means it is. */
1704 if (query_int(lsqlite3,
1707 " FROM sqlite_master\n"
1708 " WHERE type = 'table';") != 0) {
1712 if (queryInt == 0) {
1714 * Create the database schema
1716 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1717 if (ret != SQLITE_OK) {
1719 printf("lsqlite3 initializaion error: %s\n", errmsg);
1726 * Ensure that the database we opened is one of ours
1728 if (query_int(lsqlite3,
1731 " (SELECT COUNT(*) = 2"
1732 " FROM sqlite_master "
1733 " WHERE type = 'table' "
1737 " 'ldb_object_classes' "
1743 " WHERE database_type = 'LDB' "
1744 " AND version = '1.0'"
1748 /* It's not one that we created. See ya! */
1753 /* Commit the transaction */
1754 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1755 if (ret != SQLITE_OK) {
1757 printf("lsqlite3: iniialization error: %s\n", errmsg);
1766 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1767 sqlite3_close(lsqlite3->sqlite);
1774 struct lsqlite3_private *lsqlite3 = p;
1776 if (lsqlite3->sqlite) {
1777 sqlite3_close(lsqlite3->sqlite);
1783 static int lsqlite3_request(struct ldb_module *module, struct ldb_request *req)
1785 /* check for oustanding critical controls and return an error if found */
1786 if (check_critical_controls(req->controls)) {
1787 return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
1790 switch (req->operation) {
1792 case LDB_REQ_SEARCH:
1793 return lsqlite3_search_bytree(module,
1794 req->op.search.base,
1795 req->op.search.scope,
1796 req->op.search.tree,
1797 req->op.search.attrs,
1798 &req->op.search.res);
1801 return lsqlite3_add(module, req->op.add.message);
1803 case LDB_REQ_MODIFY:
1804 return lsqlite3_modify(module, req->op.mod.message);
1806 case LDB_REQ_DELETE:
1807 return lsqlite3_delete(module, req->op.del.dn);
1809 case LDB_REQ_RENAME:
1810 return lsqlite3_rename(module,
1811 req->op.rename.olddn,
1812 req->op.rename.newdn);
1815 return LDB_ERR_OPERATIONS_ERROR;
1820 static int lsqlite3_init_2(struct ldb_module *module)
1826 * Table of operations for the sqlite3 backend
1828 static const struct ldb_module_ops lsqlite3_ops = {
1830 .request = lsqlite3_request,
1831 .start_transaction = lsqlite3_start_trans,
1832 .end_transaction = lsqlite3_end_trans,
1833 .del_transaction = lsqlite3_del_trans,
1834 .second_stage_init = lsqlite3_init_2
1838 * connect to the database
1840 int lsqlite3_connect(struct ldb_context *ldb,
1843 const char *options[])
1847 struct lsqlite3_private * lsqlite3 = NULL;
1849 lsqlite3 = talloc(ldb, struct lsqlite3_private);
1854 lsqlite3->sqlite = NULL;
1855 lsqlite3->options = NULL;
1856 lsqlite3->trans_count = 0;
1858 ret = initialize(lsqlite3, ldb, url, flags);
1859 if (ret != SQLITE_OK) {
1863 talloc_set_destructor(lsqlite3, destructor);
1865 ldb->modules = talloc(ldb, struct ldb_module);
1866 if (!ldb->modules) {
1869 ldb->modules->ldb = ldb;
1870 ldb->modules->prev = ldb->modules->next = NULL;
1871 ldb->modules->private_data = lsqlite3;
1872 ldb->modules->ops = &lsqlite3_ops;
1876 * take a copy of the options array, so we don't have to rely
1877 * on the caller keeping it around (it might be dynamic)
1879 for (i=0;options[i];i++) ;
1881 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1882 if (!lsqlite3->options) {
1886 for (i=0;options[i];i++) {
1888 lsqlite3->options[i+1] = NULL;
1889 lsqlite3->options[i] =
1890 talloc_strdup(lsqlite3->options, options[i]);
1891 if (!lsqlite3->options[i]) {
1900 if (lsqlite3->sqlite != NULL) {
1901 (void) sqlite3_close(lsqlite3->sqlite);
1903 talloc_free(lsqlite3);