1f5bc8cfc8c1bd2291f3b958f954bbf3db4f6443
[framework/web/wrt-installer.git] / src / wrt-installer / wrt-installer.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 /* @file    wrt-installer.cpp
17  * @version 1.0
18  * @brief   Implementation file for installer
19  */
20
21 #include "wrt-installer.h"
22 #include "plugin_utils.h"
23
24 #include <string>
25 #include <cstring>
26 #include <cstdlib>
27 #include <dirent.h>
28 #include <sys/resource.h>
29
30 #include <dpl/log/log.h>
31 #include <dpl/optional.h>
32 #include <dpl/optional_typedefs.h>
33 #include <dpl/exception.h>
34 #include <dpl/wrt-dao-ro/global_config.h>
35 #include <dpl/wrt-dao-ro/config_parser_data.h>
36 #include <dpl/string.h>
37 #include <dpl/abstract_waitable_input_adapter.h>
38 #include <dpl/abstract_waitable_output_adapter.h>
39 #include <dpl/zip_input.h>
40 #include <dpl/binary_queue.h>
41 #include <dpl/copy.h>
42 #include <dpl/errno_string.h>
43 #include <dpl/utils/wrt_global_settings.h>
44 #include <dpl/utils/wrt_utility.h>
45 #include <parser_runner.h>
46 #include <widget_parser.h>
47 #include <root_parser.h>
48
49 #include <Elementary.h>
50
51 #include <pkg-manager/pkgmgr_signal_interface.h>
52 #include <pkg-manager/pkgmgr_signal_dummy.h>
53 #include <pkg-manager/pkgmgr_signal.h>
54
55 using namespace WrtDB;
56
57 namespace { // anonymous
58 const char * const PKGMGR_INSTALL_MSG = "Install widget";
59 const char * const PKGMGR_UNINSTALL_MSG = "Uninstall widget";
60
61 const char * const CONFIG_XML = "config.xml";
62 const char * const HYBRID_CONFIG_XML = "res/wgt/config.xml";
63
64 const unsigned int NOFILE_CNT_FOR_INSTALLER = 9999;
65
66 struct free_deleter
67 {
68     void operator()(void* x)
69     {
70         free(x);
71     }
72 };
73
74 struct PluginInstallerData
75 {
76     void* wrtInstaller;
77     std::string pluginPath;
78 };
79 } // namespace anonymous
80
81 WrtInstaller::WrtInstaller(int argc, char **argv) :
82     Application(argc, argv, "backend", false),
83     DPL::TaskDecl<WrtInstaller>(this),
84     m_installMode(WRT_INSTALL_MODE_UNKNOWN),
85     m_packagePath(),
86     m_initialized(false),
87     m_numPluginsToInstall(0),
88     m_totalPlugins(0),
89     m_returnStatus(-1),
90     m_installByPkgmgr(false),
91     m_quiet(true),
92     m_startupPluginInstallation(false)
93 {
94     Touch();
95     LogDebug("App Created");
96 }
97
98 WrtInstaller::~WrtInstaller()
99 {
100     LogDebug("App Finished");
101 }
102
103 int WrtInstaller::getReturnStatus() const
104 {
105     if (!m_returnStatus) {
106         return RE_SUCCESS;
107     } else {
108         return RE_FAIL;
109     }
110 }
111
112 void WrtInstaller::OnStop()
113 {
114     LogInfo("Stopping Dummy Client");
115 }
116
117 void WrtInstaller::OnCreate()
118 {
119     LogInfo("Creating DummyClient");
120     fprintf(stderr,
121             "===========================================================\n");
122     fprintf(stderr, "# wrt-installer #\n");
123     fprintf(stderr, "# argc [%d]\n", m_argc);
124     fprintf(stderr, "# argv[0] = [%s]\n", m_argv[0]);
125     fprintf(stderr, "# argv[1] = [%s]\n", m_argv[1]);
126     fprintf(stderr, "# argv[2] = [%s]\n", m_argv[2]);
127     fprintf(stderr,
128             "===========================================================\n");
129
130     AddStep(&WrtInstaller::initStep);
131
132     std::string arg = m_argv[0];
133
134     pkgmgrSignalInterface =
135         std::static_pointer_cast<PackageManager::IPkgmgrSignal>(
136             std::shared_ptr<PackageManager::PkgmgrSignalDummy>(
137                 new PackageManager::PkgmgrSignalDummy()
138                 )
139             );
140
141     if (arg.empty()) {
142         return showHelpAndQuit();
143     }
144
145     installNewPlugins();
146
147     if (arg.find("wrt-installer") != std::string::npos) {
148         if (m_argc <= 1) {
149             return showHelpAndQuit();
150         }
151
152         arg = m_argv[1];
153         if (arg == "-h" || arg == "--help") {
154             if (m_argc != 2) {
155                 return showHelpAndQuit();
156             }
157
158             // Just show help
159             return showHelpAndQuit();
160         } else if (arg == "-p" || arg == "--install-plugins") {
161             if (m_argc != 2) {
162                 return showHelpAndQuit();
163             }
164
165             if (!m_startupPluginInstallation) {
166                 AddStep(&WrtInstaller::installPluginsStep);
167             } else {
168                 LogInfo("Plugin installation alredy started");
169             }
170         } else if (arg == "-i" || arg == "--install") {
171             if (m_argc != 3) {
172                 return showHelpAndQuit();
173             }
174
175             struct stat info;
176             if (-1 != stat(m_argv[2], &info) && S_ISDIR(info.st_mode)) {
177                 LogInfo("Installing package directly from directory");
178                 m_installMode = WRT_INSTALL_MODE_INSTALL_DIRECTORY;
179             } else {
180                 LogInfo("Installing from regular location");
181                 m_installMode = WRT_INSTALL_MODE_INSTALL_WGT;
182             }
183             m_packagePath = m_argv[2];
184
185             AddStep(&WrtInstaller::installStep);
186         } else if (arg == "-ip" || arg == "--install-preload") {
187             LogDebug("Install preload web app");
188             if (m_argc != 3) {
189                 return showHelpAndQuit();
190             }
191             m_packagePath = m_argv[2];
192             m_installMode = WRT_INSTALL_MODE_INSTALL_PRELOAD;
193             AddStep(&WrtInstaller::installStep);
194         } else if (arg == "-un" || arg == "--uninstall-name") {
195             if (m_argc != 3) {
196                 return showHelpAndQuit();
197             }
198             m_name = m_argv[2];
199             AddStep(&WrtInstaller::uninstallPkgNameStep);
200         } else if (arg == "-up" || arg == "--uninstall-packagepath") {
201             if (m_argc != 3) {
202                 return showHelpAndQuit();
203             }
204             m_packagePath = m_argv[2];
205             AddStep(&WrtInstaller::unistallWgtFileStep);
206         } else if (arg == "-r" || arg == "--reinstall") {
207             if (m_argc != 3) {
208                 return showHelpAndQuit();
209             }
210             LogInfo("Installing package directly from directory");
211             m_installMode = WRT_INSTALL_MODE_REINSTALL;
212             m_packagePath = m_argv[2];
213             AddStep(&WrtInstaller::installStep);
214         } else {
215             return showHelpAndQuit();
216         }
217     } else if (arg.find("backend") != std::string::npos) {
218         using namespace PackageManager;
219         m_installByPkgmgr = true;
220
221         auto pkgmgrSignal = std::shared_ptr<PackageManager::PkgmgrSignal>(
222                 new PackageManager::PkgmgrSignal()
223                 );
224
225         pkgmgrSignal->initialize(m_argc, m_argv);
226         m_quiet = pkgmgrSignal->isNoPopupRequired();
227         LogDebug("backend m_quiet" << m_quiet);
228
229         int reqType = pkgmgrSignal->getRequestedType();
230
231         pkgmgrSignalInterface =
232             std::static_pointer_cast<PackageManager::IPkgmgrSignal>(
233                 pkgmgrSignal);
234         switch (reqType) {
235         case PKGMGR_REQ_INSTALL:
236             m_packagePath = m_argv[4];
237             struct stat info;
238             if (-1 != stat(m_argv[4], &info) && S_ISDIR(info.st_mode)) {
239                 LogInfo("Installing package directly from directory");
240                 m_installMode = WRT_INSTALL_MODE_INSTALL_DIRECTORY;
241             } else {
242                 LogInfo("Installing from regular location");
243                 m_installMode = WRT_INSTALL_MODE_INSTALL_WGT;
244             }
245             AddStep(&WrtInstaller::installStep);
246             break;
247         case PKGMGR_REQ_UNINSTALL:
248             m_name = m_argv[4];
249             AddStep(&WrtInstaller::uninstallPkgNameStep);
250             break;
251         case PKGMGR_REQ_REINSTALL:
252             m_packagePath = m_argv[4];
253             m_installMode = WRT_INSTALL_MODE_REINSTALL;
254             AddStep(&WrtInstaller::installStep);
255             break;
256         default:
257             LogDebug("Not available type");
258             break;
259         }
260     }
261
262     AddStep(&WrtInstaller::shutdownStep);
263     DPL::Event::ControllerEventHandler<WRTInstallerNS::NextStepEvent>::
264         PostEvent(
265         WRTInstallerNS::NextStepEvent());
266 }
267
268 void WrtInstaller::OnReset(bundle* /*b*/)
269 {
270     LogDebug("OnReset");
271 }
272
273 void WrtInstaller::OnTerminate()
274 {
275     LogDebug("Wrt Shutdown now");
276     PluginUtils::unlockPluginInstallation(m_installMode ==
277             WRT_INSTALL_MODE_INSTALL_PRELOAD);
278     if (m_initialized) {
279         wrt_installer_shutdown();
280     }
281 }
282
283 void WrtInstaller::showHelpAndQuit()
284 {
285     printf("Usage: wrt-installer [OPTION]... [WIDGET: ID/NAME/PATH]...\n"
286            "Operate with WebRuntime daemon: install, uninstall"
287            " and launch widgets.\n"
288            "Query list of installed widgets and setup up debugging support.\n"
289            "\n"
290            "Exactly one option must be selected.\n"
291            "Mandatory arguments to long options are mandatory for short "
292            "options too.\n"
293            "  -h,    --help                                 show this help\n"
294            "  -p,    --install-plugins                      install plugins\n"
295            "  -i,    --install                              "
296            "install or update widget package for given path\n"
297            "  -un,   --uninstall-name                       "
298            "uninstall widget for given package name\n"
299            "  -up,   --uninstall-packagepath                "
300            "uninstall widget for given package file path\n"
301            "  -r,    --reinstall                            "
302            "reinstall web application\n"
303            "\n");
304
305     Quit();
306 }
307
308 void WrtInstaller::OnEventReceived(const WRTInstallerNS::QuitEvent& /*event*/)
309 {
310     LogDebug("Quiting");
311
312     if (m_initialized) {
313         LogDebug("Wrt Shutdown now");
314         SwitchToStep(&WrtInstaller::shutdownStep);
315         DPL::Event::ControllerEventHandler<WRTInstallerNS::NextStepEvent>::
316             PostEvent(
317             WRTInstallerNS::NextStepEvent());
318     } else {
319         LogDebug("Quiting application");
320         return Quit();
321     }
322 }
323
324 void WrtInstaller::OnEventReceived(
325     const WRTInstallerNS::NextStepEvent& /*event*/)
326 {
327     LogDebug("Executing next step");
328     NextStep();
329 }
330
331 void WrtInstaller::OnEventReceived(
332     const WRTInstallerNS::InstallPluginEvent& /*event*/)
333 {
334     PluginInstallerData* privateData = new PluginInstallerData;
335     privateData->wrtInstaller = this;
336
337     if (!(*m_pluginsPaths).empty()) {
338         privateData->pluginPath = (*m_pluginsPaths).front();
339         (*m_pluginsPaths).pop_front();
340
341         wrt_install_plugin(privateData->pluginPath.c_str(),
342                            static_cast<void*>(privateData),
343                            &staticWrtPluginInstallationCallback,
344                            &staticWrtPluginInstallProgressCb);
345     } else {
346         delete privateData;
347     }
348 }
349
350 void WrtInstaller::initStep()
351 {
352     wrt_installer_init(this, staticWrtInitCallback);
353 }
354
355 void WrtInstaller::installStep()
356 {
357     LogDebug("Installing widget ...");
358     std::unique_ptr<char, free_deleter> packagePath(canonicalize_file_name(
359                                                         m_packagePath.c_str()));
360
361     wrt_install_widget(packagePath ? packagePath.get() : m_packagePath.c_str(),
362                        this, &staticWrtStatusCallback,
363                        (!m_quiet || m_installByPkgmgr)
364                        ? &staticWrtInstallProgressCallback : NULL,
365                        m_installMode,
366                        m_quiet,
367                        pkgmgrSignalInterface);
368 }
369
370 void WrtInstaller::installPluginsStep()
371 {
372     LogDebug("Installing plugins ...");
373     fprintf(stderr, "Installing plugins ...\n");
374
375     if (m_startupPluginInstallation) {
376         LogInfo("Plugin installation started because new plugin package found");
377     } else if (!PluginUtils::lockPluginInstallation(m_installMode ==
378                 WRT_INSTALL_MODE_INSTALL_PRELOAD)) {
379         LogError("Failed to open plugin installation lock file"
380                  " Plugins are currently installed by other process");
381         staticWrtPluginInstallationCallback(WRT_INSTALLER_ERROR_PLUGIN_INSTALLATION_FAILED,
382                                             this);
383         return;
384     }
385
386     std::string PLUGIN_PATH = std::string(GlobalConfig::GetDevicePluginPath());
387
388     DIR *dir;
389     dir = opendir(PLUGIN_PATH.c_str());
390
391     if (!dir) {
392         return;
393     }
394
395     LogInfo("Plugin DIRECTORY IS" << PLUGIN_PATH);
396
397     std::list<std::string> pluginsPaths;
398     struct dirent libdir;
399     struct dirent *result;
400     int return_code;
401     errno = 0;
402     for (return_code = readdir_r(dir, &libdir, &result);
403             result != NULL && return_code == 0;
404             return_code = readdir_r(dir, &libdir, &result))
405     {
406         if (strcmp(libdir.d_name, ".") == 0 ||
407             strcmp(libdir.d_name, "..") == 0)
408         {
409             continue;
410         }
411
412         std::string path = PLUGIN_PATH;
413         path += "/";
414         path += libdir.d_name;
415
416         struct stat tmp;
417
418         if (stat(path.c_str(), &tmp) == -1) {
419             LogError("Failed to open file" << path);
420             continue;
421         }
422
423         if (!S_ISDIR(tmp.st_mode)) {
424             LogError("Not a directory" << path);
425             continue;
426         }
427
428         pluginsPaths.push_back(path);
429     }
430
431     if (return_code != 0 || errno != 0) {
432         LogError("readdir_r() failed with " << DPL::GetErrnoString());
433     }
434
435     //set nb of plugins to install
436     //this value indicate how many callbacks are expected
437     m_numPluginsToInstall = pluginsPaths.size();
438     LogInfo("Plugins to install: " << m_numPluginsToInstall);
439     m_pluginsPaths = pluginsPaths;
440
441     m_totalPlugins = m_numPluginsToInstall;
442     DPL::Event::ControllerEventHandler<WRTInstallerNS::InstallPluginEvent>
443         ::PostEvent(WRTInstallerNS::InstallPluginEvent());
444
445     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
446         LogError("Failed to close dir: " << PLUGIN_PATH << " with error: "
447                                          << DPL::GetErrnoString());
448     }
449 }
450
451 void WrtInstaller::uninstallPkgNameStep()
452 {
453     LogDebug("Uninstalling widget ...");
454     LogDebug("Package name : " << m_name);
455     wrt_uninstall_widget(m_name.c_str(), this, &staticWrtStatusCallback,
456                          (!m_quiet || m_installByPkgmgr)
457                          ? &staticWrtUninstallProgressCallback : NULL,
458                          pkgmgrSignalInterface);
459 }
460
461 void WrtInstaller::unistallWgtFileStep()
462 {
463     LogDebug("Uninstalling widget ...");
464
465     Try {
466         // Parse config
467         ParserRunner parser;
468         ConfigParserData configInfo;
469
470         // Open zip file
471         std::unique_ptr<DPL::ZipInput> zipFile(
472             new DPL::ZipInput(m_packagePath));
473         std::unique_ptr<DPL::ZipInput::File> configFile;
474
475         Try {
476             // Open config.xml file
477             configFile.reset(zipFile->OpenFile(CONFIG_XML));
478         }
479         Catch(DPL::ZipInput::Exception::OpenFileFailed)
480         {
481             // Open config.xml file for hybrid
482             configFile.reset(zipFile->OpenFile(HYBRID_CONFIG_XML));
483         }
484
485         // Extract config
486         DPL::BinaryQueue buffer;
487         DPL::AbstractWaitableInputAdapter inputAdapter(configFile.get());
488         DPL::AbstractWaitableOutputAdapter outputAdapter(&buffer);
489         DPL::Copy(&inputAdapter, &outputAdapter);
490         parser.Parse(&buffer,
491                      ElementParserPtr(
492                          new RootParser<WidgetParser>(configInfo,
493                                                       DPL::FromUTF32String(
494                                                           L"widget"))));
495
496         DPL::OptionalString pkgId = configInfo.tizenPkgId;
497         if (!pkgId.IsNull()) {
498             LogDebug("Pkgid from packagePath : " << pkgId);
499             wrt_uninstall_widget(
500                 DPL::ToUTF8String(*pkgId).c_str(), this, &staticWrtStatusCallback,
501                 !m_quiet ? &staticWrtUninstallProgressCallback
502                 : NULL,
503                 pkgmgrSignalInterface);
504         } else {
505             LogError("Fail to uninstalling widget... ");
506             m_returnStatus = -1;
507             DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>::
508                 PostEvent(
509                 WRTInstallerNS::QuitEvent());
510         }
511     }
512     Catch(DPL::ZipInput::Exception::OpenFailed)
513     {
514         LogError("Failed to open widget package");
515         printf("failed: widget package does not exist\n");
516         m_returnStatus = -1;
517         DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>::
518             PostEvent(
519             WRTInstallerNS::QuitEvent());
520     }
521     Catch(DPL::ZipInput::Exception::OpenFileFailed)
522     {
523         printf("failed: widget config file does not exist\n");
524         LogError("Failed to open config.xml file");
525         m_returnStatus = -1;
526         DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>::
527             PostEvent(
528             WRTInstallerNS::QuitEvent());
529     }
530     Catch(ElementParser::Exception::ParseError)
531     {
532         printf("failed: can not parse config file\n");
533         LogError("Failed to parse config.xml file");
534         m_returnStatus = -1;
535         DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>::
536             PostEvent(
537             WRTInstallerNS::QuitEvent());
538     }
539 }
540
541 void WrtInstaller::shutdownStep()
542 {
543     LogDebug("Closing Wrt connection ...");
544     if (m_initialized) {
545         wrt_installer_shutdown();
546         m_initialized = false;
547         DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>::
548             PostEvent(
549             WRTInstallerNS::QuitEvent());
550     }
551 }
552
553 void WrtInstaller::staticWrtInitCallback(WrtErrStatus status,
554                                          void* userdata)
555 {
556     WrtInstaller *This = static_cast<WrtInstaller*>(userdata);
557     Assert(This);
558
559     if (status == WRT_SUCCESS) {
560         LogDebug("Init succesfull");
561         This->m_initialized = true;
562         This->m_returnStatus = 0;
563
564         This->DPL::Event::ControllerEventHandler<WRTInstallerNS::NextStepEvent>
565             ::PostEvent(WRTInstallerNS::NextStepEvent());
566     } else {
567         LogError("Init unsuccesfull");
568         This->m_returnStatus = -1;
569         This->DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>::
570             PostEvent(
571             WRTInstallerNS::QuitEvent());
572     }
573 }
574
575 void WrtInstaller::staticWrtStatusCallback(std::string tizenId,
576                                            WrtErrStatus status,
577                                            void* userdata)
578 {
579     WrtInstaller *This = static_cast<WrtInstaller*>(userdata);
580     Assert(This);
581
582     Step current = This->GetCurrentStep();
583     DPL::String resultMsg;
584     std::string printMsg;
585
586     if (current == &WrtInstaller::installStep) {
587         resultMsg = DPL::FromUTF8String(PKGMGR_INSTALL_MSG);
588         printMsg = "installation";
589     } else if (current == &WrtInstaller::uninstallPkgNameStep ||
590                current == &WrtInstaller::unistallWgtFileStep)
591     {
592         resultMsg = DPL::FromUTF8String(PKGMGR_UNINSTALL_MSG);
593         printMsg = "uninstallation";
594     }
595
596     if (WRT_SUCCESS != status) {
597         // Failure
598         LogError("Step failed");
599         This->m_returnStatus = -1;
600
601         This->DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>
602             ::PostEvent(WRTInstallerNS::QuitEvent());
603
604         switch (status) {
605             case WRT_INSTALLER_ERROR_PACKAGE_NOT_FOUND:
606                 This->m_returnStatus = 1; //this status is specific
607                 fprintf(stderr, "## wrt-installer : %s %s has failed - widget package does not exist\n",
608                         tizenId.c_str(), printMsg.c_str());
609                 break;
610
611             case WRT_INSTALLER_ERROR_PACKAGE_INVALID:
612                 This->m_returnStatus = 1; //this status is specific
613                 fprintf(stderr, "## wrt-installer : %s %s has failed - invalid widget package\n",
614                         tizenId.c_str(), printMsg.c_str());
615                 break;
616
617             case WRT_INSTALLER_ERROR_PACKAGE_LOWER_VERSION:
618                 This->m_returnStatus = 1; //this status is specific
619                 fprintf(stderr, "## wrt-installer : %s %s has failed - given"
620                         " version is lower than existing version\n",
621                         tizenId.c_str(), printMsg.c_str());
622                 break;
623
624             case WRT_INSTALLER_ERROR_MANIFEST_NOT_FOUND:
625                 This->m_returnStatus = 1; //this status is specific
626                 fprintf(stderr, "## wrt-installer : %s %s has failed - manifest"
627                         " file doesn't find in package.\n",
628                         tizenId.c_str(), printMsg.c_str());
629                 break;
630
631             case WRT_INSTALLER_ERROR_MANIFEST_INVALID:
632                 This->m_returnStatus = 1; //this status is specific
633                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
634                         "invalid manifestx.xml\n",
635                         tizenId.c_str(), printMsg.c_str());
636                 break;
637
638             case WRT_INSTALLER_CONFIG_NOT_FOUND:
639                 This->m_returnStatus = 1; //this status is specific
640                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
641                         "config.xml does not exist\n",
642                         tizenId.c_str(), printMsg.c_str());
643                 break;
644
645             case WRT_INSTALLER_ERROR_CONFIG_INVALID:
646                 This->m_returnStatus = 1; //this status is specific
647                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
648                         "invalid config.xml\n",
649                         tizenId.c_str(), printMsg.c_str());
650                 break;
651
652             case WRT_INSTALLER_ERROR_SIGNATURE_NOT_FOUND:
653                 This->m_returnStatus = 1; //this status is specific
654                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
655                         "signature doesn't exist in package.\n",
656                         tizenId.c_str(), printMsg.c_str());
657                 break;
658
659             case WRT_INSTALLER_ERROR_SIGNATURE_INVALID:
660                 This->m_returnStatus = 1; //this status is specific
661                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
662                         "invalid signature.\n",
663                         tizenId.c_str(), printMsg.c_str());
664                 break;
665
666             case WRT_INSTALLER_ERROR_SIGNATURE_VERIFICATION_FAILED:
667                 This->m_returnStatus = 1; //this status is specific
668                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
669                         "signature verification failed.\n",
670                         tizenId.c_str(), printMsg.c_str());
671                 break;
672
673             case WRT_INSTALLER_ERROR_ROOT_CERTIFICATE_NOT_FOUND:
674                 This->m_returnStatus = 1; //this status is specific
675                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
676                         "root certificate could not find.\n",
677                         tizenId.c_str(), printMsg.c_str());
678                 break;
679
680             case WRT_INSTALLER_ERROR_CERTIFICATION_INVAID:
681                 This->m_returnStatus = 1; //this status is specific
682                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
683                         "invalid certification.\n",
684                         tizenId.c_str(), printMsg.c_str());
685                 break;
686
687             case WRT_INSTALLER_ERROR_CERTIFICATE_CHAIN_VERIFICATION_FAILED:
688                 This->m_returnStatus = 1; //this status is specific
689                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
690                         "certificate chain verification failed.\n",
691                         tizenId.c_str(), printMsg.c_str());
692                 break;
693
694             case WRT_INSTALLER_ERROR_CERTIFICATE_EXPIRED:
695                 This->m_returnStatus = 1; //this status is specific
696                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
697                         "certificate expired.\n",
698                         tizenId.c_str(), printMsg.c_str());
699                 break;
700
701             case WRT_INSTALLER_ERROR_INVALID_PRIVILEGE:
702                 This->m_returnStatus = 1; //this status is specific
703                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
704                         "invalid privilege\n",
705                         tizenId.c_str(), printMsg.c_str());
706                 break;
707
708             case WRT_INSTALLER_ERROR_MENU_ICON_NOT_FOUND:
709                 This->m_returnStatus = 1; //this status is specific
710                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
711                         "menu icon could not find\n",
712                         tizenId.c_str(), printMsg.c_str());
713                 break;
714
715             case WRT_INSTALLER_ERROR_FATAL_ERROR:
716                 This->m_returnStatus = 1; //this status is specific
717                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
718                         "fatal error\n",
719                         tizenId.c_str(), printMsg.c_str());
720                 break;
721
722             case WRT_INSTALLER_ERROR_OUT_OF_STORAGE:
723                 This->m_returnStatus = 1; //this status is specific
724                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
725                         "out of storage\n",
726                         tizenId.c_str(), printMsg.c_str());
727                 break;
728
729             case WRT_INSTALLER_ERROR_OUT_OF_MEMORY:
730                 This->m_returnStatus = 1; //this status is specific
731                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
732                         "out of memory\n",
733                         tizenId.c_str(), printMsg.c_str());
734                 break;
735
736             case WRT_INSTALLER_ERROR_PACKAGE_ALREADY_INSTALLED:
737                 This->m_returnStatus = 1; //this status is specific
738                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
739                         "package already installed\n",
740                         tizenId.c_str(), printMsg.c_str());
741                 break;
742
743             case WRT_INSTALLER_ERROR_ACE_CHECK_FAILED:
744                 This->m_returnStatus = 1; //this status is specific
745                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
746                         "ace check failure\n",
747                         tizenId.c_str(), printMsg.c_str());
748                 break;
749
750             case WRT_INSTALLER_ERROR_MANIFEST_CREATE_FAILED:
751                 This->m_returnStatus = 1; //this status is specific
752                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
753                         "to create manifest failed\n",
754                         tizenId.c_str(), printMsg.c_str());
755                 break;
756
757             case WRT_INSTALLER_ERROR_ENCRYPTION_FAILED:
758                 This->m_returnStatus = 1; //this status is specific
759                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
760                         "encryption of resource failed\n",
761                         tizenId.c_str(), printMsg.c_str());
762                 break;
763
764             case WRT_INSTALLER_ERROR_INSTALL_OSP_SERVCIE:
765                 This->m_returnStatus = 1; //this status is specific
766                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
767                         "installation of osp service failed\n",
768                         tizenId.c_str(), printMsg.c_str());
769                 break;
770
771             case WRT_INSTALLER_ERROR_UNINSTALLATION_FAILED:
772                 This->m_returnStatus = 1; //this status is specific
773                 fprintf(stderr, "## wrt-installer : %s %s has failed - "
774                         "widget uninstallation failed\n",
775                         tizenId.c_str(), printMsg.c_str());
776                 break;
777
778
779             case WRT_INSTALLER_ERROR_UNKNOWN:
780                 fprintf(stderr,"## wrt-installer : %s %s has failed - unknown error\n",
781                         tizenId.c_str(), printMsg.c_str());
782                 break;
783
784             default:
785                 break;
786         }
787     } else {
788         fprintf(stderr,
789                 "## wrt-installer : %s %s was successful.\n",
790                 tizenId.c_str(),
791                 printMsg.c_str());
792         LogDebug("Status succesfull");
793         This->m_returnStatus = 0;
794         resultMsg += L" : " + DPL::FromUTF8String(PKGMGR_END_SUCCESS);
795
796         if (This->m_installMode == WRT_INSTALL_MODE_INSTALL_PRELOAD &&
797                 !This->m_packagePath.empty()) {
798             LogDebug("This widget is preloaded so it will be removed : "
799                     << This->m_packagePath);
800             if (!WrtUtilRemove(This->m_packagePath)) {
801                 LogError("Failed to remove " << This->m_packagePath);
802             }
803         }
804
805         This->DPL::Event::ControllerEventHandler<WRTInstallerNS::
806                                                      NextStepEvent>
807             ::PostEvent(WRTInstallerNS::NextStepEvent());
808     }
809 }
810
811 void WrtInstaller::staticWrtPluginInstallationCallback(WrtErrStatus status,
812                                                        void* userdata)
813 {
814     Assert(userdata);
815
816     PluginInstallerData* data = static_cast<PluginInstallerData*>(userdata);
817
818     WrtInstaller *This = static_cast<WrtInstaller*>(data->wrtInstaller);
819
820     std::string path = std::string(data->pluginPath);
821     delete data;
822
823     This->m_numPluginsToInstall--;
824     LogDebug("Plugins to install: " << This->m_numPluginsToInstall);
825
826     if (This->m_numPluginsToInstall < 1) {
827         LogDebug("All plugins installation completed");
828         fprintf(stderr, "All plugins installation completed.\n");
829
830         //remove installation request
831         if (!PluginUtils::removeInstallationRequiredFlag()) {
832             LogInfo("Failed to remove file initializing plugin installation");
833         }
834
835         //remove lock file
836         if (!PluginUtils::unlockPluginInstallation(This->m_installMode ==
837                 WRT_INSTALL_MODE_INSTALL_PRELOAD)) {
838             LogInfo("Failed to remove installation lock");
839         }
840
841         This->DPL::Event::ControllerEventHandler<WRTInstallerNS::NextStepEvent>
842             ::PostEvent(WRTInstallerNS::NextStepEvent());
843     } else {
844         This->DPL::Event::ControllerEventHandler<WRTInstallerNS::
845                                                      InstallPluginEvent>::
846             PostEvent(
847             WRTInstallerNS::InstallPluginEvent());
848     }
849
850     if (WRT_SUCCESS == status) {
851         This->m_returnStatus = 0;
852         fprintf(stderr,
853                 "## wrt-installer : plugin installation successfull [%s]\n",
854                 path.c_str());
855         LogDebug("One plugin Installation succesfull: " << path);
856         return;
857     }
858
859     // Failure
860     LogWarning("One of the plugins installation failed!: " << path);
861
862     switch (status) {
863     case WRT_INSTALLER_ERROR_PLUGIN_INSTALLATION_FAILED:
864         LogError("failed: plugin installation failed\n");
865         break;
866
867     case WRT_INSTALLER_ERROR_UNKNOWN:
868         LogError("failed: unknown error\n");
869         break;
870
871     default:
872         break;
873     }
874 }
875
876 void WrtInstaller::staticWrtPluginInstallProgressCb(float percent,
877                                                     const char* description,
878                                                     void* userdata)
879 {
880     PluginInstallerData* data = static_cast<PluginInstallerData*>(userdata);
881
882     std::string path = std::string(data->pluginPath);
883
884     LogInfo("Plugin Installation: " << path <<
885             " progress: " << percent <<
886             "description " << description);
887 }
888
889 void WrtInstaller::staticWrtInstallProgressCallback(float percent,
890                                                     const char* description,
891                                                     void* /*userdata*/)
892 {
893     //WrtInstaller *This = static_cast<WrtInstaller*>(userdata);
894     LogInfo(" progress: " << percent <<
895             " description: " << description);
896 }
897 void WrtInstaller::staticWrtUninstallProgressCallback(float percent,
898                                                       const char* description,
899                                                       void* /*userdata*/)
900 {
901     //WrtInstaller *This = static_cast<WrtInstaller*>(userdata);
902     LogInfo(" progress: " << percent <<
903             " description: " << description);
904 }
905
906 void WrtInstaller::showResultCallback(void *data, Evas_Object* /*obj*/,
907                                       void* /*event_info*/)
908 {
909     WrtInstaller *This = static_cast<WrtInstaller*>(data);
910     Assert(This);
911
912     This->DPL::Event::ControllerEventHandler<WRTInstallerNS::NextStepEvent>
913         ::PostEvent(WRTInstallerNS::NextStepEvent());
914 }
915
916 void WrtInstaller::failResultCallback(void *data, Evas_Object* /*obj*/,
917                                       void* /*event_info*/)
918 {
919     WrtInstaller *This = static_cast<WrtInstaller*>(data);
920     Assert(This);
921
922     This->DPL::Event::ControllerEventHandler<WRTInstallerNS::QuitEvent>
923         ::PostEvent(WRTInstallerNS::QuitEvent());
924 }
925
926 void WrtInstaller::installNewPlugins()
927 {
928     LogDebug("Install new plugins");
929
930     if (!PluginUtils::lockPluginInstallation(m_installMode ==
931                 WRT_INSTALL_MODE_INSTALL_PRELOAD)) {
932         LogInfo("Lock NOT created");
933         return;
934     }
935
936     if (!PluginUtils::checkPluginInstallationRequired()) {
937         LogDebug("Plugin installation not required");
938         PluginUtils::unlockPluginInstallation(m_installMode ==
939             WRT_INSTALL_MODE_INSTALL_PRELOAD);
940         return;
941     }
942
943     m_startupPluginInstallation = true;
944     AddStep(&WrtInstaller::installPluginsStep);
945 }
946
947 int main(int argc, char *argv[])
948 {
949     UNHANDLED_EXCEPTION_HANDLER_BEGIN
950     {
951         // Output on stdout will be flushed after every newline character,
952         // even if it is redirected to a pipe. This is useful for running
953         // from a script and parsing output.
954         // (Standard behavior of stdlib is to use full buffering when
955         // redirected to a pipe, which means even after an end of line
956         // the output may not be flushed).
957         setlinebuf(stdout);
958
959         // Check and re-set the file open limitation
960         struct rlimit rlim;
961         if (getrlimit(RLIMIT_NOFILE, &rlim) != -1) {
962             LogDebug("RLIMIT_NOFILE sft(" << rlim.rlim_cur << ")");
963             LogDebug("RLIMIT_NOFILE hrd(" << rlim.rlim_max << ")");
964
965             if (rlim.rlim_cur < NOFILE_CNT_FOR_INSTALLER) {
966                 rlim.rlim_cur = NOFILE_CNT_FOR_INSTALLER;
967                 rlim.rlim_max = NOFILE_CNT_FOR_INSTALLER;
968                 if (setrlimit(RLIMIT_NOFILE, &rlim) == -1) {
969                     LogError("setrlimit is fail!!");
970                 }
971             }
972         } else {
973             LogError("getrlimit is fail!!");
974         }
975
976         // set evas backend type for emulator
977         // popup isn't showed in the emulator,
978         // if backend isn't set to SW backend
979         if (GlobalSettings::IsEmulator()) {
980             if (setenv("ELM_ENGINE", "x11", 1)) {
981                 LogDebug("Enable backend");
982             }
983         }
984
985         WrtInstaller app(argc, argv);
986         int ret = app.Exec();
987         LogDebug("App returned: " << ret);
988         ret = app.getReturnStatus();
989         LogDebug("WrtInstaller returned: " << ret);
990         return ret;
991     }
992     UNHANDLED_EXCEPTION_HANDLER_END
993 }