def5184c5be6a787e5c3f706df6e1916cc3528a8
[apps/agl-service-data-persistence.git] / src / persistence-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_DEBUG("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 #if GDBM_VERSION_MAJOR > 1 || (GDBM_VERSION_MAJOR == 1 && GDBM_VERSION_MINOR >= 13)
171 # define IFSYS(yes,no)   (gdbm_syserr[gdbm_errno] ? (yes) : (no))
172 #else
173 # define IFSYS(yes,no)   (no)
174 #endif
175
176 static GDBM_FILE database;
177
178 static void onfatal(const char *text)
179 {
180         AFB_ERROR("fatal gdbm message: %s", text);
181 }
182
183 static int xdb_open(const char *path)
184 {
185         database = gdbm_open(path, 512, GDBM_WRCREAT|GDBM_SYNC, 0600, onfatal);
186         if (!database)
187         {
188                 AFB_ERROR("Fail to open/create database: %s%s%s",
189                         gdbm_strerror(gdbm_errno),
190                         IFSYS(", ", ""),
191                         IFSYS(strerror(errno), ""));
192                 return -1;
193                 
194         }
195         return 0;
196 }
197
198 static void xdb_put(struct afb_req req, datum *key, datum *data, int replace)
199 {
200         int ret;
201
202         ret = gdbm_store(database, *key, *data, replace ? GDBM_REPLACE : GDBM_INSERT);
203         if (ret == 0)
204                 afb_req_success(req, NULL, NULL);
205         else
206         {
207                 AFB_ERROR("can't %s key %s with %s: %s%s%s",
208                         replace ? "replace" : "insert",
209                         DATA_STR(*key),
210                         DATA_STR(*data),
211                         gdbm_strerror(gdbm_errno),
212                         IFSYS(", ", ""),
213                         IFSYS(strerror(errno), ""));
214                 afb_req_fail_f(req, "failed", "%s", ret > 0 ? "key already exists" : gdbm_strerror(gdbm_errno));
215         }
216 }
217
218 static void xdb_delete(struct afb_req req, datum *key)
219 {
220         int ret;
221
222         ret = gdbm_delete(database, *key);
223         if (ret == 0)
224                 afb_req_success_f(req, NULL, NULL);
225         else
226         {
227                 AFB_ERROR("can't delete key %s: %s%s%s",
228                         DATA_STR(*key),
229                         gdbm_strerror(gdbm_errno),
230                         IFSYS(", ", ""),
231                         IFSYS(strerror(errno), ""));
232                 afb_req_fail_f(req, "failed", "%s", gdbm_strerror(gdbm_errno));
233         }
234 }
235
236 static void xdb_get(struct afb_req req, datum *key)
237 {
238         struct json_object* obj;
239         datum result;
240
241         result = gdbm_fetch(database, *key);
242         if (result.dptr)
243         {
244                 obj = json_object_new_object();
245                 json_object_object_add(obj, "value", json_tokener_parse(result.dptr));
246                 afb_req_success(req, obj, NULL);
247                 free(result.dptr);
248         }
249         else
250         {
251                 AFB_ERROR("can't get key %s: %s%s%s",
252                         DATA_STR(*key),
253                         gdbm_strerror(gdbm_errno),
254                         IFSYS(", ", ""),
255                         IFSYS(strerror(errno), ""));
256                 afb_req_fail_f(req, "failed", "%s", gdbm_strerror(gdbm_errno));
257         }
258 }
259 #endif
260
261 // ----- Binding's implementations -----
262
263 /**
264  * @brief Get the path to the database
265  */
266 static int get_database_path(char *buffer, size_t size)
267 {
268         static const char dbfile[] = DBFILE;
269
270         char *home, *config;
271         int rc;
272
273         config = secure_getenv("XDG_CONFIG_HOME");
274         if (config)
275                 rc = snprintf(buffer, size, "%s/%s", config, dbfile);
276         else
277         {
278                 home = secure_getenv("HOME");
279                 if (home)
280                         rc = snprintf(buffer, size, "%s/.config/%s", home, dbfile);
281                 else
282                 {
283                         uid_t uid = getuid();
284                         struct passwd *pwd = getpwuid(uid);
285                         if (pwd)
286                                 rc = snprintf(buffer, size, "%s/.config/%s", pwd->pw_dir, dbfile);
287                         else
288                                 rc = snprintf(buffer, size, "/home/%d/.config/%s", (int)uid, dbfile);
289                 }
290         }
291         return rc;
292 }
293
294 /**
295  * @brief Initialize the binding.
296  * @return Exit code, zero if success.
297  */
298 static int ll_database_binding_init()
299 {
300         char path[PATH_MAX];
301         int ret;
302
303         ret = get_database_path(path, sizeof path);
304         if (ret < 0 || (int)ret >=  (int)(sizeof path))
305         {
306                 AFB_ERROR("Can't compute the database filename");
307                 return -1;
308         }
309
310         AFB_INFO("opening database %s", path);
311         return xdb_open(path);
312 }
313
314 /**
315  * Returns the database key for the 'req'
316  */
317 static int get_key(struct afb_req req, DATA *key)
318 {
319         char *appid, *data;
320         const char *jkey;
321
322         size_t ljkey, lappid, size;
323
324         struct json_object* args;
325         struct json_object* item;
326
327         /* get the key */
328         args = afb_req_json(req);
329         if (!json_object_object_get_ex(args, "key", &item))
330         {
331                 afb_req_fail(req, "no-key", NULL);
332                 return -1;
333         }
334         if (!item
335      || !(jkey = json_object_to_json_string_ext(item, JSON_C_TO_STRING_PLAIN))
336          || !(ljkey = strlen(jkey)))
337         {
338                 afb_req_fail(req, "bad-key", NULL);
339                 return -1;
340         }
341
342         /* get the appid */
343         appid = afb_req_get_application_id(req);
344 #if 1
345         if (!appid)
346                 appid = strdup("#UNKNOWN-APP#");
347 #endif
348         if (!appid)
349         {
350                 afb_req_fail(req, "bad-context", NULL);
351                 return -1;
352         }
353
354         /* make the db-key */
355         lappid = strlen(appid);
356         size = lappid + ljkey + 2;
357         data = realloc(appid, size);
358         if (!data)
359         {
360                 free(appid);
361                 afb_req_fail(req, "out-of-memory", NULL);
362                 return -1;
363         }
364         data[lappid] = ':';
365         memcpy(&data[lappid + 1], jkey, ljkey + 1);
366
367         /* return the key */
368         DATA_SET(key, data, size);
369         return 0;
370 }
371
372 static void put(struct afb_req req, int replace)
373 {
374         DATA key;
375         DATA data;
376
377         const char* value;
378
379         struct json_object* args;
380         struct json_object* item;
381
382         /* get the value */
383         args = afb_req_json(req);
384         if (!json_object_object_get_ex(args, "value", &item))
385         {
386                 afb_req_fail(req, "no-value", NULL);
387                 return;
388         }
389         value = json_object_to_json_string_ext(item, TO_STRING_FLAGS);
390         if (!value)
391         {
392                 afb_req_fail(req, "out-of-memory", NULL);
393                 return;
394         }
395         DATA_SET(&data, value, strlen(value) + 1); /* includes the tailing null */
396
397         /* get the key */
398         if (get_key(req, &key))
399                 return;
400
401         AFB_DEBUG("put: key=%s, value=%s", DATA_STR(key), DATA_STR(data));
402         xdb_put(req, &key, &data, replace);
403         free(DATA_PTR(key));
404 }
405
406 static void verb_insert(struct afb_req req)
407 {
408         put(req, 0);
409 }
410
411 static void verb_update(struct afb_req req)
412 {
413         put(req, 1);
414 }
415
416 static void verb_delete(struct afb_req req)
417 {
418         DATA key;
419
420         if (get_key(req, &key))
421                 return;
422
423         AFB_DEBUG("delete: key=%s", DATA_STR(key));
424         xdb_delete(req, &key);
425         free(DATA_PTR(key));
426 }
427
428 static void verb_read(struct afb_req req)
429 {
430         DATA key;
431
432         if (get_key(req, &key))
433                 return;
434
435         AFB_DEBUG("read: key=%s", DATA_STR(key));
436         xdb_get(req, &key);
437         free(DATA_PTR(key));
438 }
439
440 // ----- Binding's configuration -----
441 /*
442 static const struct afb_auth ll_database_binding_auths[] = {
443 };
444 */
445
446 #define VERB(name_,auth_,info_,sess_) {\
447         .verb = #name_, \
448         .callback = verb_##name_, \
449         .auth = auth_, \
450         .info = info_, \
451         .session = sess_ }
452
453 static const afb_verb_v2 ll_database_binding_verbs[]= {
454         VERB(insert,    NULL, NULL, AFB_SESSION_NONE_V2),
455         VERB(update,    NULL, NULL, AFB_SESSION_NONE_V2),
456         VERB(delete,    NULL, NULL, AFB_SESSION_NONE_V2),
457         VERB(read,      NULL, NULL, AFB_SESSION_NONE_V2),
458         { .verb = NULL}
459 };
460
461 const struct afb_binding_v2 afbBindingV2 = {
462         .api = "persistence",
463         .specification = NULL,
464         .verbs = ll_database_binding_verbs,
465         .preinit = NULL,
466         .init = ll_database_binding_init,
467         .onevent = NULL,
468         .noconcurrency = 0
469 };