home · contact · privacy
Server: Execute THINGS_HERE command only on existing worlds.
[plomrogue] / src / server / run.c
index 82e0aaefb866ce80fd3f5d4f63a7f281c598ac19..d88d583041b3f5007686d42a1ac02a383ee9d549 100644 (file)
-/* src/server/run.c */
+/* src/server/run.c
+ *
+ * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
+ * or any later version. For details on its copyright, license, and warranties,
+ * see the file NOTICE in the root directory of the PlomRogue source package.
+ */
 
+#define _POSIX_C_SOURCE 200809L /* strdup() */
 #include "run.h"
 #include <stddef.h> /* NULL */
-#include <stdint.h> /* uint8_t, uint16_t, uint32_t */
-#include <stdio.h> /* FILE, sprintf() */
-#include <stdlib.h> /* free() */
-#include <string.h> /* strlen(), strncmp(), atoi() */
+#include <stdint.h> /* uint8_t, uint16_t, uint32_t, int16_t */
+#include <stdio.h> /* FILE, printf(), fflush() */
+#include <stdlib.h> /* atoi(), free() */
+#include <string.h> /* strlen(), strcmp(), strncmp(), strdup() */
+#include <time.h> /* time_t, time() */
 #include <unistd.h> /* access() */
+#include "../common/parse_file.h" /* set_err_line_options(), token_from_line(),
+                                   * err_line(), err_line_inc(), parse_val(),
+                                   * parestest_int()
+                                   */
 #include "../common/readwrite.h" /* try_fopen(), try_fcose(), try_fwrite(),
-                                  * try_fgets(), try_fclose_unlink_rename(),
-                                  * textfile_width(), try_fputc()
+                                  * try_fgets(), textfile_width(), try_fputc(),
+                                  * atomic_write_finish(), build_temp_path()
                                   */
-#include "../common/rexit.h" /* exit_trouble() */
+#include "../common/rexit.h" /* exit_trouble(), exit_err() */
+#include "../common/try_malloc.h" /* try_malloc() */
 #include "ai.h" /* ai() */
-#include "init.h" /* remake_world() */
-#include "io.h" /* io_round() */
-#include "map_object_actions.h" /* get_moa_id_by_name() */
-#include "map_objects.h" /* struct MapObj, get_player() */
-#include "world.h" /* global world */
+#include "cleanup.h" /* unset_cleanup_flag() */
+#include "god_commands.h" /* parse_god_command_(1|2|3)arg() */
+#include "hardcoded_strings.h" /* s */
+#include "io.h" /* io_round(), save_world() */
+#include "things.h" /* Thing, ThingType, get_thing_action_id_by_name(),
+                     * get_player(), try_thing_proliferation()
+                     */
+#include "world.h" /* world */
 
 
 
-/* Run the game world and its inhabitants (and their actions) until the player
- * avatar is free to receive new commands (or is dead).
+/* If "string" and "comparand" match in string, set "c_to_set" to value."  */
+static uint8_t set_char_by_string_comparison(char * string, char * comparand,
+                                             char * c_to_set, char value);
+
+/* Return 1 on world.exists, else 0 and err_line() appropriate error message. */
+static uint8_t player_commands_allowed();
+
+/* Parse player commands "tok0" with optional argument "tok1" to player action.
+ * Return 1 on success, 0 on failure.
  */
-static void turn_over();
+static uint8_t parse_player_command_0arg(char * tok0);
+static uint8_t parse_player_command_1arg(char * tok0, char * tok1);
 
-/* Helper to turn_over() to determine whether a map object's action effort has
- * reached its end. The simplicity of just comparing map_object->progress to
- * moa->effort is suspended for actor movement, for in this case the effort
- * depends on the diagonal movement penalty expressed in the ratio of
- * world.map.dist_diagonal / world.map.dist_orthogonal. (Movement being diagonal
- * or orthogonal is determined by the ->arg char encoding an even or un-even
- * number digit).
+/* Parse/apply (non-)meta command "tok0" (read further tokens as necessary).
+ * Return 0 on failure, 1 on success, 2 on QUIT meta command.
  */
-static uint8_t is_effort_finished(struct MapObjAct * moa,
-                                  struct MapObj * map_object);
+static uint8_t parse_command_nonmeta(char * tok0);
+static uint8_t parse_command_meta(char * tok0);
 
-/* If "msg"'s first part matches "command_name", set player's MapObj's .command
- * to the command's id and its .arg to a numerical value following in the latter
- * part of "msg" (if no digits are found, use 0); then finish player's turn and
- * turn game over to the NPCs via turn_over(); then return 1. Else, return 0.
+/* Compare 1st line of server out file to world.server_test, abort if they don't
+ * match, but not before unsetting flags deleting files in the server directory,
+ * for in that case those must be assumed to belong to another server process.
  */
-static uint8_t apply_player_command(char * msg, char * command_name);
+static void server_test();
 
+/* Return array of IDs of non-owned things in game world, ended by non-ID -1. */
+static int16_t * build_whitelist();
 
+/* Return 1 if value of "id" appears in "whitelist", else 0. */
+static uint8_t thing_in_whitelist(uint8_t id, int16_t * whitelist);
 
-static void turn_over()
+/* Run the game world and its inhabitants (and their actions) until the player
+ * avatar is free to receive new commands (or is dead). Only actions and
+ * proliferations for non-owned things are performed that exist at the start of
+ * the turn jumped into, or started anew by the cycle.
+ */
+static void turn_over();
+
+
+
+static uint8_t set_char_by_string_comparison(char * string, char * comparand,
+                                             char * c_to_set, char value)
 {
-    struct MapObj * player = get_player();
-    struct MapObj * map_object = player;
-    uint16_t start_turn = world.turn;
-    while (    0 < player->lifepoints
-           || (0 == player->lifepoints && start_turn == world.turn))
+    if (!strcmp(string, comparand))
     {
-        if (NULL == map_object)
-        {
-            world.turn++;
-            map_object = world.map_objs;
-        }
-        if (0 < map_object->lifepoints)
+        * c_to_set = value;
+        return 1;
+    }
+    return 0;
+}
+
+
+
+static uint8_t player_commands_allowed()
+{
+    if (!world.exists)
+    {
+        return !err_line(1, "No world exists in which to run player commands.");
+    }
+    return 1;
+}
+
+
+
+static uint8_t parse_player_command_0arg(char * tok0)
+{
+    struct Thing * player = get_player();
+    if (   !strcmp(tok0, s[S_CMD_WAIT]) || !strcmp(tok0, s[S_CMD_PICKUP])
+        || !strcmp(tok0, s[S_CMD_AI]))
+    {
+        if (player_commands_allowed())
         {
-            if (0 == map_object->command)
+            if (!strcmp(tok0, s[S_CMD_AI]))
             {
-                if (map_object == player)
-                {
-                    break;
-                }
-                ai(map_object);
+                ai(player);
             }
-            map_object->progress++;
-            struct MapObjAct * moa = world.map_obj_acts;
-            while (moa->id != map_object->command)
+            else
             {
-                moa = moa->next;
-            }
-            if (is_effort_finished(moa, map_object))
-            {
-                moa->func(map_object);
-                map_object->command = 0;
-                map_object->progress = 0;
+                player->command = get_thing_action_id_by_name(tok0);
+                player->arg = 0;
             }
+            turn_over();
         }
-        map_object = map_object->next;
+        return 1;
     }
+    return 0;
 }
 
 
 
-static uint8_t is_effort_finished(struct MapObjAct * moa,
-                                  struct MapObj * map_object)
+static uint8_t parse_player_command_1arg(char * tok0, char * tok1)
 {
-    if (moa->func != actor_move)
+    struct Thing * player = get_player();
+    if (   (   parse_val(tok0, tok1, s[S_CMD_DROP], '8', (char *) &player->arg)
+            || parse_val(tok0, tok1, s[S_CMD_USE], '8', (char *) &player->arg))
+        && player_commands_allowed())
     {
-        if (map_object->progress == moa->effort)
+        player->command = get_thing_action_id_by_name(tok0);
+        turn_over();
+    }
+    else if (!strcmp(tok0, s[S_CMD_MOVE]) && player_commands_allowed())
+    {
+        char dir = '\0';
+        if (!(   set_char_by_string_comparison(tok1, "east",       &dir, 'd')
+              || set_char_by_string_comparison(tok1, "south-east", &dir, 'c')
+              || set_char_by_string_comparison(tok1, "south-west", &dir, 'x')
+              || set_char_by_string_comparison(tok1, "west",       &dir, 's')
+              || set_char_by_string_comparison(tok1, "north-west", &dir, 'w')
+              || set_char_by_string_comparison(tok1, "north-east", &dir, 'e')))
         {
-            return 1;
+            return 0;
         }
+        player->arg = dir;
+        player->command = get_thing_action_id_by_name(tok0);
+        turn_over();
     }
-    else if (strchr("8624", map_object->arg))
+    else
     {
-        if (map_object->progress == moa->effort)
+        return 0;
+    }
+    return 1;
+}
+
+
+
+static uint8_t parse_command_nonmeta(char * tok0)
+{
+    if (parse_player_command_0arg(tok0))
+    {
+        return 1;
+    }
+    else
+    {
+        char * tok1 = token_from_line(NULL);
+        if (tok1 && (   parse_player_command_1arg(tok0, tok1)
+                     || parse_god_command_1arg(tok0, tok1)))
         {
             return 1;
         }
+        else
+        {
+            char * tok2 = token_from_line(NULL);
+            if (tok2 && parse_god_command_2arg(tok0, tok1, tok2))
+            {
+                return 1;
+            }
+            else
+            {
+                char * tok3 = token_from_line(NULL);
+                if (tok2 && parse_god_command_3arg(tok0, tok1, tok2, tok3))
+                {
+                    return 1;
+                }
+            }
+        }
+    }
+    return 0;
+}
+
+
+
+static uint8_t parse_command_meta(char * tok0)
+{
+    if (!strcmp("QUIT", tok0))
+    {
+        return 2;
+    }
+    if (!strcmp("PING", tok0))
+    {
+        send_to_outfile("PONG\n", 1);
+        return 1;
     }
-    else if (strchr("1379", map_object->arg))
+    if (!strcmp("THINGS_HERE", tok0))
     {
-        uint16_t diagonal_effort =   (moa->effort * world.map.dist_diagonal)
-                                   / world.map.dist_orthogonal;
-        if (map_object->progress == diagonal_effort)
+        char * tok1 = token_from_line(NULL);
+        char * tok2 = token_from_line(NULL);
+        if (tok1&&tok2 && !parsetest_int(tok1, '8')&&!parsetest_int(tok2, '8'))
         {
+            if (!world.exists)
+            {
+                err_line(1, "Command only works on existing worlds.");
+                return 0;
+            }
+            send_to_outfile("THINGS_HERE START\n", 1);
+            struct Thing * t;
+            for (t = world.things; t; t = t->next)
+            {
+                if (t->pos.y == atoi(tok1) && t->pos.x == atoi(tok2))
+                {
+                    struct ThingType * tt = get_thing_type(t->type);
+                    send_to_outfile(tt->name, 0);
+                    send_to_outfile("\n", 1);
+                }
+            }
+            send_to_outfile("THINGS_HERE END\n", 1);
             return 1;
         }
     }
@@ -119,86 +239,207 @@ static uint8_t is_effort_finished(struct MapObjAct * moa,
 
 
 
-static uint8_t apply_player_command(char * msg, char * command_name)
+static void server_test()
 {
-    if (!strncmp(msg, command_name, strlen(command_name)))
+    char test[10 + 1 + 10 + 1 + 1];
+    FILE * file = try_fopen(s[S_PATH_OUT], "r", __func__);
+    try_fgets(test, 10 + 10 + 1 + 1, file, __func__);
+    try_fclose(file, __func__);
+    if (strcmp(test, world.server_test))
     {
-        struct MapObj * player = get_player();
-        player->arg = atoi(&(msg[strlen(command_name)]));
-        player->command = get_moa_id_by_name(command_name);
-        turn_over();
-        return 1;
+        unset_cleanup_flag(CLEANUP_WORLDSTATE);
+        unset_cleanup_flag(CLEANUP_OUT);
+        unset_cleanup_flag(CLEANUP_IN);
+        char * msg = "Server test string in server output file does not match. "
+                     "This indicates that the current server process has been "
+                     "superseded by another one.";
+        exit_err(1, msg);
+    }
+}
+
+
+
+static int16_t * build_whitelist()
+{
+    uint16_t i_things = NULL != world.things;
+    struct Thing * t = world.things;
+    for (; t; t = t->next, i_things++);
+    int16_t * whitelist = try_malloc(i_things * sizeof(int16_t), __func__);
+    for (i_things = 0, t = world.things; t;
+         whitelist[i_things] = t->id, t = t->next, i_things++);
+    whitelist[i_things] = -1;
+    return whitelist;
+}
+
+
+
+static uint8_t thing_in_whitelist(uint8_t id, int16_t * whitelist)
+{
+    uint16_t i;
+    for (i = 0; -1 < whitelist[i]; i++)
+    {
+        if ((int16_t) id == whitelist[i])
+        {
+            return 1;
+        }
     }
     return 0;
 }
 
 
 
-extern void obey_msg(char * msg, uint8_t do_record)
+static void turn_over()
 {
-    char * f_name = "obey_msg()";
-    if (   apply_player_command(msg, "wait")   /* TODO: Check for non-error   */
-        || apply_player_command(msg, "move")   /* return value of a modified  */
-        || apply_player_command(msg, "pick_up")/* get_moa_id_by_name(); if id */
-        || apply_player_command(msg, "drop")   /* found, execute on it what's */
-        || apply_player_command(msg, "use"));  /* in apply_player_command().  */
-    else
+    struct Thing * player = get_player();
+    struct Thing * thing = player;
+    int16_t * whitelist = build_whitelist();
+    while (0 < player->lifepoints)
     {
-        char * seed_command = "seed";
-        if (!strncmp(msg, seed_command, strlen(seed_command)))
+        if (!thing)
+        {
+            world.turn++;
+            thing = world.things;
+            free(whitelist);
+            whitelist = build_whitelist();/* The whitelist excludes things    */
+        }                                 /* that appear only during the turn.*/
+        if (thing_in_whitelist(thing->id, whitelist))
         {
-            remake_world(atoi(&(msg[strlen(seed_command)])));
+            if (0 < thing->lifepoints)
+            {
+                if (0 == thing->command)
+                {
+                    if (thing == player)
+                    {
+                        break;
+                    }
+                    ai(thing);
+                }
+                thing->progress++;
+                struct ThingAction * ta = get_thing_action(thing->command);
+                if (thing->progress == ta->effort)
+                {
+                    ta->func(thing);
+                    thing->command = 0;
+                    thing->progress = 0;
+                }
+            }
+            try_thing_proliferation(thing);
         }
+        thing = thing->next;
     }
-    if (do_record)
+    free(whitelist);
+}
+
+
+
+extern void send_to_outfile(char * answer, uint8_t flush)
+{
+    try_fwrite(answer, strlen(answer), 1, world.file_out, __func__);
+    if (flush)
     {
-        char path_tmp[strlen(world.path_record) + strlen(world.tmp_suffix) + 1];
-        sprintf(path_tmp, "%s%s", world.path_record, world.tmp_suffix);
-        FILE * file_tmp  = try_fopen(path_tmp, "w", f_name);
-        if (!access(world.path_record, F_OK))
+        fflush(world.file_out);
+    }
+}
+
+
+
+extern void record(char * msg, uint8_t force)
+{
+    static FILE * file_tmp = NULL;
+    static time_t save_wait = 0;
+    static char * path_tmp;
+    if (!file_tmp)
+    {
+        path_tmp = build_temp_path(s[S_PATH_RECORD]);
+        file_tmp = try_fopen(path_tmp, "w", __func__);
+        if (!access(s[S_PATH_RECORD], F_OK))
         {
-            FILE * file_read = try_fopen(world.path_record, "r", f_name);
+            FILE * file_read = try_fopen(s[S_PATH_RECORD], "r", __func__);
             uint32_t linemax = textfile_width(file_read);
-            char line[linemax + 1];
-            while (try_fgets(line, linemax + 1, file_read, f_name))
+            char * line = try_malloc(linemax + 1, __func__);
+            while (try_fgets(line, linemax + 1, file_read, __func__))
             {
-                try_fwrite(line, strlen(line), 1, file_tmp, f_name);
+                try_fwrite(line, strlen(line), 1, file_tmp, __func__);
             }
-            try_fclose(file_read, f_name);
+            free(line);
+            try_fclose(file_read, __func__);
         }
-        try_fwrite(msg, strlen(msg), 1, file_tmp, f_name);
-        try_fputc('\n', file_tmp, f_name);
-        try_fclose_unlink_rename(file_tmp, path_tmp, world.path_record, f_name);
+    }
+    if (msg)
+    {
+        try_fwrite(msg, strlen(msg), 1, file_tmp, __func__);
+        try_fputc('\n', file_tmp, __func__);
+    }
+    if (force || time(NULL) > save_wait + 15)
+    {
+        save_wait = time(NULL);
+        save_world();
+        atomic_write_finish(file_tmp, s[S_PATH_RECORD], path_tmp);
+        file_tmp = NULL;
     }
 }
 
 
 
-extern uint8_t io_loop()
+extern uint8_t obey_msg(char * msg, uint8_t obey_state)
 {
-    char * f_name = "io_loop()";
-    while (1)
+    if (world.is_verbose)
     {
-        char * msg = io_round();
-        if (NULL == msg)
+        exit_trouble(-1 == printf("Input: %s\n", msg), __func__, "printf");
+    }
+    set_err_line_options("Trouble with message: ", msg, 0);
+    char * msg_copy = strdup(msg);
+    char * tok0 = token_from_line(msg_copy);
+    uint8_t ret = 0;
+    if (tok0)
+    {
+        ret = parse_command_meta(tok0);
+        if (ret || (obey_state < 2 && parse_command_nonmeta(tok0)))
         {
-            continue;
+            if (!ret)
+            {
+                if (world.exists)
+                {
+                    world.do_update = 1;
+                }
+                if (1 == obey_state)
+                {
+                   record(msg, 0);
+                }
+            }
+            char * tokplus = token_from_line(NULL);
+            err_line(!(!tokplus), "Too many arguments, ignoring overflow.");
         }
-        if (world.is_verbose)
+        else if (world.replay)
         {
-            exit_trouble(-1 == printf("Input: %s\n", msg), f_name, "printf()");
+            ret = 3;
         }
-        if (!strcmp("QUIT", msg))
+        else if (!world.replay)
         {
-            free(msg);
-            return 1;
+            err_line(1, "Invalid command/argument or bad number of tokens.");
         }
-        if (world.replay)
+    }
+    free(msg_copy);
+    return ret;
+}
+
+
+
+extern uint8_t io_loop(uint8_t obey_state)
+{
+    while (1)
+    {
+        char * msg = io_round();
+        server_test();
+        if (msg)
         {
+            uint8_t ret = obey_msg(msg, obey_state);
             free(msg);
-            return 0;
+            if (   (!world.replay && 2 == ret)
+                || ( world.replay && 2 <= ret))
+            {
+                return ret;
+            }
         }
-        obey_msg(msg, 1);
-        free(msg);
     }
 }