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