1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
|
/*
* external.c
*
* by Gary Wong <gtw@gnu.org>, 2001, 2002.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 3 or later of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: external.c,v 1.59 2008/03/15 10:17:23 Superfly_Jon Exp $
*/
#include "config.h"
#if HAVE_SOCKETS
#include <signal.h>
#include <glib.h>
#include <glib/gstdio.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif /* #if HAVE_UNISTD_H */
#ifndef WIN32
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_SYS_SOCKET_H
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/un.h>
#endif /* #if HAVE_SYS_SOCKET_H */
#include <stdio.h>
#else /* #ifndef WIN32 */
#include <winsock2.h>
#include <ws2tcpip.h>
#define EWOULDBLOCK WSAEWOULDBLOCK
#define EINPROGRESS WSAEINPROGRESS
#define EALREADY WSAEALREADY
#define ENOTSOCK WSAENOTSOCK
#define EDESTADDRREQ WSAEDESTADDRREQ
#define EMSGSIZE WSAEMSGSIZE
#define EPROTOTYPE WSAEPROTOTYPE
#define ENOPROTOOPT WSAENOPROTOOPT
#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT
#define EOPNOTSUPP WSAEOPNOTSUPP
#define EPFNOSUPPORT WSAEPFNOSUPPORT
#define EAFNOSUPPORT WSAEAFNOSUPPORT
#define EADDRINUSE WSAEADDRINUSE
#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
#define ENETDOWN WSAENETDOWN
#define ENETUNREACH WSAENETUNREACH
#define ENETRESET WSAENETRESET
#define ECONNABORTED WSAECONNABORTED
#define ECONNRESET WSAECONNRESET
#define ENOBUFS WSAENOBUFS
#define EISCONN WSAEISCONN
#define ENOTCONN WSAENOTCONN
#define ESHUTDOWN WSAESHUTDOWN
#define ETOOMANYREFS WSAETOOMANYREFS
#define ETIMEDOUT WSAETIMEDOUT
#define ECONNREFUSED WSAECONNREFUSED
#define ELOOP WSAELOOP
#define ENAMETOOLONG WSAENAMETOOLONG
#define EHOSTDOWN WSAEHOSTDOWN
#define EHOSTUNREACH WSAEHOSTUNREACH
#define ENOTEMPTY WSAENOTEMPTY
#define EPROCLIM WSAEPROCLIM
#define EUSERS WSAEUSERS
#define EDQUOT WSAEDQUOT
#define ESTALE WSAESTALE
#define EREMOTE WSAEREMOTE
#define EINVAL WSAEINVAL
#define EINTR WSAEINTR
#define inet_aton(ip,addr) (addr)->s_addr = inet_addr(ip), 1
#define inet_pton(fam,ip,addr) (addr)->s_addr = inet_addr(ip), 1
#endif /* #ifndef WIN32 */
#endif /* HAVE_SOCKETS */
#include "backgammon.h"
#include "drawboard.h"
#include "external.h"
#include "rollout.h"
#include <glib/gi18n.h>
#if HAVE_SOCKETS
/* Stuff for the yacc/lex parser */
extern extcmd ec;
static int fError = FALSE;
static char *szError = NULL;
extern void ExtStartParse( const char *s );
#if defined(AF_UNIX) && !defined(AF_LOCAL)
#define AF_LOCAL AF_UNIX
#define PF_LOCAL PF_UNIX
#endif
#ifdef WIN32
void OutputWin32SocketError(const char* action)
{
LPVOID lpMsgBuf;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS ,
NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf, 0, NULL) != 0)
{
outputerrf(_("Windows socket error (%s):\n%s"), action, (LPCTSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
}
}
#endif
extern int ExternalSocket( struct sockaddr **ppsa, int *pcb, char *sz ) {
int sock, f;
struct sockaddr_un *psun;
struct sockaddr_in *psin;
struct hostent *phe;
char *pch;
if( ( pch = strchr( sz, ':' ) ) && !strchr( sz, '/' ) ) {
/* Internet domain socket. */
if( ( sock = socket( PF_INET, SOCK_STREAM, 0 ) ) < 0 )
return -1;
f = TRUE;
#ifdef WIN32
if( setsockopt( (SOCKET) sock, SOL_SOCKET, SO_REUSEADDR, (const char*) &f, sizeof f ) )
#else
if( setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &f, sizeof f ) )
#endif /* WIN32 */
return -1;
psin = malloc( *pcb = sizeof (struct sockaddr_in) );
memset( psin, 0, sizeof (*psin));
psin->sin_family = AF_INET;
/* split hostname and port */
*pch = 0;
if( !*sz )
/* no host specified */
psin->sin_addr.s_addr = htonl( INADDR_ANY );
#ifdef WIN32
else {
#else
else if( !inet_aton( sz, &psin->sin_addr ) ) {
#endif /* WIN32 */
if( !( phe = gethostbyname( sz ) ) ) {
*pch = ':';
errno = EINVAL;
free( psin );
return -1;
}
#ifdef WIN32
memcpy( &(psin->sin_addr), (struct in_addr *) (phe->h_addr), phe->h_length);
#else
psin->sin_addr = *(struct in_addr *) phe->h_addr;
#endif /* WIN32 */
}
*pch++ = ':';
psin->sin_port = htons( atoi( pch ) );
*ppsa = (struct sockaddr *) psin;
} else {
/* Local domain socket. */
if( ( sock = socket( PF_LOCAL, SOCK_STREAM, 0 ) ) < 0 )
return -1;
/* yuck... there's no portable way to obtain the necessary
sockaddr_un size, but this is a conservative estimate */
psun = malloc( *pcb = 16 + strlen( sz ) );
#ifndef WIN32
psun->sun_family = AF_LOCAL;
strcpy( psun->sun_path, sz );
#else /* #ifndef WIN32 */
/* FIXME: what will we do on Windows? */
return -1;
#endif /* #ifndef WIN32 */
*ppsa = (struct sockaddr *) psun;
}
return sock;
#if 0
g_assert( FALSE );
#endif /* 0 */
}
#endif /* HAVE_SOCKETS */
#if HAVE_SOCKETS
static void ExternalUnbind( char *sz ) {
if( strchr( sz, ':' ) && !strchr( sz, '/' ) )
/* it was a TCP socket; no cleanup necessary */
return;
g_unlink( sz );
}
#endif /* HAVE_SOCKETS */
#if HAVE_SOCKETS
extern int ExternalRead( int h, char *pch, size_t cch ) {
char *p = pch, *pEnd;
int n;
#ifndef WIN32
psighandler sh;
#endif
while( cch )
{
ProcessGtkEvents();
if( fInterrupt )
return -1;
#ifndef WIN32
PortableSignal( SIGPIPE, SIG_IGN, &sh, FALSE );
#endif
#ifdef WIN32
/* reading from sockets doesn't work on Windows
use recv instead */
n = recv( (SOCKET) h, p, cch, 0);
#else
n = read( h, p, cch );
#endif
#ifndef WIN32
PortableSignalRestore( SIGPIPE, &sh );
#endif
if( !n ) {
outputl( _("External connection closed.") );
return -1;
} else if( n < 0 ) {
if( errno == EINTR )
continue;
SockErr( _("reading from external connection") );
return -1;
}
if( ( pEnd = memchr( p, '\n', n ) ) ) {
*pEnd = 0;
return 0;
}
cch -= n;
p += n;
}
p[ cch - 1 ] = 0;
return 0;
#if 0
g_assert( FALSE );
#endif
}
#endif /* HAVE_SOCKETS */
#if HAVE_SOCKETS
extern int ExternalWrite( int h, char *pch, size_t cch ) {
char *p = pch;
int n;
#ifndef WIN32
psighandler sh;
#endif
while( cch )
{
ProcessGtkEvents();
if( fInterrupt )
return -1;
#ifndef WIN32
PortableSignal( SIGPIPE, SIG_IGN, &sh, FALSE );
#endif
#ifdef WIN32
/* writing to sockets doesn't work on Windows
use send instead */
n = send( (SOCKET) h, (const char *) p, cch, 0);
#else
n = write( h, p, cch );
#endif
#ifndef WIN32
PortableSignalRestore( SIGPIPE, &sh );
#endif
if( !n )
return 0;
else if( n < 0 ) {
if( errno == EINTR )
continue;
SockErr( _("writing to external connection") );
return -1;
}
cch -= n;
p += n;
}
return 0;
#if 0
g_assert( FALSE );
#endif
}
#endif /* HAVE_SOCKETS */
#if HAVE_SOCKETS
static void
ErrorHandler( const char *szMessage, const char *szNear,
const int fParseError ) {
fError = TRUE;
g_free( szError );
szError =
g_strdup_printf( "Error (%s) near '%s'\n", szMessage, szNear );
}
static extcmd *
ExtParse( const char *szCommand ) {
ExtErrorHandler = ErrorHandler;
fError = FALSE;
szError = NULL;
ExtStartParse(szCommand);
return fError ? NULL : &ec;
}
static char *
ExtEvaluation( extcmd *pec ) {
char szName[ MAX_NAME_LEN ], szOpp[ MAX_NAME_LEN ];
int nMatchTo, anScore[ 2 ],
anDice[ 2 ], nCube, fCubeOwner, fDoubled, fTurn, fCrawford;
TanBoard anBoard;
float arOutput[ NUM_ROLLOUT_OUTPUTS ];
cubeinfo ci;
int nScore, nScoreOpponent;
char *szResponse;
float r;
evalcontext ec;
if( ParseFIBSBoard( pec->szFIBSBoard, anBoard, szName, szOpp, &nMatchTo,
&nScore, &nScoreOpponent, anDice, &nCube,
&fCubeOwner, &fDoubled, &fTurn, &fCrawford ) ) {
outputl( _("Warning: badly formed board from external controller.") );
szResponse =
g_strdup_printf( "Error: badly formed board ('%s')\n", pec->szFIBSBoard );
}
else {
anScore[ 0 ] = fTurn ? nScoreOpponent : nScore;
anScore[ 1 ] = fTurn ? nScore : nScoreOpponent;
SetCubeInfo ( &ci, nCube, fCubeOwner, fTurn, nMatchTo, anScore,
fCrawford, fJacoby, nBeavers, bgvDefault );
ec.fCubeful = pec->fCubeful;
ec.nPlies = pec->nPlies;
#if defined( REDUCTION_CODE )
ec.nReduced = pec->nReduced;
#else
ec.fUsePrune = pec->fUsePrune;
#endif
ec.fDeterministic = pec->fDeterministic;
ec.rNoise = pec->rNoise;
if ( !fTurn )
SwapSides( anBoard );
if ( GeneralEvaluationE( arOutput, (ConstTanBoard)anBoard, &ci, &ec ) )
return NULL;
if ( nMatchTo ) {
if ( ec.fCubeful )
r = arOutput[ OUTPUT_CUBEFUL_EQUITY ];
else
r = eq2mwc( arOutput[ OUTPUT_EQUITY ], &ci );
}
else
r = ec.fCubeful ? arOutput[ 6 ] : arOutput[ 5 ];
szResponse = g_strdup_printf( "%f %f %f %f %f %f\n",
arOutput[ 0 ],
arOutput[ 1 ],
arOutput[ 2 ],
arOutput[ 3 ],
arOutput[ 4 ],
r );
}
return szResponse;
}
static char *
ExtFIBSBoard( extcmd *pec ) {
char szName[ MAX_NAME_LEN ], szOpp[ MAX_NAME_LEN ];
int nMatchTo, anScore[ 2 ],
anDice[ 2 ], nCube, fCubeOwner, fDoubled, fTurn, fCrawford,
anMove[ 8 ];
TanBoard anBoard, anBoardOrig;
float arDouble[ NUM_CUBEFUL_OUTPUTS ],
aarOutput[ 2 ][ NUM_ROLLOUT_OUTPUTS ],
aarStdDev[ 2 ][ NUM_ROLLOUT_OUTPUTS ];
rolloutstat aarsStatistics[ 2 ][ 2 ];
cubeinfo ci;
int nScore, nScoreOpponent;
char *szResponse;
if( ParseFIBSBoard( pec->szFIBSBoard, anBoard, szName, szOpp, &nMatchTo,
&nScore, &nScoreOpponent, anDice, &nCube,
&fCubeOwner, &fDoubled, &fTurn, &fCrawford ) ) {
outputl( _("Warning: badly formed board from external controller.") );
szResponse =
g_strdup_printf( "Error: badly formed board ('%s')\n", pec->szFIBSBoard );
}
else {
anScore[ 0 ] = fTurn ? nScoreOpponent : nScore;
anScore[ 1 ] = fTurn ? nScore : nScoreOpponent;
SetCubeInfo ( &ci, nCube, fCubeOwner, fTurn, nMatchTo, anScore,
fCrawford, fJacoby, nBeavers, bgvDefault );
if ( !fTurn )
SwapSides( anBoard );
#if 0
{
char *asz[ 7 ] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL };
cha szBoard[ 10000 ];
outputl( DrawBoard( szBoard, anBoard, fTurn, asz,
"no matchid", 15 ) );
printf( "score %d-%d to %d ", anScore[ 0 ], anScore[ 1 ],
nMatchTo );
printf( "dice %d %d ", anDice[ 0 ], anDice[ 1 ] );
printf( "cubeowner %d cube %d turn %d crawford %d doubled %d\n",
fCubeOwner, nCube, fTurn, fCrawford, fDoubled );
}
#endif
memcpy( anBoardOrig, anBoard, sizeof( anBoard ) );
if ( fDoubled ) {
/* take decision */
if( GeneralCubeDecision( aarOutput, aarStdDev,
aarsStatistics, (ConstTanBoard)anBoard, &ci,
&esEvalCube, NULL, NULL ) < 0 )
return NULL;
switch( FindCubeDecision( arDouble, aarOutput, &ci )) {
case DOUBLE_PASS:
case TOOGOOD_PASS:
case REDOUBLE_PASS:
case TOOGOODRE_PASS:
szResponse = g_strdup( "drop\n" );
break;
case NODOUBLE_BEAVER:
case DOUBLE_BEAVER:
case NO_REDOUBLE_BEAVER:
szResponse = g_strdup( "beaver\n" );
break;
default:
szResponse = g_strdup( "take\n" );
}
#if 0
/* this code is broken as the sign of fDoubled
indicates who doubled */
} else if ( fDoubled < 0 ) {
/* if opp wants to resign (extension to FIBS board) */
float arOutput[ NUM_ROLLOUT_OUTPUTS ];
float rEqBefore, rEqAfter;
const float epsilon = 1.0e-6;
getResignation( arOutput, anBoard, &ci, &esEvalCube );
getResignEquities ( arOutput, &ci, -fDoubled,
&rEqBefore, &rEqAfter );
/* if opponent gives up equity by resigning */
if( ( rEqAfter - epsilon ) < rEqBefore )
szResponse = g_strdup( "accept\n" );
else
szResponse = g_strdup( "reject\n" );
#endif /* broken */
} else if( anDice[ 0 ] ) {
/* move */
char szMove[ 64 ];
if( FindBestMove( anMove, anDice[ 0 ], anDice[ 1 ],
anBoard, &ci, &esEvalChequer.ec,
aamfEval ) < 0 )
return NULL;
FormatMovePlain( szMove, anBoardOrig, anMove );
szResponse = g_strconcat( szMove, "\n", NULL );
} else {
/* double decision */
if( GeneralCubeDecision( aarOutput, aarStdDev,
aarsStatistics, (ConstTanBoard)anBoard, &ci,
&esEvalCube, NULL, NULL ) < 0 )
return NULL;
switch( FindCubeDecision( arDouble, aarOutput, &ci )) {
case DOUBLE_TAKE:
case DOUBLE_PASS:
case DOUBLE_BEAVER:
case REDOUBLE_TAKE:
case REDOUBLE_PASS:
szResponse = g_strdup( "double\n" );
break;
default:
szResponse = g_strdup( "roll\n" );
}
}
}
return szResponse;
}
#endif
extern void CommandExternal( char *sz ) {
#if !HAVE_SOCKETS
outputl( _("This installation of GNU Backgammon was compiled without\n"
"socket support, and does not implement external controllers.") );
#else
int h, hPeer, cb;
struct sockaddr *psa;
char szCommand[ 256 ];
char *szResponse = NULL;
struct sockaddr_in saRemote;
socklen_t saLen;
extcmd *pec;
sz = NextToken( &sz );
if( !sz || !*sz ) {
outputl( _("You must specify the name of the socket to the external\n"
"controller -- try `help external'.") );
return;
}
listenloop:
{
if( ( h = ExternalSocket( &psa, &cb, sz ) ) < 0 ) {
SockErr( sz );
return;
}
if( bind( h, psa, cb ) < 0 ) {
SockErr( sz );
closesocket( h );
free( psa );
return;
}
free( psa );
if( listen( h, 1 ) < 0 ) {
SockErr( _("listen") );
closesocket( h );
ExternalUnbind( sz );
return;
}
outputf( _("Waiting for a connection from %s...\n"), sz);
outputx();
ProcessGtkEvents();
/* Must set length when using windows */
saLen = sizeof(struct sockaddr);
while( ( hPeer = accept( h, (struct sockaddr*)&saRemote, &saLen ) ) < 0 )
{
if( errno == EINTR )
{
ProcessGtkEvents();
if( fInterrupt ) {
closesocket( h );
ExternalUnbind( sz );
return;
}
continue;
}
SockErr( _("accept") );
closesocket( h );
ExternalUnbind( sz );
return;
}
closesocket( h );
ExternalUnbind( sz );
/* print info about remove client */
outputf( _("Accepted connection from %s.\n"),
inet_ntoa( saRemote.sin_addr ) );
outputx();
ProcessGtkEvents();
while( !ExternalRead( hPeer, szCommand, sizeof( szCommand ) ) ) {
if ( ! ( pec = ExtParse( szCommand ) ) ) {
/* parse error */
szResponse = szError;
}
else {
switch ( pec->ct ) {
case COMMAND_NONE:
szResponse = g_strdup( "Error: no command given\n" );
break;
case COMMAND_FIBSBOARD:
szResponse = ExtFIBSBoard( pec );
break;
case COMMAND_EVALUATION:
szResponse = ExtEvaluation( pec );
break;
}
}
if ( szResponse ) {
if ( ExternalWrite( hPeer, szResponse, strlen( szResponse ) ) )
break;
g_free( szResponse );
}
}
closesocket( hPeer );
}
goto listenloop;
#endif
}
|