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
32 * Ron Koenderink, 2007-2009
43 #include <sys/select.h>
56 static CRITICAL_SECTION signal_critical_section;
57 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
59 static unsigned char bounce_buf[RING_SIZE];
61 * Set bounce_empty to indicate bounce_buf is available for the stdin thread
64 static HANDLE bounce_empty;
66 * Set bounce_full to indicate bounce_buf is contains data from the
67 * stdin thread and is available for recv_input
69 static HANDLE bounce_full;
70 /* Ctrl-C (SIGINT) was detected, generate EINTR for the w32_select() */
71 static HANDLE ctrl_c_event;
72 static int bounce_status, bounce_error;
75 static void (*ctrl_handler)(int sig) = { SIG_DFL };
78 * Ctrl-C handler for emulating the SIGINT in WIN32
81 w32_signal_handler(DWORD ctrl_type)
83 if (ctrl_type == CTRL_C_EVENT) {
84 EnterCriticalSection(signal_critical_section_ptr);
85 if (ctrl_handler != SIG_DFL) {
87 LeaveCriticalSection(signal_critical_section_ptr);
88 SetEvent(ctrl_c_event);
91 LeaveCriticalSection(signal_critical_section_ptr);
97 * WIN32 equivalent for sigaction supports the following:
98 * set handler for SIGINT using WIN32 Ctrl-C handler
99 * reset handler SIGINT to SIG_DFL
103 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
108 if (signal == SIGPIPE)
109 assert(action->sa_handler == SIG_IGN);
111 assert(signal == SIGINT && action->sa_handler != SIG_IGN);
112 if (ctrl_handler == action->sa_handler)
114 if (signal_critical_section_ptr == NULL) {
115 signal_critical_section_ptr = &signal_critical_section;
116 InitializeCriticalSection(signal_critical_section_ptr);
118 EnterCriticalSection(signal_critical_section_ptr);
119 if (!SetConsoleCtrlHandler(w32_signal_handler,
120 action->sa_handler != SIG_DFL)) {
121 errno = GetLastError();
122 LeaveCriticalSection(signal_critical_section_ptr);
125 ctrl_handler = action->sa_handler;
126 LeaveCriticalSection(signal_critical_section_ptr);
132 * Read the stdin in WIN32 environment
133 * WIN32 does not support select type function on console input
134 * so the client uses a separate thread to read input
137 stdin_read_thread(void *dummy)
140 switch (WaitForSingleObject(bounce_empty, INFINITE)) {
143 bounce_error = GetLastError();
146 bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
147 bounce_error = errno;
154 SetEvent(bounce_full);
159 * Initialize and start the stdin reading thread for WIN32
162 sysdep_stdin_init(void)
164 bounce_empty = CreateEvent(NULL, FALSE, TRUE, NULL);
165 bounce_full = CreateEvent(NULL, TRUE, FALSE, NULL);
166 ctrl_c_event = CreateEvent(NULL, FALSE, FALSE, NULL);
167 _beginthread(stdin_read_thread, 0, NULL);
171 * This function uses to WaitForMultipleObjects to wait for both
172 * stdin and socket reading or writing.
173 * Stdin is treated special in WIN32. Waiting for stdin is done
174 * via a bounce_full event which is set in the stdin thread.
175 * Execute command file reading is done via handle. Execute
176 * command is read via CreateFile/ReadFile instead open/read
177 * because a file descriptor is not waitable.
178 * WaitForMultipleObjects will only respond with one object
179 * so an additonal select is also done to determine
180 * which individual events are active for the sock.
183 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd, struct timeval* time)
187 int inp, result, s_result, num_handles;
188 struct timeval tv_time = {0, 0};
191 switch (rdfd->fd_count) {
194 sock = rdfd->fd_array[0];
197 inp = rdfd->fd_array[0];
198 sock = rdfd->fd_array[1];
204 assert(wrfd->fd_count == 0
205 || (wrfd->fd_count == 1 && wrfd->fd_array[0] == sock));
206 assert(inp < 0 || inp == input_fd);
209 handles[num_handles++] = ctrl_c_event;
211 handles[num_handles++] = inp ? (HANDLE)inp : bounce_full;
212 /* always wait on the socket */
213 handles[num_handles++] = WSACreateEvent();
215 if (wrfd->fd_count > 0)
216 WSAEventSelect(sock, handles[num_handles - 1],
217 FD_READ | FD_WRITE | FD_CLOSE);
219 WSAEventSelect(sock, handles[num_handles - 1],
222 result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
224 errno = GetLastError();
225 WSACloseEvent(handles[num_handles - 1]);
228 WSACloseEvent(handles[num_handles - 1]);
230 if (result == WAIT_OBJECT_0) {
236 FD_SET(sock, &rdfd2);
237 s_result = select(sock + 1, &rdfd2, wrfd, NULL, &tv_time);
240 errno = WSAGetLastError();
245 if (inp >= 0 && result == WAIT_OBJECT_0 + 1) {
246 FD_SET((SOCKET)inp, rdfd);
253 * Read input from the user either stdin or from file.
254 * For stdin, read from bounce_buf which filled by the stdin thread
255 * otherwise use the regular ring_from_file.
258 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
263 return ring_from_file(r, fd);
265 if (bounce_status < 0) {
266 errno = bounce_error;
269 for (i = 0; i < bounce_status; i++) {
270 if (ring_putc(r, bounce_buf[i]) == EOF) {
271 /* more work to do, hold on to bounce_buf */
272 memmove(bounce_buf, bounce_buf + i, bounce_status - i);
280 ResetEvent(bounce_full);
281 SetEvent(bounce_empty);
284 #define ring_from_file w32_ring_from_file_or_bounce_buf
285 #define close(fd) w32_close_handle((fd))
286 #define read(sock, buffer, buf_size) \
287 w32_recv((sock), (buffer), (buf_size), 0)
288 #define select(nfds, rd, wr, error, time) \
289 w32_select((nfds), (rd), (wr), (error), (time))
290 #define sigemptyset(mask) ((void)0)
292 #define sysdep_stdin_init() ((void)0)
295 #define EOF_COOKIE "ctld\n"
296 #define INTR_COOKIE "\naborted\n"
299 int send_eof; /* need to send EOF_COOKIE */
300 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
303 * Receive and process server output from SOCK.
304 * Return number of characters received on success, -1 on error.
307 recv_output(int sock)
310 * Read a chunk of server output and feed its characters into a
311 * simple state machine.
312 * Initial state is SCANNING_ID.
313 * In state SCANNING_ID, buffer the character. If it's a space,
314 * decode the id that has been buffered, and enter state BUFFERING
315 * or COPYING depending on its value.
316 * In state BUFFERING, buffer the character. If it's newline,
317 * pass id and buffered text to servercmd(), then enter state
319 * In state COPYING, pass the character to outch(). If it's
320 * newline, enter state SCANNING_ID.
323 SCANNING_ID, BUFFERING, COPYING
324 } state = SCANNING_ID;
326 static struct lbuf lbuf;
332 n = read(sock, buf, sizeof(buf));
336 for (i = 0; i < n; i++) {
341 /* FIXME gripe unexpected! */
345 lbuf_putc(&lbuf, ch);
348 line = lbuf_line(&lbuf);
364 /* unknown or unexpected id, treat like C_DATA */
372 len = lbuf_putc(&lbuf, ch);
374 line = lbuf_line(&lbuf);
375 servercmd(id, line, len);
392 * Receive command input from FD into INBUF.
393 * Return 1 on receipt of input, zero on EOF, -1 on error.
396 recv_input(int fd, struct ring *inbuf)
398 static struct lbuf cmdbuf;
403 n = ring_from_file(inbuf, fd);
408 if (lbuf_len(&cmdbuf)) {
409 /* incomplete line */
410 ring_putc(inbuf, '\n');
414 * Can't put EOF cookie into INBUF here, it may not fit.
415 * Leave it to caller.
420 /* copy input to AUXFP etc. */
421 for (i = -n; i < 0; i++) {
422 ch = ring_peek(inbuf, i);
424 if (ch != '\r' && lbuf_putc(&cmdbuf, ch)) {
425 line = lbuf_line(&cmdbuf);
444 * The session must be in the playing phase.
445 * Return 0 when the session ended, -1 on error.
451 * Player input flows from INPUT_FD through recv_input() into ring
452 * buffer INBUF, which drains into SOCK. This must not block.
453 * Server output flows from SOCK into recv_output(). Reading SOCK
457 struct ring inbuf; /* input buffer, draining to SOCK */
458 int eof_fd0; /* read fd 0 hit EOF? */
463 sigemptyset(&sa.sa_mask);
464 sa.sa_handler = intr;
465 sigaction(SIGINT, &sa, NULL);
466 sa.sa_handler = SIG_IGN;
467 sigaction(SIGPIPE, &sa, NULL);
470 eof_fd0 = send_eof = send_intr = 0;
479 * Want to read player input only when we don't need to send
480 * cookies, and INPUT_FD is still open, and INBUF can accept
483 if (!send_intr && !send_eof && input_fd >= 0 && ring_space(&inbuf))
484 FD_SET(input_fd, &rdfd);
485 /* Want to send player input only when we have something */
486 if (send_intr || send_eof || ring_len(&inbuf))
488 /* Always want to read server output */
491 n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
493 if (errno != EINTR) {
500 && ring_putm(&inbuf, EOF_COOKIE, sizeof(EOF_COOKIE) - 1) >= 0)
503 && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
506 /* execute aborted, switch back to fd 0 */
508 input_fd = eof_fd0 ? -1 : 0;
515 /* read player input */
516 if (input_fd >= 0 && FD_ISSET(input_fd, &rdfd)) {
517 n = recv_input(input_fd, &inbuf);
519 perror("read stdin"); /* FIXME stdin misleading, could be execing */
526 /* execute done, switch back to fd 0 */
528 input_fd = eof_fd0 ? -1 : 0;
530 /* stop reading input, drain socket ring buffers */
533 sa.sa_handler = SIG_DFL;
534 sigaction(SIGINT, &sa, NULL);
539 /* send it to the server */
540 if (FD_ISSET(sock, &wrfd)) {
541 n = ring_to_file(&inbuf, sock);
543 perror("write socket");
548 /* read server output and print it */
549 if (FD_ISSET(sock, &rdfd)) {
550 n = recv_output(sock);
552 perror("read socket");