]> git.pond.sub.org Git - empserver/blob - src/client/play.c
client: Fix obscure misdetection of input EOF
[empserver] / src / client / play.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2015, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  play.c: Playing the game
28  *
29  *  Known contributors to this file:
30  *     Markus Armbruster, 2007-2016
31  *     Ron Koenderink, 2007-2009
32  */
33
34 #include <config.h>
35
36 #include <assert.h>
37 #include <errno.h>
38 #include <signal.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #ifdef _WIN32
42 #include <process.h>
43 #include <sys/socket.h>
44 #else
45 #include <sys/select.h>
46 #endif
47 #include <unistd.h>
48 #include "linebuf.h"
49 #include "misc.h"
50 #include "proto.h"
51 #include "ringbuf.h"
52 #include "secure.h"
53
54 #ifdef _WIN32
55 static CRITICAL_SECTION signal_critical_section;
56 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
57
58 static unsigned char bounce_buf[RING_SIZE];
59 /*
60  * Set bounce_empty to indicate bounce_buf is available for the stdin thread
61  * to use.
62  */
63 static HANDLE bounce_empty;
64 /*
65  * Set bounce_full to indicate bounce_buf is contains data from the
66  * stdin thread and is available for recv_input
67  */
68 static HANDLE bounce_full;
69 /* Ctrl-C (SIGINT) was detected, generate EINTR for the w32_select() */
70 static HANDLE ctrl_c_event;
71 static int bounce_status, bounce_error;
72
73 struct sigaction {
74     int sa_flags;
75     void (*sa_handler)(int sig);
76 };
77
78 #define SIGPIPE -1
79 static void (*ctrl_handler)(int sig) = { SIG_DFL };
80
81 /*
82  * Ctrl-C handler for emulating the SIGINT in WIN32
83  */
84 static BOOL WINAPI
85 w32_signal_handler(DWORD ctrl_type)
86 {
87     if (ctrl_type == CTRL_C_EVENT) {
88         EnterCriticalSection(signal_critical_section_ptr);
89         if (ctrl_handler != SIG_DFL) {
90             ctrl_handler(SIGINT);
91             LeaveCriticalSection(signal_critical_section_ptr);
92             SetEvent(ctrl_c_event);
93             return TRUE;
94         } else
95             LeaveCriticalSection(signal_critical_section_ptr);
96     }
97     return FALSE;
98 }
99
100 /*
101  * WIN32 equivalent for sigaction supports the following:
102  * set handler for SIGINT using WIN32 Ctrl-C handler
103  * reset handler SIGINT to SIG_DFL
104  * ignore SIGPIPE
105  */
106 static int
107 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
108 {
109     assert(!oaction);
110     assert(action);
111
112     if (signal == SIGPIPE)
113         assert(action->sa_handler == SIG_IGN);
114     else {
115         assert(signal == SIGINT && action->sa_handler != SIG_IGN);
116         if (ctrl_handler == action->sa_handler)
117             return 0;
118         if (signal_critical_section_ptr == NULL) {
119             signal_critical_section_ptr = &signal_critical_section;
120             InitializeCriticalSection(signal_critical_section_ptr);
121         }
122         EnterCriticalSection(signal_critical_section_ptr);
123         if (!SetConsoleCtrlHandler(w32_signal_handler,
124                                    action->sa_handler != SIG_DFL)) {
125             errno = GetLastError();
126             LeaveCriticalSection(signal_critical_section_ptr);
127             return -1;
128         }
129         ctrl_handler = action->sa_handler;
130         LeaveCriticalSection(signal_critical_section_ptr);
131     }
132     return 0;
133 }
134
135 /*
136  * Read the stdin in WIN32 environment
137  * WIN32 does not support select type function on console input
138  * so the client uses a separate thread to read input
139  */
140 static void
141 stdin_read_thread(void *dummy)
142 {
143     for (;;) {
144         switch (WaitForSingleObject(bounce_empty, INFINITE)) {
145         case WAIT_FAILED:
146             bounce_status = -1;
147             bounce_error = GetLastError();
148             break;
149         case WAIT_OBJECT_0:
150             bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
151             bounce_error = errno;
152             break;
153         case WAIT_ABANDONED:
154             return;
155         default:
156             assert(0);
157         }
158         SetEvent(bounce_full);
159     }
160 }
161
162 /*
163  * Initialize and start the stdin reading thread for WIN32
164  */
165 static void
166 sysdep_stdin_init(void)
167 {
168     bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
169     bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
170     ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
171     _beginthread(stdin_read_thread, 0, NULL);
172 }
173
174 /*
175  * This function uses to WaitForMultipleObjects to wait for both
176  * stdin and socket reading or writing.
177  * Stdin is treated special in WIN32.  Waiting for stdin is done
178  * via a bounce_full event which is set in the stdin thread.
179  * Execute command file reading is done via handle.
180  * WaitForMultipleObjects will only respond with one object,
181  * so an additonal select is also done to determine
182  * which individual events are active.
183  */
184 static int
185 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd,
186            struct timeval *time)
187 {
188     HANDLE handles[3];
189     SOCKET sock;
190     int inp, sockfd, result, s_result, num_handles;
191     struct timeval tv_time = {0, 0};
192     fd_set rdsock, wrsock;
193
194     switch (rdfd->fd_count) {
195     case 1:
196         inp = -1;
197         sockfd = rdfd->fd_array[0];
198         break;
199     case 2:
200         inp = rdfd->fd_array[0];
201         sockfd = rdfd->fd_array[1];
202         break;
203     default:
204         assert(0);
205     }
206     sock = w32_fd2socket(sockfd);
207
208     assert(wrfd->fd_count == 0
209            || (wrfd->fd_count == 1 && wrfd->fd_array[0] == (SOCKET)sockfd));
210     assert(inp < 0 || inp == input_fd);
211
212     num_handles = 0;
213     handles[num_handles++] = ctrl_c_event;
214     if (inp >= 0)
215         handles[num_handles++]
216             = inp ? (HANDLE)_get_osfhandle(inp) : bounce_full;
217     /* always wait on the socket */
218     handles[num_handles++] = WSACreateEvent();
219
220     if (wrfd->fd_count > 0)
221         WSAEventSelect(sock, handles[num_handles - 1],
222                        FD_READ | FD_WRITE | FD_CLOSE);
223     else
224         WSAEventSelect(sock, handles[num_handles - 1],
225                        FD_READ | FD_CLOSE);
226
227     result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
228     if (result < 0) {
229         errno = GetLastError();
230         WSACloseEvent(handles[num_handles - 1]);
231         return -1;
232     }
233     WSACloseEvent(handles[num_handles - 1]);
234
235     if (result == WAIT_OBJECT_0) {
236         errno = EINTR;
237         return -1;
238     }
239
240     FD_ZERO(&rdsock);
241     FD_ZERO(&wrsock);
242     FD_SET(sock, &rdsock);
243     if (wrfd->fd_count)
244         FD_SET(sock, &wrsock);
245     s_result = select(sock + 1, &rdsock, &wrsock, NULL, &tv_time);
246
247     if (s_result < 0) {
248         w32_set_winsock_errno();
249         return s_result;
250     }
251
252     if (!FD_ISSET(sock, &rdsock))
253         FD_CLR((SOCKET)sockfd, rdfd);
254     if (!FD_ISSET(sock, &wrsock))
255         FD_CLR((SOCKET)sockfd, wrfd);
256     if (inp >= 0 && result == WAIT_OBJECT_0 + 1)
257         s_result++;
258     else
259         FD_CLR((SOCKET)inp, rdfd);
260
261     return s_result;
262 }
263
264 /*
265  * Read input from the user either stdin or from file.
266  * For stdin, read from bounce_buf which filled by the stdin thread
267  * otherwise use the regular ring_from_file.
268  */
269 static int
270 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
271 {
272     int i, res;
273
274     if (fd)
275         return ring_from_file(r, fd);
276
277     if (bounce_status < 0) {
278         errno = bounce_error;
279         res = bounce_status;
280     } else {
281         for (i = 0; i < bounce_status; i++) {
282             if (ring_putc(r, bounce_buf[i]) == EOF) {
283                 /* more work to do, hold on to bounce_buf */
284                 memmove(bounce_buf, bounce_buf + i, bounce_status - i);
285                 bounce_status -= i;
286                 return i;
287             }
288         }
289         res = i;
290     }
291
292     ResetEvent(bounce_full);
293     SetEvent(bounce_empty);
294     return res;
295 }
296 #define ring_from_file w32_ring_from_file_or_bounce_buf
297 #define select(nfds, rd, wr, error, time) \
298         w32_select((nfds), (rd), (wr), (error), (time))
299 #define sigemptyset(mask) ((void)0)
300 #else
301 #define sysdep_stdin_init() ((void)0)
302 #endif
303
304 #define EOF_COOKIE "ctld\n"
305 #define INTR_COOKIE "aborted\n"
306
307 /*
308  * Player input file descriptor
309  * 0 while reading interactive input
310  * >0 while reading a batch file
311  * <0 during error handling
312  */
313 int input_fd;
314
315 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
316
317 /*
318  * Receive and process server output from @sock.
319  * Return number of characters received on success, -1 on error.
320  */
321 static int
322 recv_output(int sock)
323 {
324     /*
325      * Read a chunk of server output and feed its characters into a
326      * simple state machine.
327      * Initial state is SCANNING_ID.
328      * In state SCANNING_ID, buffer the character.  If it's a space,
329      * decode the id that has been buffered, and enter state BUFFERING
330      * or COPYING depending on its value.
331      * In state BUFFERING, buffer the character.  If it's newline,
332      * pass id and buffered text to servercmd(), then enter state
333      * SCANNING_ID.
334      * In state COPYING, pass the character to outch().  If it's
335      * newline, enter state SCANNING_ID.
336      */
337     static enum {
338         SCANNING_ID, BUFFERING, COPYING
339     } state = SCANNING_ID;
340     static int id;
341     static struct lbuf lbuf;
342     char buf[4096];
343     ssize_t n;
344     int i, ch, len;
345     char *line;
346
347     n = read(sock, buf, sizeof(buf));
348     if (n < 0)
349         return -1;
350
351     for (i = 0; i < n; i++) {
352         ch = buf[i];
353         switch (state) {
354         case SCANNING_ID:
355             if (ch == '\n') {
356                 /* FIXME gripe unexpected! */
357                 lbuf_init(&lbuf);
358                 break;
359             }
360             lbuf_putc(&lbuf, ch);
361             if (ch != ' ')
362                 break;
363             line = lbuf_line(&lbuf);
364             id = parseid(line);
365             lbuf_init(&lbuf);
366
367             switch (id) {
368             case C_PROMPT:
369             case C_FLUSH:
370             case C_EXECUTE:
371             case C_EXIT:
372             case C_FLASH:
373             case C_INFORM:
374             case C_PIPE:
375             case C_REDIR:
376                 state = BUFFERING;
377                 break;
378             default:
379                 /* unknown or unexpected id, treat like C_DATA */
380             case C_DATA:
381                 state = COPYING;
382                 break;
383             }
384             break;
385
386         case BUFFERING:
387             len = lbuf_putc(&lbuf, ch);
388             if (len) {
389                 line = lbuf_line(&lbuf);
390                 servercmd(id, line, len);
391                 lbuf_init(&lbuf);
392                 state = SCANNING_ID;
393             }
394             break;
395
396         case COPYING:
397             outch(ch);
398             if (ch == '\n')
399                 state = SCANNING_ID;
400         }
401     }
402
403     return n;
404 }
405
406 /*
407  * Receive player input from @fd into @inbuf.
408  * Return 1 on receipt of input, zero on EOF, -1 on error.
409  */
410 static int
411 recv_input(int fd, struct ring *inbuf)
412 {
413     int n, i, ch;
414     int res = 1;
415
416     n = ring_from_file(inbuf, fd);
417     if (n < 0)
418         return -1;
419     if (n == 0) {
420         /*
421          * Can't put EOF cookie into INBUF here, it may not fit.
422          * Leave it to caller.
423          */
424         res = 0;
425     }
426
427     /* copy input to AUXFP etc. */
428     for (i = -n; i < 0; i++) {
429         ch = ring_peek(inbuf, i);
430         assert(ch != EOF);
431         if (ch != '\r')
432             save_input(ch);
433         if (auxfp)
434             putc(ch, auxfp);
435     }
436
437     return res;
438 }
439
440 static void
441 intr(int sig)
442 {
443     send_intr = 1;
444 }
445
446 /*
447  * Play on @sock.
448  * The session must be in the playing phase.
449  * Return 0 when the session ended, -1 on error.
450  */
451 int
452 play(int sock)
453 {
454     /*
455      * Player input flows from INPUT_FD through recv_input() into ring
456      * buffer INBUF, which drains into SOCK.  This must not block.
457      * Server output flows from SOCK into recv_output().  Reading SOCK
458      * must not block.
459      */
460     struct sigaction sa;
461     struct ring inbuf;          /* input buffer, draining to SOCK */
462     int eof_fd0;                /* read fd 0 hit EOF? */
463     int partial_line_sent;      /* partial input line sent? */
464     int send_eof;               /* need to send EOF_COOKIE */
465     fd_set rdfd, wrfd;
466     int n;
467
468     sa.sa_flags = 0;
469     sigemptyset(&sa.sa_mask);
470     sa.sa_handler = intr;
471     sigaction(SIGINT, &sa, NULL);
472     sa.sa_handler = SIG_IGN;
473     sigaction(SIGPIPE, &sa, NULL);
474
475     ring_init(&inbuf);
476     eof_fd0 = partial_line_sent = send_eof = send_intr = 0;
477     input_fd = 0;
478     sysdep_stdin_init();
479
480     for (;;) {
481         FD_ZERO(&rdfd);
482         FD_ZERO(&wrfd);
483
484         /*
485          * Want to read player input only when we don't need to send
486          * cookies, haven't reached EOF on fd 0, and @inbuf can accept
487          * some.
488          */
489         if (!send_intr && !send_eof && (input_fd || !eof_fd0)
490             && ring_space(&inbuf))
491             FD_SET(input_fd, &rdfd);
492         /* Want to send player input only when we have something */
493         if (send_intr || send_eof || ring_len(&inbuf))
494             FD_SET(sock, &wrfd);
495         /* Always want to read server output */
496         FD_SET(sock, &rdfd);
497
498         n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
499         if (n < 0) {
500             if (errno != EINTR) {
501                 perror("select");
502                 return -1;
503             }
504         }
505
506         if ((send_eof || send_intr) && partial_line_sent
507             && ring_putc(&inbuf, '\n') != EOF)
508             partial_line_sent = 0;
509         if (send_eof && !partial_line_sent
510             && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
511             send_eof = 0;
512         if (send_intr && !partial_line_sent
513             && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
514             send_intr = 0;
515             if (input_fd) {
516                 /* execute aborted, switch back to fd 0 */
517                 close(input_fd);
518                 input_fd = 0;
519             }
520         }
521
522         if (n < 0)
523             continue;
524
525         /* read player input */
526         if (FD_ISSET(input_fd, &rdfd) && ring_space(&inbuf)) {
527             n = recv_input(input_fd, &inbuf);
528             if (n <= 0) {
529                 if (input_fd) {
530                     /* execute done, switch back to fd 0 */
531                     if (n < 0) {
532                         perror("read batch file");
533                         send_intr = 1;
534                     } else
535                         send_eof = 1;
536                     close(input_fd);
537                     input_fd = 0;
538                 } else {
539                     /* stop reading input, drain socket ring buffers */
540                     if (n < 0)
541                         perror("read stdin");
542                     send_eof = 1;
543                     eof_fd0 = 1;
544                     sa.sa_handler = SIG_DFL;
545                     sigaction(SIGINT, &sa, NULL);
546                     send_intr = 0;
547                 }
548             } else
549                 partial_line_sent = ring_peek(&inbuf, -1) != '\n';
550         }
551
552         /* send it to the server */
553         if (FD_ISSET(sock, &wrfd)) {
554             n = ring_to_file(&inbuf, sock);
555             if (n < 0) {
556                 perror("write socket");
557                 return -1;
558             }
559         }
560
561         /* read server output and print it */
562         if (FD_ISSET(sock, &rdfd)) {
563             n = recv_output(sock);
564             if (n < 0) {
565                 perror("read socket");
566                 return -1;
567             }
568             if (n == 0)
569                 return 0;
570             if (input_fd < 0) {
571                 /* execute failed */
572                 send_intr = 1;
573                 input_fd = 0;
574             }
575         }
576     }
577 }