database: switch to use gdbm by default
[apps/agl-service-data-persistence.git] / ll-database-binding / src / ll-database-binding.c
1 /*
2  * Copyright 2017 IoT.bzh
3  *
4  * author: Loïc Collignon <loic.collignon@iot.bzh>
5  * author: Jose Bollo <jose.bollo@iot.bzh>
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 #define _GNU_SOURCE
21 #include <unistd.h>
22 #include <sys/types.h>
23 #include <pwd.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <limits.h>
27
28 #include <json-c/json.h>
29
30 #define AFB_BINDING_VERSION 2
31 #include <afb/afb-binding.h>
32
33 #if !defined(TO_STRING_FLAGS)
34 # if !defined(JSON_C_TO_STRING_NOSLASHESCAPE)
35 #  define JSON_C_TO_STRING_NOSLASHESCAPE (1<<4)
36 # endif
37 # define TO_STRING_FLAGS (JSON_C_TO_STRING_PLAIN | JSON_C_TO_STRING_NOSLASHESCAPE)
38 #endif
39
40 #if defined(USE_BERKELEY_DB)
41 #  undef USE_BERKELEY_DB
42 #endif
43
44 #if defined(USE_GDBM)
45 #  undef USE_GDBM
46 #  define USE_GDBM        1
47 #  define USE_BERKELEY_DB 0
48 #else
49 #  define USE_GDBM        0
50 #  define USE_BERKELEY_DB 1
51 #endif
52
53 // ----- Berkeley database -----
54 #if USE_BERKELEY_DB
55
56 #include <db.h>
57
58 #define DBFILE  "ll-database-binding.db"
59 #define DATA    DBT
60 #define DATA_SET(k,d,s)  do{memset((k),0,sizeof*(k));(k)->data=(void*)d;(k)->size=(uint32_t)s;}while(0)
61 #define DATA_PTR(k)      ((void*)((k).data))
62 #define DATA_STR(k)      ((char*)((k).data))
63 #define DATA_SZ(k)       ((size_t)((k).size))
64
65 static DB *database;
66
67 static int xdb_open(const char *path)
68 {
69         int ret;
70
71         ret = db_create(&database, NULL, 0);
72         if (ret != 0)
73         {
74                 AFB_ERROR("Failed to create database: %s.", db_strerror(ret));
75                 return -1;
76         }
77
78         ret = database->open(database, NULL, path, NULL, DB_BTREE, DB_CREATE, 0600);
79         if (ret != 0)
80         {
81                 AFB_ERROR("Failed to open the '%s' database: %s.", path, db_strerror(ret));
82                 database->close(database, 0);
83                 return -1;
84         }
85         return 0;
86 }
87
88 static void xdb_put(struct afb_req req, DBT *key, DBT *data, int replace)
89 {
90         int ret;
91
92         ret = database->put(database, NULL, key, data, replace ? 0 : DB_NOOVERWRITE);
93         if (ret == 0)
94                 afb_req_success(req, NULL, NULL);
95         else
96         {
97                 AFB_ERROR("can't %s key %s with %s", replace ? "replace" : "insert", DATA_STR(*key), DATA_STR(*data));
98                 afb_req_fail_f(req, "failed", "%s", db_strerror(ret));
99         }
100 }
101
102 static void xdb_delete(struct afb_req req, DBT *key)
103 {
104         int ret;
105
106         ret = database->del(database, NULL, key, 0);
107         if (ret == 0)
108                 afb_req_success_f(req, NULL, NULL);
109         else
110         {
111                 AFB_ERROR("can't delete key %s", DATA_STR(*key));
112                 afb_req_fail_f(req, "failed", "%s", db_strerror(ret));
113         }
114
115         free(DATA_PTR(key));
116 }
117
118 static void verb_read(struct afb_req req)
119 {
120         DATA key;
121         DATA data;
122         int ret;
123
124         char value[4096];
125
126         struct json_object* result;
127         struct json_object* val;
128
129
130         if (get_key(req, &key))
131                 return;
132
133         AFB_INFO("read: key=%s", DATA_STR(key));
134
135         memset(&data, 0, sizeof data);
136         data.data = value;
137         data.ulen = 4096;
138         data.flags = DB_DBT_USERMEM;
139
140         ret = database->get(database, NULL, &key, &data, 0);
141         if (ret == 0)
142         {
143                 result = json_object_new_object();
144                 val = json_tokener_parse(DATA_STR(data));
145                 json_object_object_add(result, "value", val ? val : json_object_new_string(DATA_STR(data)));
146
147                 afb_req_success_f(req, result, "db success: read %s=%s.", DATA_STR(key), DATA_STR(data));
148         }
149         else
150                 afb_req_fail_f(req, "Failed to read datas.", "db fail: read %s - %s", DATA_STR(key), db_strerror(ret));
151
152         free(DATA_PTR(key));
153 }
154
155 #endif
156
157 // ----- gdbm database -----
158 #if USE_GDBM
159
160 #include <errno.h>
161 #include <gdbm.h>
162
163 #define DBFILE  "ll-database-binding.dbm"
164 #define DATA    datum
165 #define DATA_SET(k,d,s)  do{(k)->dptr=(char*)d;(k)->dsize=(int)s;}while(0)
166 #define DATA_PTR(k)      ((void*)((k).dptr))
167 #define DATA_STR(k)      ((char*)((k).dptr))
168 #define DATA_SZ(k)       ((size_t)((k).dsize))
169
170 static GDBM_FILE database;
171
172 static void onfatal(const char *text)
173 {
174         AFB_ERROR("fatal gdbm message: %s", text);
175 }
176
177 static int xdb_open(const char *path)
178 {
179         database = gdbm_open(path, 512, GDBM_WRCREAT|GDBM_SYNC, 0600, onfatal);
180         if (!database)
181         {
182                 AFB_ERROR("Fail to open/create database: %s%s%s", gdbm_errlist[gdbm_errno],
183                         gdbm_syserr[gdbm_errno] ? ", " : "",
184                         gdbm_syserr[gdbm_errno] ? strerror(errno) : "");
185                 return -1;
186                 
187         }
188         return 0;
189 }
190
191 static void xdb_put(struct afb_req req, datum *key, datum *data, int replace)
192 {
193         int ret;
194
195         ret = gdbm_store(database, *key, *data, replace ? GDBM_REPLACE : GDBM_INSERT);
196         if (ret == 0)
197                 afb_req_success(req, NULL, NULL);
198         else
199         {
200                 AFB_ERROR("can't %s key %s with %s: %s%s%s",
201                         replace ? "replace" : "insert",
202                         DATA_STR(*key),
203                         DATA_STR(*data),
204                         gdbm_errlist[gdbm_errno],
205                         gdbm_syserr[gdbm_errno] ? ", " : "",
206                         gdbm_syserr[gdbm_errno] ? strerror(errno) : "");
207                 afb_req_fail_f(req, "failed", "%s", ret > 0 ? "key already exists" : gdbm_errlist[gdbm_errno]);
208         }
209 }
210
211 static void xdb_delete(struct afb_req req, datum *key)
212 {
213         int ret;
214
215         ret = gdbm_delete(database, *key);
216         if (ret == 0)
217                 afb_req_success_f(req, NULL, NULL);
218         else
219         {
220                 AFB_ERROR("can't delete key %s: %s%s%s",
221                         DATA_STR(*key),
222                         gdbm_errlist[gdbm_errno],
223                         gdbm_syserr[gdbm_errno] ? ", " : "",
224                         gdbm_syserr[gdbm_errno] ? strerror(errno) : "");
225                 afb_req_fail_f(req, "failed", "%s", gdbm_errlist[gdbm_errno]);
226         }
227 }
228
229 static void xdb_get(struct afb_req req, datum *key)
230 {
231         struct json_object* obj;
232         datum result;
233
234         result = gdbm_fetch(database, *key);
235         if (result.dptr)
236         {
237                 obj = json_object_new_object();
238                 json_object_object_add(obj, "value", json_tokener_parse(result.dptr));
239                 afb_req_success(req, obj, NULL);
240                 free(result.dptr);
241         }
242         else
243         {
244                 AFB_ERROR("can't get key %s: %s%s%s",
245                         DATA_STR(*key),
246                         gdbm_errlist[gdbm_errno],
247                         gdbm_syserr[gdbm_errno] ? ", " : "",
248                         gdbm_syserr[gdbm_errno] ? strerror(errno) : "");
249                 afb_req_fail_f(req, "failed", "%s", gdbm_errlist[gdbm_errno]);
250         }
251 }
252 #endif
253
254 // ----- Binding's implementations -----
255
256 /**
257  * @brief Get the path to the database
258  */
259 static int get_database_path(char *buffer, size_t size)
260 {
261         static const char dbfile[] = DBFILE;
262
263         char *home, *config;
264         int rc;
265
266         config = secure_getenv("XDG_CONFIG_HOME");
267         if (config)
268                 rc = snprintf(buffer, size, "%s/%s", config, dbfile);
269         else
270         {
271                 home = secure_getenv("HOME");
272                 if (home)
273                         rc = snprintf(buffer, size, "%s/.config/%s", home, dbfile);
274                 else
275                 {
276                         uid_t uid = getuid();
277                         struct passwd *pwd = getpwuid(uid);
278                         if (pwd)
279                                 rc = snprintf(buffer, size, "%s/.config/%s", pwd->pw_dir, dbfile);
280                         else
281                                 rc = snprintf(buffer, size, "/home/%d/.config/%s", (int)uid, dbfile);
282                 }
283         }
284         return rc;
285 }
286
287 /**
288  * @brief Initialize the binding.
289  * @return Exit code, zero if success.
290  */
291 static int ll_database_binding_init()
292 {
293         char path[PATH_MAX];
294         int ret;
295
296         ret = get_database_path(path, sizeof path);
297         if (ret < 0 || (int)ret >=  (int)(sizeof path))
298         {
299                 AFB_ERROR("Can't compute the database filename");
300                 return -1;
301         }
302
303         AFB_INFO("opening database %s", path);
304         return xdb_open(path);
305 }
306
307 /**
308  * Returns the database key for the 'req'
309  */
310 static int get_key(struct afb_req req, DATA *key)
311 {
312         char *appid, *data;
313         const char *jkey;
314
315         size_t ljkey, lappid, size;
316
317         struct json_object* args;
318         struct json_object* item;
319
320         /* get the key */
321         args = afb_req_json(req);
322         if (!json_object_object_get_ex(args, "key", &item))
323         {
324                 afb_req_fail(req, "no-key", NULL);
325                 return -1;
326         }
327         if (!item
328          || !(jkey = json_object_get_string(item))
329          || !(ljkey = strlen(jkey)))
330         {
331                 afb_req_fail(req, "bad-key", NULL);
332                 return -1;
333         }
334
335         /* get the appid */
336         appid = afb_req_get_application_id(req);
337 #if 1
338         if (!appid)
339                 appid = strdup("#UNKNOWN-APP#");
340 #endif
341         if (!appid)
342         {
343                 afb_req_fail(req, "bad-context", NULL);
344                 return -1;
345         }
346
347         /* make the db-key */
348         lappid = strlen(appid);
349         size = lappid + ljkey + 2;
350         data = realloc(appid, size);
351         if (!data)
352         {
353                 free(appid);
354                 afb_req_fail(req, "out-of-memory", NULL);
355                 return -1;
356         }
357         data[lappid] = ':';
358         memcpy(&data[lappid + 1], jkey, ljkey + 1);
359
360         /* return the key */
361         DATA_SET(key, data, size);
362         return 0;
363 }
364
365 static void put(struct afb_req req, int replace)
366 {
367         DATA key;
368         DATA data;
369
370         const char* value;
371
372         struct json_object* args;
373         struct json_object* item;
374
375         /* get the value */
376         args = afb_req_json(req);
377         if (!json_object_object_get_ex(args, "value", &item))
378         {
379                 afb_req_fail(req, "no-value", NULL);
380                 return;
381         }
382         value = json_object_to_json_string_ext(item, TO_STRING_FLAGS);
383         if (!value)
384         {
385                 afb_req_fail(req, "out-of-memory", NULL);
386                 return;
387         }
388         DATA_SET(&data, value, strlen(value) + 1); /* includes the tailing null */
389
390         /* get the key */
391         if (get_key(req, &key))
392                 return;
393
394         AFB_INFO("put: key=%s, value=%s", DATA_STR(key), DATA_STR(data));
395         xdb_put(req, &key, &data, replace);
396         free(DATA_PTR(key));
397 }
398
399 static void verb_insert(struct afb_req req)
400 {
401         put(req, 0);
402 }
403
404 static void verb_update(struct afb_req req)
405 {
406         put(req, 1);
407 }
408
409 static void verb_delete(struct afb_req req)
410 {
411         DATA key;
412
413         if (get_key(req, &key))
414                 return;
415
416         AFB_INFO("delete: key=%s", DATA_STR(key));
417         xdb_delete(req, &key);
418         free(DATA_PTR(key));
419 }
420
421 static void verb_read(struct afb_req req)
422 {
423         DATA key;
424
425         if (get_key(req, &key))
426                 return;
427
428         AFB_INFO("read: key=%s", DATA_STR(key));
429         xdb_get(req, &key);
430         free(DATA_PTR(key));
431 }
432
433 // ----- Binding's configuration -----
434 /*
435 static const struct afb_auth ll_database_binding_auths[] = {
436 };
437 */
438
439 #define VERB(name_,auth_,info_,sess_) {\
440         .verb = #name_, \
441         .callback = verb_##name_, \
442         .auth = auth_, \
443         .info = info_, \
444         .session = sess_ }
445
446 static const afb_verb_v2 ll_database_binding_verbs[]= {
447         VERB(insert,    NULL, NULL, AFB_SESSION_NONE_V2),
448         VERB(update,    NULL, NULL, AFB_SESSION_NONE_V2),
449         VERB(delete,    NULL, NULL, AFB_SESSION_NONE_V2),
450         VERB(read,      NULL, NULL, AFB_SESSION_NONE_V2),
451         { .verb = NULL}
452 };
453
454 const struct afb_binding_v2 afbBindingV2 = {
455         .api = "ll-database",
456         .specification = NULL,
457         .verbs = ll_database_binding_verbs,
458         .preinit = NULL,
459         .init = ll_database_binding_init,
460         .onevent = NULL,
461         .noconcurrency = 0
462 };