1 /*
2 * Copyright (C) 2024 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
16 #include <cerrno>
17 #include <fcntl.h>
18 #include <memory>
19 #include <string>
20 #include <sys/mman.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24
25 #include "file_metadata_stream.h"
26 #include "image_log.h"
27 #include "image_utils.h"
28 #include "metadata_stream.h"
29
30 #undef LOG_DOMAIN
31 #define LOG_DOMAIN LOG_TAG_DOMAIN_ID_IMAGE
32
33 #undef LOG_TAG
34 #define LOG_TAG "FileMetadataStream"
35
36 namespace OHOS {
37 namespace Media {
FWrite(const void * src,size_t size,ssize_t nmemb,FILE * file)38 ssize_t FileWrapper::FWrite(const void *src, size_t size, ssize_t nmemb, FILE *file)
39 {
40 return ::fwrite(src, size, nmemb, file);
41 }
42
FRead(void * destv,size_t size,ssize_t nmemb,FILE * file)43 ssize_t FileWrapper::FRead(void *destv, size_t size, ssize_t nmemb, FILE *file)
44 {
45 return ::fread(destv, size, nmemb, file);
46 }
47
FileMetadataStream(const std::string & filePath,const std::string & originalPath)48 FileMetadataStream::FileMetadataStream(const std::string &filePath, const std::string &originalPath)
49 {
50 initPath_ = INIT_FROM_PATH;
51 Initialize(filePath);
52 originalPath_ = originalPath;
53 }
54
FileMetadataStream(int fileDescriptor,int originalFd)55 FileMetadataStream::FileMetadataStream(int fileDescriptor, int originalFd)
56 {
57 initPath_ = INIT_FROM_FD;
58 Initialize("", fileDescriptor);
59 originalFd_ = originalFd;
60 }
61
FileMetadataStream(const std::string & filePath,std::unique_ptr<FileWrapper> fileWrapper)62 FileMetadataStream::FileMetadataStream(const std::string &filePath, std::unique_ptr<FileWrapper> fileWrapper)
63 : fp_(nullptr), fileWrapper_(std::move(fileWrapper))
64 {
65 initPath_ = INIT_FROM_PATH;
66 Initialize(filePath);
67 }
68
~FileMetadataStream()69 FileMetadataStream::~FileMetadataStream()
70 {
71 Close();
72 }
73
Initialize(const std::string & filePath,int fileDescriptor)74 void FileMetadataStream::Initialize(const std::string &filePath, int fileDescriptor)
75 {
76 this->fp_ = nullptr;
77 this->filePath_ = filePath;
78 this->dupFD_ = dup(fileDescriptor);
79 if (!fileWrapper_) {
80 this->fileWrapper_ = std::make_unique<FileWrapper>();
81 }
82 mappedMemory_ = nullptr;
83 }
84
85 // Error handling function
HandleFileError(const std::string & operation,const std::string & filePath,int fileDescriptor,ssize_t result,ssize_t expectedSize)86 void HandleFileError(const std::string &operation, const std::string &filePath, int fileDescriptor, ssize_t result,
87 ssize_t expectedSize)
88 {
89 std::string buf(METADATA_STREAM_ERROR_BUFFER_SIZE, '\0');
90 strerror_r(errno, &buf[0], buf.size());
91
92 if (fileDescriptor != -1) { // If the operation is through a file descriptor
93 IMAGE_LOGE("%{public}s file failed: %{public}d, reason: "
94 "%{public}s. result is %{public}zd, expected size is %{public}zd",
95 operation.c_str(), fileDescriptor, buf.c_str(), result, expectedSize);
96 } else { // If the operation is through a file path
97 IMAGE_LOGE("%{public}s file failed: %{public}s, reason: "
98 "%{public}s. result is %{public}zd, expected size is %{public}zd",
99 operation.c_str(), filePath.c_str(), buf.c_str(), result, expectedSize);
100 }
101 }
102
Write(byte * data,ssize_t size)103 ssize_t FileMetadataStream::Write(byte *data, ssize_t size)
104 {
105 if (fp_ == nullptr) {
106 HandleFileError("Write", filePath_, -1, -1, size);
107 return -1;
108 }
109
110 ssize_t result = fileWrapper_->FWrite(data, 1, size, fp_);
111 if (result != size || (ferror(fp_) != 0)) {
112 HandleFileError("Write", filePath_, (initPath_ == INIT_FROM_FD) ? dupFD_ : -1, result, size);
113 return -1;
114 }
115
116 return result;
117 }
118
Read(byte * buf,ssize_t size)119 ssize_t FileMetadataStream::Read(byte *buf, ssize_t size)
120 {
121 if (fp_ == nullptr) {
122 HandleFileError("Read", filePath_, -1, -1, size);
123 return -1;
124 }
125 if (size == 0) {
126 return 0;
127 }
128
129 ssize_t result = fileWrapper_->FRead(buf, 1, size, fp_);
130 if (result == 0 && ferror(fp_) != 0) {
131 HandleFileError("Read", filePath_, (initPath_ == INIT_FROM_FD) ? dupFD_ : -1, result, size);
132 return -1;
133 }
134
135 return result;
136 }
137
ReadByte()138 int FileMetadataStream::ReadByte()
139 {
140 if (fp_ == nullptr) {
141 HandleFileError("ReadByte", filePath_, -1, -1, 1);
142 return -1;
143 }
144
145 int byte = fgetc(fp_);
146 if (byte == EOF) {
147 HandleFileError("ReadByte", filePath_, (initPath_ == INIT_FROM_FD) ? dupFD_ : -1, byte, 1);
148 return -1;
149 }
150
151 return byte;
152 }
153
Seek(long offset,SeekPos pos)154 long FileMetadataStream::Seek(long offset, SeekPos pos)
155 {
156 if (fp_ == nullptr) {
157 HandleFileError("Seek", filePath_, -1, -1, offset);
158 return -1;
159 }
160
161 int origin;
162 switch (pos) {
163 case SeekPos::BEGIN:
164 origin = SEEK_SET;
165 break;
166 case SeekPos::CURRENT:
167 origin = SEEK_CUR;
168 break;
169 case SeekPos::END:
170 origin = SEEK_END;
171 break;
172 default:
173 return -1;
174 }
175
176 int result = fseek(fp_, offset, origin);
177 if (result != 0) {
178 HandleFileError("Seek", filePath_, (initPath_ == INIT_FROM_FD) ? dupFD_ : -1, result, offset);
179 return -1;
180 }
181
182 return ftell(fp_);
183 }
184
Tell()185 long FileMetadataStream::Tell()
186 {
187 if (fp_ == nullptr) {
188 if (initPath_ == INIT_FROM_FD) {
189 IMAGE_LOGE("Tell file failed: %{public}d, reason: %{public}s", dupFD_, "fp is nullptr");
190 } else if (initPath_ == INIT_FROM_PATH) {
191 IMAGE_LOGE("Tell file failed: %{public}s, reason: %{public}s", filePath_.c_str(), "fp is nullptr");
192 } else if (initPath_ == INIT_FROM_UNKNOWN) {
193 IMAGE_LOGE("Tell file failed: %{public}s, reason: %{public}s", "initPath is INIT_FROM_UNKNOWN",
194 "fp is nullptr");
195 }
196 IMAGE_LOGE("Tell file failed: %{public}s, reason: %{public}s", filePath_.c_str(), "fp is nullptr");
197 return -1;
198 }
199
200 return ftell(fp_);
201 }
202
IsEof()203 bool FileMetadataStream::IsEof()
204 {
205 if (fp_ == nullptr) {
206 HandleFileError("Check EOF", "", -1, -1, -1);
207 return true;
208 }
209
210 if (ferror(fp_) != 0) {
211 HandleFileError("Check EOF", "", fileno(fp_), -1, -1);
212 return true;
213 }
214
215 long currentPos = ftell(fp_);
216 if (Seek(0, SeekPos::END) == -1) {
217 return true;
218 }
219
220 long fileSize = ftell(fp_);
221
222 bool isEof = currentPos == fileSize;
223
224 if (Seek(currentPos, SeekPos::BEGIN) == -1) {
225 return true;
226 }
227
228 return isEof;
229 }
230
IsOpen()231 bool FileMetadataStream::IsOpen()
232 {
233 return fp_ != nullptr;
234 }
235
Close()236 void FileMetadataStream::Close()
237 {
238 ReleaseAddr();
239
240 // If the file is not open, return directly
241 if (fp_ != nullptr) {
242 fclose(fp_);
243 fp_ = nullptr;
244 }
245
246 // Close the file
247 int tmpFD = dupFD_;
248 dupFD_ = -1;
249
250 // Reset all member variables
251 if (initPath_ == INIT_FROM_FD) {
252 IMAGE_LOGD("File closed: %{public}d", tmpFD);
253 } else if (initPath_ == INIT_FROM_PATH) {
254 IMAGE_LOGD("File closed: %{public}s", filePath_.c_str());
255 }
256 initPath_ = INIT_FROM_UNKNOWN;
257 }
258
OpenFromFD(const char * modeStr)259 bool FileMetadataStream::OpenFromFD(const char *modeStr)
260 {
261 if (dupFD_ == -1) {
262 HandleFileError("Open file", filePath_, -1, -1, -1);
263 return false;
264 }
265
266 // Decide how to create FILE* fp based on the mode parameter
267 fp_ = fdopen(dupFD_, modeStr);
268 if (fp_ == NULL || ferror(fp_) != 0) {
269 HandleFileError("Open file", filePath_, dupFD_, -1, -1);
270 return false;
271 }
272 IMAGE_LOGD("File opened: %{public}d", dupFD_);
273
274 return true;
275 }
276
OpenFromPath(const char * modeStr)277 bool FileMetadataStream::OpenFromPath(const char *modeStr)
278 {
279 IMAGE_LOGD("Open file: %{public}s, modeStr: %{public}s", filePath_.c_str(), modeStr);
280 fp_ = fopen(filePath_.c_str(), modeStr);
281 if (fp_ == nullptr) {
282 HandleFileError("Open file", filePath_, -1, -1, -1);
283 return false;
284 }
285 IMAGE_LOGD("File opened: %{public}s", filePath_.c_str());
286 return true;
287 }
288
Open(OpenMode mode)289 bool FileMetadataStream::Open(OpenMode mode)
290 {
291 if (initPath_ == INIT_FROM_UNKNOWN) {
292 IMAGE_LOGE("initPath is INIT_FROM_UNKNOWN. It seems that the file has "
293 "been closed before.");
294 return false;
295 }
296
297 const char *modeStr;
298 switch (mode) {
299 case OpenMode::Read:
300 modeStr = "r";
301 break;
302 case OpenMode::ReadWrite:
303 modeStr = "r+";
304 break;
305 default:
306 return false;
307 }
308
309 bool openResult = false;
310 if (initPath_ == INIT_FROM_FD) {
311 IMAGE_LOGD("initPath is INIT_FROM_FD");
312 openResult = OpenFromFD(modeStr);
313 }
314 if (initPath_ == INIT_FROM_PATH) {
315 IMAGE_LOGD("initPath is INIT_FROM_PATH");
316 openResult = OpenFromPath(modeStr);
317 }
318
319 if (!openResult) {
320 return false;
321 }
322
323 return true;
324 }
325
GetAddr(bool isWriteable)326 byte *FileMetadataStream::GetAddr(bool isWriteable)
327 {
328 // If there is already a memory map, return it directly
329 if (mappedMemory_ != nullptr) {
330 IMAGE_LOGE("mmap: There is already a memory mapping, return it directly");
331 return (byte *)mappedMemory_;
332 }
333
334 // If the file is not open, open it first
335 if (fp_ == nullptr) {
336 HandleFileError("Get memory address", filePath_, -1, -1, -1);
337 return nullptr;
338 }
339
340 // Get the file descriptor from the file pointer
341 int fileDescriptor = fileno(fp_);
342
343 // Create a memory map
344 fileSize_ = GetSize();
345 if (fileSize_ <= 0) {
346 mappedMemory_ = nullptr;
347 } else {
348 mappedMemory_ = ::mmap(nullptr, static_cast<size_t>(fileSize_), isWriteable ?
349 (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fileDescriptor, 0);
350 if (mappedMemory_ == static_cast<void *>(MAP_FAILED)) {
351 HandleFileError("Create memory mapping", filePath_, fileDescriptor, -1, -1);
352 mappedMemory_ = nullptr;
353 }
354 }
355 IMAGE_LOGD("mmap: Memory mapping created: %{public}s, size: %{public}zu", filePath_.c_str(), fileSize_);
356 return (byte *)mappedMemory_;
357 }
358
ReleaseAddr()359 bool FileMetadataStream::ReleaseAddr()
360 {
361 if (mappedMemory_ == nullptr) {
362 return true;
363 }
364
365 if (fileSize_ <= 0) {
366 mappedMemory_ = nullptr;
367 return true;
368 }
369 // Delete the memory map
370 if (munmap(mappedMemory_, static_cast<size_t>(fileSize_)) == -1) {
371 // Memory mapping failed
372 HandleFileError("Remove memory mapping", filePath_, -1, -1, -1);
373 return false;
374 }
375 IMAGE_LOGD("munmap: Memory mapping removed: %{public}s, size: %{public}zu", filePath_.c_str(), fileSize_);
376
377 mappedMemory_ = nullptr;
378 return true;
379 }
380
Flush()381 bool FileMetadataStream::Flush()
382 {
383 if (fp_ == nullptr) {
384 HandleFileError("Flush file", filePath_, -1, -1, -1);
385 return false;
386 }
387
388 if (fflush(fp_) != 0) {
389 HandleFileError("Flush file", filePath_, fileno(fp_), -1, -1);
390 return false;
391 }
392
393 return true;
394 }
395
TruncateFile(size_t totalBytesWritten,MetadataStream & src,ssize_t src_cur)396 bool FileMetadataStream::TruncateFile(size_t totalBytesWritten, MetadataStream &src, ssize_t src_cur)
397 {
398 int fileDescriptor = fileno(fp_);
399 if (ftruncate(fileDescriptor, totalBytesWritten) == -1) {
400 HandleFileError("Truncate file", filePath_, fileDescriptor, -1, totalBytesWritten);
401 src.Seek(src_cur, SeekPos::BEGIN); // Restore the position of src
402 return false;
403 }
404 return true;
405 }
406
CopyDataFromSource(MetadataStream & src,ssize_t & totalBytesWritten)407 bool FileMetadataStream::CopyDataFromSource(MetadataStream &src, ssize_t &totalBytesWritten)
408 {
409 ssize_t buffer_size = std::min((ssize_t)METADATA_STREAM_COPY_FROM_BUFFER_SIZE, src.GetSize());
410 if (buffer_size > METADATA_STREAM_COPY_FROM_BUFFER_SIZE) {
411 return false;
412 }
413 byte *tempBuffer = new (std::nothrow) byte[buffer_size];
414 if (tempBuffer == nullptr) {
415 // Handle memory allocation failure
416 HandleFileError("Memory allocation", filePath_, -1, -1, buffer_size);
417 return false;
418 }
419
420 Seek(0, SeekPos::BEGIN);
421 src.Seek(0, SeekPos::BEGIN); // Set the position of src to 0
422
423 bool result = ReadFromSourceAndWriteToFile(src, tempBuffer, buffer_size, totalBytesWritten);
424 delete[] tempBuffer;
425 return result;
426 }
427
ReadFromSourceAndWriteToFile(MetadataStream & src,byte * tempBuffer,ssize_t buffer_size,ssize_t & totalBytesWritten)428 bool FileMetadataStream::ReadFromSourceAndWriteToFile(MetadataStream &src, byte *tempBuffer, ssize_t buffer_size,
429 ssize_t &totalBytesWritten)
430 {
431 while (!src.IsEof()) {
432 ssize_t bytesRead = src.Read(tempBuffer, buffer_size);
433 if (bytesRead > 0) {
434 ssize_t bytesWritten = Write(tempBuffer, bytesRead);
435 if (bytesWritten == -1) {
436 // Write failed
437 HandleFileError("Write file", filePath_, fileno(fp_), bytesWritten, bytesRead);
438 return false;
439 }
440 totalBytesWritten += bytesWritten;
441 }
442 if (bytesRead < 0 && !src.IsEof()) {
443 HandleFileError("Read file", filePath_, -1, bytesRead, buffer_size);
444 return false;
445 }
446 }
447 return true;
448 }
449
CopyFrom(MetadataStream & src)450 bool FileMetadataStream::CopyFrom(MetadataStream &src)
451 {
452 ssize_t oldSize = GetSize();
453 if (!src.IsOpen()) {
454 IMAGE_LOGE("transfer: Source file is not open");
455 return false;
456 }
457
458 if (!IsOpen()) {
459 IMAGE_LOGE("transfer: File is not open: %{public}s", filePath_.c_str());
460 return false;
461 }
462
463 ssize_t totalBytesWritten = 0;
464 ssize_t src_cur = src.Tell(); // Temporarily store the position of src
465
466 if (!CopyDataFromSource(src, totalBytesWritten)) {
467 return false;
468 }
469
470 IMAGE_LOGD("transfer: Write file done: %{public}s, size: %{public}zu", filePath_.c_str(), totalBytesWritten);
471
472 // Flush the file
473 if (!Flush()) {
474 return false;
475 }
476
477 // Truncate the file only if totalBytesWritten is less than oldSize
478 if (totalBytesWritten < oldSize) {
479 if (!TruncateFile(totalBytesWritten, src, src_cur)) {
480 return false;
481 }
482 }
483
484 return true;
485 }
486
GetSize()487 ssize_t FileMetadataStream::GetSize()
488 {
489 if (fp_ == nullptr) {
490 HandleFileError("GetSize", filePath_, -1, -1, -1);
491 return -1;
492 }
493 ssize_t oldPos = Tell();
494 if (fseek(fp_, 0, SEEK_END) != 0) {
495 std::string errstr(METADATA_STREAM_ERROR_BUFFER_SIZE, '\0');
496 strerror_r(errno, &errstr[0], METADATA_STREAM_ERROR_BUFFER_SIZE);
497 IMAGE_LOGE("Failed to seek to the end of the file: %{public}s", errstr.c_str());
498 return -1;
499 }
500
501 ssize_t fileSize = ftell(fp_);
502
503 if (fseek(fp_, oldPos, SEEK_SET) != 0) { // Restore the file pointer to its original position
504 std::string errstr(METADATA_STREAM_ERROR_BUFFER_SIZE, '\0');
505 strerror_r(errno, &errstr[0], METADATA_STREAM_ERROR_BUFFER_SIZE);
506 IMAGE_LOGE("Failed to restore the file position: %{public}s", errstr.c_str());
507 return -1;
508 }
509
510 return fileSize;
511 }
512
513 } // namespace Media
514 } // namespace OHOS
515