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