getenv.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #include "curl_setup.h"
  25. #include <curl/curl.h>
  26. #include "curl_memory.h"
  27. #include "memdebug.h"
  28. static char *GetEnv(const char *variable)
  29. {
  30. #if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) || \
  31. defined(__ORBIS__) || defined(__PROSPERO__) /* PlayStation 4 and 5 */
  32. (void)variable;
  33. return NULL;
  34. #elif defined(_WIN32)
  35. /* This uses Windows API instead of C runtime getenv() to get the environment
  36. variable since some changes are not always visible to the latter. #4774 */
  37. char *buf = NULL;
  38. char *tmp;
  39. DWORD bufsize;
  40. DWORD rc = 1;
  41. const DWORD max = 32768; /* max env var size from MSCRT source */
  42. for(;;) {
  43. tmp = realloc(buf, rc);
  44. if(!tmp) {
  45. free(buf);
  46. return NULL;
  47. }
  48. buf = tmp;
  49. bufsize = rc;
  50. /* it is possible for rc to be 0 if the variable was found but empty.
  51. Since getenv does not make that distinction we ignore it as well. */
  52. rc = GetEnvironmentVariableA(variable, buf, bufsize);
  53. if(!rc || rc == bufsize || rc > max) {
  54. free(buf);
  55. return NULL;
  56. }
  57. /* if rc < bufsize then rc is bytes written not including null */
  58. if(rc < bufsize)
  59. return buf;
  60. /* else rc is bytes needed, try again */
  61. }
  62. #else
  63. char *env = getenv(variable);
  64. return (env && env[0]) ? strdup(env) : NULL;
  65. #endif
  66. }
  67. char *curl_getenv(const char *v)
  68. {
  69. return GetEnv(v);
  70. }