forked from NetworkBlockDevice/nbd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cliserv.c
111 lines (101 loc) · 2.18 KB
/
cliserv.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <config.h>
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cliserv.h>
#include <nbd-debug.h>
const u64 cliserv_magic = 0x00420281861253LL;
const u64 opts_magic = 0x49484156454F5054LL;
const u64 rep_magic = 0x3e889045565a9LL;
void setmysockopt(int sock) {
int size = 1;
#if 0
if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int)) < 0)
INFO("(no sockopt/1: %m)");
#endif
#ifdef IPPROTO_TCP
size = 1;
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &size, sizeof(int)) < 0)
INFO("(no sockopt/2: %m)");
#endif
#if 0
size = 1024;
if (setsockopt(sock, IPPROTO_TCP, TCP_MAXSEG, &size, sizeof(int)) < 0)
INFO("(no sockopt/3: %m)");
#endif
}
void err_nonfatal(const char *s) {
char s1[150], *s2;
strncpy(s1, s, sizeof(s1));
if ((s2 = strstr(s, "%m"))) {
strcpy(s1 + (s2 - s), strerror(errno));
s2 += 2;
strcpy(s1 + strlen(s1), s2);
}
#ifndef sun
/* Solaris doesn't have %h in syslog */
else if ((s2 = strstr(s, "%h"))) {
strcpy(s1 + (s2 - s), hstrerror(h_errno));
s2 += 2;
strcpy(s1 + strlen(s1), s2);
}
#endif
s1[sizeof(s1)-1] = '\0';
#ifdef ISSERVER
syslog(LOG_ERR, "%s", s1);
syslog(LOG_ERR, "Exiting.");
#endif
fprintf(stderr, "Error: %s\nExiting.\n", s1);
}
void err(const char *s) {
err_nonfatal(s);
exit(EXIT_FAILURE);
}
void logging(const char* name) {
#ifdef ISSERVER
openlog(name, LOG_PID, LOG_DAEMON);
#endif
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
}
#ifndef ntohll
#ifdef WORDS_BIGENDIAN
uint64_t ntohll(uint64_t a) {
return a;
}
#else
uint64_t ntohll(uint64_t a) {
u32 lo = a & 0xffffffff;
u32 hi = a >> 32U;
lo = ntohl(lo);
hi = ntohl(hi);
return ((uint64_t) lo) << 32U | hi;
}
#endif
#endif
/**
* Read data from a file descriptor into a buffer
*
* @param f a file descriptor
* @param buf a buffer
* @param len the number of bytes to be read
**/
void readit(int f, void *buf, size_t len) {
ssize_t res;
while (len > 0) {
DEBUG("*");
res = read(f, buf, len);
if (res > 0) {
len -= res;
buf += res;
} else if (res < 0) {
if(errno != EAGAIN) {
err("Read failed: %m");
}
} else {
err("Read failed: End of file");
}
}
}