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
32 * Martin Haukeli, 2015
44 #include <sys/socket.h>
46 #include <sys/select.h>
55 #ifdef HAVE_LIBREADLINE
56 #include <readline/readline.h>
57 #include <readline/history.h>
60 #define EOF_COOKIE "ctld\n"
61 #define INTR_COOKIE "aborted\n"
64 * Player input file descriptor
65 * 0 while reading interactive input
66 * >0 while reading a batch file
67 * <0 during error handling
71 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
74 static CRITICAL_SECTION signal_critical_section;
75 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
77 static unsigned char bounce_buf[RING_SIZE];
79 * Set bounce_empty to indicate bounce_buf is available for the stdin thread
82 static HANDLE bounce_empty;
84 * Set bounce_full to indicate bounce_buf is contains data from the
85 * stdin thread and is available for recv_input
87 static HANDLE bounce_full;
88 /* Ctrl-C (SIGINT) was detected, generate EINTR for the w32_select() */
89 static HANDLE ctrl_c_event;
90 static int bounce_status, bounce_error;
94 void (*sa_handler)(int sig);
98 static void (*ctrl_handler)(int sig) = { SIG_DFL };
101 * Ctrl-C handler for emulating the SIGINT in WIN32
104 w32_signal_handler(DWORD ctrl_type)
106 if (ctrl_type == CTRL_C_EVENT) {
107 EnterCriticalSection(signal_critical_section_ptr);
108 if (ctrl_handler != SIG_DFL) {
109 ctrl_handler(SIGINT);
110 LeaveCriticalSection(signal_critical_section_ptr);
111 SetEvent(ctrl_c_event);
114 LeaveCriticalSection(signal_critical_section_ptr);
120 * WIN32 equivalent for sigaction supports the following:
121 * set handler for SIGINT using WIN32 Ctrl-C handler
122 * reset handler SIGINT to SIG_DFL
126 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
131 if (signal == SIGPIPE)
132 assert(action->sa_handler == SIG_IGN);
134 assert(signal == SIGINT && action->sa_handler != SIG_IGN);
135 if (ctrl_handler == action->sa_handler)
137 if (signal_critical_section_ptr == NULL) {
138 signal_critical_section_ptr = &signal_critical_section;
139 InitializeCriticalSection(signal_critical_section_ptr);
141 EnterCriticalSection(signal_critical_section_ptr);
142 if (!SetConsoleCtrlHandler(w32_signal_handler,
143 action->sa_handler != SIG_DFL)) {
144 errno = GetLastError();
145 LeaveCriticalSection(signal_critical_section_ptr);
148 ctrl_handler = action->sa_handler;
149 LeaveCriticalSection(signal_critical_section_ptr);
155 * Read the stdin in WIN32 environment
156 * WIN32 does not support select type function on console input
157 * so the client uses a separate thread to read input
160 stdin_read_thread(void *dummy)
163 switch (WaitForSingleObject(bounce_empty, INFINITE)) {
166 bounce_error = GetLastError();
169 bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
170 bounce_error = errno;
177 SetEvent(bounce_full);
182 * Initialize and start the stdin reading thread for WIN32
185 sysdep_stdin_init(void)
187 bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
188 bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
189 ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
190 _beginthread(stdin_read_thread, 0, NULL);
194 * This function uses to WaitForMultipleObjects to wait for both
195 * stdin and socket reading or writing.
196 * Stdin is treated special in WIN32. Waiting for stdin is done
197 * via a bounce_full event which is set in the stdin thread.
198 * Execute command file reading is done via handle.
199 * WaitForMultipleObjects will only respond with one object,
200 * so an additonal select is also done to determine
201 * which individual events are active.
204 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd,
205 struct timeval *time)
209 int inp, sockfd, result, s_result, num_handles;
210 struct timeval tv_time = {0, 0};
211 fd_set rdsock, wrsock;
213 switch (rdfd->fd_count) {
216 sockfd = rdfd->fd_array[0];
219 inp = rdfd->fd_array[0];
220 sockfd = rdfd->fd_array[1];
225 sock = w32_fd2socket(sockfd);
227 assert(wrfd->fd_count == 0
228 || (wrfd->fd_count == 1 && wrfd->fd_array[0] == (SOCKET)sockfd));
229 assert(inp < 0 || inp == input_fd);
232 handles[num_handles++] = ctrl_c_event;
234 handles[num_handles++]
235 = inp ? (HANDLE)_get_osfhandle(inp) : bounce_full;
236 /* always wait on the socket */
237 handles[num_handles++] = WSACreateEvent();
239 if (wrfd->fd_count > 0)
240 WSAEventSelect(sock, handles[num_handles - 1],
241 FD_READ | FD_WRITE | FD_CLOSE);
243 WSAEventSelect(sock, handles[num_handles - 1],
246 result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
248 errno = GetLastError();
249 WSACloseEvent(handles[num_handles - 1]);
252 WSACloseEvent(handles[num_handles - 1]);
254 if (result == WAIT_OBJECT_0) {
261 FD_SET(sock, &rdsock);
263 FD_SET(sock, &wrsock);
264 s_result = select(sock + 1, &rdsock, &wrsock, NULL, &tv_time);
267 w32_set_winsock_errno();
271 if (!FD_ISSET(sock, &rdsock))
272 FD_CLR((SOCKET)sockfd, rdfd);
273 if (!FD_ISSET(sock, &wrsock))
274 FD_CLR((SOCKET)sockfd, wrfd);
275 if (inp >= 0 && result == WAIT_OBJECT_0 + 1)
278 FD_CLR((SOCKET)inp, rdfd);
284 * Read input from the user either stdin or from file.
285 * For stdin, read from bounce_buf which filled by the stdin thread
286 * otherwise use the regular ring_from_file.
289 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
294 return ring_from_file(r, fd);
296 if (bounce_status < 0) {
297 errno = bounce_error;
300 for (i = 0; i < bounce_status; i++) {
301 if (ring_putc(r, bounce_buf[i]) == EOF) {
302 /* more work to do, hold on to bounce_buf */
303 memmove(bounce_buf, bounce_buf + i, bounce_status - i);
311 ResetEvent(bounce_full);
312 SetEvent(bounce_empty);
315 #define ring_from_file w32_ring_from_file_or_bounce_buf
316 #define select(nfds, rd, wr, error, time) \
317 w32_select((nfds), (rd), (wr), (error), (time))
318 #define sigemptyset(mask) ((void)0)
320 #define sysdep_stdin_init() ((void)0)
324 * Receive and process server output from @sock.
325 * Return number of characters received on success, -1 on error.
328 recv_output(int sock)
331 * Read a chunk of server output and feed its characters into a
332 * simple state machine.
333 * Initial state is SCANNING_ID.
334 * In state SCANNING_ID, buffer the character. If it's a space,
335 * decode the id that has been buffered, and enter state BUFFERING
336 * or COPYING depending on its value.
337 * In state BUFFERING, buffer the character. If it's newline,
338 * pass id and buffered text to servercmd(), then enter state
340 * In state COPYING, pass the character to outch(). If it's
341 * newline, enter state SCANNING_ID.
344 SCANNING_ID, BUFFERING, COPYING
345 } state = SCANNING_ID;
347 static struct lbuf lbuf;
353 n = read(sock, buf, sizeof(buf));
357 for (i = 0; i < n; i++) {
362 /* FIXME gripe unexpected! */
366 lbuf_putc(&lbuf, ch);
369 line = lbuf_line(&lbuf);
385 /* unknown or unexpected id, treat like C_DATA */
393 len = lbuf_putc(&lbuf, ch);
395 line = lbuf_line(&lbuf);
396 fd = servercmd(id, line, len);
404 /* successful execute, switch to batch file */
423 #ifdef HAVE_LIBREADLINE
424 static char *input_from_rl;
425 static int has_rl_input;
428 input_handler(char *line)
430 input_from_rl = line;
437 ring_from_rl(struct ring *inbuf)
442 assert(has_rl_input && input_from_rl);
444 len = strlen(input_from_rl);
445 n = ring_space(inbuf);
448 if (len >= (size_t)n) {
449 ring_putm(inbuf, input_from_rl, n);
450 memmove(input_from_rl, input_from_rl + n, len - n + 1);
452 ring_putm(inbuf, input_from_rl, len);
453 ring_putc(inbuf, '\n');
461 #endif /* HAVE_LIBREADLINE */
464 * Receive player input from @fd into @inbuf.
465 * Return 1 on receipt of input, zero on EOF, -1 on error.
468 recv_input(int fd, struct ring *inbuf)
473 #ifdef HAVE_LIBREADLINE
476 rl_callback_read_char();
480 n = ring_from_rl(inbuf);
485 n = ring_from_file(inbuf, fd);
490 * Can't put EOF cookie into INBUF here, it may not fit.
491 * Leave it to caller.
500 send_input(int fd, struct ring *inbuf)
506 cnt = ring_to_iovec(inbuf, iov);
507 res = writev(fd, iov, cnt);
511 /* Copy input to @auxfp etc. */
512 for (i = 0; i < res; i++) {
513 ch = ring_getc(inbuf);
521 #ifdef HAVE_LIBREADLINE
522 if (fd == 0 && has_rl_input && input_from_rl)
537 * @history_file is the name of the history file, or null.
538 * The session must be in the playing phase.
539 * Return 0 when the session ended, -1 on error.
542 play(int sock, char *history_file)
545 * Player input flows from INPUT_FD through recv_input() into ring
546 * buffer INBUF, which drains into SOCK. This must not block.
547 * Server output flows from SOCK into recv_output(). Reading SOCK
551 struct ring inbuf; /* input buffer, draining to SOCK */
552 int eof_fd0; /* read fd 0 hit EOF? */
553 int partial_line_sent; /* partial input line sent? */
554 int send_eof; /* need to send EOF_COOKIE */
560 sigemptyset(&sa.sa_mask);
561 sa.sa_handler = intr;
562 sigaction(SIGINT, &sa, NULL);
563 sa.sa_handler = SIG_IGN;
564 sigaction(SIGPIPE, &sa, NULL);
565 #ifdef HAVE_LIBREADLINE
566 rl_already_prompted = 1;
568 read_history(history_file);
569 rl_bind_key('\t', rl_insert); /* Disable tab completion */
570 rl_callback_handler_install("", input_handler);
571 #endif /* HAVE_LIBREADLINE */
574 eof_fd0 = partial_line_sent = send_eof = send_intr = 0;
583 * Want to read player input only when we don't need to send
584 * cookies, haven't reached EOF on fd 0, and @inbuf can accept
587 if (!send_intr && !send_eof && (input_fd || !eof_fd0)
588 && ring_space(&inbuf))
589 FD_SET(input_fd, &rdfd);
590 /* Want to send player input only when we have something */
591 if (send_intr || send_eof || ring_len(&inbuf))
593 /* Always want to read server output */
596 n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
598 if (errno != EINTR) {
604 if ((send_eof || send_intr) && partial_line_sent
605 && ring_putc(&inbuf, '\n') != EOF)
606 partial_line_sent = 0;
607 if (send_eof && !partial_line_sent
608 && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
610 if (send_intr && !partial_line_sent
611 && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
614 /* execute aborted, switch back to fd 0 */
622 /* read player input */
623 if (FD_ISSET(input_fd, &rdfd) && ring_space(&inbuf)) {
624 n = recv_input(input_fd, &inbuf);
627 /* execute done, switch back to fd 0 */
629 perror("read batch file");
636 /* stop reading input, drain socket ring buffers */
638 perror("read stdin");
641 sa.sa_handler = SIG_DFL;
642 sigaction(SIGINT, &sa, NULL);
645 } else if (ring_len(&inbuf) > 0)
646 partial_line_sent = ring_peek(&inbuf, -1) != '\n';
649 /* send it to the server */
650 if (FD_ISSET(sock, &wrfd)) {
651 n = send_input(sock, &inbuf);
653 perror("write socket");
658 /* read server output and print it */
659 if (FD_ISSET(sock, &rdfd)) {
660 n = recv_output(sock);
662 perror("read socket");
672 #ifdef HAVE_LIBREADLINE
673 rl_callback_handler_remove();
675 write_history(history_file);
681 prompt(int code, char *prompt, char *teles)
685 snprintf(pr, sizeof(pr), "%s%s", teles, prompt);
686 #ifdef HAVE_LIBREADLINE
688 rl_forced_update_display();
689 #else /* !HAVE_LIBREADLINE */
692 #endif /* !HAVE_LIBREADLINE */
694 fprintf(auxfp, "%s%s", teles, prompt);