Give savefiles an identifting header. SAve format version gets bumped.
[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 struct save_t save;
22
23 #define IGNORE(r) do{if (r){}}while(0)
24
25 int savefile(FILE *fp, int32_t version)
26 /* Save game to file. No input or output from user. */
27 {
28     memcpy(&save.magic, ADVENT_MAGIC, sizeof(ADVENT_MAGIC));
29     save.version = (version == 0) ? SAVE_VERSION : version;
30
31     save.game = game;
32     IGNORE(fwrite(&save, sizeof(struct save_t), 1, fp));
33     return (0);
34 }
35
36 /* Suspend and resume */
37
38 static char *strip(char *name)
39 {
40     // Trim leading whitespace
41     while(isspace((unsigned char)*name))
42         name++; // LCOV_EXCL_LINE
43     if(*name != '\0') {
44         // Trim trailing whitespace;
45         // might be left there by autocomplete
46         char *end = name + strlen(name) - 1;
47         while(end > name && isspace((unsigned char)*end))
48             end--;
49         // Write new null terminator character
50         end[1] = '\0';
51     }
52
53     return name;
54 }
55
56 int suspend(void)
57 {
58     /*  Suspend.  Offer to save things in a file, but charging
59      *  some points (so can't win by using saved games to retry
60      *  battles or to start over after learning zzword).
61      *  If ADVENT_NOSAVE is defined, gripe instead. */
62
63 #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
64     rspeak(SAVERESUME_DISABLED);
65     return GO_TOP;
66 #endif
67     FILE *fp = NULL;
68
69     rspeak(SUSPEND_WARNING);
70     if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN]))
71         return GO_CLEAROBJ;
72     game.saved = game.saved + 5;
73
74     while (fp == NULL) {
75         char* name = myreadline("\nFile name: ");
76         if (name == NULL)
77             return GO_TOP;
78         name = strip(name);
79         if (strlen(name) == 0)
80             return GO_TOP;      // LCOV_EXCL_LINE
81         fp = fopen(strip(name), WRITE_MODE);
82         if (fp == NULL)
83             printf("Can't open file %s, try again.\n", name);
84         free(name);
85     }
86
87     savefile(fp, SAVE_VERSION);
88     fclose(fp);
89     rspeak(RESUME_HELP);
90     exit(EXIT_SUCCESS);
91 }
92
93 int resume(void)
94 {
95     /*  Resume.  Read a suspended game back from a file.
96      *  If ADVENT_NOSAVE is defined, gripe instead. */
97
98 #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
99     rspeak(SAVERESUME_DISABLED);
100     return GO_TOP;
101 #endif
102     FILE *fp = NULL;
103
104     if (game.loc != LOC_START || game.abbrev[LOC_START] != 1) {
105         rspeak(RESUME_ABANDON);
106         if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN]))
107             return GO_CLEAROBJ;
108     }
109
110     while (fp == NULL) {
111         char* name = myreadline("\nFile name: ");
112         if (name == NULL)
113             return GO_TOP;
114         name = strip(name);
115         if (strlen(name) == 0)
116             return GO_TOP;      // LCOV_EXCL_LINE
117         fp = fopen(name, READ_MODE);
118         if (fp == NULL)
119             printf("Can't open file %s, try again.\n", name);
120         free(name);
121     }
122
123     return restore(fp);
124 }
125
126 int restore(FILE* fp)
127 {
128     /*  Read and restore game state from file, assuming
129      *  sane initial state.
130      *  If ADVENT_NOSAVE is defined, gripe instead. */
131 #ifdef ADVENT_NOSAVE
132     rspeak(SAVERESUME_DISABLED)
133     return GO_TOP;
134 #endif
135
136     IGNORE(fread(&save, sizeof(struct save_t), 1, fp));
137     fclose(fp);
138     if (save.version != SAVE_VERSION) {
139         rspeak(VERSION_SKEW, save.version / 10, MOD(save.version, 10), SAVE_VERSION / 10, MOD(SAVE_VERSION, 10));
140     } else if (!is_valid(save.game)) {
141         rspeak(SAVE_TAMPERING);
142         exit(EXIT_SUCCESS);
143     } else {
144         game = save.game;
145     }
146     return GO_TOP;
147 }
148
149 bool is_valid(struct game_t valgame)
150 {
151     /*  Save files can be roughly grouped into three groups:
152      *  With valid, reachable state, with valid, but unreachable
153      *  state and with invalid state. We check that state is
154      *  valid: no states are outside minimal or maximal value
155      */
156
157     /* Prevent division by zero */
158     if (valgame.abbnum == 0) {
159         return false;   // LCOV_EXCL_LINE
160     }
161
162     /* Check for RNG overflow. Truncate */
163     if (valgame.lcg_x >= LCG_M) {
164         valgame.lcg_x %= LCG_M; // LCOV_EXCL_LINE
165     }
166
167     /* Check for RNG underflow. Transpose */
168     if (valgame.lcg_x < LCG_M) {
169         valgame.lcg_x = LCG_M + (valgame.lcg_x % LCG_M);
170     }
171
172     /*  Bounds check for locations */
173     if ( valgame.chloc  < -1 || valgame.chloc  > NLOCATIONS ||
174          valgame.chloc2 < -1 || valgame.chloc2 > NLOCATIONS ||
175          valgame.loc    <  0 || valgame.loc    > NLOCATIONS ||
176          valgame.newloc <  0 || valgame.newloc > NLOCATIONS ||
177          valgame.oldloc <  0 || valgame.oldloc > NLOCATIONS ||
178          valgame.oldlc2 <  0 || valgame.oldlc2 > NLOCATIONS) {
179         return false;   // LCOV_EXCL_LINE
180     }
181     /*  Bounds check for location arrays */
182     for (int i = 0; i <= NDWARVES; i++) {
183         if (valgame.dloc[i]  < -1 || valgame.dloc[i]  > NLOCATIONS  ||
184             valgame.odloc[i] < -1 || valgame.odloc[i] > NLOCATIONS) {
185             return false;       // LCOV_EXCL_LINE
186         }
187     }
188
189     for (int i = 0; i <= NOBJECTS; i++) {
190         if (valgame.place[i] < -1 || valgame.place[i] > NLOCATIONS  ||
191             valgame.fixed[i] < -1 || valgame.fixed[i] > NLOCATIONS) {
192             return false;       // LCOV_EXCL_LINE
193         }
194     }
195
196     /*  Bounds check for dwarves */
197     if (valgame.dtotal < 0 || valgame.dtotal > NDWARVES ||
198         valgame.dkill < 0  || valgame.dkill  > NDWARVES) {
199         return false;   // LCOV_EXCL_LINE
200     }
201
202     /*  Validate that we didn't die too many times in save */
203     if (valgame.numdie >= NDEATHS) {
204         return false;   // LCOV_EXCL_LINE
205     }
206
207     /* Recalculate tally, throw the towel if in disagreement */
208     int temp_tally = 0;
209     for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
210         if (objects[treasure].is_treasure) {
211             if (valgame.prop[treasure] == STATE_NOTFOUND) {
212                 ++temp_tally;
213             }
214         }
215     }
216     if (temp_tally != valgame.tally) {
217         return false;   // LCOV_EXCL_LINE
218     }
219
220     /* Check that properties of objects aren't beyond expected */
221     for (obj_t obj = 0; obj <= NOBJECTS; obj++) {
222         /* Magic number -2 allows a STASHED version of state 1 */
223         if (valgame.prop[obj] < -2 || valgame.prop[obj] > 1) {
224             switch (obj) {
225             case RUG:
226             case DRAGON:
227             case BIRD:
228             case BOTTLE:
229             case PLANT:
230             case PLANT2:
231             case TROLL:
232             case URN:
233             case EGGS:
234             case VASE:
235             case CHAIN:
236                 if (valgame.prop[obj] == 2) // There are multiple different states, but it's convenient to clump them together
237                     continue;   // LCOV_EXCL_LINE
238             /* FALLTHRU */
239             case BEAR:
240                 if (valgame.prop[BEAR] == CONTENTED_BEAR || valgame.prop[BEAR] == BEAR_DEAD)
241                     continue;
242             /* FALLTHRU */
243             default:
244                 return false;   // LCOV_EXCL_LINE
245             }
246         }
247     }
248
249     /* Check that values in linked lists for objects in locations are inside bounds */
250     for (loc_t loc = LOC_NOWHERE; loc <= NLOCATIONS; loc++) {
251         if (valgame.atloc[loc] < NO_OBJECT || valgame.atloc[loc] > NOBJECTS * 2) {
252             return false;       // LCOV_EXCL_LINE
253         }
254     }
255     for (obj_t obj = 0; obj <= NOBJECTS * 2; obj++ ) {
256         if (valgame.link[obj] < NO_OBJECT || valgame.link[obj] > NOBJECTS * 2) {
257             return false;       // LCOV_EXCL_LINE
258         }
259     }
260
261     return true;
262 }
263
264 /* end */