Add internal APIs for system daemon
[platform/core/appfw/librua.git] / src / rua_util.c
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd. All rights reserved.
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 #include <linux/limits.h>
18 #include <unistd.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <stdio.h>
22 #include <grp.h>
23 #include <pwd.h>
24
25 #include <sys/stat.h>
26 #include <db-util.h>
27 #include <tzplatform_config.h>
28
29 #include "rua_util.h"
30 #include "rua_internal.h"
31
32 char *_rua_util_get_db_path(uid_t uid, char *db_name)
33 {
34         char db_path[PATH_MAX];
35         const char *db_path_prefix;
36
37         if (strcmp(db_name, RUA_DB_NAME) == 0) {
38                 snprintf(db_path, sizeof(db_path), "/run/aul/dbspace/%d/%s",
39                         uid, db_name);
40         } else {
41                 tzplatform_set_user(uid);
42                 db_path_prefix = tzplatform_getenv(TZ_USER_DB);
43                 tzplatform_reset_user();
44                 snprintf(db_path, sizeof(db_path), "%s/%s", db_path_prefix, db_name);
45         }
46         LOGD("db path %s", db_path);
47         return strdup(db_path);
48 }
49
50 int _rua_util_open_db(sqlite3 **db, int flags, uid_t uid, char *db_name)
51 {
52         int r;
53         char *db_path;
54
55         db_path = _rua_util_get_db_path(uid, db_name);
56         if (db_path == NULL) {
57                 LOGE("out of memory _rua_util_get_db_path fail");
58                 return -1;
59         }
60
61         r = db_util_open_with_options(db_path, db, flags, NULL);
62         if (r) {
63                 LOGE("db util open error(%d/%d/%d/%s)", r,
64                         sqlite3_errcode(*db),
65                         sqlite3_extended_errcode(*db),
66                         sqlite3_errmsg(*db));
67                 free(db_path);
68                 return -1;
69         }
70
71         free(db_path);
72
73         return r;
74 }
75
76 int _rua_util_check_uid(uid_t target_uid)
77 {
78         uid_t uid = getuid();
79
80         if (uid > BASE_UID && uid != target_uid) {
81                 LOGE("Invalid UID : %d, target UID : %d", uid, target_uid);
82                 return -1;
83         }
84         return 0;
85 }