2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2009, Dave Pare, Jeff Bailey, Thomas Ruschak,
4 * Ken Stevens, Steve McClure
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.
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, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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.
28 * play.c: Playing the game
30 * Known contributors to this file:
31 * Markus Armbruster, 2007-2009
32 * Ron Koenderink, 2007-2009
43 #include <sys/select.h>
57 static CRITICAL_SECTION signal_critical_section;
58 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
60 static unsigned char bounce_buf[RING_SIZE];
62 * Set bounce_empty to indicate bounce_buf is available for the stdin thread
65 static HANDLE bounce_empty;
67 * Set bounce_full to indicate bounce_buf is contains data from the
68 * stdin thread and is available for recv_input
70 static HANDLE bounce_full;
71 /* Ctrl-C (SIGINT) was detected, generate EINTR for the w32_select() */
72 static HANDLE ctrl_c_event;
73 static int bounce_status, bounce_error;
77 void (*sa_handler)(int sig);
81 static void (*ctrl_handler)(int sig) = { SIG_DFL };
84 * Ctrl-C handler for emulating the SIGINT in WIN32
87 w32_signal_handler(DWORD ctrl_type)
89 if (ctrl_type == CTRL_C_EVENT) {
90 EnterCriticalSection(signal_critical_section_ptr);
91 if (ctrl_handler != SIG_DFL) {
93 LeaveCriticalSection(signal_critical_section_ptr);
94 SetEvent(ctrl_c_event);
97 LeaveCriticalSection(signal_critical_section_ptr);
103 * WIN32 equivalent for sigaction supports the following:
104 * set handler for SIGINT using WIN32 Ctrl-C handler
105 * reset handler SIGINT to SIG_DFL
109 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
114 if (signal == SIGPIPE)
115 assert(action->sa_handler == SIG_IGN);
117 assert(signal == SIGINT && action->sa_handler != SIG_IGN);
118 if (ctrl_handler == action->sa_handler)
120 if (signal_critical_section_ptr == NULL) {
121 signal_critical_section_ptr = &signal_critical_section;
122 InitializeCriticalSection(signal_critical_section_ptr);
124 EnterCriticalSection(signal_critical_section_ptr);
125 if (!SetConsoleCtrlHandler(w32_signal_handler,
126 action->sa_handler != SIG_DFL)) {
127 errno = GetLastError();
128 LeaveCriticalSection(signal_critical_section_ptr);
131 ctrl_handler = action->sa_handler;
132 LeaveCriticalSection(signal_critical_section_ptr);
138 * Read the stdin in WIN32 environment
139 * WIN32 does not support select type function on console input
140 * so the client uses a separate thread to read input
143 stdin_read_thread(void *dummy)
146 switch (WaitForSingleObject(bounce_empty, INFINITE)) {
149 bounce_error = GetLastError();
152 bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
153 bounce_error = errno;
160 SetEvent(bounce_full);
165 * Initialize and start the stdin reading thread for WIN32
168 sysdep_stdin_init(void)
170 bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
171 bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
172 ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
173 _beginthread(stdin_read_thread, 0, NULL);
177 * This function uses to WaitForMultipleObjects to wait for both
178 * stdin and socket reading or writing.
179 * Stdin is treated special in WIN32. Waiting for stdin is done
180 * via a bounce_full event which is set in the stdin thread.
181 * Execute command file reading is done via handle.
182 * WaitForMultipleObjects will only respond with one object,
183 * so an additonal select is also done to determine
184 * which individual events are active.
187 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd, struct timeval* time)
191 int inp, sockfd, result, s_result, num_handles;
192 struct timeval tv_time = {0, 0};
193 fd_set rdsock, wrsock;
195 switch (rdfd->fd_count) {
198 sockfd = rdfd->fd_array[0];
201 inp = rdfd->fd_array[0];
202 sockfd = rdfd->fd_array[1];
207 sock = W32_FD_TO_SOCKET(sockfd);
209 assert(wrfd->fd_count == 0
210 || (wrfd->fd_count == 1 && wrfd->fd_array[0] == (SOCKET)sockfd));
211 assert(inp < 0 || inp == input_fd);
214 handles[num_handles++] = ctrl_c_event;
216 handles[num_handles++]
217 = inp ? (HANDLE)_get_osfhandle(inp) : bounce_full;
218 /* always wait on the socket */
219 handles[num_handles++] = WSACreateEvent();
221 if (wrfd->fd_count > 0)
222 WSAEventSelect(sock, handles[num_handles - 1],
223 FD_READ | FD_WRITE | FD_CLOSE);
225 WSAEventSelect(sock, handles[num_handles - 1],
228 result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
230 errno = GetLastError();
231 WSACloseEvent(handles[num_handles - 1]);
234 WSACloseEvent(handles[num_handles - 1]);
236 if (result == WAIT_OBJECT_0) {
243 FD_SET(sock, &rdsock);
245 FD_SET(sock, &wrsock);
246 s_result = select(sock + 1, &rdsock, &wrsock, NULL, &tv_time);
249 w32_set_winsock_errno();
253 if (!FD_ISSET(sock, &rdsock))
254 FD_CLR((SOCKET)sockfd, rdfd);
255 if (!FD_ISSET(sock, &wrsock))
256 FD_CLR((SOCKET)sockfd, wrfd);
257 if (inp >= 0 && result == WAIT_OBJECT_0 + 1)
260 FD_CLR((SOCKET)inp, rdfd);
266 * Read input from the user either stdin or from file.
267 * For stdin, read from bounce_buf which filled by the stdin thread
268 * otherwise use the regular ring_from_file.
271 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
276 return ring_from_file(r, fd);
278 if (bounce_status < 0) {
279 errno = bounce_error;
282 for (i = 0; i < bounce_status; i++) {
283 if (ring_putc(r, bounce_buf[i]) == EOF) {
284 /* more work to do, hold on to bounce_buf */
285 memmove(bounce_buf, bounce_buf + i, bounce_status - i);
293 ResetEvent(bounce_full);
294 SetEvent(bounce_empty);
297 #define ring_from_file w32_ring_from_file_or_bounce_buf
298 #define read(sock, buffer, buf_size) \
299 w32_recv((sock), (buffer), (buf_size), 0)
300 #define select(nfds, rd, wr, error, time) \
301 w32_select((nfds), (rd), (wr), (error), (time))
302 #define sigemptyset(mask) ((void)0)
304 #define sysdep_stdin_init() ((void)0)
307 #define EOF_COOKIE "ctld\n"
308 #define INTR_COOKIE "\naborted\n"
311 int send_eof; /* need to send EOF_COOKIE */
312 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
315 * Receive and process server output from SOCK.
316 * Return number of characters received on success, -1 on error.
319 recv_output(int sock)
322 * Read a chunk of server output and feed its characters into a
323 * simple state machine.
324 * Initial state is SCANNING_ID.
325 * In state SCANNING_ID, buffer the character. If it's a space,
326 * decode the id that has been buffered, and enter state BUFFERING
327 * or COPYING depending on its value.
328 * In state BUFFERING, buffer the character. If it's newline,
329 * pass id and buffered text to servercmd(), then enter state
331 * In state COPYING, pass the character to outch(). If it's
332 * newline, enter state SCANNING_ID.
335 SCANNING_ID, BUFFERING, COPYING
336 } state = SCANNING_ID;
338 static struct lbuf lbuf;
344 n = read(sock, buf, sizeof(buf));
348 for (i = 0; i < n; i++) {
353 /* FIXME gripe unexpected! */
357 lbuf_putc(&lbuf, ch);
360 line = lbuf_line(&lbuf);
376 /* unknown or unexpected id, treat like C_DATA */
384 len = lbuf_putc(&lbuf, ch);
386 line = lbuf_line(&lbuf);
387 servercmd(id, line, len);
404 * Receive command input from FD into INBUF.
405 * Return 1 on receipt of input, zero on EOF, -1 on error.
408 recv_input(int fd, struct ring *inbuf)
410 static struct lbuf cmdbuf;
415 n = ring_from_file(inbuf, fd);
420 if (lbuf_len(&cmdbuf)) {
421 /* incomplete line */
422 ring_putc(inbuf, '\n');
426 * Can't put EOF cookie into INBUF here, it may not fit.
427 * Leave it to caller.
432 /* copy input to AUXFP etc. */
433 for (i = -n; i < 0; i++) {
434 ch = ring_peek(inbuf, i);
436 if (ch != '\r' && lbuf_putc(&cmdbuf, ch)) {
437 line = lbuf_line(&cmdbuf);
456 * The session must be in the playing phase.
457 * Return 0 when the session ended, -1 on error.
463 * Player input flows from INPUT_FD through recv_input() into ring
464 * buffer INBUF, which drains into SOCK. This must not block.
465 * Server output flows from SOCK into recv_output(). Reading SOCK
469 struct ring inbuf; /* input buffer, draining to SOCK */
470 int eof_fd0; /* read fd 0 hit EOF? */
475 sigemptyset(&sa.sa_mask);
476 sa.sa_handler = intr;
477 sigaction(SIGINT, &sa, NULL);
478 sa.sa_handler = SIG_IGN;
479 sigaction(SIGPIPE, &sa, NULL);
482 eof_fd0 = send_eof = send_intr = 0;
491 * Want to read player input only when we don't need to send
492 * cookies, and INPUT_FD is still open, and INBUF can accept
495 if (!send_intr && !send_eof && input_fd >= 0 && ring_space(&inbuf))
496 FD_SET(input_fd, &rdfd);
497 /* Want to send player input only when we have something */
498 if (send_intr || send_eof || ring_len(&inbuf))
500 /* Always want to read server output */
503 n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
505 if (errno != EINTR) {
512 && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
515 && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
518 /* execute aborted, switch back to fd 0 */
520 input_fd = eof_fd0 ? -1 : 0;
527 /* read player input */
528 if (input_fd >= 0 && FD_ISSET(input_fd, &rdfd)) {
529 n = recv_input(input_fd, &inbuf);
531 perror("read stdin"); /* FIXME stdin misleading, could be execing */
538 /* execute done, switch back to fd 0 */
540 input_fd = eof_fd0 ? -1 : 0;
542 /* stop reading input, drain socket ring buffers */
545 sa.sa_handler = SIG_DFL;
546 sigaction(SIGINT, &sa, NULL);
551 /* send it to the server */
552 if (FD_ISSET(sock, &wrfd)) {
553 n = ring_to_file(&inbuf, sock);
555 perror("write socket");
560 /* read server output and print it */
561 if (FD_ISSET(sock, &rdfd)) {
562 n = recv_output(sock);
564 perror("read socket");