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
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.
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.
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/>.
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.
27 * play.c: Playing the game
29 * Known contributors to this file:
30 * Markus Armbruster, 2007-2017
31 * Ron Koenderink, 2007-2009
43 #include <sys/socket.h>
45 #include <sys/select.h>
54 #ifdef HAVE_LIBREADLINE
55 # if defined(HAVE_READLINE_READLINE_H)
56 # include <readline/readline.h>
57 # elif defined(HAVE_READLINE_H)
58 # include <readline.h>
59 # else /* !defined(HAVE_READLINE_H) */
60 extern char *readline ();
61 # endif /* !defined(HAVE_READLINE_H) */
62 #endif /* HAVE_LIBREADLINE */
64 #ifdef HAVE_READLINE_HISTORY
65 # if defined(HAVE_READLINE_HISTORY_H)
66 # include <readline/history.h>
67 # elif defined(HAVE_HISTORY_H)
69 # else /* !defined(HAVE_HISTORY_H) */
70 extern void add_history ();
71 extern int write_history ();
72 extern int read_history ();
73 # endif /* !defined(HAVE_HISTORY_H) */
74 #endif /* HAVE_READLINE_HISTORY */
76 #define EOF_COOKIE "ctld\n"
77 #define INTR_COOKIE "aborted\n"
80 * Player input file descriptor
81 * 0 while reading interactive input
82 * >0 while reading a batch file
83 * <0 during error handling
87 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
90 static CRITICAL_SECTION signal_critical_section;
91 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
93 static unsigned char bounce_buf[RING_SIZE];
95 * Set bounce_empty to indicate bounce_buf is available for the stdin thread
98 static HANDLE bounce_empty;
100 * Set bounce_full to indicate bounce_buf is contains data from the
101 * stdin thread and is available for recv_input
103 static HANDLE bounce_full;
104 /* Ctrl-C (SIGINT) was detected, generate EINTR for the w32_select() */
105 static HANDLE ctrl_c_event;
106 static int bounce_status, bounce_error;
110 void (*sa_handler)(int sig);
114 static void (*ctrl_handler)(int sig) = { SIG_DFL };
117 * Ctrl-C handler for emulating the SIGINT in WIN32
120 w32_signal_handler(DWORD ctrl_type)
122 if (ctrl_type == CTRL_C_EVENT) {
123 EnterCriticalSection(signal_critical_section_ptr);
124 if (ctrl_handler != SIG_DFL) {
125 ctrl_handler(SIGINT);
126 LeaveCriticalSection(signal_critical_section_ptr);
127 SetEvent(ctrl_c_event);
130 LeaveCriticalSection(signal_critical_section_ptr);
136 * WIN32 equivalent for sigaction supports the following:
137 * set handler for SIGINT using WIN32 Ctrl-C handler
138 * reset handler SIGINT to SIG_DFL
142 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
147 if (signal == SIGPIPE)
148 assert(action->sa_handler == SIG_IGN);
150 assert(signal == SIGINT && action->sa_handler != SIG_IGN);
151 if (ctrl_handler == action->sa_handler)
153 if (signal_critical_section_ptr == NULL) {
154 signal_critical_section_ptr = &signal_critical_section;
155 InitializeCriticalSection(signal_critical_section_ptr);
157 EnterCriticalSection(signal_critical_section_ptr);
158 if (!SetConsoleCtrlHandler(w32_signal_handler,
159 action->sa_handler != SIG_DFL)) {
160 errno = GetLastError();
161 LeaveCriticalSection(signal_critical_section_ptr);
164 ctrl_handler = action->sa_handler;
165 LeaveCriticalSection(signal_critical_section_ptr);
171 * Read the stdin in WIN32 environment
172 * WIN32 does not support select type function on console input
173 * so the client uses a separate thread to read input
176 stdin_read_thread(void *dummy)
179 switch (WaitForSingleObject(bounce_empty, INFINITE)) {
182 bounce_error = GetLastError();
185 bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
186 bounce_error = errno;
193 SetEvent(bounce_full);
198 * Initialize and start the stdin reading thread for WIN32
201 sysdep_stdin_init(void)
203 bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
204 bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
205 ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
206 _beginthread(stdin_read_thread, 0, NULL);
210 * This function uses to WaitForMultipleObjects to wait for both
211 * stdin and socket reading or writing.
212 * Stdin is treated special in WIN32. Waiting for stdin is done
213 * via a bounce_full event which is set in the stdin thread.
214 * Execute command file reading is done via handle.
215 * WaitForMultipleObjects will only respond with one object,
216 * so an additonal select is also done to determine
217 * which individual events are active.
220 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd,
221 struct timeval *time)
225 int inp, sockfd, result, s_result, num_handles;
226 struct timeval tv_time = {0, 0};
227 fd_set rdsock, wrsock;
229 switch (rdfd->fd_count) {
232 sockfd = rdfd->fd_array[0];
235 inp = rdfd->fd_array[0];
236 sockfd = rdfd->fd_array[1];
241 sock = w32_fd2socket(sockfd);
243 assert(wrfd->fd_count == 0
244 || (wrfd->fd_count == 1 && wrfd->fd_array[0] == (SOCKET)sockfd));
245 assert(inp < 0 || inp == input_fd);
248 handles[num_handles++] = ctrl_c_event;
250 handles[num_handles++]
251 = inp ? (HANDLE)_get_osfhandle(inp) : bounce_full;
252 /* always wait on the socket */
253 handles[num_handles++] = WSACreateEvent();
255 if (wrfd->fd_count > 0)
256 WSAEventSelect(sock, handles[num_handles - 1],
257 FD_READ | FD_WRITE | FD_CLOSE);
259 WSAEventSelect(sock, handles[num_handles - 1],
262 result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
264 errno = GetLastError();
265 WSACloseEvent(handles[num_handles - 1]);
268 WSACloseEvent(handles[num_handles - 1]);
270 if (result == WAIT_OBJECT_0) {
277 FD_SET(sock, &rdsock);
279 FD_SET(sock, &wrsock);
280 s_result = select(sock + 1, &rdsock, &wrsock, NULL, &tv_time);
283 w32_set_winsock_errno();
287 if (!FD_ISSET(sock, &rdsock))
288 FD_CLR((SOCKET)sockfd, rdfd);
289 if (!FD_ISSET(sock, &wrsock))
290 FD_CLR((SOCKET)sockfd, wrfd);
291 if (inp >= 0 && result == WAIT_OBJECT_0 + 1)
294 FD_CLR((SOCKET)inp, rdfd);
300 * Read input from the user either stdin or from file.
301 * For stdin, read from bounce_buf which filled by the stdin thread
302 * otherwise use the regular ring_from_file.
305 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
310 return ring_from_file(r, fd);
312 if (bounce_status < 0) {
313 errno = bounce_error;
316 for (i = 0; i < bounce_status; i++) {
317 if (ring_putc(r, bounce_buf[i]) == EOF) {
318 /* more work to do, hold on to bounce_buf */
319 memmove(bounce_buf, bounce_buf + i, bounce_status - i);
327 ResetEvent(bounce_full);
328 SetEvent(bounce_empty);
331 #define ring_from_file w32_ring_from_file_or_bounce_buf
332 #define select(nfds, rd, wr, error, time) \
333 w32_select((nfds), (rd), (wr), (error), (time))
334 #define sigemptyset(mask) ((void)0)
336 #define sysdep_stdin_init() ((void)0)
340 * Receive and process server output from @sock.
341 * Return number of characters received on success, -1 on error.
344 recv_output(int sock)
347 * Read a chunk of server output and feed its characters into a
348 * simple state machine.
349 * Initial state is SCANNING_ID.
350 * In state SCANNING_ID, buffer the character. If it's a space,
351 * decode the id that has been buffered, and enter state BUFFERING
352 * or COPYING depending on its value.
353 * In state BUFFERING, buffer the character. If it's newline,
354 * pass id and buffered text to servercmd(), then enter state
356 * In state COPYING, pass the character to outch(). If it's
357 * newline, enter state SCANNING_ID.
360 SCANNING_ID, BUFFERING, COPYING
361 } state = SCANNING_ID;
363 static struct lbuf lbuf;
369 n = read(sock, buf, sizeof(buf));
373 for (i = 0; i < n; i++) {
378 /* FIXME gripe unexpected! */
382 lbuf_putc(&lbuf, ch);
385 line = lbuf_line(&lbuf);
401 /* unknown or unexpected id, treat like C_DATA */
409 len = lbuf_putc(&lbuf, ch);
411 line = lbuf_line(&lbuf);
412 fd = servercmd(id, line, len);
420 /* successful execute, switch to batch file */
439 char *history_file = NULL;
440 #ifdef HAVE_LIBREADLINE
441 static char *input_from_rl;
442 static int has_rl_input;
445 input_handler(char *line)
447 input_from_rl = line;
449 rl_already_prompted = 1;
450 #ifdef HAVE_READLINE_HISTORY
453 #endif /* HAVE_READLINE_HISTORY */
455 #endif /* HAVE_LIBREADLINE */
458 * Receive player input from @fd into @inbuf.
459 * Return 1 on receipt of input, zero on EOF, -1 on error.
462 recv_input(int fd, struct ring *inbuf)
466 #ifdef HAVE_LIBREADLINE
471 rl_callback_read_char();
475 len = strlen(input_from_rl);
476 n = ring_space(inbuf);
478 if (len >= (size_t)n) {
479 ring_putm(inbuf, input_from_rl, n);
480 memmove(input_from_rl, input_from_rl + n, len - n + 1);
482 ring_putm(inbuf, input_from_rl, len);
483 ring_putc(inbuf, '\n');
492 n = ring_from_file(inbuf, fd);
497 * Can't put EOF cookie into INBUF here, it may not fit.
498 * Leave it to caller.
507 send_input(int fd, struct ring *inbuf)
513 cnt = ring_to_iovec(inbuf, iov);
514 res = writev(fd, iov, cnt);
518 /* Copy input to @auxfp etc. */
519 for (i = 0; i < res; i++) {
520 ch = ring_getc(inbuf);
539 * The session must be in the playing phase.
540 * Return 0 when the session ended, -1 on error.
546 * Player input flows from INPUT_FD through recv_input() into ring
547 * buffer INBUF, which drains into SOCK. This must not block.
548 * Server output flows from SOCK into recv_output(). Reading SOCK
552 struct ring inbuf; /* input buffer, draining to SOCK */
553 int eof_fd0; /* read fd 0 hit EOF? */
554 int partial_line_sent; /* partial input line sent? */
555 int send_eof; /* need to send EOF_COOKIE */
561 sigemptyset(&sa.sa_mask);
562 sa.sa_handler = intr;
563 sigaction(SIGINT, &sa, NULL);
564 sa.sa_handler = SIG_IGN;
565 sigaction(SIGPIPE, &sa, NULL);
566 #ifdef HAVE_LIBREADLINE
567 #ifdef HAVE_READLINE_HISTORY
569 read_history(history_file);
570 #endif /* HAVE_READLINE_HISTORY */
571 rl_bind_key('\t', rl_insert); /* Disable tab completion */
572 rl_callback_handler_install("", input_handler);
573 #endif /* HAVE_LIBREADLINE */
576 eof_fd0 = partial_line_sent = send_eof = send_intr = 0;
585 * Want to read player input only when we don't need to send
586 * cookies, haven't reached EOF on fd 0, and @inbuf can accept
589 if (!send_intr && !send_eof && (input_fd || !eof_fd0)
590 && ring_space(&inbuf))
591 FD_SET(input_fd, &rdfd);
592 /* Want to send player input only when we have something */
593 if (send_intr || send_eof || ring_len(&inbuf))
595 /* Always want to read server output */
598 n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
600 if (errno != EINTR) {
606 if ((send_eof || send_intr) && partial_line_sent
607 && ring_putc(&inbuf, '\n') != EOF)
608 partial_line_sent = 0;
609 if (send_eof && !partial_line_sent
610 && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
612 if (send_intr && !partial_line_sent
613 && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
616 /* execute aborted, switch back to fd 0 */
624 /* read player input */
625 if (FD_ISSET(input_fd, &rdfd) && ring_space(&inbuf)) {
626 n = recv_input(input_fd, &inbuf);
629 /* execute done, switch back to fd 0 */
631 perror("read batch file");
638 /* stop reading input, drain socket ring buffers */
640 perror("read stdin");
643 sa.sa_handler = SIG_DFL;
644 sigaction(SIGINT, &sa, NULL);
647 } else if (ring_len(&inbuf) > 0)
648 partial_line_sent = ring_peek(&inbuf, -1) != '\n';
651 /* send it to the server */
652 if (FD_ISSET(sock, &wrfd)) {
653 n = send_input(sock, &inbuf);
655 perror("write socket");
660 /* read server output and print it */
661 if (FD_ISSET(sock, &rdfd)) {
662 n = recv_output(sock);
664 perror("read socket");
668 #ifdef HAVE_LIBREADLINE
669 #ifdef HAVE_READLINE_HISTORY
671 write_history(history_file);
672 #endif /* HAVE_READLINE_HISTORY */
673 #endif /* HAVE_LIBREADLINE */
679 #ifdef HAVE_LIBREADLINE
680 rl_callback_handler_remove();