tor  0.4.0.1-alpha
fdio.c
Go to the documentation of this file.
1 /* Copyright (c) 2003-2004, Roger Dingledine
2  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3  * Copyright (c) 2007-2019, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 
12 #include "orconfig.h"
13 
14 #ifdef HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17 #ifdef _WIN32
18 #include <windows.h>
19 #endif
20 
21 #include "lib/fdio/fdio.h"
22 #include "lib/cc/torint.h"
23 #include "lib/err/torerr.h"
24 
25 #include <stdlib.h>
26 
30 #ifndef SEEK_SET
31 #define SEEK_SET 0
32 #endif
33 #ifndef SEEK_CUR
34 #define SEEK_CUR 1
35 #endif
36 #ifndef SEEK_END
37 #define SEEK_END 2
38 #endif
39 
42 off_t
44 {
45 #ifdef _WIN32
46  return (off_t) _lseek(fd, 0, SEEK_CUR);
47 #else
48  return (off_t) lseek(fd, 0, SEEK_CUR);
49 #endif
50 }
51 
55 int
57 {
58 #ifdef _WIN32
59  return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
60 #else
61  off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
62 #ifdef ESPIPE
63  /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
64  * no need to worry. */
65  if (rc < 0 && errno == ESPIPE)
66  rc = 0;
67 #endif /* defined(ESPIPE) */
68  return (rc < 0) ? -1 : 0;
69 #endif /* defined(_WIN32) */
70 }
71 
74 int
75 tor_fd_setpos(int fd, off_t pos)
76 {
77 #ifdef _WIN32
78  return _lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
79 #else
80  return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
81 #endif
82 }
83 
86 int
88 {
89  /* Rumor has it that some versions of ftruncate do not move the file pointer.
90  */
91  if (tor_fd_setpos(fd, 0) < 0)
92  return -1;
93 
94 #ifdef _WIN32
95  return _chsize(fd, 0);
96 #else
97  return ftruncate(fd, 0);
98 #endif
99 }
100 
102 int
103 write_all_to_fd_minimal(int fd, const char *buf, size_t count)
104 {
105  size_t written = 0;
106  raw_assert(count < SSIZE_MAX);
107 
108  while (written < count) {
109  ssize_t result = write(fd, buf+written, count-written);
110  if (result<0)
111  return -1;
112  written += result;
113  }
114  return 0;
115 }
#define SEEK_SET
Definition: fdio.c:31
int write_all_to_fd_minimal(int fd, const char *buf, size_t count)
Definition: fdio.c:103
int tor_fd_setpos(int fd, off_t pos)
Definition: fdio.c:75
int tor_fd_seekend(int fd)
Definition: fdio.c:56
Header for fdio.c.
off_t tor_fd_getpos(int fd)
Definition: fdio.c:43
Integer definitions used throughout Tor.
int tor_ftruncate(int fd)
Definition: fdio.c:87
Headers for torerr.c.