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 "file.h"
16 #include "serial_struct.h"
17
18 namespace Hdc {
HdcFile(HTaskInfo hTaskInfo)19 HdcFile::HdcFile(HTaskInfo hTaskInfo)
20 : HdcTransferBase(hTaskInfo)
21 {
22 commandBegin = CMD_FILE_BEGIN;
23 commandData = CMD_FILE_DATA;
24 }
25
~HdcFile()26 HdcFile::~HdcFile()
27 {
28 WRITE_LOG(LOG_DEBUG, "~HdcFile");
29 };
30
StopTask()31 void HdcFile::StopTask()
32 {
33 WRITE_LOG(LOG_DEBUG, "HdcFile StopTask");
34 singalStop = true;
35 };
36
BeginTransfer(CtxFile * context,const string & command)37 bool HdcFile::BeginTransfer(CtxFile *context, const string &command)
38 {
39 int argc = 0;
40 bool ret = false;
41 char **argv = Base::SplitCommandToArgs(command.c_str(), &argc);
42 if (argc < CMD_ARG1_COUNT || argv == nullptr) {
43 LogMsg(MSG_FAIL, "Transfer path split failed");
44 if (argv) {
45 delete[](reinterpret_cast<char *>(argv));
46 }
47 return false;
48 }
49 if (!SetMasterParameters(context, command.c_str(), argc, argv)) {
50 delete[](reinterpret_cast<char *>(argv));
51 return false;
52 }
53 do {
54 ++refCount;
55 uv_fs_open(loopTask, &context->fsOpenReq, context->localPath.c_str(), O_RDONLY, S_IWUSR | S_IRUSR, OnFileOpen);
56 context->master = true;
57 ret = true;
58 } while (false);
59 if (!ret) {
60 LogMsg(MSG_FAIL, "Transfer path failed, Master:%s Slave:%s", context->localPath.c_str(),
61 context->remotePath.c_str());
62 }
63 delete[](reinterpret_cast<char *>(argv));
64 return ret;
65 }
66
SetMasterParameters(CtxFile * context,const char * command,int argc,char ** argv)67 bool HdcFile::SetMasterParameters(CtxFile *context, const char *command, int argc, char **argv)
68 {
69 int srcArgvIndex = 0;
70 string errStr;
71 const string cmdOptionTstmp = "-a";
72 const string cmdOptionSync = "-sync";
73 const string cmdOptionZip = "-z";
74 const string cmdOptionModeSync = "-m";
75
76 for (int i = 0; i < argc; i++) {
77 if (argv[i] == cmdOptionZip) {
78 context->transferConfig.compressType = COMPRESS_LZ4;
79 ++srcArgvIndex;
80 } else if (argv[i] == cmdOptionSync) {
81 context->transferConfig.updateIfNew = true;
82 ++srcArgvIndex;
83 } else if (argv[i] == cmdOptionTstmp) {
84 // The time zone difference may cause the display time on the PC and the
85 // device to differ by several hours
86 //
87 // ls -al --full-time
88 context->transferConfig.holdTimestamp = true;
89 ++srcArgvIndex;
90 } else if (argv[i] == CMD_OPTION_CLIENTCWD) {
91 context->transferConfig.clientCwd = argv[i + 1];
92 srcArgvIndex += CMD_ARG1_COUNT; // skip 2args
93 } else if (argv[i] == cmdOptionModeSync) {
94 context->fileModeSync = true;
95 ++srcArgvIndex;
96 } else if (argv[i] == CMDSTR_REMOTE_PARAMETER) {
97 ++srcArgvIndex;
98 } else if (argv[i][0] == '-') {
99 LogMsg(MSG_FAIL, "Unknown file option: %s", argv[i]);
100 return false;
101 }
102 }
103 if (argc == srcArgvIndex) {
104 LogMsg(MSG_FAIL, "There is no local and remote path");
105 return false;
106 }
107 context->remotePath = argv[argc - 1];
108 context->localPath = argv[argc - 2];
109 if (taskInfo->serverOrDaemon) {
110 // master and server
111 if ((srcArgvIndex + 1) == argc) {
112 LogMsg(MSG_FAIL, "There is no remote path");
113 return false;
114 }
115 ExtractRelativePath(context->transferConfig.clientCwd, context->localPath);
116 } else {
117 if ((srcArgvIndex + 1) == argc) {
118 context->remotePath = ".";
119 context->localPath = argv[argc - 1];
120 }
121 }
122
123 context->localName = Base::GetFullFilePath(context->localPath);
124
125 mode_t mode = mode_t(~S_IFMT);
126 if (!Base::CheckDirectoryOrPath(context->localPath.c_str(), true, true, errStr, mode) && (mode & S_IFDIR)) {
127 context->isDir = true;
128 GetSubFilesRecursively(context->localPath, context->localName, &context->taskQueue);
129 if (context->taskQueue.size() == 0) {
130 LogMsg(MSG_FAIL, "Directory empty.");
131 return false;
132 }
133 context->fileCnt = 0;
134 context->dirSize = 0;
135 context->localDirName = Base::GetPathWithoutFilename(context->localPath);
136
137 WRITE_LOG(LOG_DEBUG, "context->localDirName = %s", context->localDirName.c_str());
138
139 context->localName = context->taskQueue.back();
140 context->localPath = context->localDirName + context->localName;
141
142 WRITE_LOG(LOG_DEBUG, "localName = %s context->localPath = %s", context->localName.c_str(),
143 context->localPath.c_str());
144 context->taskQueue.pop_back();
145 }
146 return true;
147 }
148
CheckMaster(CtxFile * context)149 void HdcFile::CheckMaster(CtxFile *context)
150 {
151 if (context->fileModeSync) {
152 string s = SerialStruct::SerializeToString(context->fileMode);
153 SendToAnother(CMD_FILE_MODE, reinterpret_cast<uint8_t *>(const_cast<char *>(s.c_str())), s.size());
154 } else {
155 string s = SerialStruct::SerializeToString(context->transferConfig);
156 SendToAnother(CMD_FILE_CHECK, reinterpret_cast<uint8_t *>(const_cast<char *>(s.c_str())), s.size());
157 }
158 }
159
WhenTransferFinish(CtxFile * context)160 void HdcFile::WhenTransferFinish(CtxFile *context)
161 {
162 WRITE_LOG(LOG_DEBUG, "HdcTransferBase WhenTransferFinish");
163 uint8_t flag = 1;
164 context->fileCnt++;
165 context->dirSize += context->indexIO;
166 SendToAnother(CMD_FILE_FINISH, &flag, 1);
167 }
168
TransferSummary(CtxFile * context)169 void HdcFile::TransferSummary(CtxFile *context)
170 {
171 uint64_t nMSec = Base::GetRuntimeMSec() -
172 (context->fileCnt > 1 ? context->transferDirBegin : context->transferBegin);
173 uint64_t fSize = context->fileCnt > 1 ? context->dirSize : context->indexIO;
174 double fRate = static_cast<double>(fSize) / nMSec; // / /1000 * 1000 = 0
175 if (context->indexIO >= context->fileSize) {
176 WRITE_LOG(LOG_INFO, "HdcFile::TransferSummary success");
177 LogMsg(MSG_OK, "FileTransfer finish, Size:%lld, File count = %d, time:%lldms rate:%.2lfkB/s",
178 fSize, context->fileCnt, nMSec, fRate);
179 } else {
180 constexpr int bufSize = 1024;
181 char buf[bufSize] = { 0 };
182 uv_strerror_r(static_cast<int>(-context->lastErrno), buf, bufSize);
183 LogMsg(MSG_FAIL, "Transfer Stop at:%lld/%lld(Bytes), Reason: %s", context->indexIO, context->fileSize,
184 buf);
185 }
186 }
187
FileModeSync(const uint16_t cmd,uint8_t * payload,const int payloadSize)188 bool HdcFile::FileModeSync(const uint16_t cmd, uint8_t *payload, const int payloadSize)
189 {
190 if (ctxNow.master) {
191 WRITE_LOG(LOG_DEBUG, "FileModeSync master ctxNow.fileModeSync = %d size = %zu", ctxNow.fileModeSync,
192 ctxNow.dirMode.size());
193 if (ctxNow.dirMode.size() > 0) {
194 auto mode = ctxNow.dirMode.back();
195 WRITE_LOG(LOG_DEBUG, "file = %s permissions: %o u_id = %u, g_id = %u conext = %s",
196 mode.fullName.c_str(), mode.perm, mode.u_id, mode.g_id, mode.context.c_str());
197 string s = SerialStruct::SerializeToString(mode);
198 ctxNow.dirMode.pop_back();
199 SendToAnother(CMD_DIR_MODE, reinterpret_cast<uint8_t *>(const_cast<char *>(s.c_str())), s.size());
200 } else {
201 string s = SerialStruct::SerializeToString(ctxNow.transferConfig);
202 SendToAnother(CMD_FILE_CHECK, reinterpret_cast<uint8_t *>(const_cast<char *>(s.c_str())), s.size());
203 }
204 } else {
205 ctxNow.fileModeSync = true;
206 string serialString(reinterpret_cast<char *>(payload), payloadSize);
207 if (cmd == CMD_FILE_MODE) {
208 SerialStruct::ParseFromString(ctxNow.fileMode, serialString);
209 } else {
210 FileMode dirMode;
211 SerialStruct::ParseFromString(dirMode, serialString);
212
213 WRITE_LOG(LOG_DEBUG, "file = %s permissions: %o u_id = %u, g_id = %u context = %s",
214 dirMode.fullName.c_str(), dirMode.perm, dirMode.u_id, dirMode.g_id, dirMode.context.c_str());
215
216 vector<string> dirsOfOptName;
217 if (dirMode.fullName.find('/') != string::npos) {
218 WRITE_LOG(LOG_DEBUG, "dir mode create parent dir from linux system");
219 Base::SplitString(dirMode.fullName, "/", dirsOfOptName);
220 } else if (dirMode.fullName.find('\\') != string::npos) {
221 WRITE_LOG(LOG_DEBUG, "dir mode create parent dir from windows system");
222 Base::SplitString(dirMode.fullName, "\\", dirsOfOptName);
223 } else {
224 dirsOfOptName.emplace_back(dirMode.fullName);
225 }
226
227 dirMode.fullName = "";
228 for (auto s : dirsOfOptName) {
229 if (dirMode.fullName.empty()) {
230 dirMode.fullName = s;
231 } else {
232 dirMode.fullName = dirMode.fullName + Base::GetPathSep() + s;
233 }
234 }
235 WRITE_LOG(LOG_DEBUG, "dir = %s permissions: %o u_id = %u, g_id = %u context = %s",
236 dirMode.fullName.c_str(), dirMode.perm, dirMode.u_id, dirMode.g_id, dirMode.context.c_str());
237 ctxNow.dirModeMap.insert(std::make_pair(dirMode.fullName, dirMode));
238 }
239 SendToAnother(CMD_FILE_MODE, nullptr, 0);
240 }
241 return true;
242 }
243
SlaveCheck(uint8_t * payload,const int payloadSize)244 bool HdcFile::SlaveCheck(uint8_t *payload, const int payloadSize)
245 {
246 bool ret = true;
247 bool childRet = false;
248 string errStr;
249 // parse option
250 string serialString(reinterpret_cast<char *>(payload), payloadSize);
251 TransferConfig &stat = ctxNow.transferConfig;
252 SerialStruct::ParseFromString(stat, serialString);
253 ctxNow.fileSize = stat.fileSize;
254 ctxNow.localPath = stat.path;
255 ctxNow.master = false;
256 ctxNow.fsOpenReq.data = &ctxNow;
257 #ifdef HDC_DEBUG
258 WRITE_LOG(LOG_DEBUG, "HdcFile fileSize got %" PRIu64 "", ctxNow.fileSize);
259 #endif
260
261 if (!CheckLocalPath(ctxNow.localPath, stat.optionalName, errStr)) {
262 LogMsg(MSG_FAIL, "%s", errStr.c_str());
263 return false;
264 }
265
266 if (!CheckFilename(ctxNow.localPath, stat.optionalName, errStr)) {
267 LogMsg(MSG_FAIL, "%s", errStr.c_str());
268 return false;
269 }
270 // check path
271 childRet = SmartSlavePath(stat.clientCwd, ctxNow.localPath, stat.optionalName.c_str());
272 if (childRet && ctxNow.transferConfig.updateIfNew) { // file exist and option need update
273 // if is newer
274 uv_fs_t fs = {};
275 uv_fs_stat(nullptr, &fs, ctxNow.localPath.c_str(), nullptr);
276 uv_fs_req_cleanup(&fs);
277 if ((uint64_t)fs.statbuf.st_mtim.tv_sec >= ctxNow.transferConfig.mtime) {
278 LogMsg(MSG_FAIL, "Target file is the same date or newer,path: %s", ctxNow.localPath.c_str());
279 return false;
280 }
281 }
282 // begin work
283 ++refCount;
284 uv_fs_open(loopTask, &ctxNow.fsOpenReq, ctxNow.localPath.c_str(), UV_FS_O_TRUNC | UV_FS_O_CREAT | UV_FS_O_WRONLY,
285 S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH, OnFileOpen);
286 if (ctxNow.transferDirBegin == 0) {
287 ctxNow.transferDirBegin = Base::GetRuntimeMSec();
288 }
289 ctxNow.transferBegin = Base::GetRuntimeMSec();
290 return ret;
291 }
292
TransferNext(CtxFile * context)293 void HdcFile::TransferNext(CtxFile *context)
294 {
295 WRITE_LOG(LOG_DEBUG, "HdcFile::TransferNext");
296
297 context->localName = context->taskQueue.back();
298 context->localPath = context->localDirName + context->localName;
299 context->taskQueue.pop_back();
300 WRITE_LOG(LOG_DEBUG, "context->localName = %s context->localPath = %s queuesize:%d",
301 context->localName.c_str(), context->localPath.c_str(), ctxNow.taskQueue.size());
302 do {
303 ++refCount;
304 uv_fs_open(loopTask, &context->fsOpenReq, context->localPath.c_str(), O_RDONLY, S_IWUSR | S_IRUSR, OnFileOpen);
305 } while (false);
306
307 return;
308 }
309
CommandDispatch(const uint16_t command,uint8_t * payload,const int payloadSize)310 bool HdcFile::CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize)
311 {
312 HdcTransferBase::CommandDispatch(command, payload, payloadSize);
313 bool ret = true;
314 switch (command) {
315 case CMD_FILE_INIT: { // initial
316 string s = string(reinterpret_cast<char *>(payload), payloadSize);
317 ret = BeginTransfer(&ctxNow, s);
318 ctxNow.transferBegin = Base::GetRuntimeMSec();
319 break;
320 }
321 case CMD_FILE_CHECK: {
322 ret = SlaveCheck(payload, payloadSize);
323 break;
324 }
325 case CMD_FILE_MODE:
326 case CMD_DIR_MODE: {
327 ret = FileModeSync(command, payload, payloadSize);
328 break;
329 }
330 case CMD_FILE_FINISH: {
331 if (*payload) { // close-step3
332 WRITE_LOG(LOG_DEBUG, "Dir = %d taskQueue size = %d", ctxNow.isDir, ctxNow.taskQueue.size());
333 if (ctxNow.isDir && (ctxNow.taskQueue.size() > 0)) {
334 TransferNext(&ctxNow);
335 } else {
336 ctxNow.ioFinish = true;
337 ctxNow.transferDirBegin = 0;
338 --(*payload);
339 SendToAnother(CMD_FILE_FINISH, payload, 1);
340 }
341 } else { // close-step3
342 TransferSummary(&ctxNow);
343 TaskFinish();
344 }
345 break;
346 }
347 default:
348 break;
349 }
350 return ret;
351 }
352 } // namespace Hdc
353