home · contact · privacy
ee4dcc2151a7a2ce87792a61a502ab03e6f47b11
[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> /* timeout(), getch() */
12 #include <stddef.h> /* NULL */
13 #include <stdint.h> /* uint8_t, uint16_t, uint32_t, UINT32_MAX */
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 "../common/yx_uint8.h" /* yx_uint8 */
29 #include "control.h" /* try_key() */
30 #include "map.h" /* query_mapcell() */
31 #include "windows.h" /* Win, reset_windows_on_winch(), draw_all_wins(),
32                       * get_win_by_id()
33                       */
34 #include "world.h" /* world global */
35
36
37
38 /* Read next lines of "file" up to (and excluding) a line "%\n" into the
39  * world.player_inventory string.
40  */
41 static void read_inventory(char * read_buf, uint32_t linemax, FILE * file);
42
43 /* Read the next characters in "file" into "map". In detail: Read
44  * world.map.length times world.map.length characters, followed by one ignored
45  * character (that we assume is a newline).
46  */
47 static void read_map_cells(FILE * file, char ** map);
48
49 /* Return value seen by atoi() in next line of "file" when passed to try_fgets()
50  * with the given arguments.
51  */
52 static uint16_t read_value_from_line(char * read_buf, uint32_t linemax,
53                                      FILE * file);
54
55 /* If the server's worldstate file has changed since the last read_worldstate(),
56  * return a pointer to its file descriptor; else, return NULL.
57  *
58  * Two tests are performed to check for a file change. The file's last data
59  * modification time in seconds via stat() is compared against world.last_update
60  * (and if it is changed, world.last_update is re-set to it). If this does not
61  * verify a change, the first bytes of the file are read to compare the game
62  * turn number described therein to the last read turn number in world.turn.
63  *
64  * The stat() check is mostly useless, for it only detects file updates once a
65  * second. But the turn check fails if a new world is generated from turn 1 on:
66  * the new world also starts in turn 1, not signifying any world change to the
67  * turn check. The stat() check detects this change with at most 1 second delay.
68  */
69 static FILE * changed_worldstate_file(char * path);
70
71 /* Attempt to read the server's worldstate file as representation of the game
72  * world in a hard-coded serialization format. Returns 1 on success, or 0 if the
73  * out file wasn't read for supposedly not having changed since a last
74  * read_worldstate() call.
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 /* If "string", append \n-prefixed "append", else write "append" as "string". */
84 static void nl_append_string(char * append, char ** string);
85
86 /* Read messages from queue, act on them. */
87 static uint8_t read_queue();
88
89
90
91 static void read_inventory(char * read_buf, uint32_t linemax, FILE * file)
92 {
93     char * delimiter = "%\n";
94     free(world.player_inventory);
95     world.player_inventory = NULL;          /* Avoids illegal strlen() below. */
96     while (1)
97     {
98         try_fgets(read_buf, linemax + 1, file, __func__);
99         if (!(strcmp(read_buf, delimiter)))
100         {
101             break;
102         }
103         int old_size = 0;
104         if (world.player_inventory)
105         {
106             old_size = strlen(world.player_inventory);
107         }
108         int new_size = strlen(read_buf);
109         char * new_inventory = try_malloc(old_size + new_size + 1, __func__);
110         memcpy(new_inventory, world.player_inventory, old_size);
111         int test = sprintf(new_inventory + old_size, "%s", read_buf);
112         exit_trouble(test < 0, __func__, "sprintf");
113         free(world.player_inventory);
114         world.player_inventory = new_inventory;
115     }
116     world.player_inventory[strlen(world.player_inventory) - 1] = '\0';
117     world.player_inventory_select = 0;
118 }
119
120
121
122 static void read_map_cells(FILE * file, char ** map)
123 {
124     if (*map)
125     {
126         free(*map);
127         *map = NULL;
128     }
129     *map = try_malloc(world.map.length * world.map.length, __func__);
130     char * map_cells = *map;
131     uint16_t y, x;
132     for (y = 0; y < world.map.length; y++)
133     {
134         for (x = 0; x < world.map.length; x++)
135         {
136             char c = try_fgetc(file, __func__);
137             map_cells[y * world.map.length + x] = c;
138         }
139         try_fgetc(file, __func__);
140     }
141 }
142
143
144
145 static uint16_t read_value_from_line(char * read_buf, uint32_t linemax,
146                                      FILE * file)
147 {
148     try_fgets(read_buf, linemax + 1, file, __func__);
149     return atoi(read_buf);
150 }
151
152
153
154 static FILE * changed_worldstate_file(char * path)
155 {
156     struct stat stat_buf;
157     exit_trouble(stat(path, &stat_buf), __func__, "stat");
158     if (stat_buf.st_mtime != world.last_update)
159     {
160         world.last_update = stat_buf.st_mtime;
161         return try_fopen(path, "r", __func__);
162     }
163     FILE * file = try_fopen(path, "r", __func__);
164     char turn_string[6];
165     try_fgets(turn_string, 6, file, __func__);
166     if (world.turn == atoi(turn_string))
167     {
168         try_fclose(file, __func__);
169         return NULL;
170     }
171     exit_trouble(fseek(file, 0, SEEK_SET), __func__, "fseek");
172     return file;
173 }
174
175
176
177 static uint8_t read_worldstate()
178 {
179     char * path = "server/worldstate";
180     char * quit_msg = "No worldstate file found to read. Server may be down.";
181     exit_err(access(path, F_OK), quit_msg);
182     FILE * file = changed_worldstate_file(path);
183     if (!file)
184     {
185         return 0;
186     }
187     uint32_t linemax = textfile_width(file);
188     char * read_buf = try_malloc(linemax + 1, __func__);
189     world.turn = read_value_from_line(read_buf, linemax, file);
190     world.player_lifepoints = read_value_from_line(read_buf, linemax, file);
191     read_inventory(read_buf, linemax, file);
192     world.player_pos.y = read_value_from_line(read_buf, linemax, file);
193     world.player_pos.x = read_value_from_line(read_buf, linemax, file);
194     world.map.length = read_value_from_line(read_buf, linemax, file);
195     read_map_cells(file, &world.map.cells);
196     read_map_cells(file, &world.mem_map);
197     free(read_buf);
198     try_fclose(file, __func__);
199     return 1;
200 }
201
202
203
204 static void test_and_poll_server()
205 {
206     static time_t last_server_answer_time = 0;
207     static time_t last_pong_time = 0;
208     static uint8_t ping_sent = 0;
209     if (read_file_into_queue(world.file_server_out, &world.queue))
210     {
211         last_server_answer_time = time(0);
212         return;
213     }
214     time_t now = time(0);
215     if (ping_sent && last_server_answer_time > now - 5)  /* Re-set if last    */
216     {                                                    /* ping was answered */
217         ping_sent = 0;                                   /* with server       */
218         return;                                          /* activity.         */
219     }
220     if (!ping_sent && last_server_answer_time < now - 5)
221     {
222         send("PING");
223         ping_sent = 1;
224         last_pong_time = now;
225         return;
226     }
227     exit_err(ping_sent && last_pong_time < now - 5, "Server not answering.");
228 }
229
230
231
232 static void nl_append_string(char * append, char ** string)
233 {
234     char * err = "too large sizes";
235     exit_trouble(UINT32_MAX < strlen(append), __func__, err);
236     uint32_t new_size = strlen(append);
237     uint32_t old_size = 0;
238     uint8_t add_nl = 0;
239     if (*string)
240     {
241         exit_trouble(UINT32_MAX < new_size + strlen(*string), __func__, err);
242         old_size = strlen(*string);
243         add_nl = 1;
244     }
245     char * new_string = try_malloc(old_size + add_nl + new_size + 1, __func__);
246     memcpy(new_string, *string, old_size);
247     char * pattern = add_nl ? "\n%s" : "%s";
248     int test = sprintf(new_string + old_size, pattern, append);
249     exit_trouble(test < 0, __func__, "sprintf");
250     free(*string);
251     *string = new_string;
252 }
253
254
255
256 static uint8_t read_queue()
257 {
258     static uint8_t things_here_parsing = 0;
259     uint8_t ret = 0;
260     char * msg;
261     while (NULL != (msg = get_message_from_queue(&world.queue)))
262     {
263         char * log_prefix = "LOG ";
264         if      (!strcmp(msg, "THINGS_HERE START"))
265         {
266             ret = 1;
267             things_here_parsing = 1;
268             free(world.things_here);
269             world.things_here = NULL;
270         }
271         else if (!strcmp(msg, "THINGS_HERE END"))
272         {
273             things_here_parsing = 0;
274             if (!world.things_here)
275             {
276                 nl_append_string("(none known)", &world.things_here);
277             }
278         }
279         else if (things_here_parsing)
280         {
281             ret = 1;
282             nl_append_string(msg, &world.things_here);
283         }
284         else if (!strncmp(msg, log_prefix, strlen(log_prefix)))
285         {
286             ret = 1;
287             nl_append_string(msg + strlen(log_prefix), &world.log);
288         }
289         else if (!strcmp(msg, "NEW_WORLD"))
290         {
291             ret = 1;
292             free(world.log);
293             world.log = NULL;
294         }
295         else if (!strcmp(msg, "WORLD_UPDATED"))
296         {
297             query_mapcell();
298         }
299         free(msg);
300     }
301     return ret;
302 }
303
304
305
306 extern void send(char * msg)
307 {
308     uint32_t msg_size = strlen(msg) + 1;
309     char * err = "send() tried to send message larger than PIPE_BUF bytes.";
310     exit_err(msg_size > PIPE_BUF, err);
311     try_fwrite(msg, strlen(msg), 1, world.file_server_in, __func__);
312     try_fputc('\n', world.file_server_in, __func__);
313     fflush(world.file_server_in);
314 }
315
316
317
318 extern char * io_loop()
319 {
320     uint16_t delay = 1; /* Greater delay: less redundant server files reading.*/
321     uint8_t change_in_client = 0;
322     while (1)
323     {
324         timeout(delay);
325         delay = delay < 1000 ? delay * 2 : delay;
326         test_and_poll_server();
327         if (world.winch)
328         {
329             reset_windows_on_winch();
330             world.winch = 0;
331             change_in_client++;
332         }
333         if (change_in_client || read_worldstate() || read_queue())
334         {
335             delay = 1;       /* Keep client alert even if it's not getch()'d. */
336             struct Win * win_map = get_win_by_id('m');
337             if (0 == win_map->view)   /* So the map window's winconfig views  */
338             {                         /* don't get confused by the centering. */
339                 struct yx_uint8 pos=world.look?world.look_pos:world.player_pos;
340                 win_map->center.y = pos.y;
341                 win_map->center.x = pos.x * 2 + (pos.y % 2);
342             }
343             draw_all_wins();
344         }
345         change_in_client = 0;
346         int key = getch();
347         if (ERR != key)
348         {
349             delay = 1;                     /* Alert client if it's getch()'d. */
350             change_in_client = try_key((uint16_t) key);
351             if (2 == change_in_client)
352             {
353                 break;
354             }
355         }
356     }
357     send("QUIT");
358     return "Sent QUIT to server.";
359 }