]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/libsystemd/sd-bus/bus-socket.c
Suspend on lid close based on power status. (#8016)
[thirdparty/systemd.git] / src / libsystemd / sd-bus / bus-socket.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a7e3212d
LP
2/***
3 This file is part of systemd.
4
5 Copyright 2013 Lennart Poettering
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19***/
20
21#include <endian.h>
07630cea 22#include <poll.h>
a7e3212d
LP
23#include <stdlib.h>
24#include <unistd.h>
a7e3212d 25
07630cea 26#include "sd-bus.h"
24882e06 27#include "sd-daemon.h"
07630cea 28
b5efdb8a 29#include "alloc-util.h"
07630cea
LP
30#include "bus-internal.h"
31#include "bus-message.h"
3ffd4af2
LP
32#include "bus-socket.h"
33#include "fd-util.h"
f97b34a6 34#include "format-util.h"
8a5cd31e 35#include "fs-util.h"
15a5e950 36#include "hexdecoct.h"
8a5cd31e 37#include "io-util.h"
a7e3212d
LP
38#include "macro.h"
39#include "missing.h"
8a5cd31e 40#include "path-util.h"
dccca82b 41#include "process-util.h"
7fc04b12 42#include "selinux-util.h"
24882e06 43#include "signal-util.h"
15a5e950 44#include "stdio-util.h"
07630cea 45#include "string-util.h"
b1d4f8e1 46#include "user-util.h"
07630cea
LP
47#include "utf8.h"
48#include "util.h"
a7e3212d 49
aec6d91f
LP
50#define SNDBUF_SIZE (8*1024*1024)
51
2181a7f5 52static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
a7e3212d
LP
53
54 while (size > 0) {
55 struct iovec *i = iov + *idx;
56
57 if (i->iov_len > size) {
58 i->iov_base = (uint8_t*) i->iov_base + size;
59 i->iov_len -= size;
60 return;
61 }
62
63 size -= i->iov_len;
64
65 i->iov_base = NULL;
66 i->iov_len = 0;
67
313cefa1 68 (*idx)++;
a7e3212d
LP
69 }
70}
71
bc7fd8cd 72static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
2100fa10
LP
73 assert(m);
74 assert(p);
75 assert(sz > 0);
76
77 m->iovec[m->n_iovec].iov_base = (void*) p;
78 m->iovec[m->n_iovec].iov_len = sz;
79 m->n_iovec++;
bc7fd8cd
LP
80
81 return 0;
2100fa10
LP
82}
83
bc7fd8cd
LP
84static int bus_message_setup_iovec(sd_bus_message *m) {
85 struct bus_body_part *part;
13c299d3 86 unsigned n, i;
bc7fd8cd
LP
87 int r;
88
2100fa10
LP
89 assert(m);
90 assert(m->sealed);
91
92 if (m->n_iovec > 0)
bc7fd8cd
LP
93 return 0;
94
95 assert(!m->iovec);
2100fa10 96
c91cb83c 97 n = 1 + m->n_body_parts;
bc7fd8cd
LP
98 if (n < ELEMENTSOF(m->iovec_fixed))
99 m->iovec = m->iovec_fixed;
100 else {
101 m->iovec = new(struct iovec, n);
66b26c5c
LP
102 if (!m->iovec) {
103 r = -ENOMEM;
104 goto fail;
105 }
bc7fd8cd 106 }
2100fa10 107
c91cb83c 108 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
bc7fd8cd 109 if (r < 0)
66b26c5c 110 goto fail;
2100fa10 111
9b29bb68 112 MESSAGE_FOREACH_PART(part, i, m) {
66b26c5c
LP
113 r = bus_body_part_map(part);
114 if (r < 0)
115 goto fail;
116
bc7fd8cd
LP
117 r = append_iovec(m, part->data, part->size);
118 if (r < 0)
66b26c5c 119 goto fail;
bc7fd8cd
LP
120 }
121
122 assert(n == m->n_iovec);
123
124 return 0;
66b26c5c
LP
125
126fail:
127 m->poisoned = true;
128 return r;
2100fa10
LP
129}
130
2181a7f5
LP
131bool bus_socket_auth_needs_write(sd_bus *b) {
132
133 unsigned i;
134
135 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
136 return false;
137
138 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
139 struct iovec *j = b->auth_iovec + i;
140
141 if (j->iov_len > 0)
142 return true;
143 }
144
145 return false;
146}
147
a7e3212d 148static int bus_socket_write_auth(sd_bus *b) {
a7e3212d
LP
149 ssize_t k;
150
151 assert(b);
152 assert(b->state == BUS_AUTHENTICATING);
153
2181a7f5 154 if (!bus_socket_auth_needs_write(b))
a7e3212d
LP
155 return 0;
156
15d5af81
LP
157 if (b->prefer_writev)
158 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
159 else {
160 struct msghdr mh;
161 zero(mh);
162
163 mh.msg_iov = b->auth_iovec + b->auth_index;
164 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
165
166 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
167 if (k < 0 && errno == ENOTSOCK) {
168 b->prefer_writev = true;
169 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
170 }
171 }
a7e3212d 172
a7e3212d
LP
173 if (k < 0)
174 return errno == EAGAIN ? 0 : -errno;
175
176 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
a7e3212d
LP
177 return 1;
178}
179
2181a7f5 180static int bus_socket_auth_verify_client(sd_bus *b) {
a7e3212d
LP
181 char *e, *f, *start;
182 sd_id128_t peer;
183 unsigned i;
184 int r;
185
2181a7f5
LP
186 assert(b);
187
a7e3212d
LP
188 /* We expect two response lines: "OK" and possibly
189 * "AGREE_UNIX_FD" */
190
6e6c21c8 191 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
a7e3212d
LP
192 if (!e)
193 return 0;
194
c7db1984 195 if (b->accept_fd) {
a7e3212d
LP
196 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
197 if (!f)
198 return 0;
199
200 start = f + 2;
201 } else {
202 f = NULL;
203 start = e + 2;
204 }
205
206 /* Nice! We got all the lines we need. First check the OK
207 * line */
208
209 if (e - (char*) b->rbuffer != 3 + 32)
210 return -EPERM;
211
212 if (memcmp(b->rbuffer, "OK ", 3))
213 return -EPERM;
214
2181a7f5
LP
215 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
216
a7e3212d
LP
217 for (i = 0; i < 32; i += 2) {
218 int x, y;
219
220 x = unhexchar(((char*) b->rbuffer)[3 + i]);
221 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
222
223 if (x < 0 || y < 0)
224 return -EINVAL;
225
226 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
227 }
228
3bbaff3e 229 if (!sd_id128_is_null(b->server_id) &&
98178d39 230 !sd_id128_equal(b->server_id, peer))
a7e3212d
LP
231 return -EPERM;
232
98178d39 233 b->server_id = peer;
a7e3212d
LP
234
235 /* And possibly check the second line, too */
236
237 if (f)
238 b->can_fds =
fbd0b64f
LP
239 (f - e == STRLEN("\r\nAGREE_UNIX_FD")) &&
240 memcmp(e + 2, "AGREE_UNIX_FD",
241 STRLEN("AGREE_UNIX_FD")) == 0;
a7e3212d
LP
242
243 b->rbuffer_size -= (start - (char*) b->rbuffer);
244 memmove(b->rbuffer, start, b->rbuffer_size);
245
246 r = bus_start_running(b);
247 if (r < 0)
248 return r;
249
250 return 1;
251}
252
2181a7f5
LP
253static bool line_equals(const char *s, size_t m, const char *line) {
254 size_t l;
255
256 l = strlen(line);
257 if (l != m)
258 return false;
259
260 return memcmp(s, line, l) == 0;
261}
262
263static bool line_begins(const char *s, size_t m, const char *word) {
264 size_t l;
265
266 l = strlen(word);
267 if (m < l)
268 return false;
269
270 if (memcmp(s, word, l) != 0)
271 return false;
272
273 return m == l || (m > l && s[l] == ' ');
274}
275
276static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
277 _cleanup_free_ char *token = NULL;
30494563
TG
278 size_t len;
279 int r;
2181a7f5
LP
280
281 if (!b->anonymous_auth)
282 return 0;
283
284 if (l <= 0)
285 return 1;
286
287 assert(p[0] == ' ');
288 p++; l--;
289
290 if (l % 2 != 0)
291 return 0;
2181a7f5 292
30494563
TG
293 r = unhexmem(p, l, (void **) &token, &len);
294 if (r < 0)
295 return 0;
296
297 if (memchr(token, 0, len))
2181a7f5
LP
298 return 0;
299
300 return !!utf8_is_valid(token);
301}
302
303static int verify_external_token(sd_bus *b, const char *p, size_t l) {
304 _cleanup_free_ char *token = NULL;
30494563 305 size_t len;
2181a7f5
LP
306 uid_t u;
307 int r;
308
309 /* We don't do any real authentication here. Instead, we if
310 * the owner of this bus wanted authentication he should have
311 * checked SO_PEERCRED before even creating the bus object. */
312
8411d2a2 313 if (!b->anonymous_auth && !b->ucred_valid)
2181a7f5
LP
314 return 0;
315
316 if (l <= 0)
317 return 1;
318
319 assert(p[0] == ' ');
320 p++; l--;
321
322 if (l % 2 != 0)
323 return 0;
324
30494563
TG
325 r = unhexmem(p, l, (void**) &token, &len);
326 if (r < 0)
327 return 0;
2181a7f5 328
30494563 329 if (memchr(token, 0, len))
2181a7f5
LP
330 return 0;
331
332 r = parse_uid(token, &u);
333 if (r < 0)
334 return 0;
335
8411d2a2
LP
336 /* We ignore the passed value if anonymous authentication is
337 * on anyway. */
338 if (!b->anonymous_auth && u != b->ucred.uid)
2181a7f5
LP
339 return 0;
340
341 return 1;
342}
343
344static int bus_socket_auth_write(sd_bus *b, const char *t) {
345 char *p;
346 size_t l;
347
348 assert(b);
349 assert(t);
350
351 /* We only make use of the first iovec */
945c2931 352 assert(IN_SET(b->auth_index, 0, 1));
2181a7f5
LP
353
354 l = strlen(t);
355 p = malloc(b->auth_iovec[0].iov_len + l);
356 if (!p)
357 return -ENOMEM;
358
75f32f04 359 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
2181a7f5
LP
360 memcpy(p + b->auth_iovec[0].iov_len, t, l);
361
362 b->auth_iovec[0].iov_base = p;
363 b->auth_iovec[0].iov_len += l;
364
365 free(b->auth_buffer);
366 b->auth_buffer = p;
367 b->auth_index = 0;
368 return 0;
369}
370
371static int bus_socket_auth_write_ok(sd_bus *b) {
372 char t[3 + 32 + 2 + 1];
373
374 assert(b);
375
5ffa8c81 376 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
2181a7f5
LP
377
378 return bus_socket_auth_write(b, t);
379}
380
381static int bus_socket_auth_verify_server(sd_bus *b) {
382 char *e;
383 const char *line;
384 size_t l;
385 bool processed = false;
386 int r;
387
388 assert(b);
389
2b4ac889 390 if (b->rbuffer_size < 1)
2181a7f5
LP
391 return 0;
392
393 /* First char must be a NUL byte */
394 if (*(char*) b->rbuffer != 0)
395 return -EIO;
396
2b4ac889
LP
397 if (b->rbuffer_size < 3)
398 return 0;
399
2181a7f5
LP
400 /* Begin with the first line */
401 if (b->auth_rbegin <= 0)
402 b->auth_rbegin = 1;
403
404 for (;;) {
405 /* Check if line is complete */
406 line = (char*) b->rbuffer + b->auth_rbegin;
407 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
408 if (!e)
409 return processed;
410
411 l = e - line;
412
413 if (line_begins(line, l, "AUTH ANONYMOUS")) {
414
415 r = verify_anonymous_token(b, line + 14, l - 14);
416 if (r < 0)
417 return r;
418 if (r == 0)
419 r = bus_socket_auth_write(b, "REJECTED\r\n");
420 else {
421 b->auth = BUS_AUTH_ANONYMOUS;
422 r = bus_socket_auth_write_ok(b);
423 }
424
425 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
426
427 r = verify_external_token(b, line + 13, l - 13);
428 if (r < 0)
429 return r;
430 if (r == 0)
431 r = bus_socket_auth_write(b, "REJECTED\r\n");
432 else {
433 b->auth = BUS_AUTH_EXTERNAL;
434 r = bus_socket_auth_write_ok(b);
435 }
436
437 } else if (line_begins(line, l, "AUTH"))
438 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
439 else if (line_equals(line, l, "CANCEL") ||
440 line_begins(line, l, "ERROR")) {
441
442 b->auth = _BUS_AUTH_INVALID;
443 r = bus_socket_auth_write(b, "REJECTED\r\n");
444
445 } else if (line_equals(line, l, "BEGIN")) {
446
447 if (b->auth == _BUS_AUTH_INVALID)
448 r = bus_socket_auth_write(b, "ERROR\r\n");
449 else {
450 /* We can't leave from the auth phase
451 * before we haven't written
452 * everything queued, so let's check
453 * that */
454
455 if (bus_socket_auth_needs_write(b))
456 return 1;
457
458 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
459 memmove(b->rbuffer, e + 2, b->rbuffer_size);
460 return bus_start_running(b);
461 }
462
463 } else if (line_begins(line, l, "DATA")) {
464
465 if (b->auth == _BUS_AUTH_INVALID)
466 r = bus_socket_auth_write(b, "ERROR\r\n");
467 else {
468 if (b->auth == BUS_AUTH_ANONYMOUS)
469 r = verify_anonymous_token(b, line + 4, l - 4);
470 else
471 r = verify_external_token(b, line + 4, l - 4);
472
473 if (r < 0)
474 return r;
475 if (r == 0) {
476 b->auth = _BUS_AUTH_INVALID;
477 r = bus_socket_auth_write(b, "REJECTED\r\n");
478 } else
479 r = bus_socket_auth_write_ok(b);
480 }
481 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
c7db1984 482 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
2181a7f5
LP
483 r = bus_socket_auth_write(b, "ERROR\r\n");
484 else {
485 b->can_fds = true;
486 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
487 }
488 } else
489 r = bus_socket_auth_write(b, "ERROR\r\n");
490
491 if (r < 0)
492 return r;
493
494 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
495
496 processed = true;
497 }
498}
499
500static int bus_socket_auth_verify(sd_bus *b) {
501 assert(b);
502
503 if (b->is_server)
504 return bus_socket_auth_verify_server(b);
505 else
506 return bus_socket_auth_verify_client(b);
507}
508
a7e3212d
LP
509static int bus_socket_read_auth(sd_bus *b) {
510 struct msghdr mh;
7f4e6a1c 511 struct iovec iov = {};
a7e3212d
LP
512 size_t n;
513 ssize_t k;
514 int r;
515 void *p;
2181a7f5
LP
516 union {
517 struct cmsghdr cmsghdr;
d868f2a3 518 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
2181a7f5 519 } control;
15d5af81 520 bool handle_cmsg = false;
a7e3212d
LP
521
522 assert(b);
2181a7f5 523 assert(b->state == BUS_AUTHENTICATING);
a7e3212d
LP
524
525 r = bus_socket_auth_verify(b);
526 if (r != 0)
527 return r;
528
9607d947 529 n = MAX(256u, b->rbuffer_size * 2);
a7e3212d
LP
530
531 if (n > BUS_AUTH_SIZE_MAX)
532 n = BUS_AUTH_SIZE_MAX;
533
534 if (b->rbuffer_size >= n)
535 return -ENOBUFS;
536
537 p = realloc(b->rbuffer, n);
538 if (!p)
539 return -ENOMEM;
540
541 b->rbuffer = p;
542
a7e3212d
LP
543 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
544 iov.iov_len = n - b->rbuffer_size;
545
15d5af81
LP
546 if (b->prefer_readv)
547 k = readv(b->input_fd, &iov, 1);
548 else {
549 zero(mh);
550 mh.msg_iov = &iov;
551 mh.msg_iovlen = 1;
552 mh.msg_control = &control;
553 mh.msg_controllen = sizeof(control);
554
555 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
556 if (k < 0 && errno == ENOTSOCK) {
557 b->prefer_readv = true;
558 k = readv(b->input_fd, &iov, 1);
559 } else
560 handle_cmsg = true;
561 }
a7e3212d
LP
562 if (k < 0)
563 return errno == EAGAIN ? 0 : -errno;
564 if (k == 0)
565 return -ECONNRESET;
566
567 b->rbuffer_size += k;
568
2a1288ff
LP
569 if (handle_cmsg) {
570 struct cmsghdr *cmsg;
571
572 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
573 if (cmsg->cmsg_level == SOL_SOCKET &&
574 cmsg->cmsg_type == SCM_RIGHTS) {
575 int j;
576
577 /* Whut? We received fds during the auth
578 * protocol? Somebody is playing games with
579 * us. Close them all, and fail */
580 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
581 close_many((int*) CMSG_DATA(cmsg), j);
582 return -EIO;
d868f2a3
ZJS
583 } else
584 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
585 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 586 }
2181a7f5 587
a7e3212d
LP
588 r = bus_socket_auth_verify(b);
589 if (r != 0)
590 return r;
591
592 return 1;
593}
594
8f04d2eb 595void bus_socket_setup(sd_bus *b) {
a7e3212d
LP
596 assert(b);
597
aec6d91f 598 /* Increase the buffers to 8 MB */
6ae22ffb
LP
599 (void) fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
600 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
a7e3212d 601
e1d337d4 602 b->message_version = 1;
0f437184 603 b->message_endian = 0;
8f04d2eb 604}
e1d337d4 605
8f04d2eb 606static void bus_get_peercred(sd_bus *b) {
c4e6556c
ZJS
607 int r;
608
8f04d2eb 609 assert(b);
18ac4643
LP
610 assert(!b->ucred_valid);
611 assert(!b->label);
612 assert(b->n_groups == (size_t) -1);
8f04d2eb
LP
613
614 /* Get the peer for socketpair() sockets */
eff05270 615 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
c4e6556c
ZJS
616
617 /* Get the SELinux context of the peer */
db7d1dca 618 r = getpeersec(b->input_fd, &b->label);
18ac4643 619 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
db7d1dca 620 log_debug_errno(r, "Failed to determine peer security context: %m");
18ac4643
LP
621
622 /* Get the list of auxiliary groups of the peer */
623 r = getpeergroups(b->input_fd, &b->groups);
c599b325 624 if (r >= 0)
18ac4643 625 b->n_groups = (size_t) r;
c599b325
ZJS
626 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
627 log_debug_errno(r, "Failed to determine peer's group list: %m");
a7e3212d
LP
628}
629
2181a7f5 630static int bus_socket_start_auth_client(sd_bus *b) {
a7e3212d 631 size_t l;
2181a7f5 632 const char *auth_suffix, *auth_prefix;
a7e3212d
LP
633
634 assert(b);
635
2181a7f5
LP
636 if (b->anonymous_auth) {
637 auth_prefix = "\0AUTH ANONYMOUS ";
a7e3212d 638
2181a7f5
LP
639 /* For ANONYMOUS auth we send some arbitrary "trace" string */
640 l = 9;
641 b->auth_buffer = hexmem("anonymous", l);
642 } else {
5ffa8c81 643 char text[DECIMAL_STR_MAX(uid_t) + 1];
a7e3212d 644
2181a7f5 645 auth_prefix = "\0AUTH EXTERNAL ";
a7e3212d 646
5ffa8c81 647 xsprintf(text, UID_FMT, geteuid());
a7e3212d 648
2181a7f5
LP
649 l = strlen(text);
650 b->auth_buffer = hexmem(text, l);
651 }
652
653 if (!b->auth_buffer)
a7e3212d
LP
654 return -ENOMEM;
655
c7db1984 656 if (b->accept_fd)
2181a7f5
LP
657 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
658 else
659 auth_suffix = "\r\nBEGIN\r\n";
a7e3212d
LP
660
661 b->auth_iovec[0].iov_base = (void*) auth_prefix;
2181a7f5
LP
662 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
663 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
a7e3212d
LP
664 b->auth_iovec[1].iov_len = l * 2;
665 b->auth_iovec[2].iov_base = (void*) auth_suffix;
666 b->auth_iovec[2].iov_len = strlen(auth_suffix);
a7e3212d
LP
667
668 return bus_socket_write_auth(b);
669}
670
a7893c6b 671int bus_socket_start_auth(sd_bus *b) {
2181a7f5
LP
672 assert(b);
673
8f04d2eb
LP
674 bus_get_peercred(b);
675
3e0e196e 676 bus_set_state(b, BUS_AUTHENTICATING);
036d61b3 677 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
2181a7f5 678
9ab32f9d 679 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 680 b->accept_fd = false;
2181a7f5 681
9ab32f9d
LP
682 if (b->output_fd != b->input_fd)
683 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 684 b->accept_fd = false;
e82c9509 685
2181a7f5
LP
686 if (b->is_server)
687 return bus_socket_read_auth(b);
688 else
689 return bus_socket_start_auth_client(b);
690}
691
8a5cd31e
LP
692static int bus_socket_inotify_setup(sd_bus *b) {
693 _cleanup_free_ int *new_watches = NULL;
694 _cleanup_free_ char *absolute = NULL;
695 size_t n_allocated = 0, n = 0, done = 0, i;
696 unsigned max_follow = 32;
697 const char *p;
698 int wd, r;
699
700 assert(b);
701 assert(b->watch_bind);
702 assert(b->sockaddr.sa.sa_family == AF_UNIX);
703 assert(b->sockaddr.un.sun_path[0] != 0);
704
705 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
706 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
707 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
708 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
709 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
710 * components. */
711
712 if (b->inotify_fd < 0) {
713 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
714 if (b->inotify_fd < 0)
715 return -errno;
716 }
717
718 /* Make sure the path is NUL terminated */
719 p = strndupa(b->sockaddr.un.sun_path, sizeof(b->sockaddr.un.sun_path));
720
721 /* Make sure the path is absolute */
722 r = path_make_absolute_cwd(p, &absolute);
723 if (r < 0)
724 goto fail;
725
726 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
727 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
728 * they are removed or renamed. */
729
730 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
731 r = -ENOMEM;
732 goto fail;
733 }
734
735 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
736 * always exists */
737 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
738 if (wd < 0) {
739 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
740 goto fail;
741 } else
742 new_watches[n++] = wd;
743
744 for (;;) {
745 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
746 size_t n_slashes, n_component;
747 char *c = NULL;
748
749 n_slashes = strspn(absolute + done, "/");
750 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
751
752 if (n_component == 0) /* The end */
753 break;
754
755 component = strndup(absolute + done, n_component);
756 if (!component) {
757 r = -ENOMEM;
758 goto fail;
759 }
760
761 /* A trailing slash? That's a directory, and not a socket then */
762 if (path_equal(component, "/")) {
763 r = -EISDIR;
764 goto fail;
765 }
766
767 /* A single dot? Let's eat this up */
768 if (path_equal(component, "/.")) {
769 done += n_component;
770 continue;
771 }
772
773 prefix = strndup(absolute, done + n_component);
774 if (!prefix) {
775 r = -ENOMEM;
776 goto fail;
777 }
778
779 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
780 r = -ENOMEM;
781 goto fail;
782 }
783
784 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
785 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
786
787 if (wd < 0) {
788 if (IN_SET(errno, ENOENT, ELOOP))
789 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
790
791 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", isempty(prefix) ? "/" : prefix);
792 goto fail;
793 } else
794 new_watches[n++] = wd;
795
796 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
797 r = readlink_malloc(prefix, &destination);
798 if (r == -EINVAL) { /* not a symlink */
799 done += n_component;
800 continue;
801 }
802 if (r < 0)
803 goto fail;
804
805 if (isempty(destination)) { /* Empty symlink target? Yuck! */
806 r = -EINVAL;
807 goto fail;
808 }
809
810 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
811 r = -ELOOP;
812 goto fail;
813 }
814
815 if (path_is_absolute(destination)) {
816 /* For absolute symlinks we build the new path and start anew */
817 c = strjoin(destination, absolute + done + n_component);
818 done = 0;
819 } else {
820 _cleanup_free_ char *t = NULL;
821
822 /* For relative symlinks we replace the last component, and try again */
823 t = strndup(absolute, done);
824 if (!t)
825 return -ENOMEM;
826
827 c = strjoin(t, "/", destination, absolute + done + n_component);
828 }
829 if (!c) {
830 r = -ENOMEM;
831 goto fail;
832 }
833
834 free(absolute);
835 absolute = c;
836
837 max_follow--;
838 }
839
840 /* And now, let's remove all watches from the previous iteration we don't need anymore */
841 for (i = 0; i < b->n_inotify_watches; i++) {
842 bool found = false;
843 size_t j;
844
845 for (j = 0; j < n; j++)
846 if (new_watches[j] == b->inotify_watches[i]) {
847 found = true;
848 break;
849 }
850
851 if (found)
852 continue;
853
854 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
855 }
856
857 free_and_replace(b->inotify_watches, new_watches);
858 b->n_inotify_watches = n;
859
860 return 0;
861
862fail:
863 bus_close_inotify_fd(b);
864 return r;
865}
866
a7e3212d 867int bus_socket_connect(sd_bus *b) {
8a5cd31e 868 bool inotify_done = false;
a7e3212d
LP
869 int r;
870
871 assert(b);
a7e3212d 872
8a5cd31e
LP
873 for (;;) {
874 assert(b->input_fd < 0);
875 assert(b->output_fd < 0);
876 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
a7e3212d 877
8a5cd31e
LP
878 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
879 if (b->input_fd < 0)
880 return -errno;
e82c9509 881
8a5cd31e
LP
882 b->output_fd = b->input_fd;
883 bus_socket_setup(b);
a7e3212d 884
8a5cd31e
LP
885 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
886 if (errno == EINPROGRESS) {
a7e3212d 887
8a5cd31e
LP
888 /* If we have any inotify watches open, close them now, we don't need them anymore, as
889 * we have successfully initiated a connection */
890 bus_close_inotify_fd(b);
891
892 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
893 * we start parsing the address string. The only reason we set the state explicitly
894 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
3e0e196e 895 bus_set_state(b, BUS_OPENING);
8a5cd31e
LP
896 return 1;
897 }
898
899 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
900 b->watch_bind &&
901 b->sockaddr.sa.sa_family == AF_UNIX &&
902 b->sockaddr.un.sun_path[0] != 0) {
903
904 /* This connection attempt failed, let's release the socket for now, and start with a
905 * fresh one when reconnecting. */
906 bus_close_io_fds(b);
907
908 if (inotify_done) {
909 /* inotify set up already, don't do it again, just return now, and remember
910 * that we are waiting for inotify events now. */
3e0e196e 911 bus_set_state(b, BUS_WATCH_BIND);
8a5cd31e
LP
912 return 1;
913 }
914
915 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
916 r = bus_socket_inotify_setup(b);
917 if (r < 0)
918 return r;
919
920 /* Let's now try to connect a second time, because in theory there's otherwise a race
921 * here: the socket might have been created in the time between our first connect() and
922 * the time we set up the inotify logic. But let's remember that we set up inotify now,
923 * so that we don't do the connect() more than twice. */
924 inotify_done = true;
925
926 } else
927 return -errno;
928 } else
929 break;
a7e3212d
LP
930 }
931
8a5cd31e
LP
932 /* Yay, established, we don't need no inotify anymore! */
933 bus_close_inotify_fd(b);
934
a7e3212d
LP
935 return bus_socket_start_auth(b);
936}
937
938int bus_socket_exec(sd_bus *b) {
e82c9509 939 int s[2], r;
a7e3212d
LP
940
941 assert(b);
e82c9509
LP
942 assert(b->input_fd < 0);
943 assert(b->output_fd < 0);
a7e3212d 944 assert(b->exec_path);
392cf1d0 945 assert(b->busexec_pid == 0);
a7e3212d 946
e82c9509
LP
947 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
948 if (r < 0)
a7e3212d
LP
949 return -errno;
950
392cf1d0 951 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &b->busexec_pid);
4c253ed1 952 if (r < 0) {
3d94f76c 953 safe_close_pair(s);
4c253ed1 954 return r;
a7e3212d 955 }
4c253ed1 956 if (r == 0) {
a7e3212d
LP
957 /* Child */
958
a7e3212d
LP
959 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
960 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
961
945c2931 962 if (!IN_SET(s[1], STDIN_FILENO, STDOUT_FILENO))
03e334a1 963 safe_close(s[1]);
a7e3212d 964
6ae22ffb
LP
965 (void) fd_cloexec(STDIN_FILENO, false);
966 (void) fd_cloexec(STDOUT_FILENO, false);
967 (void) fd_nonblock(STDIN_FILENO, false);
968 (void) fd_nonblock(STDOUT_FILENO, false);
a7e3212d
LP
969
970 if (b->exec_argv)
971 execvp(b->exec_path, b->exec_argv);
972 else {
973 const char *argv[] = { b->exec_path, NULL };
974 execvp(b->exec_path, (char**) argv);
975 }
976
977 _exit(EXIT_FAILURE);
978 }
979
03e334a1 980 safe_close(s[1]);
e82c9509 981 b->output_fd = b->input_fd = s[0];
a7e3212d 982
8f04d2eb 983 bus_socket_setup(b);
e1d337d4 984
a7e3212d
LP
985 return bus_socket_start_auth(b);
986}
987
988int bus_socket_take_fd(sd_bus *b) {
a7e3212d
LP
989 assert(b);
990
8f04d2eb 991 bus_socket_setup(b);
a7e3212d
LP
992
993 return bus_socket_start_auth(b);
994}
995
996int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
a7e3212d
LP
997 struct iovec *iov;
998 ssize_t k;
999 size_t n;
1000 unsigned j;
bc7fd8cd 1001 int r;
a7e3212d
LP
1002
1003 assert(bus);
1004 assert(m);
1005 assert(idx);
945c2931 1006 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 1007
6629161f 1008 if (*idx >= BUS_MESSAGE_SIZE(m))
a7e3212d 1009 return 0;
a7e3212d 1010
bc7fd8cd
LP
1011 r = bus_message_setup_iovec(m);
1012 if (r < 0)
1013 return r;
2100fa10 1014
a7e3212d
LP
1015 n = m->n_iovec * sizeof(struct iovec);
1016 iov = alloca(n);
75f32f04 1017 memcpy_safe(iov, m->iovec, n);
a7e3212d
LP
1018
1019 j = 0;
1020 iovec_advance(iov, &j, *idx);
1021
15d5af81
LP
1022 if (bus->prefer_writev)
1023 k = writev(bus->output_fd, iov, m->n_iovec);
1024 else {
7f4e6a1c
ZJS
1025 struct msghdr mh = {
1026 .msg_iov = iov,
1027 .msg_iovlen = m->n_iovec,
1028 };
15d5af81 1029
f29eef2e 1030 if (m->n_fds > 0 && *idx == 0) {
15d5af81 1031 struct cmsghdr *control;
15d5af81 1032
7f4e6a1c
ZJS
1033 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
1034 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
15d5af81
LP
1035 control->cmsg_level = SOL_SOCKET;
1036 control->cmsg_type = SCM_RIGHTS;
15d5af81
LP
1037 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1038 }
1039
15d5af81
LP
1040 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1041 if (k < 0 && errno == ENOTSOCK) {
1042 bus->prefer_writev = true;
1043 k = writev(bus->output_fd, iov, m->n_iovec);
1044 }
1045 }
a7e3212d 1046
a7e3212d
LP
1047 if (k < 0)
1048 return errno == EAGAIN ? 0 : -errno;
1049
1050 *idx += (size_t) k;
1051 return 1;
1052}
1053
1054static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1055 uint32_t a, b;
1056 uint8_t e;
1057 uint64_t sum;
1058
1059 assert(bus);
1060 assert(need);
945c2931 1061 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
1062
1063 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1064 *need = sizeof(struct bus_header) + 8;
1065
1066 /* Minimum message size:
1067 *
1068 * Header +
1069 *
1070 * Method Call: +2 string headers
1071 * Signal: +3 string headers
1072 * Method Error: +1 string headers
1073 * +1 uint32 headers
1074 * Method Reply: +1 uint32 headers
1075 *
1076 * A string header is at least 9 bytes
1077 * A uint32 header is at least 8 bytes
1078 *
1079 * Hence the minimum message size of a valid message
1080 * is header + 8 bytes */
1081
1082 return 0;
1083 }
1084
1085 a = ((const uint32_t*) bus->rbuffer)[1];
1086 b = ((const uint32_t*) bus->rbuffer)[3];
1087
1088 e = ((const uint8_t*) bus->rbuffer)[0];
0461f8cd 1089 if (e == BUS_LITTLE_ENDIAN) {
a7e3212d
LP
1090 a = le32toh(a);
1091 b = le32toh(b);
0461f8cd 1092 } else if (e == BUS_BIG_ENDIAN) {
a7e3212d
LP
1093 a = be32toh(a);
1094 b = be32toh(b);
1095 } else
1096 return -EBADMSG;
1097
1098 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
1099 if (sum >= BUS_MESSAGE_SIZE_MAX)
1100 return -ENOBUFS;
1101
1102 *need = (size_t) sum;
1103 return 0;
1104}
1105
7d22c717 1106static int bus_socket_make_message(sd_bus *bus, size_t size) {
a7e3212d
LP
1107 sd_bus_message *t;
1108 void *b;
1109 int r;
1110
1111 assert(bus);
a7e3212d 1112 assert(bus->rbuffer_size >= size);
945c2931 1113 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 1114
7adc46fc
LP
1115 r = bus_rqueue_make_room(bus);
1116 if (r < 0)
1117 return r;
1118
a7e3212d
LP
1119 if (bus->rbuffer_size > size) {
1120 b = memdup((const uint8_t*) bus->rbuffer + size,
1121 bus->rbuffer_size - size);
1122 if (!b)
1123 return -ENOMEM;
1124 } else
1125 b = NULL;
1126
df2d202e
LP
1127 r = bus_message_from_malloc(bus,
1128 bus->rbuffer, size,
a7e3212d 1129 bus->fds, bus->n_fds,
038f9863 1130 NULL,
a7e3212d
LP
1131 &t);
1132 if (r < 0) {
1133 free(b);
1134 return r;
1135 }
1136
1137 bus->rbuffer = b;
1138 bus->rbuffer_size -= size;
1139
1140 bus->fds = NULL;
1141 bus->n_fds = 0;
1142
7adc46fc 1143 bus->rqueue[bus->rqueue_size++] = t;
7d22c717 1144
a7e3212d
LP
1145 return 1;
1146}
1147
7d22c717 1148int bus_socket_read_message(sd_bus *bus) {
a7e3212d 1149 struct msghdr mh;
7f4e6a1c 1150 struct iovec iov = {};
a7e3212d
LP
1151 ssize_t k;
1152 size_t need;
1153 int r;
1154 void *b;
1155 union {
1156 struct cmsghdr cmsghdr;
d868f2a3 1157 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
a7e3212d 1158 } control;
4d3a5b10 1159 bool handle_cmsg = false;
a7e3212d
LP
1160
1161 assert(bus);
945c2931 1162 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
1163
1164 r = bus_socket_read_message_need(bus, &need);
1165 if (r < 0)
1166 return r;
1167
1168 if (bus->rbuffer_size >= need)
7d22c717 1169 return bus_socket_make_message(bus, need);
a7e3212d
LP
1170
1171 b = realloc(bus->rbuffer, need);
1172 if (!b)
1173 return -ENOMEM;
1174
1175 bus->rbuffer = b;
1176
a7e3212d
LP
1177 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
1178 iov.iov_len = need - bus->rbuffer_size;
1179
15d5af81
LP
1180 if (bus->prefer_readv)
1181 k = readv(bus->input_fd, &iov, 1);
1182 else {
1183 zero(mh);
1184 mh.msg_iov = &iov;
1185 mh.msg_iovlen = 1;
1186 mh.msg_control = &control;
1187 mh.msg_controllen = sizeof(control);
1188
1189 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
1190 if (k < 0 && errno == ENOTSOCK) {
1191 bus->prefer_readv = true;
1192 k = readv(bus->input_fd, &iov, 1);
1193 } else
1194 handle_cmsg = true;
1195 }
a7e3212d
LP
1196 if (k < 0)
1197 return errno == EAGAIN ? 0 : -errno;
1198 if (k == 0)
1199 return -ECONNRESET;
1200
1201 bus->rbuffer_size += k;
1202
2a1288ff
LP
1203 if (handle_cmsg) {
1204 struct cmsghdr *cmsg;
1205
1206 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
1207 if (cmsg->cmsg_level == SOL_SOCKET &&
1208 cmsg->cmsg_type == SCM_RIGHTS) {
1209 int n, *f;
1210
1211 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1212
1213 if (!bus->can_fds) {
1214 /* Whut? We received fds but this
1215 * isn't actually enabled? Close them,
1216 * and fail */
1217
1218 close_many((int*) CMSG_DATA(cmsg), n);
1219 return -EIO;
1220 }
1221
a0f5ab70 1222 f = realloc(bus->fds, sizeof(int) * (bus->n_fds + n));
15d5af81
LP
1223 if (!f) {
1224 close_many((int*) CMSG_DATA(cmsg), n);
1225 return -ENOMEM;
1226 }
1227
75f32f04 1228 memcpy_safe(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
15d5af81
LP
1229 bus->fds = f;
1230 bus->n_fds += n;
d868f2a3
ZJS
1231 } else
1232 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1233 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 1234 }
a7e3212d
LP
1235
1236 r = bus_socket_read_message_need(bus, &need);
1237 if (r < 0)
1238 return r;
1239
1240 if (bus->rbuffer_size >= need)
7d22c717 1241 return bus_socket_make_message(bus, need);
a7e3212d
LP
1242
1243 return 1;
1244}
1245
1246int bus_socket_process_opening(sd_bus *b) {
1247 int error = 0;
1248 socklen_t slen = sizeof(error);
b92bea5d
ZJS
1249 struct pollfd p = {
1250 .fd = b->output_fd,
1251 .events = POLLOUT,
1252 };
a7e3212d
LP
1253 int r;
1254
a7e3212d
LP
1255 assert(b->state == BUS_OPENING);
1256
a7e3212d
LP
1257 r = poll(&p, 1, 0);
1258 if (r < 0)
1259 return -errno;
1260
1261 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1262 return 0;
1263
e82c9509 1264 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
a7e3212d
LP
1265 if (r < 0)
1266 b->last_connect_error = errno;
1267 else if (error != 0)
1268 b->last_connect_error = error;
1269 else if (p.revents & (POLLERR|POLLHUP))
1270 b->last_connect_error = ECONNREFUSED;
1271 else
1272 return bus_socket_start_auth(b);
1273
1274 return bus_next_address(b);
1275}
1276
1277int bus_socket_process_authenticating(sd_bus *b) {
1278 int r;
1279
1280 assert(b);
1281 assert(b->state == BUS_AUTHENTICATING);
1282
1283 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1284 return -ETIMEDOUT;
1285
1286 r = bus_socket_write_auth(b);
1287 if (r != 0)
1288 return r;
1289
1290 return bus_socket_read_auth(b);
1291}
8a5cd31e
LP
1292
1293int bus_socket_process_watch_bind(sd_bus *b) {
1294 int r, q;
1295
1296 assert(b);
1297 assert(b->state == BUS_WATCH_BIND);
1298 assert(b->inotify_fd >= 0);
1299
1300 r = flush_fd(b->inotify_fd);
1301 if (r <= 0)
1302 return r;
1303
1304 log_debug("Got inotify event on bus %s.", strna(b->description));
1305
1306 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1307 * to it again */
1308
1309 r = bus_socket_connect(b);
1310 if (r < 0)
1311 return r;
1312
1313 q = bus_attach_io_events(b);
1314 if (q < 0)
1315 return q;
1316
1317 q = bus_attach_inotify_event(b);
1318 if (q < 0)
1319 return q;
1320
1321 return r;
1322}