getenv.c 2.2 KB

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