Add multi-user feature
[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 <unistd.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <stdio.h>
21 #include <grp.h>
22 #include <pwd.h>
23
24 #include <tzplatform_config.h>
25 #include <sys/stat.h>
26 #include <db-util.h>
27
28 #include "rua_util.h"
29
30 #define DBPATH_LEN_MAX  4096
31
32 char *_rua_util_get_db_path(uid_t uid, char *db_name)
33 {
34         struct group *grpinfo = NULL;
35         char db_path[DBPATH_LEN_MAX] = {0, };
36         struct passwd *userinfo = getpwuid(uid);
37         if (userinfo == NULL) {
38                 LOGE("getpwuid(%d) returns NULL !", uid);
39                 return NULL;
40         }
41         grpinfo = getgrnam("users");
42         if (grpinfo == NULL) {
43                 LOGE("getgrnam(users) returns NULL !");
44                 return NULL;
45         }
46
47         if (grpinfo->gr_gid != userinfo->pw_gid) {
48                 LOGE("UID [%d] does not belong to 'users' group!", uid);
49                 return NULL;
50         }
51         snprintf(db_path, sizeof(db_path), "%s/.applications/dbspace/%s", userinfo->pw_dir, db_name);
52         LOGD("db path %s", db_path);
53         return db_path;
54 }
55
56 int _rua_util_open_db(sqlite3 **db, int flags, uid_t uid, char *db_name)
57 {
58         int r;
59         char *db_path = _rua_util_get_db_path(uid, db_name);
60         r = db_util_open_with_options(db_path, db, flags, NULL);
61         if (r) {
62                 LOGE("db util open error(%d/%d/%d/%s)", r,
63                         sqlite3_errcode(*db),
64                         sqlite3_extended_errcode(*db),
65                         sqlite3_errmsg(*db));
66                 return -1;
67         }
68         return r;
69 }
70
71 int _rua_util_check_uid(uid_t target_uid)
72 {
73         uid_t uid = getuid();
74         if (uid > BASE_UID && uid != target_uid) {
75                 LOGE("Invalid UID : %d, target UID : %d", uid, target_uid);
76                 return -1;
77         }
78         return 0;
79 }