1/* global.c  -	global control functions
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
3 *               2004, 2005, 2006, 2008, 2011  Free Software Foundation, Inc.
4 *
5 * This file is part of Libgcrypt.
6 *
7 * Libgcrypt is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser general Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * Libgcrypt is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21#include <config.h>
22
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <stdarg.h>
27#include <ctype.h>
28#include <limits.h>
29#include <errno.h>
30#include <unistd.h>
31#ifdef HAVE_SYSLOG
32# include <syslog.h>
33#endif /*HAVE_SYSLOG*/
34
35#include "g10lib.h"
36#include "cipher.h"
37#include "stdmem.h" /* our own memory allocator */
38#include "secmem.h" /* our own secmem allocator */
39#include "ath.h"
40
41
42
43/****************
44 * flag bits: 0 : general cipher debug
45 *	      1 : general MPI debug
46 */
47static unsigned int debug_flags;
48
49/* gcry_control (GCRYCTL_SET_FIPS_MODE), sets this flag so that the
50   initialization code switched fips mode on.  */
51static int force_fips_mode;
52
53/* Controlled by global_init().  */
54static int any_init_done;
55
56/* A table to map hardware features to a string.  */
57static struct
58{
59  unsigned int flag;
60  const char *desc;
61} hwflist[] =
62  {
63    { HWF_PADLOCK_RNG, "padlock-rng" },
64    { HWF_PADLOCK_AES, "padlock-aes" },
65    { HWF_PADLOCK_SHA, "padlock-sha" },
66    { HWF_PADLOCK_MMUL,"padlock-mmul"},
67    { HWF_INTEL_AESNI, "intel-aesni" },
68    { 0, NULL}
69  };
70
71/* A bit vector with the hardware features which shall not be used.
72   This variable must be set prior to any initialization.  */
73static unsigned int disabled_hw_features;
74
75
76/* Memory management. */
77
78static gcry_handler_alloc_t alloc_func;
79static gcry_handler_alloc_t alloc_secure_func;
80static gcry_handler_secure_check_t is_secure_func;
81static gcry_handler_realloc_t realloc_func;
82static gcry_handler_free_t free_func;
83static gcry_handler_no_mem_t outofcore_handler;
84static void *outofcore_handler_value;
85static int no_secure_memory;
86
87
88
89
90
91/* This is our handmade constructor.  It gets called by any function
92   likely to be called at startup.  The suggested way for an
93   application to make sure that this has been called is by using
94   gcry_check_version. */
95static void
96global_init (void)
97{
98  gcry_error_t err = 0;
99
100  if (any_init_done)
101    return;
102  any_init_done = 1;
103
104  /* Initialize our portable thread/mutex wrapper.  */
105  err = ath_init ();
106  if (err)
107    goto fail;
108
109  /* See whether the system is in FIPS mode.  This needs to come as
110     early as possible put after the ATH has been initialized.  */
111  _gcry_initialize_fips_mode (force_fips_mode);
112
113  /* Before we do any other initialization we need to test available
114     hardware features.  */
115  _gcry_detect_hw_features (disabled_hw_features);
116
117  err = _gcry_cipher_init ();
118  if (err)
119    goto fail;
120  err = _gcry_md_init ();
121  if (err)
122    goto fail;
123  err = _gcry_pk_init ();
124  if (err)
125    goto fail;
126#if 0
127  /* Hmmm, as of now ac_init does nothing. */
128  if ( !fips_mode () )
129    {
130      err = _gcry_ac_init ();
131      if (err)
132        goto fail;
133    }
134#endif
135
136  return;
137
138 fail:
139  BUG ();
140}
141
142
143/* This function is called by the macro fips_is_operational and makes
144   sure that the minimal initialization has been done.  This is far
145   from a perfect solution and hides problems with an improper
146   initialization but at least in single-threaded mode it should work
147   reliable.
148
149   The reason we need this is that a lot of applications don't use
150   Libgcrypt properly by not running any initialization code at all.
151   They just call a Libgcrypt function and that is all what they want.
152   Now with the FIPS mode, that has the side effect of entering FIPS
153   mode (for security reasons, FIPS mode is the default if no
154   initialization has been done) and bailing out immediately because
155   the FSM is in the wrong state.  If we always run the init code,
156   Libgcrypt can test for FIPS mode and at least if not in FIPS mode,
157   it will behave as before.  Note that this on-the-fly initialization
158   is only done for the cryptographic functions subject to FIPS mode
159   and thus not all API calls will do such an initialization.  */
160int
161_gcry_global_is_operational (void)
162{
163  if (!any_init_done)
164    {
165#ifdef HAVE_SYSLOG
166      syslog (LOG_USER|LOG_WARNING, "Libgcrypt warning: "
167              "missing initialization - please fix the application");
168#endif /*HAVE_SYSLOG*/
169      global_init ();
170    }
171  return _gcry_fips_is_operational ();
172}
173
174
175
176
177/* Version number parsing.  */
178
179/* This function parses the first portion of the version number S and
180   stores it in *NUMBER.  On success, this function returns a pointer
181   into S starting with the first character, which is not part of the
182   initial number portion; on failure, NULL is returned.  */
183static const char*
184parse_version_number( const char *s, int *number )
185{
186    int val = 0;
187
188    if( *s == '0' && isdigit(s[1]) )
189	return NULL; /* leading zeros are not allowed */
190    for ( ; isdigit(*s); s++ ) {
191	val *= 10;
192	val += *s - '0';
193    }
194    *number = val;
195    return val < 0? NULL : s;
196}
197
198/* This function breaks up the complete string-representation of the
199   version number S, which is of the following struture: <major
200   number>.<minor number>.<micro number><patch level>.  The major,
201   minor and micro number components will be stored in *MAJOR, *MINOR
202   and *MICRO.
203
204   On success, the last component, the patch level, will be returned;
205   in failure, NULL will be returned.  */
206
207static const char *
208parse_version_string( const char *s, int *major, int *minor, int *micro )
209{
210    s = parse_version_number( s, major );
211    if( !s || *s != '.' )
212	return NULL;
213    s++;
214    s = parse_version_number( s, minor );
215    if( !s || *s != '.' )
216	return NULL;
217    s++;
218    s = parse_version_number( s, micro );
219    if( !s )
220	return NULL;
221    return s; /* patchlevel */
222}
223
224/* If REQ_VERSION is non-NULL, check that the version of the library
225   is at minimum the requested one.  Returns the string representation
226   of the library version if the condition is satisfied; return NULL
227   if the requested version is newer than that of the library.
228
229   If a NULL is passed to this function, no check is done, but the
230   string representation of the library is simply returned.  */
231const char *
232gcry_check_version( const char *req_version )
233{
234    const char *ver = VERSION;
235    int my_major, my_minor, my_micro;
236    int rq_major, rq_minor, rq_micro;
237    const char *my_plvl;
238
239    /* Initialize library.  */
240    global_init ();
241
242    if ( !req_version )
243        /* Caller wants our version number.  */
244	return ver;
245
246    /* Parse own version number.  */
247    my_plvl = parse_version_string( ver, &my_major, &my_minor, &my_micro );
248    if ( !my_plvl )
249        /* very strange our own version is bogus.  Shouldn't we use
250	   assert() here and bail out in case this happens?  -mo.  */
251	return NULL;
252
253    /* Parse requested version number.  */
254    if (!parse_version_string (req_version, &rq_major, &rq_minor, &rq_micro))
255      return NULL;  /* req version string is invalid, this can happen.  */
256
257    /* Compare version numbers.  */
258    if ( my_major > rq_major
259	|| (my_major == rq_major && my_minor > rq_minor)
260	|| (my_major == rq_major && my_minor == rq_minor		                           		 && my_micro > rq_micro)
261	|| (my_major == rq_major && my_minor == rq_minor
262                                 && my_micro == rq_micro))
263      {
264	return ver;
265      }
266
267    return NULL;
268}
269
270
271static void
272print_config ( int (*fnc)(FILE *fp, const char *format, ...), FILE *fp)
273{
274  unsigned int hwf;
275  int i;
276
277  fnc (fp, "version:%s:\n", VERSION);
278  fnc (fp, "ciphers:%s:\n", LIBGCRYPT_CIPHERS);
279  fnc (fp, "pubkeys:%s:\n", LIBGCRYPT_PUBKEY_CIPHERS);
280  fnc (fp, "digests:%s:\n", LIBGCRYPT_DIGESTS);
281  fnc (fp, "rnd-mod:"
282#if USE_RNDEGD
283                "egd:"
284#endif
285#if USE_RNDLINUX
286                "linux:"
287#endif
288#if USE_RNDUNIX
289                "unix:"
290#endif
291#if USE_RNDW32
292                "w32:"
293#endif
294       "\n");
295  fnc (fp, "mpi-asm:%s:\n", _gcry_mpi_get_hw_config ());
296  hwf = _gcry_get_hw_features ();
297  fnc (fp, "hwflist:");
298  for (i=0; hwflist[i].desc; i++)
299    if ( (hwf & hwflist[i].flag) )
300      fnc (fp, "%s:", hwflist[i].desc);
301  fnc (fp, "\n");
302  /* We use y/n instead of 1/0 for the simple reason that Emacsen's
303     compile error parser would accidently flag that line when printed
304     during "make check" as an error.  */
305  fnc (fp, "fips-mode:%c:%c:\n",
306       fips_mode ()? 'y':'n',
307       _gcry_enforced_fips_mode ()? 'y':'n' );
308}
309
310
311
312
313/* Command dispatcher function, acting as general control
314   function.  */
315gcry_error_t
316_gcry_vcontrol (enum gcry_ctl_cmds cmd, va_list arg_ptr)
317{
318  static int init_finished = 0;
319  gcry_err_code_t err = 0;
320
321  switch (cmd)
322    {
323    case GCRYCTL_ENABLE_M_GUARD:
324      _gcry_private_enable_m_guard ();
325      break;
326
327    case GCRYCTL_ENABLE_QUICK_RANDOM:
328      _gcry_enable_quick_random_gen ();
329      break;
330
331    case GCRYCTL_FAKED_RANDOM_P:
332      /* Return an error if the RNG is faked one (e.g. enabled by
333         ENABLE_QUICK_RANDOM. */
334      if (_gcry_random_is_faked ())
335        err = GPG_ERR_GENERAL;  /* Use as TRUE value.  */
336      break;
337
338    case GCRYCTL_DUMP_RANDOM_STATS:
339      _gcry_random_dump_stats ();
340      break;
341
342    case GCRYCTL_DUMP_MEMORY_STATS:
343      /*m_print_stats("[fixme: prefix]");*/
344      break;
345
346    case GCRYCTL_DUMP_SECMEM_STATS:
347      _gcry_secmem_dump_stats ();
348      break;
349
350    case GCRYCTL_DROP_PRIVS:
351      global_init ();
352      _gcry_secmem_init (0);
353      break;
354
355    case GCRYCTL_DISABLE_SECMEM:
356      global_init ();
357      no_secure_memory = 1;
358      break;
359
360    case GCRYCTL_INIT_SECMEM:
361      global_init ();
362      _gcry_secmem_init (va_arg (arg_ptr, unsigned int));
363      if ((_gcry_secmem_get_flags () & GCRY_SECMEM_FLAG_NOT_LOCKED))
364        err = GPG_ERR_GENERAL;
365      break;
366
367    case GCRYCTL_TERM_SECMEM:
368      global_init ();
369      _gcry_secmem_term ();
370      break;
371
372    case GCRYCTL_DISABLE_SECMEM_WARN:
373      _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
374			       | GCRY_SECMEM_FLAG_NO_WARNING));
375      break;
376
377    case GCRYCTL_SUSPEND_SECMEM_WARN:
378      _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
379			       | GCRY_SECMEM_FLAG_SUSPEND_WARNING));
380      break;
381
382    case GCRYCTL_RESUME_SECMEM_WARN:
383      _gcry_secmem_set_flags ((_gcry_secmem_get_flags ()
384			       & ~GCRY_SECMEM_FLAG_SUSPEND_WARNING));
385      break;
386
387    case GCRYCTL_USE_SECURE_RNDPOOL:
388      global_init ();
389      _gcry_secure_random_alloc (); /* Put random number into secure memory. */
390      break;
391
392    case GCRYCTL_SET_RANDOM_SEED_FILE:
393      _gcry_set_random_seed_file (va_arg (arg_ptr, const char *));
394      break;
395
396    case GCRYCTL_UPDATE_RANDOM_SEED_FILE:
397      if ( fips_is_operational () )
398        _gcry_update_random_seed_file ();
399      break;
400
401    case GCRYCTL_SET_VERBOSITY:
402      _gcry_set_log_verbosity (va_arg (arg_ptr, int));
403      break;
404
405    case GCRYCTL_SET_DEBUG_FLAGS:
406      debug_flags |= va_arg (arg_ptr, unsigned int);
407      break;
408
409    case GCRYCTL_CLEAR_DEBUG_FLAGS:
410      debug_flags &= ~va_arg (arg_ptr, unsigned int);
411      break;
412
413    case GCRYCTL_DISABLE_INTERNAL_LOCKING:
414      /* Not used anymore.  */
415      global_init ();
416      break;
417
418    case GCRYCTL_ANY_INITIALIZATION_P:
419      if (any_init_done)
420	err = GPG_ERR_GENERAL;
421      break;
422
423    case GCRYCTL_INITIALIZATION_FINISHED_P:
424      if (init_finished)
425	err = GPG_ERR_GENERAL; /* Yes.  */
426      break;
427
428    case GCRYCTL_INITIALIZATION_FINISHED:
429      /* This is a hook which should be used by an application after
430	 all initialization has been done and right before any threads
431	 are started.  It is not really needed but the only way to be
432	 really sure that all initialization for thread-safety has
433	 been done. */
434      if (! init_finished)
435        {
436          global_init ();
437          /* Do only a basic random initialization, i.e. init the
438             mutexes. */
439          _gcry_random_initialize (0);
440          init_finished = 1;
441          /* Force us into operational state if in FIPS mode.  */
442          (void)fips_is_operational ();
443        }
444      break;
445
446    case GCRYCTL_SET_THREAD_CBS:
447      err = ath_install (va_arg (arg_ptr, void *), any_init_done);
448      if (! err)
449	global_init ();
450      break;
451
452    case GCRYCTL_FAST_POLL:
453      /* We need to do make sure that the random pool is really
454         initialized so that the poll function is not a NOP. */
455      _gcry_random_initialize (1);
456
457      if ( fips_is_operational () )
458        _gcry_fast_random_poll ();
459      break;
460
461    case GCRYCTL_SET_RNDEGD_SOCKET:
462#if USE_RNDEGD
463      err = _gcry_rndegd_set_socket_name (va_arg (arg_ptr, const char *));
464#else
465      err = gpg_error (GPG_ERR_NOT_SUPPORTED);
466#endif
467      break;
468
469    case GCRYCTL_SET_RANDOM_DAEMON_SOCKET:
470      _gcry_set_random_daemon_socket (va_arg (arg_ptr, const char *));
471      break;
472
473    case GCRYCTL_USE_RANDOM_DAEMON:
474      /* We need to do make sure that the random pool is really
475         initialized so that the poll function is not a NOP. */
476      _gcry_random_initialize (1);
477      _gcry_use_random_daemon (!! va_arg (arg_ptr, int));
478      break;
479
480      /* This command dumps information pertaining to the
481         configuration of libgcrypt to the given stream.  It may be
482         used before the initialization has been finished but not
483         before a gcry_version_check. */
484    case GCRYCTL_PRINT_CONFIG:
485      {
486        FILE *fp = va_arg (arg_ptr, FILE *);
487        print_config (fp?fprintf:_gcry_log_info_with_dummy_fp, fp);
488      }
489      break;
490
491    case GCRYCTL_OPERATIONAL_P:
492      /* Returns true if the library is in an operational state.  This
493         is always true for non-fips mode.  */
494      if (_gcry_fips_test_operational ())
495        err = GPG_ERR_GENERAL; /* Used as TRUE value */
496      break;
497
498    case GCRYCTL_FIPS_MODE_P:
499      if (fips_mode ()
500          && !_gcry_is_fips_mode_inactive ()
501          && !no_secure_memory)
502	err = GPG_ERR_GENERAL; /* Used as TRUE value */
503      break;
504
505    case GCRYCTL_FORCE_FIPS_MODE:
506      /* Performing this command puts the library into fips mode.  If
507         the library has already been initialized into fips mode, a
508         selftest is triggered.  It is not possible to put the libraty
509         into fips mode after having passed the initialization. */
510      if (!any_init_done)
511        {
512          /* Not yet intialized at all.  Set a flag so that we are put
513             into fips mode during initialization.  */
514          force_fips_mode = 1;
515        }
516      else
517        {
518          /* Already initialized.  If we are already operational we
519             run a selftest.  If not we use the is_operational call to
520             force us into operational state if possible.  */
521          if (_gcry_fips_test_error_or_operational ())
522            _gcry_fips_run_selftests (1);
523          if (_gcry_fips_is_operational ())
524            err = GPG_ERR_GENERAL; /* Used as TRUE value */
525      }
526      break;
527
528    case GCRYCTL_SELFTEST:
529      /* Run a selftest.  This works in fips mode as well as in
530         standard mode.  In contrast to the power-up tests, we use an
531         extended version of the selftests. Returns 0 on success or an
532         error code. */
533      global_init ();
534      err = _gcry_fips_run_selftests (1);
535      break;
536
537#if _GCRY_GCC_VERSION >= 40600
538# pragma GCC diagnostic push
539# pragma GCC diagnostic ignored "-Wswitch"
540#endif
541    case 58:  /* Init external random test.  */
542      {
543        void **rctx        = va_arg (arg_ptr, void **);
544        unsigned int flags = va_arg (arg_ptr, unsigned int);
545        const void *key    = va_arg (arg_ptr, const void *);
546        size_t keylen      = va_arg (arg_ptr, size_t);
547        const void *seed   = va_arg (arg_ptr, const void *);
548        size_t seedlen     = va_arg (arg_ptr, size_t);
549        const void *dt     = va_arg (arg_ptr, const void *);
550        size_t dtlen       = va_arg (arg_ptr, size_t);
551        if (!fips_is_operational ())
552          err = fips_not_operational ();
553        else
554          err = _gcry_random_init_external_test (rctx, flags, key, keylen,
555                                                 seed, seedlen, dt, dtlen);
556      }
557      break;
558    case 59:  /* Run external random test.  */
559      {
560        void *ctx     = va_arg (arg_ptr, void *);
561        void *buffer  = va_arg (arg_ptr, void *);
562        size_t buflen = va_arg (arg_ptr, size_t);
563        if (!fips_is_operational ())
564          err = fips_not_operational ();
565        else
566          err = _gcry_random_run_external_test (ctx, buffer, buflen);
567      }
568      break;
569    case 60:  /* Deinit external random test.  */
570      {
571        void *ctx = va_arg (arg_ptr, void *);
572        _gcry_random_deinit_external_test (ctx);
573      }
574      break;
575    case 61:  /* RFU */
576      break;
577    case 62:  /* RFU */
578      break;
579#if _GCRY_GCC_VERSION >= 40600
580# pragma GCC diagnostic pop
581#endif
582
583    case GCRYCTL_DISABLE_HWF:
584      {
585        const char *name = va_arg (arg_ptr, const char *);
586        int i;
587
588        for (i=0; hwflist[i].desc; i++)
589          if (!strcmp (hwflist[i].desc, name))
590            {
591              disabled_hw_features |= hwflist[i].flag;
592              break;
593            }
594        if (!hwflist[i].desc)
595          err = GPG_ERR_INV_NAME;
596      }
597      break;
598
599    default:
600      /* A call to make sure that the dummy code is linked in.  */
601      _gcry_compat_identification ();
602      err = GPG_ERR_INV_OP;
603    }
604
605  return gcry_error (err);
606}
607
608
609/* Command dispatcher function, acting as general control
610   function.  */
611gcry_error_t
612gcry_control (enum gcry_ctl_cmds cmd, ...)
613{
614  gcry_error_t err;
615  va_list arg_ptr;
616
617  va_start (arg_ptr, cmd);
618  err = _gcry_vcontrol (cmd, arg_ptr);
619  va_end(arg_ptr);
620  return err;
621}
622
623
624
625/* Return a pointer to a string containing a description of the error
626   code in the error value ERR.  */
627const char *
628gcry_strerror (gcry_error_t err)
629{
630  return gpg_strerror (err);
631}
632
633/* Return a pointer to a string containing a description of the error
634   source in the error value ERR.  */
635const char *
636gcry_strsource (gcry_error_t err)
637{
638  return gpg_strsource (err);
639}
640
641/* Retrieve the error code for the system error ERR.  This returns
642   GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped (report
643   this).  */
644gcry_err_code_t
645gcry_err_code_from_errno (int err)
646{
647  return gpg_err_code_from_errno (err);
648}
649
650
651/* Retrieve the system error for the error code CODE.  This returns 0
652   if CODE is not a system error code.  */
653int
654gcry_err_code_to_errno (gcry_err_code_t code)
655{
656  return gpg_err_code_from_errno (code);
657}
658
659
660/* Return an error value with the error source SOURCE and the system
661   error ERR.  */
662gcry_error_t
663gcry_err_make_from_errno (gpg_err_source_t source, int err)
664{
665  return gpg_err_make_from_errno (source, err);
666}
667
668
669/* Return an error value with the system error ERR.  */
670gcry_err_code_t
671gcry_error_from_errno (int err)
672{
673  return gcry_error (gpg_err_code_from_errno (err));
674}
675
676
677/* Set custom allocation handlers.  This is in general not useful
678 * because the libgcrypt allocation functions are guaranteed to
679 * provide proper allocation handlers which zeroize memory if needed.
680 * NOTE: All 5 functions should be set.  */
681void
682gcry_set_allocation_handler (gcry_handler_alloc_t new_alloc_func,
683			     gcry_handler_alloc_t new_alloc_secure_func,
684			     gcry_handler_secure_check_t new_is_secure_func,
685			     gcry_handler_realloc_t new_realloc_func,
686			     gcry_handler_free_t new_free_func)
687{
688  global_init ();
689
690  if (fips_mode ())
691    {
692      /* We do not want to enforce the fips mode, but merely set a
693         flag so that the application may check whether it is still in
694         fips mode.  */
695      _gcry_inactivate_fips_mode ("custom allocation handler");
696    }
697
698  alloc_func = new_alloc_func;
699  alloc_secure_func = new_alloc_secure_func;
700  is_secure_func = new_is_secure_func;
701  realloc_func = new_realloc_func;
702  free_func = new_free_func;
703}
704
705
706
707/****************
708 * Set an optional handler which is called in case the xmalloc functions
709 * ran out of memory.  This handler may do one of these things:
710 *   o free some memory and return true, so that the xmalloc function
711 *     tries again.
712 *   o Do whatever it like and return false, so that the xmalloc functions
713 *     use the default fatal error handler.
714 *   o Terminate the program and don't return.
715 *
716 * The handler function is called with 3 arguments:  The opaque value set with
717 * this function, the requested memory size, and a flag with these bits
718 * currently defined:
719 *	bit 0 set = secure memory has been requested.
720 */
721void
722gcry_set_outofcore_handler( int (*f)( void*, size_t, unsigned int ),
723							void *value )
724{
725  global_init ();
726
727  if (fips_mode () )
728    {
729      log_info ("out of core handler ignored in FIPS mode\n");
730      return;
731    }
732
733  outofcore_handler = f;
734  outofcore_handler_value = value;
735}
736
737/* Return the no_secure_memory flag.  */
738static int
739get_no_secure_memory (void)
740{
741  if (!no_secure_memory)
742    return 0;
743  if (_gcry_enforced_fips_mode ())
744    {
745      no_secure_memory = 0;
746      return 0;
747    }
748  return no_secure_memory;
749}
750
751
752static gcry_err_code_t
753do_malloc (size_t n, unsigned int flags, void **mem)
754{
755  gcry_err_code_t err = 0;
756  void *m;
757
758  if ((flags & GCRY_ALLOC_FLAG_SECURE) && !get_no_secure_memory ())
759    {
760      if (alloc_secure_func)
761	m = (*alloc_secure_func) (n);
762      else
763	m = _gcry_private_malloc_secure (n);
764    }
765  else
766    {
767      if (alloc_func)
768	m = (*alloc_func) (n);
769      else
770	m = _gcry_private_malloc (n);
771    }
772
773  if (!m)
774    {
775      /* Make sure that ERRNO has been set in case a user supplied
776         memory handler didn't it correctly. */
777      if (!errno)
778        gpg_err_set_errno (ENOMEM);
779      err = gpg_err_code_from_errno (errno);
780    }
781  else
782    *mem = m;
783
784  return err;
785}
786
787void *
788gcry_malloc (size_t n)
789{
790  void *mem = NULL;
791
792  do_malloc (n, 0, &mem);
793
794  return mem;
795}
796
797void *
798gcry_malloc_secure (size_t n)
799{
800  void *mem = NULL;
801
802  do_malloc (n, GCRY_ALLOC_FLAG_SECURE, &mem);
803
804  return mem;
805}
806
807int
808gcry_is_secure (const void *a)
809{
810  if (get_no_secure_memory ())
811    return 0;
812  if (is_secure_func)
813    return is_secure_func (a) ;
814  return _gcry_private_is_secure (a);
815}
816
817void
818_gcry_check_heap( const void *a )
819{
820  (void)a;
821
822    /* FIXME: implement this*/
823#if 0
824    if( some_handler )
825	some_handler(a)
826    else
827	_gcry_private_check_heap(a)
828#endif
829}
830
831void *
832gcry_realloc (void *a, size_t n)
833{
834  void *p;
835
836  /* To avoid problems with non-standard realloc implementations and
837     our own secmem_realloc, we divert to malloc and free here.  */
838  if (!a)
839    return gcry_malloc (n);
840  if (!n)
841    {
842      gcry_free (a);
843      return NULL;
844    }
845
846  if (realloc_func)
847    p = realloc_func (a, n);
848  else
849    p =  _gcry_private_realloc (a, n);
850  if (!p && !errno)
851    gpg_err_set_errno (ENOMEM);
852  return p;
853}
854
855void
856gcry_free (void *p)
857{
858  int save_errno;
859
860  if (!p)
861    return;
862
863  /* In case ERRNO is set we better save it so that the free machinery
864     may not accidently change ERRNO.  We restore it only if it was
865     already set to comply with the usual C semantic for ERRNO.  */
866  save_errno = errno;
867  if (free_func)
868    free_func (p);
869  else
870    _gcry_private_free (p);
871
872  if (save_errno)
873    gpg_err_set_errno (save_errno);
874}
875
876void *
877gcry_calloc (size_t n, size_t m)
878{
879  size_t bytes;
880  void *p;
881
882  bytes = n * m; /* size_t is unsigned so the behavior on overflow is
883                    defined. */
884  if (m && bytes / m != n)
885    {
886      gpg_err_set_errno (ENOMEM);
887      return NULL;
888    }
889
890  p = gcry_malloc (bytes);
891  if (p)
892    memset (p, 0, bytes);
893  return p;
894}
895
896void *
897gcry_calloc_secure (size_t n, size_t m)
898{
899  size_t bytes;
900  void *p;
901
902  bytes = n * m; /* size_t is unsigned so the behavior on overflow is
903                    defined. */
904  if (m && bytes / m != n)
905    {
906      gpg_err_set_errno (ENOMEM);
907      return NULL;
908    }
909
910  p = gcry_malloc_secure (bytes);
911  if (p)
912    memset (p, 0, bytes);
913  return p;
914}
915
916
917/* Create and return a copy of the null-terminated string STRING.  If
918   it is contained in secure memory, the copy will be contained in
919   secure memory as well.  In an out-of-memory condition, NULL is
920   returned.  */
921char *
922gcry_strdup (const char *string)
923{
924  char *string_cp = NULL;
925  size_t string_n = 0;
926
927  string_n = strlen (string);
928
929  if (gcry_is_secure (string))
930    string_cp = gcry_malloc_secure (string_n + 1);
931  else
932    string_cp = gcry_malloc (string_n + 1);
933
934  if (string_cp)
935    strcpy (string_cp, string);
936
937  return string_cp;
938}
939
940
941void *
942gcry_xmalloc( size_t n )
943{
944  void *p;
945
946  while ( !(p = gcry_malloc( n )) )
947    {
948      if ( fips_mode ()
949           || !outofcore_handler
950           || !outofcore_handler (outofcore_handler_value, n, 0) )
951        {
952          _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL);
953        }
954    }
955    return p;
956}
957
958void *
959gcry_xrealloc( void *a, size_t n )
960{
961  void *p;
962
963  while ( !(p = gcry_realloc( a, n )) )
964    {
965      if ( fips_mode ()
966           || !outofcore_handler
967           || !outofcore_handler (outofcore_handler_value, n,
968                                   gcry_is_secure(a)? 3:2 ) )
969        {
970          _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL );
971	}
972    }
973    return p;
974}
975
976void *
977gcry_xmalloc_secure( size_t n )
978{
979  void *p;
980
981  while ( !(p = gcry_malloc_secure( n )) )
982    {
983      if ( fips_mode ()
984           || !outofcore_handler
985           || !outofcore_handler (outofcore_handler_value, n, 1) )
986        {
987          _gcry_fatal_error (gpg_err_code_from_errno (errno),
988                             _("out of core in secure memory"));
989	}
990    }
991  return p;
992}
993
994
995void *
996gcry_xcalloc( size_t n, size_t m )
997{
998  size_t nbytes;
999  void *p;
1000
1001  nbytes = n * m;
1002  if (m && nbytes / m != n)
1003    {
1004      gpg_err_set_errno (ENOMEM);
1005      _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL );
1006    }
1007
1008  p = gcry_xmalloc ( nbytes );
1009  memset ( p, 0, nbytes );
1010  return p;
1011}
1012
1013void *
1014gcry_xcalloc_secure( size_t n, size_t m )
1015{
1016  size_t nbytes;
1017  void *p;
1018
1019  nbytes = n * m;
1020  if (m && nbytes / m != n)
1021    {
1022      gpg_err_set_errno (ENOMEM);
1023      _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL );
1024    }
1025
1026  p = gcry_xmalloc_secure ( nbytes );
1027  memset ( p, 0, nbytes );
1028  return p;
1029}
1030
1031char *
1032gcry_xstrdup (const char *string)
1033{
1034  char *p;
1035
1036  while ( !(p = gcry_strdup (string)) )
1037    {
1038      size_t n = strlen (string);
1039      int is_sec = !!gcry_is_secure (string);
1040
1041      if (fips_mode ()
1042          || !outofcore_handler
1043          || !outofcore_handler (outofcore_handler_value, n, is_sec) )
1044        {
1045          _gcry_fatal_error (gpg_err_code_from_errno (errno),
1046                             is_sec? _("out of core in secure memory"):NULL);
1047	}
1048    }
1049
1050  return p;
1051}
1052
1053
1054int
1055_gcry_get_debug_flag (unsigned int mask)
1056{
1057  if ( fips_mode () )
1058    return 0;
1059  return (debug_flags & mask);
1060}
1061
1062
1063
1064/* It is often useful to get some feedback of long running operations.
1065   This function may be used to register a handler for this.
1066   The callback function CB is used as:
1067
1068   void cb (void *opaque, const char *what, int printchar,
1069           int current, int total);
1070
1071   Where WHAT is a string identifying the the type of the progress
1072   output, PRINTCHAR the character usually printed, CURRENT the amount
1073   of progress currently done and TOTAL the expected amount of
1074   progress.  A value of 0 for TOTAL indicates that there is no
1075   estimation available.
1076
1077   Defined values for WHAT:
1078
1079   "need_entropy"  X    0  number-of-bytes-required
1080            When running low on entropy
1081   "primegen"      '\n'  0 0
1082           Prime generated
1083                   '!'
1084           Need to refresh the prime pool
1085                   '<','>'
1086           Number of bits adjusted
1087                   '^'
1088           Looking for a generator
1089                   '.'
1090           Fermat tests on 10 candidates failed
1091                  ':'
1092           Restart with a new random value
1093                  '+'
1094           Rabin Miller test passed
1095   "pk_elg"        '+','-','.','\n'   0  0
1096            Only used in debugging mode.
1097   "pk_dsa"
1098            Only used in debugging mode.
1099*/
1100void
1101gcry_set_progress_handler (void (*cb)(void *,const char*,int, int, int),
1102                           void *cb_data)
1103{
1104#if USE_DSA
1105  _gcry_register_pk_dsa_progress (cb, cb_data);
1106#endif
1107#if USE_ELGAMAL
1108  _gcry_register_pk_elg_progress (cb, cb_data);
1109#endif
1110  _gcry_register_primegen_progress (cb, cb_data);
1111  _gcry_register_random_progress (cb, cb_data);
1112}
1113