make update
[openssl.git] / crypto / cryptlib.c
1 /* ====================================================================
2  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    openssl-core@openssl.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This product includes cryptographic software written by Eric Young
50  * (eay@cryptsoft.com).  This product includes software written by Tim
51  * Hudson (tjh@cryptsoft.com).
52  *
53  */
54 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
55  * All rights reserved.
56  *
57  * This package is an SSL implementation written
58  * by Eric Young (eay@cryptsoft.com).
59  * The implementation was written so as to conform with Netscapes SSL.
60  *
61  * This library is free for commercial and non-commercial use as long as
62  * the following conditions are aheared to.  The following conditions
63  * apply to all code found in this distribution, be it the RC4, RSA,
64  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
65  * included with this distribution is covered by the same copyright terms
66  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
67  *
68  * Copyright remains Eric Young's, and as such any Copyright notices in
69  * the code are not to be removed.
70  * If this package is used in a product, Eric Young should be given attribution
71  * as the author of the parts of the library used.
72  * This can be in the form of a textual message at program startup or
73  * in documentation (online or textual) provided with the package.
74  *
75  * Redistribution and use in source and binary forms, with or without
76  * modification, are permitted provided that the following conditions
77  * are met:
78  * 1. Redistributions of source code must retain the copyright
79  *    notice, this list of conditions and the following disclaimer.
80  * 2. Redistributions in binary form must reproduce the above copyright
81  *    notice, this list of conditions and the following disclaimer in the
82  *    documentation and/or other materials provided with the distribution.
83  * 3. All advertising materials mentioning features or use of this software
84  *    must display the following acknowledgement:
85  *    "This product includes cryptographic software written by
86  *     Eric Young (eay@cryptsoft.com)"
87  *    The word 'cryptographic' can be left out if the rouines from the library
88  *    being used are not cryptographic related :-).
89  * 4. If you include any Windows specific code (or a derivative thereof) from
90  *    the apps directory (application code) you must include an acknowledgement:
91  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
92  *
93  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
94  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
95  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
96  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
97  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
98  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
99  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
101  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
102  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
103  * SUCH DAMAGE.
104  *
105  * The licence and distribution terms for any publically available version or
106  * derivative of this code cannot be changed.  i.e. this code cannot simply be
107  * copied and put under another distribution licence
108  * [including the GNU Public Licence.]
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECDH support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114  */
115
116 #include "internal/cryptlib_int.h"
117 #include <openssl/safestack.h>
118
119 #if     defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
120         defined(__INTEL__) || \
121         defined(__x86_64) || defined(__x86_64__) || \
122         defined(_M_AMD64) || defined(_M_X64)
123
124 extern unsigned int OPENSSL_ia32cap_P[4];
125 unsigned int *OPENSSL_ia32cap_loc(void)
126 {
127     return OPENSSL_ia32cap_P;
128 }
129
130 # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
131 #include <stdio.h>
132 #  define OPENSSL_CPUID_SETUP
133 typedef uint64_t IA32CAP;
134 void OPENSSL_cpuid_setup(void)
135 {
136     static int trigger = 0;
137     IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
138     IA32CAP vec;
139     char *env;
140
141     if (trigger)
142         return;
143
144     trigger = 1;
145     if ((env = getenv("OPENSSL_ia32cap"))) {
146         int off = (env[0] == '~') ? 1 : 0;
147 #  if defined(_WIN32)
148         if (!sscanf(env + off, "%I64i", &vec))
149             vec = strtoul(env + off, NULL, 0);
150 #  else
151         if (!sscanf(env + off, "%lli", (long long *)&vec))
152             vec = strtoul(env + off, NULL, 0);
153 #  endif
154         if (off)
155             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~vec;
156         else if (env[0] == ':')
157             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
158
159         OPENSSL_ia32cap_P[2] = 0;
160         if ((env = strchr(env, ':'))) {
161             unsigned int vecx;
162             env++;
163             off = (env[0] == '~') ? 1 : 0;
164             vecx = strtoul(env + off, NULL, 0);
165             if (off)
166                 OPENSSL_ia32cap_P[2] &= ~vecx;
167             else
168                 OPENSSL_ia32cap_P[2] = vecx;
169         }
170     } else
171         vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
172
173     /*
174      * |(1<<10) sets a reserved bit to signal that variable
175      * was initialized already... This is to avoid interference
176      * with cpuid snippets in ELF .init segment.
177      */
178     OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
179     OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
180 }
181 # else
182 unsigned int OPENSSL_ia32cap_P[4];
183 # endif
184
185 #else
186 unsigned int *OPENSSL_ia32cap_loc(void)
187 {
188     return NULL;
189 }
190 #endif
191 int OPENSSL_NONPIC_relocated = 0;
192 #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
193 void OPENSSL_cpuid_setup(void)
194 {
195 }
196 #endif
197
198 #if defined(_WIN32) && !defined(__CYGWIN__)
199 # include <tchar.h>
200 # include <signal.h>
201 # ifdef __WATCOMC__
202 #  if defined(_UNICODE) || defined(__UNICODE__)
203 #   define _vsntprintf _vsnwprintf
204 #  else
205 #   define _vsntprintf _vsnprintf
206 #  endif
207 # endif
208 # ifdef _MSC_VER
209 #  define alloca _alloca
210 # endif
211
212 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
213 int OPENSSL_isservice(void)
214 {
215     HWINSTA h;
216     DWORD len;
217     WCHAR *name;
218     static union {
219         void *p;
220         FARPROC f;
221     } _OPENSSL_isservice = {
222         NULL
223     };
224
225     if (_OPENSSL_isservice.p == NULL) {
226         HANDLE mod = GetModuleHandle(NULL);
227         if (mod != NULL)
228             _OPENSSL_isservice.f = GetProcAddress(mod, "_OPENSSL_isservice");
229         if (_OPENSSL_isservice.p == NULL)
230             _OPENSSL_isservice.p = (void *)-1;
231     }
232
233     if (_OPENSSL_isservice.p != (void *)-1)
234         return (*_OPENSSL_isservice.f) ();
235
236     h = GetProcessWindowStation();
237     if (h == NULL)
238         return -1;
239
240     if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
241         GetLastError() != ERROR_INSUFFICIENT_BUFFER)
242         return -1;
243
244     if (len > 512)
245         return -1;              /* paranoia */
246     len++, len &= ~1;           /* paranoia */
247     name = (WCHAR *)alloca(len + sizeof(WCHAR));
248     if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
249         return -1;
250
251     len++, len &= ~1;           /* paranoia */
252     name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
253 #  if 1
254     /*
255      * This doesn't cover "interactive" services [working with real
256      * WinSta0's] nor programs started non-interactively by Task Scheduler
257      * [those are working with SAWinSta].
258      */
259     if (wcsstr(name, L"Service-0x"))
260         return 1;
261 #  else
262     /* This covers all non-interactive programs such as services. */
263     if (!wcsstr(name, L"WinSta0"))
264         return 1;
265 #  endif
266     else
267         return 0;
268 }
269 # else
270 int OPENSSL_isservice(void)
271 {
272     return 0;
273 }
274 # endif
275
276 void OPENSSL_showfatal(const char *fmta, ...)
277 {
278     va_list ap;
279     TCHAR buf[256];
280     const TCHAR *fmt;
281 # ifdef STD_ERROR_HANDLE        /* what a dirty trick! */
282     HANDLE h;
283
284     if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
285         GetFileType(h) != FILE_TYPE_UNKNOWN) {
286         /* must be console application */
287         int len;
288         DWORD out;
289
290         va_start(ap, fmta);
291         len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
292         WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
293         va_end(ap);
294         return;
295     }
296 # endif
297
298     if (sizeof(TCHAR) == sizeof(char))
299         fmt = (const TCHAR *)fmta;
300     else
301         do {
302             int keepgoing;
303             size_t len_0 = strlen(fmta) + 1, i;
304             WCHAR *fmtw;
305
306             fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
307             if (fmtw == NULL) {
308                 fmt = (const TCHAR *)L"no stack?";
309                 break;
310             }
311             if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
312                 for (i = 0; i < len_0; i++)
313                     fmtw[i] = (WCHAR)fmta[i];
314             for (i = 0; i < len_0; i++) {
315                 if (fmtw[i] == L'%')
316                     do {
317                         keepgoing = 0;
318                         switch (fmtw[i + 1]) {
319                         case L'0':
320                         case L'1':
321                         case L'2':
322                         case L'3':
323                         case L'4':
324                         case L'5':
325                         case L'6':
326                         case L'7':
327                         case L'8':
328                         case L'9':
329                         case L'.':
330                         case L'*':
331                         case L'-':
332                             i++;
333                             keepgoing = 1;
334                             break;
335                         case L's':
336                             fmtw[i + 1] = L'S';
337                             break;
338                         case L'S':
339                             fmtw[i + 1] = L's';
340                             break;
341                         case L'c':
342                             fmtw[i + 1] = L'C';
343                             break;
344                         case L'C':
345                             fmtw[i + 1] = L'c';
346                             break;
347                         }
348                     } while (keepgoing);
349             }
350             fmt = (const TCHAR *)fmtw;
351         } while (0);
352
353     va_start(ap, fmta);
354     _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
355     buf[OSSL_NELEM(buf) - 1] = _T('\0');
356     va_end(ap);
357
358 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
359     /* this -------------v--- guards NT-specific calls */
360     if (check_winnt() && OPENSSL_isservice() > 0) {
361         HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
362
363         if (hEventLog != NULL) {
364             const TCHAR *pmsg = buf;
365
366             if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
367                              1, 0, &pmsg, NULL)) {
368 #if defined(DEBUG)
369                 /*
370                  * We are in a situation where we tried to report a critical
371                  * error and this failed for some reason. As a last resort,
372                  * in debug builds, send output to the debugger or any other
373                  * tool like DebugView which can monitor the output.
374                  */
375                 OutputDebugString(pmsg);
376 #endif
377             }
378
379             (void)DeregisterEventSource(hEventLog);
380         }
381     } else
382 # endif
383         MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
384 }
385 #else
386 void OPENSSL_showfatal(const char *fmta, ...)
387 {
388 #ifndef OPENSSL_NO_STDIO
389     va_list ap;
390
391     va_start(ap, fmta);
392     vfprintf(stderr, fmta, ap);
393     va_end(ap);
394 #endif
395 }
396
397 int OPENSSL_isservice(void)
398 {
399     return 0;
400 }
401 #endif
402
403 void OPENSSL_die(const char *message, const char *file, int line)
404 {
405     OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n",
406                       file, line, message);
407 #if !defined(_WIN32) || defined(__CYGWIN__)
408     abort();
409 #else
410     /*
411      * Win32 abort() customarily shows a dialog, but we just did that...
412      */
413 # if !defined(_WIN32_WCE)
414     raise(SIGABRT);
415 # endif
416     _exit(3);
417 #endif
418 }
419
420 /* volatile unsigned char* pointers are there because
421  * 1. Accessing a variable declared volatile via a pointer
422  *    that lacks a volatile qualifier causes undefined behavior.
423  * 2. When the variable itself is not volatile the compiler is
424  *    not required to keep all those reads and can convert
425  *    this into canonical memcmp() which doesn't read the whole block.
426  * Pointers to volatile resolve the first problem fully. The second
427  * problem cannot be resolved in any Standard-compliant way but this
428  * works the problem around. Compilers typically react to
429  * pointers to volatile by preserving the reads and writes through them.
430  * The latter is not required by the Standard if the memory pointed to
431  * is not volatile.
432  * Pointers themselves are volatile in the function signature to work
433  * around a subtle bug in gcc 4.6+ which causes writes through
434  * pointers to volatile to not be emitted in some rare,
435  * never needed in real life, pieces of code.
436  */
437 int CRYPTO_memcmp(const volatile void * volatile in_a,
438                   const volatile void * volatile in_b,
439                   size_t len)
440 {
441     size_t i;
442     const volatile unsigned char *a = in_a;
443     const volatile unsigned char *b = in_b;
444     unsigned char x = 0;
445
446     for (i = 0; i < len; i++)
447         x |= a[i] ^ b[i];
448
449     return x;
450 }