Copyright consolidation 09/10
[openssl.git] / crypto / bio / bss_file.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9
10 /*-
11  * 03-Dec-1997  rdenny@dc3.com  Fix bug preventing use of stdin/stdout
12  *              with binary data (e.g. asn1parse -inform DER < xxx) under
13  *              Windows
14  */
15
16 #ifndef HEADER_BSS_FILE_C
17 # define HEADER_BSS_FILE_C
18
19 # if defined(__linux) || defined(__sun) || defined(__hpux)
20 /*
21  * Following definition aliases fopen to fopen64 on above mentioned
22  * platforms. This makes it possible to open and sequentially access files
23  * larger than 2GB from 32-bit application. It does not allow to traverse
24  * them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit
25  * platform permits that, not with fseek/ftell. Not to mention that breaking
26  * 2GB limit for seeking would require surgery to *our* API. But sequential
27  * access suffices for practical cases when you can run into large files,
28  * such as fingerprinting, so we can let API alone. For reference, the list
29  * of 32-bit platforms which allow for sequential access of large files
30  * without extra "magic" comprise *BSD, Darwin, IRIX...
31  */
32 #  ifndef _FILE_OFFSET_BITS
33 #   define _FILE_OFFSET_BITS 64
34 #  endif
35 # endif
36
37 # include <stdio.h>
38 # include <errno.h>
39 # include "bio_lcl.h"
40 # include <openssl/err.h>
41
42 # if !defined(OPENSSL_NO_STDIO)
43
44 static int file_write(BIO *h, const char *buf, int num);
45 static int file_read(BIO *h, char *buf, int size);
46 static int file_puts(BIO *h, const char *str);
47 static int file_gets(BIO *h, char *str, int size);
48 static long file_ctrl(BIO *h, int cmd, long arg1, void *arg2);
49 static int file_new(BIO *h);
50 static int file_free(BIO *data);
51 static const BIO_METHOD methods_filep = {
52     BIO_TYPE_FILE,
53     "FILE pointer",
54     file_write,
55     file_read,
56     file_puts,
57     file_gets,
58     file_ctrl,
59     file_new,
60     file_free,
61     NULL,
62 };
63
64 static FILE *file_fopen(const char *filename, const char *mode)
65 {
66     FILE *file = NULL;
67
68 #  if defined(_WIN32) && defined(CP_UTF8)
69     int sz, len_0 = (int)strlen(filename) + 1;
70     DWORD flags;
71
72     /*
73      * Basically there are three cases to cover: a) filename is
74      * pure ASCII string; b) actual UTF-8 encoded string and
75      * c) locale-ized string, i.e. one containing 8-bit
76      * characters that are meaningful in current system locale.
77      * If filename is pure ASCII or real UTF-8 encoded string,
78      * MultiByteToWideChar succeeds and _wfopen works. If
79      * filename is locale-ized string, chances are that
80      * MultiByteToWideChar fails reporting
81      * ERROR_NO_UNICODE_TRANSLATION, in which case we fall
82      * back to fopen...
83      */
84     if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
85                                   filename, len_0, NULL, 0)) > 0 ||
86         (GetLastError() == ERROR_INVALID_FLAGS &&
87          (sz = MultiByteToWideChar(CP_UTF8, (flags = 0),
88                                    filename, len_0, NULL, 0)) > 0)
89         ) {
90         WCHAR wmode[8];
91         WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));
92
93         if (MultiByteToWideChar(CP_UTF8, flags,
94                                 filename, len_0, wfilename, sz) &&
95             MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1,
96                                 wmode, OSSL_NELEM(wmode)) &&
97             (file = _wfopen(wfilename, wmode)) == NULL &&
98             (errno == ENOENT || errno == EBADF)
99             ) {
100             /*
101              * UTF-8 decode succeeded, but no file, filename
102              * could still have been locale-ized...
103              */
104             file = fopen(filename, mode);
105         }
106     } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
107         file = fopen(filename, mode);
108     }
109 #  elif defined(__DJGPP__)
110     {
111         char *newname = NULL;
112
113         if (!HAS_LFN_SUPPORT(filename)) {
114             char *iterator;
115             char lastchar;
116
117             newname = OPENSSL_malloc(strlen(filename) + 1);
118             if (newname == NULL)
119                 return NULL;
120
121             for(iterator = newname, lastchar = '\0';
122                 *filename; filename++, iterator++) {
123                 if (lastchar == '/' && filename[0] == '.'
124                     && filename[1] != '.' && filename[1] != '/') {
125                     /* Leading dots are not permitted in plain DOS. */
126                     *iterator = '_';
127                 } else {
128                     *iterator = *filename;
129                 }
130                 lastchar = *filename;
131             }
132             *iterator = '\0';
133             filename = newname;
134         }
135         file = fopen(filename, mode);
136
137         OPENSSL_free(newname);
138     }
139 #  else
140     file = fopen(filename, mode);
141 #  endif
142     return (file);
143 }
144
145 BIO *BIO_new_file(const char *filename, const char *mode)
146 {
147     BIO  *ret;
148     FILE *file = file_fopen(filename, mode);
149     int fp_flags = BIO_CLOSE;
150
151     if (strchr(mode, 'b') == NULL)
152         fp_flags |= BIO_FP_TEXT;
153
154     if (file == NULL) {
155         SYSerr(SYS_F_FOPEN, get_last_sys_error());
156         ERR_add_error_data(5, "fopen('", filename, "','", mode, "')");
157         if (errno == ENOENT)
158             BIOerr(BIO_F_BIO_NEW_FILE, BIO_R_NO_SUCH_FILE);
159         else
160             BIOerr(BIO_F_BIO_NEW_FILE, ERR_R_SYS_LIB);
161         return (NULL);
162     }
163     if ((ret = BIO_new(BIO_s_file())) == NULL) {
164         fclose(file);
165         return (NULL);
166     }
167
168     BIO_clear_flags(ret, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
169                                              * UPLINK */
170     BIO_set_fp(ret, file, fp_flags);
171     return (ret);
172 }
173
174 BIO *BIO_new_fp(FILE *stream, int close_flag)
175 {
176     BIO *ret;
177
178     if ((ret = BIO_new(BIO_s_file())) == NULL)
179         return (NULL);
180
181     /* redundant flag, left for documentation purposes */
182     BIO_set_flags(ret, BIO_FLAGS_UPLINK);
183     BIO_set_fp(ret, stream, close_flag);
184     return (ret);
185 }
186
187 const BIO_METHOD *BIO_s_file(void)
188 {
189     return (&methods_filep);
190 }
191
192 static int file_new(BIO *bi)
193 {
194     bi->init = 0;
195     bi->num = 0;
196     bi->ptr = NULL;
197     bi->flags = BIO_FLAGS_UPLINK; /* default to UPLINK */
198     return (1);
199 }
200
201 static int file_free(BIO *a)
202 {
203     if (a == NULL)
204         return (0);
205     if (a->shutdown) {
206         if ((a->init) && (a->ptr != NULL)) {
207             if (a->flags & BIO_FLAGS_UPLINK)
208                 UP_fclose(a->ptr);
209             else
210                 fclose(a->ptr);
211             a->ptr = NULL;
212             a->flags = BIO_FLAGS_UPLINK;
213         }
214         a->init = 0;
215     }
216     return (1);
217 }
218
219 static int file_read(BIO *b, char *out, int outl)
220 {
221     int ret = 0;
222
223     if (b->init && (out != NULL)) {
224         if (b->flags & BIO_FLAGS_UPLINK)
225             ret = UP_fread(out, 1, (int)outl, b->ptr);
226         else
227             ret = fread(out, 1, (int)outl, (FILE *)b->ptr);
228         if (ret == 0
229             && (b->flags & BIO_FLAGS_UPLINK) ? UP_ferror((FILE *)b->ptr) :
230                                                ferror((FILE *)b->ptr)) {
231             SYSerr(SYS_F_FREAD, get_last_sys_error());
232             BIOerr(BIO_F_FILE_READ, ERR_R_SYS_LIB);
233             ret = -1;
234         }
235     }
236     return (ret);
237 }
238
239 static int file_write(BIO *b, const char *in, int inl)
240 {
241     int ret = 0;
242
243     if (b->init && (in != NULL)) {
244         if (b->flags & BIO_FLAGS_UPLINK)
245             ret = UP_fwrite(in, (int)inl, 1, b->ptr);
246         else
247             ret = fwrite(in, (int)inl, 1, (FILE *)b->ptr);
248         if (ret)
249             ret = inl;
250         /* ret=fwrite(in,1,(int)inl,(FILE *)b->ptr); */
251         /*
252          * according to Tim Hudson <tjh@cryptsoft.com>, the commented out
253          * version above can cause 'inl' write calls under some stupid stdio
254          * implementations (VMS)
255          */
256     }
257     return (ret);
258 }
259
260 static long file_ctrl(BIO *b, int cmd, long num, void *ptr)
261 {
262     long ret = 1;
263     FILE *fp = (FILE *)b->ptr;
264     FILE **fpp;
265     char p[4];
266
267     switch (cmd) {
268     case BIO_C_FILE_SEEK:
269     case BIO_CTRL_RESET:
270         if (b->flags & BIO_FLAGS_UPLINK)
271             ret = (long)UP_fseek(b->ptr, num, 0);
272         else
273             ret = (long)fseek(fp, num, 0);
274         break;
275     case BIO_CTRL_EOF:
276         if (b->flags & BIO_FLAGS_UPLINK)
277             ret = (long)UP_feof(fp);
278         else
279             ret = (long)feof(fp);
280         break;
281     case BIO_C_FILE_TELL:
282     case BIO_CTRL_INFO:
283         if (b->flags & BIO_FLAGS_UPLINK)
284             ret = UP_ftell(b->ptr);
285         else
286             ret = ftell(fp);
287         break;
288     case BIO_C_SET_FILE_PTR:
289         file_free(b);
290         b->shutdown = (int)num & BIO_CLOSE;
291         b->ptr = ptr;
292         b->init = 1;
293 #  if BIO_FLAGS_UPLINK!=0
294 #   if defined(__MINGW32__) && defined(__MSVCRT__) && !defined(_IOB_ENTRIES)
295 #    define _IOB_ENTRIES 20
296 #   endif
297         /* Safety net to catch purely internal BIO_set_fp calls */
298 #   if defined(_MSC_VER) && _MSC_VER>=1900
299         if (ptr == stdin || ptr == stdout || ptr == stderr)
300             BIO_clear_flags(b, BIO_FLAGS_UPLINK);
301 #   elif defined(_IOB_ENTRIES)
302         if ((size_t)ptr >= (size_t)stdin &&
303             (size_t)ptr < (size_t)(stdin + _IOB_ENTRIES))
304             BIO_clear_flags(b, BIO_FLAGS_UPLINK);
305 #   endif
306 #  endif
307 #  ifdef UP_fsetmod
308         if (b->flags & BIO_FLAGS_UPLINK)
309             UP_fsetmod(b->ptr, (char)((num & BIO_FP_TEXT) ? 't' : 'b'));
310         else
311 #  endif
312         {
313 #  if defined(OPENSSL_SYS_WINDOWS)
314             int fd = _fileno((FILE *)ptr);
315             if (num & BIO_FP_TEXT)
316                 _setmode(fd, _O_TEXT);
317             else
318                 _setmode(fd, _O_BINARY);
319 #  elif defined(OPENSSL_SYS_MSDOS)
320             int fd = fileno((FILE *)ptr);
321             /* Set correct text/binary mode */
322             if (num & BIO_FP_TEXT)
323                 _setmode(fd, _O_TEXT);
324             /* Dangerous to set stdin/stdout to raw (unless redirected) */
325             else {
326                 if (fd == STDIN_FILENO || fd == STDOUT_FILENO) {
327                     if (isatty(fd) <= 0)
328                         _setmode(fd, _O_BINARY);
329                 } else
330                     _setmode(fd, _O_BINARY);
331             }
332 #  elif defined(OPENSSL_SYS_WIN32_CYGWIN)
333             int fd = fileno((FILE *)ptr);
334             if (num & BIO_FP_TEXT)
335                 setmode(fd, O_TEXT);
336             else
337                 setmode(fd, O_BINARY);
338 #  endif
339         }
340         break;
341     case BIO_C_SET_FILENAME:
342         file_free(b);
343         b->shutdown = (int)num & BIO_CLOSE;
344         if (num & BIO_FP_APPEND) {
345             if (num & BIO_FP_READ)
346                 OPENSSL_strlcpy(p, "a+", sizeof p);
347             else
348                 OPENSSL_strlcpy(p, "a", sizeof p);
349         } else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE))
350             OPENSSL_strlcpy(p, "r+", sizeof p);
351         else if (num & BIO_FP_WRITE)
352             OPENSSL_strlcpy(p, "w", sizeof p);
353         else if (num & BIO_FP_READ)
354             OPENSSL_strlcpy(p, "r", sizeof p);
355         else {
356             BIOerr(BIO_F_FILE_CTRL, BIO_R_BAD_FOPEN_MODE);
357             ret = 0;
358             break;
359         }
360 #  if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32_CYGWIN)
361         if (!(num & BIO_FP_TEXT))
362             strcat(p, "b");
363         else
364             strcat(p, "t");
365 #  endif
366         fp = file_fopen(ptr, p);
367         if (fp == NULL) {
368             SYSerr(SYS_F_FOPEN, get_last_sys_error());
369             ERR_add_error_data(5, "fopen('", ptr, "','", p, "')");
370             BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
371             ret = 0;
372             break;
373         }
374         b->ptr = fp;
375         b->init = 1;
376         BIO_clear_flags(b, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
377                                                * UPLINK */
378         break;
379     case BIO_C_GET_FILE_PTR:
380         /* the ptr parameter is actually a FILE ** in this case. */
381         if (ptr != NULL) {
382             fpp = (FILE **)ptr;
383             *fpp = (FILE *)b->ptr;
384         }
385         break;
386     case BIO_CTRL_GET_CLOSE:
387         ret = (long)b->shutdown;
388         break;
389     case BIO_CTRL_SET_CLOSE:
390         b->shutdown = (int)num;
391         break;
392     case BIO_CTRL_FLUSH:
393         if (b->flags & BIO_FLAGS_UPLINK)
394             UP_fflush(b->ptr);
395         else
396             fflush((FILE *)b->ptr);
397         break;
398     case BIO_CTRL_DUP:
399         ret = 1;
400         break;
401
402     case BIO_CTRL_WPENDING:
403     case BIO_CTRL_PENDING:
404     case BIO_CTRL_PUSH:
405     case BIO_CTRL_POP:
406     default:
407         ret = 0;
408         break;
409     }
410     return (ret);
411 }
412
413 static int file_gets(BIO *bp, char *buf, int size)
414 {
415     int ret = 0;
416
417     buf[0] = '\0';
418     if (bp->flags & BIO_FLAGS_UPLINK) {
419         if (!UP_fgets(buf, size, bp->ptr))
420             goto err;
421     } else {
422         if (!fgets(buf, size, (FILE *)bp->ptr))
423             goto err;
424     }
425     if (buf[0] != '\0')
426         ret = strlen(buf);
427  err:
428     return (ret);
429 }
430
431 static int file_puts(BIO *bp, const char *str)
432 {
433     int n, ret;
434
435     n = strlen(str);
436     ret = file_write(bp, str, n);
437     return (ret);
438 }
439
440 #else
441
442 static int file_write(BIO *b, const char *in, int inl)
443 {
444     return -1;
445 }
446 static int file_read(BIO *b, char *out, int outl)
447 {
448     return -1;
449 }
450 static int file_puts(BIO *bp, const char *str)
451 {
452     return -1;
453 }
454 static int file_gets(BIO *bp, char *buf, int size)
455 {
456     return 0;
457 }
458 static long file_ctrl(BIO *b, int cmd, long num, void *ptr)
459 {
460     return 0;
461 }
462 static int file_new(BIO *bi)
463 {
464     return 0;
465 }
466 static int file_free(BIO *a)
467 {
468     return 0;
469 }
470
471 static const BIO_METHOD methods_filep = {
472     BIO_TYPE_FILE,
473     "FILE pointer",
474     file_write,
475     file_read,
476     file_puts,
477     file_gets,
478     file_ctrl,
479     file_new,
480     file_free,
481     NULL,
482 };
483
484 const BIO_METHOD *BIO_s_file(void)
485 {
486     return (&methods_filep);
487 }
488
489 BIO *BIO_new_file(const char *filename, const char *mode)
490 {
491     return NULL;
492 }
493
494 # endif                         /* OPENSSL_NO_STDIO */
495
496 #endif                          /* HEADER_BSS_FILE_C */