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