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 ssize_t 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(), GetSize());
356 return (byte *)mappedMemory_;
357 }
358
ReleaseAddr()359 bool FileMetadataStream::ReleaseAddr()
360 {
361 if (mappedMemory_ == nullptr) {
362 return true;
363 }
364
365 ssize_t fileSize = GetSize();
366 if (fileSize <= 0) {
367 mappedMemory_ = nullptr;
368 return true;
369 }
370 // Delete the memory map
371 if (munmap(mappedMemory_, static_cast<size_t>(fileSize)) == -1) {
372 // Memory mapping failed
373 HandleFileError("Remove memory mapping", filePath_, -1, -1, -1);
374 return false;
375 }
376 IMAGE_LOGD("munmap: Memory mapping removed: %{public}s, size: %{public}zu", filePath_.c_str(), GetSize());
377
378 mappedMemory_ = nullptr;
379 return true;
380 }
381
Flush()382 bool FileMetadataStream::Flush()
383 {
384 if (fp_ == nullptr) {
385 HandleFileError("Flush file", filePath_, -1, -1, -1);
386 return false;
387 }
388
389 if (fflush(fp_) != 0) {
390 HandleFileError("Flush file", filePath_, fileno(fp_), -1, -1);
391 return false;
392 }
393
394 return true;
395 }
396
TruncateFile(size_t totalBytesWritten,MetadataStream & src,ssize_t src_cur)397 bool FileMetadataStream::TruncateFile(size_t totalBytesWritten, MetadataStream &src, ssize_t src_cur)
398 {
399 int fileDescriptor = fileno(fp_);
400 if (ftruncate(fileDescriptor, totalBytesWritten) == -1) {
401 HandleFileError("Truncate file", filePath_, fileDescriptor, -1, totalBytesWritten);
402 src.Seek(src_cur, SeekPos::BEGIN); // Restore the position of src
403 return false;
404 }
405 return true;
406 }
407
CopyDataFromSource(MetadataStream & src,ssize_t & totalBytesWritten)408 bool FileMetadataStream::CopyDataFromSource(MetadataStream &src, ssize_t &totalBytesWritten)
409 {
410 ssize_t buffer_size = std::min((ssize_t)METADATA_STREAM_COPY_FROM_BUFFER_SIZE, src.GetSize());
411 if (buffer_size > METADATA_STREAM_COPY_FROM_BUFFER_SIZE) {
412 return false;
413 }
414 byte *tempBuffer = new (std::nothrow) byte[buffer_size];
415 if (tempBuffer == nullptr) {
416 // Handle memory allocation failure
417 HandleFileError("Memory allocation", filePath_, -1, -1, buffer_size);
418 return false;
419 }
420
421 Seek(0, SeekPos::BEGIN);
422 src.Seek(0, SeekPos::BEGIN); // Set the position of src to 0
423
424 bool result = ReadFromSourceAndWriteToFile(src, tempBuffer, buffer_size, totalBytesWritten);
425 delete[] tempBuffer;
426 return result;
427 }
428
ReadFromSourceAndWriteToFile(MetadataStream & src,byte * tempBuffer,ssize_t buffer_size,ssize_t & totalBytesWritten)429 bool FileMetadataStream::ReadFromSourceAndWriteToFile(MetadataStream &src, byte *tempBuffer, ssize_t buffer_size,
430 ssize_t &totalBytesWritten)
431 {
432 while (!src.IsEof()) {
433 ssize_t bytesRead = src.Read(tempBuffer, buffer_size);
434 if (bytesRead > 0) {
435 ssize_t bytesWritten = Write(tempBuffer, bytesRead);
436 if (bytesWritten == -1) {
437 // Write failed
438 HandleFileError("Write file", filePath_, fileno(fp_), bytesWritten, bytesRead);
439 return false;
440 }
441 totalBytesWritten += bytesWritten;
442 }
443 if (bytesRead < 0 && !src.IsEof()) {
444 HandleFileError("Read file", filePath_, -1, bytesRead, buffer_size);
445 return false;
446 }
447 }
448 return true;
449 }
450
CopyFrom(MetadataStream & src)451 bool FileMetadataStream::CopyFrom(MetadataStream &src)
452 {
453 ssize_t oldSize = GetSize();
454 if (!src.IsOpen()) {
455 IMAGE_LOGE("transfer: Source file is not open");
456 return false;
457 }
458
459 if (!IsOpen()) {
460 IMAGE_LOGE("transfer: File is not open: %{public}s", filePath_.c_str());
461 return false;
462 }
463
464 ssize_t totalBytesWritten = 0;
465 ssize_t src_cur = src.Tell(); // Temporarily store the position of src
466
467 if (!CopyDataFromSource(src, totalBytesWritten)) {
468 return false;
469 }
470
471 IMAGE_LOGD("transfer: Write file done: %{public}s, size: %{public}zu", filePath_.c_str(), totalBytesWritten);
472
473 // Flush the file
474 if (!Flush()) {
475 return false;
476 }
477
478 // Truncate the file only if totalBytesWritten is less than oldSize
479 if (totalBytesWritten < oldSize) {
480 if (!TruncateFile(totalBytesWritten, src, src_cur)) {
481 return false;
482 }
483 }
484
485 return true;
486 }
487
GetSize()488 ssize_t FileMetadataStream::GetSize()
489 {
490 if (fp_ == nullptr) {
491 HandleFileError("GetSize", filePath_, -1, -1, -1);
492 return -1;
493 }
494 ssize_t oldPos = Tell();
495 if (fseek(fp_, 0, SEEK_END) != 0) {
496 std::string errstr(METADATA_STREAM_ERROR_BUFFER_SIZE, '\0');
497 strerror_r(errno, &errstr[0], METADATA_STREAM_ERROR_BUFFER_SIZE);
498 IMAGE_LOGE("Failed to seek to the end of the file: %{public}s", errstr.c_str());
499 return -1;
500 }
501
502 ssize_t fileSize = ftell(fp_);
503
504 if (fseek(fp_, oldPos, SEEK_SET) != 0) { // Restore the file pointer to its original position
505 std::string errstr(METADATA_STREAM_ERROR_BUFFER_SIZE, '\0');
506 strerror_r(errno, &errstr[0], METADATA_STREAM_ERROR_BUFFER_SIZE);
507 IMAGE_LOGE("Failed to restore the file position: %{public}s", errstr.c_str());
508 return -1;
509 }
510
511 return fileSize;
512 }
513
514 } // namespace Media
515 } // namespace OHOS
516