tor  0.4.2.1-alpha-dev
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 #ifdef HAVE_SYS_TYPES_H
21 #include <sys/types.h>
22 #endif
23 
24 #include "lib/fdio/fdio.h"
25 #include "lib/cc/torint.h"
26 #include "lib/err/torerr.h"
27 
28 #include <stdlib.h>
29 #include <stdio.h>
30 
34 #ifndef SEEK_SET
35 #define SEEK_SET 0
36 #endif
37 #ifndef SEEK_CUR
38 #define SEEK_CUR 1
39 #endif
40 #ifndef SEEK_END
41 #define SEEK_END 2
42 #endif
43 
46 off_t
48 {
49 #ifdef _WIN32
50  return (off_t) _lseek(fd, 0, SEEK_CUR);
51 #else
52  return (off_t) lseek(fd, 0, SEEK_CUR);
53 #endif
54 }
55 
59 int
61 {
62 #ifdef _WIN32
63  return _lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
64 #else
65  off_t rc = lseek(fd, 0, SEEK_END) < 0 ? -1 : 0;
66 #ifdef ESPIPE
67  /* If we get an error and ESPIPE, then it's a pipe or a socket of a fifo:
68  * no need to worry. */
69  if (rc < 0 && errno == ESPIPE)
70  rc = 0;
71 #endif /* defined(ESPIPE) */
72  return (rc < 0) ? -1 : 0;
73 #endif /* defined(_WIN32) */
74 }
75 
78 int
79 tor_fd_setpos(int fd, off_t pos)
80 {
81 #ifdef _WIN32
82  return _lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
83 #else
84  return lseek(fd, pos, SEEK_SET) < 0 ? -1 : 0;
85 #endif
86 }
87 
90 int
92 {
93  /* Rumor has it that some versions of ftruncate do not move the file pointer.
94  */
95  if (tor_fd_setpos(fd, 0) < 0)
96  return -1;
97 
98 #ifdef _WIN32
99  return _chsize(fd, 0);
100 #else
101  return ftruncate(fd, 0);
102 #endif
103 }
104 
106 int
107 write_all_to_fd_minimal(int fd, const char *buf, size_t count)
108 {
109  size_t written = 0;
110  raw_assert(count < SSIZE_MAX);
111 
112  while (written < count) {
113  ssize_t result = write(fd, buf+written, count-written);
114  if (result<0)
115  return -1;
116  written += result;
117  }
118  return 0;
119 }
#define SEEK_SET
Definition: fdio.c:35
int write_all_to_fd_minimal(int fd, const char *buf, size_t count)
Definition: fdio.c:107
int tor_fd_setpos(int fd, off_t pos)
Definition: fdio.c:79
int tor_fd_seekend(int fd)
Definition: fdio.c:60
Header for fdio.c.
off_t tor_fd_getpos(int fd)
Definition: fdio.c:47
Integer definitions used throughout Tor.
int tor_ftruncate(int fd)
Definition: fdio.c:91
Headers for torerr.c.