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