summaryrefslogtreecommitdiffstats
path: root/src/common/file-utils.cpp
blob: d9cdb402dc8a1fbc4ecb119a744c1c0a49b28af9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/*
 * Copyright (c) 2017-2020 [Ribose Inc](https://www.ribose.com).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/** File utilities
 *  @file
 */

#include "file-utils.h"
#include "config.h"
#ifdef _MSC_VER
#include <stdlib.h>
#include <stdio.h>
#include "uniwin.h"
#include <errno.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif // !_MSC_VER
#include "str-utils.h"
#include <algorithm>
#ifdef _WIN32
#include <random> // for rnp_mkstemp
#define CATCH_AND_RETURN(v) \
    catch (...)             \
    {                       \
        errno = ENOMEM;     \
        return v;           \
    }
#else
#include <string.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <stdarg.h>

int
rnp_unlink(const char *filename)
{
#ifdef _WIN32
    try {
        return _wunlink(wstr_from_utf8(filename).c_str());
    }
    CATCH_AND_RETURN(-1)
#else
    return unlink(filename);
#endif
}

bool
rnp_file_exists(const char *path)
{
    struct stat st;
    return rnp_stat(path, &st) == 0 && S_ISREG(st.st_mode);
}

bool
rnp_dir_exists(const char *path)
{
    struct stat st;
    return rnp_stat(path, &st) == 0 && S_ISDIR(st.st_mode);
}

int
rnp_open(const char *filename, int oflag, int pmode)
{
#ifdef _WIN32
    try {
        return _wopen(wstr_from_utf8(filename).c_str(), oflag, pmode);
    }
    CATCH_AND_RETURN(-1)
#else
    return open(filename, oflag, pmode);
#endif
}

FILE *
rnp_fopen(const char *filename, const char *mode)
{
#ifdef _WIN32
    try {
        return _wfopen(wstr_from_utf8(filename).c_str(), wstr_from_utf8(mode).c_str());
    }
    CATCH_AND_RETURN(NULL)
#else
    return fopen(filename, mode);
#endif
}

FILE *
rnp_fdopen(int fildes, const char *mode)
{
#ifdef _WIN32
    return _fdopen(fildes, mode);
#else
    return fdopen(fildes, mode);
#endif
}

int
rnp_access(const char *path, int mode)
{
#ifdef _WIN32
    try {
        return _waccess(wstr_from_utf8(path).c_str(), mode);
    }
    CATCH_AND_RETURN(-1)
#else
    return access(path, mode);
#endif
}

int
rnp_stat(const char *filename, struct stat *statbuf)
{
#ifdef _WIN32
    static_assert(sizeof(struct stat) == sizeof(struct _stat64i32),
                  "stat is expected to match _stat64i32");
    try {
        return _wstat64i32(wstr_from_utf8(filename).c_str(), (struct _stat64i32 *) statbuf);
    }
    CATCH_AND_RETURN(-1)
#else
    return stat(filename, statbuf);
#endif
}

#ifdef _WIN32
int
rnp_mkdir(const char *path)
{
    try {
        return _wmkdir(wstr_from_utf8(path).c_str());
    }
    CATCH_AND_RETURN(-1)
}
#endif

int
rnp_rename(const char *oldpath, const char *newpath)
{
#ifdef _WIN32
    try {
        return _wrename(wstr_from_utf8(oldpath).c_str(), wstr_from_utf8(newpath).c_str());
    }
    CATCH_AND_RETURN(-1)
#else
    return rename(oldpath, newpath);
#endif
}

#ifdef _WIN32
_WDIR *
#else
DIR *
#endif
rnp_opendir(const char *path)
{
#ifdef _WIN32
    try {
        return _wopendir(wstr_from_utf8(path).c_str());
    }
    CATCH_AND_RETURN(NULL)
#else
    return opendir(path);
#endif
}

std::string
#ifdef _WIN32
rnp_readdir_name(_WDIR *dir)
{
    _wdirent *ent;
    for (;;) {
        if ((ent = _wreaddir(dir)) == NULL) {
            return std::string();
        }
        if (wcscmp(ent->d_name, L".") && wcscmp(ent->d_name, L"..")) {
            break;
        }
    }
    try {
        return wstr_to_utf8(ent->d_name);
    }
    CATCH_AND_RETURN(std::string())
#else
rnp_readdir_name(DIR *dir)
{
    dirent *ent;
    for (;;) {
        if ((ent = readdir(dir)) == NULL) {
            return std::string();
        }
        if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) {
            break;
        }
    }
    return std::string(ent->d_name);
#endif
}

/* return the file modification time */
int64_t
rnp_filemtime(const char *path)
{
    struct stat st;

    if (rnp_stat(path, &st) != 0) {
        return 0;
    } else {
        return st.st_mtime;
    }
}

#ifdef _WIN32
static const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

/** @private
 *  generate a temporary file name based on TMPL.
 *
 *  @param tmpl filename template in UTF-8 ending in XXXXXX
 *  @return file descriptor of newly created and opened file, or -1 on error
 **/
int
rnp_mkstemp(char *tmpl)
{
    try {
        int       save_errno = errno;
        const int mask_length = 6;
        int       len = strlen(tmpl);
        if (len < mask_length || strcmp(&tmpl[len - mask_length], "XXXXXX")) {
            errno = EINVAL;
            return -1;
        }
        std::wstring tmpl_w = wstr_from_utf8(tmpl, tmpl + len - mask_length);

        /* This is where the Xs start.  */
        char *XXXXXX = &tmpl[len - mask_length];

        std::random_device rd;
        std::mt19937_64    rng(rd());

        for (unsigned int countdown = TMP_MAX; --countdown;) {
            unsigned long long v = rng();

            XXXXXX[0] = letters[v % 36];
            v /= 36;
            XXXXXX[1] = letters[v % 36];
            v /= 36;
            XXXXXX[2] = letters[v % 36];
            v /= 36;
            XXXXXX[3] = letters[v % 36];
            v /= 36;
            XXXXXX[4] = letters[v % 36];
            v /= 36;
            XXXXXX[5] = letters[v % 36];

            int flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
            int fd =
              _wopen((tmpl_w + wstr_from_utf8(XXXXXX)).c_str(), flags, _S_IREAD | _S_IWRITE);
            if (fd != -1) {
                errno = save_errno;
                return fd;
            } else if (errno != EEXIST)
                return -1;
        }

        // We got out of the loop because we ran out of combinations to try.
        errno = EEXIST;
        return -1;
    }
    CATCH_AND_RETURN(-1)
}
#endif // _WIN32

namespace rnp {
namespace path {
inline char
separator()
{
#ifdef _WIN32
    return '\\';
#else
    return '/';
#endif
}

bool
exists(const std::string &path, bool is_dir)
{
    return is_dir ? rnp_dir_exists(path.c_str()) : rnp_file_exists(path.c_str());
}

bool
empty(const std::string &path)
{
    auto dir = rnp_opendir(path.c_str());
    if (!dir) {
        return true;
    }
    bool empty = rnp_readdir_name(dir).empty();
    rnp_closedir(dir);
    return empty;
}

std::string
HOME(const std::string &sdir)
{
    const char *home = getenv("HOME");
    if (!home) {
        return "";
    }
    return sdir.empty() ? home : append(home, sdir);
}

static bool
has_forward_slash(const std::string &path)
{
    return std::find(path.begin(), path.end(), '/') != path.end();
}

std::string
append(const std::string &path, const std::string &name)
{
    bool no_sep = path.empty() || name.empty() || (rnp::is_slash(path.back())) ||
                  (rnp::is_slash(name.front()));
    if (no_sep) {
        return path + name;
    }
    /* Use forward slash if there is at least one in the path/name. */
    char sep = has_forward_slash(path) || has_forward_slash(name) ? '/' : separator();
    return path + sep + name;
}

} // namespace path
} // namespace rnp