7 #include <sys/socket.h>
10 #include <nbd-debug.h>
12 const u64 cliserv_magic = 0x00420281861253LL;
13 const u64 opts_magic = 0x49484156454F5054LL;
14 const u64 rep_magic = 0x3e889045565a9LL;
17 * Set a socket to blocking or non-blocking
19 * @param fd The socket's FD
20 * @param nb nonzero to set to non-blocking, else 0 to set to blocking
21 * @return 0 - OK, -1 failed
23 int set_nonblocking(int fd, int nb) {
24 int sf = fcntl (fd, F_GETFL, 0);
27 return fcntl (fd, F_SETFL, nb ? (sf | O_NONBLOCK) : (sf & ~O_NONBLOCK));
31 void setmysockopt(int sock) {
34 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int)) < 0)
35 INFO("(no sockopt/1: %m)");
39 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &size, sizeof(int)) < 0)
40 INFO("(no sockopt/2: %m)");
44 if (setsockopt(sock, IPPROTO_TCP, TCP_MAXSEG, &size, sizeof(int)) < 0)
45 INFO("(no sockopt/3: %m)");
49 void err_nonfatal(const char *s) {
52 strncpy(s1, s, sizeof(s1));
53 if ((s2 = strstr(s, "%m"))) {
54 strncpy(s1 + (s2 - s), strerror(errno), sizeof(s1) - (s2 - s));
56 strncpy(s1 + strlen(s1), s2, sizeof(s1) - strlen(s1));
59 /* Solaris doesn't have %h in syslog */
60 else if ((s2 = strstr(s, "%h"))) {
61 strncpy(s1 + (s2 - s), hstrerror(h_errno), sizeof(s1) - (s2 - s));
63 strncpy(s1 + strlen(s1), s2, sizeof(s1) - strlen(s1));
67 s1[sizeof(s1)-1] = '\0';
69 syslog(LOG_ERR, "%s", s1);
70 syslog(LOG_ERR, "Exiting.");
72 fprintf(stderr, "Error: %s\n", s1);
75 void err(const char *s) {
77 fprintf(stderr, "Exiting.\n");
81 void logging(const char* name) {
83 openlog(name, LOG_PID, LOG_DAEMON);
85 setvbuf(stdout, NULL, _IONBF, 0);
86 setvbuf(stderr, NULL, _IONBF, 0);
90 #ifdef WORDS_BIGENDIAN
91 uint64_t ntohll(uint64_t a) {
95 uint64_t ntohll(uint64_t a) {
96 u32 lo = a & 0xffffffff;
100 return ((uint64_t) lo) << 32U | hi;
106 * Read data from a file descriptor into a buffer
108 * @param f a file descriptor
109 * @param buf a buffer
110 * @param len the number of bytes to be read
111 * @return 0 on completion, or -1 on failure
113 int readit(int f, void *buf, size_t len) {
117 res = read(f, buf, len);
121 } else if (res < 0) {
122 if(errno != EAGAIN) {
123 err_nonfatal("Read failed: %m");
135 * Write data from a buffer into a filedescriptor
137 * @param f a file descriptor
138 * @param buf a buffer containing data
139 * @param len the number of bytes to be written
140 * @return 0 on success, or -1 if the socket was closed
142 int writeit(int f, void *buf, size_t len) {
146 if ((res = write(f, buf, len)) <= 0) {
151 err_nonfatal("Send failed: %m");