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 #define EOF_COOKIE "ctld\n"
55 #define INTR_COOKIE "aborted\n"
58 * Player input file descriptor
59 * 0 while reading interactive input
60 * >0 while reading a batch file
61 * <0 during error handling
65 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
68 static CRITICAL_SECTION signal_critical_section;
69 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
71 static unsigned char bounce_buf[RING_SIZE];
73 * Set bounce_empty to indicate bounce_buf is available for the stdin thread
76 static HANDLE bounce_empty;
78 * Set bounce_full to indicate bounce_buf is contains data from the
79 * stdin thread and is available for recv_input
81 static HANDLE bounce_full;
82 /* Ctrl-C (SIGINT) was detected, generate EINTR for the w32_select() */
83 static HANDLE ctrl_c_event;
84 static int bounce_status, bounce_error;
88 void (*sa_handler)(int sig);
92 static void (*ctrl_handler)(int sig) = { SIG_DFL };
95 * Ctrl-C handler for emulating the SIGINT in WIN32
98 w32_signal_handler(DWORD ctrl_type)
100 if (ctrl_type == CTRL_C_EVENT) {
101 EnterCriticalSection(signal_critical_section_ptr);
102 if (ctrl_handler != SIG_DFL) {
103 ctrl_handler(SIGINT);
104 LeaveCriticalSection(signal_critical_section_ptr);
105 SetEvent(ctrl_c_event);
108 LeaveCriticalSection(signal_critical_section_ptr);
114 * WIN32 equivalent for sigaction supports the following:
115 * set handler for SIGINT using WIN32 Ctrl-C handler
116 * reset handler SIGINT to SIG_DFL
120 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
125 if (signal == SIGPIPE)
126 assert(action->sa_handler == SIG_IGN);
128 assert(signal == SIGINT && action->sa_handler != SIG_IGN);
129 if (ctrl_handler == action->sa_handler)
131 if (signal_critical_section_ptr == NULL) {
132 signal_critical_section_ptr = &signal_critical_section;
133 InitializeCriticalSection(signal_critical_section_ptr);
135 EnterCriticalSection(signal_critical_section_ptr);
136 if (!SetConsoleCtrlHandler(w32_signal_handler,
137 action->sa_handler != SIG_DFL)) {
138 errno = GetLastError();
139 LeaveCriticalSection(signal_critical_section_ptr);
142 ctrl_handler = action->sa_handler;
143 LeaveCriticalSection(signal_critical_section_ptr);
149 * Read the stdin in WIN32 environment
150 * WIN32 does not support select type function on console input
151 * so the client uses a separate thread to read input
154 stdin_read_thread(void *dummy)
157 switch (WaitForSingleObject(bounce_empty, INFINITE)) {
160 bounce_error = GetLastError();
163 bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
164 bounce_error = errno;
171 SetEvent(bounce_full);
176 * Initialize and start the stdin reading thread for WIN32
179 sysdep_stdin_init(void)
181 bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
182 bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
183 ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
184 _beginthread(stdin_read_thread, 0, NULL);
188 * This function uses to WaitForMultipleObjects to wait for both
189 * stdin and socket reading or writing.
190 * Stdin is treated special in WIN32. Waiting for stdin is done
191 * via a bounce_full event which is set in the stdin thread.
192 * Execute command file reading is done via handle.
193 * WaitForMultipleObjects will only respond with one object,
194 * so an additonal select is also done to determine
195 * which individual events are active.
198 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd,
199 struct timeval *time)
203 int inp, sockfd, result, s_result, num_handles;
204 struct timeval tv_time = {0, 0};
205 fd_set rdsock, wrsock;
207 switch (rdfd->fd_count) {
210 sockfd = rdfd->fd_array[0];
213 inp = rdfd->fd_array[0];
214 sockfd = rdfd->fd_array[1];
219 sock = w32_fd2socket(sockfd);
221 assert(wrfd->fd_count == 0
222 || (wrfd->fd_count == 1 && wrfd->fd_array[0] == (SOCKET)sockfd));
223 assert(inp < 0 || inp == input_fd);
226 handles[num_handles++] = ctrl_c_event;
228 handles[num_handles++]
229 = inp ? (HANDLE)_get_osfhandle(inp) : bounce_full;
230 /* always wait on the socket */
231 handles[num_handles++] = WSACreateEvent();
233 if (wrfd->fd_count > 0)
234 WSAEventSelect(sock, handles[num_handles - 1],
235 FD_READ | FD_WRITE | FD_CLOSE);
237 WSAEventSelect(sock, handles[num_handles - 1],
240 result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
242 errno = GetLastError();
243 WSACloseEvent(handles[num_handles - 1]);
246 WSACloseEvent(handles[num_handles - 1]);
248 if (result == WAIT_OBJECT_0) {
255 FD_SET(sock, &rdsock);
257 FD_SET(sock, &wrsock);
258 s_result = select(sock + 1, &rdsock, &wrsock, NULL, &tv_time);
261 w32_set_winsock_errno();
265 if (!FD_ISSET(sock, &rdsock))
266 FD_CLR((SOCKET)sockfd, rdfd);
267 if (!FD_ISSET(sock, &wrsock))
268 FD_CLR((SOCKET)sockfd, wrfd);
269 if (inp >= 0 && result == WAIT_OBJECT_0 + 1)
272 FD_CLR((SOCKET)inp, rdfd);
278 * Read input from the user either stdin or from file.
279 * For stdin, read from bounce_buf which filled by the stdin thread
280 * otherwise use the regular ring_from_file.
283 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
288 return ring_from_file(r, fd);
290 if (bounce_status < 0) {
291 errno = bounce_error;
294 for (i = 0; i < bounce_status; i++) {
295 if (ring_putc(r, bounce_buf[i]) == EOF) {
296 /* more work to do, hold on to bounce_buf */
297 memmove(bounce_buf, bounce_buf + i, bounce_status - i);
305 ResetEvent(bounce_full);
306 SetEvent(bounce_empty);
309 #define ring_from_file w32_ring_from_file_or_bounce_buf
310 #define select(nfds, rd, wr, error, time) \
311 w32_select((nfds), (rd), (wr), (error), (time))
312 #define sigemptyset(mask) ((void)0)
314 #define sysdep_stdin_init() ((void)0)
318 * Receive and process server output from @sock.
319 * Return number of characters received on success, -1 on error.
322 recv_output(int sock)
325 * Read a chunk of server output and feed its characters into a
326 * simple state machine.
327 * Initial state is SCANNING_ID.
328 * In state SCANNING_ID, buffer the character. If it's a space,
329 * decode the id that has been buffered, and enter state BUFFERING
330 * or COPYING depending on its value.
331 * In state BUFFERING, buffer the character. If it's newline,
332 * pass id and buffered text to servercmd(), then enter state
334 * In state COPYING, pass the character to outch(). If it's
335 * newline, enter state SCANNING_ID.
338 SCANNING_ID, BUFFERING, COPYING
339 } state = SCANNING_ID;
341 static struct lbuf lbuf;
347 n = read(sock, buf, sizeof(buf));
351 for (i = 0; i < n; i++) {
356 /* FIXME gripe unexpected! */
360 lbuf_putc(&lbuf, ch);
363 line = lbuf_line(&lbuf);
379 /* unknown or unexpected id, treat like C_DATA */
387 len = lbuf_putc(&lbuf, ch);
389 line = lbuf_line(&lbuf);
390 fd = servercmd(id, line, len);
398 /* successful execute, switch to batch file */
418 * Receive player input from @fd into @inbuf.
419 * Return 1 on receipt of input, zero on EOF, -1 on error.
422 recv_input(int fd, struct ring *inbuf)
427 n = ring_from_file(inbuf, fd);
432 * Can't put EOF cookie into INBUF here, it may not fit.
433 * Leave it to caller.
442 send_input(int fd, struct ring *inbuf)
448 cnt = ring_to_iovec(inbuf, iov);
449 res = writev(fd, iov, cnt);
453 /* Copy input to @auxfp etc. */
454 for (i = 0; i < res; i++) {
455 ch = ring_getc(inbuf);
474 * The session must be in the playing phase.
475 * Return 0 when the session ended, -1 on error.
481 * Player input flows from INPUT_FD through recv_input() into ring
482 * buffer INBUF, which drains into SOCK. This must not block.
483 * Server output flows from SOCK into recv_output(). Reading SOCK
487 struct ring inbuf; /* input buffer, draining to SOCK */
488 int eof_fd0; /* read fd 0 hit EOF? */
489 int partial_line_sent; /* partial input line sent? */
490 int send_eof; /* need to send EOF_COOKIE */
495 sigemptyset(&sa.sa_mask);
496 sa.sa_handler = intr;
497 sigaction(SIGINT, &sa, NULL);
498 sa.sa_handler = SIG_IGN;
499 sigaction(SIGPIPE, &sa, NULL);
502 eof_fd0 = partial_line_sent = send_eof = send_intr = 0;
511 * Want to read player input only when we don't need to send
512 * cookies, haven't reached EOF on fd 0, and @inbuf can accept
515 if (!send_intr && !send_eof && (input_fd || !eof_fd0)
516 && ring_space(&inbuf))
517 FD_SET(input_fd, &rdfd);
518 /* Want to send player input only when we have something */
519 if (send_intr || send_eof || ring_len(&inbuf))
521 /* Always want to read server output */
524 n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
526 if (errno != EINTR) {
532 if ((send_eof || send_intr) && partial_line_sent
533 && ring_putc(&inbuf, '\n') != EOF)
534 partial_line_sent = 0;
535 if (send_eof && !partial_line_sent
536 && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
538 if (send_intr && !partial_line_sent
539 && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
542 /* execute aborted, switch back to fd 0 */
551 /* read player input */
552 if (FD_ISSET(input_fd, &rdfd) && ring_space(&inbuf)) {
553 n = recv_input(input_fd, &inbuf);
556 /* execute done, switch back to fd 0 */
558 perror("read batch file");
565 /* stop reading input, drain socket ring buffers */
567 perror("read stdin");
570 sa.sa_handler = SIG_DFL;
571 sigaction(SIGINT, &sa, NULL);
575 partial_line_sent = ring_peek(&inbuf, -1) != '\n';
578 /* send it to the server */
579 if (FD_ISSET(sock, &wrfd)) {
580 n = send_input(sock, &inbuf);
582 perror("write socket");
587 /* read server output and print it */
588 if (FD_ISSET(sock, &rdfd)) {
589 n = recv_output(sock);
591 perror("read socket");