2 * Copyright 2016 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)
19 FILE *openssl_fopen(const char *filename, const char *mode)
22 # if defined(_WIN32) && defined(CP_UTF8)
23 int sz, len_0 = (int)strlen(filename) + 1;
27 * Basically there are three cases to cover: a) filename is
28 * pure ASCII string; b) actual UTF-8 encoded string and
29 * c) locale-ized string, i.e. one containing 8-bit
30 * characters that are meaningful in current system locale.
31 * If filename is pure ASCII or real UTF-8 encoded string,
32 * MultiByteToWideChar succeeds and _wfopen works. If
33 * filename is locale-ized string, chances are that
34 * MultiByteToWideChar fails reporting
35 * ERROR_NO_UNICODE_TRANSLATION, in which case we fall
38 if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
39 filename, len_0, NULL, 0)) > 0 ||
40 (GetLastError() == ERROR_INVALID_FLAGS &&
41 (sz = MultiByteToWideChar(CP_UTF8, (flags = 0),
42 filename, len_0, NULL, 0)) > 0)
45 WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));
47 if (MultiByteToWideChar(CP_UTF8, flags,
48 filename, len_0, wfilename, sz) &&
49 MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1,
50 wmode, OSSL_NELEM(wmode)) &&
51 (file = _wfopen(wfilename, wmode)) == NULL &&
52 (errno == ENOENT || errno == EBADF)
55 * UTF-8 decode succeeded, but no file, filename
56 * could still have been locale-ized...
58 file = fopen(filename, mode);
60 } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
61 file = fopen(filename, mode);
63 # elif defined(__DJGPP__)
67 if (!HAS_LFN_SUPPORT(filename)) {
71 newname = OPENSSL_malloc(strlen(filename) + 1);
75 for (iterator = newname, lastchar = '\0';
76 *filename; filename++, iterator++) {
77 if (lastchar == '/' && filename[0] == '.'
78 && filename[1] != '.' && filename[1] != '/') {
79 /* Leading dots are not permitted in plain DOS. */
82 *iterator = *filename;
89 file = fopen(filename, mode);
91 OPENSSL_free(newname);
94 file = fopen(filename, mode);
101 void *openssl_fopen(const char *filename, const char *mode)