Release version 0.25.2
[platform/core/appfw/pkgmgr-info.git] / tool / pkg-db-recovery.c
index 715d48a..f48d2b4 100644 (file)
 
 #define _GNU_SOURCE
 
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <glib.h>
+#include <stdbool.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
+#include <sys/stat.h>
 #include <sys/types.h>
+#include <sys/wait.h>
+#include <pwd.h>
+#include <unistd.h>
 
+#include <dlog.h>
 #include <sqlite3.h>
 #include <tzplatform_config.h>
 
+#include <pkgmgr_parser_db.h>
+#include <pkgmgr_parser_db_queries.h>
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#endif
+
+#define LOG_TAG "PKG_DB_RECOVERY"
+
+#ifndef APPFW_USER
+#define APPFW_USER "app_fw"
+#endif
+#ifndef OWNER_ROOT
+#define OWNER_ROOT 0
+#endif
 #define REGULAR_USER 5000
 #define MAX_QUERY_LEN  4096
+#define BUFSIZE 4096
 
 #define PKGMGR_PARSER_DB_FILE tzplatform_mkpath(TZ_SYS_DB, ".pkgmgr_parser.db")
 #define PKGMGR_CERT_DB_FILE tzplatform_mkpath(TZ_SYS_DB, ".pkgmgr_cert.db")
+#define NEED_RECOVERY_FILE tzplatform_mkpath(TZ_SYS_DB, ".need_pkg_recovery")
+
+#define GLOBAL_USER tzplatform_getuid(TZ_SYS_GLOBALAPP_USER)
+
+typedef struct user_info {
+       uid_t uid;
+       char *db_path;
+} user_info;
+
+static GList *user_info_list;
+
+char *string_trim_inplace(char *s) {
+       char *original = s;
+       size_t len = 0;
 
-static int __rollback_db(sqlite3 *db, const char *table_name)
+       while (isspace((unsigned char) *s))
+               s++;
+
+       if (*s) {
+               char *p = s;
+               while (*p)
+                       p++;
+               while (isspace((unsigned char) *(--p)));
+               p[1] = '\0';
+               len = (size_t) (p - s + 1);
+       }
+
+       if (len > MAX_QUERY_LEN)
+               return NULL;
+       return (s == original) ? s : memmove(original, s, len + 1);
+}
+
+static char *__get_dbpath(uid_t uid)
 {
-       static const char rollback_query_raw[] =
-                       "SELECT COUNT(*) FROM %s WHERE 1=0";
-       int ret;
+       const char *db_path;
+       char path[PATH_MAX];
+
+       db_path = tzplatform_getenv(TZ_SYS_DB);
+       if (db_path == NULL) {
+               LOGE("Failed to get TZ_SYS_DB path");
+               return NULL;
+       }
+
+       snprintf(path, sizeof(path), "%s/user/%d/.pkgmgr_parser.db", db_path, uid);
+       return strdup(path);
+}
+
+#define BUSY_WAITING_USEC (1000000 / 10 / 2) /* 0.05 sec */
+#define BUSY_WAITING_MAX 100 /* wait for max 5 sec */
+static int __db_busy_handler(void *data, int count)
+{
+       if (count < BUSY_WAITING_MAX) {
+               usleep(BUSY_WAITING_USEC);
+               return 1;
+       } else {
+               /* sqlite3_prepare_v2 will return SQLITE_BUSY */
+               return 0;
+       }
+}
+
+static bool __check_aborted(uid_t uid)
+{
+       char buf[BUFSIZE];
+
+       snprintf(buf, sizeof(buf), "%s_%d", NEED_RECOVERY_FILE, uid);
+       if (access(buf, F_OK) == 0) {
+               return true;
+       } else {
+               if (errno != ENOENT)
+                       LOGE("failed to access %s, errno: %d", buf, errno);
+               return false;
+       }
+}
+
+static void __create_need_to_recovery_file(uid_t uid)
+{
+       int fd;
+       char buf[BUFSIZE];
+
+       snprintf(buf, sizeof(buf), "%s_%d", NEED_RECOVERY_FILE, uid);
+       fd = open(buf, O_CREAT | O_WRONLY, S_IRWXU);
+       if (fd == -1)
+               LOGE("failed to create file: %s, errno: %d", buf, errno);
+       else
+               close(fd);
+}
+
+static void __remove_need_to_recovery_file(uid_t uid)
+{
+       char buf[BUFSIZE];
+
+       snprintf(buf, sizeof(buf), "%s_%d", NEED_RECOVERY_FILE, uid);
+       if (unlink(buf))
+               LOGE("failed to remove file: %s, errno: %d", buf, errno);
+}
+
+static bool __integrity_check(const char *db_path)
+{
+       int ret = -1;
        sqlite3_stmt *stmt = NULL;
-       char query[MAX_QUERY_LEN] = { '\0' };
+       const char *check_result;
+       static const char integrity_check_query[] =
+                       "PRAGMA integrity_check";
+       sqlite3 *db;
+
+       ret = sqlite3_open_v2(db_path, &db,
+                       SQLITE_OPEN_READWRITE, NULL);
+       if (ret != SQLITE_OK) {
+               LOGE("Failed to open db");
+               sqlite3_close_v2(db);
+               return false;
+       }
 
-       sqlite3_snprintf(MAX_QUERY_LEN, query, rollback_query_raw, table_name);
-       ret = sqlite3_prepare_v2(db, query, strlen(query), &stmt, NULL);
+       ret = sqlite3_busy_handler(db, __db_busy_handler, NULL);
        if (ret != SQLITE_OK) {
-               printf("Failed to recover db : %s\n", sqlite3_errmsg(db));
-               return -1;
+               LOGE("failed to register busy handler: %s",
+                               sqlite3_errmsg(db));
+               sqlite3_close_v2(db);
+               return ret;
+       }
+
+       ret = sqlite3_prepare_v2(db, integrity_check_query,
+                       strlen(integrity_check_query), &stmt, NULL);
+       if (ret != SQLITE_OK) {
+               LOGE("Failed to check integrity_check : %s", sqlite3_errmsg(db));
+               goto err;
        }
+
+       ret = sqlite3_step(stmt);
+       if (ret != SQLITE_ROW) {
+               LOGE("Failed to check integrity db :%s", sqlite3_errmsg(db));
+               goto err;
+       }
+
+       check_result = (const char *)sqlite3_column_text(stmt, 0);
+       if (!check_result) {
+               LOGE("Failed to check integrity db :%s", sqlite3_errmsg(db));
+               goto err;
+       }
+
+       if (strcasecmp(check_result, "ok") != 0) {
+               LOGE("db corrupted :%s", db_path);
+               goto err;
+       }
+
        sqlite3_finalize(stmt);
-       return 0;
+       sqlite3_close(db);
+       return true;
+
+err:
+       sqlite3_finalize(stmt);
+       sqlite3_close(db);
+       return false;
+}
+
+static void _xsystem(const char *argv[])
+{
+       int status = 0;
+       pid_t pid;
+
+       pid = fork();
+       switch (pid) {
+       case -1:
+               perror("fork failed");
+               return;
+       case 0:
+               /* child */
+               execvp(argv[0], (char *const *)argv);
+               _exit(-1);
+       default:
+               /* parent */
+               break;
+       }
+       if (waitpid(pid, &status, 0) == -1) {
+               perror("waitpid failed");
+               return;
+       }
+       if (WIFSIGNALED(status)) {
+               perror("signal");
+               return;
+       }
+       if (!WIFEXITED(status)) {
+               /* shouldn't happen */
+               perror("should not happen");
+               return;
+       }
+}
+
+static void __create_db(uid_t uid)
+{
+       char uid_string[11];
+       const char *create_db[] = { "/usr/bin/pkg-db-creator", uid_string, NULL};
+
+       snprintf(uid_string, sizeof(uid_string), "%d", (int)uid);
+       _xsystem(create_db);
+}
+
+static void __initdb(uid_t uid)
+{
+       char uid_string[11];
+       const char *initdb_rw[] = { "/usr/bin/pkg_initdb",
+                       "--recover-db", "--uid", uid_string, "--keep-db", NULL};
+       const char *initdb_ro[] =  { "/usr/bin/pkg_initdb",
+                       "--recover-db", "--keep-db", NULL};
+
+       __create_need_to_recovery_file(uid);
+       __create_db(uid);
+       snprintf(uid_string, sizeof(uid_string), "%d", (int)uid);
+       _xsystem((uid > REGULAR_USER) ? initdb_rw : initdb_ro);
+       __remove_need_to_recovery_file(uid);
+}
+
+static void __initdb_all()
+{
+       GList *tmp_list = NULL;
+       user_info *tmp_info;
+       __initdb(GLOBAL_USER);
+
+       for (tmp_list = user_info_list;
+                       tmp_list != NULL; tmp_list = g_list_next(tmp_list)) {
+               tmp_info = (user_info *)tmp_list->data;
+               if (!tmp_info)
+                       continue;
+               __initdb(tmp_info->uid);
+       }
 }
 
-static int __check_and_rollback_db(const char *db_path, const char *table_name)
+static void __check_user_db()
 {
+       GList *tmp_list = NULL;
+       user_info *tmp_info;
+       bool need_recovery;
+
+       for (tmp_list = user_info_list;
+                       tmp_list != NULL; tmp_list = g_list_next(tmp_list)) {
+               need_recovery = false;
+               tmp_info = (user_info *)tmp_list->data;
+               if (!tmp_info)
+                       continue;
+               if (!__integrity_check(tmp_info->db_path)) {
+                       LOGE("User db for %d has corrupted", (int)tmp_info->uid);
+                       need_recovery = true;
+               } else if (__check_aborted(tmp_info->uid)) {
+                       need_recovery = true;
+               }
+
+               if (need_recovery)
+                       __initdb(tmp_info->uid);
+       }
+}
+
+static void _free_user_info(gpointer data)
+{
+       user_info *info = (user_info *)data;
+       free(info->db_path);
+       free(info);
+}
+
+static void _get_user_list()
+{
+       DIR *dir;
+       struct dirent *ent;
+       struct stat stats;
+       char traverse_path[PATH_MAX];
+       char abs_dirname[PATH_MAX];
+       const char *db_path;
+       int ret;
+       uid_t uid;
+       user_info *info;
+
+       db_path = tzplatform_getenv(TZ_SYS_DB);
+       if (db_path == NULL) {
+               LOGE("Failed to get TZ_SYS_DB path");
+               return;
+       }
+
+       snprintf(traverse_path, sizeof(traverse_path), "%s/user", db_path);
+       dir = opendir(traverse_path);
+       if (!dir) {
+               LOGE("Failed to open dir: %d (%s)", errno, traverse_path);
+               return;
+       }
+
+       while ((ent = readdir(dir)) != NULL) {
+               ret = snprintf(abs_dirname, PATH_MAX, "%s/%s", traverse_path,
+                        ent->d_name);
+               if (ret < 0 || ret > PATH_MAX) {
+                       LOGE("snprintf fail");
+                       closedir(dir);
+                       return;
+               }
+
+               ret = stat(abs_dirname, &stats);
+               if (ret != 0) {
+                       LOGE("failed to stat: %d (%s)", errno, abs_dirname);
+                       continue;
+               }
+
+               if (!strcmp(".", ent->d_name) || !strcmp("..", ent->d_name) ||
+                               !S_ISDIR(stats.st_mode))
+                       continue;
+               uid = (uid_t)atoi(ent->d_name);
+               if (uid < REGULAR_USER)
+                       continue;
+
+               info = calloc(1, sizeof(user_info));
+               if (!info) {
+                       closedir(dir);
+                       return;
+               }
+
+               info->uid = uid;
+               info->db_path = __get_dbpath(uid);
+               user_info_list = g_list_prepend(user_info_list, info);
+       }
+
+       closedir(dir);
+}
+
+static bool __check_db_schema(const char *db_path,
+               const char **db_tables, const char **init_queries) {
        int ret = -1;
+       int i;
+       sqlite3_stmt *stmt = NULL;
+       const char *check_result;
+       char *schema_in_library, *schema_in_db;
+       static const char table_schema_query[] =
+                       "SELECT sql from sqlite_master WHERE name=?";
        sqlite3 *db;
+       char *schema_lib_tmp;
+       char *schema_lib_ptr;
+       char *schema_db_tmp;
+       char *schema_db_ptr;
+       char *line_db;
+       char *line_library;
 
        ret = sqlite3_open_v2(db_path, &db,
-                       SQLITE_OPEN_READWRITE, NULL);
+                       SQLITE_OPEN_READONLY, NULL);
        if (ret != SQLITE_OK) {
-               printf("Failed to open db\n");
-               return -1;
+               LOGE("Failed to open db");
+               sqlite3_close_v2(db);
+               return false;
+       }
+
+       ret = sqlite3_busy_handler(db, __db_busy_handler, NULL);
+       if (ret != SQLITE_OK) {
+               LOGE("failed to register busy handler: %s",
+                               sqlite3_errmsg(db));
+               sqlite3_close_v2(db);
+               return ret;
+       }
+       for (i = 0; db_tables[i] != NULL; i++) {
+               ret = sqlite3_prepare_v2(db, table_schema_query,
+                               strlen(table_schema_query), &stmt, NULL);
+               if (ret != SQLITE_OK) {
+                       LOGE("Failed to check db schema : %s",
+                                       sqlite3_errmsg(db));
+                       goto err;
+               }
+
+               ret = sqlite3_bind_text(stmt, 1,
+                               db_tables[i],-1, SQLITE_STATIC);
+
+               ret = sqlite3_step(stmt);
+               if (ret != SQLITE_ROW) {
+                       LOGE("Failed to check db schema :%s",
+                                       sqlite3_errmsg(db));
+                       goto err;
+               }
+
+               check_result = (const char *)sqlite3_column_text(stmt, 0);
+               if (!check_result) {
+                       LOGE("Failed to check db schema :%s",
+                                       sqlite3_errmsg(db));
+                       goto err;
+               }
+
+               schema_in_library = strstr(init_queries[i], db_tables[i]);
+               if (schema_in_library == NULL) {
+                       LOGE("Failed to get initialization query from library");
+                       goto err;
+               }
+               schema_lib_tmp = strdup(schema_in_library);
+               schema_lib_ptr = schema_lib_tmp;
+               if (schema_lib_tmp == NULL) {
+                       LOGE("Out of memory");
+                       goto err;
+               }
+
+               schema_in_db = strstr(check_result, db_tables[i]);
+               if (schema_in_db == NULL) {
+                       LOGE("Failed to get initialization query from db");
+                       free(schema_lib_ptr);
+                       goto err;
+               }
+               schema_db_tmp = strdup(schema_in_db);
+               schema_db_ptr = schema_db_tmp;
+               if (schema_db_tmp == NULL) {
+                       LOGE("Out of memory");
+                       free(schema_lib_ptr);
+                       goto err;
+               }
+
+               while (true) {
+                       line_db = strsep(&schema_db_tmp, ",");
+                       line_library = strsep(&schema_lib_tmp, ",");
+                       if (line_db == NULL || line_library == NULL)
+                               break;
+
+                       if (string_trim_inplace(line_db) == NULL ||
+                                       string_trim_inplace(line_library) == NULL)
+                               break;
+
+                       ret = strcmp(string_trim_inplace(line_db),
+                                       string_trim_inplace(line_library));
+                       if (ret != 0)
+                               break;
+               }
+
+               free(schema_lib_ptr);
+               free(schema_db_ptr);
+
+               if (ret != 0) {
+                       LOGE("Broken schema detected in table[%s], query[%s]",
+                                       db_tables[i], schema_in_db);
+                       goto err;
+               }
+
+               sqlite3_finalize(stmt);
+               stmt = NULL;
        }
 
-       ret = __rollback_db(db, table_name);
-       if (ret != 0)
-               printf("Failed to rollback db\n");
+       sqlite3_close(db);
+       return true;
 
+err:
+       sqlite3_finalize(stmt);
        sqlite3_close(db);
-       return ret;
+       return false;
 }
 
 static void _check_db()
 {
-       int ret;
+       int need_recovery = false;
 
-       ret = __check_and_rollback_db(PKGMGR_PARSER_DB_FILE, "package_info");
-       if (ret != 0)
-               printf("Failed to check and rollback parser db\n");
+       if (!__integrity_check(PKGMGR_CERT_DB_FILE)) {
+               LOGE("Cert db corrupted. restore entire pkgmgr db");
+               need_recovery = true;
+       } else if (!__integrity_check(PKGMGR_PARSER_DB_FILE)) {
+               LOGE("Global parser db corrupted. restore entire pkgmgr db");
+               need_recovery = true;
+       } else if (__check_aborted(GLOBAL_USER)) {
+               LOGE("Previous recovery was aborted. restore entire pkgmgr db");
+               need_recovery = true;
+       } else if (!__check_db_schema(PKGMGR_PARSER_DB_FILE,
+                       PARSER_TABLES, PARSER_INIT_QUERIES)) {
+               LOGE("Global parser db schema was broken. restore entire pkgmgr db");
+               need_recovery = true;
+       } else if (!__check_db_schema(PKGMGR_CERT_DB_FILE,
+                       CERT_TABLES, CERT_INIT_QUERIES)) {
+               LOGE("Cert db schema was broken. restore entire pkgmgr db");
+               need_recovery = true;
+       }
 
-       ret = __check_and_rollback_db(PKGMGR_CERT_DB_FILE, "package_cert_info");
-       if (ret != 0)
-               printf("Failed to check and rollback cert db\n");
-}
+       if (need_recovery) {
+               __initdb_all();
+               return;
+       }
 
+       __check_user_db();
+}
 
 int main(int argc, char *argv[])
 {
        if ((int)getuid() > REGULAR_USER) {
-               printf("This cmd is not allowed for regular user\n");
+               LOGE("This cmd is not allowed for regular user");
                return -1;
        }
 
+       _get_user_list();
        _check_db();
 
+       g_list_free_full(user_info_list, _free_user_info);
        return 0;
 }