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