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