getenv.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2022, 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_APP)
  31. (void)variable;
  32. return NULL;
  33. #elif defined(WIN32)
  34. /* This uses Windows API instead of C runtime getenv() to get the environment
  35. variable since some changes aren't always visible to the latter. #4774 */
  36. char *buf = NULL;
  37. char *tmp;
  38. DWORD bufsize;
  39. DWORD rc = 1;
  40. const DWORD max = 32768; /* max env var size from MSCRT source */
  41. for(;;) {
  42. tmp = realloc(buf, rc);
  43. if(!tmp) {
  44. free(buf);
  45. return NULL;
  46. }
  47. buf = tmp;
  48. bufsize = rc;
  49. /* It's possible for rc to be 0 if the variable was found but empty.
  50. Since getenv doesn't make that distinction we ignore it as well. */
  51. rc = GetEnvironmentVariableA(variable, buf, bufsize);
  52. if(!rc || rc == bufsize || rc > max) {
  53. free(buf);
  54. return NULL;
  55. }
  56. /* if rc < bufsize then rc is bytes written not including null */
  57. if(rc < bufsize)
  58. return buf;
  59. /* else rc is bytes needed, try again */
  60. }
  61. #else
  62. char *env = getenv(variable);
  63. return (env && env[0])?strdup(env):NULL;
  64. #endif
  65. }
  66. char *curl_getenv(const char *v)
  67. {
  68. return GetEnv(v);
  69. }