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