curl_get_line.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <[email protected]>, 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. #if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \
  26. !defined(CURL_DISABLE_HSTS) || !defined(CURL_DISABLE_NETRC)
  27. #include "curl_get_line.h"
  28. #include "curl_memory.h"
  29. /* The last #include file should be: */
  30. #include "memdebug.h"
  31. static int appendnl(struct dynbuf *buf)
  32. {
  33. CURLcode result = curlx_dyn_addn(buf, "\n", 1);
  34. if(result)
  35. /* too long line or out of memory */
  36. return 0; /* error */
  37. return 1; /* all good */
  38. }
  39. /*
  40. * Curl_get_line() makes sure to only return complete whole lines that end
  41. * newlines.
  42. */
  43. int Curl_get_line(struct dynbuf *buf, FILE *input)
  44. {
  45. CURLcode result;
  46. char buffer[128];
  47. curlx_dyn_reset(buf);
  48. while(1) {
  49. char *b = fgets(buffer, sizeof(buffer), input);
  50. size_t rlen;
  51. if(b) {
  52. rlen = strlen(b);
  53. if(!rlen)
  54. break;
  55. result = curlx_dyn_addn(buf, b, rlen);
  56. if(result)
  57. /* too long line or out of memory */
  58. return 0; /* error */
  59. else if(b[rlen-1] == '\n')
  60. /* end of the line */
  61. return 1; /* all good */
  62. else if(feof(input))
  63. /* append a newline */
  64. return appendnl(buf);
  65. }
  66. else {
  67. rlen = curlx_dyn_len(buf);
  68. if(rlen) {
  69. b = curlx_dyn_ptr(buf);
  70. if(b[rlen-1] != '\n')
  71. /* append a newline */
  72. return appendnl(buf);
  73. return 1; /* all good */
  74. }
  75. else
  76. break;
  77. }
  78. }
  79. return 0;
  80. }
  81. #endif /* if not disabled */