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