a7b405bee8fbaaf8e31f1789ade3f1202f160cda
[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_livebox_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 <dpl/wrt-dao-ro/widget_dao_types.h>
40 #include <string>
41 #include <sstream>
42 #include <ace_api_install.h>
43 #include <ace_registration.h>
44 #include <errno.h>
45 #include <string.h>
46 #include <vconf.h>
47 #include <map>
48
49 using namespace WrtDB;
50
51 namespace Jobs {
52 namespace WidgetInstall {
53 TaskDatabase::TaskDatabase(InstallerContext& context) :
54     DPL::TaskDecl<TaskDatabase>(this),
55     m_context(context),
56     m_handleToRemove(INVALID_WIDGET_HANDLE),
57     m_handle(INVALID_WIDGET_HANDLE)
58 {
59     AddStep(&TaskDatabase::StepRegisterExternalFiles);
60     AddStep(&TaskDatabase::StepWrtDBInsert);
61     AddStep(&TaskDatabase::StepAceDBInsert);
62     AddStep(&TaskDatabase::StepSecurityOriginDBInsert);
63     AddStep(&TaskDatabase::StepRemoveExternalFiles);
64     AddStep(&TaskDatabase::StepCreateVconf);
65     AddStep(&TaskDatabase::StepLiveboxDBInsert);
66
67     AddAbortStep(&TaskDatabase::StepAbortDBInsert);
68     AddAbortStep(&TaskDatabase::StepAbortAceDBInsert);
69 }
70
71 void TaskDatabase::StepWrtDBInsert()
72 {
73     Try
74     {
75         /* Set install Time */
76         time(&m_context.widgetConfig.installedTime);
77
78         if (m_context.isUpdateMode) { //update
79             LogInfo("Registering widget... (update)");
80             Try
81             {
82                 m_handleToRemove = WidgetDAOReadOnly::getHandle(
83                         m_context.widgetConfig.tzAppid);
84
85                 std::string makeAppid =
86                     DPL::ToUTF8String(m_context.widgetConfig.tzAppid) + "." +
87                     "backup";
88                 m_backAppId = DPL::FromUTF8String(makeAppid);
89             }
90             Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
91             {
92                 LogError(
93                     "Given tizenId not found for update installation (Same GUID?)");
94                 ThrowMsg(Exceptions::DatabaseFailure,
95                          "Given tizenId not found for update installation");
96             }
97
98             WidgetDAO::backupAndUpdateWidget(
99                 m_backAppId,
100                 m_context.widgetConfig.tzAppid,
101                 m_context.widgetConfig,
102                 m_context.wacSecurity);
103             m_handle = WidgetDAOReadOnly::getHandle(
104                     m_context.widgetConfig.tzAppid);
105         } else { //new installation
106             LogInfo("Registering widget...");
107             WidgetDAO::registerWidget(
108                 m_context.widgetConfig.tzAppid,
109                 m_context.widgetConfig,
110                 m_context.wacSecurity);
111             m_handle = WidgetDAOReadOnly::getHandle(
112                     m_context.widgetConfig.tzAppid);
113         }
114
115         FOREACH(cap, m_context.staticPermittedDevCaps) {
116             LogInfo(
117                 "staticPermittedDevCaps : " << cap->first
118                                             << " smack status: " <<
119                 cap->second);
120         }
121
122         LogInfo("Widget registered");
123     }
124     Catch(WidgetDAO::Exception::DatabaseError)
125     {
126         LogError("Database failure!");
127         ReThrowMsg(Exceptions::InsertNewWidgetFailed, "Database failure!");
128     }
129     Catch(DPL::DB::SqlConnection::Exception::Base)
130     {
131         LogError("Database failure!");
132         ReThrowMsg(Exceptions::InsertNewWidgetFailed, "Database failure!");
133     }
134 }
135
136 void TaskDatabase::StepAceDBInsert()
137 {
138     LogDebug("Inserting Ace database entry. New handle: " << m_handle);
139     if (INVALID_WIDGET_HANDLE != m_handleToRemove) {
140         LogDebug("Removing old insallation. Handle: " << m_handleToRemove);
141         if (ACE_OK != ace_unregister_widget(
142                 static_cast<ace_widget_handle_t>(m_handleToRemove)))
143         {
144             LogWarning(
145                 "Error while removing ace entry for previous insallation");
146         }
147     }
148
149     if (!AceApi::registerAceWidget(m_handle, m_context.widgetConfig,
150                                    m_context.wacSecurity.getCertificateList()))
151     {
152         LogError("ace database insert failed");
153         ThrowMsg(Exceptions::UpdateFailed,
154                  "Update failure. ace_register_widget failed");
155     }
156     LogDebug("Ace data inserted");
157 }
158
159 void TaskDatabase::StepSecurityOriginDBInsert()
160 {
161     LogDebug("Create Security origin database");
162     // automatically create security origin database
163     using namespace SecurityOriginDB;
164     using namespace WrtDB;
165
166     SecurityOriginDAO dao(m_context.locations->getPkgId());
167
168     // Checking privilege list for setting security origin exception data
169     FOREACH(it, m_context.widgetConfig.configInfo.privilegeList) {
170         std::map<std::string, Feature>::const_iterator result =
171             g_W3CPrivilegeTextMap.find(DPL::ToUTF8String(it->name));
172         if (result != g_W3CPrivilegeTextMap.end()) {
173             if (result->second == FEATURE_USER_MEDIA) {
174                 dao.setPrivilegeSecurityOriginData(result->second, false);
175             } else if (result->second == FEATURE_FULLSCREEN_MODE) {
176                 continue;
177             } else {
178                 dao.setPrivilegeSecurityOriginData(result->second);
179             }
180         }
181     }
182
183     m_context.job->UpdateProgress(
184         InstallerContext::INSTALL_NEW_DB_INSERT,
185         "New Widget DB UPDATE Finished");
186 }
187
188 void TaskDatabase::StepRegisterExternalFiles()
189 {
190     WrtDB::ExternalLocationList externalLocationsUpdate =
191         m_context.locations->listExternalLocations();
192     if (m_context.isUpdateMode) { //update
193         Try
194         {
195             WidgetDAO dao(m_context.widgetConfig.tzAppid);
196             WrtDB::ExternalLocationList externalLocationsDB =
197                 dao.getWidgetExternalLocations();
198             FOREACH(file, externalLocationsDB)
199             {
200                 if (std::find(externalLocationsUpdate.begin(),
201                               externalLocationsUpdate.end(),
202                               *file) == externalLocationsUpdate.end())
203                 {
204                     m_externalLocationsToRemove.push_back(*file);
205                 }
206             }
207         }
208         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
209         {
210             LogError(
211                 "Given tizenId not found for update installation (Same GUID?)");
212             ThrowMsg(Exceptions::UpdateFailed,
213                      "Given tizenId not found for update installation");
214         }
215     }
216     LogDebug("Registering external files:");
217     FOREACH(file, externalLocationsUpdate)
218     {
219         LogDebug("  -> " << *file);
220     }
221
222     //set external locations to be registered
223     m_context.widgetConfig.externalLocations = externalLocationsUpdate;
224 }
225
226 void TaskDatabase::StepRemoveExternalFiles()
227 {
228     if (!m_externalLocationsToRemove.empty()) {
229         LogDebug("Removing external files:");
230     }
231
232     FOREACH(file, m_externalLocationsToRemove)
233     {
234         if (WrtUtilFileExists(*file)) {
235             LogDebug("  -> " << *file);
236             if (-1 == TEMP_FAILURE_RETRY(remove(file->c_str()))) {
237                 ThrowMsg(Exceptions::RemovingFileFailure,
238                          "Failed to remove external file");
239             }
240         } else if (WrtUtilDirExists(*file)) {
241             LogDebug("  -> " << *file);
242             if (!WrtUtilRemove(*file)) {
243                 ThrowMsg(Exceptions::RemovingFolderFailure,
244                          "Failed to remove external directory");
245             }
246         } else {
247             LogWarning("  -> " << *file << "(no such a path)");
248         }
249     }
250 }
251
252 void TaskDatabase::StepCreateVconf()
253 {
254     LogDebug("StepCreateVconf");
255     std::map<std::string, WrtDB::SettingsType> vconfData;
256     vconfData[
257         WrtDB::VconfConfig::GetVconfKeyPopupUsage(
258             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
259     vconfData[
260         WrtDB::VconfConfig::GetVconfKeyGeolocationUsage(
261             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
262     vconfData[
263         WrtDB::VconfConfig::GetVconfKeyWebNotificationUsage(
264             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
265     vconfData[
266         WrtDB::VconfConfig::GetVconfKeyWebDatabaseUsage(
267             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
268     vconfData[
269         WrtDB::VconfConfig::GetVconfKeyMemorySavingMode(
270             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_OFF;
271
272     // vconftool -g 5000 set -t int <path> initialize value
273     // Current installer should use vconftool for setting group ID
274     // In case of install application by pkgcmd, permission for others
275     // set to read-only
276     FOREACH(it, vconfData) {
277         std::ostringstream command;
278         command << "vconftool -g 5000 set -t int ";
279         command << (*it).first;
280         command << " \"" << static_cast<int>((*it).second) << "\"";
281         int ret = system(command.str().c_str());
282         if (-1 == ret) {
283             ThrowMsg(Exceptions::CreateVconfFailure,
284                      "Failed to create vconf files");
285         }
286     }
287 }
288
289 void TaskDatabase::StepAbortDBInsert()
290 {
291     LogWarning("[DB Update Task] Aborting... (DB Clean)");
292     Try
293     {
294         WidgetDAO::restoreUpdateWidget(m_backAppId,
295                 m_context.widgetConfig.tzAppid);
296         LogDebug("Cleaning DB successful!");
297     }
298     Catch(DPL::DB::SqlConnection::Exception::Base)
299     {
300         LogError("Failed to handle StepAbortDBClean!");
301     }
302 }
303
304 void TaskDatabase::StepAbortAceDBInsert()
305 {
306     LogWarning("[DB Update Task] ACE DB Aborting... (DB Clean)");
307
308     ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
309     // Remove also old one. If it was already updated nothing wrong will happen,
310     // but if not old widget will be removed.
311     if (INVALID_WIDGET_HANDLE != m_handleToRemove) {
312         ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
313     }
314
315     if (!AceApi::registerAceWidgetFromDB(m_handleToRemove))
316     {
317         LogError("ace database restore failed");
318     }
319     LogDebug("Ace data inserted");
320 }
321
322 void TaskDatabase::StepLiveboxDBInsert()
323 {
324     if (m_context.widgetConfig.configInfo.m_livebox.size() <= 0) {
325         return;
326     }
327
328     std::string tizenId = DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
329
330     // insert specific information to web livebox db
331     for (auto it = m_context.widgetConfig.configInfo.m_livebox.begin();
332          it != m_context.widgetConfig.configInfo.m_livebox.end(); ++it)
333     {
334         std::string boxId = DPL::ToUTF8String((**it).m_liveboxId);
335         std::string boxType;
336         if ((**it).m_type.empty()) {
337             boxType = web_provider_livebox_get_default_type();
338         } else {
339             boxType = DPL::ToUTF8String((**it).m_type);
340         }
341         LogInfo("livebox id: " << boxId);
342         LogInfo("livebox type: " << boxType);
343
344         int autoLaunch = (**it).m_autoLaunch == L"true" ? 1 : 0;
345         LogInfo("livebox auto-launch: " << autoLaunch);
346
347         int mouseEvent = (**it).m_boxInfo.m_boxMouseEvent == L"true" ? 1 : 0;
348         LogInfo("livebox mouse-event: " << mouseEvent);
349
350         int pdFastOpen = (**it).m_boxInfo.m_pdFastOpen == L"true" ? 1 : 0;
351         LogInfo("livebox pd fast-open: " << pdFastOpen);
352
353         web_provider_livebox_insert_box_info(
354                 boxId.c_str(), tizenId.c_str(), boxType.c_str(),
355                 autoLaunch, mouseEvent, pdFastOpen);
356     }
357 }
358 } //namespace WidgetInstall
359 } //namespace Jobs