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