home · contact · privacy
233a60c78043bd8e6c7de7e54c0e98eed511bcdf
[plomrogue] / src / client / io.c
1 /* src/client/io.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 1 /* PIPE_BUF */
9 #include "io.h"
10 #include <limits.h> /* PIPE_BUF */
11 #include <ncurses.h> /* halfdelay(), getch() */
12 #include <stddef.h> /* NULL */
13 #include <stdint.h> /* uint8_t, uint16_t, uint32_t */
14 #include <stdio.h> /* FILE, sprintf(), fseek(), fflush() */
15 #include <string.h> /* strcmp(), strlen(), memcpy() */
16 #include <stdlib.h> /* free(), atoi() */
17 #include <sys/stat.h> /* stat() */
18 #include <sys/types.h> /* time_t */
19 #include <time.h> /* time() */
20 #include <unistd.h> /* access() */
21 #include "../common/try_malloc.h" /* try_malloc() */
22 #include "../common/rexit.h" /* exit_trouble(), exit_err() */
23 #include "../common/readwrite.h" /* try_fopen(), try_fclose(), try_fgets(),
24                                   * try_fgetc(), textfile_width(), try_fputc(),
25                                   * read_file_into_queue(),
26                                   * get_message_from_queue(),
27                                   */
28 #include "control.h" /* try_key() */
29 #include "map.h" /* map_center() */
30 #include "windows.h" /* reset_windows_on_winch(), draw_all_wins() */
31 #include "world.h" /* world global */
32
33
34
35 /* Read next lines of "file" up to (and excluding) a line "%\n" into the
36  * world.player_inventory string.
37  */
38 static void read_inventory(char * read_buf, uint32_t linemax, FILE * file);
39
40 /* Read the next characters in "file" into "map". In detail: Read
41  * world.map.length times world.map.length characters, followed by one ignored
42  * character (that we assume is a newline).
43  */
44 static void read_map_cells(FILE * file, char ** map);
45
46 /* Return value seen by atoi() in next line of "file" when passed to try_fgets()
47  * with the given arguments.
48  */
49 static uint16_t read_value_from_line(char * read_buf, uint32_t linemax,
50                                      FILE * file);
51
52 /* If the server's worldstate file has changed since the last read_worldstate(),
53  * return a pointer to its file descriptor; else, return NULL.
54  *
55  * Two tests are performed to check for a file change. The file's last data
56  * modification time in seconds via stat() is compared against world.last_update
57  * (and if it is changed, world.last_update is re-set to it). If this does not
58  * verify a change, the first bytes of the file are read to compare the game
59  * turn number described therein to the last read turn number in world.turn.
60  *
61  * The stat() check is mostly useless, for it only detects file updates once a
62  * second. But the turn check fails if a new world is generated from turn 1 on:
63  * the new world also starts in turn 1, not signifying any world change to the
64  * turn check. The stat() check detects this change with at most 1 second delay.
65  */
66 static FILE * changed_worldstate_file(char * path);
67
68 /* Attempt to read the server's worldstate file as representation of the game
69  * world in a hard-coded serialization format. Returns 1 on success, or 0 if the
70  * out file wasn't read for supposedly not having changed since a last
71  * read_worldstate() call.
72  *
73  * map_center() is triggered by either, the first successful read_worldstate()
74  * (thus on client start), or on turn 1 (thus on world start).
75  */
76 static uint8_t read_worldstate();
77
78 /* Poll server for queue input. If no new input, send ping, or, if ping already
79  * sent but unanswered for some time, abort.
80  */
81 static void test_and_poll_server();
82
83 /* Read queue, act on them (as of right now only: derive log messages). */
84 static uint8_t read_queue();
85
86
87
88 static void read_inventory(char * read_buf, uint32_t linemax, FILE * file)
89 {
90     char * delimiter = "%\n";
91     free(world.player_inventory);
92     world.player_inventory = NULL;          /* Avoids illegal strlen() below. */
93     while (1)
94     {
95         try_fgets(read_buf, linemax + 1, file, __func__);
96         if (!(strcmp(read_buf, delimiter)))
97         {
98             break;
99         }
100         int old_size = 0;
101         if (world.player_inventory)
102         {
103             old_size = strlen(world.player_inventory);
104         }
105         int new_size = strlen(read_buf);
106         char * new_inventory = try_malloc(old_size + new_size + 1, __func__);
107         memcpy(new_inventory, world.player_inventory, old_size);
108         int test = sprintf(new_inventory + old_size, "%s", read_buf);
109         exit_trouble(test < 0, __func__, "sprintf");
110         free(world.player_inventory);
111         world.player_inventory = new_inventory;
112     }
113     world.player_inventory[strlen(world.player_inventory) - 1] = '\0';
114     world.player_inventory_select = 0;
115 }
116
117
118
119 static void read_map_cells(FILE * file, char ** map)
120 {
121     if (*map)
122     {
123         free(*map);
124         *map = NULL;
125     }
126     *map = try_malloc(world.map.length * world.map.length, __func__);
127     char * map_cells = *map;
128     uint16_t y, x;
129     for (y = 0; y < world.map.length; y++)
130     {
131         for (x = 0; x < world.map.length; x++)
132         {
133             char c = try_fgetc(file, __func__);
134             map_cells[y * world.map.length + x] = c;
135         }
136         try_fgetc(file, __func__);
137     }
138 }
139
140
141
142 static uint16_t read_value_from_line(char * read_buf, uint32_t linemax,
143                                      FILE * file)
144 {
145     try_fgets(read_buf, linemax + 1, file, __func__);
146     return atoi(read_buf);
147 }
148
149
150
151 static FILE * changed_worldstate_file(char * path)
152 {
153     struct stat stat_buf;
154     exit_trouble(stat(path, &stat_buf), __func__, "stat");
155     if (stat_buf.st_mtime != world.last_update)
156     {
157         world.last_update = stat_buf.st_mtime;
158         return try_fopen(path, "r", __func__);
159     }
160     FILE * file = try_fopen(path, "r", __func__);
161     char turn_string[6];
162     try_fgets(turn_string, 6, file, __func__);
163     if (world.turn == atoi(turn_string))
164     {
165         try_fclose(file, __func__);
166         return NULL;
167     }
168     exit_trouble(fseek(file, 0, SEEK_SET), __func__, "fseek");
169     return file;
170 }
171
172
173
174 static uint8_t read_worldstate()
175 {
176     char * path = "server/worldstate";
177     char * quit_msg = "No worldstate file found to read. Server may be down.";
178     static uint8_t first_read = 1;
179     exit_err(access(path, F_OK), quit_msg);
180     FILE * file = changed_worldstate_file(path);
181     if (!file)
182     {
183         return 0;
184     }
185     uint32_t linemax = textfile_width(file);
186     char * read_buf = try_malloc(linemax + 1, __func__);
187     world.turn = read_value_from_line(read_buf, linemax, file);
188     world.player_lifepoints = read_value_from_line(read_buf, linemax, file);
189     read_inventory(read_buf, linemax, file);
190     world.player_pos.y = read_value_from_line(read_buf, linemax, file);
191     world.player_pos.x = read_value_from_line(read_buf, linemax, file);
192     if (1 == world.turn || first_read)
193     {
194         map_center();
195         first_read = 0;
196     }
197     world.map.length = read_value_from_line(read_buf, linemax, file);
198     read_map_cells(file, &world.map.cells);
199     read_map_cells(file, &world.mem_map);
200     free(read_buf);
201     try_fclose(file, __func__);
202     return 1;
203 }
204
205
206
207 static void test_and_poll_server()
208 {
209     static time_t last_server_answer_time = 0;
210     static uint8_t ping_sent = 0;
211     if (read_file_into_queue(world.file_server_out, &world.queue))
212     {
213         last_server_answer_time = time(0);
214         return;
215     }
216     time_t now = time(0);
217     if (ping_sent && last_server_answer_time > now - 3)  /* Re-set if last    */
218     {                                                    /* ping was answered */
219         ping_sent = 0;                                   /* with server       */
220         return;                                          /* activity.         */
221     }
222     if (!ping_sent && last_server_answer_time < now - 3)
223     {
224         send("PING");
225         ping_sent = 1;
226         return;
227     }
228     exit_err(last_server_answer_time < now - 6, "Server not answering.");
229 }
230
231
232
233 static uint8_t read_queue()
234 {
235     uint8_t ret = 0;
236     char * msg;
237     while (NULL != (msg = get_message_from_queue(&world.queue)))
238     {
239         char * log_prefix = "LOG ";
240         if (!strncmp(msg, log_prefix, strlen(log_prefix)))
241         {
242             ret = 1;
243             char * log_msg = msg + strlen(log_prefix);
244             int old_size = 0;
245             if (world.log)
246             {
247                 old_size = strlen(world.log);
248             }
249             int new_size = strlen(log_msg);
250             char * new_log = try_malloc(old_size + 1 + new_size + 1, __func__);
251             memcpy(new_log, world.log, old_size);
252             int test = sprintf(new_log + old_size, "\n%s", log_msg);
253             exit_trouble(test < 0, __func__, "sprintf");
254             free(world.log);
255             world.log = new_log;
256         }
257         free(msg);
258     }
259     return ret;
260 }
261
262
263
264 extern void send(char * msg)
265 {
266     uint32_t msg_size = strlen(msg) + 1;
267     char * err = "send() tried to send message larger than PIPE_BUF bytes.";
268     exit_err(msg_size > PIPE_BUF, err);
269     try_fwrite(msg, strlen(msg), 1, world.file_server_in, __func__);
270     try_fputc('\n', world.file_server_in, __func__);
271     fflush(world.file_server_in);
272 }
273
274
275
276 extern char * io_loop()
277 {
278     world.halfdelay = 1;             /* Ensure server is polled only 10 times */
279     halfdelay(world.halfdelay);      /* a second during user inactivity.      */
280     uint8_t change_in_client = 0;
281     uint16_t last_focused_turn = world.turn;
282     while (1)
283     {
284         test_and_poll_server();
285         if (world.winch)
286         {
287             reset_windows_on_winch();
288             world.winch = 0;
289             change_in_client++;
290         }
291         if (change_in_client || read_worldstate() || read_queue())
292         {
293             if (world.turn != last_focused_turn && world.focus_each_turn)
294             {
295                 last_focused_turn = world.turn;
296                 map_center();
297             }
298             draw_all_wins();
299         }
300         change_in_client = 0;
301         int key = getch();
302         if (ERR != key)
303         {
304             change_in_client = try_key((uint16_t) key);
305             if (2 == change_in_client)
306             {
307                 break;
308             }
309         }
310     }
311     send("QUIT");
312     return "Sent QUIT to server.";
313 }