1 /*
2 * Copyright (c) 2020-2022 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 "write_file.h"
17
18 #include <cstdio>
19 #include <cstdlib>
20 #include <cstring>
21 #include <fcntl.h>
22 #include <memory>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include "mbedtls/base64.h"
28 #include "securec.h"
29
30 namespace {
31 const int32_t MAX_FILE_LEN = 1000000;
32 const int32_t ONCE_WRITE = 2000;
33 }
34
CopyFile(const char * org,const char * dest)35 int32_t CopyFile(const char *org, const char *dest)
36 {
37 int32_t ret = 0;
38 if (org == nullptr || dest == nullptr) {
39 return -1;
40 }
41 int32_t in = open(dest, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
42 if (in < 0) {
43 return -1;
44 }
45
46 int32_t wholeLen = strlen(org);
47 if (wholeLen == 0 || wholeLen > MAX_FILE_LEN) {
48 close(in);
49 return -1;
50 }
51 std::unique_ptr<char[]> buffer = std::make_unique<char[]>(wholeLen);
52 (void)memset_s(buffer.get(), wholeLen, 0, wholeLen);
53 int32_t len = 0;
54 mbedtls_base64_decode(reinterpret_cast<unsigned char *>(buffer.get()), static_cast<size_t>(wholeLen),
55 reinterpret_cast<size_t *>(&len), reinterpret_cast<const unsigned char *>(org), static_cast<size_t>(wholeLen));
56 int32_t num = 0;
57 while (num < len) {
58 int32_t trueLen = ((len - num) >= ONCE_WRITE) ? ONCE_WRITE : (len - num);
59 char *temp = buffer.get() + num;
60 num += trueLen;
61 ret = write(in, temp, trueLen);
62 if (ret < 0) {
63 goto EXIT;
64 }
65 }
66 ret = 0;
67 EXIT:
68 close(in);
69 return ret;
70 }
71
DeleteFile(const char * path)72 void DeleteFile(const char *path)
73 {
74 if (path == nullptr) {
75 return;
76 }
77 remove(path);
78 return;
79 }
80
81