002d572019393857c7fe8c70d11da16645f8e3af
[sfrench/samba-autobuild/.git] / source3 / lib / dbwrap_util.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Utility functions for the dbwrap API
4    Copyright (C) Volker Lendecke 2007
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "includes.h"
22
23 int32_t dbwrap_fetch_int32(struct db_context *db, const char *keystr)
24 {
25         TDB_DATA dbuf;
26         int32 ret;
27
28         if (db->fetch(db, NULL, string_term_tdb_data(keystr), &dbuf) != 0) {
29                 return -1;
30         }
31
32         if ((dbuf.dptr == NULL) || (dbuf.dsize != sizeof(int32_t))) {
33                 TALLOC_FREE(dbuf.dptr);
34                 return -1;
35         }
36
37         ret = IVAL(dbuf.dptr, 0);
38         TALLOC_FREE(dbuf.dptr);
39         return ret;
40 }
41
42 int dbwrap_store_int32(struct db_context *db, const char *keystr, int32_t v)
43 {
44         struct db_record *rec;
45         int32 v_store;
46         NTSTATUS status;
47
48         rec = db->fetch_locked(db, NULL, string_term_tdb_data(keystr));
49         if (rec == NULL) {
50                 return -1;
51         }
52
53         SIVAL(&v_store, 0, v);
54
55         status = rec->store(rec, make_tdb_data((const uint8 *)&v_store,
56                                                sizeof(v_store)),
57                             TDB_REPLACE);
58         TALLOC_FREE(rec);
59         return NT_STATUS_IS_OK(status) ? 0 : -1;
60 }
61
62 uint32_t dbwrap_change_uint32_atomic(struct db_context *db, const char *keystr,
63                                      uint32_t *oldval, uint32_t change_val)
64 {
65         struct db_record *rec;
66         uint32 val = -1;
67         TDB_DATA data;
68
69         if (!(rec = db->fetch_locked(db, NULL,
70                                      string_term_tdb_data(keystr)))) {
71                 return -1;
72         }
73
74         if ((rec->value.dptr != NULL)
75             && (rec->value.dsize == sizeof(val))) {
76                 val = IVAL(rec->value.dptr, 0);
77         }
78
79         val += change_val;
80
81         data.dsize = sizeof(val);
82         data.dptr = (uint8 *)&val;
83
84         rec->store(rec, data, TDB_REPLACE);
85
86         TALLOC_FREE(rec);
87
88         return 0;
89 }
90