hfile.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /* hfile.c -- buffered low-level input/output streams.
  2. Copyright (C) 2013-2014 Genome Research Ltd.
  3. Author: John Marshall <jm18@sanger.ac.uk>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notices and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  15. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  17. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  18. DEALINGS IN THE SOFTWARE. */
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <errno.h>
  23. #include "htslib/hfile.h"
  24. #include "hfile_internal.h"
  25. /* hFILE fields are used as follows:
  26. char *buffer; // Pointer to the start of the I/O buffer
  27. char *begin; // First not-yet-read character / unused position
  28. char *end; // First unfilled/unfillable position
  29. char *limit; // Pointer to the first position past the buffer
  30. const hFILE_backend *backend; // Methods to refill/flush I/O buffer
  31. off_t offset; // Offset within the stream of buffer position 0
  32. int at_eof:1; // For reading, whether EOF has been seen
  33. int has_errno; // Error number from the last failure on this stream
  34. For reading, begin is the first unread character in the buffer and end is the
  35. first unfilled position:
  36. -----------ABCDEFGHIJKLMNO---------------
  37. ^buffer ^begin ^end ^limit
  38. For writing, begin is the first unused position and end is unused so remains
  39. equal to buffer:
  40. ABCDEFGHIJKLMNOPQRSTUVWXYZ---------------
  41. ^buffer ^begin ^limit
  42. ^end
  43. Thus if begin > end then there is a non-empty write buffer, if begin < end
  44. then there is a non-empty read buffer, and if begin == end then both buffers
  45. are empty. In all cases, the stream's file position indicator corresponds
  46. to the position pointed to by begin. */
  47. hFILE *hfile_init(size_t struct_size, const char *mode, size_t capacity)
  48. {
  49. hFILE *fp = (hFILE *) malloc(struct_size);
  50. if (fp == NULL) goto error;
  51. if (capacity == 0) capacity = 32768;
  52. // FIXME For now, clamp input buffer sizes so mpileup doesn't eat memory
  53. if (strchr(mode, 'r') && capacity > 32768) capacity = 32768;
  54. fp->buffer = (char *) malloc(capacity);
  55. if (fp->buffer == NULL) goto error;
  56. fp->begin = fp->end = fp->buffer;
  57. fp->limit = &fp->buffer[capacity];
  58. fp->offset = 0;
  59. fp->at_eof = 0;
  60. fp->has_errno = 0;
  61. return fp;
  62. error:
  63. hfile_destroy(fp);
  64. return NULL;
  65. }
  66. void hfile_destroy(hFILE *fp)
  67. {
  68. int save = errno;
  69. if (fp) free(fp->buffer);
  70. free(fp);
  71. errno = save;
  72. }
  73. static inline int writebuffer_is_nonempty(hFILE *fp)
  74. {
  75. return fp->begin > fp->end;
  76. }
  77. /* Refills the read buffer from the backend (once, so may only partially
  78. fill the buffer), returning the number of additional characters read
  79. (which might be 0), or negative when an error occurred. */
  80. static ssize_t refill_buffer(hFILE *fp)
  81. {
  82. ssize_t n;
  83. // Move any unread characters to the start of the buffer
  84. if (fp->begin > fp->buffer) {
  85. fp->offset += fp->begin - fp->buffer;
  86. memmove(fp->buffer, fp->begin, fp->end - fp->begin);
  87. fp->end = &fp->buffer[fp->end - fp->begin];
  88. fp->begin = fp->buffer;
  89. }
  90. // Read into the available buffer space at fp->[end,limit)
  91. if (fp->at_eof || fp->end == fp->limit) n = 0;
  92. else {
  93. n = fp->backend->read(fp, fp->end, fp->limit - fp->end);
  94. if (n < 0) { fp->has_errno = errno; return n; }
  95. else if (n == 0) fp->at_eof = 1;
  96. }
  97. fp->end += n;
  98. return n;
  99. }
  100. /* Called only from hgetc(), when our buffer is empty. */
  101. int hgetc2(hFILE *fp)
  102. {
  103. return (refill_buffer(fp) > 0)? (unsigned char) *(fp->begin++) : EOF;
  104. }
  105. ssize_t hpeek(hFILE *fp, void *buffer, size_t nbytes)
  106. {
  107. size_t n = fp->end - fp->begin;
  108. while (n < nbytes) {
  109. ssize_t ret = refill_buffer(fp);
  110. if (ret < 0) return ret;
  111. else if (ret == 0) break;
  112. else n += ret;
  113. }
  114. if (n > nbytes) n = nbytes;
  115. memcpy(buffer, fp->begin, n);
  116. return n;
  117. }
  118. /* Called only from hread(); when called, our buffer is empty and nread bytes
  119. have already been placed in the destination buffer. */
  120. ssize_t hread2(hFILE *fp, void *destv, size_t nbytes, size_t nread)
  121. {
  122. const size_t capacity = fp->limit - fp->buffer;
  123. char *dest = (char *) destv;
  124. dest += nread, nbytes -= nread;
  125. // Read large requests directly into the destination buffer
  126. while (nbytes * 2 >= capacity && !fp->at_eof) {
  127. ssize_t n = fp->backend->read(fp, dest, nbytes);
  128. if (n < 0) { fp->has_errno = errno; return n; }
  129. else if (n == 0) fp->at_eof = 1;
  130. fp->offset += n;
  131. dest += n, nbytes -= n;
  132. nread += n;
  133. }
  134. while (nbytes > 0 && !fp->at_eof) {
  135. size_t n;
  136. ssize_t ret = refill_buffer(fp);
  137. if (ret < 0) return ret;
  138. n = fp->end - fp->begin;
  139. if (n > nbytes) n = nbytes;
  140. memcpy(dest, fp->begin, n);
  141. fp->begin += n;
  142. dest += n, nbytes -= n;
  143. nread += n;
  144. }
  145. return nread;
  146. }
  147. /* Flushes the write buffer, fp->[buffer,begin), out through the backend
  148. returning 0 on success or negative if an error occurred. */
  149. static ssize_t flush_buffer(hFILE *fp)
  150. {
  151. const char *buffer = fp->buffer;
  152. while (buffer < fp->begin) {
  153. ssize_t n = fp->backend->write(fp, buffer, fp->begin - buffer);
  154. if (n < 0) { fp->has_errno = errno; return n; }
  155. buffer += n;
  156. fp->offset += n;
  157. }
  158. fp->begin = fp->buffer; // Leave the buffer empty
  159. return 0;
  160. }
  161. int hflush(hFILE *fp)
  162. {
  163. if (flush_buffer(fp) < 0) return EOF;
  164. if (fp->backend->flush(fp) < 0) { fp->has_errno = errno; return EOF; }
  165. return 0;
  166. }
  167. /* Called only from hputc(), when our buffer is already full. */
  168. int hputc2(int c, hFILE *fp)
  169. {
  170. if (flush_buffer(fp) < 0) return EOF;
  171. *(fp->begin++) = c;
  172. return c;
  173. }
  174. /* Called only from hwrite() and hputs2(); when called, our buffer is full and
  175. ncopied bytes from the source have already been copied to our buffer. */
  176. ssize_t hwrite2(hFILE *fp, const void *srcv, size_t totalbytes, size_t ncopied)
  177. {
  178. const char *src = (const char *) srcv;
  179. ssize_t ret;
  180. const size_t capacity = fp->limit - fp->buffer;
  181. size_t remaining = totalbytes - ncopied;
  182. src += ncopied;
  183. ret = flush_buffer(fp);
  184. if (ret < 0) return ret;
  185. // Write large blocks out directly from the source buffer
  186. while (remaining * 2 >= capacity) {
  187. ssize_t n = fp->backend->write(fp, src, remaining);
  188. if (n < 0) { fp->has_errno = errno; return n; }
  189. fp->offset += n;
  190. src += n, remaining -= n;
  191. }
  192. // Just buffer any remaining characters
  193. memcpy(fp->begin, src, remaining);
  194. fp->begin += remaining;
  195. return totalbytes;
  196. }
  197. /* Called only from hputs(), when our buffer is already full. */
  198. int hputs2(const char *text, size_t totalbytes, size_t ncopied, hFILE *fp)
  199. {
  200. return (hwrite2(fp, text, totalbytes, ncopied) >= 0)? 0 : EOF;
  201. }
  202. off_t hseek(hFILE *fp, off_t offset, int whence)
  203. {
  204. off_t pos;
  205. if (writebuffer_is_nonempty(fp)) {
  206. int ret = flush_buffer(fp);
  207. if (ret < 0) return ret;
  208. }
  209. pos = fp->backend->seek(fp, offset, whence);
  210. if (pos < 0) { fp->has_errno = errno; return pos; }
  211. // Seeking succeeded, so discard any non-empty read buffer
  212. fp->begin = fp->end = fp->buffer;
  213. fp->at_eof = 0;
  214. fp->offset = pos;
  215. return pos;
  216. }
  217. int hclose(hFILE *fp)
  218. {
  219. int err = fp->has_errno;
  220. if (writebuffer_is_nonempty(fp) && hflush(fp) < 0) err = fp->has_errno;
  221. if (fp->backend->close(fp) < 0) err = errno;
  222. hfile_destroy(fp);
  223. if (err) {
  224. errno = err;
  225. return EOF;
  226. }
  227. else return 0;
  228. }
  229. void hclose_abruptly(hFILE *fp)
  230. {
  231. int save = errno;
  232. if (fp->backend->close(fp) < 0) { /* Ignore subsequent errors */ }
  233. hfile_destroy(fp);
  234. errno = save;
  235. }
  236. /***************************
  237. * File descriptor backend *
  238. ***************************/
  239. #include <sys/socket.h>
  240. #include <sys/stat.h>
  241. #include <fcntl.h>
  242. #include <unistd.h>
  243. #ifdef _WIN32
  244. #define HAVE_CLOSESOCKET
  245. #endif
  246. /* For Unix, it doesn't matter whether a file descriptor is a socket.
  247. However Windows insists on send()/recv() and its own closesocket()
  248. being used when fd happens to be a socket. */
  249. typedef struct {
  250. hFILE base;
  251. int fd;
  252. int is_socket:1;
  253. } hFILE_fd;
  254. static ssize_t fd_read(hFILE *fpv, void *buffer, size_t nbytes)
  255. {
  256. hFILE_fd *fp = (hFILE_fd *) fpv;
  257. ssize_t n;
  258. do {
  259. n = fp->is_socket? recv(fp->fd, buffer, nbytes, 0)
  260. : read(fp->fd, buffer, nbytes);
  261. } while (n < 0 && errno == EINTR);
  262. return n;
  263. }
  264. static ssize_t fd_write(hFILE *fpv, const void *buffer, size_t nbytes)
  265. {
  266. hFILE_fd *fp = (hFILE_fd *) fpv;
  267. ssize_t n;
  268. do {
  269. n = fp->is_socket? send(fp->fd, buffer, nbytes, 0)
  270. : write(fp->fd, buffer, nbytes);
  271. } while (n < 0 && errno == EINTR);
  272. return n;
  273. }
  274. static off_t fd_seek(hFILE *fpv, off_t offset, int whence)
  275. {
  276. hFILE_fd *fp = (hFILE_fd *) fpv;
  277. return lseek(fp->fd, offset, whence);
  278. }
  279. static int fd_flush(hFILE *fpv)
  280. {
  281. hFILE_fd *fp = (hFILE_fd *) fpv;
  282. int ret;
  283. do {
  284. #ifdef HAVE_FDATASYNC
  285. ret = fdatasync(fp->fd);
  286. #else
  287. ret = fsync(fp->fd);
  288. #endif
  289. // Ignore invalid-for-fsync(2) errors due to being, e.g., a pipe,
  290. // and operation-not-supported errors (Mac OS X)
  291. if (ret < 0 && (errno == EINVAL || errno == ENOTSUP)) ret = 0;
  292. } while (ret < 0 && errno == EINTR);
  293. return ret;
  294. }
  295. static int fd_close(hFILE *fpv)
  296. {
  297. hFILE_fd *fp = (hFILE_fd *) fpv;
  298. int ret;
  299. do {
  300. #ifdef HAVE_CLOSESOCKET
  301. ret = fp->is_socket? closesocket(fp->fd) : close(fp->fd);
  302. #else
  303. ret = close(fp->fd);
  304. #endif
  305. } while (ret < 0 && errno == EINTR);
  306. return ret;
  307. }
  308. static const struct hFILE_backend fd_backend =
  309. {
  310. fd_read, fd_write, fd_seek, fd_flush, fd_close
  311. };
  312. static size_t blksize(int fd)
  313. {
  314. struct stat sbuf;
  315. if (fstat(fd, &sbuf) != 0) return 0;
  316. return sbuf.st_blksize;
  317. }
  318. static hFILE *hopen_fd(const char *filename, const char *mode)
  319. {
  320. hFILE_fd *fp = NULL;
  321. int fd = open(filename, hfile_oflags(mode), 0666);
  322. if (fd < 0) goto error;
  323. fp = (hFILE_fd *) hfile_init(sizeof (hFILE_fd), mode, blksize(fd));
  324. if (fp == NULL) goto error;
  325. fp->fd = fd;
  326. fp->is_socket = 0;
  327. fp->base.backend = &fd_backend;
  328. return &fp->base;
  329. error:
  330. if (fd >= 0) { int save = errno; (void) close(fd); errno = save; }
  331. hfile_destroy((hFILE *) fp);
  332. return NULL;
  333. }
  334. hFILE *hdopen(int fd, const char *mode)
  335. {
  336. hFILE_fd *fp = (hFILE_fd*) hfile_init(sizeof (hFILE_fd), mode, blksize(fd));
  337. if (fp == NULL) return NULL;
  338. fp->fd = fd;
  339. fp->is_socket = (strchr(mode, 's') != NULL);
  340. fp->base.backend = &fd_backend;
  341. return &fp->base;
  342. }
  343. static hFILE *hopen_fd_stdinout(const char *mode)
  344. {
  345. int fd = (strchr(mode, 'r') != NULL)? STDIN_FILENO : STDOUT_FILENO;
  346. // TODO Set binary mode (for Windows)
  347. return hdopen(fd, mode);
  348. }
  349. int hfile_oflags(const char *mode)
  350. {
  351. int rdwr = 0, flags = 0;
  352. const char *s;
  353. for (s = mode; *s; s++)
  354. switch (*s) {
  355. case 'r': rdwr = O_RDONLY; break;
  356. case 'w': rdwr = O_WRONLY; flags |= O_CREAT | O_TRUNC; break;
  357. case 'a': rdwr = O_WRONLY; flags |= O_CREAT | O_APPEND; break;
  358. case '+': rdwr = O_RDWR; break;
  359. default: break;
  360. }
  361. #ifdef O_BINARY
  362. flags |= O_BINARY;
  363. #endif
  364. return rdwr | flags;
  365. }
  366. /*********************
  367. * In-memory backend *
  368. *********************/
  369. typedef struct {
  370. hFILE base;
  371. const char *buffer;
  372. size_t length, pos;
  373. } hFILE_mem;
  374. static ssize_t mem_read(hFILE *fpv, void *buffer, size_t nbytes)
  375. {
  376. hFILE_mem *fp = (hFILE_mem *) fpv;
  377. size_t avail = fp->length - fp->pos;
  378. if (nbytes > avail) nbytes = avail;
  379. memcpy(buffer, fp->buffer + fp->pos, nbytes);
  380. fp->pos += nbytes;
  381. return nbytes;
  382. }
  383. static off_t mem_seek(hFILE *fpv, off_t offset, int whence)
  384. {
  385. hFILE_mem *fp = (hFILE_mem *) fpv;
  386. size_t absoffset = (offset >= 0)? offset : -offset;
  387. size_t origin;
  388. switch (whence) {
  389. case SEEK_SET: origin = 0; break;
  390. case SEEK_CUR: origin = fp->pos; break;
  391. case SEEK_END: origin = fp->length; break;
  392. default: errno = EINVAL; return -1;
  393. }
  394. if ((offset < 0 && absoffset > origin) ||
  395. (offset >= 0 && absoffset > fp->length - origin)) {
  396. errno = EINVAL;
  397. return -1;
  398. }
  399. fp->pos = origin + offset;
  400. return fp->pos;
  401. }
  402. static int mem_close(hFILE *fpv)
  403. {
  404. return 0;
  405. }
  406. static const struct hFILE_backend mem_backend =
  407. {
  408. mem_read, NULL, mem_seek, NULL, mem_close
  409. };
  410. static hFILE *hopen_mem(const char *data, const char *mode)
  411. {
  412. // TODO Implement write modes, which will require memory allocation
  413. if (strchr(mode, 'r') == NULL) { errno = EINVAL; return NULL; }
  414. hFILE_mem *fp = (hFILE_mem *) hfile_init(sizeof (hFILE_mem), mode, 0);
  415. if (fp == NULL) return NULL;
  416. fp->buffer = data;
  417. fp->length = strlen(data);
  418. fp->pos = 0;
  419. fp->base.backend = &mem_backend;
  420. return &fp->base;
  421. }
  422. /******************************
  423. * hopen() backend dispatcher *
  424. ******************************/
  425. hFILE *hopen(const char *fname, const char *mode)
  426. {
  427. if (strncmp(fname, "http://", 7) == 0 ||
  428. strncmp(fname, "ftp://", 6) == 0) return hopen_net(fname, mode);
  429. else if (strncmp(fname, "data:", 5) == 0) return hopen_mem(fname + 5, mode);
  430. else if (strcmp(fname, "-") == 0) return hopen_fd_stdinout(mode);
  431. else return hopen_fd(fname, mode);
  432. }