home · contact · privacy
a1bf343b57599b9c66b384caf2351ce66273180f
[plomrogue] / src / server / run.c
1 /* src/server/run.c
2  *
3  * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4  * or any later version. For details on its copyright, license, and warranties,
5  * see the file NOTICE in the root directory of the PlomRogue source package.
6  */
7
8 #define _POSIX_C_SOURCE 200809L /* strdup() */
9 #include "run.h"
10 #include <stddef.h> /* NULL */
11 #include <stdint.h> /* uint8_t, uint16_t, uint32_t, int16_t */
12 #include <stdio.h> /* FILE, printf(), fflush() */
13 #include <stdlib.h> /* free() */
14 #include <string.h> /* strlen(), strcmp(), strncmp(), strdup() */
15 #include <time.h> /* time_t, time() */
16 #include <unistd.h> /* access() */
17 #include "../common/parse_file.h" /* set_err_line_options(), token_from_line(),
18                                    * err_line(), err_line_inc(), parse_val()
19                                    */
20 #include "../common/readwrite.h" /* try_fopen(), try_fcose(), try_fwrite(),
21                                   * try_fgets(), textfile_width(), try_fputc(),
22                                   * atomic_write_finish(), build_temp_path()
23                                   */
24 #include "../common/rexit.h" /* exit_trouble(), exit_err() */
25 #include "../common/try_malloc.h" /* try_malloc() */
26 #include "ai.h" /* ai() */
27 #include "cleanup.h" /* unset_cleanup_flag() */
28 #include "god_commands.h" /* parse_god_command_(1|2|3)arg() */
29 #include "hardcoded_strings.h" /* s */
30 #include "io.h" /* io_round(), save_world() */
31 #include "things.h" /* Thing, ThingType, get_thing_action_id_by_name(),
32                      * get_player(), try_thing_proliferation()
33                      */
34 #include "world.h" /* world */
35
36
37
38 /* If "string" and "comparand" match in string, set "c_to_set" to value."  */
39 static uint8_t set_char_by_string_comparison(char * string, char * comparand,
40                                              char * c_to_set, char value);
41
42 /* Return 1 on world.exists, else 0 and err_line() appropriate error message. */
43 static uint8_t player_commands_allowed();
44
45 /* Parse player commands "tok0" with optional argument "tok1" to player action.
46  * Return 1 on success, 0 on failure.
47  */
48 static uint8_t parse_player_command_0arg(char * tok0);
49 static uint8_t parse_player_command_1arg(char * tok0, char * tok1);
50
51 /* Parse/apply (non-)meta command "tok0" (read further tokens as necessary).
52  * Return 0 on failure, 1 on success, 2 on QUIT meta command.
53  */
54 static uint8_t parse_command_nonmeta(char * tok0);
55 static uint8_t parse_command_meta(char * tok0);
56
57 /* Compare 1st line of server out file to world.server_test, abort if they don't
58  * match, but not before unsetting flags deleting files in the server directory,
59  * for in that case those must be assumed to belong to another server process.
60  */
61 static void server_test();
62
63 /* Return array of IDs of non-owned things in game world, ended by non-ID -1. */
64 static int16_t * build_whitelist();
65
66 /* Return 1 if value of "id" appears in "whitelist", else 0. */
67 static uint8_t thing_in_whitelist(uint8_t id, int16_t * whitelist);
68
69 /* Run the game world and its inhabitants (and their actions) until the player
70  * avatar is free to receive new commands (or is dead). Only actions and
71  * proliferations for non-owned things are performed that exist at the start of
72  * the turn jumped into, or started anew by the cycle.
73  */
74 static void turn_over();
75
76
77
78 static uint8_t set_char_by_string_comparison(char * string, char * comparand,
79                                              char * c_to_set, char value)
80 {
81     if (!strcmp(string, comparand))
82     {
83         * c_to_set = value;
84         return 1;
85     }
86     return 0;
87 }
88
89
90
91 static uint8_t player_commands_allowed()
92 {
93     if (!world.exists)
94     {
95         return !err_line(1, "No world exists in which to run player commands.");
96     }
97     return 1;
98 }
99
100
101
102 static uint8_t parse_player_command_0arg(char * tok0)
103 {
104     struct Thing * player = get_player();
105     if (   !strcmp(tok0, s[S_CMD_WAIT]) || !strcmp(tok0, s[S_CMD_PICKUP])
106         || !strcmp(tok0, s[S_CMD_AI]))
107     {
108         if (player_commands_allowed())
109         {
110             if (!strcmp(tok0, s[S_CMD_AI]))
111             {
112                 ai(player);
113             }
114             else
115             {
116                 player->command = get_thing_action_id_by_name(tok0);
117                 player->arg = 0;
118             }
119             turn_over();
120         }
121         return 1;
122     }
123     return 0;
124 }
125
126
127
128 static uint8_t parse_player_command_1arg(char * tok0, char * tok1)
129 {
130     struct Thing * player = get_player();
131     if (   (   parse_val(tok0, tok1, s[S_CMD_DROP], '8', (char *) &player->arg)
132             || parse_val(tok0, tok1, s[S_CMD_USE], '8', (char *) &player->arg))
133         && player_commands_allowed())
134     {
135         player->command = get_thing_action_id_by_name(tok0);
136         turn_over();
137     }
138     else if (!strcmp(tok0, s[S_CMD_MOVE]) && player_commands_allowed())
139     {
140         char dir = '\0';
141         if (!(   set_char_by_string_comparison(tok1, "east",       &dir, 'd')
142               || set_char_by_string_comparison(tok1, "south-east", &dir, 'c')
143               || set_char_by_string_comparison(tok1, "south-west", &dir, 'x')
144               || set_char_by_string_comparison(tok1, "west",       &dir, 's')
145               || set_char_by_string_comparison(tok1, "north-west", &dir, 'w')
146               || set_char_by_string_comparison(tok1, "north-east", &dir, 'e')))
147         {
148             return 0;
149         }
150         player->arg = dir;
151         player->command = get_thing_action_id_by_name(tok0);
152         turn_over();
153     }
154     else
155     {
156         return 0;
157     }
158     return 1;
159 }
160
161
162
163 static uint8_t parse_command_nonmeta(char * tok0)
164 {
165     if (parse_player_command_0arg(tok0))
166     {
167         return 1;
168     }
169     else
170     {
171         char * tok1 = token_from_line(NULL);
172         if (tok1 && (   parse_player_command_1arg(tok0, tok1)
173                      || parse_god_command_1arg(tok0, tok1)))
174         {
175             return 1;
176         }
177         else
178         {
179             char * tok2 = token_from_line(NULL);
180             if (tok2 && parse_god_command_2arg(tok0, tok1, tok2))
181             {
182                 return 1;
183             }
184             else
185             {
186                 char * tok3 = token_from_line(NULL);
187                 if (tok2 && parse_god_command_3arg(tok0, tok1, tok2, tok3))
188                 {
189                     return 1;
190                 }
191             }
192         }
193     }
194     return 0;
195 }
196
197
198
199 static uint8_t parse_command_meta(char * tok0)
200 {
201     if (!strcmp("QUIT", tok0))
202     {
203         return 2;
204     }
205     if (!strcmp("PING", tok0))
206     {
207         send_to_outfile("PONG\n", 1);
208         return 1;
209     }
210     if (!strcmp("STACK", tok0))
211     {
212         send_to_outfile("THINGS_BELOW_PLAYER START\n", 1);
213         struct Thing * player = get_player();
214         struct Thing * t;
215         for (t = world.things; t; t = t->next)
216         {
217             if (   t->pos.y == player->pos.y && t->pos.x == player->pos.x
218                 && t != player)
219             {
220                 struct ThingType * tt = get_thing_type(t->type);
221                 send_to_outfile(tt->name, 0);
222                 send_to_outfile("\n", 1);
223             }
224         }
225         send_to_outfile("THINGS_BELOW_PLAYER END\n", 1);
226         return 1;
227     }
228     return 0;
229 }
230
231
232
233 static void server_test()
234 {
235     char test[10 + 1 + 10 + 1 + 1];
236     FILE * file = try_fopen(s[S_PATH_OUT], "r", __func__);
237     try_fgets(test, 10 + 10 + 1 + 1, file, __func__);
238     try_fclose(file, __func__);
239     if (strcmp(test, world.server_test))
240     {
241         unset_cleanup_flag(CLEANUP_WORLDSTATE);
242         unset_cleanup_flag(CLEANUP_OUT);
243         unset_cleanup_flag(CLEANUP_IN);
244         char * msg = "Server test string in server output file does not match. "
245                      "This indicates that the current server process has been "
246                      "superseded by another one.";
247         exit_err(1, msg);
248     }
249 }
250
251
252
253 static int16_t * build_whitelist()
254 {
255     uint16_t i_things = NULL != world.things;
256     struct Thing * t = world.things;
257     for (; t; t = t->next, i_things++);
258     int16_t * whitelist = try_malloc(i_things * sizeof(int16_t), __func__);
259     for (i_things = 0, t = world.things; t;
260          whitelist[i_things] = t->id, t = t->next, i_things++);
261     whitelist[i_things] = -1;
262     return whitelist;
263 }
264
265
266
267 static uint8_t thing_in_whitelist(uint8_t id, int16_t * whitelist)
268 {
269     uint16_t i;
270     for (i = 0; -1 < whitelist[i]; i++)
271     {
272         if ((int16_t) id == whitelist[i])
273         {
274             return 1;
275         }
276     }
277     return 0;
278 }
279
280
281
282 static void turn_over()
283 {
284     struct Thing * player = get_player();
285     struct Thing * thing = player;
286     int16_t * whitelist = build_whitelist();
287     while (0 < player->lifepoints)
288     {
289         if (!thing)
290         {
291             world.turn++;
292             thing = world.things;
293             free(whitelist);
294             whitelist = build_whitelist();/* The whitelist excludes things    */
295         }                                 /* that appear only during the turn.*/
296         if (thing_in_whitelist(thing->id, whitelist))
297         {
298             if (0 < thing->lifepoints)
299             {
300                 if (0 == thing->command)
301                 {
302                     if (thing == player)
303                     {
304                         break;
305                     }
306                     ai(thing);
307                 }
308                 thing->progress++;
309                 struct ThingAction * ta = get_thing_action(thing->command);
310                 if (thing->progress == ta->effort)
311                 {
312                     ta->func(thing);
313                     thing->command = 0;
314                     thing->progress = 0;
315                 }
316             }
317             try_thing_proliferation(thing);
318         }
319         thing = thing->next;
320     }
321     free(whitelist);
322 }
323
324
325
326 extern void send_to_outfile(char * answer, uint8_t flush)
327 {
328     try_fwrite(answer, strlen(answer), 1, world.file_out, __func__);
329     if (flush)
330     {
331         fflush(world.file_out);
332     }
333 }
334
335
336
337 extern void record(char * msg, uint8_t force)
338 {
339     static FILE * file_tmp = NULL;
340     static time_t save_wait = 0;
341     static char * path_tmp;
342     if (!file_tmp)
343     {
344         path_tmp = build_temp_path(s[S_PATH_RECORD]);
345         file_tmp = try_fopen(path_tmp, "w", __func__);
346         if (!access(s[S_PATH_RECORD], F_OK))
347         {
348             FILE * file_read = try_fopen(s[S_PATH_RECORD], "r", __func__);
349             uint32_t linemax = textfile_width(file_read);
350             char * line = try_malloc(linemax + 1, __func__);
351             while (try_fgets(line, linemax + 1, file_read, __func__))
352             {
353                 try_fwrite(line, strlen(line), 1, file_tmp, __func__);
354             }
355             free(line);
356             try_fclose(file_read, __func__);
357         }
358     }
359     if (msg)
360     {
361         try_fwrite(msg, strlen(msg), 1, file_tmp, __func__);
362         try_fputc('\n', file_tmp, __func__);
363     }
364     if (force || time(NULL) > save_wait + 15)
365     {
366         save_wait = time(NULL);
367         save_world();
368         atomic_write_finish(file_tmp, s[S_PATH_RECORD], path_tmp);
369         file_tmp = NULL;
370     }
371 }
372
373
374
375 extern uint8_t obey_msg(char * msg, uint8_t obey_state)
376 {
377     if (world.is_verbose)
378     {
379         exit_trouble(-1 == printf("Input: %s\n", msg), __func__, "printf");
380     }
381     set_err_line_options("Trouble with message: ", msg, 0);
382     char * msg_copy = strdup(msg);
383     char * tok0 = token_from_line(msg_copy);
384     uint8_t ret = 0;
385     if (tok0)
386     {
387         ret = parse_command_meta(tok0);
388         if (ret || (obey_state < 2 && parse_command_nonmeta(tok0)))
389         {
390             if (!ret)
391             {
392                 if (world.exists)
393                 {
394                     world.do_update = 1;
395                 }
396                 if (1 == obey_state)
397                 {
398                    record(msg, 0);
399                 }
400             }
401             char * tokplus = token_from_line(NULL);
402             err_line(!(!tokplus), "Too many arguments, ignoring overflow.");
403         }
404         else if (world.replay)
405         {
406             ret = 3;
407         }
408         else if (!world.replay)
409         {
410             err_line(1, "Unknown command/argument or bad number of tokens.");
411         }
412     }
413     free(msg_copy);
414     return ret;
415 }
416
417
418
419 extern uint8_t io_loop(uint8_t obey_state)
420 {
421     while (1)
422     {
423         char * msg = io_round();
424         server_test();
425         if (msg)
426         {
427             uint8_t ret = obey_msg(msg, obey_state);
428             free(msg);
429             if (   (!world.replay && 2 == ret)
430                 || ( world.replay && 2 <= ret))
431             {
432                 return ret;
433             }
434         }
435     }
436 }