zip_fdopen.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. zip_fdopen.c -- open read-only archive from file descriptor
  3. Copyright (C) 2009-2010 Dieter Baron and Thomas Klausner
  4. This file is part of libzip, a library to manipulate ZIP archives.
  5. The authors can be contacted at <[email protected]>
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions
  8. are met:
  9. 1. Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. 2. Redistributions in binary form must reproduce the above copyright
  12. notice, this list of conditions and the following disclaimer in
  13. the documentation and/or other materials provided with the
  14. distribution.
  15. 3. The names of the authors may not be used to endorse or promote
  16. products derived from this software without specific prior
  17. written permission.
  18. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
  19. OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  22. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  24. GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  25. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  26. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  27. OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  28. IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include "zipint.h"
  31. ZIP_EXTERN struct zip *
  32. zip_fdopen(int fd_orig, int _flags, int *zep)
  33. {
  34. int fd;
  35. FILE *fp;
  36. unsigned int flags;
  37. if (_flags < 0) {
  38. if (zep)
  39. *zep = ZIP_ER_INVAL;
  40. return NULL;
  41. }
  42. flags = (unsigned int)_flags;
  43. if (flags & ZIP_TRUNCATE) {
  44. *zep = ZIP_ER_INVAL;
  45. return NULL;
  46. }
  47. /* We dup() here to avoid messing with the passed in fd.
  48. We could not restore it to the original state in case of error. */
  49. if ((fd=dup(fd_orig)) < 0) {
  50. *zep = ZIP_ER_OPEN;
  51. return NULL;
  52. }
  53. if ((fp=fdopen(fd, "rb")) == NULL) {
  54. close(fd);
  55. *zep = ZIP_ER_OPEN;
  56. return NULL;
  57. }
  58. close(fd_orig);
  59. return _zip_open(NULL, fp, flags, zep);
  60. }