Fix setbuf use for VMS C
[openssl.git] / crypto / rand / randfile.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 #include "internal/cryptlib.h"
11
12 #include <errno.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16
17 #include <openssl/crypto.h>
18 #include <openssl/rand.h>
19 #include <openssl/buffer.h>
20
21 #ifdef OPENSSL_SYS_VMS
22 # include <unixio.h>
23 #endif
24 #include <sys/types.h>
25 #ifndef OPENSSL_NO_POSIX_IO
26 # include <sys/stat.h>
27 # include <fcntl.h>
28 # ifdef _WIN32
29 #  include <windows.h>
30 #  include <io.h>
31 #  define stat    _stat
32 #  define chmod   _chmod
33 #  define open    _open
34 #  define fdopen  _fdopen
35 #  define fstat   _fstat
36 #  define fileno  _fileno
37 # endif
38 #endif
39
40 /*
41  * Following should not be needed, and we could have been stricter
42  * and demand S_IS*. But some systems just don't comply... Formally
43  * below macros are "anatomically incorrect", because normally they
44  * would look like ((m) & MASK == TYPE), but since MASK availability
45  * is as questionable, we settle for this poor-man fallback...
46  */
47 # if !defined(S_ISREG)
48 #   define S_ISREG(m) ((m) & S_IFREG)
49 # endif
50
51 #define RAND_FILE_SIZE 1024
52 #define RFILE ".rnd"
53
54 #ifdef OPENSSL_SYS_VMS
55 /*
56  * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
57  * to make sure the FILE* is a 32-bit pointer no matter what.  We know that
58  * stdio functions return this type (a study of stdio.h proves it).
59  *
60  * This declaration is a nasty hack to get around vms' extension to fopen for
61  * passing in sharing options being disabled by /STANDARD=ANSI89
62  */
63 static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
64         (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
65 # define VMS_OPEN_ATTRS \
66         "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
67 # define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
68 #endif
69
70 /*
71  * Note that these functions are intended for seed files only. Entropy
72  * devices and EGD sockets are handled in rand_unix.c  If |bytes| is
73  * -1 read the complete file; otherwise read the specified amount.
74  */
75 int RAND_load_file(const char *file, long bytes)
76 {
77     unsigned char buf[RAND_FILE_SIZE];
78 #ifndef OPENSSL_NO_POSIX_IO
79     struct stat sb;
80 #endif
81     int i, n, ret = 0;
82     FILE *in;
83
84     if (bytes == 0)
85         return 0;
86
87     if ((in = openssl_fopen(file, "rb")) == NULL) {
88         RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_CANNOT_OPEN_FILE);
89         ERR_add_error_data(2, "Filename=", file);
90         return -1;
91     }
92
93 #ifndef OPENSSL_NO_POSIX_IO
94     if (fstat(fileno(in), &sb) < 0) {
95         RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_INTERNAL_ERROR);
96         ERR_add_error_data(2, "Filename=", file);
97         return -1;
98     }
99
100     if (!S_ISREG(sb.st_mode) && bytes < 0)
101         bytes = 256;
102 #endif
103     /*
104      * On VMS, setbuf() will only take 32-bit pointers, and a compilation
105      * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
106      * However, we trust that the C RTL will never give us a FILE pointer
107      * above the first 4 GB of memory, so we simply turn off the warning
108      * temporarily.
109      */
110 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
111 # pragma environment save
112 # pragma message disable maylosedata2
113 #endif
114     /*
115      * Don't buffer, because even if |file| is regular file, we have
116      * no control over the buffer, so why would we want a copy of its
117      * contents lying around?
118      */
119     setbuf(in, NULL);
120 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
121 # pragma environment restore
122 #endif
123
124     for ( ; ; ) {
125         if (bytes > 0)
126             n = (bytes < RAND_FILE_SIZE) ? (int)bytes : RAND_FILE_SIZE;
127         else
128             n = RAND_FILE_SIZE;
129         i = fread(buf, 1, n, in);
130 #ifdef EINTR
131         if (ferror(in) && errno == EINTR){
132             clearerr(in);
133             if (i == 0)
134                 continue;
135         }
136 #endif
137         if (i == 0)
138             break;
139
140         RAND_add(buf, i, (double)i);
141         ret += i;
142
143         /* If given a bytecount, and we did it, break. */
144         if (bytes > 0 && (bytes -= i) <= 0)
145             break;
146     }
147
148     OPENSSL_cleanse(buf, sizeof(buf));
149     fclose(in);
150     return ret;
151 }
152
153 int RAND_write_file(const char *file)
154 {
155     unsigned char buf[RAND_FILE_SIZE];
156     int ret = -1;
157     FILE *out = NULL;
158 #ifndef OPENSSL_NO_POSIX_IO
159     struct stat sb;
160
161     if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
162         RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_NOT_A_REGULAR_FILE);
163         ERR_add_error_data(2, "Filename=", file);
164         return -1;
165     }
166 #endif
167
168     /* Collect enough random data. */
169     if (RAND_bytes(buf, (int)sizeof(buf)) != 1)
170         return  -1;
171
172 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
173     !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
174     {
175 # ifndef O_BINARY
176 #  define O_BINARY 0
177 # endif
178         /*
179          * chmod(..., 0600) is too late to protect the file, permissions
180          * should be restrictive from the start
181          */
182         int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
183         if (fd != -1)
184             out = fdopen(fd, "wb");
185     }
186 #endif
187
188 #ifdef OPENSSL_SYS_VMS
189     /*
190      * VMS NOTE: Prior versions of this routine created a _new_ version of
191      * the rand file for each call into this routine, then deleted all
192      * existing versions named ;-1, and finally renamed the current version
193      * as ';1'. Under concurrent usage, this resulted in an RMS race
194      * condition in rename() which could orphan files (see vms message help
195      * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
196      * the top-level version of the rand file. Note that there may still be
197      * conditions where the top-level rand file is locked. If so, this code
198      * will then create a new version of the rand file. Without the delete
199      * and rename code, this can result in ascending file versions that stop
200      * at version 32767, and this routine will then return an error. The
201      * remedy for this is to recode the calling application to avoid
202      * concurrent use of the rand file, or synchronize usage at the
203      * application level. Also consider whether or not you NEED a persistent
204      * rand file in a concurrent use situation.
205      */
206     out = openssl_fopen(file, "rb+");
207 #endif
208
209     if (out == NULL)
210         out = openssl_fopen(file, "wb");
211     if (out == NULL) {
212         RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_CANNOT_OPEN_FILE);
213         ERR_add_error_data(2, "Filename=", file);
214         return -1;
215     }
216
217 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
218     /*
219      * Yes it's late to do this (see above comment), but better than nothing.
220      */
221     chmod(file, 0600);
222 #endif
223
224     ret = fwrite(buf, 1, RAND_FILE_SIZE, out);
225     fclose(out);
226     OPENSSL_cleanse(buf, RAND_FILE_SIZE);
227     return ret;
228 }
229
230 const char *RAND_file_name(char *buf, size_t size)
231 {
232     char *s = NULL;
233     size_t len;
234     int use_randfile = 1;
235
236 #if defined(_WIN32) && defined(CP_UTF8)
237     DWORD envlen;
238     WCHAR *var;
239
240     /* Look up various environment variables. */
241     if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
242         use_randfile = 0;
243         if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
244                 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
245                                                   NULL, 0)) == 0)
246             envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
247     }
248
249     /* If we got a value, allocate space to hold it and then get it. */
250     if (envlen != 0) {
251         int sz;
252         WCHAR *val = _alloca(envlen * sizeof(WCHAR));
253
254         if (GetEnvironmentVariableW(var, val, envlen) < envlen
255                 && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
256                                              NULL, NULL)) != 0) {
257             s = _alloca(sz);
258             if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
259                                     NULL, NULL) == 0)
260                 s = NULL;
261         }
262     }
263 #else
264     if (OPENSSL_issetugid() != 0) {
265         use_randfile = 0;
266     } else if ((s = getenv("RANDFILE")) == NULL || *s == '\0') {
267         use_randfile = 0;
268         s = getenv("HOME");
269     }
270 #endif
271
272 #ifdef DEFAULT_HOME
273     if (!use_randfile && s == NULL)
274         s = DEFAULT_HOME;
275 #endif
276     if (s == NULL || *s == '\0')
277         return NULL;
278
279     len = strlen(s);
280     if (use_randfile) {
281         if (len + 1 >= size)
282             return NULL;
283         strcpy(buf, s);
284     } else {
285         if (len + 1 + strlen(RFILE) + 1 >= size)
286             return NULL;
287         strcpy(buf, s);
288 #ifndef OPENSSL_SYS_VMS
289         strcat(buf, "/");
290 #endif
291         strcat(buf, RFILE);
292     }
293
294     return buf;
295 }