Debian Codegraph @

src/dbus/socket.c

raw
1 /*
2 * D-Bus Socket Abstraction
3 *
4 * The Socket objects wraps a single connection between two DBus peers
5 * using streaming sockets. File-desciptor management is done by the caller.
6 * This object is mainly used for line and message buffering. It supports
7 * dual-mode: Line-based buffers for initial SASL transactions, and
8 * message-based buffers for DBus transactions.
9 *
10 * Note that once the first real DBus message was read, you must not use the
11 * line-helpers, anymore!
12 */
13
14 #include <c-list.h>
15 #include <c-stdaux.h>
16 #include <linux/sockios.h>
17 #include <stdlib.h>
18 #include <sys/epoll.h>
19 #include <sys/ioctl.h>
20 #include <sys/socket.h>
21 #include <sys/types.h>
22 #include <sys/un.h>
23 #include "dbus/message.h"
24 #include "dbus/queue.h"
25 #include "dbus/socket.h"
26 #include "util/error.h"
27 #include "util/fdlist.h"
28 #include "util/user.h"
29
30 struct SocketBuffer {
31 CList link;
32 UserCharge charges[2];
33
34 size_t n_total;
35 Message *message;
36
37 size_t n_vecs;
38 struct iovec *writer;
39 struct iovec vecs[];
40 };
41
42 static char *socket_buffer_get_base(SocketBuffer *buffer) {
43 return (char *)(buffer->vecs + buffer->n_vecs);
44 }
45
46 static SocketBuffer *socket_buffer_free(SocketBuffer *buffer) {
47 if (!buffer)
48 return NULL;
49
50 user_charge_deinit(&buffer->charges[1]);
51 user_charge_deinit(&buffer->charges[0]);
52 c_list_unlink(&buffer->link);
53 message_unref(buffer->message);
54 free(buffer);
55
56 return NULL;
57 }
58
59 C_DEFINE_CLEANUP(SocketBuffer *, socket_buffer_free);
60
61 static int socket_buffer_new_internal(SocketBuffer **bufferp, size_t n_vecs, size_t n_line) {
62 SocketBuffer *buffer;
63
64 buffer = malloc(sizeof(*buffer) + n_vecs * sizeof(*buffer->vecs) + n_line);
65 if (!buffer)
66 return error_origin(-ENOMEM);
67
68 buffer->link = (CList)C_LIST_INIT(buffer->link);
69 user_charge_init(&buffer->charges[0]);
70 user_charge_init(&buffer->charges[1]);
71 buffer->n_total = n_line;
72 buffer->message = NULL;
73 buffer->n_vecs = n_vecs;
74 buffer->writer = NULL;
75
76 *bufferp = buffer;
77 return 0;
78 }
79
80 static int socket_buffer_new_line(SocketBuffer **bufferp,
81 Socket *socket,
82 User *user,
83 size_t n) {
84 _c_cleanup_(socket_buffer_freep) SocketBuffer *buffer = NULL;
85 int r;
86
87 r = socket_buffer_new_internal(&buffer, 1, c_max(n, SOCKET_LINE_PREALLOC));
88 if (r)
89 return error_trace(r);
90
91 buffer->vecs[0] = (struct iovec){ socket_buffer_get_base(buffer), 0 };
92
93 r = user_charge(socket->user,
94 &buffer->charges[0],
95 user,
96 USER_SLOT_BYTES,
97 sizeof(SocketBuffer) + buffer->n_total);
98 if (r)
99 return (r == USER_E_QUOTA) ? SOCKET_E_QUOTA : error_fold(r);
100
101 *bufferp = buffer;
102 buffer = NULL;
103 return 0;
104 }
105
106 static int socket_buffer_new_message(SocketBuffer **bufferp,
107 Socket *socket,
108 User *user,
109 Message *message) {
110 _c_cleanup_(socket_buffer_freep) SocketBuffer *buffer = NULL;
111 int r;
112
113 r = socket_buffer_new_internal(&buffer, C_ARRAY_SIZE(message->vecs), 0);
114 if (r)
115 return error_trace(r);
116
117 buffer->message = message_ref(message);
118 c_memcpy(buffer->vecs, message->vecs, sizeof(message->vecs));
119
120 r = user_charge(socket->user,
121 &buffer->charges[0],
122 user,
123 USER_SLOT_BYTES,
124 sizeof(SocketBuffer) + sizeof(Message) + message->n_data);
125 if (r)
126 return (r == USER_E_QUOTA) ? SOCKET_E_QUOTA : error_fold(r);
127
128 r = user_charge(socket->user,
129 &buffer->charges[1],
130 user,
131 USER_SLOT_FDS,
132 fdlist_count(buffer->message->fds));
133 if (r)
134 return (r == USER_E_QUOTA) ? SOCKET_E_QUOTA : error_fold(r);
135
136 *bufferp = buffer;
137 buffer = NULL;
138 return 0;
139 }
140
141 static size_t socket_buffer_get_line_space(SocketBuffer *buffer) {
142 size_t n_remaining;
143
144 c_assert(!buffer->message);
145
146 n_remaining = buffer->n_total;
147 n_remaining -= (char *)buffer->vecs[0].iov_base - socket_buffer_get_base(buffer);
148 n_remaining -= buffer->vecs[0].iov_len;
149
150 return n_remaining;
151 }
152
153 static void socket_buffer_get_line_cursor(SocketBuffer *buffer, char **datap, size_t **posp) {
154 c_assert(!buffer->message);
155
156 *datap = buffer->vecs[0].iov_base + buffer->vecs[0].iov_len;
157 *posp = &buffer->vecs[0].iov_len;
158 }
159
160 static bool socket_buffer_is_uncomsumed(SocketBuffer *buffer) {
161 return !buffer->writer;
162 }
163
164 static bool socket_buffer_is_consumed(SocketBuffer *buffer) {
165 return buffer->writer >= buffer->vecs + buffer->n_vecs;
166 }
167
168 static bool socket_buffer_consume(SocketBuffer *buffer, size_t n) {
169 size_t t;
170
171 if (!buffer->writer)
172 buffer->writer = buffer->vecs;
173
174 for ( ; !socket_buffer_is_consumed(buffer); ++buffer->writer) {
175 t = c_min(buffer->writer->iov_len, n);
176 // IOVs can be empty/NULL. Ensure we do not calculate
177 // `NULL + 0`, as this is, unfortunately, UB.
178 if (t) {
179 buffer->writer->iov_len -= t;
180 buffer->writer->iov_base += t;
181 n -= t;
182 }
183 if (buffer->writer->iov_len)
184 break;
185 }
186
187 c_assert(!n);
188
189 return socket_buffer_is_consumed(buffer);
190 }
191
192 static void socket_discard_input(Socket *socket) {
193 iqueue_flush(&socket->in.queue);
194 socket->in.message = message_unref(socket->in.message);
195 }
196
197 static void socket_discard_output(Socket *socket) {
198 SocketBuffer *buffer;
199
200 while ((buffer = c_list_first_entry(&socket->out.queue, SocketBuffer, link)))
201 socket_buffer_free(buffer);
202 }
203
204 /**
205 * socket_init() - initialize socket
206 * @socket: socket to operate on
207 * @user: socket owner, or NULL
208 * @fd: socket file descriptor
209 *
210 * This initializes the new socket @socket. The socket will be owned by @user
211 * (and accounted on it), and @fd will be used as socket file descriptor. Not
212 * that @fd is still owned by the caller and must not be closed while the
213 * socket is used.
214 */
215 void socket_init(Socket *socket, User *user, int fd) {
216 *socket = (Socket)SOCKET_NULL(*socket);
217 socket->user = user_ref(user);
218 socket->fd = fd;
219 iqueue_init(&socket->in.queue, user);
220 }
221
222 /**
223 * socket_deinit() - deinitialize socket
224 * @socket: socket to operate on
225 *
226 * This deinitializes @socket and clears all allocated resources. The socket is
227 * cleared to SOCKET_NULL afterwards. Hence, it is safe to call socket_deinit()
228 * multiple times.
229 *
230 * Note that the socket file descriptor is *NOT* closed. It is still owned by
231 * the caller!
232 */
233 void socket_deinit(Socket *socket) {
234 SocketBuffer *buffer;
235
236 socket_discard_input(socket);
237 socket_discard_output(socket);
238
239 while ((buffer = c_list_first_entry(&socket->out.pending, SocketBuffer, link)))
240 socket_buffer_free(buffer);
241
242 c_assert(c_list_is_empty(&socket->out.pending));
243 c_assert(c_list_is_empty(&socket->out.queue));
244 c_assert(!socket->in.message);
245
246 iqueue_deinit(&socket->in.queue);
247 socket->fd = -1;
248 socket->user = user_unref(socket->user);
249 }
250
251 static void socket_might_reset(Socket *socket) {
252 if (_c_unlikely_(!socket->reset &&
253 socket->hup_in &&
254 socket->hup_out &&
255 c_list_is_empty(&socket->out.pending) &&
256 iqueue_is_eof(&socket->in.queue)))
257 socket->reset = true;
258 }
259
260 static void socket_hangup_input(Socket *socket) {
261 /*
262 * A read-side hangup is detected when recv(2) returns EOF or failure.
263 * In that case, we stop reading data from the socket, but still
264 * dispatch all pending input. Hence, we don't discard input buffers.
265 */
266 if (!socket->hup_in) {
267 socket->hup_in = true;
268 socket_might_reset(socket);
269 }
270 }
271
272 static void socket_hangup_output(Socket *socket) {
273 /*
274 * A write-side hangup is detected when send(2) or recv(2) fail. In
275 * that case, we cannot ever continue writing data to the socket, even
276 * though there might still be data to read.
277 * We always discard our output buffers, since the remote peer
278 * disconnected asynchronously, and there is no way for us to avoid
279 * data loss.
280 */
281 if (!socket->hup_out) {
282 socket->hup_out = true;
283 socket_discard_output(socket);
284 socket_might_reset(socket);
285 }
286 }
287
288 static void socket_shutdown_now(Socket *socket) {
289 int r;
290
291 c_assert(socket->shutdown);
292
293 if (!socket->hup_out) {
294 r = shutdown(socket->fd, SHUT_WR);
295 c_assert(r >= 0);
296
297 socket_hangup_output(socket);
298 }
299 }
300
301 /**
302 * socket_dequeue_line() - fetch line from input buffer
303 * @socket: socket to operate on
304 * @linep: output argument for read line
305 * @np: output argument for read line length
306 *
307 * This fetchs the next full line from the input buffer. The \r\n is stripped,
308 * and the line is returned in @linep and @np. That is, @np might be 0 (in case
309 * the line was empty apart from \r\n), but @linep will still point to the line
310 * in that case (that is, it is non-NULL).
311 *
312 * If no more lines can be fetched, this returns NULL in @linep, and 0 in @np.
313 *
314 * Note that any fetched line is always owned by the socket. That is, @linep is
315 * only valid until the next call to a socket function. It points directly into
316 * the input buffer of the socket, and might be moved, overwritten, or
317 * deallocated by any other socket call.
318 *
319 * This function must not be called once the socket has been put into
320 * message-mode. That is, the line-based I/O is torn down as soon as the first
321 * message is read or written.
322 *
323 * Return: On success, 0 is returned and @linep and @np either contain the read
324 * line, or (NULL, 0) if there is no more data to fetch.
325 * If the input-stream was closed and no more data is to be read,
326 * SOCKET_E_EOF is returned.
327 * On fatal errors, a negative error code is returned.
328 */
329 int socket_dequeue_line(Socket *socket, const char **linep, size_t *np) {
330 int r;
331
332 r = iqueue_pop_line(&socket->in.queue, linep, np);
333 if (r) {
334 if (r == IQUEUE_E_PENDING) {
335 socket_might_reset(socket);
336 if (_c_unlikely_(socket->hup_in))
337 return SOCKET_E_EOF;
338
339 *linep = NULL;
340 *np = 0;
341 return 0;
342 } else if (r == IQUEUE_E_VIOLATION) {
343 socket_close(socket);
344 return SOCKET_E_EOF;
345 }
346
347 return error_fold(r);
348 }
349
350 return 0;
351 }
352
353 /**
354 * socket_dequeue() - fetch message from input buffer
355 * @socket: socket to operate on
356 * @messagep: output argument for read message
357 *
358 * This fetches a message from the input buffer. If a full message was parsed,
359 * the @messagep argument will now point to it and own a single reference to be
360 * released by the caller.
361 * If no more messages can be fetched from the input buffer, NULL is put into
362 * @messagep.
363 *
364 * If the input stream was shutdown, SOCKET_E_EOF is returned and no further
365 * data can be read.
366 *
367 * Return: On success, 0 is returned and @messagep will point to the read
368 * message (now owned by the caller). If no more messages can be
369 * fetched, NULL is put into @messagep.
370 * If the input-stream was closed and no more data is to be read,
371 * SOCKET_E_EOF is returned.
372 * If the incoming message would exceed the quota of the caller, then
373 * SOCKET_E_QUOTA is returned.
374 * On fatal errors, a negative error code is returned.
375 */
376 int socket_dequeue(Socket *socket, Message **messagep) {
377 Message *message;
378 int r;
379
380 if (!iqueue_get_target(&socket->in.queue)) {
381 r = iqueue_set_target(&socket->in.queue,
382 &socket->in.header,
383 sizeof(socket->in.header));
384 if (r)
385 return (r == IQUEUE_E_QUOTA) ? SOCKET_E_QUOTA : error_fold(r);
386 }
387
388 if (!socket->in.message) {
389 r = iqueue_pop_data(&socket->in.queue, NULL);
390 if (r == IQUEUE_E_PENDING) {
391 goto nodata;
392 } else if (r == IQUEUE_E_VIOLATION) {
393 socket_close(socket);
394 return SOCKET_E_EOF;
395 } else if (r) {
396 return error_fold(r);
397 }
398
399 r = message_new_incoming(&message, socket->in.header);
400 if (r == MESSAGE_E_CORRUPT_HEADER ||
401 r == MESSAGE_E_TOO_LARGE) {
402 socket_close(socket);
403 return SOCKET_E_EOF;
404 } else if (r) {
405 return error_fold(r);
406 }
407
408 r = iqueue_set_target(&socket->in.queue,
409 message->data + sizeof(socket->in.header),
410 message->n_data - sizeof(socket->in.header));
411 if (r) {
412 message_unref(message);
413 return (r == IQUEUE_E_QUOTA) ? SOCKET_E_QUOTA : error_fold(r);
414 }
415
416 socket->in.message = message;
417 }
418
419 c_assert(socket->in.message);
420
421 r = iqueue_pop_data(&socket->in.queue, &socket->in.message->fds);
422 if (r == IQUEUE_E_PENDING) {
423 goto nodata;
424 } else if (r == IQUEUE_E_VIOLATION) {
425 socket_close(socket);
426 return SOCKET_E_EOF;
427 } else if (r) {
428 return error_fold(r);
429 }
430
431 *messagep = socket->in.message;
432 socket->in.message = NULL;
433 return 0;
434
435 nodata:
436 socket_might_reset(socket);
437 if (_c_unlikely_(socket->hup_in))
438 return SOCKET_E_EOF;
439
440 *messagep = NULL;
441 return 0;
442 }
443
444 /**
445 * socket_queue_line() - queue line on socket
446 * @socket: socket to operate on
447 * @user: user to account for, or NULL
448 * @line_in: line pointer
449 * @n: length of line
450 *
451 * This queues the line (@line_in, @n) on the socket @socket, accounting @user
452 * as the sender. If @user is NULL, the owner of the socket is accounted.
453 *
454 * \r\n is always appended to the message by this function.
455 *
456 * Return: 0 on success, SOCKET_E_QUOTA if quota failed, SOCKET_E_SHUTDOWN if
457 * write-side end is already shutdown, negative error code on failure.
458 */
459 int socket_queue_line(Socket *socket, User *user, const char *line_in, size_t n) {
460 SocketBuffer *buffer;
461 char *line_out;
462 size_t *pos;
463 int r;
464
465 if (_c_unlikely_(socket->hup_out || socket->shutdown))
466 return SOCKET_E_SHUTDOWN;
467
468 buffer = c_list_last_entry(&socket->out.queue, SocketBuffer, link);
469 if (!buffer || n + strlen("\r\n") > socket_buffer_get_line_space(buffer)) {
470 r = socket_buffer_new_line(&buffer, socket, user, n + strlen("\r\n"));
471 if (r)
472 return error_trace(r);
473
474 c_list_link_tail(&socket->out.queue, &buffer->link);
475 }
476
477 socket_buffer_get_line_cursor(buffer, &line_out, &pos);
478
479 c_memcpy(line_out, line_in, n);
480 line_out += n;
481 *pos += n;
482
483 c_memcpy(line_out, "\r\n", strlen("\r\n"));
484 *pos += strlen("\r\n");
485
486 return 0;
487 }
488
489 /**
490 * socket_queue() - queue socket buffer on socket
491 * @socket: socket to operate on
492 * @user: user to charge as
493 * @message: message to queue
494 *
495 * This queues @message on the socket @socket, charging @user for the required
496 * quota on the socket owner of @socket.
497 *
498 * Return: 0 on success, SOCKET_E_QUOTA if quota failed, SOCKET_E_SHUTDOWN if
499 * write-side end is already shutdown, negative error code on failure.
500 */
501 int socket_queue(Socket *socket, User *user, Message *message) {
502 _c_cleanup_(socket_buffer_freep) SocketBuffer *buffer = NULL;
503 int r;
504
505 if (_c_unlikely_(socket->hup_out || socket->shutdown))
506 return SOCKET_E_SHUTDOWN;
507
508 r = socket_buffer_new_message(&buffer, socket, user, message);
509 if (r)
510 return error_trace(r);
511
512 c_list_link_tail(&socket->out.queue, &buffer->link);
513 buffer = NULL;
514 return 0;
515 }
516
517 static int socket_recvmsg(Socket *socket,
518 void *buffer,
519 size_t *from,
520 size_t to,
521 FDList **fdsp,
522 UserCharge *charge_fds) {
523 union {
524 struct cmsghdr cmsg;
525 char buffer[CMSG_SPACE(sizeof(int) * SOCKET_FD_MAX)];
526 } control;
527 struct cmsghdr *cmsg;
528 struct msghdr msg;
529 int r, *fds = NULL;
530 size_t n_fds = 0;
531 ssize_t l;
532
533 c_assert(to > *from);
534
535 msg = (struct msghdr){
536 .msg_iov = &(struct iovec){
537 .iov_base = buffer + *from,
538 .iov_len = to - *from,
539 },
540 .msg_iovlen = 1,
541 .msg_control = &control,
542 .msg_controllen = sizeof(control),
543 };
544
545 l = recvmsg(socket->fd, &msg, MSG_DONTWAIT | MSG_CMSG_CLOEXEC);
546 if (_c_unlikely_(!l)) {
547 /*
548 * A 0 return of recvmsg() signals end-of-file. Hence, hangup
549 * the input side, but keep the output alive. We might still
550 * want to flush more data out.
551 */
552 socket_hangup_input(socket);
553 return SOCKET_E_LOST_INTEREST;
554 } else if (_c_unlikely_(l < 0)) {
555 switch (errno) {
556 case EAGAIN:
557 return 0;
558 case ECOMM:
559 case ECONNABORTED:
560 case ECONNRESET:
561 case EHOSTDOWN:
562 case EHOSTUNREACH:
563 case EIO:
564 case ENOBUFS:
565 case ENOMEM:
566 case EPIPE:
567 case EPROTO:
568 case EREMOTEIO:
569 case ESHUTDOWN:
570 case ETIMEDOUT:
571 /*
572 * If recvmsg(2) fails, this means both read-side *and*
573 * write-side are shutdown. A mere read-side hangup is
574 * signalled by a 0 return-value (handled above).
575 */
576 socket_hangup_input(socket);
577 socket_hangup_output(socket);
578 return SOCKET_E_LOST_INTEREST;
579 }
580
581 return error_origin(-errno);
582 }
583
584 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
585 if (cmsg->cmsg_level == SOL_SOCKET &&
586 cmsg->cmsg_type == SCM_RIGHTS) {
587 /*
588 * Kernel breaks after SKB+fd, so we never get more
589 * than one SCM_RIGHTS array.
590 */
591 c_assert(!n_fds);
592 fds = (void *)CMSG_DATA(cmsg);
593 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
594 c_assert(n_fds <= SOCKET_FD_MAX);
595 }
596 }
597
598 if (msg.msg_flags & MSG_CTRUNC) {
599 /*
600 * Our control-buffer-size is carefully calculated to be big
601 * enough for any possible ancillary data we expect. Therefore,
602 * the kernel should never be required to truncate it, and thus
603 * MSG_CTRUNC will never be set. This is also foward compatible
604 * to future extensions to the ancillary data, since these must
605 * be enabled explicitly before the kernel considers forwarding
606 * them.
607 *
608 * Unfortunately, the SCM_RIGHTS implementation might set this
609 * flag as well. In particular, if not all FDs can be returned
610 * to user-space, MSG_CTRUNC will be set (signalling that the
611 * FD-set is non-complete). No other error is returned or
612 * signalled, though. There are several reasons why the FD
613 * transmission can fail. Most importantly, if we exhaust our
614 * FD limit, further FDs will simply be discarded. We are
615 * protected against this by our accounting-quotas, but we
616 * would still like to catch this condition and warn loudly.
617 * However, FDs are also dropped if the security layer refused
618 * the transmission of the FD in question. This means, if an
619 * LSM refuses the D-Bus client to send us an FD, the FD is
620 * just dropped and MSG_CTRUNC will be set. This can be
621 * triggered by clients.
622 *
623 * To summarize: In an ideal world, we would expect this flag
624 * to never be set, and we would just use
625 * `error_origin(-ENOTRECOVERABLE)` to provide diagnostics.
626 * Unfortunately, the gross misuse of this flag for LSM
627 * security enforcements means we have to assume any occurence
628 * of MSG_CTRUNC means the client was refused to send a
629 * specific message. Our only possible way to deal with this is
630 * to disconnect the client.
631 */
632 socket_close(socket);
633 r = SOCKET_E_LOST_INTEREST;
634 goto error;
635 }
636
637 if (_c_unlikely_(*fdsp && n_fds)) {
638 /* XXX: this is a protocol violation, but for now simply drop the
639 * spurios fds as sd-bus is broken and passes us this.
640 * This whole conditional should simply be dropped.
641 */
642 while (n_fds)
643 close(fds[--n_fds]);
644
645 fprintf(stderr, "socket: discarded unexpected file descriptors.\n");
646 }
647
648 if (_c_unlikely_(n_fds)) {
649 /*
650 * So we received FDs with this hunk. If we already got FDs for
651 * this pending message, we must follow the D-Bus spec and
652 * treat this as protocol violation. So close the socket
653 * immediately. We also close the socket immediately in case
654 * the sending user's fd quota has been exceeded.
655 * Otherwise, remember the FDs in the socket. Note that FDs
656 * always belong to the *last* byte of a received hunk, since
657 * the kernel breaks SKBs *AFTER* FDs, but not before them.
658 * This also means we must never call into recvmsg(2) if there
659 * is unparsed data in our buffers, since we might incorrectly
660 * merge two messages.
661 */
662
663 if (_c_unlikely_(*fdsp)) {
664 socket_close(socket);
665 r = SOCKET_E_LOST_INTEREST;
666 goto error;
667 }
668
669 r = user_charge(socket->user,
670 charge_fds,
671 NULL,
672 USER_SLOT_FDS,
673 n_fds);
674 if (r == USER_E_QUOTA) {
675 /*
676 * Too many/large outstanding messages accross all
677 * a user's peers is considered a protocol
678 * violation too and causes an immediate shutdown.
679 */
680 socket_close(socket);
681 r = SOCKET_E_LOST_INTEREST;
682 goto error;
683 } else if (r) {
684 r = error_fold(r);
685 goto error;
686 }
687
688 r = fdlist_new_consume_fds(fdsp, fds, n_fds);
689 if (r) {
690 user_charge_deinit(charge_fds);
691 r = error_fold(r);
692 goto error;
693 }
694 }
695
696 *from += l;
697 return SOCKET_E_PREEMPTED;
698
699 error:
700 while (n_fds)
701 close(fds[--n_fds]);
702 return r;
703 }
704
705 static int socket_dispatch_read(Socket *socket) {
706 UserCharge *charge_fds;
707 size_t *from, to;
708 FDList **fds;
709 void *buffer;
710 int r;
711
712 if (socket->hup_in)
713 return SOCKET_E_LOST_INTEREST;
714
715 r = iqueue_get_cursor(&socket->in.queue,
716 &buffer,
717 &from,
718 &to,
719 &fds,
720 &charge_fds);
721 if (r == IQUEUE_E_PENDING) {
722 return 0;
723 } else if (r == IQUEUE_E_QUOTA ||
724 r == IQUEUE_E_VIOLATION) {
725 socket_close(socket);
726 return SOCKET_E_LOST_INTEREST;
727 } else if (r) {
728 return error_fold(r);
729 }
730
731 return socket_recvmsg(socket,
732 buffer,
733 from,
734 to,
735 fds,
736 charge_fds);
737 }
738
739 static int socket_dispatch_write(Socket *socket) {
740 SocketBuffer *buffer, *safe;
741 struct mmsghdr msgs[SOCKET_MMSG_MAX];
742 struct msghdr *msg;
743 int r, i, v, n_msgs;
744
745 if (!c_list_is_empty(&socket->out.pending)) {
746 r = ioctl(socket->fd, SIOCOUTQ, &v);
747 if (r < 0)
748 return error_origin(-errno);
749
750 /*
751 * We would like to check for an empty queue here:
752 *
753 * if (v > 0)
754 * return 0;
755 *
756 * Unfortunately, the kernel uses the write-buffer as a
757 * reference counter. This effectively means that when it drops
758 * buffers from the write-queue, it drops all but 1 from the
759 * `sk_wmem_alloc` counter, then notifies user-space, and
760 * eventually drops its final reference, possibly freeing the
761 * underlying socket structures, if this was the last
762 * reference.
763 *
764 * While it is possible to hit this small race with a single
765 * kernel thread currently holding this temporary reference,
766 * technically there can be many threads in parallel. However,
767 * this would require multiple readers on the other end of the
768 * dbus-socket, and all of them dispatching data in parallel
769 * (which does not make sense for stream sockets), and all in
770 * exactly the same kernel path at the same time. While we
771 * consider it impossible to hit this with more than one thread
772 * in the same path, we use 128 as a safety measure here.
773 *
774 * Note that the kernel uses `skb->truesize` for write-buffer
775 * allocations, meaning that even transmitting a single byte
776 * will allocate buffers larger than 128 bytes. Therefore, this
777 * seems like a suitable tradeoff.
778 *
779 * The preferred fix would be the kernel returning the actual
780 * data, rather than misusing the counter, but that is not how
781 * things currently work.
782 *
783 * Lastly, we simply return 0 and treat this condition as
784 * EAGAIN. We know that the kernel will send us an EPOLLOUT
785 * notification as soon as the write-buffer clears, so we will
786 * be woken up again when there is no more pending data in the
787 * outgoing queues.
788 */
789 if (v > 128)
790 return 0;
791
792 c_list_for_each_entry_safe(buffer, safe, &socket->out.pending, link)
793 socket_buffer_free(buffer);
794
795 socket_might_reset(socket);
796 }
797
798 if (socket->hup_out)
799 return SOCKET_E_LOST_INTEREST;
800
801 n_msgs = 0;
802 c_list_for_each_entry(buffer, &socket->out.queue, link) {
803 msg = &msgs[n_msgs].msg_hdr;
804
805 msg->msg_name = NULL;
806 msg->msg_namelen = 0;
807 msg->msg_iov = buffer->vecs;
808 msg->msg_iovlen = buffer->n_vecs;
809 if (buffer->message &&
810 buffer->message->fds &&
811 socket_buffer_is_uncomsumed(buffer)) {
812 msg->msg_control = buffer->message->fds->cmsg;
813 msg->msg_controllen = fdlist_size(buffer->message->fds);
814 } else {
815 msg->msg_control = NULL;
816 msg->msg_controllen = 0;
817 }
818 msg->msg_flags = 0;
819
820 if (++n_msgs >= (ssize_t)C_ARRAY_SIZE(msgs))
821 break;
822
823 /*
824 * Right now, the only information the kernel gives us about
825 * outgoing queues is whether there is data queued or not. That
826 * is, a boolean state. There is some other data, but we cannot
827 * reliable deduce any useful state from it.
828 *
829 * Hence, we only ever queue at most 1 message with FDs on it.
830 * This way, we can reliably get notified about FDs being
831 * queued and dequeued.
832 *
833 * We could, technically, avoid this and just spam out
834 * messages. However, we better be notified as early as
835 * possible about dequeued FDs, so our accounting actually
836 * represents the real client-controlled state. If we were
837 * notified late (because we continued queueing), then a client
838 * might have dequeued the FDs at fault, but we still consider
839 * them queued and thus might exceed its quota.
840 */
841 if (buffer->message && fdlist_count(buffer->message->fds))
842 break;
843 }
844
845 if (!n_msgs)
846 return SOCKET_E_LOST_INTEREST;
847
848 n_msgs = sendmmsg(socket->fd, msgs, n_msgs, MSG_DONTWAIT | MSG_NOSIGNAL);
849 if (n_msgs < 0) {
850 switch (errno) {
851 case EAGAIN:
852 return 0;
853 case ETOOMANYREFS:
854 /*
855 * The kernel used to return ETOOMANYREFS if we exceed
856 * the fd-passing recursion limit. This was dropped in
857 * commit:
858 *
859 * commit 27eac47b00789522ba00501b0838026e1ecb6f05
860 * Author: David Herrmann <[email protected]>
861 * Commit: David S. Miller <[email protected]>
862 * Date: Mon Jul 17 11:35:54 2017 +0200
863 *
864 * net/unix: drop obsolete fd-recursion limits
865 *
866 * Since then the kernel no longer limits the recursion
867 * depth, thus we will not trigger ETOOMANYREFS. You
868 * are highly recommended to run >=linux-4.14,
869 * otherwise clients can exploit this by modifying
870 * file-descriptors while inflight.
871 *
872 * Note that the kernel also returns ETOOMANYREFS if we
873 * exceeded our per-user limit of maximum inflight
874 * file-descriptors. Since we employ quota-accounting,
875 * ETOOMANYREFS should never occur, unless you
876 * misconfigured your broker. Hence, we treat this as
877 * fatal error.
878 *
879 * XXX: At one point in the future, we should remove
880 * this switch-case. We leave it here purely for
881 * documenting the history of this error-code.
882 */
883 break;
884 case ECOMM:
885 case ECONNABORTED:
886 case ECONNRESET:
887 case EHOSTDOWN:
888 case EHOSTUNREACH:
889 case EIO:
890 case ENOBUFS:
891 case ENOMEM:
892 case EPIPE:
893 case EPROTO:
894 case EREMOTEIO:
895 case ESHUTDOWN:
896 case ETIMEDOUT:
897 socket_hangup_output(socket);
898 return SOCKET_E_LOST_INTEREST;
899 }
900
901 return error_origin(-errno);
902 }
903
904 i = 0;
905 c_list_for_each_entry_safe(buffer, safe, &socket->out.queue, link) {
906 if (i >= n_msgs)
907 break;
908
909 if (socket_buffer_consume(buffer, msgs[i].msg_len)) {
910 if (buffer->message && buffer->message->fds) {
911 c_list_unlink(&buffer->link);
912 c_list_link_tail(&socket->out.pending, &buffer->link);
913 } else {
914 socket_buffer_free(buffer);
915 }
916 }
917
918 ++i;
919 }
920 c_assert(i == n_msgs);
921
922 if (c_list_is_empty(&socket->out.queue)) {
923 if (_c_unlikely_(socket->shutdown))
924 socket_shutdown_now(socket);
925
926 if (_c_likely_(c_list_is_empty(&socket->out.pending)))
927 return SOCKET_E_LOST_INTEREST;
928 }
929
930 return 0;
931 }
932
933 /**
934 * socket_dispatch() - dispatch event
935 * @socket: socket to operate on
936 * @event: epoll-event to dispatch
937 *
938 * This dispatches the epoll-event @event on the socket @socket. After calling
939 * this, the caller must loop on socket_dequeue{,_line}() to fetch all data.
940 *
941 * Return: 0 on success, SOCKET_E_LOST_INTEREST if the socket lost interest in
942 * the event, SOCKET_E_PREEMPTED if the socket was preempted while
943 * handling the event, negative error code on failure.
944 */
945 int socket_dispatch(Socket *socket, uint32_t event) {
946 int r = SOCKET_E_LOST_INTEREST;
947
948 switch (event) {
949 case EPOLLIN:
950 r = socket_dispatch_read(socket);
951 break;
952 case EPOLLOUT:
953 r = socket_dispatch_write(socket);
954 break;
955 case EPOLLHUP:
956 socket_hangup_output(socket);
957 break;
958 }
959
960 return r;
961 }
962
963 /**
964 * socket_shutdown() - disallow further queueing on the socket
965 * @socket: socket to operate on
966 *
967 * This disallows further queuing on the socket, but still flushes out the
968 * pending socket buffers to the kernel. Once all pending output has been
969 * sent the remote end is notified of the shutdown.
970 */
971 void socket_shutdown(Socket *socket) {
972 if (!socket->shutdown) {
973 socket->shutdown = true;
974 if (c_list_is_empty(&socket->out.queue))
975 socket_shutdown_now(socket);
976 }
977 }
978
979 /**
980 * socket_close() - close both communication directions
981 * @socket: socket to operate on
982 *
983 * This disallows both further queuing and dequeuing on the socket, but
984 * still flushes out the pending socket buffers to the kernel. Once all
985 * pending output has been sent the remote end is notified of the shutdown.
986 */
987 void socket_close(Socket *socket) {
988 socket_hangup_input(socket);
989 socket_shutdown(socket);
990
991 /*
992 * Now that both input and output were shut down, we discard pending
993 * input, since we want an immediate shutdown.
994 * Note that this might trigger a reset, so we have to call into
995 * socket_might_reset() here (the call to socket_discard_input() does
996 * not do that).
997 */
998 socket_discard_input(socket);
999 socket_might_reset(socket);
1000 }
1001
1002 /**
1003 * socket_get_stats() - calculate socket statistics
1004 * @socket: socket to operate on
1005 * @n_in_bytesp: output argument for #incoming bytes
1006 * @n_in_fdsp: output argument for #incoming fds
1007 * @n_out_bytesp: output argument for #outgoing bytes
1008 * @n_out_fdsp: output argument for #outgoing fds
1009 *
1010 * This calculates the statistics of incoming and outgoing messages on @socket.
1011 */
1012 void socket_get_stats(Socket *socket,
1013 unsigned int *n_in_bytesp,
1014 unsigned int *n_in_fdsp,
1015 unsigned int *n_out_bytesp,
1016 unsigned int *n_out_fdsp) {
1017 unsigned int n_in_bytes = 0, n_in_fds = 0, n_out_bytes = 0, n_out_fds = 0;
1018 SocketBuffer *buffer;
1019
1020 n_in_bytes += socket->in.queue.charge_data.charge;
1021 n_in_bytes += socket->in.queue.pending.charge_data.charge;
1022 n_in_fds += socket->in.queue.charge_fds.charge;
1023 n_in_fds += socket->in.queue.pending.charge_fds.charge;
1024
1025 c_list_for_each_entry(buffer, &socket->out.queue, link) {
1026 n_out_bytes += buffer->charges[0].charge;
1027 n_out_fds += buffer->charges[1].charge;
1028 }
1029
1030 c_list_for_each_entry(buffer, &socket->out.pending, link) {
1031 n_out_bytes += buffer->charges[0].charge;
1032 n_out_fds += buffer->charges[1].charge;
1033 }
1034
1035 *n_in_bytesp = n_in_bytes;
1036 *n_in_fdsp = n_in_fds;
1037 *n_out_bytesp = n_out_bytes;
1038 *n_out_fdsp = n_out_fds;
1039 }