Implement privilege for usermedia permission
[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             if (result->second == FEATURE_USER_MEDIA) {
163                 dao.setPrivilegeSecurityOriginData(result->second, false);
164             } else {
165                 dao.setPrivilegeSecurityOriginData(result->second);
166             }
167         }
168     }
169
170     m_context.job->UpdateProgress(
171         InstallerContext::INSTALL_NEW_DB_INSERT,
172         "New Widget DB UPDATE Finished");
173 }
174
175 void TaskDatabase::StepRegisterExternalFiles()
176 {
177     WrtDB::ExternalLocationList externalLocationsUpdate =
178         m_context.locations->listExternalLocations();
179     if (m_context.existingWidgetInfo.isExist) { //update
180         Try
181         {
182             WidgetDAO dao(m_context.widgetConfig.tzAppid);
183             WrtDB::ExternalLocationList externalLocationsDB =
184                 dao.getWidgetExternalLocations();
185             FOREACH(file, externalLocationsDB)
186             {
187                 if (std::find(externalLocationsUpdate.begin(),
188                               externalLocationsUpdate.end(),
189                               *file) == externalLocationsUpdate.end())
190                 {
191                     m_externalLocationsToRemove.push_back(*file);
192                 }
193             }
194         }
195         Catch(WidgetDAOReadOnly::Exception::WidgetNotExist)
196         {
197             LogError(
198                 "Given tizenId not found for update installation (Same GUID?)");
199             ThrowMsg(Exceptions::UpdateFailed,
200                      "Given tizenId not found for update installation");
201         }
202     }
203     LogDebug("Registering external files:");
204     FOREACH(file, externalLocationsUpdate)
205     {
206         LogDebug("  -> " << *file);
207     }
208
209     //set external locations to be registered
210     m_context.widgetConfig.externalLocations = externalLocationsUpdate;
211 }
212
213 void TaskDatabase::StepRemoveExternalFiles()
214 {
215     if (!m_externalLocationsToRemove.empty()) {
216         LogDebug("Removing external files:");
217     }
218
219     FOREACH(file, m_externalLocationsToRemove)
220     {
221         if (WrtUtilFileExists(*file)) {
222             LogDebug("  -> " << *file);
223             if (-1 == TEMP_FAILURE_RETRY(remove(file->c_str()))) {
224                 ThrowMsg(Exceptions::RemovingFileFailure,
225                          "Failed to remove external file");
226             }
227         } else if (WrtUtilDirExists(*file)) {
228             LogDebug("  -> " << *file);
229             if (!WrtUtilRemove(*file)) {
230                 ThrowMsg(Exceptions::RemovingFolderFailure,
231                          "Failed to remove external directory");
232             }
233         } else {
234             LogWarning("  -> " << *file << "(no such a path)");
235         }
236     }
237 }
238
239 void TaskDatabase::StepCreateVconf()
240 {
241     LogDebug("StepCreateVconf");
242     std::map<std::string, WrtDB::SettingsType> vconfData;
243     vconfData[
244         WrtDB::VconfConfig::GetVconfKeyPopupUsage(
245             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
246     vconfData[
247         WrtDB::VconfConfig::GetVconfKeyGeolocationUsage(
248             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
249     vconfData[
250         WrtDB::VconfConfig::GetVconfKeyWebNotificationUsage(
251             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_ON;
252     vconfData[
253         WrtDB::VconfConfig::GetVconfKeyMemorySavingMode(
254             m_context.widgetConfig.tzAppid)] = WrtDB::SETTINGS_TYPE_OFF;
255
256     // vconftool -g 5000 set -t int <path> initialize value
257     // Current installer should use vconftool for setting group ID
258     // In case of install application by pkgcmd, permission for others
259     // set to read-only
260     FOREACH(it, vconfData) {
261         std::ostringstream command;
262         command << "vconftool -g 5000 set -t int ";
263         command << (*it).first;
264         command << " \"" << static_cast<int>((*it).second) << "\"";
265         int ret = system(command.str().c_str());
266         if (-1 == ret) {
267             ThrowMsg(Exceptions::CreateVconfFailure,
268                      "Failed to create vconf files");
269         }
270     }
271 }
272
273 void TaskDatabase::StepAbortDBInsert()
274 {
275     LogWarning("[DB Update Task] Aborting... (DB Clean)");
276     Try
277     {
278         WidgetDAO::unregisterWidget(m_context.widgetConfig.tzAppid);
279         LogDebug("Cleaning DB successful!");
280     }
281     Catch(DPL::DB::SqlConnection::Exception::Base)
282     {
283         LogError("Failed to handle StepAbortDBClean!");
284     }
285
286     ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
287     // Remove also old one. If it was already updated nothing wrong will happen,
288     // but if not old widget will be removed.
289     if (INVALID_WIDGET_HANDLE != m_handleToRemove) {
290         ace_unregister_widget(static_cast<ace_widget_handle_t>(m_handle));
291     }
292 }
293
294 void TaskDatabase::StepLiveboxDBInsert()
295 {
296     if (m_context.widgetConfig.configInfo.m_livebox.size() <= 0) {
297         return;
298     }
299
300     std::string tizenId = DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
301
302     for (auto it = m_context.widgetConfig.configInfo.m_livebox.begin();
303          it != m_context.widgetConfig.configInfo.m_livebox.end(); ++it)
304     {
305         std::string boxId = DPL::ToUTF8String((**it).m_liveboxId);
306         std::string boxType;
307         if ((**it).m_type == L"") {
308             boxType = web_provider_info_get_default_type();
309         } else {
310             boxType = DPL::ToUTF8String((**it).m_type);
311         }
312         LogInfo("livebox id: " << boxId);
313         LogInfo("livebox type: " << boxType);
314
315         int ret =
316             web_provider_info_insert_box_type(
317                 boxId.c_str(), tizenId.c_str(), boxType.c_str());
318
319         if (ret < 0) {
320             LogDebug("failed to set type of livebox: " << boxId);
321         }
322     }
323 }
324 } //namespace WidgetInstall
325 } //namespace Jobs