Magic-number elimination.
[open-adventure.git] / saveresume.c
1 /*
2  * Saving and resuming.
3  *
4  * (ESR) This replaces  a bunch of particularly nasty FORTRAN-derived code;
5  * see the history.adoc file in the source distribution for discussion.
6  *
7  * SPDX-FileCopyrightText: 1977, 2005 by Will Crowther and Don Woods
8  * SPDX-FileCopyrightText: 2017 by Eric S. Raymond
9  * SPDX-License-Identifier: BSD-2-Clause
10  */
11
12 #include <stdlib.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include <time.h>
16 #include <inttypes.h>
17
18 #include "advent.h"
19 #include "dungeon.h"
20
21 /*
22  * Bump on save format change.
23  *
24  * Note: Verify that the tests run clean before bumping this, then rebuild the check
25  * files afterwards.  Otherwise you will get a spurious failure due to the old version
26  * having been generated into a check file.
27  */
28 #define VRSION  29
29
30 /*
31  * If you change the first three members, the resume function may not properly
32  * reject saves from older versions. Later members can change, but bump the version
33  * when you do that.
34  */
35 struct save_t {
36     int64_t savetime;
37     int32_t mode;               /* not used, must be present for version detection */
38     int32_t version;
39     struct game_t game;
40 };
41 struct save_t save;
42
43 #define IGNORE(r) do{if (r){}}while(0)
44
45 int savefile(FILE *fp, int32_t version)
46 /* Save game to file. No input or output from user. */
47 {
48     save.savetime = time(NULL);
49     save.mode = -1;
50     save.version = (version == 0) ? VRSION : version;
51
52     save.game = game;
53     IGNORE(fwrite(&save, sizeof(struct save_t), 1, fp));
54     return (0);
55 }
56
57 /* Suspend and resume */
58
59 static char *strip(char *name)
60 {
61     // Trim leading whitespace
62     while(isspace((unsigned char)*name))
63         name++; // LCOV_EXCL_LINE
64     if(*name != '\0') {
65         // Trim trailing whitespace;
66         // might be left there by autocomplete
67         char *end = name + strlen(name) - 1;
68         while(end > name && isspace((unsigned char)*end))
69             end--;
70         // Write new null terminator character
71         end[1] = '\0';
72     }
73
74     return name;
75 }
76
77 int suspend(void)
78 {
79     /*  Suspend.  Offer to save things in a file, but charging
80      *  some points (so can't win by using saved games to retry
81      *  battles or to start over after learning zzword).
82      *  If ADVENT_NOSAVE is defined, gripe instead. */
83
84 #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
85     rspeak(SAVERESUME_DISABLED);
86     return GO_TOP;
87 #endif
88     FILE *fp = NULL;
89
90     rspeak(SUSPEND_WARNING);
91     if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN]))
92         return GO_CLEAROBJ;
93     game.saved = game.saved + 5;
94
95     while (fp == NULL) {
96         char* name = myreadline("\nFile name: ");
97         if (name == NULL)
98             return GO_TOP;
99         name = strip(name);
100         if (strlen(name) == 0)
101             return GO_TOP;      // LCOV_EXCL_LINE
102         fp = fopen(strip(name), WRITE_MODE);
103         if (fp == NULL)
104             printf("Can't open file %s, try again.\n", name);
105         free(name);
106     }
107
108     savefile(fp, VRSION);
109     fclose(fp);
110     rspeak(RESUME_HELP);
111     exit(EXIT_SUCCESS);
112 }
113
114 int resume(void)
115 {
116     /*  Resume.  Read a suspended game back from a file.
117      *  If ADVENT_NOSAVE is defined, gripe instead. */
118
119 #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
120     rspeak(SAVERESUME_DISABLED);
121     return GO_TOP;
122 #endif
123     FILE *fp = NULL;
124
125     if (game.loc != LOC_START || game.abbrev[LOC_START] != 1) {
126         rspeak(RESUME_ABANDON);
127         if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN]))
128             return GO_CLEAROBJ;
129     }
130
131     while (fp == NULL) {
132         char* name = myreadline("\nFile name: ");
133         if (name == NULL)
134             return GO_TOP;
135         name = strip(name);
136         if (strlen(name) == 0)
137             return GO_TOP;      // LCOV_EXCL_LINE
138         fp = fopen(name, READ_MODE);
139         if (fp == NULL)
140             printf("Can't open file %s, try again.\n", name);
141         free(name);
142     }
143
144     return restore(fp);
145 }
146
147 int restore(FILE* fp)
148 {
149     /*  Read and restore game state from file, assuming
150      *  sane initial state.
151      *  If ADVENT_NOSAVE is defined, gripe instead. */
152 #ifdef ADVENT_NOSAVE
153     rspeak(SAVERESUME_DISABLED)
154     return GO_TOP;
155 #endif
156
157     IGNORE(fread(&save, sizeof(struct save_t), 1, fp));
158     fclose(fp);
159     if (save.version != VRSION) {
160         rspeak(VERSION_SKEW, save.version / 10, MOD(save.version, 10), VRSION / 10, MOD(VRSION, 10));
161     } else if (!is_valid(save.game)) {
162         rspeak(SAVE_TAMPERING);
163         exit(EXIT_SUCCESS);
164     } else {
165         game = save.game;
166     }
167     return GO_TOP;
168 }
169
170 bool is_valid(struct game_t valgame)
171 {
172     /*  Save files can be roughly grouped into three groups:
173      *  With valid, reachable state, with valid, but unreachable
174      *  state and with invalid state. We check that state is
175      *  valid: no states are outside minimal or maximal value
176      */
177
178     /* Prevent division by zero */
179     if (valgame.abbnum == 0) {
180         return false;   // LCOV_EXCL_LINE
181     }
182
183     /* Check for RNG overflow. Truncate */
184     if (valgame.lcg_x >= LCG_M) {
185         valgame.lcg_x %= LCG_M; // LCOV_EXCL_LINE
186     }
187
188     /* Check for RNG underflow. Transpose */
189     if (valgame.lcg_x < LCG_M) {
190         valgame.lcg_x = LCG_M + (valgame.lcg_x % LCG_M);
191     }
192
193     /*  Bounds check for locations */
194     if ( valgame.chloc  < -1 || valgame.chloc  > NLOCATIONS ||
195          valgame.chloc2 < -1 || valgame.chloc2 > NLOCATIONS ||
196          valgame.loc    <  0 || valgame.loc    > NLOCATIONS ||
197          valgame.newloc <  0 || valgame.newloc > NLOCATIONS ||
198          valgame.oldloc <  0 || valgame.oldloc > NLOCATIONS ||
199          valgame.oldlc2 <  0 || valgame.oldlc2 > NLOCATIONS) {
200         return false;   // LCOV_EXCL_LINE
201     }
202     /*  Bounds check for location arrays */
203     for (int i = 0; i <= NDWARVES; i++) {
204         if (valgame.dloc[i]  < -1 || valgame.dloc[i]  > NLOCATIONS  ||
205             valgame.odloc[i] < -1 || valgame.odloc[i] > NLOCATIONS) {
206             return false;       // LCOV_EXCL_LINE
207         }
208     }
209
210     for (int i = 0; i <= NOBJECTS; i++) {
211         if (valgame.place[i] < -1 || valgame.place[i] > NLOCATIONS  ||
212             valgame.fixed[i] < -1 || valgame.fixed[i] > NLOCATIONS) {
213             return false;       // LCOV_EXCL_LINE
214         }
215     }
216
217     /*  Bounds check for dwarves */
218     if (valgame.dtotal < 0 || valgame.dtotal > NDWARVES ||
219         valgame.dkill < 0  || valgame.dkill  > NDWARVES) {
220         return false;   // LCOV_EXCL_LINE
221     }
222
223     /*  Validate that we didn't die too many times in save */
224     if (valgame.numdie >= NDEATHS) {
225         return false;   // LCOV_EXCL_LINE
226     }
227
228     /* Recalculate tally, throw the towel if in disagreement */
229     int temp_tally = 0;
230     for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
231         if (objects[treasure].is_treasure) {
232             if (valgame.prop[treasure] == STATE_NOTFOUND) {
233                 ++temp_tally;
234             }
235         }
236     }
237     if (temp_tally != valgame.tally) {
238         return false;   // LCOV_EXCL_LINE
239     }
240
241     /* Check that properties of objects aren't beyond expected */
242     for (obj_t obj = 0; obj <= NOBJECTS; obj++) {
243         /* Magic number -2 allows a STASHED version of state 1 */
244         if (valgame.prop[obj] < -2 || valgame.prop[obj] > 1) {
245             switch (obj) {
246             case RUG:
247             case DRAGON:
248             case BIRD:
249             case BOTTLE:
250             case PLANT:
251             case PLANT2:
252             case TROLL:
253             case URN:
254             case EGGS:
255             case VASE:
256             case CHAIN:
257                 if (valgame.prop[obj] == 2) // There are multiple different states, but it's convenient to clump them together
258                     continue;   // LCOV_EXCL_LINE
259             /* FALLTHRU */
260             case BEAR:
261                 if (valgame.prop[BEAR] == CONTENTED_BEAR || valgame.prop[BEAR] == BEAR_DEAD)
262                     continue;
263             /* FALLTHRU */
264             default:
265                 return false;   // LCOV_EXCL_LINE
266             }
267         }
268     }
269
270     /* Check that values in linked lists for objects in locations are inside bounds */
271     for (loc_t loc = LOC_NOWHERE; loc <= NLOCATIONS; loc++) {
272         if (valgame.atloc[loc] < NO_OBJECT || valgame.atloc[loc] > NOBJECTS * 2) {
273             return false;       // LCOV_EXCL_LINE
274         }
275     }
276     for (obj_t obj = 0; obj <= NOBJECTS * 2; obj++ ) {
277         if (valgame.link[obj] < NO_OBJECT || valgame.link[obj] > NOBJECTS * 2) {
278             return false;       // LCOV_EXCL_LINE
279         }
280     }
281
282     return true;
283 }
284
285 /* end */