Rename invalid WRT_SMACK_LABEL macro to WRT_SMACK_ENABLED
[platform/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 <cstdio>
26 #include <time.h>
27 #include <sys/stat.h>
28 #include <widget_install/task_database.h>
29 #include <widget_install/job_widget_install.h>
30 #include <widget_install/widget_install_errors.h>
31 #include <widget_install/widget_install_context.h>
32 #ifdef LIVEBOX
33 #include <web_provider_livebox_info.h>
34 #endif
35 #include <dpl/wrt-dao-rw/widget_dao.h>
36 #include <dpl/foreach.h>
37 #include <dpl/utils/wrt_utility.h>
38 #include <dpl/assert.h>
39 #include <wrt-commons/security-origin-dao/security_origin_dao.h>
40 #include <wrt-commons/widget-interface-dao/widget_interface_dao.h>
41 #include <dpl/wrt-dao-ro/global_config.h>
42 #include <dpl/wrt-dao-ro/widget_dao_types.h>
43 #include <string>
44 #include <sstream>
45 #include <ace_api_install.h>
46 #include <ace_registration.h>
47 #include <errno.h>
48 #include <string.h>
49 #include <map>
50 #include <installer_log.h>
51
52 using namespace WrtDB;
53
54 namespace Jobs {
55 namespace WidgetInstall {
56 TaskDatabase::TaskDatabase(InstallerContext& context) :
57     DPL::TaskDecl<TaskDatabase>(this),
58     m_context(context),
59     m_handleToRemove(INVALID_WIDGET_HANDLE),
60     m_handle(INVALID_WIDGET_HANDLE)
61 {
62     AddStep(&TaskDatabase::StartStep);
63     AddStep(&TaskDatabase::StepRegisterExternalFiles);
64     AddStep(&TaskDatabase::StepWrtDBInsert);
65     AddStep(&TaskDatabase::StepAceDBInsert);
66     AddStep(&TaskDatabase::StepSecurityOriginDBInsert);
67     AddStep(&TaskDatabase::StepWidgetInterfaceDBInsert);
68     AddStep(&TaskDatabase::StepRemoveExternalFiles);
69 #ifdef LIVEBOX
70     AddStep(&TaskDatabase::StepLiveboxDBInsert);
71 #endif
72     AddStep(&TaskDatabase::EndStep);
73
74     AddAbortStep(&TaskDatabase::StepAbortDBInsert);
75     AddAbortStep(&TaskDatabase::StepAbortAceDBInsert);
76     AddAbortStep(&TaskDatabase::StepAbortWidgetInterfaceDBInsert);
77 }
78
79 void TaskDatabase::StepWrtDBInsert()
80 {
81     Try
82     {
83         /* Set install Time */
84         time(&m_context.widgetConfig.installedTime);
85
86         if (m_context.isUpdateMode) { //update
87             _D("Registering widget... (update)");
88             Try
89             {
90                 m_handleToRemove = WidgetDAOReadOnly::getHandle(
91                         m_context.widgetConfig.tzAppid);
92
93                 std::string makeAppid =
94                     DPL::ToUTF8String(m_context.widgetConfig.tzAppid) + "." +
95                     "backup";
96                 m_backAppId = DPL::FromUTF8String(makeAppid);
97             }
98             Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
99             {
100                 _E("Given tizenId not found for update installation (Same GUID?)");
101                 ThrowMsg(Exceptions::DatabaseFailure,
102                          "Given tizenId not found for update installation");
103             }
104
105             WidgetDAO::updateTizenAppId(m_context.widgetConfig.tzAppid,
106                                         m_backAppId);
107             WidgetDAO::registerWidget(m_context.widgetConfig.tzAppid,
108                                       m_context.widgetConfig,
109                                       m_context.widgetSecurity);
110             m_handle =
111                 WidgetDAOReadOnly::getHandle(m_context.widgetConfig.tzAppid);
112         } else { //new installation
113             _D("Registering widget...");
114             WidgetDAO::registerWidget(
115                 m_context.widgetConfig.tzAppid,
116                 m_context.widgetConfig,
117                 m_context.widgetSecurity);
118             m_handle = WidgetDAOReadOnly::getHandle(
119                     m_context.widgetConfig.tzAppid);
120         }
121
122         FOREACH(cap, m_context.staticPermittedDevCaps) {
123             _D("staticPermittedDevCaps : %ls smack status: %d", cap->first.c_str(), cap->second);
124         }
125
126         _D("Widget registered");
127     }
128     Catch(WidgetDAO::Exception::DatabaseError)
129     {
130         _E("Database failure!");
131         ReThrowMsg(Exceptions::InsertNewWidgetFailed, "Database failure!");
132     }
133     Catch(DPL::DB::SqlConnection::Exception::Base)
134     {
135         _E("Database failure!");
136         ReThrowMsg(Exceptions::InsertNewWidgetFailed, "Database failure!");
137     }
138 }
139
140 void TaskDatabase::StepAceDBInsert()
141 {
142     _D("Inserting Ace database entry. New handle: %d", m_handle);
143     if (INVALID_WIDGET_HANDLE != m_handleToRemove) {
144         _D("Removing old insallation. Handle: %d", m_handleToRemove);
145         if (ACE_OK != ace_unregister_widget(
146                 static_cast<ace_widget_handle_t>(m_handleToRemove)))
147         {
148             _W("Error while removing ace entry for previous insallation");
149         }
150     }
151
152     if (!AceApi::registerAceWidget(m_handle, m_context.widgetConfig,
153                                    m_context.widgetSecurity.getCertificateList()))
154     {
155         _E("ace database insert failed");
156         ThrowMsg(Exceptions::UpdateFailed,
157                  "Update failure. ace_register_widget failed");
158     }
159     _D("Ace data inserted");
160 }
161
162 void TaskDatabase::StepSecurityOriginDBInsert()
163 {
164     _D("Create Security origin database");
165     // automatically create security origin database
166     using namespace SecurityOriginDB;
167     using namespace WrtDB;
168
169     SecurityOriginDAO dao(m_context.locations->getPkgId());
170
171     // Checking privilege list for setting security origin exception data
172     FOREACH(it, m_context.widgetConfig.configInfo.privilegeList) {
173         std::map<std::string, Feature>::const_iterator result =
174             g_W3CPrivilegeTextMap.find(DPL::ToUTF8String(it->name));
175         if (result != g_W3CPrivilegeTextMap.end()) {
176             if (result->second == FEATURE_USER_MEDIA) {
177                 dao.setPrivilegeSecurityOriginData(result->second, false);
178             } else if (result->second == FEATURE_FULLSCREEN_MODE) {
179                 continue;
180             } else {
181                 dao.setPrivilegeSecurityOriginData(result->second);
182             }
183         }
184     }
185 }
186
187 void TaskDatabase::StepWidgetInterfaceDBInsert()
188 {
189     _D("Create Widget Interface database");
190     using namespace WidgetInterfaceDB;
191     using namespace WrtDB;
192
193     DbWidgetHandle handle =
194         WidgetDAOReadOnly::getHandle(m_context.widgetConfig.tzAppid);
195
196     // backup database
197     if (m_context.isUpdateMode) {
198         std::string dbPath = WidgetInterfaceDAO::databaseFileName(handle);
199         std::string backupDbPath = dbPath;
200         backupDbPath += GlobalConfig::GetBackupDatabaseSuffix();
201         _D("\"%s\" to \"%s\"", dbPath.c_str(), backupDbPath.c_str());
202         if (0 != std::rename(dbPath.c_str(), backupDbPath.c_str())) {
203             _E("widget interface database backup failed");
204             ThrowMsg(Exceptions::UpdateFailed,
205                      "widget interface database backup failed");
206         }
207     }
208
209     Try
210     {
211         // automatically create widget interface database
212         WidgetInterfaceDAO dao(handle);
213     }
214     Catch(WidgetInterfaceDAO::Exception::DatabaseError)
215     {
216         _E("widget interface database create failed");
217         ThrowMsg(Exceptions::UpdateFailed,
218                  "widget interface database create failed");
219     }
220 }
221
222 void TaskDatabase::StepRegisterExternalFiles()
223 {
224     WrtDB::ExternalLocationList externalLocationsUpdate =
225         m_context.locations->listExternalLocations();
226     if (m_context.isUpdateMode) { //update
227         Try
228         {
229             WidgetDAO dao(m_context.widgetConfig.tzAppid);
230             WrtDB::ExternalLocationList externalLocationsDB =
231                 dao.getWidgetExternalLocations();
232             FOREACH(file, externalLocationsDB)
233             {
234                 if (std::find(externalLocationsUpdate.begin(),
235                               externalLocationsUpdate.end(),
236                               *file) == externalLocationsUpdate.end())
237                 {
238                     m_externalLocationsToRemove.push_back(*file);
239                 }
240             }
241         }
242         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
243         {
244             _E("Given tizenId not found for update installation (Same GUID?)");
245             ThrowMsg(Exceptions::UpdateFailed,
246                      "Given tizenId not found for update installation");
247         }
248     }
249     _D("Registering external files:");
250     FOREACH(file, externalLocationsUpdate)
251     {
252         _D("  -> %s", (*file).c_str());
253     }
254
255     //set external locations to be registered
256     m_context.widgetConfig.externalLocations = externalLocationsUpdate;
257 }
258
259 void TaskDatabase::StepRemoveExternalFiles()
260 {
261     if (!m_externalLocationsToRemove.empty()) {
262         _D("Removing external files:");
263     }
264
265     FOREACH(file, m_externalLocationsToRemove)
266     {
267         if (WrtUtilFileExists(*file)) {
268             _D("  -> %s", (*file).c_str());
269             if (-1 == TEMP_FAILURE_RETRY(remove(file->c_str()))) {
270                 ThrowMsg(Exceptions::RemovingFileFailure,
271                          "Failed to remove external file");
272             }
273         } else if (WrtUtilDirExists(*file)) {
274             _D("  -> %s", (*file).c_str());
275             if (!WrtUtilRemove(*file)) {
276                 ThrowMsg(Exceptions::RemovingFolderFailure,
277                          "Failed to remove external directory");
278             }
279         } else {
280             _W("  -> %s(no such a path)", (*file).c_str());
281         }
282     }
283 }
284
285 void TaskDatabase::StepAbortDBInsert()
286 {
287     _W("[DB Update Task] Aborting... (DB Clean)");
288     Try
289     {
290         if (m_context.isUpdateMode) {
291             WidgetDAO::unregisterWidget(m_context.widgetConfig.tzAppid);
292             WidgetDAO::updateTizenAppId(m_backAppId,
293                                         m_context.widgetConfig.tzAppid);
294         } else {
295             WidgetDAO::unregisterWidget(m_context.widgetConfig.tzAppid);
296         }
297         _D("Cleaning DB successful!");
298     }
299     Catch(DPL::DB::SqlConnection::Exception::Base)
300     {
301         _E("Failed to handle StepAbortDBClean!");
302     }
303 }
304
305 void TaskDatabase::StepAbortAceDBInsert()
306 {
307     _W("[DB Update Task] ACE DB Aborting... (DB Clean)");
308
309     ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
310     // Remove also old one. If it was already updated nothing wrong will happen,
311     // but if not old widget will be removed.
312     if (INVALID_WIDGET_HANDLE != m_handleToRemove) {
313         ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
314     }
315
316     if (!AceApi::registerAceWidgetFromDB(m_handleToRemove))
317     {
318         _E("ace database restore failed");
319     }
320     _D("Ace data inserted");
321 }
322
323 void TaskDatabase::StepAbortWidgetInterfaceDBInsert()
324 {
325     _D("[DB Update Task] Widget interface Aborting...");
326     using namespace WidgetInterfaceDB;
327     using namespace WrtDB;
328
329     DbWidgetHandle handle =
330         WidgetDAOReadOnly::getHandle(m_context.widgetConfig.tzAppid);
331     std::string dbPath = WidgetInterfaceDAO::databaseFileName(handle);
332
333     // remove database
334     if (remove(dbPath.c_str()) != 0) {
335         _W("Fail to remove");
336     }
337
338     // rollback database
339     if (m_context.isUpdateMode) {
340         std::string backupDbPath = dbPath;
341         backupDbPath += GlobalConfig::GetBackupDatabaseSuffix();
342         _D("\"%s\" to \"%s\"", dbPath.c_str(), backupDbPath.c_str());
343         if (0 != std::rename(backupDbPath.c_str(), dbPath.c_str())) {
344             _W("Fail to rollback");
345         }
346     }
347 }
348
349 #ifdef LIVEBOX
350 void TaskDatabase::StepLiveboxDBInsert()
351 {
352     if (m_context.widgetConfig.configInfo.m_livebox.size() <= 0) {
353         return;
354     }
355
356     std::string tizenId = DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
357
358     // insert specific information to web livebox db
359     for (auto it = m_context.widgetConfig.configInfo.m_livebox.begin();
360          it != m_context.widgetConfig.configInfo.m_livebox.end(); ++it)
361     {
362         std::string boxId = DPL::ToUTF8String((**it).m_liveboxId);
363         std::string boxType;
364         if ((**it).m_type.empty()) {
365             boxType = web_provider_livebox_get_default_type();
366         } else {
367             boxType = DPL::ToUTF8String((**it).m_type);
368         }
369         _D("livebox id: %s", boxId.c_str());
370         _D("livebox type: %s", boxType.c_str());
371
372         int autoLaunch = (**it).m_autoLaunch == L"true" ? 1 : 0;
373         _D("livebox auto-launch: %d", autoLaunch);
374
375         int mouseEvent = (**it).m_boxInfo.m_boxMouseEvent == L"true" ? 1 : 0;
376         _D("livebox mouse-event: %d", mouseEvent);
377
378         int pdFastOpen = (**it).m_boxInfo.m_pdFastOpen == L"true" ? 1 : 0;
379         _D("livebox pd fast-open: %d", pdFastOpen);
380
381         web_provider_livebox_insert_box_info(
382                 boxId.c_str(), tizenId.c_str(), boxType.c_str(),
383                 autoLaunch, mouseEvent, pdFastOpen);
384     }
385 }
386 #endif // LIVEBOX
387
388 void TaskDatabase::StartStep()
389 {
390     _D("--------- <TaskDatabase> : START ----------");
391 }
392
393 void TaskDatabase::EndStep()
394 {
395     _D("--------- <TaskDatabase> : END ----------");
396 }
397 } //namespace WidgetInstall
398 } //namespace Jobs