Repository navigation
Expand file tree
/
Copy pathcommon.c
More file actions
71 lines (63 loc) · 1.77 KB
/
Copy pathcommon.c
File metadata and controls
71 lines (63 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "common.h"
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
static int write_all(int fd, const void *buffer, size_t length) {
const unsigned char *p = buffer;
while (length > 0) {
ssize_t n = send(fd, p, length, 0);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) return -1;
p += (size_t)n;
length -= (size_t)n;
}
return 0;
}
static int read_all(int fd, void *buffer, size_t length) {
unsigned char *p = buffer;
while (length > 0) {
ssize_t n = recv(fd, p, length, 0);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) return -1;
p += (size_t)n;
length -= (size_t)n;
}
return 0;
}
int send_u32(int fd, uint32_t value) {
value = htonl(value);
return write_all(fd, &value, sizeof(value));
}
int recv_u32(int fd, uint32_t *value) {
uint32_t wire;
if (read_all(fd, &wire, sizeof(wire)) < 0) return -1;
*value = ntohl(wire);
return 0;
}
int send_blob(int fd, const void *data, uint32_t length) {
if (send_u32(fd, length) < 0) return -1;
return length == 0 ? 0 : write_all(fd, data, length);
}
int send_string(int fd, const char *text) {
size_t length = strlen(text);
if (length > UINT32_MAX) return -1;
return send_blob(fd, text, (uint32_t)length);
}
int recv_blob(int fd, char **data, uint32_t *length, uint32_t maximum) {
uint32_t n;
char *result;
if (recv_u32(fd, &n) < 0 || n > maximum) return -1;
result = malloc((size_t)n + 1);
if (!result) return -1;
if (n > 0 && read_all(fd, result, n) < 0) {
free(result);
return -1;
}
result[n] = '\0';
*data = result;
if (length) *length = n;
return 0;
}