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