summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSimon Rettberg2014-12-31 23:39:21 +0100
committerSimon Rettberg2014-12-31 23:39:21 +0100
commit6788efa3459b9581b1e4197e37f504d8fb2e8e87 (patch)
treef177c92792884dd98c82b8d8828b092b2119a36c
parent[SERVER] Minor tweaks and improvements (diff)
downloaddnbd3-6788efa3459b9581b1e4197e37f504d8fb2e8e87.tar.gz
dnbd3-6788efa3459b9581b1e4197e37f504d8fb2e8e87.tar.xz
dnbd3-6788efa3459b9581b1e4197e37f504d8fb2e8e87.zip
[SERVER] Use stdbool.h for booleans; minor refactoring of variable and function names
-rw-r--r--CMakeLists.txt2
-rw-r--r--src/server/altservers.c28
-rw-r--r--src/server/altservers.h2
-rw-r--r--src/server/fileutil.c36
-rw-r--r--src/server/fileutil.h8
-rw-r--r--src/server/globals.c14
-rw-r--r--src/server/globals.h24
-rw-r--r--src/server/helper.c41
-rw-r--r--src/server/helper.h56
-rw-r--r--src/server/image.c195
-rw-r--r--src/server/image.h14
-rw-r--r--src/server/integrity.c10
-rw-r--r--src/server/locks.c2
-rw-r--r--src/server/net.c54
-rw-r--r--src/server/protocol.h48
-rw-r--r--src/server/server.c30
-rw-r--r--src/server/sockhelper.c10
-rw-r--r--src/server/sockhelper.h4
-rw-r--r--src/server/uplink.c73
-rw-r--r--src/server/uplink.h4
-rw-r--r--src/types.h8
21 files changed, 327 insertions, 336 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e04416d..d81a842 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -16,7 +16,7 @@ if(CMAKE_C_COMPILER MATCHES "clang")
SET(CMAKE_C_FLAGS_RELEASE "-std=c99 -O2 -Wno-unused-result -D_GNU_SOURCE -DNDEBUG -Wno-multichar")
elseif (CMAKE_C_COMPILER MATCHES "(cc-)|(cc$)")
message( "Using (g)cc flags." )
- SET(CMAKE_C_FLAGS_DEBUG "-std=c99 -O0 -g -Wall -Wno-unused-result -D_GNU_SOURCE -D_DEBUG -Wno-multichar")
+ SET(CMAKE_C_FLAGS_DEBUG "-std=c99 -O0 -g -pedantic -Wall -Wno-unused-result -D_GNU_SOURCE -D_DEBUG -Wno-multichar")
SET(CMAKE_C_FLAGS_RELEASE "-std=c99 -O2 -Wno-unused-result -D_GNU_SOURCE -DNDEBUG -Wno-multichar")
else()
message( FATAL_ERROR "Could not determine compiler type." )
diff --git a/src/server/altservers.c b/src/server/altservers.c
index 7781e69..7ed1a57 100644
--- a/src/server/altservers.c
+++ b/src/server/altservers.c
@@ -26,7 +26,7 @@ static int signalPipe = -1;
static dnbd3_alt_server_t altServers[SERVER_MAX_ALTS];
static int numAltServers = 0;
static pthread_spinlock_t altServersLock;
-static int initDone = FALSE;
+static bool initDone = false;
static pthread_t altThread;
@@ -46,7 +46,7 @@ void altservers_init()
memlogf( "[ERROR] Could not start altservers connector thread" );
exit( EXIT_FAILURE );
}
- initDone = TRUE;
+ initDone = true;
}
void altservers_shutdown()
@@ -69,11 +69,11 @@ int altservers_load()
if ( fp == NULL ) return -1;
while ( !feof( fp ) ) {
if ( fgets( buffer, 1000, fp ) == NULL ) break;
- int isPrivate = FALSE;
- int isClientOnly = FALSE;
+ bool isPrivate = false;
+ bool isClientOnly = false;
for (line = buffer; *line != '\0'; ) { // Trim left and scan for "-" prefix
- if ( *line == '-' ) isPrivate = TRUE;
- else if ( *line == '+' ) isClientOnly = TRUE;
+ if ( *line == '-' ) isPrivate = true;
+ else if ( *line == '+' ) isClientOnly = true;
else if ( *line != ' ' && *line != '\t' ) break;
line++;
}
@@ -92,14 +92,14 @@ int altservers_load()
return count;
}
-int altservers_add(dnbd3_host_t *host, const char *comment, const int isPrivate, const int isClientOnly)
+bool altservers_add(dnbd3_host_t *host, const char *comment, const int isPrivate, const int isClientOnly)
{
int i, freeSlot = -1;
spin_lock( &altServersLock );
for (i = 0; i < numAltServers; ++i) {
if ( isSameAddressPort( &altServers[i].host, host ) ) {
spin_unlock( &altServersLock );
- return FALSE;
+ return false;
} else if ( freeSlot == -1 && altServers[i].host.type == 0 ) {
freeSlot = i;
}
@@ -108,7 +108,7 @@ int altservers_add(dnbd3_host_t *host, const char *comment, const int isPrivate,
if ( numAltServers >= SERVER_MAX_ALTS ) {
memlogf( "[WARNING] Cannot add another alt server, maximum of %d already reached.", (int)SERVER_MAX_ALTS );
spin_unlock( &altServersLock );
- return FALSE;
+ return false;
}
freeSlot = numAltServers++;
}
@@ -117,7 +117,7 @@ int altservers_add(dnbd3_host_t *host, const char *comment, const int isPrivate,
altServers[freeSlot].isClientOnly = isClientOnly;
if ( comment != NULL ) snprintf( altServers[freeSlot].comment, COMMENT_LENGTH, "%s", comment );
spin_unlock( &altServersLock );
- return TRUE;
+ return true;
}
/**
@@ -344,7 +344,7 @@ static void *altservers_main(void *data)
struct epoll_event ev, events[MAXEVENTS];
int fdEpoll = -1;
int numSocks, ret, itLink, itAlt, numAlts;
- int found;
+ bool found;
char buffer[DNBD3_BLOCK_SIZE ];
dnbd3_reply_t reply;
dnbd3_host_t servers[ALTS + 1];
@@ -416,10 +416,10 @@ static void *altservers_main(void *data)
numAlts = altservers_get( servers, ALTS, uplink->fd == -1 );
if ( uplink->fd != -1 ) {
// Add current server if not already in list
- found = FALSE;
+ found = false;
for (itAlt = 0; itAlt < numAlts; ++itAlt) {
if ( !isSameAddressPort( &uplink->currentServer, &servers[itAlt] ) ) continue;
- found = TRUE;
+ found = true;
break;
}
if ( !found ) servers[numAlts++] = uplink->currentServer;
@@ -460,7 +460,7 @@ static void *altservers_main(void *data)
}
// Request first block (NOT random!) ++++++++++++++++++++++++++++++
fixup_request( request );
- if ( !dnbd3_get_block( sock, 0, DNBD3_BLOCK_SIZE ) ) {
+ if ( !dnbd3_get_block( sock, 0, DNBD3_BLOCK_SIZE, 0 ) ) {
ERROR_GOTO_VA( server_failed, "[ERROR] Could not request random block for %s", image->lower_name );
}
// See if requesting the block succeeded ++++++++++++++++++++++
diff --git a/src/server/altservers.h b/src/server/altservers.h
index 459c546..699551a 100644
--- a/src/server/altservers.h
+++ b/src/server/altservers.h
@@ -9,7 +9,7 @@ void altservers_shutdown();
int altservers_load();
-int altservers_add(dnbd3_host_t *host, const char *comment, const int isPrivate, const int isClientOnly);
+bool altservers_add(dnbd3_host_t *host, const char *comment, const int isPrivate, const int isClientOnly);
void altservers_findUplink(dnbd3_connection_t *uplink);
diff --git a/src/server/fileutil.c b/src/server/fileutil.c
index 5adc90a..d16c4d8 100644
--- a/src/server/fileutil.c
+++ b/src/server/fileutil.c
@@ -9,53 +9,53 @@
#include <assert.h>
#include <string.h>
-int file_isReadable(char *file)
+bool file_isReadable(char *file)
{
int fd = open( file, O_RDONLY );
- if ( fd < 0 ) return FALSE;
+ if ( fd < 0 ) return false;
close( fd );
- return TRUE;
+ return true;
}
-int file_isWritable(char *file)
+bool file_isWritable(char *file)
{
int fd = open( file, O_WRONLY );
if ( fd >= 0 ) {
close( fd );
- return TRUE;
+ return true;
}
fd = open( file, O_WRONLY | O_CREAT, 0600 );
- if ( fd < 0 ) return FALSE;
+ if ( fd < 0 ) return false;
close( fd );
unlink( file );
- return TRUE;
+ return true;
}
-int mkdir_p(const char* path)
+bool mkdir_p(const char* path)
{
assert( path != NULL );
- if ( *path == '\0' ) return TRUE;
+ if ( *path == '\0' ) return true;
char buffer[strlen( path ) + 1];
strcpy( buffer, path );
char *current = buffer;
char *slash;
while ( (slash = strchr( current, '/' )) != NULL ) {
*slash = '\0';
- if ( *buffer != '\0' && mkdir( buffer, 0750 ) != 0 && errno != EEXIST ) return FALSE;
+ if ( *buffer != '\0' && mkdir( buffer, 0755 ) != 0 && errno != EEXIST ) return false;
*slash = '/';
current = slash + 1;
}
- if ( mkdir( buffer, 0750 ) != 0 && errno != EEXIST ) return FALSE;
- return TRUE;
+ if ( mkdir( buffer, 0755 ) != 0 && errno != EEXIST ) return false;
+ return true;
}
-int file_alloc(int fd, uint64_t offset, uint64_t size)
+bool file_alloc(int fd, uint64_t offset, uint64_t size)
{
- if ( fallocate( fd, 0, offset, size ) == 0 ) return TRUE; // fast way
- if ( posix_fallocate( fd, offset, size ) == 0 ) return TRUE; // slow way
- if ( lseek( fd, offset + size - 1, SEEK_SET ) != offset ) return FALSE; // dumb way
- if ( write( fd, "", 1 ) != 1 ) return FALSE;
- return TRUE;
+ if ( fallocate( fd, 0, offset, size ) == 0 ) return true; // fast way
+ if ( posix_fallocate( fd, offset, size ) == 0 ) return true; // slow way
+ if ( lseek( fd, offset + size - 1, SEEK_SET ) != offset ) return false; // dumb way
+ if ( write( fd, "", 1 ) != 1 ) return false;
+ return true;
}
int64_t file_freeDiskSpace(const char * const path)
diff --git a/src/server/fileutil.h b/src/server/fileutil.h
index db60699..d868ccc 100644
--- a/src/server/fileutil.h
+++ b/src/server/fileutil.h
@@ -4,10 +4,10 @@
#include "../types.h"
#include <time.h>
-int file_isReadable(char *file);
-int file_isWritable(char *file);
-int mkdir_p(const char* path);
-int file_alloc(int fd, uint64_t offset, uint64_t size);
+bool file_isReadable(char *file);
+bool file_isWritable(char *file);
+bool mkdir_p(const char* path);
+bool file_alloc(int fd, uint64_t offset, uint64_t size);
int64_t file_freeDiskSpace(const char * const path);
time_t file_lastModification(const char * const file);
diff --git a/src/server/globals.c b/src/server/globals.c
index 0f26169..1e35a8f 100644
--- a/src/server/globals.c
+++ b/src/server/globals.c
@@ -8,18 +8,18 @@
char *_configDir = NULL;
char *_basePath = NULL;
-int _vmdkLegacyMode = FALSE;
-int _shutdown = 0;
+bool _vmdkLegacyMode = false;
+bool _shutdown = false;
int _serverPenalty = 0;
int _clientPenalty = 0;
-int _isProxy = FALSE;
-int _proxyPrivateOnly = FALSE;
+bool _isProxy = false;
+bool _proxyPrivateOnly = false;
+bool _backgroundReplication = true;
int _uplinkTimeout = 1250;
int _clientTimeout = 15000;
-int _backgroundReplication = TRUE;
#define SAVE_TO_VAR_STR(ss, kk) do { if (strcmp(section, #ss) == 0 && strcmp(key, #kk) == 0) { if (_ ## kk != NULL) free(_ ## kk); _ ## kk = strdup(value); } } while (0)
-#define SAVE_TO_VAR_BOOL(ss, kk) do { if (strcmp(section, #ss) == 0 && strcmp(key, #kk) == 0) _ ## kk = atoi(value) != 0 || strcmp(value, "true") == 0 || strcmp(value, "True") == 0 || strcmp(value, "TRUE") == 0; } while (0)
+#define SAVE_TO_VAR_BOOL(ss, kk) do { if (strcmp(section, #ss) == 0 && strcmp(key, #kk) == 0) _ ## kk = atoi(value) != 0 || strcmp(value, "true") == 0 || strcmp(value, "True") == 0 || strcmp(value, "true") == 0; } while (0)
#define SAVE_TO_VAR_INT(ss, kk) do { if (strcmp(section, #ss) == 0 && strcmp(key, #kk) == 0) _ ## kk = atoi(value); } while (0)
static int ini_handler(void *custom, const char* section, const char* key, const char* value)
@@ -33,7 +33,7 @@ static int ini_handler(void *custom, const char* section, const char* key, const
SAVE_TO_VAR_INT( dnbd3, clientPenalty );
SAVE_TO_VAR_INT( dnbd3, uplinkTimeout );
SAVE_TO_VAR_INT( dnbd3, clientTimeout );
- return TRUE;
+ return 1;
}
void globals_loadConfig()
diff --git a/src/server/globals.h b/src/server/globals.h
index d9a299d..1ac1495 100644
--- a/src/server/globals.h
+++ b/src/server/globals.h
@@ -54,9 +54,8 @@ struct _dnbd3_connection
int betterFd; // Active connection to better server, ready to use
uint8_t *recvBuffer; // Buffer for receiving payload
int recvBufferLen; // Len of ^^
- volatile int shutdown; // bool to signal thread to stop, must only be set from uplink_shutdown() or cleanup in uplink_mainloop()
+ volatile bool shutdown; // signal this thread to stop, must only be set from uplink_shutdown() or cleanup in uplink_mainloop()
int replicatedLastBlock; // bool telling if the last block has been replicated yet
- //time_t lastReplication; // timestamp of when last replication requests were sent
uint64_t replicationHandle; // Handle of pending replication request
};
@@ -77,7 +76,7 @@ typedef struct
dnbd3_host_t host;
int rtt[SERVER_RTT_PROBES];
int rttIndex;
- int isPrivate, isClientOnly;
+ bool isPrivate, isClientOnly;
time_t lastFail;
int numFails;
} dnbd3_alt_server_t;
@@ -108,7 +107,7 @@ struct _dnbd3_image
int rid; // revision of image
int users; // clients currently using this image
time_t atime; // last access time
- char working; // TRUE if image exists and completeness is == 100% or a working upstream proxy is connected
+ bool working; // true if image exists and completeness is == 100% or a working upstream proxy is connected
pthread_spinlock_t lock;
};
@@ -116,12 +115,12 @@ struct _dnbd3_client
{
int sock;
dnbd3_host_t host;
- uint8_t is_server; // TRUE if a server in proxy mode, FALSE if real client
pthread_t thread;
dnbd3_image_t *image;
pthread_spinlock_t lock;
pthread_mutex_t sendMutex;
- int running;
+ bool running;
+ bool isServer; // true if a server in proxy mode, false if real client
};
// #######################################################
@@ -140,7 +139,7 @@ extern char *_basePath;
/**
* Whether or not simple *.vmdk files should be treated as revision 1
*/
-extern int _vmdkLegacyMode;
+extern bool _vmdkLegacyMode;
/**
* How much artificial delay should we add when a server connects to us?
@@ -155,17 +154,17 @@ extern int _clientPenalty;
/**
* Is server shutting down?
*/
-extern int _shutdown;
+extern bool _shutdown;
/**
* Is server allowed to provide images in proxy mode?
*/
-extern int _isProxy;
+extern bool _isProxy;
/**
* Only use servers as upstream proxy which are private?
*/
-extern int _proxyPrivateOnly;
+extern bool _proxyPrivateOnly;
/**
* Read timeout when waiting for or sending data on an uplink
@@ -181,8 +180,11 @@ extern int _clientTimeout;
* Should we replicate incomplete images in the background?
* Otherwise, only blocks that were explicitly requested will be cached.
*/
-extern int _backgroundReplication;
+extern bool _backgroundReplication;
+/**
+ * Load the server configuration.
+ */
void globals_loadConfig();
#endif /* GLOBALS_H_ */
diff --git a/src/server/helper.c b/src/server/helper.c
index 8070fa0..87e0b7f 100644
--- a/src/server/helper.c
+++ b/src/server/helper.c
@@ -10,15 +10,16 @@
/**
* Parse IPv4 or IPv6 address in string representation to a suitable format usable by the BSD socket library
- * @string eg. "1.2.3.4" or "2a01::10:5", optially with port appended, eg "1.2.3.4:6666" or "[2a01::10:5]:6666"
- * @host pointer to dnbd3_host_t that will be filled with the following data:
- * type will contain either AF_INET or AF_INET6
- * addr will contain the address in network representation
- * port will contain the port in network representation, defaulting to #define PORT if none was given
- * returns TRUE on success, FALSE in failure. contents of af, addr and port are undefined in the latter case
- * !! Contents of @string might be modified by this function !!
+ * !! Contents of 'string' might be modified by this function !!
+ *
+ * @param string eg. "1.2.3.4" or "2a01::10:5", optially with port appended, eg "1.2.3.4:6666" or "[2a01::10:5]:6666"
+ * @param host pointer to dnbd3_host_t that will be filled with the following data:
+ * .type will contain either AF_INET or AF_INET6
+ * .addr will contain the address in network representation
+ * .port will contain the port in network representation, defaulting to #define PORT if none was given
+ * @return true on success, false in failure. contents of af, addr and port are undefined in the latter case
*/
-char parse_address(char *string, dnbd3_host_t *host)
+bool parse_address(char *string, dnbd3_host_t *host)
{
struct in_addr v4;
struct in6_addr v6;
@@ -29,14 +30,14 @@ char parse_address(char *string, dnbd3_host_t *host)
host->type = AF_INET;
memcpy( host->addr, &v4, 4 );
host->port = htons( PORT );
- return TRUE;
+ return true;
}
// Try IPv6 without port
if ( 1 == inet_pton( AF_INET6, string, &v6 ) ) {
host->type = AF_INET6;
memcpy( host->addr, &v6, 16 );
host->port = htons( PORT );
- return TRUE;
+ return true;
}
// Scan for port
@@ -45,7 +46,7 @@ char parse_address(char *string, dnbd3_host_t *host)
if ( *ptr == ':' ) portpos = ptr;
++ptr;
}
- if ( portpos == NULL ) return FALSE; // No port in string
+ if ( portpos == NULL ) return false; // No port in string
// Consider IP being surrounded by [ ]
if ( *string == '[' && *(portpos - 1) == ']' ) {
++string;
@@ -53,35 +54,35 @@ char parse_address(char *string, dnbd3_host_t *host)
}
*portpos++ = '\0';
int p = atoi( portpos );
- if ( p < 1 || p > 65535 ) return FALSE; // Invalid port
+ if ( p < 1 || p > 65535 ) return false; // Invalid port
host->port = htons( (uint16_t)p );
// Try IPv4 with port
if ( 1 == inet_pton( AF_INET, string, &v4 ) ) {
host->type = AF_INET;
memcpy( host->addr, &v4, 4 );
- return TRUE;
+ return true;
}
// Try IPv6 with port
if ( 1 == inet_pton( AF_INET6, string, &v6 ) ) {
host->type = AF_INET6;
memcpy( host->addr, &v6, 16 );
- return TRUE;
+ return true;
}
// FAIL
- return FALSE;
+ return false;
}
/**
* Convert a host and port (network byte order) to printable representation.
* Worst case required buffer len is 48, eg. [1234:1234:1234:1234:1234:1234:1234:1234]:12345 (+ \0)
- * Returns TRUE on success, FALSE on error
+ * Returns true on success, false on error
*/
-char host_to_string(const dnbd3_host_t *host, char *target, size_t targetlen)
+bool host_to_string(const dnbd3_host_t *host, char *target, size_t targetlen)
{
// Worst case: Port 5 chars, ':' to separate ip and port 1 char, terminating null 1 char = 7, [] for IPv6
- if ( targetlen < 10 ) return FALSE;
+ if ( targetlen < 10 ) return false;
if ( host->type == AF_INET6 ) {
*target++ = '[';
inet_ntop( AF_INET6, host->addr, target, targetlen - 10 );
@@ -92,14 +93,14 @@ char host_to_string(const dnbd3_host_t *host, char *target, size_t targetlen)
target += strlen( target );
} else {
snprintf( target, targetlen, "<?addrtype=%d>", (int)host->type );
- return FALSE;
+ return false;
}
*target = '\0';
if ( host->port != 0 ) {
// There are still at least 7 bytes left in the buffer, port is at most 5 bytes + ':' + '\0' = 7
snprintf( target, 7, ":%d", (int)ntohs( host->port ) );
}
- return TRUE;
+ return true;
}
void strtolower(char *string)
diff --git a/src/server/helper.h b/src/server/helper.h
index 95a5157..0ecbdfd 100644
--- a/src/server/helper.h
+++ b/src/server/helper.h
@@ -11,87 +11,85 @@
#define ERROR_GOTO(jumplabel, errormsg) do { memlogf(errormsg); goto jumplabel; } while (0);
#define ERROR_GOTO_VA(jumplabel, errormsg, ...) do { memlogf(errormsg, __VA_ARGS__); goto jumplabel; } while (0);
-char parse_address(char *string, dnbd3_host_t *host);
-char host_to_string(const dnbd3_host_t *host, char *target, size_t targetlen);
+bool parse_address(char *string, dnbd3_host_t *host);
+bool host_to_string(const dnbd3_host_t *host, char *target, size_t targetlen);
void strtolower(char *string);
void remove_trailing_slash(char *string);
void trim_right(char * const string);
void setThreadName(char *name);
void blockNoncriticalSignals();
-static inline int isSameAddress(const dnbd3_host_t * const a, const dnbd3_host_t * const b)
+static inline bool isSameAddress(const dnbd3_host_t * const a, const dnbd3_host_t * const b)
{
return (a->type == b->type) && (0 == memcmp( a->addr, b->addr, (a->type == AF_INET ? 4 : 16) ));
}
-static inline int isSameAddressPort(const dnbd3_host_t * const a, const dnbd3_host_t * const b)
+static inline bool isSameAddressPort(const dnbd3_host_t * const a, const dnbd3_host_t * const b)
{
return (a->type == b->type) && (a->port == b->port) && (0 == memcmp( a->addr, b->addr, (a->type == AF_INET ? 4 : 16) ));
}
/**
- * Send message to client, return !=0 on success, 0 on failure
+ * Send message to client.
+ * @return true on success, false on failure
*/
static inline int send_data(int client_sock, void *data_in, int len)
{
- if ( len <= 0 ) // Nothing to send
- return 1;
+ if ( len <= 0 ) return true; // Nothing to send
char *data = data_in; // Needed for pointer arithmetic
int ret, i;
for (i = 0; i < 3; ++i) // Retry at most 3 times, each try takes at most 0.5 seconds (socket timeout)
- {
+ {
ret = send( client_sock, data, len, 0 );
- if ( ret == 0 ) // Connection closed
- return 0;
+ if ( ret == 0 ) return false; // Connection closed
if ( ret < 0 ) {
- if ( errno != EAGAIN ) // Some unexpected error
- return 0;
+ if ( errno != EAGAIN ) return false; // Some unexpected error
usleep( 1000 ); // 1ms
continue;
}
len -= ret;
- if ( len <= 0 ) // Sent everything
- return 1;
+ if ( len <= 0 ) return true; // Sent everything
data += ret; // move target buffer pointer
}
- return 0;
+ return false;
}
/**
- * Receive data from client, return !=0 on success, 0 on failure
+ * Receive data from client.
+ * @return true on success, false otherwise
*/
-static inline int recv_data(int client_sock, void *buffer_out, int len)
+static inline bool recv_data(int client_sock, void *buffer_out, int len)
{
- if ( len <= 0 ) // Nothing to receive
- return 1;
+ if ( len <= 0 ) return true; // Nothing to receive
char *data = buffer_out; // Needed for pointer arithmetic
int ret, i;
for (i = 0; i < 3; ++i) // Retry at most 3 times, each try takes at most 0.5 seconds (socket timeout)
{
ret = recv( client_sock, data, len, MSG_WAITALL );
- if ( ret == 0 ) // Connection closed
- return 0;
+ if ( ret == 0 ) return false; // Connection closed
if ( ret < 0 ) {
- if ( errno != EAGAIN ) // Some unexpected error
- return 0;
+ if ( errno != EAGAIN ) return false; // Some unexpected error
usleep( 1000 ); // 1ms
continue;
}
len -= ret;
- if ( len <= 0 ) // Received everything
- return 1;
+ if ( len <= 0 ) return true; // Received everything
data += ret; // move target buffer pointer
}
- return 0;
+ return false;
}
+/**
+ * Test whether string ends in suffix.
+ * @return true if string =~ /suffix$/
+ */
static inline int strend(char *string, char *suffix)
{
- if ( string == NULL ) return FALSE;
- if ( suffix == NULL || *suffix == '\0' ) return TRUE;
+ if ( string == NULL ) return false;
+ if ( suffix == NULL || *suffix == '\0' ) return true;
const size_t len1 = strlen( string );
const size_t len2 = strlen( suffix );
- if ( len2 > len1 ) return FALSE;
+ if ( len2 > len1 ) return false;
return strcmp( string + len1 - len2, suffix ) == 0;
}
diff --git a/src/server/image.c b/src/server/image.c
index d6fad22..e6a763b 100644
--- a/src/server/image.c
+++ b/src/server/image.c
@@ -43,37 +43,37 @@ static int remoteCloneCacheIndex = -1;
// ##########################################
-static int image_isHashBlockComplete(uint8_t * const cacheMap, const uint64_t block, const uint64_t fileSize);
-static int image_load_all_internal(char *base, char *path);
-static int image_load(char *base, char *path, int withUplink);
+static bool image_isHashBlockComplete(uint8_t * const cacheMap, const uint64_t block, const uint64_t fileSize);
+static bool image_load_all_internal(char *base, char *path);
+static bool image_load(char *base, char *path, int withUplink);
static int64_t image_pad(const char *path, const int64_t currentSize);
-static int image_clone(int sock, char *name, uint16_t revision, uint64_t imageSize);
-static int image_ensureDiskSpace(uint64_t size);
+static bool image_clone(int sock, char *name, uint16_t revision, uint64_t imageSize);
+static bool image_ensureDiskSpace(uint64_t size);
static uint8_t* image_loadCacheMap(const char * const imagePath, const int64_t fileSize);
static uint32_t* image_loadCrcList(const char * const imagePath, const int64_t fileSize, uint32_t *masterCrc);
-static int image_checkRandomBlocks(const int count, int fdImage, const int64_t fileSize, uint32_t * const crc32list,
- uint8_t * const cache_map);
+static bool image_checkRandomBlocks(const int count, int fdImage, const int64_t fileSize, uint32_t * const crc32list, uint8_t * const cache_map);
// ##########################################
/**
- * Returns TRUE if the given image is complete
+ * Returns true if the given image is complete
*/
-int image_isComplete(dnbd3_image_t *image)
+bool image_isComplete(dnbd3_image_t *image)
{
assert( image != NULL );
if ( image->working && image->cache_map == NULL ) {
- return TRUE;
+ return true;
}
if ( image->filesize == 0 ) {
- return FALSE;
+ return false;
}
- int complete = TRUE, j;
+ bool complete = true;
+ int j;
const int map_len_bytes = IMGSIZE_TO_MAPBYTES( image->filesize );
for (j = 0; j < map_len_bytes - 1; ++j) {
if ( image->cache_map[j] != 0xFF ) {
- complete = FALSE;
+ complete = false;
break;
}
}
@@ -97,14 +97,14 @@ int image_isComplete(dnbd3_image_t *image)
* start (inclusive) - end (exclusive)
* Locks on: images[].lock
*/
-void image_updateCachemap(dnbd3_image_t *image, uint64_t start, uint64_t end, const int set)
+void image_updateCachemap(dnbd3_image_t *image, uint64_t start, uint64_t end, const bool set)
{
assert( image != NULL );
// This should always be block borders due to how the protocol works, but better be safe
// than accidentally mark blocks as cached when they really aren't entirely cached.
end &= ~(uint64_t)(DNBD3_BLOCK_SIZE - 1);
start = (uint64_t)(start + DNBD3_BLOCK_SIZE - 1) & ~(uint64_t)(DNBD3_BLOCK_SIZE - 1);
- int dirty = FALSE;
+ bool dirty = false;
uint64_t pos = start;
spin_lock( &image->lock );
if ( image->cache_map == NULL ) {
@@ -118,7 +118,7 @@ void image_updateCachemap(dnbd3_image_t *image, uint64_t start, uint64_t end, co
const int map_x = (pos >> 12) & 7; // mod 8
const uint8_t bit_mask = 0b00000001 << map_x;
if ( set ) {
- if ( (image->cache_map[map_y] & bit_mask) == 0 ) dirty = TRUE;
+ if ( (image->cache_map[map_y] & bit_mask) == 0 ) dirty = true;
image->cache_map[map_y] |= bit_mask;
} else {
image->cache_map[map_y] &= ~bit_mask;
@@ -174,18 +174,18 @@ void image_saveAllCacheMaps()
/**
* Saves the cache map of the given image.
- * Return TRUE on success.
+ * Return true on success.
* Locks on: image.lock
*/
-int image_saveCacheMap(dnbd3_image_t *image)
+bool image_saveCacheMap(dnbd3_image_t *image)
{
- if ( image == NULL || image->cache_map == NULL ) return TRUE;
+ if ( image == NULL || image->cache_map == NULL ) return true;
spin_lock( &image->lock );
// Lock and get a copy of the cache map, as it could be freed by another thread that is just about to
// figure out that this image's cache copy is complete
if ( image->cache_map == NULL || image->filesize < DNBD3_BLOCK_SIZE ) {
spin_unlock( &image->lock );
- return TRUE;
+ return true;
}
const size_t size = IMGSIZE_TO_MAPBYTES(image->filesize);
uint8_t *map = malloc( size );
@@ -207,7 +207,7 @@ int image_saveCacheMap(dnbd3_image_t *image)
image->users--;
spin_unlock( &image->lock );
free( map );
- return FALSE;
+ return false;
}
write( fd, map, size );
@@ -221,7 +221,7 @@ int image_saveCacheMap(dnbd3_image_t *image)
spin_lock( &image->lock );
image->users--;
spin_unlock( &image->lock );
- return TRUE;
+ return true;
}
/**
@@ -268,15 +268,15 @@ dnbd3_image_t* image_get(char *name, uint16_t revision)
if ( candidate->working && stat( candidate->path, &st ) < 0 ) {
// Either the image is already marked as "not working", or the file cannot be accessed
printf( "[DEBUG] File '%s' has gone away...\n", candidate->path );
- candidate->working = FALSE; // No file? OUT!
+ candidate->working = false; // No file? OUT!
} else if ( !candidate->working && candidate->cache_map != NULL && candidate->uplink == NULL && file_isWritable( candidate->path ) ) {
// Not working and has file + cache-map, try to init uplink (uplink_init will check if proxy mode is enabled)
uplink_init( candidate, -1, NULL );
} else if ( candidate->working && candidate->uplink != NULL && candidate->uplink->queueLen > SERVER_UPLINK_QUEUELEN_THRES ) {
// To many pending uplink requests. We take that as a hint that the uplink is clogged or no working uplink server
- // exists, so "working" is changed to FALSE for now. Should a new uplink server be found the uplink thread will
- // set this back to TRUE some time.
- candidate->working = FALSE;
+ // exists, so "working" is changed to false for now. Should a new uplink server be found the uplink thread will
+ // set this back to true some time.
+ candidate->working = false;
}
return candidate; // Success :-)
}
@@ -375,7 +375,7 @@ void image_killUplinks()
if ( _images[i] == NULL ) continue;
spin_lock( &_images[i]->lock );
if ( _images[i]->uplink != NULL ) {
- _images[i]->uplink->shutdown = TRUE;
+ _images[i]->uplink->shutdown = true;
if ( _images[i]->uplink->signal != -1 ) {
write( _images[i]->uplink->signal, "", 1 );
}
@@ -411,7 +411,7 @@ dnbd3_image_t* image_free(dnbd3_image_t *image)
* Load all images in given path recursively.
* Pass NULL to use path from config.
*/
-int image_loadAll(char *path)
+bool image_loadAll(char *path)
{
if ( path == NULL ) {
return image_load_all_internal( _basePath, _basePath );
@@ -419,14 +419,14 @@ int image_loadAll(char *path)
return image_load_all_internal( path, path );
}
-static int image_isHashBlockComplete(uint8_t * const cacheMap, const uint64_t block, const uint64_t fileSize)
+static bool image_isHashBlockComplete(uint8_t * const cacheMap, const uint64_t block, const uint64_t fileSize)
{
- if ( cacheMap == NULL ) return TRUE;
+ if ( cacheMap == NULL ) return true;
const uint64_t end = (block + 1) * HASH_BLOCK_SIZE;
if ( end <= fileSize ) {
for (uint64_t mapPos = block * HASH_BLOCK_SIZE; mapPos < end; mapPos += (DNBD3_BLOCK_SIZE * 8)) {
if ( cacheMap[mapPos / (DNBD3_BLOCK_SIZE * 8)] != 0xff ) {
- return FALSE;
+ return false;
}
}
} else {
@@ -434,17 +434,17 @@ static int image_isHashBlockComplete(uint8_t * const cacheMap, const uint64_t bl
const int map_y = mapPos >> 15;
const int map_x = (mapPos >> 12) & 7; // mod 8
const int mask = 1 << map_x;
- if ( (cacheMap[map_y] & mask) == 0 ) return FALSE;
+ if ( (cacheMap[map_y] & mask) == 0 ) return false;
}
}
- return TRUE;
+ return true;
}
/**
* Load all images in the given path recursively,
* consider *base the base path that is to be cut off
*/
-static int image_load_all_internal(char *base, char *path)
+static bool image_load_all_internal(char *base, char *path)
{
#define SUBDIR_LEN 120
assert( path != NULL );
@@ -453,7 +453,7 @@ static int image_load_all_internal(char *base, char *path)
DIR *dir = opendir( path );
if ( dir == NULL ) {
memlogf( "[ERROR] Could not opendir '%s' for loading", path );
- return FALSE;
+ return false;
}
const int pathLen = strlen( path );
const int len = pathLen + SUBDIR_LEN + 1;
@@ -477,15 +477,15 @@ static int image_load_all_internal(char *base, char *path)
if ( S_ISDIR( st.st_mode )) {
image_load_all_internal( base, subpath ); // Recurse
} else {
- image_load( base, subpath, TRUE ); // Load image if possible
+ image_load( base, subpath, true ); // Load image if possible
}
}
closedir( dir );
- return TRUE;
+ return true;
#undef SUBDIR_LEN
}
-static int image_load(char *base, char *path, int withUplink)
+static bool image_load(char *base, char *path, int withUplink)
{
int i, revision;
struct stat st;
@@ -493,7 +493,7 @@ static int image_load(char *base, char *path, int withUplink)
uint32_t *crc32list = NULL;
dnbd3_image_t *existing = NULL;
int fdImage = -1;
- int function_return = FALSE; // Return false by default
+ bool function_return = false; // Return false by default
assert( base != NULL );
assert( path != NULL );
assert( *path == '/' );
@@ -524,9 +524,9 @@ static int image_load(char *base, char *path, int withUplink)
for (i = fileNameLen - 1; i > 1; --i) {
if ( fileName[i] < '0' || fileName[i] > '9' ) break;
}
- if ( i == fileNameLen - 1 ) return FALSE;
- if ( fileName[i] != 'r' ) return FALSE;
- if ( fileName[i - 1] != '.' ) return FALSE;
+ if ( i == fileNameLen - 1 ) return false;
+ if ( fileName[i] != 'r' ) return false;
+ if ( fileName[i - 1] != '.' ) return false;
revision = atoi( fileName + i + 1 );
src = fileName;
while ( src < fileName + i - 1 ) {
@@ -598,16 +598,16 @@ static int image_load(char *base, char *path, int withUplink)
existing->crc32 = crc32list;
existing->masterCrc32 = masterCrc;
crc32list = NULL;
- function_return = TRUE;
+ function_return = true;
goto load_error;
} else if ( existing->cache_map != NULL && cache_map == NULL ) {
// Just ignore that fact, if replication is really complete the cache map will be removed anyways
memlogf( "[INFO] Image '%s:%d' has no cache map on disk!", existing->lower_name, (int)existing->rid );
- function_return = TRUE;
+ function_return = true;
goto load_error;
} else {
// Nothing changed about the existing image, so do nothing
- function_return = TRUE;
+ function_return = true;
goto load_error;
}
// Remove image from images array
@@ -643,12 +643,12 @@ static int image_load(char *base, char *path, int withUplink)
// Get rid of cache map if image is complete
if ( image->cache_map != NULL && image_isComplete( image ) ) {
image_markComplete( image );
- image->working = TRUE;
+ image->working = true;
}
// Image is definitely incomplete, open image file for writing, so we can update the cache
if ( image->cache_map != NULL ) {
- image->working = FALSE;
+ image->working = false;
image->cacheFd = open( path, O_WRONLY );
if ( image->cacheFd < 0 ) {
// Proxy mode without disk caching is pointless, bail out
@@ -682,7 +682,7 @@ static int image_load(char *base, char *path, int withUplink)
}
spin_unlock( &_images_lock );
- function_return = TRUE;
+ function_return = true;
// Clean exit:
load_error: ;
@@ -756,8 +756,7 @@ static uint32_t* image_loadCrcList(const char * const imagePath, const int64_t f
return retval;
}
-static int image_checkRandomBlocks(const int count, int fdImage, const int64_t fileSize, uint32_t * const crc32list,
- uint8_t * const cache_map)
+static bool image_checkRandomBlocks(const int count, int fdImage, const int64_t fileSize, uint32_t * const crc32list, uint8_t * const cache_map)
{
// This checks the first block and (up to) count - 1 random blocks for corruption
// via the known crc32 list. This is very sloppy and is merely supposed to detect
@@ -785,15 +784,15 @@ while_end: ;
/**
* Create a new image with the given image name and revision id in _basePath
- * Returns TRUE on success, FALSE otherwise
+ * Returns true on success, false otherwise
*/
-int image_create(char *image, int revision, uint64_t size)
+bool image_create(char *image, int revision, uint64_t size)
{
assert( image != NULL );
assert( size >= DNBD3_BLOCK_SIZE );
if ( revision <= 0 ) {
memlogf( "[ERROR] revision id invalid: %d", revision );
- return FALSE;
+ return false;
}
const int PATHLEN = 2000;
char path[PATHLEN], cache[PATHLEN];
@@ -809,7 +808,7 @@ int image_create(char *image, int revision, uint64_t size)
}
if ( file_isReadable( path ) ) {
memlogf( "[ERROR] Image %s with rid %d already exists!", image, revision );
- return FALSE;
+ return false;
}
snprintf( cache, PATHLEN, "%s.map", path );
size = (size + DNBD3_BLOCK_SIZE - 1) & ~(uint64_t)(DNBD3_BLOCK_SIZE - 1);
@@ -840,14 +839,14 @@ int image_create(char *image, int revision, uint64_t size)
}
close( fdImage );
close( fdCache );
- return TRUE;
+ return true;
//
failure_cleanup: ;
if ( fdImage >= 0 ) close( fdImage );
if ( fdCache >= 0 ) close( fdCache );
remove( path );
remove( cache );
- return FALSE;
+ return false;
}
/**
@@ -901,7 +900,7 @@ dnbd3_image_t* image_getOrClone(char *name, uint16_t revision)
dnbd3_host_t servers[4];
int uplinkSock = -1;
dnbd3_host_t *uplinkServer = NULL;
- const int count = altservers_get( servers, 4, FALSE );
+ const int count = altservers_get( servers, 4, false );
uint16_t remoteVersion, remoteRid;
uint64_t remoteImageSize;
for (i = 0; i < count; ++i) {
@@ -929,7 +928,7 @@ dnbd3_image_t* image_getOrClone(char *name, uint16_t revision)
if ( image != NULL && uplinkSock != -1 && uplinkServer != NULL ) {
// If so, init the uplink and pass it the socket
uplink_init( image, uplinkSock, uplinkServer );
- image->working = TRUE;
+ image->working = true;
} else if ( uplinkSock >= 0 ) {
close( uplinkSock );
}
@@ -941,12 +940,12 @@ dnbd3_image_t* image_getOrClone(char *name, uint16_t revision)
* 1. Allocate empty image file and its cache map
* 2. Use passed socket to request the crc32 list and save it to disk
* 3. Load the image from disk
- * Returns: TRUE on success, FALSE otherwise
+ * Returns: true on success, false otherwise
*/
-static int image_clone(int sock, char *name, uint16_t revision, uint64_t imageSize)
+static bool image_clone(int sock, char *name, uint16_t revision, uint64_t imageSize)
{
// Allocate disk space and create cache map
- if ( !image_create( name, revision, imageSize ) ) return FALSE;
+ if ( !image_create( name, revision, imageSize ) ) return false;
// CRC32
const size_t len = strlen( _basePath ) + strlen( name ) + 20;
char crcFile[len];
@@ -958,7 +957,7 @@ static int image_clone(int sock, char *name, uint16_t revision, uint64_t imageSi
uint8_t *crc32list = malloc( crc32len );
if ( !dnbd3_get_crc32( sock, &masterCrc, crc32list, &crc32len ) ) {
free( crc32list );
- return FALSE;
+ return false;
}
if ( crc32len != 0 ) {
uint32_t lists_crc = crc32( 0L, Z_NULL, 0 );
@@ -976,7 +975,7 @@ static int image_clone(int sock, char *name, uint16_t revision, uint64_t imageSi
}
// HACK: Chop of ".crc" to get the image file name
crcFile[strlen( crcFile ) - 4] = '\0';
- return image_load( _basePath, crcFile, FALSE );
+ return image_load( _basePath, crcFile, false );
}
/**
@@ -984,19 +983,19 @@ static int image_clone(int sock, char *name, uint16_t revision, uint64_t imageSi
* This function wants a plain file name instead of a dnbd3_image_t,
* as it can be used directly from the command line.
*/
-int image_generateCrcFile(char *image)
+bool image_generateCrcFile(char *image)
{
int fdImage = open( image, O_RDONLY );
if ( fdImage < 0 ) {
printf( "Could not open %s.\n", image );
- return FALSE;
+ return false;
}
// force size to be multiple of DNBD3_BLOCK_SIZE
int64_t fileLen = lseek( fdImage, 0, SEEK_END );
if ( fileLen <= 0 ) {
printf( "Error seeking to end, or file is empty.\n" );
close( fdImage );
- return FALSE;
+ return false;
}
if ( fileLen % DNBD3_BLOCK_SIZE != 0 ) {
printf( "File length is not a multiple of DNBD3_BLOCK_SIZE\n" );
@@ -1004,7 +1003,7 @@ int image_generateCrcFile(char *image)
if ( ret < fileLen ) {
printf( "Error appending to file in order to make it block aligned.\n" );
close( fdImage );
- return FALSE;
+ return false;
}
printf( "...fixed!\n" );
fileLen = ret;
@@ -1012,7 +1011,7 @@ int image_generateCrcFile(char *image)
if ( lseek( fdImage, 0, SEEK_SET ) != 0 ) {
printf( "Seeking back to start failed.\n" );
close( fdImage );
- return FALSE;
+ return false;
}
char crcFile[strlen( image ) + 4 + 1];
sprintf( crcFile, "%s.crc", image );
@@ -1020,23 +1019,23 @@ int image_generateCrcFile(char *image)
if ( stat( crcFile, &sst ) == 0 ) {
printf( "CRC File for %s already exists! Delete it first if you want to regen.\n", image );
close( fdImage );
- return FALSE;
+ return false;
}
int fdCrc = open( crcFile, O_RDWR | O_CREAT, 0644 );
if ( fdCrc < 0 ) {
printf( "Could not open CRC File %s for writing..\n", crcFile );
close( fdImage );
- return FALSE;
+ return false;
}
// CRC of all CRCs goes first. Don't know it yet, write 4 bytes dummy data.
if ( write( fdCrc, crcFile, 4 ) != 4 ) {
printf( "Write error\n" );
close( fdImage );
close( fdCrc );
- return FALSE;
+ return false;
}
char buffer[80000]; // Read buffer from image
- int finished = FALSE; // end of file reached
+ bool finished = false; // end of file reached
int hasSum; // unwritten (unfinished?) crc32 exists
int blocksToGo = 0; // Count number of checksums written
printf( "Generating CRC32" );
@@ -1045,7 +1044,7 @@ int image_generateCrcFile(char *image)
// Start of a block - init
uint32_t crc = crc32( 0L, Z_NULL, 0 );
int remaining = HASH_BLOCK_SIZE;
- hasSum = FALSE;
+ hasSum = false;
while ( remaining > 0 ) {
const int blockSize = MIN(remaining, sizeof(buffer));
const int ret = read( fdImage, buffer, blockSize );
@@ -1053,12 +1052,12 @@ int image_generateCrcFile(char *image)
printf( "Read error\n" );
close( fdImage );
close( fdCrc );
- return FALSE;
+ return false;
} else if ( ret == 0 ) { // EOF
- finished = TRUE;
+ finished = true;
break;
} else { // Read something
- hasSum = TRUE;
+ hasSum = true;
crc = crc32( crc, (Bytef*)buffer, ret );
remaining -= ret;
}
@@ -1069,7 +1068,7 @@ int image_generateCrcFile(char *image)
printf( "Write error\n" );
close( fdImage );
close( fdCrc );
- return FALSE;
+ return false;
}
printf( "." );
fflush( stdout );
@@ -1083,7 +1082,7 @@ int image_generateCrcFile(char *image)
if ( lseek( fdCrc, 4, SEEK_SET ) != 4 ) {
printf( "Could not seek to beginning of crc list in file\n" );
close( fdCrc );
- return FALSE;
+ return false;
}
uint32_t crc = crc32( 0L, Z_NULL, 0 );
while ( blocksToGo > 0 ) {
@@ -1091,7 +1090,7 @@ int image_generateCrcFile(char *image)
if ( read( fdCrc, buffer, numBlocks * 4 ) != numBlocks * 4 ) {
printf( "Could not re-read from crc32 file\n" );
close( fdCrc );
- return FALSE;
+ return false;
}
crc = crc32( crc, (Bytef*)buffer, numBlocks * 4 );
blocksToGo -= numBlocks;
@@ -1099,16 +1098,16 @@ int image_generateCrcFile(char *image)
if ( lseek( fdCrc, 0, SEEK_SET ) != 0 ) {
printf( "Could not seek back to beginning of crc32 file\n" );
close( fdCrc );
- return FALSE;
+ return false;
}
if ( write( fdCrc, &crc, 4 ) != 4 ) {
printf( "Could not write master crc to file\n" );
close( fdCrc );
- return FALSE;
+ return false;
}
printf( "..done!\nCRC-32 file successfully generated.\n" );
fflush( stdout );
- return TRUE;
+ return true;
}
void image_printAll()
@@ -1164,15 +1163,15 @@ int image_getCompletenessEstimate(const dnbd3_image_t * const image)
/**
* Check the CRC-32 of the given blocks. The array blocks is of variable length.
* !! pass -1 as the last block so the function knows when to stop !!
- * Returns TRUE or FALSE
+ * Returns true or false
*/
-int image_checkBlocksCrc32(int fd, uint32_t *crc32list, const int *blocks, const uint64_t fileSize)
+bool image_checkBlocksCrc32(int fd, uint32_t *crc32list, const int *blocks, const uint64_t fileSize)
{
char buffer[40000];
while ( *blocks != -1 ) {
if ( lseek( fd, (int64_t)*blocks * HASH_BLOCK_SIZE, SEEK_SET ) != (int64_t)*blocks * HASH_BLOCK_SIZE ) {
memlogf( "Seek error" );
- return FALSE;
+ return false;
}
uint32_t crc = crc32( 0L, Z_NULL, 0 );
int bytes = 0;
@@ -1182,18 +1181,18 @@ int image_checkBlocksCrc32(int fd, uint32_t *crc32list, const int *blocks, const
const int r = read( fd, buffer, n );
if ( r <= 0 ) {
memlogf( "Read error" );
- return FALSE;
+ return false;
}
crc = crc32( crc, (Bytef*)buffer, r );
bytes += r;
}
if ( crc != crc32list[*blocks] ) {
printf( "Block %d is %x, should be %x\n", *blocks, crc, crc32list[*blocks] );
- return FALSE;
+ return false;
}
blocks++;
}
- return TRUE;
+ return true;
}
static int64_t image_pad(const char *path, const int64_t currentSize)
@@ -1202,7 +1201,7 @@ static int64_t image_pad(const char *path, const int64_t currentSize)
char buffer[missing];
memset( buffer, 0, missing );
int tmpFd = open( path, O_WRONLY | O_APPEND );
- int success = FALSE;
+ bool success = false;
if ( tmpFd < 0 ) {
memlogf( "[WARNING] Can't open image for writing, can't fix %s", path );
} else if ( lseek( tmpFd, currentSize, SEEK_SET ) != currentSize ) {
@@ -1210,7 +1209,7 @@ static int64_t image_pad(const char *path, const int64_t currentSize)
} else if ( write( tmpFd, buffer, missing ) != missing ) {
memlogf( "[WARNING] write() failed, can't fix %s", path );
} else {
- success = TRUE;
+ success = true;
}
if ( tmpFd >= 0 ) close( tmpFd );
if ( success ) {
@@ -1226,22 +1225,22 @@ static int64_t image_pad(const char *path, const int64_t currentSize)
* TODO: Store last access time of images. Currently the
* last access time is reset on server restart. Thus it will
* currently only delete images if server uptime is > 10 hours
- * Return TRUE iff enough space is available. FALSE in random other cases
+ * Return true iff enough space is available. false in random other cases
*/
-static int image_ensureDiskSpace(uint64_t size)
+static bool image_ensureDiskSpace(uint64_t size)
{
for (;;) {
const int64_t available = file_freeDiskSpace( _basePath );
if ( available == -1 ) {
const int e = errno;
memlogf( "[WARNING] Could not get free disk space (errno %d), will assume there is enough space left... ;-)\n", e );
- return TRUE;
+ return true;
}
- if ( available > size ) return TRUE;
+ if ( available > size ) return true;
if ( dnbd3_serverUptime() < 10 * 3600 ) {
memlogf( "[INFO] Only %dMiB free, %dMiB requested, but server uptime < 10 hours...", (int)(available / (1024ll * 1024ll)),
(int)(size / (1024 * 1024)) );
- return FALSE;
+ return false;
}
memlogf( "[INFO] Only %dMiB free, %dMiB requested, freeing an image...", (int)(available / (1024ll * 1024ll)),
(int)(size / (1024 * 1024)) );
@@ -1262,10 +1261,10 @@ static int image_ensureDiskSpace(uint64_t size)
}
if ( oldest == NULL || time( NULL ) - oldest->atime < 86400 ) {
printf( "[DEBUG] No image is old enough :-(\n" );
- return FALSE;
+ return false;
}
oldest = image_lock( oldest );
- if ( oldest == NULL ) return FALSE;
+ if ( oldest == NULL ) return false;
memlogf( "[INFO] '%s:%d' has to go!", oldest->lower_name, (int)oldest->rid );
unlink( oldest->path );
size_t len = strlen( oldest->path ) + 5 + 1;
@@ -1279,7 +1278,7 @@ static int image_ensureDiskSpace(uint64_t size)
image_remove( oldest );
image_release( oldest );
}
- return FALSE;
+ return false;
}
/*
diff --git a/src/server/image.h b/src/server/image.h
index a624bfb..6d283ff 100644
--- a/src/server/image.h
+++ b/src/server/image.h
@@ -8,15 +8,15 @@ extern dnbd3_image_t *_images[SERVER_MAX_IMAGES];
extern int _num_images;
extern pthread_spinlock_t _images_lock;
-int image_isComplete(dnbd3_image_t *image);
+bool image_isComplete(dnbd3_image_t *image);
-void image_updateCachemap(dnbd3_image_t *image, uint64_t start, uint64_t end, const int set);
+void image_updateCachemap(dnbd3_image_t *image, uint64_t start, uint64_t end, const bool set);
void image_markComplete(dnbd3_image_t *image);
void image_saveAllCacheMaps();
-int image_saveCacheMap(dnbd3_image_t *image);
+bool image_saveCacheMap(dnbd3_image_t *image);
dnbd3_image_t* image_get(char *name, uint16_t revision);
@@ -26,17 +26,17 @@ dnbd3_image_t* image_lock(dnbd3_image_t *image);
dnbd3_image_t* image_release(dnbd3_image_t *image);
-int image_checkBlocksCrc32(int fd, uint32_t *crc32list, const int *blocks, const uint64_t fileSize);
+bool image_checkBlocksCrc32(int fd, uint32_t *crc32list, const int *blocks, const uint64_t fileSize);
void image_killUplinks();
dnbd3_image_t* image_free(dnbd3_image_t *image);
-int image_loadAll(char *path);
+bool image_loadAll(char *path);
-int image_create(char *image, int revision, uint64_t size);
+bool image_create(char *image, int revision, uint64_t size);
-int image_generateCrcFile(char *image);
+bool image_generateCrcFile(char *image);
void image_printAll();
diff --git a/src/server/integrity.c b/src/server/integrity.c
index 245d394..2911085 100644
--- a/src/server/integrity.c
+++ b/src/server/integrity.c
@@ -29,7 +29,7 @@ static queue_entry checkQueue[CHECK_QUEUE_SIZE];
static pthread_mutex_t integrityQueueLock;
static pthread_cond_t queueSignal;
static volatile int queueLen = -1;
-static volatile int bRunning = FALSE;
+static volatile bool bRunning = false;
static void* integrity_main(void *data);
@@ -41,9 +41,9 @@ void integrity_init()
assert( queueLen == -1 );
pthread_mutex_init( &integrityQueueLock, NULL );
pthread_cond_init( &queueSignal, NULL );
- bRunning = TRUE;
+ bRunning = true;
if ( 0 != thread_create( &thread, NULL, &integrity_main, (void *)NULL ) ) {
- bRunning = FALSE;
+ bRunning = false;
memlogf( "[WARNING] Could not start integrity check thread. Corrupted images will not be detected." );
return;
}
@@ -143,7 +143,7 @@ static void* integrity_main(void *data)
//printf( "[DEBUG] CRC check of block %d for %s succeeded :-)\n", blocks[0], image->lower_name );
} else {
memlogf( "[WARNING] Hash check for block %d of %s failed!", blocks[0], image->lower_name );
- image_updateCachemap( image, blocks[0] * HASH_BLOCK_SIZE, (blocks[0] + 1) * HASH_BLOCK_SIZE, FALSE );
+ image_updateCachemap( image, blocks[0] * HASH_BLOCK_SIZE, (blocks[0] + 1) * HASH_BLOCK_SIZE, false );
}
close( fd );
}
@@ -157,6 +157,6 @@ static void* integrity_main(void *data)
}
pthread_mutex_unlock( &integrityQueueLock );
if ( buffer != NULL ) free( buffer );
- bRunning = FALSE;
+ bRunning = false;
return NULL ;
}
diff --git a/src/server/locks.c b/src/server/locks.c
index 65e3abd..48f67a9 100644
--- a/src/server/locks.c
+++ b/src/server/locks.c
@@ -299,7 +299,7 @@ void debug_locks_start_watchdog()
void debug_locks_stop_watchdog()
{
#ifdef _DEBUG
- _shutdown = TRUE;
+ _shutdown = true;
printf( "Killing debug watchdog...\n" );
pthread_spin_lock( &initdestory );
signal_call( watchdogSignal );
diff --git a/src/server/net.c b/src/server/net.c
index ee621f8..3dc1f63 100644
--- a/src/server/net.c
+++ b/src/server/net.c
@@ -45,62 +45,62 @@
#include "../types.h"
#include "locks.h"
-static inline char recv_request_header(int sock, dnbd3_request_t *request)
+static inline bool recv_request_header(int sock, dnbd3_request_t *request)
{
int ret, fails = 0;
// Read request header from socket
while ( (ret = recv( sock, request, sizeof(*request), MSG_WAITALL )) != sizeof(*request) ) {
- if ( ret >= 0 || ++fails > SOCKET_TIMEOUT_SERVER_RETRIES ) return FALSE;
+ if ( ret >= 0 || ++fails > SOCKET_TIMEOUT_SERVER_RETRIES ) return false;
const int err = errno;
if ( err == EAGAIN || err == EINTR ) continue;
printf( "[DEBUG] Error receiving request: Could not read message header (%d/%d, e=%d)\n", ret, (int)sizeof(*request), err );
- return FALSE;
+ return false;
}
// Make sure all bytes are in the right order (endianness)
fixup_request( *request );
if ( request->magic != dnbd3_packet_magic ) {
printf( "[DEBUG] Magic in client request incorrect (cmd: %d, len: %d)\n", (int)request->cmd, (int)request->size );
- return FALSE;
+ return false;
}
// Payload sanity check
if ( request->cmd != CMD_GET_BLOCK && request->size > MAX_PAYLOAD ) {
memlogf( "[WARNING] Client tries to send a packet of type %d with %d bytes payload. Dropping client.", (int)request->cmd,
(int)request->size );
- return FALSE;
+ return false;
}
#ifdef _DEBUG
if ( _fake_delay ) usleep( _fake_delay );
#endif
- return TRUE;
+ return true;
}
-static inline char recv_request_payload(int sock, uint32_t size, serialized_buffer_t *payload)
+static inline bool recv_request_payload(int sock, uint32_t size, serialized_buffer_t *payload)
{
if ( size == 0 ) {
memlogf( "[BUG] Called recv_request_payload() to receive 0 bytes" );
- return FALSE;
+ return false;
}
if ( size > MAX_PAYLOAD ) {
memlogf( "[BUG] Called recv_request_payload() for more bytes than the passed buffer could hold!" );
- return FALSE;
+ return false;
}
if ( recv( sock, payload->buffer, size, MSG_WAITALL ) != size ) {
printf( "[ERROR] Could not receive request payload of length %d\n", (int)size );
- return FALSE;
+ return false;
}
// Prepare payload buffer for reading
serializer_reset_read( payload, size );
- return TRUE;
+ return true;
}
-static inline char send_reply(int sock, dnbd3_reply_t *reply, void *payload)
+static inline bool send_reply(int sock, dnbd3_reply_t *reply, void *payload)
{
const unsigned int size = reply->size;
fixup_reply( *reply );
if ( !payload || size == 0 ) {
if ( send( sock, reply, sizeof(dnbd3_reply_t), MSG_WAITALL ) != sizeof(dnbd3_reply_t) ) {
printf( "[DEBUG] Send failed (header-only)\n" );
- return FALSE;
+ return false;
}
} else {
struct iovec iov[2];
@@ -110,10 +110,10 @@ static inline char send_reply(int sock, dnbd3_reply_t *reply, void *payload)
iov[1].iov_len = (size_t)size;
if ( writev( sock, iov, 2 ) != sizeof(dnbd3_reply_t) + size ) {
printf( "[DEBUG] Send failed (reply with payload of %u bytes)\n", size );
- return FALSE;
+ return false;
}
}
- return TRUE;
+ return true;
}
void *net_client_handler(void *dnbd3_client)
@@ -126,7 +126,7 @@ void *net_client_handler(void *dnbd3_client)
int image_file = -1;
int num;
- int bOk = FALSE;
+ bool bOk = false;
serialized_buffer_t payload;
char *image_name;
@@ -153,7 +153,7 @@ void *net_client_handler(void *dnbd3_client)
client_version = serializer_get_uint16( &payload );
image_name = serializer_get_string( &payload );
rid = serializer_get_uint16( &payload );
- client->is_server = serializer_get_uint8( &payload );
+ client->isServer = serializer_get_uint8( &payload );
if ( request.size < 3 || !image_name || client_version < MIN_SUPPORTED_CLIENT ) {
if ( client_version < MIN_SUPPORTED_CLIENT ) {
printf( "[DEBUG] Client too old\n" );
@@ -177,8 +177,8 @@ void *net_client_handler(void *dnbd3_client)
reply.cmd = CMD_SELECT_IMAGE;
reply.size = serializer_get_written_length( &payload );
if ( send_reply( client->sock, &reply, &payload ) ) {
- if ( !client->is_server ) image->atime = time( NULL );
- bOk = TRUE;
+ if ( !client->isServer ) image->atime = time( NULL );
+ bOk = true;
}
}
}
@@ -189,9 +189,9 @@ void *net_client_handler(void *dnbd3_client)
if ( bOk ) {
// add artificial delay if applicable
- if ( client->is_server && _serverPenalty != 0 ) {
+ if ( client->isServer && _serverPenalty != 0 ) {
usleep( _serverPenalty );
- } else if ( !client->is_server && _clientPenalty != 0 ) {
+ } else if ( !client->isServer && _clientPenalty != 0 ) {
usleep( _clientPenalty );
}
if ( host_to_string( &client->host, buffer, sizeof buffer ) ) {
@@ -233,7 +233,7 @@ void *net_client_handler(void *dnbd3_client)
// This is a proxyed image, check if we need to relay the request...
start = request.offset & ~(uint64_t)(DNBD3_BLOCK_SIZE - 1);
end = (request.offset + request.size + DNBD3_BLOCK_SIZE - 1) & ~(uint64_t)(DNBD3_BLOCK_SIZE - 1);
- int isCached = TRUE;
+ bool isCached = true;
spin_lock( &image->lock );
// Check again as we only aquired the lock just now
if ( image->cache_map != NULL ) {
@@ -245,7 +245,7 @@ void *net_client_handler(void *dnbd3_client)
const int map_x = (pos >> 12) & 7; // mod 8
const uint8_t bit_mask = 0b00000001 << map_x;
if ( (image->cache_map[firstByte] & bit_mask) == 0 ) {
- isCached = FALSE;
+ isCached = false;
break;
}
pos += DNBD3_BLOCK_SIZE;
@@ -255,7 +255,7 @@ void *net_client_handler(void *dnbd3_client)
pos = firstByte + 1;
while ( pos < lastByte ) {
if ( image->cache_map[pos] != 0xff ) {
- isCached = FALSE;
+ isCached = false;
break;
}
++pos;
@@ -269,7 +269,7 @@ void *net_client_handler(void *dnbd3_client)
const int map_x = (pos >> 12) & 7; // mod 8
const uint8_t bit_mask = 0b00000001 << map_x;
if ( (image->cache_map[lastByte] & bit_mask) == 0 ) {
- isCached = FALSE;
+ isCached = false;
break;
}
pos += DNBD3_BLOCK_SIZE;
@@ -318,7 +318,7 @@ void *net_client_handler(void *dnbd3_client)
break;
case CMD_GET_SERVERS:
- client->is_server = FALSE; // Only clients request list of servers
+ client->isServer = false; // Only clients request list of servers
// Build list of known working alt servers
num = altservers_getMatching( &client->host, server_list, NUMBER_SERVERS );
reply.cmd = CMD_GET_SERVERS;
@@ -375,7 +375,7 @@ void *net_client_handler(void *dnbd3_client)
exit_client_cleanup: ;
if ( image_file != -1 ) close( image_file );
dnbd3_remove_client( client );
- client->running = FALSE;
+ client->running = false;
client = dnbd3_free_client( client );
pthread_exit( NULL );
return NULL ;
diff --git a/src/server/protocol.h b/src/server/protocol.h
index d54f44e..6d7af40 100644
--- a/src/server/protocol.h
+++ b/src/server/protocol.h
@@ -6,17 +6,17 @@
#define FLAGS8_SERVER 1
-static inline int dnbd3_get_reply(int sock, dnbd3_reply_t *reply)
+static inline bool dnbd3_get_reply(int sock, dnbd3_reply_t *reply)
{
if ( recv( sock, reply, sizeof(*reply), MSG_WAITALL ) != sizeof(*reply) ) {
- return FALSE;
+ return false;
}
fixup_reply( *reply );
- if ( reply->magic != dnbd3_packet_magic ) return FALSE;
- return TRUE;
+ if ( reply->magic != dnbd3_packet_magic ) return false;
+ return true;
}
-static inline int dnbd3_select_image(int sock, char *lower_name, uint16_t rid, uint8_t flags8)
+static inline bool dnbd3_select_image(int sock, char *lower_name, uint16_t rid, uint8_t flags8)
{
serialized_buffer_t serialized;
dnbd3_request_t request;
@@ -42,19 +42,19 @@ static inline int dnbd3_select_image(int sock, char *lower_name, uint16_t rid, u
return writev( sock, iov, 2 ) == len + sizeof(request);
}
-static inline int dnbd3_get_block(int sock, uint64_t offset, uint32_t size)
+static inline bool dnbd3_get_block(int sock, uint64_t offset, uint32_t size, uint64_t handle)
{
dnbd3_request_t request;
request.magic = dnbd3_packet_magic;
- request.handle = 0;
+ request.handle = handle;
request.cmd = CMD_GET_BLOCK;
request.offset = offset;
request.size = size;
fixup_request( request );
- return send( sock, &request, sizeof(request), 0 ) == sizeof(request);
+ return send( sock, &request, sizeof(request), MSG_NOSIGNAL ) == sizeof(request);
}
-static inline int dnbd3_get_crc32(int sock, uint32_t *master, void *buffer, size_t *bufferLen)
+static inline bool dnbd3_get_crc32(int sock, uint32_t *master, void *buffer, size_t *bufferLen)
{
dnbd3_request_t request;
dnbd3_reply_t reply;
@@ -64,43 +64,45 @@ static inline int dnbd3_get_crc32(int sock, uint32_t *master, void *buffer, size
request.offset = 0;
request.size = 0;
fixup_request( request );
- if ( send( sock, &request, sizeof(request), 0 ) != sizeof(request) ) return FALSE;
- if ( !dnbd3_get_reply( sock, &reply ) ) return FALSE;
+ if ( send( sock, &request, sizeof(request), 0 ) != sizeof(request) ) return false;
+ if ( !dnbd3_get_reply( sock, &reply ) ) return false;
if ( reply.size == 0 ) {
*bufferLen = 0;
- return TRUE;
+ return true;
}
- if ( reply.size < 4 ) return FALSE;
+ if ( reply.size < 4 ) return false;
reply.size -= 4;
- if ( reply.cmd != CMD_GET_CRC32 || reply.size > *bufferLen ) return FALSE;
+ if ( reply.cmd != CMD_GET_CRC32 || reply.size > *bufferLen ) return false;
*bufferLen = reply.size;
- if ( recv( sock, master, sizeof(uint32_t), MSG_WAITALL ) != sizeof(uint32_t) ) return FALSE;
+ if ( recv( sock, master, sizeof(uint32_t), MSG_WAITALL ) != sizeof(uint32_t) ) return false;
int done = 0;
while ( done < reply.size ) {
- const int ret = recv( sock, buffer + done, reply.size - done, 0 );
- if ( ret <= 0 ) return FALSE;
+ const int ret = recv( sock, (char*)buffer + done, reply.size - done, 0 );
+ if ( ret <= 0 ) return false;
done += ret;
}
- return TRUE;
+ return true;
}
/**
* Pass a full serialized_buffer_t and a socket fd. Parsed data will be returned in further arguments.
* Note that all strings will point into the passed buffer, so there's no need to free them.
+ * This function will also read the header for you, as this message can only occur during connection,
+ * where no unrequested messages could arrive inbetween.
*/
-static inline int dnbd3_select_image_reply(serialized_buffer_t *buffer, int sock, uint16_t *protocol_version, char **name, uint16_t *rid,
+static inline bool dnbd3_select_image_reply(serialized_buffer_t *buffer, int sock, uint16_t *protocol_version, char **name, uint16_t *rid,
uint64_t *imageSize)
{
dnbd3_reply_t reply;
if ( !dnbd3_get_reply( sock, &reply ) ) {
- return FALSE;
+ return false;
}
if ( reply.cmd != CMD_SELECT_IMAGE || reply.size < 3 || reply.size > MAX_PAYLOAD ) {
- return FALSE;
+ return false;
}
// receive reply payload
if ( recv( sock, buffer, reply.size, MSG_WAITALL ) != reply.size ) {
- return FALSE;
+ return false;
}
// handle/check reply payload
serializer_reset_read( buffer, reply.size );
@@ -108,7 +110,7 @@ static inline int dnbd3_select_image_reply(serialized_buffer_t *buffer, int sock
*name = serializer_get_string( buffer );
*rid = serializer_get_uint16( buffer );
*imageSize = serializer_get_uint64( buffer );
- return TRUE;
+ return true;
}
#endif
diff --git a/src/server/server.c b/src/server/server.c
index 3c3fa06..ee39b8f 100644
--- a/src/server/server.c
+++ b/src/server/server.c
@@ -60,9 +60,9 @@ pthread_spinlock_t _clients_lock;
* Time the server was started
*/
static time_t _startupTime = 0;
-static int _doReload = FALSE, _printStats = FALSE;
+static bool sigReload = false, sigPrintStats = false;
-static int dnbd3_add_client(dnbd3_client_t *client);
+static bool dnbd3_add_client(dnbd3_client_t *client);
static void dnbd3_handle_signal(int signum);
static void dnbd3_printClients();
@@ -109,7 +109,7 @@ void dnbd3_cleanup()
{
int i, count;
- _shutdown = TRUE;
+ _shutdown = true;
debug_locks_stop_watchdog();
memlogf( "INFO: Cleanup...\n" );
@@ -336,13 +336,13 @@ int main(int argc, char *argv[])
// +++++++++++++++++++++++++++++++++++++++++++++++++++ main loop
while ( !_shutdown ) {
// Handle signals
- if ( _doReload ) {
- _doReload = FALSE;
+ if ( sigReload ) {
+ sigReload = false;
memlogf( "INFO: SIGUSR1 received, re-scanning image directory" );
image_loadAll( NULL );
}
- if ( _printStats ) {
- _printStats = FALSE;
+ if ( sigPrintStats ) {
+ sigPrintStats = false;
printf( "[DEBUG] SIGUSR2 received, stats incoming\n" );
printf( " ** Images **\n" );
image_printAll();
@@ -413,7 +413,7 @@ dnbd3_client_t* dnbd3_init_client(struct sockaddr_storage *client, int fd)
free( dnbd3_client );
return NULL ;
}
- dnbd3_client->running = TRUE;
+ dnbd3_client->running = true;
dnbd3_client->sock = fd;
spin_init( &dnbd3_client->lock, PTHREAD_PROCESS_PRIVATE );
pthread_mutex_init( &dnbd3_client->sendMutex, NULL );
@@ -470,7 +470,7 @@ dnbd3_client_t* dnbd3_free_client(dnbd3_client_t *client)
* Add client to the clients array.
* Locks on: _clients_lock
*/
-static int dnbd3_add_client(dnbd3_client_t *client)
+static bool dnbd3_add_client(dnbd3_client_t *client)
{
int i;
spin_lock( &_clients_lock );
@@ -478,26 +478,26 @@ static int dnbd3_add_client(dnbd3_client_t *client)
if ( _clients[i] != NULL ) continue;
_clients[i] = client;
spin_unlock( &_clients_lock );
- return TRUE;
+ return true;
}
if ( _num_clients >= SERVER_MAX_CLIENTS ) {
spin_unlock( &_clients_lock );
memlogf( "[ERROR] Maximum number of clients reached!" );
- return FALSE;
+ return false;
}
_clients[_num_clients++] = client;
spin_unlock( &_clients_lock );
- return TRUE;
+ return true;
}
static void dnbd3_handle_signal(int signum)
{
if ( signum == SIGINT || signum == SIGTERM ) {
- _shutdown = TRUE;
+ _shutdown = true;
} else if ( signum == SIGUSR1 || signum == SIGHUP ) {
- _doReload = TRUE;
+ sigReload = true;
} else if ( signum == SIGUSR2 ) {
- _printStats = TRUE;
+ sigPrintStats = true;
}
}
diff --git a/src/server/sockhelper.c b/src/server/sockhelper.c
index 83bea2e..2fc0620 100644
--- a/src/server/sockhelper.c
+++ b/src/server/sockhelper.c
@@ -187,17 +187,17 @@ void sock_set_block(int sock)
fcntl( sock, F_SETFL, flags & ~(int)O_NONBLOCK );
}
-int sock_add_array(const int sock, int *array, int *array_fill, const int array_length)
+bool sock_add_array(const int sock, int *array, int *array_fill, const int array_length)
{
- if ( sock == -1 ) return TRUE;
+ if ( sock == -1 ) return true;
for (int i = 0; i < *array_fill; ++i) {
if ( array[i] == -1 ) {
array[i] = sock;
- return TRUE;
+ return true;
}
}
- if ( *array_fill >= array_length ) return FALSE;
+ if ( *array_fill >= array_length ) return false;
array[*array_fill] = sock;
(*array_fill) += 1;
- return TRUE;
+ return true;
}
diff --git a/src/server/sockhelper.h b/src/server/sockhelper.h
index cef19ec..394e5e4 100644
--- a/src/server/sockhelper.h
+++ b/src/server/sockhelper.h
@@ -77,8 +77,8 @@ inline void sock_set_addr4(char *ip, uint16_t port, struct sockaddr_in *addr)
* in between are counted too. In other words: represents the index of the last valid socket fd in the
* array plus one, or 0 if there are none.
* @param array_length the capacity of the array
- * @return TRUE on success or if the passed fd was -1, FALSE iff the array is already full
+ * @return true on success or if the passed fd was -1, false iff the array is already full
*/
-int sock_add_array(const int sock, int *array, int *array_fill, const int array_length);
+bool sock_add_array(const int sock, int *array, int *array_fill, const int array_length);
#endif /* SOCKHELPER_H_ */
diff --git a/src/server/uplink.c b/src/server/uplink.c
index cfe959c..6c00bbf 100644
--- a/src/server/uplink.c
+++ b/src/server/uplink.c
@@ -23,9 +23,9 @@
#include <fcntl.h>
static void* uplink_mainloop(void *data);
-static void uplink_send_requests(dnbd3_connection_t *link, int newOnly);
-static void uplink_handle_receive(dnbd3_connection_t *link);
-static int uplink_send_keepalive(const int fd);
+static void uplink_sendRequests(dnbd3_connection_t *link, bool newOnly);
+static void uplink_handleReceive(dnbd3_connection_t *link);
+static int uplink_sendKeepalive(const int fd);
static void uplink_addCrc32(dnbd3_connection_t *uplink);
static void uplink_sendReplicationRequest(dnbd3_connection_t *link);
@@ -36,15 +36,15 @@ static void uplink_sendReplicationRequest(dnbd3_connection_t *link);
* image. Uplinks run in their own thread.
* Locks on: _images[].lock
*/
-int uplink_init(dnbd3_image_t *image, int sock, dnbd3_host_t *host)
+bool uplink_init(dnbd3_image_t *image, int sock, dnbd3_host_t *host)
{
- if ( !_isProxy ) return FALSE;
+ if ( !_isProxy ) return false;
dnbd3_connection_t *link = NULL;
assert( image != NULL );
spin_lock( &image->lock );
if ( image->uplink != NULL ) {
spin_unlock( &image->lock );
- return TRUE;
+ return true;
}
if ( image->cache_map == NULL ) {
memlogf( "[WARNING] Uplink was requested for image %s, but it is already complete", image->lower_name );
@@ -65,19 +65,19 @@ int uplink_init(dnbd3_image_t *image, int sock, dnbd3_host_t *host)
link->rttTestResult = RTT_IDLE;
}
link->recvBufferLen = 0;
- link->shutdown = FALSE;
+ link->shutdown = false;
spin_init( &link->queueLock, PTHREAD_PROCESS_PRIVATE );
if ( 0 != thread_create( &(link->thread), NULL, &uplink_mainloop, (void *)(uintptr_t)link ) ) {
memlogf( "[ERROR] Could not start thread for new client." );
goto failure;
}
spin_unlock( &image->lock );
- return TRUE;
+ return true;
failure: ;
if ( link != NULL ) free( link );
link = image->uplink = NULL;
spin_unlock( &image->lock );
- return FALSE;
+ return false;
}
/**
@@ -102,7 +102,7 @@ void uplink_shutdown(dnbd3_image_t *image)
return;
}
image->uplink = NULL;
- uplink->shutdown = TRUE;
+ uplink->shutdown = true;
if ( uplink->signal != -1 ) signal_call( uplink->signal );
pthread_t thread = uplink->thread;
spin_unlock( &uplink->queueLock );
@@ -131,21 +131,21 @@ void uplink_removeClient(dnbd3_connection_t *uplink, dnbd3_client_t *client)
* Request a chunk of data through an uplink server
* Locks on: image.lock, uplink.queueLock
*/
-int uplink_request(dnbd3_client_t *client, uint64_t handle, uint64_t start, uint32_t length)
+bool uplink_request(dnbd3_client_t *client, uint64_t handle, uint64_t start, uint32_t length)
{
- if ( client == NULL || client->image == NULL ) return FALSE;
+ if ( client == NULL || client->image == NULL ) return false;
spin_lock( &client->image->lock );
if ( client->image->uplink == NULL ) {
spin_unlock( &client->image->lock );
printf( "[DEBUG] Uplink request for image with no uplink (%s)\n", client->image->lower_name );
- return FALSE;
+ return false;
}
dnbd3_connection_t * const uplink = client->image->uplink;
// Check if the client is the same host as the uplink. If so assume this is a circular proxy chain
if ( isSameAddress( &uplink->currentServer, &client->host ) ) {
spin_unlock( &client->image->lock );
printf( "[DEBUG] Proxy cycle detected.\n" );
- return FALSE;
+ return false;
}
int foundExisting = -1; // Index of a pending request that is a superset of our range, -1 otherwise
@@ -169,7 +169,7 @@ int uplink_request(dnbd3_client_t *client, uint64_t handle, uint64_t start, uint
if ( uplink->queueLen >= SERVER_MAX_UPLINK_QUEUE ) {
spin_unlock( &uplink->queueLock );
memlogf( "[WARNING] Uplink queue is full, consider increasing SERVER_MAX_UPLINK_QUEUE. Dropping client..." );
- return FALSE;
+ return false;
}
freeSlot = uplink->queueLen++;
}
@@ -194,7 +194,7 @@ int uplink_request(dnbd3_client_t *client, uint64_t handle, uint64_t start, uint
if ( foundExisting == -1 ) { // Only wake up uplink thread if the request needs to be relayed
signal_call( uplink->signal );
}
- return TRUE;
+ return true;
}
/**
@@ -252,9 +252,9 @@ static void* uplink_mainloop(void *data)
link->currentServer = link->betterServer;
link->replicationHandle = 0;
// Re-send all pending requests
- uplink_send_requests( link, FALSE );
+ uplink_sendRequests( link, false );
uplink_sendReplicationRequest( link );
- link->image->working = TRUE;
+ link->image->working = true;
buffer[0] = '@';
if ( host_to_string( &link->currentServer, buffer + 1, sizeof(buffer) - 1 ) ) {
printf( "[DEBUG] Now connected to %s\n", buffer + 1 );
@@ -309,10 +309,10 @@ static void* uplink_mainloop(void *data)
}
if ( link->fd != -1 ) {
// Uplink seems fine, relay requests to it...
- uplink_send_requests( link, TRUE );
+ uplink_sendRequests( link, true );
}
} else if ( events[i].data.fd == link->fd ) {
- uplink_handle_receive( link );
+ uplink_handleReceive( link );
if ( link->fd == -1 ) nextAltCheck = 0;
if ( _shutdown || link->shutdown ) goto cleanup;
} else {
@@ -342,7 +342,7 @@ static void* uplink_mainloop(void *data)
altservers_findUplink( link ); // This will set RTT_INPROGRESS (synchronous)
// Also send a keepalive packet to the currently connected server
if ( link->fd != -1 ) {
- if ( !uplink_send_keepalive( link->fd ) ) {
+ if ( !uplink_sendKeepalive( link->fd ) ) {
printf( "[DEBUG] Error sending keep-alive to uplink\n" );
altservers_serverFailed( &link->currentServer );
const int fd = link->fd;
@@ -362,7 +362,7 @@ static void* uplink_mainloop(void *data)
// TODO: If background replication is disabled, send keepalive every 30 seconds or so
#ifdef _DEBUG
if ( link->fd != -1 && !link->shutdown ) {
- int resend = FALSE;
+ bool resend = false;
time_t deadline = time( NULL ) - 10;
spin_lock( &link->queueLock );
for (i = 0; i < link->queueLen; ++i) {
@@ -371,7 +371,7 @@ static void* uplink_mainloop(void *data)
"%s\n(from %" PRIu64 " to %" PRIu64 ", status: %d)\n", link->queue[i].client->image->lower_name,
link->queue[i].from, link->queue[i].to, link->queue[i].status );
//link->queue[i].status = ULR_NEW;
- //resend = TRUE;
+ //resend = true;
spin_unlock( &link->queueLock );
printf("%s", buffer);
spin_lock( &link->queueLock );
@@ -379,7 +379,7 @@ static void* uplink_mainloop(void *data)
}
spin_unlock( &link->queueLock );
if ( resend )
- uplink_send_requests( link, TRUE );
+ uplink_sendRequests( link, true );
}
#endif
}
@@ -393,7 +393,7 @@ static void* uplink_mainloop(void *data)
link->fd = -1;
link->signal = -1;
if ( !link->shutdown ) {
- link->shutdown = TRUE;
+ link->shutdown = true;
thread_detach( link->thread );
}
spin_unlock( &link->image->lock );
@@ -412,24 +412,19 @@ static void* uplink_mainloop(void *data)
return NULL ;
}
-static void uplink_send_requests(dnbd3_connection_t *link, int newOnly)
+static void uplink_sendRequests(dnbd3_connection_t *link, bool newOnly)
{
// Scan for new requests
int j;
- dnbd3_request_t request;
- request.magic = dnbd3_packet_magic;
spin_lock( &link->queueLock );
for (j = 0; j < link->queueLen; ++j) {
if ( link->queue[j].status != ULR_NEW && (newOnly || link->queue[j].status != ULR_PENDING) ) continue;
link->queue[j].status = ULR_PENDING;
- request.handle = link->queue[j].from; // HACK: Store offset in handle too, as it won't be included in the reply
- request.cmd = CMD_GET_BLOCK;
- request.offset = link->queue[j].from;
- request.size = link->queue[j].to - link->queue[j].from;
+ const uint64_t offset = link->queue[j].from;
+ const uint32_t size = link->queue[j].to - link->queue[j].from;
spin_unlock( &link->queueLock );
- fixup_request( request );
- const int ret = send( link->fd, &request, sizeof request, MSG_NOSIGNAL );
- if ( ret != sizeof(request) ) {
+ const int ret = dnbd3_get_block( link->fd, offset, size, offset );
+ if ( !ret ) {
// Non-critical - if the connection dropped or the server was changed
// the thread will re-send this request as soon as the connection
// is reestablished.
@@ -470,7 +465,7 @@ static void uplink_sendReplicationRequest(dnbd3_connection_t *link)
for (int i = 0; i <= len; ++i) {
if ( image->cache_map == NULL || link->fd == -1 ) break;
if ( image->cache_map[i] == 0xff || (i == len && link->replicatedLastBlock) ) continue;
- if ( i == len ) link->replicatedLastBlock = TRUE; // Special treatment, last byte in map could represent less than 8 blocks
+ if ( i == len ) link->replicatedLastBlock = true; // Special treatment, last byte in map could represent less than 8 blocks
link->replicationHandle = 1; // Prevent race condition
spin_unlock( &image->lock );
// Unlocked - do not break or continue here...
@@ -497,7 +492,7 @@ static void uplink_sendReplicationRequest(dnbd3_connection_t *link)
* Receive data from uplink server and process/dispatch
* Locks on: link.lock, indirectly on images[].lock
*/
-static void uplink_handle_receive(dnbd3_connection_t *link)
+static void uplink_handleReceive(dnbd3_connection_t *link)
{
dnbd3_reply_t inReply, outReply;
int ret, i;
@@ -554,7 +549,7 @@ static void uplink_handle_receive(dnbd3_connection_t *link)
memlogf( "[ERROR] lseek() failed when writing to cache for %s", link->image->path );
} else {
ret = (int)write( link->image->cacheFd, link->recvBuffer, inReply.size );
- if ( ret > 0 ) image_updateCachemap( link->image, start, start + ret, TRUE );
+ if ( ret > 0 ) image_updateCachemap( link->image, start, start + ret, true );
}
// 2) Figure out which clients are interested in it
struct iovec iov[2];
@@ -611,7 +606,7 @@ static void uplink_handle_receive(dnbd3_connection_t *link)
/**
* Send keep alive request to server
*/
-static int uplink_send_keepalive(const int fd)
+static int uplink_sendKeepalive(const int fd)
{
static dnbd3_request_t request = { 0, 0, 0, 0, 0 };
if ( request.magic == 0 ) {
diff --git a/src/server/uplink.h b/src/server/uplink.h
index e9a4760..e77c591 100644
--- a/src/server/uplink.h
+++ b/src/server/uplink.h
@@ -4,11 +4,11 @@
#include "../types.h"
#include "globals.h"
-int uplink_init(dnbd3_image_t *image, int sock, dnbd3_host_t *host);
+bool uplink_init(dnbd3_image_t *image, int sock, dnbd3_host_t *host);
void uplink_removeClient(dnbd3_connection_t *uplink, dnbd3_client_t *client);
-int uplink_request(dnbd3_client_t *client, uint64_t handle, uint64_t start, uint32_t length);
+bool uplink_request(dnbd3_client_t *client, uint64_t handle, uint64_t start, uint32_t length);
void uplink_shutdown(dnbd3_image_t *image);
diff --git a/src/types.h b/src/types.h
index 5efa305..e2de013 100644
--- a/src/types.h
+++ b/src/types.h
@@ -24,13 +24,7 @@
#include "config.h"
#ifndef KERNEL_MODULE
#include <stdint.h>
-#endif
-
-#ifndef TRUE
-#define TRUE 1
-#endif
-#ifndef FALSE
-#define FALSE 0
+#include <stdbool.h>
#endif
#ifndef MIN