]> git.pond.sub.org Git - empserver/blob - src/client/play.c
Update copyright notice
[empserver] / src / client / play.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2010, 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-2009
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 #ifdef _WIN32
43 #include <process.h>
44 #include <sys/socket.h>
45 #else
46 #include <sys/select.h>
47 #endif
48 #include <unistd.h>
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 struct sigaction {
75     int sa_flags;
76     void (*sa_handler)(int sig);
77 };
78
79 #define SIGPIPE -1
80 static void (*ctrl_handler)(int sig) = { SIG_DFL };
81
82 /*
83  * Ctrl-C handler for emulating the SIGINT in WIN32
84  */
85 static BOOL WINAPI
86 w32_signal_handler(DWORD ctrl_type)
87 {
88     if (ctrl_type == CTRL_C_EVENT) {
89         EnterCriticalSection(signal_critical_section_ptr);
90         if (ctrl_handler != SIG_DFL) {
91             ctrl_handler(SIGINT);
92             LeaveCriticalSection(signal_critical_section_ptr);
93             SetEvent(ctrl_c_event);
94             return TRUE;
95         } else
96             LeaveCriticalSection(signal_critical_section_ptr);
97     }
98     return FALSE;
99 }
100
101 /*
102  * WIN32 equivalent for sigaction supports the following:
103  * set handler for SIGINT using WIN32 Ctrl-C handler
104  * reset handler SIGINT to SIG_DFL
105  * ignore SIGPIPE
106  */
107 static int
108 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
109 {
110     assert(!oaction);
111     assert(action);
112
113     if (signal == SIGPIPE)
114         assert(action->sa_handler == SIG_IGN);
115     else {
116         assert(signal == SIGINT && action->sa_handler != SIG_IGN);
117         if (ctrl_handler == action->sa_handler)
118             return 0;
119         if (signal_critical_section_ptr == NULL) {
120             signal_critical_section_ptr = &signal_critical_section;
121             InitializeCriticalSection(signal_critical_section_ptr);
122         }
123         EnterCriticalSection(signal_critical_section_ptr);
124         if (!SetConsoleCtrlHandler(w32_signal_handler,
125                                    action->sa_handler != SIG_DFL)) {
126             errno = GetLastError();
127             LeaveCriticalSection(signal_critical_section_ptr);
128             return -1;
129         }
130         ctrl_handler = action->sa_handler;
131         LeaveCriticalSection(signal_critical_section_ptr);
132     }
133     return 0;
134 }
135
136 /*
137  * Read the stdin in WIN32 environment
138  * WIN32 does not support select type function on console input
139  * so the client uses a separate thread to read input
140  */
141 static void
142 stdin_read_thread(void *dummy)
143 {
144     for (;;) {
145         switch (WaitForSingleObject(bounce_empty, INFINITE)) {
146         case WAIT_FAILED:
147             bounce_status = -1;
148             bounce_error = GetLastError();
149             break;
150         case WAIT_OBJECT_0:
151             bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
152             bounce_error = errno;
153             break;
154         case WAIT_ABANDONED:
155             return;
156         default:
157             assert(0);
158         }
159         SetEvent(bounce_full);
160     }
161 }
162
163 /*
164  * Initialize and start the stdin reading thread for WIN32
165  */
166 static void
167 sysdep_stdin_init(void)
168 {
169     bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
170     bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
171     ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
172     _beginthread(stdin_read_thread, 0, NULL);
173 }
174
175 /*
176  * This function uses to WaitForMultipleObjects to wait for both
177  * stdin and socket reading or writing.
178  * Stdin is treated special in WIN32.  Waiting for stdin is done
179  * via a bounce_full event which is set in the stdin thread.
180  * Execute command file reading is done via handle.
181  * WaitForMultipleObjects will only respond with one object,
182  * so an additonal select is also done to determine
183  * which individual events are active.
184  */
185 static int
186 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd, 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 "\naborted\n"
306
307 int input_fd;
308 int send_eof;                           /* need to send EOF_COOKIE */
309 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
310
311 /*
312  * Receive and process server output from SOCK.
313  * Return number of characters received on success, -1 on error.
314  */
315 static int
316 recv_output(int sock)
317 {
318     /*
319      * Read a chunk of server output and feed its characters into a
320      * simple state machine.
321      * Initial state is SCANNING_ID.
322      * In state SCANNING_ID, buffer the character.  If it's a space,
323      * decode the id that has been buffered, and enter state BUFFERING
324      * or COPYING depending on its value.
325      * In state BUFFERING, buffer the character.  If it's newline,
326      * pass id and buffered text to servercmd(), then enter state
327      * SCANNING_ID.
328      * In state COPYING, pass the character to outch().  If it's
329      * newline, enter state SCANNING_ID.
330      */
331     static enum {
332         SCANNING_ID, BUFFERING, COPYING
333     } state = SCANNING_ID;
334     static int id;
335     static struct lbuf lbuf;
336     char buf[4096];
337     ssize_t n;
338     int i, ch, len;
339     char *line;
340
341     n = read(sock, buf, sizeof(buf));
342     if (n < 0)
343         return -1;
344
345     for (i = 0; i < n; i++) {
346         ch = buf[i];
347         switch (state) {
348         case SCANNING_ID:
349             if (ch == '\n') {
350                 /* FIXME gripe unexpected! */
351                 lbuf_init(&lbuf);
352                 break;
353             }
354             lbuf_putc(&lbuf, ch);
355             if (ch != ' ')
356                 break;
357             line = lbuf_line(&lbuf);
358             id = parseid(line);
359             lbuf_init(&lbuf);
360
361             switch (id) {
362             case C_PROMPT:
363             case C_FLUSH:
364             case C_EXECUTE:
365             case C_EXIT:
366             case C_FLASH:
367             case C_INFORM:
368             case C_PIPE:
369             case C_REDIR:
370                 state = BUFFERING;
371                 break;
372             default:
373                 /* unknown or unexpected id, treat like C_DATA */
374             case C_DATA:
375                 state = COPYING;
376                 break;
377             }
378             break;
379
380         case BUFFERING:
381             len = lbuf_putc(&lbuf, ch);
382             if (len) {
383                 line = lbuf_line(&lbuf);
384                 servercmd(id, line, len);
385                 lbuf_init(&lbuf);
386                 state = SCANNING_ID;
387             }
388             break;
389
390         case COPYING:
391             outch(ch);
392             if (ch == '\n')
393                 state = SCANNING_ID;
394         }
395     }
396
397     return n;
398 }
399
400 /*
401  * Receive command input from FD into INBUF.
402  * Return 1 on receipt of input, zero on EOF, -1 on error.
403  */
404 static int
405 recv_input(int fd, struct ring *inbuf)
406 {
407     static struct lbuf cmdbuf;
408     int n, i, ch;
409     char *line;
410     int res = 1;
411
412     n = ring_from_file(inbuf, fd);
413     if (n < 0)
414         return -1;
415     if (n == 0) {
416         /* EOF on input */
417         if (lbuf_len(&cmdbuf)) {
418             /* incomplete line */
419             ring_putc(inbuf, '\n');
420             n++;
421         }
422         /*
423          * Can't put EOF cookie into INBUF here, it may not fit.
424          * Leave it to caller.
425          */
426         res = 0;
427     }
428
429     /* copy input to AUXFP etc. */
430     for (i = -n; i < 0; i++) {
431         ch = ring_peek(inbuf, i);
432         assert(ch != EOF);
433         if (ch != '\r' && lbuf_putc(&cmdbuf, ch)) {
434             line = lbuf_line(&cmdbuf);
435             if (auxfp)
436                 fputs(line, auxfp);
437             save_input(line);
438             lbuf_init(&cmdbuf);
439         }
440     }
441
442     return res;
443 }
444
445 static void
446 intr(int sig)
447 {
448     send_intr = 1;
449 }
450
451 /*
452  * Play on SOCK.
453  * The session must be in the playing phase.
454  * Return 0 when the session ended, -1 on error.
455  */
456 int
457 play(int sock)
458 {
459     /*
460      * Player input flows from INPUT_FD through recv_input() into ring
461      * buffer INBUF, which drains into SOCK.  This must not block.
462      * Server output flows from SOCK into recv_output().  Reading SOCK
463      * must not block.
464      */
465     struct sigaction sa;
466     struct ring inbuf;          /* input buffer, draining to SOCK */
467     int eof_fd0;                /* read fd 0 hit EOF? */
468     fd_set rdfd, wrfd;
469     int n;
470
471     sa.sa_flags = 0;
472     sigemptyset(&sa.sa_mask);
473     sa.sa_handler = intr;
474     sigaction(SIGINT, &sa, NULL);
475     sa.sa_handler = SIG_IGN;
476     sigaction(SIGPIPE, &sa, NULL);
477
478     ring_init(&inbuf);
479     eof_fd0 = send_eof = send_intr = 0;
480     input_fd = 0;
481     sysdep_stdin_init();
482
483     for (;;) {
484         FD_ZERO(&rdfd);
485         FD_ZERO(&wrfd);
486
487         /*
488          * Want to read player input only when we don't need to send
489          * cookies, and INPUT_FD is still open, and INBUF can accept
490          * some.
491          */
492         if (!send_intr && !send_eof && input_fd >= 0 && ring_space(&inbuf))
493             FD_SET(input_fd, &rdfd);
494         /* Want to send player input only when we have something */
495         if (send_intr || send_eof || ring_len(&inbuf))
496             FD_SET(sock, &wrfd);
497         /* Always want to read server output */
498         FD_SET(sock, &rdfd);
499
500         n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
501         if (n < 0) {
502             if (errno != EINTR) {
503                 perror("select");
504                 return -1;
505             }
506         }
507
508         if (send_eof
509             && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
510             send_eof--;
511         if (send_intr
512             && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
513             send_intr = 0;
514             if (input_fd) {
515                 /* execute aborted, switch back to fd 0 */
516                 close(input_fd);
517                 input_fd = eof_fd0 ? -1 : 0;
518             }
519         }
520
521         if (n < 0)
522             continue;
523
524         /* read player input */
525         if (input_fd >= 0 && FD_ISSET(input_fd, &rdfd)) {
526             n = recv_input(input_fd, &inbuf);
527             if (n < 0) {
528                 perror("read stdin"); /* FIXME stdin misleading, could be execing */
529                 n = 0;
530             }
531             if (n == 0) {
532                 /* EOF on input */
533                 send_eof++;
534                 if (input_fd) {
535                     /* execute done, switch back to fd 0 */
536                     close(input_fd);
537                     input_fd = eof_fd0 ? -1 : 0;
538                 } else {
539                     /* stop reading input, drain socket ring buffers */
540                     eof_fd0 = 1;
541                     input_fd = -1;
542                     sa.sa_handler = SIG_DFL;
543                     sigaction(SIGINT, &sa, NULL);
544                 }
545             }
546         }
547
548         /* send it to the server */
549         if (FD_ISSET(sock, &wrfd)) {
550             n = ring_to_file(&inbuf, sock);
551             if (n < 0) {
552                 perror("write socket");
553                 return -1;
554             }
555         }
556
557         /* read server output and print it */
558         if (FD_ISSET(sock, &rdfd)) {
559             n = recv_output(sock);
560             if (n < 0) {
561                 perror("read socket");
562                 return -1;
563             }
564             if (n == 0)
565                 return 0;
566         }
567     }
568 }