Debian Codegraph @

src/tls/socket-io.c

raw
1 /*
2 * Copyright (C) 2019 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 #include "socket-io.h"
9
10 #include <assert.h>
11 #include <ctype.h>
12 #include <err.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <poll.h>
16 #include <stdarg.h>
17 #include <stdint.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <sys/socket.h>
21 #include <sys/un.h>
22
23 #include "utils.h"
24
25 static uint64_t
26 get_elapsed_time (struct timespec *start)
27 {
28 struct timespec now;
29 int r;
30
31 r = clock_gettime (CLOCK_MONOTONIC, &now);
32 assert (r == 0);
33
34 if (start->tv_sec == 0 && start->tv_nsec == 0)
35 *start = now;
36
37 int64_t elapsed = ((int64_t) now.tv_sec - start->tv_sec) * 1000000 +
38 ((int64_t) now.tv_nsec - start->tv_nsec) / 1000;
39
40 assert (elapsed >= 0);
41
42 return elapsed;
43 }
44
45 /**
46 * get_remaining_timeout:
47 * @start: a timespec struct, initially initialised to { 0, 0 }
48 * @timeout_remaining: out-value for timeout remaining, in microseconds
49 * @timeout_us: the total timeout value in microseconds
50 *
51 * Uses @start to keep track of how much time of an initial timeout is
52 * remaining.
53 *
54 * This is useful to keep track of multiple-syscall IO operations with
55 * one global timeout, in the presence of multiple read() or write()
56 * calls, poll(), and the possibility of EINTR.
57 *
58 * On the first call (when @start is filled with zeros), @start is
59 * initialised and @timeout_remaining will be set to the value of
60 * @timeout_us. On successive calls (which should usually have the same
61 * value of @timeout_us), smaller values will be returned in line with
62 * the passage of time, until there is no timeout remaining.
63 *
64 * Returns #true when there has been a non-negative value written into
65 * @timeout_remaining, and returns #false when the timeout has expired.
66 */
67 bool
68 get_remaining_timeout (struct timespec *start,
69 uint64_t *timeout_remaining,
70 uint64_t timeout_us)
71 {
72 uint64_t elapsed = get_elapsed_time (start);
73
74 debug (SOCKET_IO, " -> %lld of %lld elapsed", (long long) elapsed, (long long) timeout_us);
75
76 if (timeout_us < elapsed)
77 return false;
78
79 *timeout_remaining = timeout_us - elapsed;
80
81 return true;
82 }
83
84 /* Return true if IO on fd is pending, false on timeout */
85 static bool
86 wait_for_io (struct timespec *start,
87 int fd,
88 short events,
89 uint64_t timeout_us)
90 {
91 struct pollfd pfd = { .fd = fd, .events = events };
92 uint64_t remaining;
93 int r;
94
95 debug (SOCKET_IO, "wait_for_io(%d, %u, %ju):", fd, (unsigned) events, (uintmax_t) timeout_us);
96
97 if (!get_remaining_timeout (start, &remaining, timeout_us))
98 return false;
99
100 debug (SOCKET_IO, " -> waiting for %jd", (uintmax_t) remaining);
101
102 do
103 r = poll (&pfd, 1, (remaining + 999) / 1000);
104 while (r == -1 && errno == EINTR);
105
106 if (r < 0)
107 err (EXIT_FAILURE, "poll() failed");
108
109 debug (SOCKET_IO, " -> result is %d", r);
110
111 return r == 1;
112 }
113
114 /**
115 * recv_all:
116 * @fd: a file descriptor for a connected stream socket
117 * @buffer: a buffer
118 * @size: the size of @buffer
119 * @timeout: a timeout, in microseconds
120 *
121 * Attempts to read up to @size - 1 bytes from the connected stream
122 * socket @fd, followed by EOF. On success, a nul terminator is
123 * inserted after the last byte and the number of bytes read (which
124 * might be less than @size - 1) is returned, excluding the nul
125 * terminator. 0 is a valid result.
126 *
127 * On failure (socket errors, timeout, or simply too much data read
128 * without EOF), -1 is returned.
129 *
130 * This function is meant to be used with send_all() on the other side.
131 */
132 static ssize_t
133 recv_all (int fd,
134 char *buffer,
135 size_t size,
136 int timeout)
137 {
138 struct timespec start = { 0, 0 };
139 size_t count = 0;
140
141 debug (SOCKET_IO, "read_all(fd=%d, size=%zu, timeout=%d)", fd, size, timeout);
142
143 /* We need to see recv() return 0 in order to know that we have EOF.
144 * In order to see that 0, we need to call recv() with a non-empty
145 * buffer. Conveniently, we can use the byte at the end of the buffer
146 * that we will write the nul terminator byte into. Without this
147 * extra byte, we'd need to have a separate throwaway variable and a
148 * separately-coded function call.
149 */
150 while (count < size && wait_for_io (&start, fd, POLLIN, timeout))
151 {
152 ssize_t s = recv (fd, buffer + count, size - count, MSG_DONTWAIT);
153 debug (SOCKET_IO, " -> recv returned %zd/%m", s);
154
155 if (s == -1)
156 {
157 if (errno == EINTR || errno == EAGAIN)
158 continue;
159
160 warn ("recv_all() failed");
161 return -1;
162 }
163
164 if (s == 0)
165 {
166 /* EOF → success */
167 debug (SOCKET_IO, " -> successfully received %zu bytes and EOF.", count);
168 buffer[count] = '\0';
169 return count;
170 }
171
172 count += s;
173 }
174
175 /* either the buffer overflowed or we timed out */
176 if (count >= size)
177 warnx ("recv_all() failed: buffer is full and no EOF received");
178 else
179 warnx ("recv_all() failed: timeout; got %zu bytes, size == %zu", count, size);
180 return -1;
181 }
182
183 /**
184 * recv_alnum:
185 * @fd: a file descriptor for a connected stream socket
186 * @buffer: a buffer
187 * @size: the size of @buffer
188 * @timeout: a timeout, in microseconds
189 *
190 * Attempts to read a non-empty alphanumeric string up to @size - 1
191 * bytes from the connected stream socket @fd, followed by EOF. On
192 * success, a nul terminator is inserted after the last byte and true is
193 * returned. The empty string is not a valid result.
194 *
195 * On failure (socket errors, timeout, too much data read, no data read,
196 * or in case the data is not alphanumeric), false is returned.
197 */
198 bool
199 recv_alnum (int fd,
200 char *buffer,
201 size_t size,
202 int timeout)
203 {
204 ssize_t r;
205 size_t i;
206
207 r = recv_all (fd, buffer, size, timeout);
208
209 /* we need to have read at least one byte */
210 if (r < 1)
211 return false;
212
213 for (i = 0; i < r; i++)
214 if (!isalnum (buffer[i]))
215 return false;
216
217 return true;
218 }
219
220 /**
221 * send_all:
222 * @fd: a file descriptor for a connected stream socket
223 * @buffer: a buffer
224 * @size: the size of @buffer
225 * @timeout: a timeout, in microseconds
226 *
227 * Writes exactly @size bytes of @buffer to @fd, followed by EOF (ie:
228 * SHUT_WR).
229 *
230 * If all the bytes are written and the shutdown is successful, #true is
231 * returned. On failure (socket errors, or timeout) #false is returned.
232 *
233 * This function is meant to be used with recv_all() on the other side.
234 */
235 bool
236 send_all (int fd,
237 const char *buffer,
238 size_t size,
239 int timeout)
240 {
241 struct timespec start = { 0, 0 };
242 size_t count = 0;
243
244 while (count < size && wait_for_io (&start, fd, POLLOUT, timeout))
245 {
246 ssize_t s = send (fd, buffer + count, size - count, MSG_DONTWAIT | MSG_NOSIGNAL);
247
248 if (s == -1)
249 {
250 if (errno == EINTR || errno == EAGAIN)
251 continue;
252
253 warn ("send_all() failed");
254 return false;
255 }
256
257 count += s;
258 }
259
260 if (count != size)
261 {
262 warnx ("send_all() timed out");
263 return false;
264 }
265
266 if (shutdown (fd, SHUT_WR) != 0)
267 {
268 warn ("send_all(): shutdown(SHUT_WR)");
269 return false;
270 }
271
272 debug (SOCKET_IO, " -> successfully sent all %zu bytes and EOF.", count);
273 return true;
274 }
275
276 /**
277 * af_unix_fill_sockaddr_at:
278 * @addr: a (probably uninitialised) struct sockaddr_in
279 * @dirfd: a directory fd, or AT_FDCWD
280 * @pathname: a pathname
281 *
282 * Fills in @addr (both family and name) fields to be used with a
283 * connect() or bind() call on a AF_UNIX socket.
284 *
285 * If the pathname given in @pathname is relative, then it is interpreted
286 * relative to the directory referred to bythe file descriptor dirfd
287 * (rather than relative to the current working directory of the calling
288 * process, as is done by connect() or bind() for a relative pathname).
289 * This is accomplished by building a pathname based on the symlinks in
290 * /proc/self/fd/ (so @dirfd needs to remain open for the actual call to
291 * connect() or bind()).
292 *
293 * If @pathname is relative and dirfd is the special value AT_FDCWD,
294 * then @pathname is interpreted relative to the current working
295 * directory of the calling process (like connect() or bind()).
296 *
297 * If @pathname is absolute, then dirfd is ignored.
298 *
299 * @dirfd is never actually inspected in any way during this call: it is
300 * assumed to be a valid open directory file descriptor. If it's not,
301 * then this error won't be detected.
302 *
303 * Returns: %true on success, or %false (and errno == ENOMEM) in case it
304 * was not possible to fit the formatted string into the `struct
305 * sockaddr_un`.
306 */
307 static bool
308 af_unix_fill_sockaddr_at (struct sockaddr_un *addr,
309 int dirfd,
310 const char *pathname)
311 {
312 int r;
313
314 addr->sun_family = AF_UNIX;
315
316 if (pathname[0] != '/' && dirfd != AT_FDCWD)
317 r = snprintf (addr->sun_path, sizeof addr->sun_path, "/proc/self/fd/%d/%s", dirfd, pathname);
318 else
319 r = snprintf (addr->sun_path, sizeof addr->sun_path, "%s", pathname);
320
321 if (0 < r && r < sizeof addr->sun_path)
322 return true;
323
324 errno = ENOMEM;
325 return false;
326 }
327
328 /**
329 * af_unix_connectat:
330 * @sockfd: a socket file descriptor
331 * @dirfd: a directory file descriptor
332 * @pathname: a pathname
333 *
334 * Connects @sockfd to the unix domain socket at @pathname (relative to
335 * @dirfd).
336 *
337 * This call operates in exactly the same way as connect(), except for
338 * the differences described here.
339 *
340 * If the pathname given in @pathname is relative, then it is
341 * interpreted relative to the directory referred to bythe file
342 * descriptor dirfd (rather than relative to the current working
343 * directory of the calling process, as is done by connect() for a
344 * relative pathname).
345 *
346 * If @pathname is relative and dirfd is the special value AT_FDCWD,
347 * then @pathname is interpreted relative to the current working
348 * directory of the calling process (like connect()).
349 *
350 * If @pathname is absolute, then dirfd is ignored.
351 *
352 * An additional error of %ENOMEM can be returned in the event that it
353 * was not possible to fit the filename into a `struct sockaddr_un`.
354 *
355 * Returns: 0 on success, or -1 (and errno set) on error
356 */
357 int
358 af_unix_connectat (int sockfd,
359 int dirfd,
360 const char *pathname)
361 {
362 struct sockaddr_un addr;
363
364 if (!af_unix_fill_sockaddr_at (&addr, dirfd, pathname))
365 return -1;
366
367 debug (SOCKET_IO, "af_unix_connectat(%d, %s) to '%s'", dirfd, pathname, addr.sun_path);
368
369 return connect (sockfd, (struct sockaddr *) &addr, sizeof addr);
370 }
371
372 /**
373 * af_unix_bindat:
374 * @sockfd: a socket file descriptor
375 * @dirfd: a directory file descriptor
376 * @pathname: a pathname
377 *
378 * Binds @sockfd to the filesystem at @pathname (relative to @dirfd).
379 *
380 * This call operates in exactly the same way as bind(), except for
381 * the differences described here.
382 *
383 * If the pathname given in @pathname is relative, then it is
384 * interpreted relative to the directory referred to bythe file
385 * descriptor dirfd (rather than relative to the current working
386 * directory of the calling process, as is done by bind() for a
387 * relative pathname).
388 *
389 * If @pathname is relative and dirfd is the special value AT_FDCWD,
390 * then @pathname is interpreted relative to the current working
391 * directory of the calling process (like bind()).
392 *
393 * If @pathname is absolute, then dirfd is ignored.
394 *
395 * An additional error of %ENOMEM can be returned in the event that it
396 * was not possible to fit the filename into a `struct sockaddr_un`.
397 *
398 * Returns: 0 on success, or -1 (and errno set) on error
399 */
400 int
401 af_unix_bindat (int sockfd,
402 int dirfd,
403 const char *pathname)
404 {
405 struct sockaddr_un addr;
406
407 if (!af_unix_fill_sockaddr_at (&addr, dirfd, pathname))
408 return -1;
409
410 debug (SOCKET_IO, "af_unix_bindat(%d, %s) to '%s'", dirfd, pathname, addr.sun_path);
411
412 return bind (sockfd, (struct sockaddr *) &addr, sizeof addr);
413 }