Fixing issues found by prevent (49866)
[framework/web/wrt-installer.git] / src / jobs / plugin_install / plugin_install_task.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    install_one_task.cpp
18  * @author  Pawel Sikorski (p.sikorski@samgsung.com)
19  * @author  Grzegorz Krawczyk (g.krawczyk@samgsung.com)
20  * @version
21  * @brief
22  */
23
24 //SYSTEM INCLUDES
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <dlfcn.h>
28
29 //WRT INCLUDES
30 #include <dpl/log/log.h>
31 #include <dpl/foreach.h>
32 #include <job.h>
33 #include "plugin_install_task.h"
34 #include "job_plugin_install.h"
35 #include "plugin_installer_errors.h"
36 #include "plugin_metafile_reader.h"
37 #include <dpl/wrt-dao-ro/global_config.h>
38 //#include <plugin.h>
39 #include <wrt_common_types.h>
40 #include <dpl/wrt-dao-rw/feature_dao.h>
41 #include <dpl/wrt-dao-rw/plugin_dao.h>
42 #include "plugin_objects.h"
43 #include <wrt_plugin_export.h>
44
45 using namespace WrtDB;
46
47 namespace {
48 const std::string DIRECTORY_SEPARATOR = std::string("/");
49 }
50
51 #define SET_PLUGIN_INSTALL_PROGRESS(step, desc)              \
52     m_context->installerTask->UpdateProgress(               \
53         PluginInstallerContext::step, desc);
54
55 #define DISABLE_IF_PLUGIN_WITHOUT_LIB()        \
56     if (m_pluginInfo.m_libraryName.empty()) \
57     {                                          \
58         LogWarning("Plugin without library."); \
59         return;                                \
60     }
61
62 namespace Jobs {
63 namespace PluginInstall {
64 PluginInstallTask::PluginInstallTask(PluginInstallerContext *inCont) :
65     DPL::TaskDecl<PluginInstallTask>(this),
66     m_context(inCont),
67     m_pluginHandle(0),
68     m_dataFromConfigXML(true)
69 {
70     AddStep(&PluginInstallTask::stepCheckPluginPath);
71     AddStep(&PluginInstallTask::stepParseConfigFile);
72     AddStep(&PluginInstallTask::stepFindPluginLibrary);
73     AddStep(&PluginInstallTask::stepCheckIfAlreadyInstalled);
74     AddStep(&PluginInstallTask::stepLoadPluginLibrary);
75     AddStep(&PluginInstallTask::stepRegisterPlugin);
76     AddStep(&PluginInstallTask::stepRegisterFeatures);
77     AddStep(&PluginInstallTask::stepRegisterPluginObjects);
78     AddStep(&PluginInstallTask::stepResolvePluginDependencies);
79
80     SET_PLUGIN_INSTALL_PROGRESS(START, "Installation initialized");
81 }
82
83 PluginInstallTask::~PluginInstallTask()
84 {}
85
86 void PluginInstallTask::stepCheckPluginPath()
87 {
88     LogInfo("Plugin installation: step CheckPluginPath");
89
90     struct stat tmp;
91
92     if (-1 == stat(m_context->pluginFilePath.c_str(), &tmp)) {
93         ThrowMsg(Exceptions::PluginPathFailed,
94                  "Stat function failed");
95     }
96
97     if (!S_ISDIR(tmp.st_mode)) {
98         ThrowMsg(Exceptions::PluginPathFailed,
99                  "Invalid Directory");
100     }
101
102     SET_PLUGIN_INSTALL_PROGRESS(PLUGIN_PATH, "Path to plugin verified");
103 }
104
105 void PluginInstallTask::stepParseConfigFile()
106 {
107     LogInfo("Plugin installation: step parse config file");
108
109     struct stat tmp;
110
111     std::string filename = m_context->pluginFilePath + DIRECTORY_SEPARATOR +
112         std::string(GlobalConfig::GetPluginMetafileName());
113
114     if (-1 == stat(filename.c_str(), &tmp)) {
115         m_dataFromConfigXML = false;
116         return;
117     }
118
119     LogInfo("Plugin Config file::" << filename);
120
121     Try
122     {
123         PluginMetafileReader reader;
124         reader.initialize(filename);
125         reader.read(m_pluginInfo);
126
127         FOREACH(it, m_pluginInfo.m_featureContainer)
128         {
129             LogDebug("Parsed feature : " << it->m_name);
130             FOREACH(devCap, it->m_deviceCapabilities) {
131                 LogDebug("  |  DevCap : " << *devCap);
132             }
133         }
134
135         SET_PLUGIN_INSTALL_PROGRESS(PLUGIN_PATH, "Config file analyzed");
136     }
137     Catch(ValidationCore::ParserSchemaException::Base)
138     {
139         LogError("Error during file processing " << filename);
140         ThrowMsg(Exceptions::PluginMetafileFailed,
141                  "Metafile error");
142     }
143 }
144
145 void PluginInstallTask::stepFindPluginLibrary()
146 {
147     if (m_dataFromConfigXML) {
148         return;
149     }
150     LogDebug("Plugin installation: step find plugin library");
151     std::string pluginPath = m_context->pluginFilePath;
152     size_t indexpos = pluginPath.find_last_of('/');
153
154     if (std::string::npos == indexpos) {
155         indexpos = 0;
156     } else {
157         indexpos += 1;  // move after '/'
158     }
159
160     std::string libName = pluginPath.substr(indexpos);
161     libName = GlobalConfig::GetPluginPrefix() + libName +
162         GlobalConfig::GetPluginSuffix();
163     LogDebug("Plugin .so: " << libName);
164     m_pluginInfo.m_libraryName = libName;
165 }
166
167 void PluginInstallTask::stepCheckIfAlreadyInstalled()
168 {
169     if (PluginDAO::isPluginInstalled(m_pluginInfo.m_libraryName)) {
170         ThrowMsg(Exceptions::PluginAlreadyInstalled,
171                  "Plugin already installed");
172     }
173
174     SET_PLUGIN_INSTALL_PROGRESS(PLUGIN_EXISTS_CHECK, "Check if plugin exist");
175 }
176
177 void PluginInstallTask::stepLoadPluginLibrary()
178 {
179     LogInfo("Plugin installation: step load library");
180
181     DISABLE_IF_PLUGIN_WITHOUT_LIB()
182
183     std::string filename = m_context->pluginFilePath + DIRECTORY_SEPARATOR +
184         m_pluginInfo.m_libraryName;
185
186     LogDebug("Loading plugin: " << filename);
187
188     void *dlHandle = dlopen(filename.c_str(), RTLD_NOW);
189     if (dlHandle == NULL) {
190         LogError(
191             "Failed to load plugin: " << filename <<
192             ". Reason: " << (dlerror() != NULL ? dlerror() : "unknown"));
193         ThrowMsg(Exceptions::PluginLibraryError, "Library error");
194     }
195
196     const js_entity_definition_t *rawEntityList = NULL;
197     get_widget_entity_map_proc *getWidgetEntityMapProcPtr = NULL;
198
199     getWidgetEntityMapProcPtr =
200         reinterpret_cast<get_widget_entity_map_proc *>(dlsym(dlHandle,
201                                                              PLUGIN_GET_CLASS_MAP_PROC_NAME));
202
203     if (getWidgetEntityMapProcPtr) {
204         rawEntityList = (*getWidgetEntityMapProcPtr)();
205     } else {
206         rawEntityList =
207             static_cast<const js_entity_definition_t *>(dlsym(dlHandle,
208                                                               PLUGIN_CLASS_MAP_NAME));
209     }
210
211     if (rawEntityList == NULL) {
212         dlclose(dlHandle);
213         LogError("Failed to read class name" << filename);
214         ThrowMsg(Exceptions::PluginLibraryError, "Library error");
215     }
216
217     if (!m_dataFromConfigXML) {
218         on_widget_init_proc *onWidgetInitProc =
219             reinterpret_cast<on_widget_init_proc *>(
220                 dlsym(dlHandle, PLUGIN_WIDGET_INIT_PROC_NAME));
221
222         if (NULL == onWidgetInitProc) {
223             dlclose(dlHandle);
224             LogError("Failed to read onWidgetInit symbol" << filename);
225             ThrowMsg(Exceptions::PluginLibraryError, "Library error");
226         }
227
228         // obtain feature -> dev-cap mapping
229         feature_mapping_interface_t mappingInterface = { NULL, NULL, NULL };
230         (*onWidgetInitProc)(&mappingInterface);
231
232         if (!mappingInterface.featGetter || !mappingInterface.release ||
233             !mappingInterface.dcGetter)
234         {
235             LogError("Failed to obtain mapping interface from .so");
236             ThrowMsg(Exceptions::PluginLibraryError, "Library error");
237         }
238
239         feature_mapping_t* devcapMapping = mappingInterface.featGetter();
240
241         LogDebug("Getting mapping from features to device capabilities");
242
243         for (size_t i = 0; i < devcapMapping->featuresCount; ++i) {
244             PluginMetafileData::Feature feature;
245             feature.m_name = devcapMapping->features[i].feature_name;
246
247             LogDebug("Feature: " << feature.m_name);
248
249             const devcaps_t* dc =
250                 mappingInterface.dcGetter(
251                     devcapMapping,
252                     devcapMapping->features[i].
253                         feature_name);
254
255             LogDebug("device=cap: " << dc);
256
257             if (dc) {
258                 LogDebug("devcaps count: " << dc->devCapsCount);
259
260                 for (size_t j = 0; j < dc->devCapsCount; ++j) {
261                     LogDebug("devcap: " << dc->deviceCaps[j]);
262                     feature.m_deviceCapabilities.insert(dc->deviceCaps[j]);
263                 }
264             }
265
266             m_pluginInfo.m_featureContainer.insert(feature);
267         }
268
269         mappingInterface.release(devcapMapping);
270     }
271
272     m_libraryObjects = PluginObjectsPtr(new PluginObjects());
273     const js_entity_definition_t *rawEntityListIterator = rawEntityList;
274
275     LogInfo("#####");
276     LogInfo("##### Plugin: " << filename << " supports new plugin API");
277     LogInfo("#####");
278
279     while (rawEntityListIterator->parent_name != NULL &&
280            rawEntityListIterator->object_name != NULL)
281     {
282         LogInfo("#####     [" << rawEntityListIterator->object_name << "]: ");
283         LogInfo("#####     Parent: " << rawEntityListIterator->parent_name);
284         LogInfo("#####");
285
286         m_libraryObjects->addObjects(rawEntityListIterator->parent_name,
287                                      rawEntityListIterator->object_name);
288
289         ++rawEntityListIterator;
290     }
291
292     // Unload library
293     if (dlclose(dlHandle) != 0) {
294         LogError("Cannot close plugin handle");
295     } else {
296         LogDebug("Library is unloaded");
297     }
298
299     // Load export table
300     LogDebug("Library successfuly loaded and parsed");
301
302     SET_PLUGIN_INSTALL_PROGRESS(LOADING_LIBRARY, "Library loaded and analyzed");
303 }
304
305 void PluginInstallTask::stepRegisterPlugin()
306 {
307     LogInfo("Plugin installation: step register Plugin");
308
309     m_pluginHandle =
310         PluginDAO::registerPlugin(m_pluginInfo, m_context->pluginFilePath);
311
312     SET_PLUGIN_INSTALL_PROGRESS(REGISTER_PLUGIN, "Plugin registered");
313 }
314
315 void PluginInstallTask::stepRegisterFeatures()
316 {
317     LogInfo("Plugin installation: step register features");
318
319     FOREACH(it, m_pluginInfo.m_featureContainer)
320     {
321         LogError("PluginHandle: " << m_pluginHandle);
322         FeatureDAO::RegisterFeature(*it, m_pluginHandle);
323     }
324     SET_PLUGIN_INSTALL_PROGRESS(REGISTER_FEATURES, "Features registered");
325 }
326
327 void PluginInstallTask::stepRegisterPluginObjects()
328 {
329     LogInfo("Plugin installation: step register objects");
330
331     DISABLE_IF_PLUGIN_WITHOUT_LIB()
332
333     //register implemented objects
334     PluginObjects::ObjectsPtr objects =
335         m_libraryObjects->getImplementedObject();
336
337     FOREACH(it, *objects)
338     {
339         PluginDAO::registerPluginImplementedObject(*it, m_pluginHandle);
340     }
341
342     //register requiredObjects
343     objects = m_libraryObjects->getDependentObjects();
344
345     FOREACH(it, *objects)
346     {
347         if (m_libraryObjects->hasObject(*it)) {
348             LogDebug("Dependency from the same library. ignored");
349             continue;
350         }
351
352         PluginDAO::registerPluginRequiredObject(*it, m_pluginHandle);
353     }
354
355     SET_PLUGIN_INSTALL_PROGRESS(REGISTER_OBJECTS, "Plugin Objects registered");
356 }
357
358 void PluginInstallTask::stepResolvePluginDependencies()
359 {
360     LogInfo("Plugin installation: step resolve dependencies ");
361
362     //DISABLE_IF_PLUGIN_WITHOUT_LIB
363     if (m_pluginInfo.m_libraryName.empty()) {
364         PluginDAO::setPluginInstallationStatus(
365             m_pluginHandle,
366             PluginDAO::
367                 INSTALLATION_COMPLETED);
368         //Installation completed
369         m_context->pluginHandle = m_pluginHandle;
370         m_context->installationCompleted = true;
371         LogWarning("Plugin without library.");
372         return;
373     }
374
375     PluginHandleSetPtr handles = PluginHandleSetPtr(new PluginHandleSet);
376
377     DbPluginHandle handle = INVALID_PLUGIN_HANDLE;
378
379     //register requiredObjects
380     FOREACH(it, *(m_libraryObjects->getDependentObjects()))
381     {
382         if (m_libraryObjects->hasObject(*it)) {
383             LogDebug("Dependency from the same library. ignored");
384             continue;
385         }
386
387         handle = PluginDAO::getPluginHandleForImplementedObject(*it);
388         if (handle == INVALID_PLUGIN_HANDLE) {
389             LogError("Library implementing: " << *it << " NOT FOUND");
390             PluginDAO::setPluginInstallationStatus(
391                 m_pluginHandle,
392                 PluginDAO::INSTALLATION_WAITING);
393             return;
394         }
395
396         handles->insert(handle);
397     }
398
399     PluginDAO::registerPluginLibrariesDependencies(m_pluginHandle, handles);
400
401     PluginDAO::setPluginInstallationStatus(m_pluginHandle,
402                                            PluginDAO::INSTALLATION_COMPLETED);
403
404     //Installation completed
405     m_context->pluginHandle = m_pluginHandle;
406     m_context->installationCompleted = true;
407
408     SET_PLUGIN_INSTALL_PROGRESS(RESOLVE_DEPENDENCIES, "Dependencies resolved");
409 }
410
411 #undef SET_PLUGIN_INSTALL_PROGRESS
412 } //namespace Jobs
413 } //namespace PluginInstall