]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/reply-password/reply-password.c
Merge pull request #6910 from ssahani/issue-6359
[thirdparty/systemd.git] / src / reply-password / reply-password.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2010 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 <errno.h>
22 #include <stddef.h>
23 #include <string.h>
24 #include <sys/socket.h>
25 #include <sys/un.h>
26
27 #include "fd-util.h"
28 #include "log.h"
29 #include "macro.h"
30 #include "socket-util.h"
31 #include "string-util.h"
32 #include "util.h"
33
34 static int send_on_socket(int fd, const char *socket_name, const void *packet, size_t size) {
35 union sockaddr_union sa = {
36 .un.sun_family = AF_UNIX,
37 };
38
39 assert(fd >= 0);
40 assert(socket_name);
41 assert(packet);
42
43 strncpy(sa.un.sun_path, socket_name, sizeof(sa.un.sun_path));
44
45 if (sendto(fd, packet, size, MSG_NOSIGNAL, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
46 return log_error_errno(errno, "Failed to send: %m");
47
48 return 0;
49 }
50
51 int main(int argc, char *argv[]) {
52 _cleanup_close_ int fd = -1;
53 char packet[LINE_MAX];
54 size_t length;
55 int r;
56
57 log_set_target(LOG_TARGET_AUTO);
58 log_parse_environment();
59 log_open();
60
61 if (argc != 3) {
62 log_error("Wrong number of arguments.");
63 return EXIT_FAILURE;
64 }
65
66 if (streq(argv[1], "1")) {
67
68 packet[0] = '+';
69 if (!fgets(packet+1, sizeof(packet)-1, stdin)) {
70 r = log_error_errno(errno, "Failed to read password: %m");
71 goto finish;
72 }
73
74 truncate_nl(packet+1);
75 length = 1 + strlen(packet+1) + 1;
76 } else if (streq(argv[1], "0")) {
77 packet[0] = '-';
78 length = 1;
79 } else {
80 log_error("Invalid first argument %s", argv[1]);
81 r = -EINVAL;
82 goto finish;
83 }
84
85 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
86 if (fd < 0) {
87 r = log_error_errno(errno, "socket() failed: %m");
88 goto finish;
89 }
90
91 r = send_on_socket(fd, argv[2], packet, length);
92
93 finish:
94 explicit_bzero(packet, sizeof(packet));
95
96 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
97 }