]> git.pond.sub.org Git - empserver/blob - src/client/play.c
client: Rewrite readline configuration
[empserver] / src / client / play.c
1 /*
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
5  *
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.
10  *
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.
15  *
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/>.
18  *
19  *  ---
20  *
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.
24  *
25  *  ---
26  *
27  *  play.c: Playing the game
28  *
29  *  Known contributors to this file:
30  *     Markus Armbruster, 2007-2017
31  *     Ron Koenderink, 2007-2009
32  *     Martin Haukeli, 2015
33  */
34
35 #include <config.h>
36
37 #include <assert.h>
38 #include <errno.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #ifdef _WIN32
43 #include <process.h>
44 #include <sys/socket.h>
45 #else
46 #include <sys/select.h>
47 #endif
48 #include <unistd.h>
49 #include "linebuf.h"
50 #include "misc.h"
51 #include "proto.h"
52 #include "ringbuf.h"
53 #include "secure.h"
54
55 #ifdef HAVE_LIBREADLINE
56 #include <readline/readline.h>
57 #include <readline/history.h>
58 #endif
59
60 #define EOF_COOKIE "ctld\n"
61 #define INTR_COOKIE "aborted\n"
62
63 /*
64  * Player input file descriptor
65  * 0 while reading interactive input
66  * >0 while reading a batch file
67  * <0 during error handling
68  */
69 static int input_fd;
70
71 static volatile sig_atomic_t send_intr; /* need to send INTR_COOKIE */
72
73 #ifdef _WIN32
74 static CRITICAL_SECTION signal_critical_section;
75 static LPCRITICAL_SECTION signal_critical_section_ptr = NULL;
76
77 static unsigned char bounce_buf[RING_SIZE];
78 /*
79  * Set bounce_empty to indicate bounce_buf is available for the stdin thread
80  * to use.
81  */
82 static HANDLE bounce_empty;
83 /*
84  * Set bounce_full to indicate bounce_buf is contains data from the
85  * stdin thread and is available for recv_input
86  */
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;
91
92 struct sigaction {
93     int sa_flags;
94     void (*sa_handler)(int sig);
95 };
96
97 #define SIGPIPE -1
98 static void (*ctrl_handler)(int sig) = { SIG_DFL };
99
100 /*
101  * Ctrl-C handler for emulating the SIGINT in WIN32
102  */
103 static BOOL WINAPI
104 w32_signal_handler(DWORD ctrl_type)
105 {
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);
112             return TRUE;
113         } else
114             LeaveCriticalSection(signal_critical_section_ptr);
115     }
116     return FALSE;
117 }
118
119 /*
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
123  * ignore SIGPIPE
124  */
125 static int
126 sigaction(int signal, struct sigaction *action, struct sigaction *oaction)
127 {
128     assert(!oaction);
129     assert(action);
130
131     if (signal == SIGPIPE)
132         assert(action->sa_handler == SIG_IGN);
133     else {
134         assert(signal == SIGINT && action->sa_handler != SIG_IGN);
135         if (ctrl_handler == action->sa_handler)
136             return 0;
137         if (signal_critical_section_ptr == NULL) {
138             signal_critical_section_ptr = &signal_critical_section;
139             InitializeCriticalSection(signal_critical_section_ptr);
140         }
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);
146             return -1;
147         }
148         ctrl_handler = action->sa_handler;
149         LeaveCriticalSection(signal_critical_section_ptr);
150     }
151     return 0;
152 }
153
154 /*
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
158  */
159 static void
160 stdin_read_thread(void *dummy)
161 {
162     for (;;) {
163         switch (WaitForSingleObject(bounce_empty, INFINITE)) {
164         case WAIT_FAILED:
165             bounce_status = -1;
166             bounce_error = GetLastError();
167             break;
168         case WAIT_OBJECT_0:
169             bounce_status = _read(0, bounce_buf, sizeof(bounce_buf));
170             bounce_error = errno;
171             break;
172         case WAIT_ABANDONED:
173             return;
174         default:
175             assert(0);
176         }
177         SetEvent(bounce_full);
178     }
179 }
180
181 /*
182  * Initialize and start the stdin reading thread for WIN32
183  */
184 static void
185 sysdep_stdin_init(void)
186 {
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);
191 }
192
193 /*
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.
202  */
203 static int
204 w32_select(int nfds, fd_set *rdfd, fd_set *wrfd, fd_set *errfd,
205            struct timeval *time)
206 {
207     HANDLE handles[3];
208     SOCKET sock;
209     int inp, sockfd, result, s_result, num_handles;
210     struct timeval tv_time = {0, 0};
211     fd_set rdsock, wrsock;
212
213     switch (rdfd->fd_count) {
214     case 1:
215         inp = -1;
216         sockfd = rdfd->fd_array[0];
217         break;
218     case 2:
219         inp = rdfd->fd_array[0];
220         sockfd = rdfd->fd_array[1];
221         break;
222     default:
223         assert(0);
224     }
225     sock = w32_fd2socket(sockfd);
226
227     assert(wrfd->fd_count == 0
228            || (wrfd->fd_count == 1 && wrfd->fd_array[0] == (SOCKET)sockfd));
229     assert(inp < 0 || inp == input_fd);
230
231     num_handles = 0;
232     handles[num_handles++] = ctrl_c_event;
233     if (inp >= 0)
234         handles[num_handles++]
235             = inp ? (HANDLE)_get_osfhandle(inp) : bounce_full;
236     /* always wait on the socket */
237     handles[num_handles++] = WSACreateEvent();
238
239     if (wrfd->fd_count > 0)
240         WSAEventSelect(sock, handles[num_handles - 1],
241                        FD_READ | FD_WRITE | FD_CLOSE);
242     else
243         WSAEventSelect(sock, handles[num_handles - 1],
244                        FD_READ | FD_CLOSE);
245
246     result = WaitForMultipleObjects(num_handles, handles, 0, INFINITE);
247     if (result < 0) {
248         errno = GetLastError();
249         WSACloseEvent(handles[num_handles - 1]);
250         return -1;
251     }
252     WSACloseEvent(handles[num_handles - 1]);
253
254     if (result == WAIT_OBJECT_0) {
255         errno = EINTR;
256         return -1;
257     }
258
259     FD_ZERO(&rdsock);
260     FD_ZERO(&wrsock);
261     FD_SET(sock, &rdsock);
262     if (wrfd->fd_count)
263         FD_SET(sock, &wrsock);
264     s_result = select(sock + 1, &rdsock, &wrsock, NULL, &tv_time);
265
266     if (s_result < 0) {
267         w32_set_winsock_errno();
268         return s_result;
269     }
270
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)
276         s_result++;
277     else
278         FD_CLR((SOCKET)inp, rdfd);
279
280     return s_result;
281 }
282
283 /*
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.
287  */
288 static int
289 w32_ring_from_file_or_bounce_buf(struct ring *r, int fd)
290 {
291     int i, res;
292
293     if (fd)
294         return ring_from_file(r, fd);
295
296     if (bounce_status < 0) {
297         errno = bounce_error;
298         res = bounce_status;
299     } else {
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);
304                 bounce_status -= i;
305                 return i;
306             }
307         }
308         res = i;
309     }
310
311     ResetEvent(bounce_full);
312     SetEvent(bounce_empty);
313     return res;
314 }
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)
319 #else
320 #define sysdep_stdin_init() ((void)0)
321 #endif
322
323 /*
324  * Receive and process server output from @sock.
325  * Return number of characters received on success, -1 on error.
326  */
327 static int
328 recv_output(int sock)
329 {
330     /*
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
339      * SCANNING_ID.
340      * In state COPYING, pass the character to outch().  If it's
341      * newline, enter state SCANNING_ID.
342      */
343     static enum {
344         SCANNING_ID, BUFFERING, COPYING
345     } state = SCANNING_ID;
346     static int id;
347     static struct lbuf lbuf;
348     char buf[4096];
349     ssize_t n;
350     int i, ch, len, fd;
351     char *line;
352
353     n = read(sock, buf, sizeof(buf));
354     if (n < 0)
355         return -1;
356
357     for (i = 0; i < n; i++) {
358         ch = buf[i];
359         switch (state) {
360         case SCANNING_ID:
361             if (ch == '\n') {
362                 /* FIXME gripe unexpected! */
363                 lbuf_init(&lbuf);
364                 break;
365             }
366             lbuf_putc(&lbuf, ch);
367             if (ch != ' ')
368                 break;
369             line = lbuf_line(&lbuf);
370             id = parseid(line);
371             lbuf_init(&lbuf);
372
373             switch (id) {
374             case C_PROMPT:
375             case C_FLUSH:
376             case C_EXECUTE:
377             case C_EXIT:
378             case C_FLASH:
379             case C_INFORM:
380             case C_PIPE:
381             case C_REDIR:
382                 state = BUFFERING;
383                 break;
384             default:
385                 /* unknown or unexpected id, treat like C_DATA */
386             case C_DATA:
387                 state = COPYING;
388                 break;
389             }
390             break;
391
392         case BUFFERING:
393             len = lbuf_putc(&lbuf, ch);
394             if (len) {
395                 line = lbuf_line(&lbuf);
396                 fd = servercmd(id, line, len);
397                 if (fd < 0) {
398                     /* failed execute */
399                     if (input_fd)
400                         close(input_fd);
401                     input_fd = 0;
402                     send_intr = 1;
403                 } else if (fd > 0) {
404                     /* successful execute, switch to batch file */
405                     assert(!input_fd);
406                     input_fd = fd;
407                 }
408                 lbuf_init(&lbuf);
409                 state = SCANNING_ID;
410             }
411             break;
412
413         case COPYING:
414             outch(ch);
415             if (ch == '\n')
416                 state = SCANNING_ID;
417         }
418     }
419
420     return n;
421 }
422
423 #ifdef HAVE_LIBREADLINE
424 static char *input_from_rl;
425 static int has_rl_input;
426
427 static void
428 input_handler(char *line)
429 {
430     input_from_rl = line;
431     has_rl_input = 1;
432     if (line && *line)
433         add_history(line);
434 }
435
436 static int
437 ring_from_rl(struct ring *inbuf)
438 {
439     size_t len;
440     int n;
441
442     assert(has_rl_input && input_from_rl);
443
444     len = strlen(input_from_rl);
445     n = ring_space(inbuf);
446     assert(n);
447
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);
451     } else {
452         ring_putm(inbuf, input_from_rl, len);
453         ring_putc(inbuf, '\n');
454         free(input_from_rl);
455         has_rl_input = 0;
456         n = len + 1;
457     }
458
459     return n;
460 }
461 #endif /* HAVE_LIBREADLINE */
462
463 /*
464  * Receive player input from @fd into @inbuf.
465  * Return 1 on receipt of input, zero on EOF, -1 on error.
466  */
467 static int
468 recv_input(int fd, struct ring *inbuf)
469 {
470     int n;
471     int res = 1;
472
473 #ifdef HAVE_LIBREADLINE
474     if (fd == 0) {
475         if (!has_rl_input)
476             rl_callback_read_char();
477         if (!has_rl_input)
478             return 1;
479         if (input_from_rl) {
480             n = ring_from_rl(inbuf);
481         } else
482             n = 0;
483     } else
484 #endif
485         n = ring_from_file(inbuf, fd);
486     if (n < 0)
487         return -1;
488     if (n == 0) {
489         /*
490          * Can't put EOF cookie into INBUF here, it may not fit.
491          * Leave it to caller.
492          */
493         res = 0;
494     }
495
496     return res;
497 }
498
499 static int
500 send_input(int fd, struct ring *inbuf)
501 {
502     struct iovec iov[2];
503     int cnt, i, ch;
504     ssize_t res;
505
506     cnt = ring_to_iovec(inbuf, iov);
507     res = writev(fd, iov, cnt);
508     if (res < 0)
509         return res;
510
511     /* Copy input to @auxfp etc. */
512     for (i = 0; i < res; i++) {
513         ch = ring_getc(inbuf);
514         assert(ch != EOF);
515         if (ch != '\r')
516             save_input(ch);
517         if (auxfp)
518             putc(ch, auxfp);
519     }
520
521 #ifdef HAVE_LIBREADLINE
522     if (fd == 0 && has_rl_input && input_from_rl)
523         ring_from_rl(inbuf);
524 #endif
525
526     return res;
527 }
528
529 static void
530 intr(int sig)
531 {
532     send_intr = 1;
533 }
534
535 /*
536  * Play on @sock.
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.
540  */
541 int
542 play(int sock, char *history_file)
543 {
544     /*
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
548      * must not block.
549      */
550     struct sigaction sa;
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 */
555     fd_set rdfd, wrfd;
556     int n;
557     int ret = -1;
558
559     sa.sa_flags = 0;
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;
567     if (history_file)
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 */
572
573     ring_init(&inbuf);
574     eof_fd0 = partial_line_sent = send_eof = send_intr = 0;
575     input_fd = 0;
576     sysdep_stdin_init();
577
578     for (;;) {
579         FD_ZERO(&rdfd);
580         FD_ZERO(&wrfd);
581
582         /*
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
585          * some.
586          */
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))
592             FD_SET(sock, &wrfd);
593         /* Always want to read server output */
594         FD_SET(sock, &rdfd);
595
596         n = select(MAX(input_fd, sock) + 1, &rdfd, &wrfd, NULL, NULL);
597         if (n < 0) {
598             if (errno != EINTR) {
599                 perror("select");
600                 break;
601             }
602         }
603
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)
609             send_eof = 0;
610         if (send_intr && !partial_line_sent
611             && ring_putm(&inbuf, INTR_COOKIE, sizeof(INTR_COOKIE) - 1) >= 0) {
612             send_intr = 0;
613             if (input_fd) {
614                 /* execute aborted, switch back to fd 0 */
615                 close(input_fd);
616                 input_fd = 0;
617             }
618         }
619         if (n < 0)
620             continue;
621
622         /* read player input */
623         if (FD_ISSET(input_fd, &rdfd) && ring_space(&inbuf)) {
624             n = recv_input(input_fd, &inbuf);
625             if (n <= 0) {
626                 if (input_fd) {
627                     /* execute done, switch back to fd 0 */
628                     if (n < 0) {
629                         perror("read batch file");
630                         send_intr = 1;
631                     } else
632                         send_eof = 1;
633                     close(input_fd);
634                     input_fd = 0;
635                 } else {
636                     /* stop reading input, drain socket ring buffers */
637                     if (n < 0)
638                         perror("read stdin");
639                     send_eof = 1;
640                     eof_fd0 = 1;
641                     sa.sa_handler = SIG_DFL;
642                     sigaction(SIGINT, &sa, NULL);
643                     send_intr = 0;
644                 }
645             } else if (ring_len(&inbuf) > 0)
646                 partial_line_sent = ring_peek(&inbuf, -1) != '\n';
647         }
648
649         /* send it to the server */
650         if (FD_ISSET(sock, &wrfd)) {
651             n = send_input(sock, &inbuf);
652             if (n < 0) {
653                 perror("write socket");
654                 break;
655             }
656         }
657
658         /* read server output and print it */
659         if (FD_ISSET(sock, &rdfd)) {
660             n = recv_output(sock);
661             if (n < 0) {
662                 perror("read socket");
663                 break;
664             }
665             if (n == 0) {
666                 ret = 0;
667                 break;
668             }
669         }
670     }
671
672 #ifdef HAVE_LIBREADLINE
673     rl_callback_handler_remove();
674     if (history_file)
675         write_history(history_file);
676 #endif
677     return ret;
678 }
679
680 void
681 prompt(int code, char *prompt, char *teles)
682 {
683     char pr[1024];
684
685     snprintf(pr, sizeof(pr), "%s%s", teles, prompt);
686 #ifdef HAVE_LIBREADLINE
687     rl_set_prompt(pr);
688     rl_forced_update_display();
689 #else  /* !HAVE_LIBREADLINE */
690     printf("%s", pr);
691     fflush(stdout);
692 #endif /* !HAVE_LIBREADLINE */
693     if (auxfp) {
694         fprintf(auxfp, "%s%s", teles, prompt);
695         fflush(auxfp);
696     }
697 }