1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to.  The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 *    notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 *    notice, this list of conditions and the following disclaimer in the
29 *    documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 *    must display the following acknowledgement:
32 *    "This product includes cryptographic software written by
33 *     Eric Young (eay@cryptsoft.com)"
34 *    The word 'cryptographic' can be left out if the rouines from the library
35 *    being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 *    the apps directory (application code) you must include an acknowledgement:
38 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed.  i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.] */
56
57#if defined(__linux) || defined(__sun) || defined(__hpux)
58/* Following definition aliases fopen to fopen64 on above mentioned
59 * platforms. This makes it possible to open and sequentially access
60 * files larger than 2GB from 32-bit application. It does not allow to
61 * traverse them beyond 2GB with fseek/ftell, but on the other hand *no*
62 * 32-bit platform permits that, not with fseek/ftell. Not to mention
63 * that breaking 2GB limit for seeking would require surgery to *our*
64 * API. But sequential access suffices for practical cases when you
65 * can run into large files, such as fingerprinting, so we can let API
66 * alone. For reference, the list of 32-bit platforms which allow for
67 * sequential access of large files without extra "magic" comprise *BSD,
68 * Darwin, IRIX...
69 */
70#ifndef _FILE_OFFSET_BITS
71#define _FILE_OFFSET_BITS 64
72#endif
73#endif
74
75#include <openssl/bio.h>
76
77#include <errno.h>
78#include <stdio.h>
79#include <string.h>
80
81#include <openssl/buf.h>
82#include <openssl/err.h>
83#include <openssl/mem.h>
84
85
86#define BIO_FP_READ 0x02
87#define BIO_FP_WRITE 0x04
88#define BIO_FP_APPEND 0x08
89
90static FILE *open_file(const char *filename, const char *mode) {
91#if defined(OPENSSL_WINDOWS) && defined(CP_UTF8)
92  int sz, len_0 = (int)strlen(filename) + 1;
93  DWORD flags;
94
95  /* Basically there are three cases to cover: a) filename is pure ASCII
96   * string; b) actual UTF-8 encoded string and c) locale-ized string, i.e. one
97   * containing 8-bit characters that are meaningful in current system locale.
98   * If filename is pure ASCII or real UTF-8 encoded string,
99   * MultiByteToWideChar succeeds and _wfopen works. If filename is locale-ized
100   * string, chances are that MultiByteToWideChar fails reporting
101   * ERROR_NO_UNICODE_TRANSLATION, in which case we fall back to fopen... */
102  if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
103                                filename, len_0, NULL, 0)) > 0 ||
104      (GetLastError() == ERROR_INVALID_FLAGS &&
105       (sz = MultiByteToWideChar(CP_UTF8, (flags = 0), filename, len_0, NULL,
106                                 0)) > 0)) {
107    WCHAR wmode[8];
108    WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));
109
110    if (MultiByteToWideChar(CP_UTF8, flags, filename, len_0, wfilename, sz) &&
111        MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1, wmode,
112                            sizeof(wmode) / sizeof(wmode[0])) &&
113        (file = _wfopen(wfilename, wmode)) == NULL &&
114        (errno == ENOENT ||
115         errno == EBADF)) /* UTF-8 decode succeeded, but no file, filename
116                           * could still have been locale-ized... */
117      return fopen(filename, mode);
118  } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
119    return fopen(filename, mode);
120  }
121#else
122  return fopen(filename, mode);
123#endif
124}
125
126BIO *BIO_new_file(const char *filename, const char *mode) {
127  BIO *ret;
128  FILE *file;
129
130  file = open_file(filename, mode);
131  if (file == NULL) {
132    OPENSSL_PUT_SYSTEM_ERROR();
133
134    ERR_add_error_data(5, "fopen('", filename, "','", mode, "')");
135    if (errno == ENOENT) {
136      OPENSSL_PUT_ERROR(BIO, BIO_R_NO_SUCH_FILE);
137    } else {
138      OPENSSL_PUT_ERROR(BIO, BIO_R_SYS_LIB);
139    }
140    return NULL;
141  }
142
143  ret = BIO_new(BIO_s_file());
144  if (ret == NULL) {
145    fclose(file);
146    return NULL;
147  }
148
149  BIO_set_fp(ret, file, BIO_CLOSE);
150  return ret;
151}
152
153BIO *BIO_new_fp(FILE *stream, int close_flag) {
154  BIO *ret = BIO_new(BIO_s_file());
155
156  if (ret == NULL) {
157    return NULL;
158  }
159
160  BIO_set_fp(ret, stream, close_flag);
161  return ret;
162}
163
164static int file_new(BIO *bio) { return 1; }
165
166static int file_free(BIO *bio) {
167  if (bio == NULL) {
168    return 0;
169  }
170
171  if (!bio->shutdown) {
172    return 1;
173  }
174
175  if (bio->init && bio->ptr != NULL) {
176    fclose(bio->ptr);
177    bio->ptr = NULL;
178  }
179  bio->init = 0;
180
181  return 1;
182}
183
184static int file_read(BIO *b, char *out, int outl) {
185  if (!b->init) {
186    return 0;
187  }
188
189  size_t ret = fread(out, 1, outl, (FILE *)b->ptr);
190  if (ret == 0 && ferror((FILE *)b->ptr)) {
191    OPENSSL_PUT_SYSTEM_ERROR();
192    OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB);
193    return -1;
194  }
195
196  /* fread reads at most |outl| bytes, so |ret| fits in an int. */
197  return (int)ret;
198}
199
200static int file_write(BIO *b, const char *in, int inl) {
201  int ret = 0;
202
203  if (!b->init) {
204    return 0;
205  }
206
207  ret = fwrite(in, inl, 1, (FILE *)b->ptr);
208  if (ret > 0) {
209    ret = inl;
210  }
211  return ret;
212}
213
214static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
215  long ret = 1;
216  FILE *fp = (FILE *)b->ptr;
217  FILE **fpp;
218  char p[4];
219
220  switch (cmd) {
221    case BIO_CTRL_RESET:
222      num = 0;
223    case BIO_C_FILE_SEEK:
224      ret = (long)fseek(fp, num, 0);
225      break;
226    case BIO_CTRL_EOF:
227      ret = (long)feof(fp);
228      break;
229    case BIO_C_FILE_TELL:
230    case BIO_CTRL_INFO:
231      ret = ftell(fp);
232      break;
233    case BIO_C_SET_FILE_PTR:
234      file_free(b);
235      b->shutdown = (int)num & BIO_CLOSE;
236      b->ptr = ptr;
237      b->init = 1;
238      break;
239    case BIO_C_SET_FILENAME:
240      file_free(b);
241      b->shutdown = (int)num & BIO_CLOSE;
242      if (num & BIO_FP_APPEND) {
243        if (num & BIO_FP_READ) {
244          BUF_strlcpy(p, "a+", sizeof(p));
245        } else {
246          BUF_strlcpy(p, "a", sizeof(p));
247        }
248      } else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE)) {
249        BUF_strlcpy(p, "r+", sizeof(p));
250      } else if (num & BIO_FP_WRITE) {
251        BUF_strlcpy(p, "w", sizeof(p));
252      } else if (num & BIO_FP_READ) {
253        BUF_strlcpy(p, "r", sizeof(p));
254      } else {
255        OPENSSL_PUT_ERROR(BIO, BIO_R_BAD_FOPEN_MODE);
256        ret = 0;
257        break;
258      }
259      fp = open_file(ptr, p);
260      if (fp == NULL) {
261        OPENSSL_PUT_SYSTEM_ERROR();
262        ERR_add_error_data(5, "fopen('", ptr, "','", p, "')");
263        OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB);
264        ret = 0;
265        break;
266      }
267      b->ptr = fp;
268      b->init = 1;
269      break;
270    case BIO_C_GET_FILE_PTR:
271      /* the ptr parameter is actually a FILE ** in this case. */
272      if (ptr != NULL) {
273        fpp = (FILE **)ptr;
274        *fpp = (FILE *)b->ptr;
275      }
276      break;
277    case BIO_CTRL_GET_CLOSE:
278      ret = (long)b->shutdown;
279      break;
280    case BIO_CTRL_SET_CLOSE:
281      b->shutdown = (int)num;
282      break;
283    case BIO_CTRL_FLUSH:
284      ret = 0 == fflush((FILE *)b->ptr);
285      break;
286    case BIO_CTRL_WPENDING:
287    case BIO_CTRL_PENDING:
288    default:
289      ret = 0;
290      break;
291  }
292  return ret;
293}
294
295static int file_gets(BIO *bp, char *buf, int size) {
296  int ret = 0;
297
298  if (size == 0) {
299    return 0;
300  }
301
302  if (!fgets(buf, size, (FILE *)bp->ptr)) {
303    buf[0] = 0;
304    goto err;
305  }
306  ret = strlen(buf);
307
308err:
309  return ret;
310}
311
312static int file_puts(BIO *bp, const char *str) {
313  return file_write(bp, str, strlen(str));
314}
315
316static const BIO_METHOD methods_filep = {
317    BIO_TYPE_FILE, "FILE pointer", file_write, file_read, file_puts,
318    file_gets,     file_ctrl,      file_new,   file_free, NULL, };
319
320const BIO_METHOD *BIO_s_file(void) { return &methods_filep; }
321
322
323int BIO_get_fp(BIO *bio, FILE **out_file) {
324  return BIO_ctrl(bio, BIO_C_GET_FILE_PTR, 0, (char*) out_file);
325}
326
327int BIO_set_fp(BIO *bio, FILE *file, int close_flag) {
328  return BIO_ctrl(bio, BIO_C_SET_FILE_PTR, close_flag, (char *) file);
329}
330
331int BIO_read_filename(BIO *bio, const char *filename) {
332  return BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_READ,
333                  (char *)filename);
334}
335
336int BIO_write_filename(BIO *bio, const char *filename) {
337  return BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_WRITE,
338                  (char *)filename);
339}
340
341int BIO_append_filename(BIO *bio, const char *filename) {
342  return BIO_ctrl(bio, BIO_C_SET_FILENAME, BIO_CLOSE | BIO_FP_APPEND,
343                  (char *)filename);
344}
345
346int BIO_rw_filename(BIO *bio, const char *filename) {
347  return BIO_ctrl(bio, BIO_C_SET_FILENAME,
348                  BIO_CLOSE | BIO_FP_READ | BIO_FP_WRITE, (char *)filename);
349}
350