home · contact · privacy
Make server config files more readable, their parsing more lenient.
[plomrogue] / src / server / configfile.c
1 /* src/server/configfile.c */
2
3 #define _POSIX_C_SOURCE 200809L /* strdup() */
4 #include <stddef.h> /* size_t, NULL */
5 #include <stdio.h> /* FILE, sprintf() */
6 #include <stdint.h> /* uint8_t, uint32_t */
7 #include <stdlib.h> /* atoi(), free() */
8 #include <string.h> /* strchr(), strcmp(), strdup(), strlen() */
9 #include <unistd.h> /* access(), F_OK */
10 #include "../common/err_try_fgets.h" /* err_line(), err_try_fgets(),
11                                       * reset_err_try_fgets_counter()
12                                       */
13 #include "../common/readwrite.h" /* try_fopen(),try_fclose(),textfile_width() */
14 #include "../common/rexit.h" /* exit_err() */
15 #include "../common/try_malloc.h" /* try_malloc() */
16 #include "cleanup.h" /* set_cleanup_flag(), CLEANUP_MAP_OBJ_DEFS,
17                       * CLEANUP_MAP_OBJ_ACTS
18                       */
19 #include "map_object_actions.h" /* struct MapObjAct */
20 #include "map_objects.h" /* struct MapObj, struct MapObjDef */
21 #include "world.h" /* world global */
22
23
24
25 /* Flags defining state of object and action entry reading ((un-)finished, ready
26  * for starting the reading of a new definition etc.
27  */
28 enum flag
29 {
30     EDIT_STARTED   = 0x01,
31     NAME_SET       = 0x02,
32     EFFORT_SET     = 0x04,
33     CORPSE_ID_SET  = 0x04,
34     SYMBOL_SET     = 0x08,
35     LIFEPOINTS_SET = 0x10,
36     CONSUMABLE_SET = 0x20,
37     READY_ACT = NAME_SET | EFFORT_SET,
38     READY_OBJ = NAME_SET | CORPSE_ID_SET | SYMBOL_SET | LIFEPOINTS_SET
39                 | CONSUMABLE_SET
40 };
41
42
43
44 /* What MapObjDef and MapObjAct structs have in common at their top. Used to
45  * have common functions run over structs of both types.
46  */
47 struct EntryHead
48 {
49     uint8_t id;
50     struct EntryHead * next;
51 };
52
53
54
55 /* Many functions working on config file lines / tokens work with these elements
56  * that only change on line change. Makes sense to pass them over together.
57  */
58 struct Context {
59     char * line;
60     char * token0;
61     char * token1;
62     char * err_pre;
63 };
64
65
66
67 /* Return next token from "line" or NULL if none is found. Tokens either a)
68  * start at the first non-whitespace character and end before the next
69  * whitespace character after that; or b) if the first non-whitespace character
70  * is a single quote followed by at least one other single quote some time later
71  * on the line, the token starts after that first single quote and ends before
72  * the second, with the next token_from_line() call starting its token search
73  * after that second quote. The only way to return an empty string (instead of
74  * NULL) as a token is to delimit the token by two succeeding single quotes.
75  * */
76 static char * token_from_line(char * line);
77
78 /* Determines the end of the token_from_line() token. */
79 static void set_token_end(char ** start, char ** limit_char);
80
81 /* Get tokens from "context" and, by their order (in the individual context and
82  * in subsequent calls of this function), interpret them as data to write into
83  * the MapObjAct / MapObjDef DB.
84  *
85  * Individual MapObjDef / MapObjAct DB entries are put together line by line
86  * before being written. Writing only happens after all necessary members of an
87  * entry have been assembled, and when additionally a) a new entry is started by
88  * a context->token0 of "ACTION" or "OBJECT"; or b) a NULL context->token0 is
89  * passed. This is interpreted as the end of the MapObjDef / MapObjAct DB read,
90  * so the appropriate cleanup flags are set and test_corpse_ids() is called.
91  */
92 static void tokens_into_entries(struct Context * context);
93
94 /* Start reading a new DB entry of "size" from tokens in "context" if ->token0
95  * matches "comparand". Set EDIT_STARTED in "flags" to mark beginning of new
96  * entry reading. Check that id of new entry in ->token1 has not already been
97  * used in DB starting at "entry_cmp".
98  */
99 static uint8_t new_entry(struct Context * context, char * comparand,
100                          enum flag * flags, size_t size,
101                          struct EntryHead ** entry,
102                          struct EntryHead * entry_cmp);
103
104 /* Write DB entry pointed to by "entry" to its appropriate location. */
105 static void write_if_entry(struct EntryHead ** entry,
106                            struct EntryHead *** entry_p_p_p);
107
108 /* Ensure that all .corpse_id members in the MapObjDef DB fit .id members of
109  * MapObjDef DB entries.
110  */
111 static void test_corpse_ids();
112
113 /* Try to read tokens in "context" as members for the entry currently edited,
114  * which must be either "mod" or "moa". What member of which of the two is set
115  * depends on which of "object_flags" and "action_flags" has EDIT_STARTED set
116  * and on the key name of ->token0. Return 1 if interpretation succeeds, else 0.
117  *
118  * Note that MapObjAct entries' .name also determines their .func.
119  */
120 static uint8_t set_members(struct Context * context, enum flag * object_flags,
121                            enum flag * action_flags, struct MapObjDef * mod,
122                            struct MapObjAct * moa);
123
124 /* If "context"->token0 fits "comparand", set "element" to value read from
125  * ->token1 as either string (type: "s"), char ("c") or uint8 ("8"), set
126  * that element's flag to "flags" and return 1; else return 0.
127  */
128 static uint8_t set_val(struct Context * context, char * comparand,
129                        enum flag * flags, enum flag set_flag, char type,
130                        char * element);
131
132 /* Writes "context"->token1 to "target" only if it describes a proper uint8. */
133 static void set_uint8(struct Context * context, uint8_t * target);
134
135 /* If "name" fits "moa"->name, set "moa"->func to "func". (Derives MapObjAct
136  * .func from .name for set_members().
137  */
138 static uint8_t try_func_name(struct MapObjAct * moa,
139                              char * name, void (* func) (struct MapObj *));
140
141
142
143 static char * token_from_line(char * line)
144 {
145     static char * final_char = NULL;
146     static char * limit_char = NULL;
147     char * start = limit_char + 1;
148     if (line)
149     {
150         start      = line;
151         limit_char = start;
152         final_char = &(line[strlen(line)]);
153         if ('\n' == *(final_char - 1))
154         {
155             *(--final_char) = '\0';
156         }
157     }
158     uint8_t empty = 1;
159     uint32_t i;
160     for (i = 0; '\0' != start[i]; i++)
161     {
162         if (' ' != start[i] && '\t' != start[i])
163         {
164             start = &start[i];
165             empty = 0;
166             break;
167         }
168     }
169     if (empty)
170     {
171         return start = NULL;
172     }
173     set_token_end(&start, &limit_char);
174     return start;
175 }
176
177
178
179 static void set_token_end(char ** start, char ** limit_char)
180 {
181     char * end_quote = ('\'' == (*start)[0]) ? strchr(*start + 1, '\'') : NULL;
182     *start = (end_quote) ? *start + 1 : *start;
183     if (end_quote)
184     {
185         *end_quote = '\0';
186         *limit_char = end_quote;
187         return;
188     }
189     char * space = strchr(*start, ' ');
190     char * tab   = strchr(*start, '\t');
191     space = (!space || (tab && tab < space)) ? tab : space;
192     if (space)
193     {
194         * space = '\0';
195     }
196     *limit_char = strchr(*start, '\0');
197 }
198
199
200
201 static void tokens_into_entries(struct Context * context)
202 {
203     char * str_act = "ACTION";
204     char * str_obj = "OBJECT";
205     static struct MapObjAct ** moa_p_p = &world.map_obj_acts;
206     static struct MapObjDef ** mod_p_p = &world.map_obj_defs;
207     static enum flag action_flags = READY_ACT;
208     static enum flag object_flags = READY_OBJ;
209     static struct EntryHead * moa = NULL;
210     static struct EntryHead * mod = NULL;
211     if (   !context->token0
212         || !strcmp(context->token0,str_act) || !strcmp(context->token0,str_obj))
213     {
214         char * err_fin = "Last definition block not finished yet.";
215         err_line((action_flags & READY_ACT) ^ READY_ACT,
216                  context->line, context->err_pre, err_fin);
217         err_line((object_flags & READY_OBJ) ^ READY_OBJ,
218                  context->line, context->err_pre, err_fin);
219         object_flags = action_flags = READY_OBJ;
220         write_if_entry(&moa, (struct EntryHead ***) &moa_p_p);
221         write_if_entry(&mod, (struct EntryHead ***) &mod_p_p);
222     }
223     if (!context->token0)
224     {
225         set_cleanup_flag(CLEANUP_MAP_OBJECT_ACTS | CLEANUP_MAP_OBJECT_DEFS);
226         test_corpse_ids();
227         return;
228     }
229     if (!(   new_entry(context, str_act, &action_flags,
230                        sizeof(struct MapObjAct), (struct EntryHead**) &moa,
231                        (struct EntryHead *) world.map_obj_acts)
232           || new_entry(context, str_obj, &object_flags,
233                        sizeof(struct MapObjDef), (struct EntryHead**) &mod,
234                        (struct EntryHead *) world.map_obj_defs)
235           || set_members(context, &object_flags, &action_flags,
236                          (struct MapObjDef *) mod, (struct MapObjAct *) moa)))
237     {
238         err_line(1, context->line, context->err_pre, "Unknown argument");
239     }
240 }
241
242
243
244 static uint8_t new_entry(struct Context * context, char * comparand,
245                          enum flag * flags, size_t size,
246                          struct EntryHead ** entry,struct EntryHead * entry_cmp)
247 {
248     char * f_name = "new_entry()";
249     char * err_uni = "Declaration of ID already used.";
250     if (!strcmp(context->token0, comparand))
251     {
252         * flags = EDIT_STARTED;
253         * entry = try_malloc(size, f_name);
254         set_uint8(context, &((*entry)->id));
255         for (; NULL != entry_cmp; entry_cmp = entry_cmp->next)
256         {
257             err_line((*entry)->id == entry_cmp->id,
258                      context->line, context->err_pre, err_uni);
259         }
260         return 1;
261     }
262     return 0;
263 }
264
265
266
267 static void write_if_entry(struct EntryHead ** entry,
268                            struct EntryHead *** entry_p_p_p)
269 {
270     if (*entry)
271     {
272         (* entry)->next = NULL;
273         ** entry_p_p_p = *entry;
274         * entry_p_p_p = &((*entry)->next);
275         * entry = NULL;  /* So later runs of this don't re-append same entry. */
276     }
277 }
278
279
280
281 static void test_corpse_ids()
282 {
283     char * f_name = "test_corpse_ids()";
284     char * err_corpse_prefix = "In the object definition DB, one object corpse "
285                                "ID does not reference any known object in the "
286                                "DB. ID of responsible object: ";
287     char * err_corpse = try_malloc(strlen(err_corpse_prefix) + 3 + 1, f_name);
288     struct MapObjDef * test_entry_0 = world.map_obj_defs;
289     for (; test_entry_0; test_entry_0 = test_entry_0->next)
290     {
291         uint8_t corpse_id_found = 0;
292         struct MapObjDef * test_entry_1 = world.map_obj_defs;
293         for (; test_entry_1; test_entry_1 = test_entry_1->next)
294         {
295             if (test_entry_0->corpse_id == test_entry_1->id)
296             {
297                 corpse_id_found = 1;
298             }
299         }
300         sprintf(err_corpse, "%s%d", err_corpse_prefix, test_entry_0->id);
301         exit_err(!corpse_id_found, err_corpse);
302     }
303     free(err_corpse);
304 }
305
306
307
308 static uint8_t set_members(struct Context * context, enum flag * object_flags,
309                            enum flag * action_flags, struct MapObjDef * mod,
310                            struct MapObjAct * moa)
311 {
312     if (   * action_flags & EDIT_STARTED
313         && set_val(context, "NAME", action_flags,
314                    NAME_SET, 's', (char *) &moa->name))
315     {
316         if (!(   try_func_name(moa, "move", actor_move)
317               || try_func_name(moa, "pick_up", actor_pick)
318               || try_func_name(moa, "drop", actor_drop)
319               || try_func_name(moa, "use", actor_use)))
320         {
321             moa->func = actor_wait;
322         }
323         *action_flags = *action_flags | NAME_SET;
324         return 1;
325     }
326     else if (   set_val(context, "NAME", object_flags,
327                         NAME_SET, 's', (char *) &mod->name)
328              || set_val(context, "SYMBOL", object_flags,
329                         SYMBOL_SET, 'c', (char *) &mod->char_on_map)
330              || set_val(context, "EFFORT", action_flags,
331                         EFFORT_SET, '8', (char *) &moa->effort)
332              || set_val(context, "LIFEPOINTS", object_flags,
333                         LIFEPOINTS_SET, '8', (char *) &mod->lifepoints)
334              || set_val(context, "CONSUMABLE", object_flags,
335                         CONSUMABLE_SET, '8', (char *) &mod->consumable)
336              || set_val(context, "CORPSE_ID", object_flags,
337                         CORPSE_ID_SET, '8', (char *) &mod->corpse_id))
338     {
339         return 1;
340     }
341     return 0;
342 }
343
344
345
346 static uint8_t set_val(struct Context * context, char * comparand,
347                        enum flag * flags, enum flag set_flag, char type,
348                        char * element)
349 {
350     char * err_out = "Outside appropriate definition's context.";
351     char * err_singlechar = "Value must be single ASCII character.";
352     if (!strcmp(context->token0, comparand))
353     {
354         err_line(!(* flags & EDIT_STARTED),
355                  context->line, context->err_pre, err_out);
356         * flags = * flags | set_flag;
357         if      ('s' == type)
358         {
359             * (char **) element = strdup(context->token1);
360         }
361         else if ('c' == type)
362         {
363             err_line(1 != strlen(context->token1),
364                      context->line, context->err_pre, err_singlechar);
365             * element = (context->token1)[0];
366         }
367         else if ('8' == type)
368         {
369             set_uint8(context, (uint8_t *) element);
370         }
371         return 1;
372     }
373     return 0;
374 }
375
376
377
378 static void set_uint8(struct Context * context, uint8_t * target)
379 {
380     char * err_uint8 = "Value not unsigned decimal number between 0 and 255.";
381     uint8_t i;
382     uint8_t is_uint8 = 1;
383     for (i = 0; '\0' != context->token1[i]; i++)
384     {
385         if (i > 2 || '0' > context->token1[i] || '9' < context->token1[i])
386         {
387             is_uint8 = 0;
388         }
389     }
390     if (is_uint8 && atoi(context->token1) > UINT8_MAX)
391     {
392         is_uint8 = 0;
393     }
394     err_line(!(is_uint8), context->line, context->err_pre, err_uint8);
395     *target = atoi(context->token1);
396 }
397
398
399
400 static uint8_t try_func_name(struct MapObjAct * moa,
401                              char * name, void (* func) (struct MapObj *))
402 {
403     if (0 == strcmp(moa->name, name))
404     {
405         moa->func = func;
406         return 1;
407     }
408     return 0;
409 }
410
411
412
413 extern void read_config_file() {
414     char * f_name = "read_new_config_file()";
415     char * path = world.path_config;
416     struct Context context;
417     char * err_pre_prefix = "Failed reading config file: \"";
418     char * err_pre_affix = "\". ";
419     context.err_pre = try_malloc(strlen(err_pre_prefix) + strlen(path)
420                                  + strlen(err_pre_affix) + 1, f_name);
421     sprintf(context.err_pre, "%s%s%s", err_pre_prefix, path, err_pre_affix);
422     exit_err(access(path, F_OK), context.err_pre);
423     FILE * file = try_fopen(path, "r", f_name);
424     uint32_t linemax = textfile_width(file);
425     context.line = try_malloc(linemax + 1, f_name);
426     reset_err_try_fgets_counter();
427     err_line(0 == linemax, context.line, context.err_pre, "File is empty.");
428     context.token0 = NULL; /* For tokens_into_entries() if while() stagnates. */
429     char * err_val = "No value given.";
430     char * err_many = "Too many values.";
431     while (err_try_fgets(context.line, linemax + 1, file, context.err_pre, ""))
432     {
433         char * line_copy = strdup(context.line);
434         context.token0 = token_from_line(line_copy);
435         if (context.token0)
436         {
437             err_line(0 == (context.token1 = token_from_line(NULL)),
438                      context.line, context.err_pre, err_val);
439             err_line(NULL != token_from_line(NULL),
440                      context.line, context.err_pre, err_many);
441             tokens_into_entries(&context);
442             context.token0 = NULL;
443         }
444         free(line_copy);
445     }
446     tokens_into_entries(&context);
447     try_fclose(file, f_name);
448     free(context.line);
449     free(context.err_pre);
450 }