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