1
2/*
3 * Copyright (C) Igor Sysoev
4 * Copyright (C) Nginx, Inc.
5 */
6
7
8#include <ngx_config.h>
9#include <ngx_core.h>
10
11
12/*
13 * Solaris has thread-safe crypt()
14 * Linux has crypt_r(); "struct crypt_data" is more than 128K
15 * FreeBSD needs the mutex to protect crypt()
16 *
17 * TODO:
18 *     ngx_crypt_init() to init mutex
19 */
20
21
22#if (NGX_CRYPT)
23
24#if (NGX_HAVE_GNU_CRYPT_R)
25
26ngx_int_t
27ngx_libc_crypt(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
28{
29    char               *value;
30    size_t              len;
31    struct crypt_data   cd;
32
33    cd.initialized = 0;
34#ifdef __GLIBC__
35    /* work around the glibc bug */
36    cd.current_salt[0] = ~salt[0];
37#endif
38
39    value = crypt_r((char *) key, (char *) salt, &cd);
40
41    if (value) {
42        len = ngx_strlen(value) + 1;
43
44        *encrypted = ngx_pnalloc(pool, len);
45        if (*encrypted == NULL) {
46            return NGX_ERROR;
47        }
48
49        ngx_memcpy(*encrypted, value, len);
50        return NGX_OK;
51    }
52
53    ngx_log_error(NGX_LOG_CRIT, pool->log, ngx_errno, "crypt_r() failed");
54
55    return NGX_ERROR;
56}
57
58#else
59
60ngx_int_t
61ngx_libc_crypt(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
62{
63    char       *value;
64    size_t      len;
65    ngx_err_t   err;
66
67    value = crypt((char *) key, (char *) salt);
68
69    if (value) {
70        len = ngx_strlen(value) + 1;
71
72        *encrypted = ngx_pnalloc(pool, len);
73        if (*encrypted == NULL) {
74            return NGX_ERROR;
75        }
76
77        ngx_memcpy(*encrypted, value, len);
78        return NGX_OK;
79    }
80
81    err = ngx_errno;
82
83    ngx_log_error(NGX_LOG_CRIT, pool->log, err, "crypt() failed");
84
85    return NGX_ERROR;
86}
87
88#endif
89
90#endif /* NGX_CRYPT */
91