commit:142c00ad296af327d5d1718d60f23c0807033f15
author:Chip Black
committer:Chip Black
date:Sun Jun 2 18:59:47 2013 -0500
parents:5b9a1c597b87485253a11339067b60d08534f8b0
More safety checks
diff --git a/database/database.c b/database/database.c
line changes: +20/-10
index c0ec591..c8b9b58
--- a/database/database.c
+++ b/database/database.c
@@ -17,6 +17,12 @@
 #include "util.h"
 #include "config.h"
 
+#define CHECK_VALID_BLERG(r)                               \
+	if (blerg == NULL) {                               \
+		fprintf(stderr, "Invalid struct blerg\n"); \
+		return r;                                  \
+	}
+
 uint64_t blerg_get_record_count(struct blerg *blerg) {
 	uint64_t count;
 	flock(blerg->meta_fd, LOCK_SH);
@@ -218,6 +224,7 @@ open_failed_blerg_malloc:
 }
 
 int blerg_close(struct blerg *blerg) {
+	CHECK_VALID_BLERG(0)
 	blerg_segment_close(blerg);
 	munmap((void *)blerg->meta, sizeof(struct meta));
 	close(blerg->meta_fd);
@@ -231,8 +238,10 @@ int blerg_store(struct blerg *blerg, const char *data, int len) {
 	struct stat st;
 	int n;
 
-	if (len > MAX_RECORD_SIZE) {
-		fprintf(stderr, "len > 64K\n");
+	CHECK_VALID_BLERG(-1)
+
+	if (len > MAX_RECORD_SIZE || len <= 0) {
+		fprintf(stderr, "len out of bounds\n");
 		return -1;
 	}
 
@@ -282,12 +291,13 @@ int blerg_store(struct blerg *blerg, const char *data, int len) {
 }
 
 int blerg_fetch(struct blerg *blerg, int record, char **data, int *length) {
-	if (record < 0) {
+	CHECK_VALID_BLERG(0)
+	if (record < 0 || record >= blerg_get_record_count(blerg)) {
 		fprintf(stderr, "Invalid record\n");
 		return 0;
 	}
-	if (record >= blerg_get_record_count(blerg)) {
-		fprintf(stderr, "Invalid record\n");
+	if (data == NULL || length == NULL) {
+		fprintf(stderr, "data or length is null\n");
 		return 0;
 	}
 
@@ -329,11 +339,8 @@ int blerg_fetch(struct blerg *blerg, int record, char **data, int *length) {
 }
 
 time_t blerg_get_timestamp(struct blerg *blerg, int record) {
-	if (record < 0) {
-		fprintf(stderr, "Invalid record\n");
-		return 0;
-	}
-	if (record >= blerg_get_record_count(blerg)) {
+	CHECK_VALID_BLERG(0)
+	if (record < 0 || record >= blerg_get_record_count(blerg)) {
 		fprintf(stderr, "Invalid record\n");
 		return 0;
 	}
@@ -352,9 +359,12 @@ time_t blerg_get_timestamp(struct blerg *blerg, int record) {
 }
 
 int blerg_set_subscription_mark(struct blerg *blerg) {
+	CHECK_VALID_BLERG(0)
 	blerg->meta->subscription_mark = subscription_count_items(blerg->name);
+	return 1;
 }
 
 uint64_t blerg_get_subscription_mark(struct blerg *blerg) {
+	CHECK_VALID_BLERG(0)
 	return blerg->meta->subscription_mark;
 }