Subject: bin/6138: [PATCH] Battlestar save file handling 1
To: None <gnats-bugs@gnats.netbsd.org>
From: Joseph Myers <jsm@octomino.demon.co.uk>
List: netbsd-bugs
Date: 09/10/1998 21:28:09
>Number:         6138
>Category:       bin
>Synopsis:       [PATCH] Battlestar save file handling 1
>Confidential:   no
>Severity:       non-critical
>Priority:       low
>Responsible:    bin-bug-people (Utility Bug People)
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Thu Sep 10 14:35:01 1998
>Last-Modified:
>Originator:     Joseph Samuel Myers
>Organization:
Trinity College, University of Cambridge, UK
>Release:        NetBSD-current of 1998-08-30
>Environment:
[
System: Linux octomino 2.0.35 #1 Wed Aug 12 15:54:21 UTC 1998 i586 unknown
Architecture: i586
]
>Description:

The patch below improves battlestar(6)'s handling of save files.  If
restoring a game (which is only done on startup) fails, the program
must exit because it will not be initialised.  Also, it is a good idea
to check the final fread() on restoring, which will catch save files
that are too short, and to fflush() and check for write errors at the
end of saving, and to close the save files after use.  These
improvements are handled by the patch below.

>How-To-Repeat:

>Fix:

diff -ruN battlestar/save.c battlestar+/save.c
--- battlestar/save.c	Sun Oct 12 11:24:53 1997
+++ battlestar+/save.c	Thu Sep 10 21:17:15 1998
@@ -57,8 +57,7 @@
 	strcpy(home1, home);
 	strcat(home1, "/Bstar");
 	if ((fp = fopen(home1, "r")) == 0) {
-		warn("fopen %s", home1);
-		return;
+		err(1, "fopen %s", home1);
 	}
 	fread(&WEIGHT, sizeof WEIGHT, 1, fp);
 	fread(&CUMBER, sizeof CUMBER, 1, fp);
@@ -94,7 +93,10 @@
 	fread(&loved, sizeof loved, 1, fp);
 	fread(&pleasure, sizeof pleasure, 1, fp);
 	fread(&power, sizeof power, 1, fp);
-	fread(&ego, sizeof ego, 1, fp);
+	/* We must check the last read, to catch truncated save files.  */
+	if (fread(&ego, sizeof ego, 1, fp) < 1)
+		errx(1, "save file %s too short", home1);
+	fclose(fp);
 }
 
 void
@@ -149,4 +151,8 @@
 	fwrite(&pleasure, sizeof pleasure, 1, fp);
 	fwrite(&power, sizeof power, 1, fp);
 	fwrite(&ego, sizeof ego, 1, fp);
+	fflush(fp);
+	if (ferror(fp))
+		warn("fwrite %s", home1);
+	fclose(fp);
 }
>Audit-Trail:
>Unformatted: