2 * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "internal/cryptlib.h"
12 #if !defined(OPENSSL_NO_STDIO)
22 FILE *openssl_fopen(const char *filename, const char *mode)
25 # if defined(_WIN32) && defined(CP_UTF8)
26 int sz, len_0 = (int)strlen(filename) + 1;
30 * Basically there are three cases to cover: a) filename is
31 * pure ASCII string; b) actual UTF-8 encoded string and
32 * c) locale-ized string, i.e. one containing 8-bit
33 * characters that are meaningful in current system locale.
34 * If filename is pure ASCII or real UTF-8 encoded string,
35 * MultiByteToWideChar succeeds and _wfopen works. If
36 * filename is locale-ized string, chances are that
37 * MultiByteToWideChar fails reporting
38 * ERROR_NO_UNICODE_TRANSLATION, in which case we fall
41 if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
42 filename, len_0, NULL, 0)) > 0 ||
43 (GetLastError() == ERROR_INVALID_FLAGS &&
44 (sz = MultiByteToWideChar(CP_UTF8, (flags = 0),
45 filename, len_0, NULL, 0)) > 0)
48 WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));
50 if (MultiByteToWideChar(CP_UTF8, flags,
51 filename, len_0, wfilename, sz) &&
52 MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1,
53 wmode, OSSL_NELEM(wmode)) &&
54 (file = _wfopen(wfilename, wmode)) == NULL &&
55 (errno == ENOENT || errno == EBADF)
58 * UTF-8 decode succeeded, but no file, filename
59 * could still have been locale-ized...
61 file = fopen(filename, mode);
63 } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
64 file = fopen(filename, mode);
66 # elif defined(__DJGPP__)
70 if (pathconf(filename, _PC_NAME_MAX) <= 12) { /* 8.3 file system? */
74 if ((newname = OPENSSL_malloc(strlen(filename) + 1)) == NULL) {
75 CRYPTOerr(CRYPTO_F_OPENSSL_FOPEN, ERR_R_MALLOC_FAILURE);
79 for (iterator = newname, lastchar = '\0';
80 *filename; filename++, iterator++) {
81 if (lastchar == '/' && filename[0] == '.'
82 && filename[1] != '.' && filename[1] != '/') {
83 /* Leading dots are not permitted in plain DOS. */
86 *iterator = *filename;
93 file = fopen(filename, mode);
95 OPENSSL_free(newname);
98 file = fopen(filename, mode);
105 void *openssl_fopen(const char *filename, const char *mode)