2 * Copyright (C) 2015 Red Hat, Inc.
4 * This file is part of the device-mapper multipath userspace tools.
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public License
8 * as published by the Free Software Foundation; either version 2.1
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <sys/types.h>
24 #include <sys/socket.h>
30 #include "mpath_cmd.h"
33 * keep reading until its all read
35 static ssize_t read_all(int fd, void *buf, size_t len, unsigned int timeout)
45 ret = poll(&pfd, 1, timeout);
53 } else if (!(pfd.revents & POLLIN))
55 n = recv(fd, buf, len, 0);
57 if ((errno == EINTR) || (errno == EAGAIN))
63 buf = n + (char *)buf;
71 * keep writing until it's all sent
73 static size_t write_all(int fd, const void *buf, size_t len)
78 ssize_t n = send(fd, buf, len, MSG_NOSIGNAL);
80 if ((errno == EINTR) || (errno == EAGAIN))
86 buf = n + (const char *)buf;
94 * connect to a unix domain socket
96 int mpath_connect(void)
99 struct sockaddr_un addr;
101 memset(&addr, 0, sizeof(addr));
102 addr.sun_family = AF_LOCAL;
103 addr.sun_path[0] = '\0';
104 len = strlen(DEFAULT_SOCKET) + 1 + sizeof(sa_family_t);
105 strncpy(&addr.sun_path[1], DEFAULT_SOCKET, len);
107 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
111 if (connect(fd, (struct sockaddr *)&addr, len) == -1) {
119 int mpath_disconnect(int fd)
124 ssize_t mpath_recv_reply_len(int fd, unsigned int timeout)
129 ret = read_all(fd, &len, sizeof(len), timeout);
132 if (ret != sizeof(len)) {
136 if (len <= 0 || len >= MAX_REPLY_LEN) {
143 int mpath_recv_reply_data(int fd, char *reply, size_t len,
144 unsigned int timeout)
148 ret = read_all(fd, reply, len, timeout);
155 reply[len - 1] = '\0';
159 int mpath_recv_reply(int fd, char **reply, unsigned int timeout)
165 len = mpath_recv_reply_len(fd, timeout);
168 *reply = malloc(len);
171 err = mpath_recv_reply_data(fd, *reply, len, timeout);
180 int mpath_send_cmd(int fd, const char *cmd)
185 len = strlen(cmd) + 1;
188 if (write_all(fd, &len, sizeof(len)) != sizeof(len))
190 if (len && write_all(fd, cmd, len) != len)
195 int mpath_process_cmd(int fd, const char *cmd, char **reply,
196 unsigned int timeout)
198 if (mpath_send_cmd(fd, cmd) != 0)
200 return mpath_recv_reply(fd, reply, timeout);