1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24
25#include "curl_setup.h"
26
27#include <curl/curl.h>
28#include "curl_memory.h"
29
30#include "memdebug.h"
31
32static char *GetEnv(const char *variable)
33{
34#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_APP)
35 (void)variable;
36 return NULL;
37#elif defined(WIN32)
38 /* This uses Windows API instead of C runtime getenv() to get the environment
39 variable since some changes aren't always visible to the latter. #4774 */
40 char *buf = NULL;
41 char *tmp;
42 DWORD bufsize;
43 DWORD rc = 1;
44 const DWORD max = 32768; /* max env var size from MSCRT source */
45
46 for(;;) {
47 tmp = realloc(buf, rc);
48 if(!tmp) {
49 free(buf);
50 return NULL;
51 }
52
53 buf = tmp;
54 bufsize = rc;
55
56 /* It's possible for rc to be 0 if the variable was found but empty.
57 Since getenv doesn't make that distinction we ignore it as well. */
58 rc = GetEnvironmentVariableA(variable, buf, bufsize);
59 if(!rc || rc == bufsize || rc > max) {
60 free(buf);
61 return NULL;
62 }
63
64 /* if rc < bufsize then rc is bytes written not including null */
65 if(rc < bufsize)
66 return buf;
67
68 /* else rc is bytes needed, try again */
69 }
70#else
71 char *env = getenv(name: variable);
72 return (env && env[0])?strdup(env):NULL;
73#endif
74}
75
76char *curl_getenv(const char *v)
77{
78 return GetEnv(variable: v);
79}
80