2
* Copyright (C) 2011-2012 Red Hat, Inc.
4
* This file is part of LVM2.
6
* This copyrighted material is made available to anyone wishing to use,
7
* modify, copy, or redistribute it subject to the terms and conditions
8
* of the GNU Lesser General Public License v.2.1.
10
* You should have received a copy of the GNU Lesser General Public License
11
* along with this program; if not, write to the Free Software Foundation,
12
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
#include "daemon-shared.h"
23
#include "libdevmapper.h"
26
* Read a single message from a (socket) filedescriptor. Messages are delimited
27
* by blank lines. This call will block until all of a message is received. The
28
* memory will be allocated from heap. Upon error, all memory is freed and the
29
* buffer pointer is set to NULL.
31
* See also write_buffer about blocking (read_buffer has identical behaviour).
33
int read_buffer(int fd, char **buffer) {
37
*buffer = malloc(buffersize + 1);
40
int result = read(fd, (*buffer) + bytes, buffersize - bytes);
45
goto fail; /* we should never encounter EOF here */
47
if (result < 0 && errno != EAGAIN && errno != EWOULDBLOCK)
50
if (!strncmp((*buffer) + bytes - 4, "\n##\n", 4)) {
51
*(*buffer + bytes - 4) = 0;
52
break; /* success, we have the full message now */
55
if (bytes == buffersize) {
57
if (!(new = realloc(*buffer, buffersize + 1)))
62
/* TODO call select here if we encountered EAGAIN/EWOULDBLOCK */
72
* Write a buffer to a filedescriptor. Keep trying. Blocks (even on
73
* SOCK_NONBLOCK) until all of the write went through.
75
* TODO use select on EWOULDBLOCK/EAGAIN to avoid useless spinning
77
int write_buffer(int fd, const char *buffer, int length) {
78
static const char terminate[] = "\n##\n";
83
int result = write(fd, buffer + written, length - written);
86
if (result < 0 && errno != EWOULDBLOCK && errno != EAGAIN)
87
return 0; /* too bad */
88
if (written == length) {
103
char *format_buffer(const char *what, const char *id, va_list ap)
109
dm_asprintf(&buffer, "%s = \"%s\"\n", what, id);
110
if (!buffer) goto fail;
112
while ((next = va_arg(ap, char *))) {
114
assert(strchr(next, '='));
115
keylen = strchr(next, '=') - next;
116
if (strstr(next, "%d")) {
117
int value = va_arg(ap, int);
118
dm_asprintf(&buffer, "%s%.*s= %d\n", buffer, keylen, next, value);
120
} else if (strstr(next, "%s")) {
121
char *value = va_arg(ap, char *);
122
dm_asprintf(&buffer, "%s%.*s= \"%s\"\n", buffer, keylen, next, value);
124
} else if (strstr(next, "%b")) {
125
char *block = va_arg(ap, char *);
128
dm_asprintf(&buffer, "%s%.*s%s", buffer, keylen, next, block);
131
dm_asprintf(&buffer, "%s%s", buffer, next);
134
if (!buffer) goto fail;