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