HEIMDAL: move code from source4/heimdal* to third_party/heimdal*
[samba.git] / third_party / heimdal / lib / hdb / db3.c
1 /*
2  * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include "hdb_locl.h"
35
36 #include <fcntl.h>
37
38 #if HAVE_DB3
39
40 #ifdef HAVE_DBHEADER
41 #include <db.h>
42 #elif HAVE_DB6_DB_H
43 #include <db6/db.h>
44 #elif HAVE_DB5_DB_H
45 #include <db5/db.h>
46 #elif HAVE_DB4_DB_H
47 #include <db4/db.h>
48 #elif HAVE_DB3_DB_H
49 #include <db3/db.h>
50 #else
51 #include <db.h>
52 #endif
53
54 typedef struct {
55     HDB hdb;            /* generic members */
56     int lock_fd;        /* DB3-specific */
57     int do_sync;        /* DB3-specific */
58 } DB3_HDB;
59
60
61 static krb5_error_code
62 DB_close(krb5_context context, HDB *db)
63 {
64     DB3_HDB *db3 = (DB3_HDB *)db;
65     DB *d = (DB*)db->hdb_db;
66     DBC *dbcp = (DBC*)db->hdb_dbc;
67
68     heim_assert(d != 0, "Closing already closed HDB");
69
70     if (dbcp != NULL)
71         dbcp->c_close(dbcp);
72     if (d != NULL)
73         d->close(d, 0);
74     if (db3->lock_fd >= 0)
75         close(db3->lock_fd);
76
77     db3->lock_fd = -1;
78     db->hdb_dbc = 0;
79     db->hdb_db = 0;
80
81     return 0;
82 }
83
84 static krb5_error_code
85 DB_destroy(krb5_context context, HDB *db)
86 {
87     krb5_error_code ret;
88
89     ret = hdb_clear_master_key(context, db);
90     krb5_config_free_strings(db->virtual_hostbased_princ_svcs);
91     free(db->hdb_name);
92     free(db);
93     return ret;
94 }
95
96 static krb5_error_code
97 DB_set_sync(krb5_context context, HDB *db, int on)
98 {
99     DB3_HDB *db3 = (DB3_HDB *)db;
100     DB *d = (DB*)db->hdb_db;
101     krb5_error_code ret = 0;
102
103     db3->do_sync = on;
104     if (on) {
105         ret = (*d->sync)(d, 0);
106         if (ret) {
107             if (ret == EACCES || ret == ENOSPC || ret == EINVAL) {
108                 krb5_set_error_message(context, ret,
109                                        "Database %s put sync error: %s",
110                                        db->hdb_name, strerror(ret));
111             } else {
112                 ret = HDB_ERR_UK_SERROR;
113                 krb5_set_error_message(context, ret,
114                                        "Database %s put sync error: unknown (%d)",
115                                        db->hdb_name, ret);
116             }
117         }
118     }
119     return ret;
120 }
121
122 static krb5_error_code
123 DB_lock(krb5_context context, HDB *db, int operation)
124 {
125
126     return 0;
127 }
128
129 static krb5_error_code
130 DB_unlock(krb5_context context, HDB *db)
131 {
132
133     return 0;
134 }
135
136
137 static krb5_error_code
138 DB_seq(krb5_context context, HDB *db,
139        unsigned flags, hdb_entry_ex *entry, int flag)
140 {
141     DBT key, value;
142     DBC *dbcp = db->hdb_dbc;
143     krb5_data key_data, data;
144     int code;
145
146     memset(&key, 0, sizeof(DBT));
147     memset(&value, 0, sizeof(DBT));
148     code = (*dbcp->c_get)(dbcp, &key, &value, flag);
149     if (code == DB_NOTFOUND)
150         return HDB_ERR_NOENTRY;
151     if (code)
152         return code;
153
154     key_data.data = key.data;
155     key_data.length = key.size;
156     data.data = value.data;
157     data.length = value.size;
158     memset(entry, 0, sizeof(*entry));
159     if (hdb_value2entry(context, &data, &entry->entry))
160         return DB_seq(context, db, flags, entry, DB_NEXT);
161     if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
162         code = hdb_unseal_keys (context, db, &entry->entry);
163         if (code)
164             hdb_free_entry (context, entry);
165     }
166     if (entry->entry.principal == NULL) {
167         entry->entry.principal = malloc(sizeof(*entry->entry.principal));
168         if (entry->entry.principal == NULL) {
169             hdb_free_entry (context, entry);
170             krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
171             return ENOMEM;
172         } else {
173             hdb_key2principal(context, &key_data, entry->entry.principal);
174         }
175     }
176     return 0;
177 }
178
179
180 static krb5_error_code
181 DB_firstkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
182 {
183     return DB_seq(context, db, flags, entry, DB_FIRST);
184 }
185
186
187 static krb5_error_code
188 DB_nextkey(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
189 {
190     return DB_seq(context, db, flags, entry, DB_NEXT);
191 }
192
193 static krb5_error_code
194 DB_rename(krb5_context context, HDB *db, const char *new_name)
195 {
196     int ret;
197     char *old, *new;
198
199     if (strncmp(new_name, "db:", sizeof("db:") - 1) == 0)
200         new_name += sizeof("db:") - 1;
201     else if (strncmp(new_name, "db3:", sizeof("db3:") - 1) == 0)
202         new_name += sizeof("db3:") - 1;
203
204     ret = asprintf(&old, "%s.db", db->hdb_name);
205     if (ret == -1)
206         return ENOMEM;
207     ret = asprintf(&new, "%s.db", new_name);
208     if (ret == -1) {
209         free(old);
210         return ENOMEM;
211     }
212     ret = rename(old, new);
213     free(old);
214     if(ret) {
215         free(new);
216         return errno;
217     }
218
219     free(db->hdb_name);
220     new[strlen(new) - 3] = '\0';
221     db->hdb_name = new;
222     return 0;
223 }
224
225 static krb5_error_code
226 DB__get(krb5_context context, HDB *db, krb5_data key, krb5_data *reply)
227 {
228     DB *d = (DB*)db->hdb_db;
229     DBT k, v;
230     int code;
231
232     memset(&k, 0, sizeof(DBT));
233     memset(&v, 0, sizeof(DBT));
234     k.data = key.data;
235     k.size = key.length;
236     k.flags = 0;
237     code = (*d->get)(d, NULL, &k, &v, 0);
238     if(code == DB_NOTFOUND)
239         return HDB_ERR_NOENTRY;
240     if(code)
241         return code;
242
243     krb5_data_copy(reply, v.data, v.size);
244     return 0;
245 }
246
247 static krb5_error_code
248 DB__put(krb5_context context, HDB *db, int replace,
249         krb5_data key, krb5_data value)
250 {
251     DB3_HDB *db3 = (DB3_HDB *)db;
252     DB *d = (DB*)db->hdb_db;
253     DBT k, v;
254     int code;
255
256     memset(&k, 0, sizeof(DBT));
257     memset(&v, 0, sizeof(DBT));
258     k.data = key.data;
259     k.size = key.length;
260     k.flags = 0;
261     v.data = value.data;
262     v.size = value.length;
263     v.flags = 0;
264     code = (*d->put)(d, NULL, &k, &v, replace ? 0 : DB_NOOVERWRITE);
265     if(code == DB_KEYEXIST)
266         return HDB_ERR_EXISTS;
267     if (code) {
268         /*
269          * Berkeley DB 3 and up have a terrible error reporting
270          * interface...
271          *
272          * DB->err() doesn't output a string.
273          * DB->set_errcall()'s callback function doesn't have a void *
274          * argument that can be used to place the error somewhere.
275          *
276          * The only thing we could do is fopen()/fdopen() a file, set it
277          * with DB->set_errfile(), then call DB->err(), then read the
278          * message from the file, unset it with DB->set_errfile(), close
279          * it and delete it.  That's a lot of work... so we don't do it.
280          */
281         if (code == EACCES || code == ENOSPC || code == EINVAL) {
282             krb5_set_error_message(context, code,
283                                    "Database %s put error: %s",
284                                    db->hdb_name, strerror(code));
285         } else {
286             code = HDB_ERR_UK_SERROR;
287             krb5_set_error_message(context, code,
288                                    "Database %s put error: unknown (%d)",
289                                    db->hdb_name, code);
290         }
291         return code;
292     }
293     return db->hdb_set_sync(context, db, db3->do_sync);
294 }
295
296 static krb5_error_code
297 DB__del(krb5_context context, HDB *db, krb5_data key)
298 {
299     DB3_HDB *db3 = (DB3_HDB *)db;
300     DB *d = (DB*)db->hdb_db;
301     DBT k;
302     krb5_error_code code;
303     memset(&k, 0, sizeof(DBT));
304     k.data = key.data;
305     k.size = key.length;
306     k.flags = 0;
307     code = (*d->del)(d, NULL, &k, 0);
308     if(code == DB_NOTFOUND)
309         return HDB_ERR_NOENTRY;
310     if (code) {
311         if (code == EACCES || code == ENOSPC || code == EINVAL) {
312             krb5_set_error_message(context, code,
313                                    "Database %s del error: %s",
314                                    db->hdb_name, strerror(code));
315         } else {
316             code = HDB_ERR_UK_SERROR;
317             krb5_set_error_message(context, code,
318                                    "Database %s del error: unknown (%d)",
319                                    db->hdb_name, code);
320         }
321         return code;
322     }
323     return db->hdb_set_sync(context, db, db3->do_sync);
324 }
325
326 #define RD_CACHE_SZ 0x8000     /* Minimal read cache size */
327 #define WR_CACHE_SZ 0x8000     /* Minimal write cache size */
328
329 static int
330 _open_db(DB *d, char *fn, int myflags, int flags, mode_t mode, int *fd)
331 {
332     int ret;
333     int cache_size = (myflags & DB_RDONLY) ? RD_CACHE_SZ : WR_CACHE_SZ;
334
335     *fd = open(fn, flags, mode);
336
337     if (*fd == -1)
338        return errno;
339
340     /*
341      * Without DB_FCNTL_LOCKING, the DB library complains when initializing
342      * a database in an empty file. Since the database is our lock file,
343      * we create it before Berkeley DB does, so a new DB always starts empty.
344      */
345     myflags |= DB_FCNTL_LOCKING;
346
347     ret = flock(*fd, (myflags&DB_RDONLY) ? LOCK_SH : LOCK_EX);
348     if (ret == -1) {
349         ret = errno;
350         close(*fd);
351         *fd = -1;
352         return ret;
353     }
354
355     d->set_cachesize(d, 0, cache_size, 0);
356
357 #if (DB_VERSION_MAJOR > 4) || ((DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 1))
358     ret = (*d->open)(d, NULL, fn, NULL, DB_BTREE, myflags, mode);
359 #else
360     ret = (*d->open)(d, fn, NULL, DB_BTREE, myflags, mode);
361 #endif
362
363     if (ret != 0) {
364         close(*fd);
365         *fd = -1;
366     }
367
368     return ret;
369 }
370
371 static krb5_error_code
372 DB_open(krb5_context context, HDB *db, int flags, mode_t mode)
373 {
374     DB3_HDB *db3 = (DB3_HDB *)db;
375     DBC *dbc = NULL;
376     char *fn;
377     krb5_error_code ret;
378     DB *d;
379     int myflags = 0;
380     int aret;
381
382     heim_assert(db->hdb_db == 0, "Opening already open HDB");
383
384     if (flags & O_CREAT)
385       myflags |= DB_CREATE;
386
387     if (flags & O_EXCL)
388       myflags |= DB_EXCL;
389
390     if((flags & O_ACCMODE) == O_RDONLY)
391       myflags |= DB_RDONLY;
392
393     if (flags & O_TRUNC)
394       myflags |= DB_TRUNCATE;
395
396     aret = asprintf(&fn, "%s.db", db->hdb_name);
397     if (aret == -1) {
398         krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
399         return ENOMEM;
400     }
401
402     if (db_create(&d, NULL, 0) != 0) {
403         free(fn);
404         krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
405         return ENOMEM;
406     }
407     db->hdb_db = d;
408
409     /* From here on out always DB_close() before returning on error */
410
411     ret = _open_db(d, fn, myflags, flags, mode, &db3->lock_fd);
412     free(fn);
413     if (ret == ENOENT) {
414         /* try to open without .db extension */
415         ret = _open_db(d, db->hdb_name, myflags, flags, mode, &db3->lock_fd);
416     }
417
418     if (ret) {
419         DB_close(context, db);
420         krb5_set_error_message(context, ret, "opening %s: %s",
421                                db->hdb_name, strerror(ret));
422         return ret;
423     }
424
425 #ifndef DB_CURSOR_BULK
426 # define DB_CURSOR_BULK 0       /* Missing with DB < 4.8 */
427 #endif
428     ret = (*d->cursor)(d, NULL, &dbc, DB_CURSOR_BULK);
429
430     if (ret) {
431         DB_close(context, db);
432         krb5_set_error_message(context, ret, "d->cursor: %s", strerror(ret));
433         return ret;
434     }
435     db->hdb_dbc = dbc;
436
437     if((flags & O_ACCMODE) == O_RDONLY)
438         ret = hdb_check_db_format(context, db);
439     else
440         ret = hdb_init_db(context, db);
441     if(ret == HDB_ERR_NOENTRY)
442         return 0;
443     if (ret) {
444         DB_close(context, db);
445         krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
446                                (flags & O_ACCMODE) == O_RDONLY ?
447                                "checking format of" : "initialize",
448                                db->hdb_name);
449     }
450
451     return ret;
452 }
453
454 krb5_error_code
455 hdb_db3_create(krb5_context context, HDB **db,
456                const char *filename)
457 {
458     DB3_HDB **db3 = (DB3_HDB **)db;
459     *db3 = calloc(1, sizeof(**db3));    /* Allocate space for the larger db3 */
460     if (*db == NULL) {
461         krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
462         return ENOMEM;
463     }
464
465     (*db)->hdb_db = NULL;
466     (*db)->hdb_name = strdup(filename);
467     if ((*db)->hdb_name == NULL) {
468         free(*db);
469         *db = NULL;
470         krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
471         return ENOMEM;
472     }
473     (*db)->hdb_master_key_set = 0;
474     (*db)->hdb_openp = 0;
475     (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
476     (*db)->hdb_open  = DB_open;
477     (*db)->hdb_close = DB_close;
478     (*db)->hdb_fetch_kvno = _hdb_fetch_kvno;
479     (*db)->hdb_store = _hdb_store;
480     (*db)->hdb_remove = _hdb_remove;
481     (*db)->hdb_firstkey = DB_firstkey;
482     (*db)->hdb_nextkey= DB_nextkey;
483     (*db)->hdb_lock = DB_lock;
484     (*db)->hdb_unlock = DB_unlock;
485     (*db)->hdb_rename = DB_rename;
486     (*db)->hdb__get = DB__get;
487     (*db)->hdb__put = DB__put;
488     (*db)->hdb__del = DB__del;
489     (*db)->hdb_destroy = DB_destroy;
490     (*db)->hdb_set_sync = DB_set_sync;
491
492     (*db3)->lock_fd = -1;
493     return 0;
494 }
495 #endif /* HAVE_DB3 */