filestr.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Part of Very Secure FTPd
  3. * Licence: GPL v2
  4. * Author: Chris Evans
  5. * filestr.c
  6. *
  7. * This file contains extensions to the string/buffer API, to load a file
  8. * into a buffer.
  9. */
  10. #include "filestr.h"
  11. /* Get access to "private" functions */
  12. #define VSFTP_STRING_HELPER
  13. #include "str.h"
  14. #include "sysutil.h"
  15. #include "secbuf.h"
  16. #include "utility.h"
  17. int
  18. str_fileread(struct mystr* p_str, const char* p_filename, unsigned int maxsize)
  19. {
  20. int fd;
  21. int retval = 0;
  22. filesize_t size;
  23. char* p_sec_buf = 0;
  24. struct vsf_sysutil_statbuf* p_stat = 0;
  25. /* In case we fail, make sure we return an empty string */
  26. str_empty(p_str);
  27. fd = vsf_sysutil_open_file(p_filename, kVSFSysUtilOpenReadOnly);
  28. if (vsf_sysutil_retval_is_error(fd))
  29. {
  30. return fd;
  31. }
  32. vsf_sysutil_fstat(fd, &p_stat);
  33. if (vsf_sysutil_statbuf_is_regfile(p_stat))
  34. {
  35. size = vsf_sysutil_statbuf_get_size(p_stat);
  36. if (size > maxsize)
  37. {
  38. size = maxsize;
  39. }
  40. vsf_secbuf_alloc(&p_sec_buf, (unsigned int) size);
  41. retval = vsf_sysutil_read_loop(fd, p_sec_buf, (unsigned int) size);
  42. if (vsf_sysutil_retval_is_error(retval))
  43. {
  44. goto free_out;
  45. }
  46. else if ((unsigned int) retval != size)
  47. {
  48. die("read size mismatch");
  49. }
  50. str_alloc_memchunk(p_str, p_sec_buf, (unsigned int) size);
  51. }
  52. free_out:
  53. vsf_sysutil_free(p_stat);
  54. vsf_secbuf_free(&p_sec_buf);
  55. vsf_sysutil_close(fd);
  56. return retval;
  57. }