Implement known_command; make gtp_is_valid() stricter
[pachi/pachi-r6144.git] / gtp.c
blob206e80e3a8edad7ac263b47003ee165bac9e9fd8
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <math.h>
5 #include <stdarg.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
11 #include "board.h"
12 #include "debug.h"
13 #include "engine.h"
14 #include "fbook.h"
15 #include "gtp.h"
16 #include "mq.h"
17 #include "uct/uct.h"
18 #include "version.h"
19 #include "timeinfo.h"
21 #define NO_REPLY (-2)
23 /* Sleep 5 seconds after a game ends to give time to kill the program. */
24 #define GAME_OVER_SLEEP 5
26 void
27 gtp_prefix(char prefix, int id)
29 if (id == NO_REPLY) return;
30 if (id >= 0)
31 printf("%c%d ", prefix, id);
32 else
33 printf("%c ", prefix);
36 void
37 gtp_flush(void)
39 putchar('\n');
40 fflush(stdout);
43 void
44 gtp_output(char prefix, int id, va_list params)
46 if (id == NO_REPLY) return;
47 gtp_prefix(prefix, id);
48 char *s;
49 while ((s = va_arg(params, char *))) {
50 fputs(s, stdout);
52 putchar('\n');
53 gtp_flush();
56 void
57 gtp_reply(int id, ...)
59 va_list params;
60 va_start(params, id);
61 gtp_output('=', id, params);
62 va_end(params);
65 void
66 gtp_error(int id, ...)
68 va_list params;
69 va_start(params, id);
70 gtp_output('?', id, params);
71 va_end(params);
74 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
75 * it should only be used between master and slaves of the distributed engine. */
76 static char *known_commands =
77 "protocol_version\n"
78 "echo\n"
79 "name\n"
80 "version\n"
81 "list_commands\n"
82 "known_command\n"
83 "quit\n"
84 "boardsize\n"
85 "clear_board\n"
86 "kgs-game_over\n"
87 "komi\n"
88 "kgs-rules\n"
89 "play\n"
90 "genmove\n"
91 "kgs-genmove_cleanup\n"
92 "set_free_handicap\n"
93 "place_free_handicap\n"
94 "final_status_list\n"
95 "undo\n"
96 "pachi-result\n"
97 "kgs-chat\n"
98 "time_left\n"
99 "time_settings\n"
100 "kgs-time_settings";
103 /* Return true if cmd is a valid gtp command. */
104 bool
105 gtp_is_valid(char *cmd)
107 if (!cmd || !*cmd) return false;
108 char *s = strcasestr(known_commands, cmd);
109 if (!s) return false;
110 if (s != known_commands && s[-1] != '\n') return false;
112 int len = strlen(cmd);
113 return s[len] == '\0' || s[len] == '\n';
116 /* XXX: THIS IS TOTALLY INSECURE!!!!
117 * Even basic input checking is missing. */
119 enum parse_code
120 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
122 #define next_tok(to_) \
123 to_ = next; \
124 next = next + strcspn(next, " \t\r\n"); \
125 if (*next) { \
126 *next = 0; next++; \
127 next += strspn(next, " \t\r\n"); \
130 if (strchr(buf, '#'))
131 *strchr(buf, '#') = 0;
133 char *cmd, *next = buf;
134 next_tok(cmd);
136 int id = -1;
137 if (isdigit(*cmd)) {
138 id = atoi(cmd);
139 next_tok(cmd);
142 if (!*cmd)
143 return P_OK;
145 if (!strcasecmp(cmd, "protocol_version")) {
146 gtp_reply(id, "2", NULL);
147 return P_OK;
149 } else if (!strcasecmp(cmd, "name")) {
150 /* KGS hack */
151 gtp_reply(id, "Pachi ", engine->name, NULL);
152 return P_OK;
154 } else if (!strcasecmp(cmd, "echo")) {
155 gtp_reply(id, next, NULL);
156 return P_OK;
158 } else if (!strcasecmp(cmd, "version")) {
159 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
160 return P_OK;
162 } else if (!strcasecmp(cmd, "list_commands")) {
163 gtp_reply(id, known_commands, NULL);
164 return P_OK;
166 } else if (!strcasecmp(cmd, "known_command")) {
167 char *arg;
168 next_tok(arg);
169 if (gtp_is_valid(arg)) {
170 gtp_reply(id, "true", NULL);
171 } else {
172 gtp_reply(id, "false", NULL);
174 return P_OK;
177 if (engine->notify && gtp_is_valid(cmd)) {
178 char *reply;
179 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
180 if (c == P_NOREPLY) {
181 id = NO_REPLY;
182 } else if (c == P_DONE_OK) {
183 gtp_reply(id, reply, NULL);
184 return P_OK;
185 } else if (c == P_DONE_ERROR) {
186 gtp_error(id, reply, NULL);
187 /* This is an internal error for the engine, but
188 * it is still OK from main's point of view. */
189 return P_OK;
190 } else if (c != P_OK) {
191 return c;
195 if (!strcasecmp(cmd, "quit")) {
196 gtp_reply(id, NULL);
197 exit(0);
199 } else if (!strcasecmp(cmd, "boardsize")) {
200 char *arg;
201 next_tok(arg);
202 int size = atoi(arg);
203 if (size < 1 || size > BOARD_MAX_SIZE) {
204 gtp_error(id, "illegal board size", NULL);
205 return P_OK;
207 board_resize(board, size);
208 gtp_reply(id, NULL);
210 } else if (!strcasecmp(cmd, "clear_board")) {
211 board_clear(board);
212 if (DEBUGL(1) && debug_boardprint)
213 board_print(board, stderr);
214 gtp_reply(id, NULL);
215 return P_ENGINE_RESET;
217 } else if (!strcasecmp(cmd, "kgs-game_over")) {
218 /* The game may not be really over, just adjourned.
219 * Do not clear the board to avoid illegal moves
220 * if the game is resumed immediately after. KGS
221 * may start directly with genmove on resumption. */
222 if (DEBUGL(1)) {
223 fprintf(stderr, "game is over\n");
224 fflush(stderr);
226 /* Sleep before replying, so that kgs doesn't
227 * start another game immediately. */
228 sleep(GAME_OVER_SLEEP);
229 gtp_reply(id, NULL);
231 } else if (!strcasecmp(cmd, "komi")) {
232 char *arg;
233 next_tok(arg);
234 sscanf(arg, PRIfloating, &board->komi);
236 if (DEBUGL(1 && debug_boardprint))
237 board_print(board, stderr);
238 gtp_reply(id, NULL);
240 } else if (!strcasecmp(cmd, "kgs-rules")) {
241 char *arg;
242 next_tok(arg);
243 if (!strcasecmp(arg, "japanese")) {
244 board->rules = RULES_JAPANESE;
245 } else if (!strcasecmp(arg, "chinese")) {
246 board->rules = RULES_CHINESE;
247 } else if (!strcasecmp(arg, "aga")) {
248 board->rules = RULES_AGA;
249 } else if (!strcasecmp(arg, "new_zealand")) {
250 board->rules = RULES_NEW_ZEALAND;
251 } else {
252 gtp_error(id, "unknown rules", NULL);
253 return P_OK;
255 gtp_reply(id, NULL);
257 } else if (!strcasecmp(cmd, "play")) {
258 struct move m;
260 char *arg;
261 next_tok(arg);
262 m.color = str2stone(arg);
263 next_tok(arg);
264 coord_t *c = str2coord(arg, board_size(board));
265 m.coord = *c; coord_done(c);
266 char *reply = NULL;
268 if (DEBUGL(1))
269 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
271 // This is where kgs starts the timer, not at genmove!
272 time_start_timer(&ti[stone_other(m.color)]);
274 if (engine->notify_play)
275 reply = engine->notify_play(engine, board, &m);
276 if (board_play(board, &m) < 0) {
277 if (DEBUGL(0)) {
278 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
279 board_print(board, stderr);
281 gtp_error(id, "illegal move", NULL);
282 } else {
283 if (DEBUGL(1) && debug_boardprint)
284 board_print_custom(board, stderr, engine->printhook);
285 gtp_reply(id, reply, NULL);
288 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
289 char *arg;
290 next_tok(arg);
291 enum stone color = str2stone(arg);
292 coord_t *c = NULL;
294 if (!ti[color].len.t.timer_start) {
295 /* First game move. */
296 time_start_timer(&ti[color]);
299 coord_t cf = pass;
300 if (board->fbook)
301 cf = fbook_check(board);
302 if (!is_pass(cf)) {
303 c = coord_copy(cf);
304 } else {
305 c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
307 struct move m = { *c, color };
308 if (board_play(board, &m) < 0) {
309 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
310 abort();
312 char *str = coord2str(*c, board);
313 if (DEBUGL(1))
314 fprintf(stderr, "playing move %s\n", str);
315 if (DEBUGL(1) && debug_boardprint) {
316 board_print_custom(board, stderr, engine->printhook);
318 gtp_reply(id, str, NULL);
319 free(str); coord_done(c);
321 /* Account for spent time. If our GTP peer keeps our clock, this will
322 * be overriden by next time_left GTP command properly. */
323 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
324 * should be absolutely rare situation and we will just spend a little
325 * less time than we could on next few moves.) */
326 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
327 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
329 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
330 char *arg;
331 next_tok(arg);
332 enum stone color = str2stone(arg);
333 void *stats;
334 int stats_size;
336 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
337 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
338 &stats, &stats_size);
339 if (!reply) {
340 gtp_error(id, "genmoves error", NULL);
341 return P_OK;
343 if (DEBUGL(3))
344 fprintf(stderr, "proposing moves %s\n", reply);
345 if (DEBUGL(4) && debug_boardprint)
346 board_print_custom(board, stderr, engine->printhook);
347 gtp_reply(id, reply, NULL);
348 if (stats_size > 0) {
349 double start = time_now();
350 fwrite(stats, 1, stats_size, stdout);
351 fflush(stdout);
352 if (DEBUGVV(2))
353 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
354 stats_size, (time_now() - start)*1000);
357 } else if (!strcasecmp(cmd, "set_free_handicap")) {
358 struct move m;
359 m.color = S_BLACK;
361 char *arg;
362 next_tok(arg);
363 do {
364 coord_t *c = str2coord(arg, board_size(board));
365 m.coord = *c; coord_done(c);
366 if (DEBUGL(1))
367 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
369 if (board_play(board, &m) < 0) {
370 if (DEBUGL(0))
371 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
372 gtp_error(id, "illegal move", NULL);
374 board->handicap++;
375 next_tok(arg);
376 } while (*arg);
377 if (DEBUGL(1) && debug_boardprint)
378 board_print(board, stderr);
379 gtp_reply(id, NULL);
381 /* TODO: Engine should choose free handicap; however, it tends to take
382 * overly long to think it all out, and unless it's clever its
383 * handicap stones won't be of much help. ;-) */
384 } else if (!strcasecmp(cmd, "place_free_handicap")
385 || !strcasecmp(cmd, "fixed_handicap")) {
386 char *arg;
387 next_tok(arg);
388 int stones = atoi(arg);
390 gtp_prefix('=', id);
391 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
392 if (DEBUGL(1) && debug_boardprint)
393 board_print(board, stderr);
394 if (id == NO_REPLY) return P_OK;
395 putchar('\n');
396 gtp_flush();
398 } else if (!strcasecmp(cmd, "final_score")) {
399 struct move_queue q = { .moves = 0 };
400 if (engine->dead_group_list)
401 engine->dead_group_list(engine, board, &q);
402 floating_t score = board_official_score(board, &q);
403 char str[64];
404 if (DEBUGL(1))
405 fprintf(stderr, "counted score %.1f\n", score);
406 if (score == 0) {
407 gtp_reply(id, "0", NULL);
408 } else if (score > 0) {
409 snprintf(str, 64, "W+%.1f", score);
410 gtp_reply(id, str, NULL);
411 } else {
412 snprintf(str, 64, "B+%.1f", -score);
413 gtp_reply(id, str, NULL);
416 /* XXX: This is a huge hack. */
417 } else if (!strcasecmp(cmd, "final_status_list")) {
418 if (id == NO_REPLY) return P_OK;
419 char *arg;
420 next_tok(arg);
421 struct move_queue q = { .moves = 0 };
422 if (engine->dead_group_list)
423 engine->dead_group_list(engine, board, &q);
424 /* else we return empty list - i.e. engine not supporting
425 * this assumes all stones alive at the game end. */
426 if (!strcasecmp(arg, "dead")) {
427 gtp_prefix('=', id);
428 for (unsigned int i = 0; i < q.moves; i++) {
429 foreach_in_group(board, q.move[i]) {
430 printf("%s ", coord2sstr(c, board));
431 } foreach_in_group_end;
432 putchar('\n');
434 if (!q.moves)
435 putchar('\n');
436 gtp_flush();
437 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
438 gtp_prefix('=', id);
439 bool printed_group = false;
440 foreach_point(board) { // foreach_group, effectively
441 group_t g = group_at(board, c);
442 if (!g || g != c) continue;
444 for (unsigned int i = 0; i < q.moves; i++) {
445 if (q.move[i] == g)
446 goto next_group;
448 foreach_in_group(board, g) {
449 printf("%s ", coord2sstr(c, board));
450 } foreach_in_group_end;
451 putchar('\n');
452 printed_group = true;
453 next_group:;
454 } foreach_point_end;
455 if (!printed_group)
456 putchar('\n');
457 gtp_flush();
458 } else {
459 gtp_error(id, "illegal status specifier", NULL);
462 } else if (!strcasecmp(cmd, "undo")) {
463 if (board_undo(board) < 0) {
464 if (DEBUGL(1)) {
465 fprintf(stderr, "undo on non-pass move %s\n", coord2sstr(board->last_move.coord, board));
466 board_print(board, stderr);
468 gtp_error(id, "cannot undo", NULL);
469 return P_OK;
471 char *reply = NULL;
472 if (engine->undo)
473 reply = engine->undo(engine, board);
474 if (DEBUGL(1) && debug_boardprint)
475 board_print(board, stderr);
476 gtp_reply(id, reply, NULL);
478 /* Custom commands for handling UCT opening tbook */
479 } else if (!strcasecmp(cmd, "uct_gentbook")) {
480 /* Board must be initialized properly, as if for genmove;
481 * makes sense only as 'uct_gentbook b'. */
482 char *arg;
483 next_tok(arg);
484 enum stone color = str2stone(arg);
485 if (uct_gentbook(engine, board, &ti[color], color))
486 gtp_reply(id, NULL);
487 else
488 gtp_error(id, "error generating tbook", NULL);
490 } else if (!strcasecmp(cmd, "uct_dumptbook")) {
491 char *arg;
492 next_tok(arg);
493 enum stone color = str2stone(arg);
494 uct_dumptbook(engine, board, color);
495 gtp_reply(id, NULL);
497 } else if (!strcasecmp(cmd, "uct_evaluate")) {
498 char *arg;
499 next_tok(arg);
500 enum stone color = str2stone(arg);
502 gtp_prefix('=', id);
503 /* Iterate through the list of all free coordinates
504 * and call uct_evaluate() for each. uct_evaluate()
505 * will throw NAN in case of invalid moves and such. */
506 for (int i = 0; i < board->flen; i++) {
507 floating_t val = uct_evaluate(engine, board, &ti[color], board->f[i], color);
508 if (isnan(val))
509 continue;
510 printf("%s %1.3f\n", coord2sstr(board->f[i], board), (double) val);
512 gtp_flush();
514 } else if (!strcasecmp(cmd, "pachi-result")) {
515 /* More detailed result of the last genmove. */
516 /* For UCT, the output format is: = color move playouts winrate dynkomi */
517 char *reply = NULL;
518 if (engine->result)
519 reply = engine->result(engine, board);
520 if (reply)
521 gtp_reply(id, reply, NULL);
522 else
523 gtp_error(id, "unknown pachi-result command", NULL);
525 } else if (!strcasecmp(cmd, "kgs-chat")) {
526 char *loc;
527 next_tok(loc);
528 char *src;
529 next_tok(src);
530 char *msg;
531 next_tok(msg);
532 char *reply = NULL;
533 if (engine->chat)
534 reply = engine->chat(engine, board, msg);
535 if (reply)
536 gtp_reply(id, reply, NULL);
537 else
538 gtp_error(id, "unknown kgs-chat command", NULL);
540 } else if (!strcasecmp(cmd, "time_left")) {
541 char *arg;
542 next_tok(arg);
543 enum stone color = str2stone(arg);
544 next_tok(arg);
545 int time = atoi(arg);
546 next_tok(arg);
547 int stones = atoi(arg);
548 if (!ti[color].ignore_gtp) {
549 time_left(&ti[color], time, stones);
550 } else {
551 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
554 gtp_reply(id, NULL);
556 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
557 char *time_system;
558 char *arg;
559 if (!strcasecmp(cmd, "kgs-time_settings")) {
560 next_tok(time_system);
561 } else {
562 time_system = "canadian";
565 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
566 if (!strcasecmp(time_system, "none")) {
567 main_time = -1;
568 } else if (!strcasecmp(time_system, "absolute")) {
569 next_tok(arg);
570 main_time = atoi(arg);
571 } else if (!strcasecmp(time_system, "byoyomi")) {
572 next_tok(arg);
573 main_time = atoi(arg);
574 next_tok(arg);
575 byoyomi_time = atoi(arg);
576 next_tok(arg);
577 byoyomi_periods = atoi(arg);
578 } else if (!strcasecmp(time_system, "canadian")) {
579 next_tok(arg);
580 main_time = atoi(arg);
581 next_tok(arg);
582 byoyomi_time = atoi(arg);
583 next_tok(arg);
584 byoyomi_stones = atoi(arg);
587 if (DEBUGL(1))
588 fprintf(stderr, "time_settings %d %d/%d*%d\n",
589 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
590 if (!ti[S_BLACK].ignore_gtp) {
591 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
592 ti[S_WHITE] = ti[S_BLACK];
593 } else {
594 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
597 gtp_reply(id, NULL);
599 } else {
600 gtp_error(id, "unknown command", NULL);
601 return P_UNKNOWN_COMMAND;
603 return P_OK;
605 #undef next_tok