Replace json_object_from_file to inputJsonFilie
[apps/agl-service-windowmanager.git] / src / policy_manager / policy_manager.cpp
1 /*
2  * Copyright (c) 2018 TOYOTA MOTOR CORPORATION
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17
18 #include <fstream>
19 #include <sstream>
20 #include <istream>
21 #include <json-c/json.h>
22 #include "policy_manager.hpp"
23 #if 0
24 extern "C" {
25 #include "dummy_stm.h"
26 }
27 #endif
28 #include "hmi-debug.h"
29
30
31 PolicyManager::PolicyManager() :
32   eventname2no_(),
33   categoryname2no_(),
34   areaname2no_(),
35   role2category_(),
36   category2role_(),
37   role2defaultarea_(),
38   current_state_()
39 {
40     HMI_DEBUG("wm:pm", "Call");
41 }
42
43 int PolicyManager::initialize() {
44     HMI_DEBUG("wm:pm", "Call");
45
46     int ret = 0;
47
48     // Create convert map
49     for (unsigned int i=0; i<STM_NUM_EVT; i++) {
50         HMI_DEBUG("wm:pm", "event name:%s no:%d", stm::gStmEventName[i], stm::gStmEventNo[i]);
51         this->eventname2no_[stm::gStmEventName[i]] = stm::gStmEventNo[i];
52     }
53
54     for (unsigned int i=0; i<STM_NUM_CTG; i++) {
55         HMI_DEBUG("wm:pm", "category name:%s no:%d", stm::gStmCategoryName[i], stm::gStmCategoryNo[i]);
56         this->categoryname2no_[stm::gStmCategoryName[i]] = stm::gStmCategoryNo[i];
57     }
58
59     for (unsigned int i=0; i<STM_NUM_ARA; i++) {
60         HMI_DEBUG("wm:pm", "area name:%s no:%d", stm::gStmAreaName[i], stm::gStmAreaNo[i]);
61         this->areaname2no_[stm::gStmAreaName[i]] = stm::gStmAreaNo[i];
62     }
63
64     // Load role.db
65     ret = loadRoleDb();
66     if (0 > ret) {
67         HMI_ERROR("wm:pm", "Load role.db Error!!");
68         return ret;
69     }
70
71     // Initialize StateTransitioner
72     stm::stmInitialize();
73
74     return ret;
75 }
76
77 int PolicyManager::checkPolicy(json_object* json_in, json_object** json_out) {
78     HMI_DEBUG("wm:pm", "Call");
79
80     // Check arguments
81     if ((nullptr == json_in) || (nullptr == json_out)) {
82         HMI_ERROR("wm:pm", "Argument is NULL!!");
83         return -1;
84     }
85
86     // Get event from json_object
87     const char* event = this->getStringFromJson(json_in, "event");
88     int event_no = 0;
89     if (nullptr != event) {
90         // Convert name to number
91         event_no = this->eventname2no_[event];
92         HMI_DEBUG("wm:pm", "event(%s:%d)", event, event_no);
93     }
94
95     // Get role from json_object
96     const char* role = this->getStringFromJson(json_in, "role");
97     int category_no = 0;
98     if (nullptr != role) {
99         HMI_DEBUG("wm:pm", "role(%s)", role);
100
101         // Convert role to category
102         const char* category = this->role2category_[role].c_str();
103         if (0 == strcmp("", category)) {
104             HMI_ERROR("wm:pm", "Error!!");
105             return -1;
106         }
107         HMI_DEBUG("wm:pm", "category(%s)", category);
108
109         // Convert name to number
110         category_no = categoryname2no_[category];
111         HMI_DEBUG("wm:pm", "role(%s), category(%s:%d)", role, category, category_no);
112     }
113
114     // Get areat from json_object
115     const char* area = this->getStringFromJson(json_in, "area");
116     int area_no = 0;
117     if (nullptr != area) {
118         // Convert name to number
119         area_no = areaname2no_[area];
120         HMI_DEBUG("wm:pm", "area(%s:%d)", area, area_no);
121     }
122
123     // Transition state
124     HMI_DEBUG("wm:pm", "set event:0x%x", (event_no | category_no | area_no));
125     int ret = stm::stmTransitionState((event_no | category_no | area_no),
126                                        &(this->current_state_));
127     if (0 > ret) {
128         HMI_ERROR("wm:pm", "Error!!");
129         return -1;
130     }
131
132     // Create result
133     // {
134     //     "parking_brake": {
135     //         "is_changed": <bool>,
136     //         "state": <const char*>
137     //     },
138     HMI_DEBUG("wm", "parking brake state (is_changed:%d state:%d:%s)",
139               this->current_state_.parking_brake.is_changed,
140               this->current_state_.parking_brake.state,
141               stm::gStmParkingBrakeStateNo2Name[this->current_state_.parking_brake.state]);
142     this->addStateToJson("parking_brake",
143                          this->current_state_.parking_brake.is_changed,
144                          stm::gStmParkingBrakeStateNo2Name[this->current_state_.parking_brake.state],
145                          json_out);
146
147     //     "car": {
148     //         "is_changed": <bool>,
149     //         "state": <const char*>
150     //     },
151     HMI_DEBUG("wm", "car state (is_changed:%d state:%d:%s)",
152               this->current_state_.car.is_changed,
153               this->current_state_.car.state,
154               stm::gStmCarStateNo2Name[this->current_state_.car.state]);
155     this->addStateToJson("car",
156                          this->current_state_.car.is_changed,
157                          stm::gStmCarStateNo2Name[this->current_state_.car.state],
158                          json_out);
159
160     //     "lamp": {
161     //         "is_changed": <bool>,
162     //         "state": <const char*>
163     //     },
164     HMI_DEBUG("wm", "lamp state (is_changed:%d state:%d:%s)",
165               this->current_state_.lamp.is_changed,
166               this->current_state_.lamp.state,
167               stm::gStmLampStateNo2Name[this->current_state_.lamp.state]);
168     this->addStateToJson("lamp",
169                          this->current_state_.lamp.is_changed,
170                          stm::gStmLampStateNo2Name[this->current_state_.lamp.state],
171                          json_out);
172
173     //     "layers": [
174     //         {
175     //             "on_screen": {
176     //                 "is_changed": <bool>,
177     //                 "state": <const char*>
178     //             }
179     //         },
180     json_object* json_layer = json_object_new_array();
181     json_object* json_tmp = json_object_new_object();
182     this->addStateToJson("on_screen",
183                          this->current_state_.layer.on_screen.is_changed,
184                          stm::gStmLayoutNo2Name[this->current_state_.layer.on_screen.state],
185                          &json_tmp);
186     json_object_array_add(json_layer, json_tmp);
187
188     //         {
189     //             "restriction": {
190     //                 "is_changed": <bool>,
191     //                 "state": <const char*>
192     //             }
193     //         },
194     json_tmp = json_object_new_object();
195     this->addStateToJson("restriction",
196                          this->current_state_.layer.restriction.is_changed,
197                          stm::gStmLayoutNo2Name[this->current_state_.layer.restriction.state],
198                          &json_tmp);
199     json_object_array_add(json_layer, json_tmp);
200
201     //         {
202     //             "apps": {
203     //                 "is_changed": <bool>,
204     //                 "state": <const char*>
205     //             }
206     //         },
207     json_tmp = json_object_new_object();
208     this->addStateToJson("apps",
209                          this->current_state_.layer.apps.is_changed,
210                          stm::gStmLayoutNo2Name[this->current_state_.layer.apps.state],
211                          &json_tmp);
212     json_object_array_add(json_layer, json_tmp);
213
214     //         {
215     //             "homescreen": {
216     //                 "is_changed": <bool>,
217     //                 "state": <const char*>
218     //             }
219     //         },
220     //     ]
221     // }
222     json_tmp = json_object_new_object();
223     this->addStateToJson("homescreen",
224                          this->current_state_.layer.homescreen.is_changed,
225                          stm::gStmLayoutNo2Name[this->current_state_.layer.homescreen.state],
226                          &json_tmp);
227     json_object_array_add(json_layer, json_tmp);
228
229     // Add json array of layer
230     json_object_object_add(*json_out, "layers", json_layer);
231
232     return 0;
233 }
234
235 std::string PolicyManager::roleToCategory(const char* role) {
236     return this->role2category_[role];
237 }
238
239 extern const char* kDefaultRoleDb;
240 int PolicyManager::loadRoleDb() {
241     HMI_DEBUG("wm:pm", "Call");
242
243     std::string file_name;
244
245     // Get afm application installed dir
246     char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR");
247     HMI_DEBUG("wm:pm", "afm_app_install_dir:%s", afm_app_install_dir);
248
249     if (!afm_app_install_dir) {
250         HMI_ERROR("wm:pm", "AFM_APP_INSTALL_DIR is not defined");
251     }
252     else {
253         file_name = std::string(afm_app_install_dir) + std::string("/etc/role.db");
254     }
255
256     // Load role.db
257     json_object* json_obj;
258     int ret = this->inputJsonFilie(file_name.c_str(), &json_obj);
259     if (0 > ret) {
260         HMI_ERROR("wm:pm", "Could not open role.db, so use default role information");
261         json_obj = json_tokener_parse(kDefaultRoleDb);
262     }
263     HMI_DEBUG("wm:pm", "json_obj dump:%s", json_object_get_string(json_obj));
264
265     json_object* json_roles;
266     if (!json_object_object_get_ex(json_obj, "roles", &json_roles)) {
267         HMI_ERROR("wm:pm", "Parse Error!!");
268         return -1;
269     }
270
271     int len = json_object_array_length(json_roles);
272     HMI_DEBUG("wm:pm", "json_cfg len:%d", len);
273     HMI_DEBUG("wm:pm", "json_cfg dump:%s", json_object_get_string(json_roles));
274
275     json_object* json_tmp;
276     const char* category;
277     const char* roles;
278     const char* areas;
279     for (int i=0; i<len; i++) {
280         json_tmp = json_object_array_get_idx(json_roles, i);
281
282         category = this->getStringFromJson(json_tmp, "category");
283         roles =  this->getStringFromJson(json_tmp, "role");
284         areas =  this->getStringFromJson(json_tmp, "area");
285
286         if ((nullptr == category) || (nullptr == roles) || (nullptr == areas)) {
287             HMI_ERROR("wm:pm", "Parse Error!!");
288             return -1;
289         }
290
291         // Parse roles by '|'
292         std::vector<std::string> vct_roles;
293         vct_roles = this->parseString(std::string(roles), '|');
294
295         // Parse areas by '|'
296         std::vector<std::string> vct_areas;
297         vct_areas = this->parseString(std::string(areas), '|');
298
299         // Set role, category, default area
300         for (auto itr = vct_roles.begin(); itr != vct_roles.end(); ++itr) {
301             // Delete space from role and area name
302             std::string role = this->deleteSpace(*itr);
303             std::string area = this->deleteSpace(vct_areas[0]);
304
305             this->role2category_[role] = std::string(category);
306             this->role2defaultarea_[role] = area;
307         }
308
309         this->category2role_[std::string(category)] = std::string(roles);
310     }
311
312     // Check
313     HMI_DEBUG("wm:pm", "Check role2category_");
314     for (auto& x:this->role2category_){
315         HMI_DEBUG("wm:pm", "key:%s, val:%s", x.first.c_str(), x.second.c_str());
316     }
317
318     HMI_DEBUG("wm:pm", "Check role2defaultarea_");
319     for (auto& x:this->role2defaultarea_){
320         HMI_DEBUG("wm:pm", "key:%s, val:%s", x.first.c_str(), x.second.c_str());
321     }
322
323     HMI_DEBUG("wm:pm", "Check category2role_");
324     for (auto& x:this->category2role_){
325         HMI_DEBUG("wm:pm", "key:%s, val:%s", x.first.c_str(), x.second.c_str());
326     }
327
328     return 0;
329 }
330
331 // TODO:
332 // This function will be removed because json_helper has same function.
333 // json_helper should be library.
334 const char* PolicyManager::getStringFromJson(json_object* obj, const char* key) {
335     if ((nullptr == obj) || (nullptr == key)) {
336         HMI_ERROR("wm:pm", "Argument is nullptr!!!");
337         return nullptr;
338     }
339
340     json_object* tmp;
341     if (!json_object_object_get_ex(obj, key, &tmp)) {
342         HMI_DEBUG("wm:pm", "Not found key \"%s\"", key);
343         return nullptr;
344     }
345
346     return json_object_get_string(tmp);
347 }
348
349 // TODO:
350 // This function will be removed because json_helper has same function.
351 // json_helper should be library.
352 int PolicyManager::inputJsonFilie(const char* file, json_object** obj) {
353     const int input_size = 128;
354     int ret = -1;
355
356     if ((nullptr == file) || (nullptr == obj)) {
357         HMI_ERROR("wm:jh", "Argument is nullptr!!!");
358         return ret;
359     }
360
361     HMI_DEBUG("wm:jh", "Input file: %s", file);
362
363     // Open json file
364     FILE *fp = fopen(file, "rb");
365     if (nullptr == fp) {
366         HMI_ERROR("wm:jh", "Could not open file");
367         return ret;
368     }
369
370     // Parse file data
371     struct json_tokener *tokener = json_tokener_new();
372     enum json_tokener_error json_error;
373     char buffer[input_size];
374     int block_cnt = 1;
375     while (1) {
376         size_t len = fread(buffer, sizeof(char), input_size, fp);
377         *obj = json_tokener_parse_ex(tokener, buffer, len);
378         if (nullptr != *obj) {
379             HMI_DEBUG("wm:jh", "File input is success");
380             ret = 0;
381             break;
382         }
383
384         json_error = json_tokener_get_error(tokener);
385         if ((json_tokener_continue != json_error)
386             || (input_size > len)) {
387             HMI_ERROR("wm:jh", "Failed to parse file (byte:%d err:%s)",
388                       (input_size * block_cnt), json_tokener_error_desc(json_error));
389             HMI_ERROR("wm:jh", "\n%s", buffer);
390             *obj = nullptr;
391             break;
392         }
393         block_cnt++;
394     }
395
396     // Close json file
397     fclose(fp);
398
399     // Free json_tokener
400     json_tokener_free(tokener);
401
402     return ret;
403 }
404
405 void PolicyManager::addStateToJson(
406   const char* key, int is_changed, const char* state, json_object** json_out) {
407     if ((nullptr == key) || (nullptr == state) || (nullptr == json_out)) {
408         HMI_ERROR("wm:pm", "Argument is nullptr!!!");
409         return;
410     }
411
412     json_object* json_obj = json_object_new_object();
413     json_object_object_add(json_obj, "is_changed", json_object_new_boolean(is_changed));
414     if (is_changed) {
415         HMI_DEBUG("wm:pm", "%s: state changed (%s)", key, state);
416         json_object_object_add(json_obj, "state", json_object_new_string(state));
417     }
418     json_object_object_add(*json_out, key, json_obj);
419 }
420
421 std::vector<std::string> PolicyManager::parseString(std::string str, char delimiter) {
422     // Parse string by delimiter
423     std::vector<std::string> vct;
424     std::stringstream ss{str};
425     std::string buf;
426     while (std::getline(ss, buf, delimiter)) {
427       if (!buf.empty()) {
428         vct.push_back(buf);
429       }
430     }
431     return vct;
432 }
433
434 std::string PolicyManager::deleteSpace(std::string str) {
435     std::string ret = str;
436     size_t pos;
437     while ((pos = ret.find_first_of(" ")) != std::string::npos) {
438       ret.erase(pos, 1);
439     }
440     return ret;
441 }
442
443 const char* kDefaultRoleDb = "{ \
444     \"roles\":[ \
445     { \
446         \"category\": \"homescreen\", \
447         \"role\": \"homescreen\", \
448         \"area\": \"full\", \
449     }, \
450     { \
451         \"category\": \"map\", \
452         \"role\": \"map\", \
453         \"area\": \"full | normal | split.main\", \
454     }, \
455     { \
456         \"category\": \"general\", \
457         \"role\": \"poi | music | video | browser | sdl | settings | mixer | radio | hvac | dashboard | debug\", \
458         \"area\": \"normal\", \
459     }, \
460     { \
461         \"category\": \"phone\", \
462         \"role\": \"phone\", \
463         \"area\": \"normal\", \
464     }, \
465     { \
466         \"category\": \"splitable\", \
467         \"role\": \"splitable1 | splitable2\", \
468         \"area\": \"normal | split.main | split.sub\", \
469     }, \
470     { \
471         \"category\": \"popup\", \
472         \"role\": \"popup\", \
473         \"area\": \"on_screen\", \
474     }, \
475     { \
476         \"category\": \"system_alert\", \
477         \"role\": \"system_alert\", \
478         \"area\": \"on_screen\", \
479     }, \
480     { \
481         \"category\": \"tbt\", \
482         \"role\": \"tbt\", \
483         \"area\": \"hud\", \
484     } \
485     ] \
486 }";