]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/reply-password/reply-password.c
util-lib: split our string related calls from util.[ch] into its own file string...
[thirdparty/systemd.git] / src / reply-password / reply-password.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <errno.h>
23 #include <stddef.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/un.h>
27
28 #include "log.h"
29 #include "macro.h"
30 #include "string-util.h"
31 #include "util.h"
32
33 static int send_on_socket(int fd, const char *socket_name, const void *packet, size_t size) {
34 union {
35 struct sockaddr sa;
36 struct sockaddr_un un;
37 } sa = {
38 .un.sun_family = AF_UNIX,
39 };
40
41 assert(fd >= 0);
42 assert(socket_name);
43 assert(packet);
44
45 strncpy(sa.un.sun_path, socket_name, sizeof(sa.un.sun_path));
46
47 if (sendto(fd, packet, size, MSG_NOSIGNAL, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(socket_name)) < 0)
48 return log_error_errno(errno, "Failed to send: %m");
49
50 return 0;
51 }
52
53 int main(int argc, char *argv[]) {
54 _cleanup_close_ int fd = -1;
55 char packet[LINE_MAX];
56 size_t length;
57 int r;
58
59 log_set_target(LOG_TARGET_AUTO);
60 log_parse_environment();
61 log_open();
62
63 if (argc != 3) {
64 log_error("Wrong number of arguments.");
65 return EXIT_FAILURE;
66 }
67
68 if (streq(argv[1], "1")) {
69
70 packet[0] = '+';
71 if (!fgets(packet+1, sizeof(packet)-1, stdin)) {
72 r = log_error_errno(errno, "Failed to read password: %m");
73 goto finish;
74 }
75
76 truncate_nl(packet+1);
77 length = 1 + strlen(packet+1) + 1;
78 } else if (streq(argv[1], "0")) {
79 packet[0] = '-';
80 length = 1;
81 } else {
82 log_error("Invalid first argument %s", argv[1]);
83 r = -EINVAL;
84 goto finish;
85 }
86
87 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
88 if (fd < 0) {
89 r = log_error_errno(errno, "socket() failed: %m");
90 goto finish;
91 }
92
93 r = send_on_socket(fd, argv[2], packet, length);
94
95 finish:
96 memory_erase(packet, sizeof(packet));
97
98 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
99 }