072a9f9b81e6ae9854ef7268a95a9f1787c83a08
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_database.cpp
1 /*
2  * Copyright (c) 2011 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  * @file    task_new_db_insert.cpp
18  * @author  Lukasz Wrzosek(l.wrzosek@samsung.com)
19  * @author  Soyoung kim(sy037.kim@samsung.com)
20  * @version 1.0
21  * @brief   Implementation file for installer task database updating for widget
22  * update
23  */
24 #include <unistd.h>
25 #include <time.h>
26 #include <sys/stat.h>
27 #include <widget_install/task_database.h>
28 #include <widget_install/job_widget_install.h>
29 #include <widget_install/widget_install_errors.h>
30 #include <widget_install/widget_install_context.h>
31 #include <web-provider-info.h>
32 #include <dpl/wrt-dao-rw/widget_dao.h>
33 #include <dpl/wrt-dao-ro/vconf_config.h>
34 #include <dpl/foreach.h>
35 #include <dpl/utils/wrt_utility.h>
36 #include <dpl/log/log.h>
37 #include <dpl/assert.h>
38 #include <wrt-commons/security-origin-dao/security_origin_dao.h>
39 #include <string>
40 #include <sstream>
41 #include <ace_api_install.h>
42 #include <ace_registration.h>
43 #include <errno.h>
44 #include <string.h>
45 #include <vconf.h>
46 #include <map>
47
48 using namespace WrtDB;
49
50 namespace Jobs {
51 namespace WidgetInstall {
52 TaskDatabase::TaskDatabase(InstallerContext& context) :
53     DPL::TaskDecl<TaskDatabase>(this),
54     m_context(context),
55     m_handleToRemove(INVALID_WIDGET_HANDLE),
56     m_handle(INVALID_WIDGET_HANDLE)
57 {
58     AddStep(&TaskDatabase::StepRegisterExternalFiles);
59     AddStep(&TaskDatabase::StepWrtDBInsert);
60     AddStep(&TaskDatabase::StepAceDBInsert);
61     AddStep(&TaskDatabase::StepSecurityOriginDBInsert);
62     AddStep(&TaskDatabase::StepRemoveExternalFiles);
63     AddStep(&TaskDatabase::StepCreateVconf);
64     AddStep(&TaskDatabase::StepLiveboxDBInsert);
65
66     AddAbortStep(&TaskDatabase::StepAbortDBInsert);
67 }
68
69 void TaskDatabase::StepWrtDBInsert()
70 {
71     Try
72     {
73         /* Set install Time */
74         time(&m_context.widgetConfig.installedTime);
75
76         if (m_context.existingWidgetInfo.isExist) { //update
77             LogInfo("Registering widget... (update)");
78             Try
79             {
80                 m_handleToRemove = WidgetDAOReadOnly::getHandle(
81                         m_context.widgetConfig.tzAppid);
82             }
83             Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
84             {
85                 LogError(
86                     "Given tizenId not found for update installation (Same GUID?)");
87                 ThrowMsg(Exceptions::InvalidPackage,
88                          "Given tizenId not found for update installation");
89             }
90             WidgetDAO::registerOrUpdateWidget(
91                 m_context.widgetConfig.tzAppid,
92                 m_context.widgetConfig,
93                 m_context.wacSecurity);
94             m_handle = WidgetDAOReadOnly::getHandle(
95                     m_context.widgetConfig.tzAppid);
96         } else { //new installation
97             LogInfo("Registering widget...");
98             WidgetDAO::registerWidget(
99                 m_context.widgetConfig.tzAppid,
100                 m_context.widgetConfig,
101                 m_context.wacSecurity);
102             m_handle = WidgetDAOReadOnly::getHandle(
103                     m_context.widgetConfig.tzAppid);
104         }
105
106         FOREACH(cap, m_context.staticPermittedDevCaps) {
107             LogInfo(
108                 "staticPermittedDevCaps : " << cap->first
109                                             << " smack status: " <<
110                 cap->second);
111         }
112
113         LogInfo("Widget registered");
114     }
115     Catch(WidgetDAO::Exception::DatabaseError)
116     {
117         LogError("Database failure!");
118         ReThrowMsg(Exceptions::InsertNewWidgetFailed, "Database failure!");
119     }
120     Catch(DPL::DB::SqlConnection::Exception::Base)
121     {
122         LogError("Database failure!");
123         ReThrowMsg(Exceptions::InsertNewWidgetFailed, "Database failure!");
124     }
125 }
126
127 void TaskDatabase::StepAceDBInsert()
128 {
129     LogDebug("Inserting Ace database entry. New handle: " << m_handle);
130     if (INVALID_WIDGET_HANDLE != m_handleToRemove) {
131         LogDebug("Removing old insallation. Handle: " << m_handleToRemove);
132         if (ACE_OK != ace_unregister_widget(
133                 static_cast<ace_widget_handle_t>(m_handleToRemove)))
134         {
135             LogWarning(
136                 "Error while removing ace entry for previous insallation");
137         }
138     }
139
140     if (!AceApi::registerAceWidget(m_handle, m_context.widgetConfig,
141                                    m_context.wacSecurity.getCertificateList()))
142     {
143         LogError("ace database insert failed");
144         ThrowMsg(Exceptions::UpdateFailed,
145                  "Update failure. ace_register_widget failed");
146     }
147     LogDebug("Ace data inserted");
148 }
149
150 void TaskDatabase::StepSecurityOriginDBInsert()
151 {
152     LogDebug("Create Security origin database");
153     // automatically create security origin database
154     using namespace SecurityOriginDB;
155     SecurityOriginDAO dao(m_context.locations->getPkgId());
156
157     // Checking privilege list for setting security origin exception data
158     FOREACH(it, m_context.widgetConfig.configInfo.privilegeList) {
159         std::map<std::string, Feature>::const_iterator result =
160             g_W3CPrivilegeTextMap.find(DPL::ToUTF8String(it->name));
161         if (result != g_W3CPrivilegeTextMap.end()) {
162             dao.setPrivilegeSecurityOriginData(result->second);
163         }
164     }
165
166     m_context.job->UpdateProgress(
167         InstallerContext::INSTALL_NEW_DB_INSERT,
168         "New Widget DB UPDATE Finished");
169 }
170
171 void TaskDatabase::StepRegisterExternalFiles()
172 {
173     WrtDB::ExternalLocationList externalLocationsUpdate =
174         m_context.locations->listExternalLocations();
175     if (m_context.existingWidgetInfo.isExist) { //update
176         Try
177         {
178             WidgetDAO dao(m_context.widgetConfig.tzAppid);
179             WrtDB::ExternalLocationList externalLocationsDB =
180                 dao.getWidgetExternalLocations();
181             FOREACH(file, externalLocationsDB)
182             {
183                 if (std::find(externalLocationsUpdate.begin(),
184                               externalLocationsUpdate.end(),
185                               *file) == externalLocationsUpdate.end())
186                 {
187                     m_externalLocationsToRemove.push_back(*file);
188                 }
189             }
190         }
191         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
192         {
193             LogError(
194                 "Given tizenId not found for update installation (Same GUID?)");
195             ThrowMsg(Exceptions::UpdateFailed,
196                      "Given tizenId not found for update installation");
197         }
198     }
199     LogDebug("Registering external files:");
200     FOREACH(file, externalLocationsUpdate)
201     {
202         LogDebug("  -> " << *file);
203     }
204
205     //set external locations to be registered
206     m_context.widgetConfig.externalLocations = externalLocationsUpdate;
207 }
208
209 void TaskDatabase::StepRemoveExternalFiles()
210 {
211     if (!m_externalLocationsToRemove.empty()) {
212         LogDebug("Removing external files:");
213     }
214
215     FOREACH(file, m_externalLocationsToRemove)
216     {
217         if (WrtUtilFileExists(*file)) {
218             LogDebug("  -> " << *file);
219             if (-1 == TEMP_FAILURE_RETRY(remove(file->c_str()))) {
220                 ThrowMsg(Exceptions::RemovingFileFailure,
221                          "Failed to remove external file");
222             }
223         } else if (WrtUtilDirExists(*file)) {
224             LogDebug("  -> " << *file);
225             if (!WrtUtilRemove(*file)) {
226                 ThrowMsg(Exceptions::RemovingFolderFailure,
227                          "Failed to remove external directory");
228             }
229         } else {
230             LogWarning("  -> " << *file << "(no such a path)");
231         }
232     }
233 }
234
235 void TaskDatabase::StepCreateVconf()
236 {
237     LogDebug("StepCreateVconf");
238     std::map<std::string, WrtDB::SettingsType> vconfData;
239     vconfData[
240         WrtDB::VconfConfig::GetVconfKeyPopupUsage(
241             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
242     vconfData[
243         WrtDB::VconfConfig::GetVconfKeyGeolocationUsage(
244             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
245     vconfData[
246         WrtDB::VconfConfig::GetVconfKeyWebNotificationUsage(
247             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
248     vconfData[
249         WrtDB::VconfConfig::GetVconfKeyWebDatabaseUsage(
250             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
251     vconfData[
252         WrtDB::VconfConfig::GetVconfKeyFilesystemUsage(
253             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
254     vconfData[
255         WrtDB::VconfConfig::GetVconfKeyMemorySavingMode(
256             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_OFF;
257
258     // vconftool -g 5000 set -t int <path> initialize value
259     // Current installer should use vconftool for setting group ID
260     // In case of install application by pkgcmd, permission for others
261     // set to read-only
262     FOREACH(it, vconfData) {
263         std::ostringstream command;
264         command << "vconftool -g 5000 set -t int ";
265         command << (*it).first;
266         command << " \"" << static_cast<int>((*it).second) << "\"";
267         int ret = system(command.str().c_str());
268         if (-1 == ret) {
269             ThrowMsg(Exceptions::CreateVconfFailure,
270                      "Failed to create vconf files");
271         }
272     }
273 }
274
275 void TaskDatabase::StepAbortDBInsert()
276 {
277     LogWarning("[DB Update Task] Aborting... (DB Clean)");
278     Try
279     {
280         WidgetDAO::unregisterWidget(m_context.widgetConfig.tzAppid);
281         LogDebug("Cleaning DB successful!");
282     }
283     Catch(DPL::DB::SqlConnection::Exception::Base)
284     {
285         LogError("Failed to handle StepAbortDBClean!");
286     }
287
288     ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
289     // Remove also old one. If it was already updated nothing wrong will happen,
290     // but if not old widget will be removed.
291     if (INVALID_WIDGET_HANDLE != m_handleToRemove) {
292         ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
293     }
294 }
295
296 void TaskDatabase::StepLiveboxDBInsert()
297 {
298     if (m_context.widgetConfig.configInfo.m_livebox.size() <= 0) {
299         return;
300     }
301
302     std::string tizenId = DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
303
304     for (auto it = m_context.widgetConfig.configInfo.m_livebox.begin();
305          it != m_context.widgetConfig.configInfo.m_livebox.end(); ++it)
306     {
307         std::string boxId = DPL::ToUTF8String((**it).m_liveboxId);
308         std::string boxType;
309         if ((**it).m_type == L"") {
310             boxType = web_provider_info_get_default_type();
311         } else {
312             boxType = DPL::ToUTF8String((**it).m_type);
313         }
314         LogInfo("livebox id: " << boxId);
315         LogInfo("livebox type: " << boxType);
316
317         int ret =
318             web_provider_info_insert_box_type(
319                 boxId.c_str(), tizenId.c_str(), boxType.c_str());
320
321         if (ret < 0) {
322             LogDebug("failed to set type of livebox: " << boxId);
323         }
324     }
325 }
326 } //namespace WidgetInstall
327 } //namespace Jobs