2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2021, 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
45 #include <sys/socket.h>
47 #include <sys/select.h>
56 #ifdef HAVE_LIBREADLINE
57 #include <readline/readline.h>
58 #include <readline/history.h>
61 #define EOF_COOKIE "ctld\n"
62 #define INTR_COOKIE "aborted\n"
65 * Player input file descriptor
66 * 0 while reading interactive input
67 * >0 while reading a batch file
68 * <0 during error handling
72 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
75 static CRITICAL_SECTION signal_critical_section;
76 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
78 static unsigned char bounce_buf[RING_SIZE];
80 * Set bounce_empty to indicate bounce_buf is available for the stdin thread
83 static HANDLE bounce_empty;
85 * Set bounce_full to indicate bounce_buf is contains data from the
86 * stdin thread and is available for recv_input
88 static HANDLE bounce_full;
89 /* Ctrl-C (SIGINT) was detected, generate EINTR for the w32_select() */
90 static HANDLE ctrl_c_event;
91 static int bounce_status, bounce_error;
95 void (*sa_handler)(int sig);
99 static void (*ctrl_handler)(int sig) = { SIG_DFL };
102 * Ctrl-C handler for emulating the SIGINT in WIN32
105 w32_signal_handler(DWORD ctrl_type)
107 if (ctrl_type == CTRL_C_EVENT) {
108 EnterCriticalSection(signal_critical_section_ptr);
109 if (ctrl_handler != SIG_DFL) {
110 ctrl_handler(SIGINT);
111 LeaveCriticalSection(signal_critical_section_ptr);
112 SetEvent(ctrl_c_event);
115 LeaveCriticalSection(signal_critical_section_ptr);
121 * WIN32 equivalent for sigaction supports the following:
122 * set handler for SIGINT using WIN32 Ctrl-C handler
123 * reset handler SIGINT to SIG_DFL
127 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
132 if (signal == SIGPIPE)
133 assert(action->sa_handler == SIG_IGN);
135 assert(signal == SIGINT && action->sa_handler != SIG_IGN);
136 if (ctrl_handler == action->sa_handler)
138 if (signal_critical_section_ptr == NULL) {
139 signal_critical_section_ptr = &signal_critical_section;
140 InitializeCriticalSection(signal_critical_section_ptr);
142 EnterCriticalSection(signal_critical_section_ptr);
143 if (!SetConsoleCtrlHandler(w32_signal_handler,
144 action->sa_handler != SIG_DFL)) {
145 errno = GetLastError();
146 LeaveCriticalSection(signal_critical_section_ptr);
149 ctrl_handler = action->sa_handler;
150 LeaveCriticalSection(signal_critical_section_ptr);
156 * Read the stdin in WIN32 environment
157 * WIN32 does not support select type function on console input
158 * so the client uses a separate thread to read input
161 stdin_read_thread(void *dummy)
164 switch (WaitForSingleObject(bounce_empty, INFINITE)) {
167 bounce_error = GetLastError();
170 bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
171 bounce_error = errno;
178 SetEvent(bounce_full);
183 * Initialize and start the stdin reading thread for WIN32
186 sysdep_stdin_init(void)
188 bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
189 bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
190 ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
191 _beginthread(stdin_read_thread, 0, NULL);
195 * This function uses to WaitForMultipleObjects to wait for both
196 * stdin and socket reading or writing.
197 * Stdin is treated special in WIN32. Waiting for stdin is done
198 * via a bounce_full event which is set in the stdin thread.
199 * Execute command file reading is done via handle.
200 * WaitForMultipleObjects will only respond with one object,
201 * so an additonal select is also done to determine
202 * which individual events are active.
205 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd,
206 struct timeval *time)
210 int inp, sockfd, result, s_result, num_handles;
211 struct timeval tv_time = {0, 0};
212 fd_set rdsock, wrsock;
214 switch (rdfd->fd_count) {
217 sockfd = rdfd->fd_array[0];
220 inp = rdfd->fd_array[0];
221 sockfd = rdfd->fd_array[1];
226 sock = w32_fd2socket(sockfd);
228 assert(wrfd->fd_count == 0
229 || (wrfd->fd_count == 1 && wrfd->fd_array[0] == (SOCKET)sockfd));
230 assert(inp < 0 || inp == input_fd);
233 handles[num_handles++] = ctrl_c_event;
235 handles[num_handles++]
236 = inp ? (HANDLE)_get_osfhandle(inp) : bounce_full;
237 /* always wait on the socket */
238 handles[num_handles++] = WSACreateEvent();
240 if (wrfd->fd_count > 0)
241 WSAEventSelect(sock, handles[num_handles - 1],
242 FD_READ | FD_WRITE | FD_CLOSE);
244 WSAEventSelect(sock, handles[num_handles - 1],
247 result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
249 errno = GetLastError();
250 WSACloseEvent(handles[num_handles - 1]);
253 WSACloseEvent(handles[num_handles - 1]);
255 if (result == WAIT_OBJECT_0) {
262 FD_SET(sock, &rdsock);
264 FD_SET(sock, &wrsock);
265 s_result = select(sock + 1, &rdsock, &wrsock, NULL, &tv_time);
268 w32_set_winsock_errno();
272 if (!FD_ISSET(sock, &rdsock))
273 FD_CLR((SOCKET)sockfd, rdfd);
274 if (!FD_ISSET(sock, &wrsock))
275 FD_CLR((SOCKET)sockfd, wrfd);
276 if (inp >= 0 && result == WAIT_OBJECT_0 + 1)
279 FD_CLR((SOCKET)inp, rdfd);
285 * Read input from the user either stdin or from file.
286 * For stdin, read from bounce_buf which filled by the stdin thread
287 * otherwise use the regular ring_from_file.
290 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
295 return ring_from_file(r, fd);
297 if (bounce_status < 0) {
298 errno = bounce_error;
301 for (i = 0; i < bounce_status; i++) {
302 if (ring_putc(r, bounce_buf[i]) == EOF) {
303 /* more work to do, hold on to bounce_buf */
304 memmove(bounce_buf, bounce_buf + i, bounce_status - i);
312 ResetEvent(bounce_full);
313 SetEvent(bounce_empty);
316 #define ring_from_file w32_ring_from_file_or_bounce_buf
317 #define select(nfds, rd, wr, error, time) \
318 w32_select((nfds), (rd), (wr), (error), (time))
319 #define sigemptyset(mask) ((void)0)
321 #define sysdep_stdin_init() ((void)0)
325 * Receive and process server output from @sock.
326 * Return number of characters received on success, -1 on error.
329 recv_output(int sock)
332 * Read a chunk of server output and feed its characters into a
333 * simple state machine.
334 * Initial state is SCANNING_ID.
335 * In state SCANNING_ID, buffer the character. If it's a space,
336 * decode the ID that has been buffered, and enter state BUFFERING
337 * or COPYING depending on its value.
338 * In state BUFFERING, buffer the character. If it's newline,
339 * pass ID and buffered text to servercmd(), then enter state
341 * In state COPYING, pass the character to outch(). If it's
342 * newline, enter state SCANNING_ID.
345 SCANNING_ID, BUFFERING, COPYING
346 } state = SCANNING_ID;
348 static struct lbuf lbuf;
354 n = read(sock, buf, sizeof(buf));
358 for (i = 0; i < n; i++) {
363 /* FIXME gripe unexpected! */
367 lbuf_putc(&lbuf, ch);
370 line = lbuf_line(&lbuf);
386 /* unknown or unexpected ID, treat like C_DATA */
394 len = lbuf_putc(&lbuf, ch);
396 line = lbuf_line(&lbuf);
397 fd = servercmd(id, line, len);
405 /* successful execute, switch to batch file */
424 #ifdef HAVE_LIBREADLINE
425 static int use_readline;
426 static char *input_from_rl;
427 static int has_rl_input;
430 input_handler(char *line)
432 input_from_rl = line;
439 ring_from_rl(struct ring *inbuf)
444 assert(has_rl_input && input_from_rl);
446 len = strlen(input_from_rl);
447 n = ring_space(inbuf);
450 if (len >= (size_t)n) {
451 ring_putm(inbuf, input_from_rl, n);
452 memmove(input_from_rl, input_from_rl + n, len - n + 1);
454 ring_putm(inbuf, input_from_rl, len);
455 ring_putc(inbuf, '\n');
463 #endif /* HAVE_LIBREADLINE */
466 * Receive player input from @fd into @inbuf.
467 * Return 1 on receipt of input, zero on EOF, -1 on error.
470 recv_input(int fd, struct ring *inbuf)
475 #ifdef HAVE_LIBREADLINE
476 if (fd == 0 && use_readline) {
478 rl_callback_read_char();
482 n = ring_from_rl(inbuf);
487 n = ring_from_file(inbuf, fd);
492 * Can't put EOF cookie into @inbuf here, it may not fit.
493 * Leave it to caller.
502 send_input(int fd, struct ring *inbuf)
508 cnt = ring_to_iovec(inbuf, iov);
509 res = writev(fd, iov, cnt);
513 /* Copy input to @auxfp etc. */
514 for (i = 0; i < res; i++) {
515 ch = ring_getc(inbuf);
523 #ifdef HAVE_LIBREADLINE
524 if (fd == 0 && use_readline && has_rl_input && input_from_rl)
539 * @history_file is the name of the history file, or null.
540 * The session must be in the playing phase.
541 * Return 0 when the session ended, -1 on error.
544 play(int sock, char *history_file)
547 * Player input flows from @input_fd through recv_input() into
548 * ring buffer @inbuf, which drains into @sock. This must not
549 * block. Server output flows from @sock into recv_output().
550 * Reading @sock must not block.
553 struct ring inbuf; /* input buffer, draining to SOCK */
554 int eof_fd0; /* read fd 0 hit EOF? */
555 int partial_line_sent; /* partial input line sent? */
556 int send_eof; /* need to send EOF_COOKIE */
562 sigemptyset(&sa.sa_mask);
563 sa.sa_handler = intr;
564 sigaction(SIGINT, &sa, NULL);
565 sa.sa_handler = SIG_IGN;
566 sigaction(SIGPIPE, &sa, NULL);
567 #ifdef HAVE_LIBREADLINE
570 rl_already_prompted = 1;
571 rl_readline_name = "Empire";
573 read_history(history_file);
574 rl_bind_key('\t', rl_insert); /* Disable tab completion */
575 rl_callback_handler_install("", input_handler);
577 #endif /* HAVE_LIBREADLINE */
580 eof_fd0 = partial_line_sent = send_eof = send_intr = 0;
589 * Want to read player input only when we don't need to send
590 * cookies, haven't reached EOF on fd 0, and @inbuf can accept
593 if (!send_intr && !send_eof && (input_fd || !eof_fd0)
594 && ring_space(&inbuf))
595 FD_SET(input_fd, &rdfd);
596 /* Want to send player input only when we have something */
597 if (send_intr || send_eof || ring_len(&inbuf))
599 /* Always want to read server output */
602 n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
604 if (errno != EINTR) {
610 if ((send_eof || send_intr) && partial_line_sent
611 && ring_putc(&inbuf, '\n') != EOF)
612 partial_line_sent = 0;
613 if (send_eof && !partial_line_sent
614 && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
616 if (send_intr && !partial_line_sent
617 && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
620 /* execute aborted, switch back to fd 0 */
628 /* read player input */
629 if (FD_ISSET(input_fd, &rdfd) && ring_space(&inbuf)) {
630 n = recv_input(input_fd, &inbuf);
633 /* execute done, switch back to fd 0 */
635 perror("read batch file");
642 /* stop reading input, drain socket ring buffers */
644 perror("read stdin");
647 sa.sa_handler = SIG_DFL;
648 sigaction(SIGINT, &sa, NULL);
651 } else if (ring_len(&inbuf) > 0)
652 partial_line_sent = ring_peek(&inbuf, -1) != '\n';
655 /* send it to the server */
656 if (FD_ISSET(sock, &wrfd)) {
657 n = send_input(sock, &inbuf);
659 perror("write socket");
664 /* read server output and print it */
665 if (FD_ISSET(sock, &rdfd)) {
666 n = recv_output(sock);
668 perror("read socket");
678 #ifdef HAVE_LIBREADLINE
680 rl_callback_handler_remove();
682 write_history(history_file);
689 prompt(int code, char *prompt, char *teles)
693 snprintf(pr, sizeof(pr), "%s%s", teles, prompt);
694 #ifdef HAVE_LIBREADLINE
697 rl_forced_update_display();
699 #endif /* HAVE_LIBREADLINE */
705 fprintf(auxfp, "%s%s", teles, prompt);