1 /*
2 * Copyright (C) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "daemon_app.h"
16 #include "decompress.h"
17
18 namespace Hdc {
HdcDaemonApp(HTaskInfo hTaskInfo)19 HdcDaemonApp::HdcDaemonApp(HTaskInfo hTaskInfo)
20 : HdcTransferBase(hTaskInfo)
21 {
22 commandBegin = CMD_APP_BEGIN;
23 commandData = CMD_APP_DATA;
24 funcAppModFinish = nullptr;
25 }
26
~HdcDaemonApp()27 HdcDaemonApp::~HdcDaemonApp()
28 {
29 WRITE_LOG(LOG_INFO, "~HdcDaemonApp channelId:%u", taskInfo->channelId);
30 }
31
ReadyForRelease()32 bool HdcDaemonApp::ReadyForRelease()
33 {
34 if (!HdcTaskBase::ReadyForRelease()) {
35 WRITE_LOG(LOG_WARN, "HdcTaskBase not ready for release channelId:%u", taskInfo->channelId);
36 return false;
37 }
38 if (!asyncCommand.ReadyForRelease()) {
39 WRITE_LOG(LOG_WARN, "asyncCommand not ready for release channelId:%u", taskInfo->channelId);
40 return false;
41 }
42 WRITE_LOG(LOG_INFO, "ReadyForRelease channelId:%u", taskInfo->channelId);
43 return true;
44 }
45
CommandDispatch(const uint16_t command,uint8_t * payload,const int payloadSize)46 bool HdcDaemonApp::CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize)
47 {
48 if (!HdcTransferBase::CommandDispatch(command, payload, payloadSize)) {
49 WRITE_LOG(LOG_WARN, "HdcTransferBase::CommandDispatch false command:%u channelId:%u",
50 command, taskInfo->channelId);
51 return false;
52 }
53 bool ret = true;
54 switch (command) {
55 case CMD_APP_CHECK: {
56 string dstPath = "/data/local/tmp/";
57 string bufString(reinterpret_cast<char *>(payload), payloadSize);
58 SerialStruct::ParseFromString(ctxNow.transferConfig, bufString);
59 // update transferconfig to main context
60 ctxNow.master = false;
61 ctxNow.fsOpenReq.data = &ctxNow;
62 #ifdef HDC_PCDEBUG
63 char tmpPath[256] = "";
64 size_t size = 256;
65 uv_os_tmpdir(tmpPath, &size);
66 dstPath = tmpPath;
67 dstPath += Base::GetPathSep();
68 #endif
69 dstPath += ctxNow.transferConfig.optionalName;
70 ctxNow.localPath = dstPath;
71 ctxNow.transferBegin = Base::GetRuntimeMSec();
72 ctxNow.fileSize = ctxNow.transferConfig.fileSize;
73 ++refCount;
74 uv_fs_open(loopTask, &ctxNow.fsOpenReq, ctxNow.localPath.c_str(),
75 UV_FS_O_TRUNC | UV_FS_O_CREAT | UV_FS_O_WRONLY, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH,
76 OnFileOpen);
77 break;
78 }
79 case CMD_APP_UNINSTALL: {
80 // This maybe has a command implanting risk, since it is a controllable device, it can be ignored
81 string bufString(reinterpret_cast<char *>(payload), payloadSize);
82 string options = "";
83 string packages = "";
84 vector<string> segments;
85 Base::SplitString(bufString, " ", segments);
86 for (auto seg: segments) {
87 if (seg[0] == '-') {
88 options += " " + seg;
89 } else {
90 packages += " " + seg;
91 }
92 }
93 PackageShell(false, options.c_str(), packages);
94 break;
95 }
96 default:
97 break;
98 }
99 return ret;
100 };
101
AsyncInstallFinish(bool finish,int64_t exitStatus,const string result)102 bool HdcDaemonApp::AsyncInstallFinish(bool finish, int64_t exitStatus, const string result)
103 {
104 if (mode == APPMOD_INSTALL) {
105 unlink(ctxNow.localPath.c_str());
106 string::size_type rindex = ctxNow.localPath.rfind(".tar");
107 if (rindex != string::npos) {
108 string dir = ctxNow.localPath.substr(0, rindex);
109 RemovePath(dir);
110 WRITE_LOG(LOG_DEBUG, "RemovePath dir:%s", dir.c_str());
111 }
112 }
113 asyncCommand.DoRelease();
114 string echo = result;
115 echo = Base::ReplaceAll(echo, "\n", " ");
116 vector<uint8_t> vecBuf;
117 vecBuf.push_back(mode);
118 vecBuf.push_back(exitStatus == 0);
119 vecBuf.insert(vecBuf.end(), (uint8_t *)echo.c_str(), (uint8_t *)echo.c_str() + echo.size());
120 SendToAnother(CMD_APP_FINISH, vecBuf.data(), vecBuf.size());
121 --refCount;
122 #ifdef UNIT_TEST
123 Base::WriteBinFile((UT_TMP_PATH + "/appinstall.result").c_str(), (uint8_t *)MESSAGE_SUCCESS.c_str(),
124 MESSAGE_SUCCESS.size(), true);
125 #endif
126 return true;
127 }
128
PackageShell(bool installOrUninstall,const char * options,const string package)129 void HdcDaemonApp::PackageShell(bool installOrUninstall, const char *options, const string package)
130 {
131 ++refCount;
132 // asynccmd Other processes, no RunningProtect protection
133 chmod(package.c_str(), 0755);
134 string doBuf;
135 string opts = string(options);
136 if (installOrUninstall) { // either -p or -s is always required in install
137 if (opts.find("p") == string::npos && opts.find("s") == string::npos) {
138 // basic mode: blank options or both "-s" / "-p" are omitted
139 // eg. hdc install x.hap --> bm install -p x.hap
140 // eg. hdc install -r x.hap --> bm install -r -p x.hap
141 doBuf = Base::StringFormat("bm install %s -p %s", options, package.c_str());
142 } else {
143 // advansed mode for -p/-r/-s and some other options in the future
144 doBuf = Base::StringFormat("bm install %s %s", options, package.c_str());
145 }
146 } else { // -n is always required in uninstall
147 if (opts.find("n") == string::npos) {
148 // basic mode: blank options or "-n" is omitted
149 // eg. hdc uninstall com.xx.xx --> bm uninstall -n com.xx.xx
150 // eg. hdc uninstall -s com.xx.xx --> bm uninstall -s -n com.xx.xx
151 doBuf = Base::StringFormat("bm uninstall %s -n %s", options, package.c_str());
152 } else {
153 // advansed mode for -s/-n and some other options in the future
154 doBuf = Base::StringFormat("bm uninstall %s %s", options, package.c_str());
155 }
156 }
157
158 funcAppModFinish = [this](bool finish, int64_t exitStatus, const string result) -> bool {
159 return this->AsyncInstallFinish(finish, exitStatus, result);
160 };
161 if (installOrUninstall) {
162 mode = APPMOD_INSTALL;
163 } else {
164 mode = APPMOD_UNINSTALL;
165 }
166 asyncCommand.Initial(loopTask, funcAppModFinish, AsyncCmd::OPTION_COMMAND_ONETIME);
167 asyncCommand.ExecuteCommand(doBuf);
168 }
169
Sideload(const char * pathOTA)170 void HdcDaemonApp::Sideload(const char *pathOTA)
171 {
172 mode = APPMOD_SIDELOAD;
173 LogMsg(MSG_OK, "[placeholders] sideload %s", pathOTA);
174 TaskFinish();
175 unlink(pathOTA);
176 }
177
Tar2Dir(const char * path)178 string HdcDaemonApp::Tar2Dir(const char *path)
179 {
180 string dir;
181 string tarpath = path;
182 string::size_type rindex = tarpath.rfind(".tar");
183 if (rindex != string::npos) {
184 dir = tarpath.substr(0, rindex) + Base::GetPathSep();
185 WRITE_LOG(LOG_DEBUG, "path:%s dir:%s", path, dir.c_str());
186 Decompress dc(tarpath);
187 dc.DecompressToLocal(dir);
188 }
189 return dir;
190 }
191
RemoveDir(const string & dir)192 int HdcDaemonApp::RemoveDir(const string &dir)
193 {
194 DIR *pdir = opendir(dir.c_str());
195 if (pdir == nullptr) {
196 WRITE_LOG(LOG_FATAL, "opendir failed dir:%s", dir.c_str());
197 return -1;
198 }
199 struct dirent *ent;
200 struct stat st;
201 while ((ent = readdir(pdir)) != nullptr) {
202 if (ent->d_name[0] == '.') {
203 continue;
204 }
205 std::string subpath = dir + Base::GetPathSep() + ent->d_name;
206 if (lstat(subpath.c_str(), &st) == -1) {
207 WRITE_LOG(LOG_WARN, "lstat failed subpath:%s", subpath.c_str());
208 continue;
209 }
210 if (S_ISDIR(st.st_mode)) {
211 if (RemoveDir(subpath) == -1) {
212 closedir(pdir);
213 return -1;
214 }
215 rmdir(subpath.c_str());
216 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
217 unlink(subpath.c_str());
218 } else {
219 WRITE_LOG(LOG_DEBUG, "lstat st_mode:%07o subpath:%s", st.st_mode, subpath.c_str());
220 }
221 }
222 if (rmdir(dir.c_str()) == -1) {
223 closedir(pdir);
224 return -1;
225 }
226 closedir(pdir);
227 return 0;
228 }
229
RemovePath(const string & path)230 void HdcDaemonApp::RemovePath(const string &path)
231 {
232 struct stat st;
233 if (lstat(path.c_str(), &st) == -1) {
234 WRITE_LOG(LOG_WARN, "lstat failed path:%s", path.c_str());
235 return;
236 }
237 if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
238 unlink(path.c_str());
239 } else if (S_ISDIR(st.st_mode)) {
240 if (path == "." || path == "..") {
241 return;
242 }
243 int rc = RemoveDir(path);
244 WRITE_LOG(LOG_INFO, "RemoveDir rc:%d path:%s", rc, path.c_str());
245 }
246 }
247
WhenTransferFinish(CtxFile * context)248 void HdcDaemonApp::WhenTransferFinish(CtxFile *context)
249 {
250 if (context->lastErrno > 0) {
251 constexpr int bufSize = 1024;
252 char buf[bufSize] = { 0 };
253 uv_strerror_r(static_cast<int>(-context->lastErrno), buf, bufSize);
254 WRITE_LOG(LOG_DEBUG, "HdcDaemonApp WhenTransferFinish with errno:%d", context->lastErrno);
255 LogMsg(MSG_FAIL, "Transfer App at:%lld/%lld(Bytes), Reason: %s",
256 context->indexIO, context->fileSize, buf);
257 return;
258 }
259 if (ctxNow.transferConfig.functionName == CMDSTR_APP_SIDELOAD) {
260 Sideload(context->localPath.c_str());
261 } else if (ctxNow.transferConfig.functionName == CMDSTR_APP_INSTALL) {
262 string dir = Tar2Dir(context->localPath.c_str());
263 if (!dir.empty()) {
264 PackageShell(true, context->transferConfig.options.c_str(), dir.c_str());
265 } else {
266 PackageShell(true, context->transferConfig.options.c_str(), context->localPath.c_str());
267 }
268 } else {
269 }
270 };
271 }
272