OSDN Git Service

Merge commit 'android-4.0.4_r1.1' into ics-x86
[android-x86/system-extras.git] / su / db.c
1 /*
2 ** Copyright 2010, Adam Shanks (@ChainsDD)
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 <stdlib.h>
18 #include <sys/stat.h>
19 #include <limits.h>
20 #include <cutils/log.h>
21
22 #include <sqlite3.h>
23
24 #include "su.h"
25
26 // { int* pint; pint=(int*)data; ++(*pint); }
27
28 sqlite3 *database_init()
29 {
30     sqlite3 *db;
31     int rc;
32
33     rc = sqlite3_open_v2(REQUESTOR_DATABASE_PATH, &db, SQLITE_OPEN_READONLY, NULL);
34     if ( rc ) {
35         LOGE("Couldn't open database: %s", sqlite3_errmsg(db));
36         return NULL;
37     }
38
39     // Create an automatic busy handler in case the db is locked
40     sqlite3_busy_timeout(db, 1000);
41     return db;
42 }
43
44 int database_check(sqlite3 *db, struct su_initiator *from, struct su_request *to)
45 {
46     char sql[4096];
47     char *zErrmsg;
48     char **result;
49     int nrow,ncol;
50     int allow = DB_INTERACTIVE;
51
52     sqlite3_snprintf(
53         sizeof(sql), sql,
54         "SELECT _id,name,allow FROM apps WHERE uid=%u AND exec_uid=%u AND exec_cmd='%q';",
55         (unsigned)from->uid, to->uid, to->command
56     );
57
58     if (strlen(sql) >= sizeof(sql)-1)
59         return DB_DENY;
60
61     int error = sqlite3_get_table(db, sql, &result, &nrow, &ncol, &zErrmsg);
62     if (error != SQLITE_OK) {
63         LOGE("Database check failed with error message %s", zErrmsg);
64         if (error == SQLITE_BUSY) {
65             LOGE("Specifically, the database is busy");
66         }
67         return DB_DENY;
68     }
69
70     if (nrow == 0 || ncol != 3)
71         goto out;
72
73     if (strcmp(result[0], "_id") == 0 && strcmp(result[2], "allow") == 0) {
74         if (strcmp(result[5], "1") == 0) {
75             allow = DB_ALLOW;
76         } else if (strcmp(result[5], "-1") == 0){
77             allow = DB_INTERACTIVE;
78         } else {
79             allow = DB_DENY;
80         }
81     }
82
83 out:
84     sqlite3_free_table(result);
85
86     return allow;
87 }