src/os/unix/ngx_user.c - nginx-1.7.10

Functions defined

Source code


  1. /*
  2. * Copyright (C) Igor Sysoev
  3. * Copyright (C) Nginx, Inc.
  4. */


  5. #include <ngx_config.h>
  6. #include <ngx_core.h>


  7. /*
  8. * Solaris has thread-safe crypt()
  9. * Linux has crypt_r(); "struct crypt_data" is more than 128K
  10. * FreeBSD needs the mutex to protect crypt()
  11. *
  12. * TODO:
  13. *     ngx_crypt_init() to init mutex
  14. */


  15. #if (NGX_CRYPT)

  16. #if (NGX_HAVE_GNU_CRYPT_R)

  17. ngx_int_t
  18. ngx_libc_crypt(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
  19. {
  20.     char               *value;
  21.     size_t              len;
  22.     struct crypt_data   cd;

  23.     cd.initialized = 0;
  24. #ifdef __GLIBC__
  25.     /* work around the glibc bug */
  26.     cd.current_salt[0] = ~salt[0];
  27. #endif

  28.     value = crypt_r((char *) key, (char *) salt, &cd);

  29.     if (value) {
  30.         len = ngx_strlen(value) + 1;

  31.         *encrypted = ngx_pnalloc(pool, len);
  32.         if (*encrypted == NULL) {
  33.             return NGX_ERROR;
  34.         }

  35.         ngx_memcpy(*encrypted, value, len);
  36.         return NGX_OK;
  37.     }

  38.     ngx_log_error(NGX_LOG_CRIT, pool->log, ngx_errno, "crypt_r() failed");

  39.     return NGX_ERROR;
  40. }

  41. #else

  42. ngx_int_t
  43. ngx_libc_crypt(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
  44. {
  45.     char       *value;
  46.     size_t      len;
  47.     ngx_err_t   err;

  48. #if (NGX_THREADS && NGX_NONREENTRANT_CRYPT)

  49.     /* crypt() is a time consuming function, so we only try to lock */

  50.     if (ngx_mutex_trylock(ngx_crypt_mutex) != NGX_OK) {
  51.         return NGX_AGAIN;
  52.     }

  53. #endif

  54.     value = crypt((char *) key, (char *) salt);

  55.     if (value) {
  56.         len = ngx_strlen(value) + 1;

  57.         *encrypted = ngx_pnalloc(pool, len);
  58.         if (*encrypted == NULL) {
  59. #if (NGX_THREADS && NGX_NONREENTRANT_CRYPT)
  60.             ngx_mutex_unlock(ngx_crypt_mutex);
  61. #endif
  62.             return NGX_ERROR;
  63.         }

  64.         ngx_memcpy(*encrypted, value, len);
  65. #if (NGX_THREADS && NGX_NONREENTRANT_CRYPT)
  66.         ngx_mutex_unlock(ngx_crypt_mutex);
  67. #endif
  68.         return NGX_OK;
  69.     }

  70.     err = ngx_errno;

  71. #if (NGX_THREADS && NGX_NONREENTRANT_CRYPT)
  72.     ngx_mutex_unlock(ngx_crypt_mutex);
  73. #endif

  74.     ngx_log_error(NGX_LOG_CRIT, pool->log, err, "crypt() failed");

  75.     return NGX_ERROR;
  76. }

  77. #endif

  78. #endif /* NGX_CRYPT */