]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/reply-password/reply-password.c
Merge pull request #7411 from joergsteffens/tapechanger
[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 "alloc-util.h"
10 #include "def.h"
11 #include "fd-util.h"
12 #include "fileio.h"
13 #include "log.h"
14 #include "macro.h"
15 #include "socket-util.h"
16 #include "string-util.h"
17 #include "util.h"
18
19 static int send_on_socket(int fd, const char *socket_name, const void *packet, size_t size) {
20 union sockaddr_union sa = {};
21 int salen;
22
23 assert(fd >= 0);
24 assert(socket_name);
25 assert(packet);
26
27 salen = sockaddr_un_set_path(&sa.un, socket_name);
28 if (salen < 0)
29 return log_error_errno(salen, "Specified socket path for AF_UNIX socket invalid, refusing: %s", socket_name);
30
31 if (sendto(fd, packet, size, MSG_NOSIGNAL, &sa.sa, salen) < 0)
32 return log_error_errno(errno, "Failed to send: %m");
33
34 return 0;
35 }
36
37 int main(int argc, char *argv[]) {
38 _cleanup_free_ char *packet = NULL;
39 _cleanup_close_ int fd = -1;
40 size_t length;
41 int r;
42
43 log_set_target(LOG_TARGET_AUTO);
44 log_parse_environment();
45 log_open();
46
47 if (argc != 3) {
48 log_error("Wrong number of arguments.");
49 return EXIT_FAILURE;
50 }
51
52 if (streq(argv[1], "1")) {
53 _cleanup_string_free_erase_ char *line = NULL;
54
55 r = read_line(stdin, LONG_LINE_MAX, &line);
56 if (r < 0) {
57 log_error_errno(r, "Failed to read password: %m");
58 goto finish;
59 }
60 if (r == 0) {
61 log_error("Got EOF while reading password.");
62 r = -EIO;
63 goto finish;
64 }
65
66 packet = strjoin("+", line);
67 if (!packet) {
68 r = log_oom();
69 goto finish;
70 }
71
72 length = 1 + strlen(line) + 1;
73
74 } else if (streq(argv[1], "0")) {
75 packet = strdup("-");
76 if (!packet) {
77 r = log_oom();
78 goto finish;
79 }
80
81 length = 1;
82
83 } else {
84 log_error("Invalid first argument %s", argv[1]);
85 r = -EINVAL;
86 goto finish;
87 }
88
89 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
90 if (fd < 0) {
91 r = log_error_errno(errno, "socket() failed: %m");
92 goto finish;
93 }
94
95 r = send_on_socket(fd, argv[2], packet, length);
96
97 finish:
98 explicit_bzero(packet, length);
99
100 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
101 }