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