PATTERN_SPEC_MATCHFAST: Whitelist PFs instead of blacklisting
[pachi/peepo.git] / gtp.c
blob9fe6ee847a3ca82af866856df4ce2edce9597812
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <stdarg.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
10 #include "board.h"
11 #include "debug.h"
12 #include "engine.h"
13 #include "gtp.h"
14 #include "mq.h"
15 #include "uct/uct.h"
16 #include "version.h"
17 #include "timeinfo.h"
19 #define NO_REPLY (-2)
21 /* Sleep 5 seconds after a game ends to give time to kill the program. */
22 #define GAME_OVER_SLEEP 5
24 void
25 gtp_prefix(char prefix, int id)
27 if (id == NO_REPLY) return;
28 if (id >= 0)
29 printf("%c%d ", prefix, id);
30 else
31 printf("%c ", prefix);
34 void
35 gtp_flush(void)
37 putchar('\n');
38 fflush(stdout);
41 void
42 gtp_output(char prefix, int id, va_list params)
44 if (id == NO_REPLY) return;
45 gtp_prefix(prefix, id);
46 char *s;
47 while ((s = va_arg(params, char *))) {
48 fputs(s, stdout);
50 putchar('\n');
51 gtp_flush();
54 void
55 gtp_reply(int id, ...)
57 va_list params;
58 va_start(params, id);
59 gtp_output('=', id, params);
60 va_end(params);
63 void
64 gtp_error(int id, ...)
66 va_list params;
67 va_start(params, id);
68 gtp_output('?', id, params);
69 va_end(params);
72 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
73 * it should only be used between master and slaves of the distributed engine. */
74 static char *known_commands =
75 "protocol_version\n"
76 "name\n"
77 "version\n"
78 "list_commands\n"
79 "quit\n"
80 "boardsize\n"
81 "clear_board\n"
82 "kgs-game_over\n"
83 "komi\n"
84 "kgs-rules\n"
85 "play\n"
86 "genmove\n"
87 "kgs-genmove_cleanup\n"
88 "set_free_handicap\n"
89 "place_free_handicap\n"
90 "final_status_list\n"
91 "kgs-chat\n"
92 "time_left\n"
93 "time_settings\n"
94 "kgs-time_settings";
97 /* Return true if cmd is a valid gtp command. */
98 bool
99 gtp_is_valid(char *cmd)
101 if (!cmd || !*cmd) return false;
102 char *s = strcasestr(known_commands, cmd);
103 if (!s) return false;
105 int len = strlen(cmd);
106 return s[len] == '\0' || s[len] == '\n';
109 /* XXX: THIS IS TOTALLY INSECURE!!!!
110 * Even basic input checking is missing. */
112 enum parse_code
113 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
115 #define next_tok(to_) \
116 to_ = next; \
117 next = next + strcspn(next, " \t\r\n"); \
118 if (*next) { \
119 *next = 0; next++; \
120 next += strspn(next, " \t\r\n"); \
123 if (strchr(buf, '#'))
124 *strchr(buf, '#') = 0;
126 char *cmd, *next = buf;
127 next_tok(cmd);
129 int id = -1;
130 if (isdigit(*cmd)) {
131 id = atoi(cmd);
132 next_tok(cmd);
135 if (!*cmd)
136 return P_OK;
138 if (!strcasecmp(cmd, "protocol_version")) {
139 gtp_reply(id, "2", NULL);
140 return P_OK;
142 } else if (!strcasecmp(cmd, "name")) {
143 /* KGS hack */
144 gtp_reply(id, "Pachi ", engine->name, NULL);
145 return P_OK;
147 } else if (!strcasecmp(cmd, "version")) {
148 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
149 return P_OK;
151 } else if (!strcasecmp(cmd, "list_commands")) {
152 gtp_reply(id, known_commands, NULL);
153 return P_OK;
156 if (engine->notify) {
157 char *reply;
158 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
159 if (c == P_NOREPLY) {
160 id = NO_REPLY;
161 } else if (c == P_DONE_OK) {
162 gtp_reply(id, reply, NULL);
163 return P_OK;
164 } else if (c == P_DONE_ERROR) {
165 gtp_error(id, reply, NULL);
166 /* This is an internal error for the engine, but
167 * it is still OK from main's point of view. */
168 return P_OK;
169 } else if (c != P_OK) {
170 return c;
174 if (!strcasecmp(cmd, "quit")) {
175 gtp_reply(id, NULL);
176 exit(0);
178 } else if (!strcasecmp(cmd, "boardsize")) {
179 char *arg;
180 next_tok(arg);
181 board_resize(board, atoi(arg));
183 gtp_reply(id, NULL);
185 } else if (!strcasecmp(cmd, "clear_board") || !strcasecmp(cmd, "kgs-game_over")) {
186 board_clear(board);
187 if (DEBUGL(1))
188 board_print(board, stderr);
189 if (!strcasecmp(cmd, "kgs-game_over")) {
190 if (DEBUGL(0))
191 fprintf(stderr, "game is over\n");
192 /* Sleep before replying, so that kgs doesn't
193 * start another game immediately. */
194 sleep(GAME_OVER_SLEEP);
196 gtp_reply(id, NULL);
197 return P_ENGINE_RESET;
199 } else if (!strcasecmp(cmd, "komi")) {
200 char *arg;
201 next_tok(arg);
202 sscanf(arg, "%f", &board->komi);
204 if (DEBUGL(1))
205 board_print(board, stderr);
206 gtp_reply(id, NULL);
208 } else if (!strcasecmp(cmd, "kgs-rules")) {
209 char *arg;
210 next_tok(arg);
211 if (!strcasecmp(arg, "japanese")) {
212 board->rules = RULES_JAPANESE;
213 } else if (!strcasecmp(arg, "chinese")) {
214 board->rules = RULES_CHINESE;
215 } else if (!strcasecmp(arg, "aga")) {
216 board->rules = RULES_AGA;
217 } else if (!strcasecmp(arg, "new_zealand")) {
218 board->rules = RULES_NEW_ZEALAND;
219 } else {
220 gtp_error(id, "unknown rules", NULL);
221 return P_OK;
223 gtp_reply(id, NULL);
225 } else if (!strcasecmp(cmd, "play")) {
226 struct move m;
228 char *arg;
229 next_tok(arg);
230 m.color = str2stone(arg);
231 next_tok(arg);
232 coord_t *c = str2coord(arg, board_size(board));
233 m.coord = *c; coord_done(c);
234 char *reply = NULL;
236 if (DEBUGL(1))
237 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
239 // This is where kgs starts the timer, not at genmove!
240 time_start_timer(&ti[stone_other(m.color)]);
242 if (engine->notify_play)
243 reply = engine->notify_play(engine, board, &m);
244 if (board_play(board, &m) < 0) {
245 if (DEBUGL(0)) {
246 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
247 board_print(board, stderr);
249 gtp_error(id, "illegal move", NULL);
250 } else {
251 if (DEBUGL(1))
252 board_print_custom(board, stderr, engine->printhook);
253 gtp_reply(id, reply, NULL);
256 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
257 char *arg;
258 next_tok(arg);
259 enum stone color = str2stone(arg);
261 coord_t *c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
262 struct move m = { *c, color };
263 if (board_play(board, &m) < 0) {
264 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
265 abort();
267 char *str = coord2str(*c, board);
268 if (DEBUGL(1))
269 fprintf(stderr, "playing move %s\n", str);
270 if (DEBUGL(1)) {
271 board_print_custom(board, stderr, engine->printhook);
273 gtp_reply(id, str, NULL);
274 free(str); coord_done(c);
276 /* Account for spent time. If our GTP peer keeps our clock, this will
277 * be overriden by next time_left GTP command properly. */
278 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
279 * should be absolutely rare situation and we will just spend a little
280 * less time than we could on next few moves.) */
281 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
282 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
284 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
285 char *arg;
286 next_tok(arg);
287 enum stone color = str2stone(arg);
288 void *stats;
289 int stats_size;
291 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
292 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
293 &stats, &stats_size);
294 if (!reply) {
295 gtp_error(id, "genmoves error", NULL);
296 return P_OK;
298 if (DEBUGL(3))
299 fprintf(stderr, "proposing moves %s\n", reply);
300 if (DEBUGL(4))
301 board_print_custom(board, stderr, engine->printhook);
302 gtp_reply(id, reply, NULL);
303 if (stats_size > 0) {
304 double start = time_now();
305 fwrite(stats, 1, stats_size, stdout);
306 fflush(stdout);
307 if (DEBUGVV(2))
308 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
309 stats_size, (time_now() - start)*1000);
312 } else if (!strcasecmp(cmd, "set_free_handicap")) {
313 struct move m;
314 m.color = S_BLACK;
316 char *arg;
317 next_tok(arg);
318 do {
319 coord_t *c = str2coord(arg, board_size(board));
320 m.coord = *c; coord_done(c);
321 if (DEBUGL(1))
322 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
324 if (board_play(board, &m) < 0) {
325 if (DEBUGL(0))
326 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
327 gtp_error(id, "illegal move", NULL);
329 board->handicap++;
330 next_tok(arg);
331 } while (*arg);
332 if (DEBUGL(1))
333 board_print(board, stderr);
334 gtp_reply(id, NULL);
336 /* TODO: Engine should choose free handicap; however, it tends to take
337 * overly long to think it all out, and unless it's clever its
338 * handicap stones won't be of much help. ;-) */
339 } else if (!strcasecmp(cmd, "place_free_handicap")
340 || !strcasecmp(cmd, "fixed_handicap")) {
341 char *arg;
342 next_tok(arg);
343 int stones = atoi(arg);
345 gtp_prefix('=', id);
346 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
347 if (DEBUGL(1))
348 board_print(board, stderr);
349 if (id == NO_REPLY) return P_OK;
350 putchar('\n');
351 gtp_flush();
353 } else if (!strcasecmp(cmd, "final_score")) {
354 struct move_queue q = { .moves = 0 };
355 if (engine->dead_group_list)
356 engine->dead_group_list(engine, board, &q);
357 float score = board_official_score(board, &q);
358 char str[64];
359 if (DEBUGL(1))
360 fprintf(stderr, "counted score %.1f\n", score);
361 if (score == 0) {
362 gtp_reply(id, "0", NULL);
363 } else if (score > 0) {
364 snprintf(str, 64, "W+%.1f", score);
365 gtp_reply(id, str, NULL);
366 } else {
367 snprintf(str, 64, "B+%.1f", -score);
368 gtp_reply(id, str, NULL);
371 /* XXX: This is a huge hack. */
372 } else if (!strcasecmp(cmd, "final_status_list")) {
373 if (id == NO_REPLY) return P_OK;
374 char *arg;
375 next_tok(arg);
376 struct move_queue q = { .moves = 0 };
377 if (engine->dead_group_list)
378 engine->dead_group_list(engine, board, &q);
379 /* else we return empty list - i.e. engine not supporting
380 * this assumes all stones alive at the game end. */
381 if (!strcasecmp(arg, "dead")) {
382 gtp_prefix('=', id);
383 for (unsigned int i = 0; i < q.moves; i++) {
384 foreach_in_group(board, q.move[i]) {
385 printf("%s ", coord2sstr(c, board));
386 } foreach_in_group_end;
387 putchar('\n');
389 if (!q.moves)
390 putchar('\n');
391 gtp_flush();
392 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
393 gtp_prefix('=', id);
394 bool printed_group = false;
395 foreach_point(board) { // foreach_group, effectively
396 group_t g = group_at(board, c);
397 if (!g || g != c) continue;
399 for (unsigned int i = 0; i < q.moves; i++) {
400 if (q.move[i] == g)
401 goto next_group;
403 foreach_in_group(board, g) {
404 printf("%s ", coord2sstr(c, board));
405 } foreach_in_group_end;
406 putchar('\n');
407 printed_group = true;
408 next_group:;
409 } foreach_point_end;
410 if (!printed_group)
411 putchar('\n');
412 gtp_flush();
413 } else {
414 gtp_error(id, "illegal status specifier", NULL);
417 /* Custom commands for handling UCT opening book */
418 } else if (!strcasecmp(cmd, "uct_genbook")) {
419 /* Board must be initialized properly, as if for genmove;
420 * makes sense only as 'uct_genbook b'. */
421 char *arg;
422 next_tok(arg);
423 enum stone color = str2stone(arg);
424 if (uct_genbook(engine, board, &ti[color], color))
425 gtp_reply(id, NULL);
426 else
427 gtp_error(id, "error generating book", NULL);
429 } else if (!strcasecmp(cmd, "uct_dumpbook")) {
430 char *arg;
431 next_tok(arg);
432 enum stone color = str2stone(arg);
433 uct_dumpbook(engine, board, color);
434 gtp_reply(id, NULL);
436 } else if (!strcasecmp(cmd, "kgs-chat")) {
437 char *loc;
438 next_tok(loc);
439 char *src;
440 next_tok(src);
441 char *msg;
442 next_tok(msg);
443 char *reply = NULL;
444 if (engine->chat)
445 reply = engine->chat(engine, board, msg);
446 if (reply)
447 gtp_reply(id, reply, NULL);
448 else
449 gtp_error(id, "unknown chat command", NULL);
451 } else if (!strcasecmp(cmd, "time_left")) {
452 char *arg;
453 next_tok(arg);
454 enum stone color = str2stone(arg);
455 next_tok(arg);
456 int time = atoi(arg);
457 next_tok(arg);
458 int stones = atoi(arg);
459 if (!ti[color].ignore_gtp) {
460 time_left(&ti[color], time, stones);
461 } else {
462 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
465 gtp_reply(id, NULL);
467 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
468 char *time_system;
469 char *arg;
470 if (!strcasecmp(cmd, "kgs-time_settings")) {
471 next_tok(time_system);
472 } else {
473 time_system = "canadian";
476 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
477 if (!strcasecmp(time_system, "none")) {
478 main_time = -1;
479 } else if (!strcasecmp(time_system, "absolute")) {
480 next_tok(arg);
481 main_time = atoi(arg);
482 } else if (!strcasecmp(time_system, "byoyomi")) {
483 next_tok(arg);
484 main_time = atoi(arg);
485 next_tok(arg);
486 byoyomi_time = atoi(arg);
487 next_tok(arg);
488 byoyomi_periods = atoi(arg);
489 } else if (!strcasecmp(time_system, "canadian")) {
490 next_tok(arg);
491 main_time = atoi(arg);
492 next_tok(arg);
493 byoyomi_time = atoi(arg);
494 next_tok(arg);
495 byoyomi_stones = atoi(arg);
498 if (DEBUGL(1))
499 fprintf(stderr, "time_settings %d %d/%d*%d\n",
500 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
501 if (!ti[S_BLACK].ignore_gtp) {
502 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
503 ti[S_WHITE] = ti[S_BLACK];
504 } else {
505 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
508 gtp_reply(id, NULL);
510 } else {
511 gtp_error(id, "unknown command", NULL);
512 return P_UNKNOWN_COMMAND;
514 return P_OK;
516 #undef next_tok