]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/reply-password/reply-password.c
efb68a354f08be4f98560ffe2b30087e25e04357
[thirdparty/systemd.git] / src / reply-password / reply-password.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <stddef.h>
5 #include <string.h>
6 #include <sys/socket.h>
7 #include <sys/un.h>
8
9 #include "fd-util.h"
10 #include "log.h"
11 #include "macro.h"
12 #include "socket-util.h"
13 #include "string-util.h"
14 #include "util.h"
15
16 static int send_on_socket(int fd, const char *socket_name, const void *packet, size_t size) {
17 union sockaddr_union sa = {
18 .un.sun_family = AF_UNIX,
19 };
20
21 assert(fd >= 0);
22 assert(socket_name);
23 assert(packet);
24
25 strncpy(sa.un.sun_path, socket_name, sizeof(sa.un.sun_path));
26
27 if (sendto(fd, packet, size, MSG_NOSIGNAL, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
28 return log_error_errno(errno, "Failed to send: %m");
29
30 return 0;
31 }
32
33 int main(int argc, char *argv[]) {
34 _cleanup_close_ int fd = -1;
35 char packet[LINE_MAX];
36 size_t length;
37 int r;
38
39 log_set_target(LOG_TARGET_AUTO);
40 log_parse_environment();
41 log_open();
42
43 if (argc != 3) {
44 log_error("Wrong number of arguments.");
45 return EXIT_FAILURE;
46 }
47
48 if (streq(argv[1], "1")) {
49
50 packet[0] = '+';
51 if (!fgets(packet+1, sizeof(packet)-1, stdin)) {
52 r = log_error_errno(errno, "Failed to read password: %m");
53 goto finish;
54 }
55
56 truncate_nl(packet+1);
57 length = 1 + strlen(packet+1) + 1;
58 } else if (streq(argv[1], "0")) {
59 packet[0] = '-';
60 length = 1;
61 } else {
62 log_error("Invalid first argument %s", argv[1]);
63 r = -EINVAL;
64 goto finish;
65 }
66
67 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
68 if (fd < 0) {
69 r = log_error_errno(errno, "socket() failed: %m");
70 goto finish;
71 }
72
73 r = send_on_socket(fd, argv[2], packet, length);
74
75 finish:
76 explicit_bzero(packet, sizeof(packet));
77
78 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
79 }