database: refactor path compute of database
[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  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #define _GNU_SOURCE
20 #include <unistd.h>
21 #include <sys/types.h>
22 #include <pwd.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <linux/limits.h>
26 #include <json-c/json.h>
27 #include <db.h>
28
29 #define AFB_BINDING_VERSION 2
30 #include <afb/afb-binding.h>
31
32 #include "utils.h"
33
34 #ifndef MAX_PATH
35 #define MAX_PATH 1024
36 #endif
37
38 #define DBFILE          "ll-database-binding.db"
39
40 #if !defined(TO_STRING_FLAGS)
41 # if !defined(JSON_C_TO_STRING_NOSLASHESCAPE)
42 #  define JSON_C_TO_STRING_NOSLASHESCAPE (1<<4)
43 # endif
44 # define TO_STRING_FLAGS (JSON_C_TO_STRING_PLAIN | JSON_C_TO_STRING_NOSLASHESCAPE)
45 #endif
46
47 // ----- Globals -----
48 static DB *database;
49
50 // ----- Binding's declarations -----
51 static int ll_database_binding_init();
52 static void verb_insert(struct afb_req req);
53 static void verb_update(struct afb_req req);
54 static void verb_delete(struct afb_req req);
55 static void verb_read(struct afb_req req);
56
57 // ----- Binding's implementations -----
58
59 /**
60  * @brief Get the path to the database
61  */
62 static int get_database_path(char *buffer, size_t size)
63 {
64         static const char dbfile[] = DBFILE;
65
66         char *home, *config;
67         int rc;
68
69         config = secure_getenv("XDG_CONFIG_HOME");
70         if (config)
71                 rc = snprintf(buffer, size, "%s/.config/%s", home, dbfile);
72         else
73         {
74                 home = secure_getenv("HOME");
75                 if (home)
76                         rc = snprintf(buffer, size, "%s/.config/%s", home, dbfile);
77                 else
78                 {
79                         struct passwd *pwd = getpwuid(getuid());
80                         if (pwd)
81                                 rc = snprintf(buffer, size, "%s/.config/%s", result->pw_dir, dbfile);
82                         else
83                                 rc = snprintf(buffer, size, "/home/%d/.config/%s", (int)getuid(), dbfile);
84                 }
85         }
86         return rc;
87 }
88
89 /**
90  * @brief Initialize the binding.
91  * @return Exit code, zero if success.
92  */
93 static int ll_database_binding_init()
94 {
95         char path[MAX_PATH];
96         int ret;
97
98         ret = get_database_path(path, sizeof path);
99         if (ret < 0 || (int)ret >=  (int)(sizeof path))
100         {
101                 AFB_ERROR("Can't compute the database filename");
102                 return -1;
103         }
104
105         AFB_INFO("opening database %s", path);
106
107         if ((ret = db_create(&database, NULL, 0)) != 0)
108         {
109                 AFB_ERROR("Failed to create database: %s.", db_strerror(ret));
110                 return -1;
111         }
112
113         if ((ret = database->open(database, NULL, path, NULL, DB_BTREE, DB_CREATE, 0664)) != 0)
114         {
115                 AFB_ERROR("Failed to open the '%s' database: %s.", path, db_strerror(ret));
116                 database->close(database, 0);
117                 return -1;
118         }
119
120         return 0;
121 }
122
123 /**
124  * Returns the database key for the 'req'
125  */
126 static int get_key(struct afb_req req, DBT *key)
127 {
128         char *appid, *data;
129         const char *jkey;
130
131         size_t ljkey, lappid, size;
132
133         struct json_object* args;
134         struct json_object* item;
135
136         /* get the key */
137         args = afb_req_json(req);
138         if (!json_object_object_get_ex(args, "key", &item))
139         {
140                 afb_req_fail(req, "no-key", NULL);
141                 return -1;
142         }
143         if (!item
144          || !(jkey = json_object_get_string(item))
145          || !(ljkey = strlen(jkey)))
146         {
147                 afb_req_fail(req, "bad-key", NULL);
148                 return -1;
149         }
150
151         /* get the appid */
152         appid = afb_req_get_application_id(req);
153         if (!appid)
154         {
155                 afb_req_fail(req, "bad-context", NULL);
156                 return -1;
157         }
158
159         /* make the db-key */
160         lappid = strlen(appid);
161         size = lappid + ljkey + 2;
162         data = realloc(appid, size);
163         if (!data)
164         {
165                 free(appid);
166                 afb_req_fail(req, "out-of-memory", NULL);
167                 return -1;
168         }
169         data[lappid] = ':';
170         memcpy(&data[lappid + 1], jkey, ljkey + 1);
171
172         /* return the key */
173         key->data = data;
174         key->size = (uint32_t)size;
175         return 0;
176 }
177
178 static void put(struct afb_req req, int replace)
179 {
180         int ret;
181         DBT key;
182         DBT data;
183
184         const char* value;
185
186         struct json_object* args;
187         struct json_object* item;
188
189         args = afb_req_json(req);
190
191         if (!json_object_object_get_ex(args, "value", &item))
192         {
193                 afb_req_fail(req, "no-value", NULL);
194                 return;
195         }
196
197         value = json_object_to_json_string_ext(item, TO_STRING_FLAGS);
198         if (!value)
199         {
200                 afb_req_fail(req, "out-of-memory", NULL);
201                 return;
202         }
203
204         if (get_key(req, &key))
205                 return;
206
207         AFB_INFO("put: key=%s, value=%s", (char*)key.data, value);
208
209         data.data = (void*)value;
210         data.size = (uint32_t)strlen(value);
211
212         ret = database->put(database, NULL, &key, &data, replace ? 0 : DB_NOOVERWRITE);
213         if (ret == 0)
214                 afb_req_success(req, NULL, NULL);
215         else
216         {
217                 AFB_ERROR("can't %s key %s with %s", replace ? "replace" : "insert", (char*)key.data, (char*)data.data);
218                 afb_req_fail_f(req, "failed", "%s", db_strerror(ret));
219         }
220         free(key.data);
221 }
222
223 static void verb_insert(struct afb_req req)
224 {
225         put(req, 0);
226 }
227
228 static void verb_update(struct afb_req req)
229 {
230         put(req, 1);
231 }
232
233 static void verb_delete(struct afb_req req)
234 {
235         DBT key;
236         int ret;
237
238         if (get_key(req, &key))
239                 return;
240
241         AFB_INFO("delete: key=%s", (char*)key.data);
242
243         if ((ret = database->del(database, NULL, &key, 0)) == 0)
244                 afb_req_success_f(req, NULL, "db success: delete %s.", (char *)key.data);
245         else
246                 afb_req_fail_f(req, "Failed to delete datas.", "db fail: delete %s - %s", (char*)key.data, db_strerror(ret));
247
248         free(key.data);
249 }
250
251 static void verb_read(struct afb_req req)
252 {
253         DBT key;
254         DBT data;
255         int ret;
256
257         char value[4096];
258
259         struct json_object* result;
260         struct json_object* val;
261
262
263         if (get_key(req, &key))
264                 return;
265
266         AFB_INFO("read: key=%s", (char*)key.data);
267
268         data.data = value;
269         data.ulen = 4096;
270         data.flags = DB_DBT_USERMEM;
271
272         if ((ret = database->get(database, NULL, &key, &data, 0)) == 0)
273         {
274                 result = json_object_new_object();
275                 val = json_tokener_parse((char*)data.data);
276                 json_object_object_add(result, "value", val ? val : json_object_new_string((char*)data.data));
277
278                 afb_req_success_f(req, result, "db success: read %s=%s.", (char*)key.data, (char*)data.data);
279         }
280         else
281                 afb_req_fail_f(req, "Failed to read datas.", "db fail: read %s - %s", (char*)key.data, db_strerror(ret));
282
283         free(key.data);
284 }
285
286 // ----- Binding's configuration -----
287 /*
288 static const struct afb_auth ll_database_binding_auths[] = {
289 };
290 */
291
292 static const afb_verb_v2 ll_database_binding_verbs[]= {
293                 REGISTER_VERB(insert,   NULL, NULL, AFB_SESSION_NONE_V2),
294                 REGISTER_VERB(update,   NULL, NULL, AFB_SESSION_NONE_V2),
295                 REGISTER_VERB(delete,   NULL, NULL, AFB_SESSION_NONE_V2),
296                 REGISTER_VERB(read,             NULL, NULL, AFB_SESSION_NONE_V2),
297         { .verb = NULL}
298 };
299
300 const struct afb_binding_v2 afbBindingV2 = {
301                 .api = "ll-database",
302                 .specification = NULL,
303                 .verbs = ll_database_binding_verbs,
304                 .preinit = NULL,
305                 .init = ll_database_binding_init,
306                 .onevent = NULL,
307                 .noconcurrency = 0
308 };