security fix: replaced sprintf with snprintf
[xboard.git] / gamelist.c
1 /*
2  * gamelist.c -- Functions to manage a gamelist
3  *
4  * Copyright 1995, 2009, 2010 Free Software Foundation, Inc.
5  *
6  * Enhancements Copyright 2005 Alessandro Scotti
7  *
8  * ------------------------------------------------------------------------
9  *
10  * GNU XBoard is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or (at
13  * your option) any later version.
14  *
15  * GNU XBoard is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see http://www.gnu.org/licenses/.
22  *
23  *------------------------------------------------------------------------
24  ** See the file ChangeLog for a revision history.  */
25
26 #include "config.h"
27
28 #include <stdio.h>
29 #include <errno.h>
30 #if STDC_HEADERS
31 # include <stdlib.h>
32 # include <string.h>
33 #else /* not STDC_HEADERS */
34 # if HAVE_STRING_H
35 #  include <string.h>
36 # else /* not HAVE_STRING_H */
37 #  include <strings.h>
38 # endif /* not HAVE_STRING_H */
39 #endif /* not STDC_HEADERS */
40
41 #include "common.h"
42 #include "frontend.h"
43 #include "backend.h"
44 #include "parser.h"
45
46
47 /* Variables
48  */
49 List gameList;
50
51
52 /* Local function prototypes
53  */
54 static void GameListDeleteGame P((ListGame *));
55 static ListGame *GameListCreate P((void));
56 static void GameListFree P((List *));
57 static int GameListNewGame P((ListGame **));
58
59 /* [AS] Wildcard pattern matching */
60 Boolean
61 HasPattern( const char * text, const char * pattern )
62 {
63     while( *pattern != '\0' ) {
64         if( *pattern == '*' ) {
65             while( *pattern == '*' ) {
66                 pattern++;
67             }
68
69             if( *pattern == '\0' ) {
70                 return TRUE;
71             }
72
73             while( *text != '\0' ) {
74                 if( HasPattern( text, pattern ) ) {
75                     return TRUE;
76                 }
77                 text++;
78             }
79         }
80         else if( (*pattern == *text) || ((*pattern == '?') && (*text != '\0')) ) {
81             pattern++;
82             text++;
83             continue;
84         }
85
86         return FALSE;
87     }
88
89     return TRUE;
90 }
91
92 Boolean
93 SearchPattern( const char * text, const char * pattern )
94 {
95     Boolean result = TRUE;
96
97     if( pattern != NULL && *pattern != '\0' ) {
98         if( *pattern == '*' ) {
99             result = HasPattern( text, pattern );
100         }
101         else {
102             result = FALSE;
103
104             while( *text != '\0' ) {
105                 if( HasPattern( text, pattern ) ) {
106                     result = TRUE;
107                     break;
108                 }
109                 text++;
110             }
111         }
112     }
113
114     return result;
115 }
116
117 /* Delete a ListGame; implies removint it from a list.
118  */
119 static void GameListDeleteGame(listGame)
120     ListGame *listGame;
121 {
122     if (listGame) {
123         if (listGame->gameInfo.event) free(listGame->gameInfo.event);
124         if (listGame->gameInfo.site) free(listGame->gameInfo.site);
125         if (listGame->gameInfo.date) free(listGame->gameInfo.date);
126         if (listGame->gameInfo.round) free(listGame->gameInfo.round);
127         if (listGame->gameInfo.white) free(listGame->gameInfo.white);
128         if (listGame->gameInfo.black) free(listGame->gameInfo.black);
129         if (listGame->gameInfo.fen) free(listGame->gameInfo.fen);
130         if (listGame->gameInfo.resultDetails) free(listGame->gameInfo.resultDetails);
131         if (listGame->gameInfo.timeControl) free(listGame->gameInfo.timeControl);
132         if (listGame->gameInfo.extraTags) free(listGame->gameInfo.extraTags);
133         if (listGame->gameInfo.outOfBook) free(listGame->gameInfo.outOfBook);
134         ListNodeFree((ListNode *) listGame);
135     }
136 }
137
138
139 /* Free the previous list of games.
140  */
141 static void GameListFree(gameList)
142     List *gameList;
143 {
144     while (!ListEmpty(gameList))
145     {
146         GameListDeleteGame((ListGame *) gameList->head);
147     }
148 }
149
150
151
152 /* Initialize a new GameInfo structure.
153  */
154 void GameListInitGameInfo(gameInfo)
155     GameInfo *gameInfo;
156 {
157     gameInfo->event = NULL;
158     gameInfo->site = NULL;
159     gameInfo->date = NULL;
160     gameInfo->round = NULL;
161     gameInfo->white = NULL;
162     gameInfo->black = NULL;
163     gameInfo->result = GameUnfinished;
164     gameInfo->fen = NULL;
165     gameInfo->resultDetails = NULL;
166     gameInfo->timeControl = NULL;
167     gameInfo->extraTags = NULL;
168     gameInfo->whiteRating = -1; /* unknown */
169     gameInfo->blackRating = -1; /* unknown */
170     gameInfo->variant = VariantNormal;
171     gameInfo->outOfBook = NULL;
172     gameInfo->resultDetails = NULL;
173 }
174
175
176 /* Create empty ListGame; returns ListGame or NULL, if out of memory.
177  *
178  * Note, that the ListGame is *not* added to any list
179  */
180 static ListGame *GameListCreate()
181
182 {
183     ListGame *listGame;
184
185     if ((listGame = (ListGame *) ListNodeCreate(sizeof(*listGame)))) {
186         GameListInitGameInfo(&listGame->gameInfo);
187     }
188     return(listGame);
189 }
190
191
192 /* Creates a new game for the gamelist.
193  */
194 static int GameListNewGame(listGamePtr)
195      ListGame **listGamePtr;
196 {
197     if (!(*listGamePtr = (ListGame *) GameListCreate())) {
198         GameListFree(&gameList);
199         return(ENOMEM);
200     }
201     ListAddTail(&gameList, (ListNode *) *listGamePtr);
202     return(0);
203 }
204
205
206 /* Build the list of games in the open file f.
207  * Returns 0 for success or error number.
208  */
209 int GameListBuild(f)
210     FILE *f;
211 {
212     ChessMove cm, lastStart;
213     int gameNumber;
214     ListGame *currentListGame = NULL;
215     int error;
216     int offset;
217     char lastComment[MSG_SIZ];
218
219     GameListFree(&gameList);
220     yynewfile(f);
221     gameNumber = 0;
222
223     lastStart = (ChessMove) 0;
224     yyskipmoves = FALSE;
225     do {
226         yyboardindex = 0;
227         offset = yyoffset();
228         cm = (ChessMove) yylex();
229         switch (cm) {
230           case GNUChessGame:
231             if ((error = GameListNewGame(&currentListGame))) {
232                 rewind(f);
233                 yyskipmoves = FALSE;
234                 return(error);
235             }
236             currentListGame->number = ++gameNumber;
237             currentListGame->offset = offset;
238             if (currentListGame->gameInfo.event != NULL) {
239                 free(currentListGame->gameInfo.event);
240             }
241             currentListGame->gameInfo.event = StrSave(yy_text);
242             lastStart = cm;
243             break;
244           case XBoardGame:
245             lastStart = cm;
246             break;
247           case MoveNumberOne:
248             switch (lastStart) {
249               case GNUChessGame:
250                 break;          /*  ignore  */
251               case PGNTag:
252                 lastStart = cm;
253                 break;          /*  Already started */
254               case (ChessMove) 0:
255               case MoveNumberOne:
256               case XBoardGame:
257                 if ((error = GameListNewGame(&currentListGame))) {
258                     rewind(f);
259                     yyskipmoves = FALSE;
260                     return(error);
261                 }
262                 currentListGame->number = ++gameNumber;
263                 currentListGame->offset = offset;
264                 lastStart = cm;
265                 break;
266               default:
267                 break;          /*  impossible  */
268             }
269             break;
270           case PGNTag:
271             lastStart = cm;
272             if ((error = GameListNewGame(&currentListGame))) {
273                 rewind(f);
274                 yyskipmoves = FALSE;
275                 return(error);
276             }
277             currentListGame->number = ++gameNumber;
278             currentListGame->offset = offset;
279             ParsePGNTag(yy_text, &currentListGame->gameInfo);
280             do {
281                 yyboardindex = 1;
282                 offset = yyoffset();
283                 cm = (ChessMove) yylex();
284                 if (cm == PGNTag) {
285                     ParsePGNTag(yy_text, &currentListGame->gameInfo);
286                 }
287             } while (cm == PGNTag || cm == Comment);
288             break;
289           case NormalMove:
290             /* Allow the first game to start with an unnumbered move */
291             yyskipmoves = TRUE;
292             if (lastStart == (ChessMove) 0) {
293               if ((error = GameListNewGame(&currentListGame))) {
294                 rewind(f);
295                 yyskipmoves = FALSE;
296                 return(error);
297               }
298               currentListGame->number = ++gameNumber;
299               currentListGame->offset = offset;
300               lastStart = MoveNumberOne;
301             }
302             break;
303         case WhiteWins: // [HGM] rescom: save last comment as result details
304         case BlackWins:
305         case GameIsDrawn:
306         case GameUnfinished:
307             if (currentListGame->gameInfo.resultDetails != NULL) {
308                 free(currentListGame->gameInfo.resultDetails);
309             }
310             if(yy_text[0] == '{') { char *p;
311               safeStrCpy(lastComment, yy_text+1, sizeof(lastComment)/sizeof(lastComment[0]));
312               if(p = strchr(lastComment, '}')) *p = 0;
313               currentListGame->gameInfo.resultDetails = StrSave(lastComment);
314             }
315             break;
316           default:
317             break;
318         }
319     }
320     while (cm != (ChessMove) 0);
321
322
323     if (appData.debugMode) {
324         for (currentListGame = (ListGame *) gameList.head;
325              currentListGame->node.succ;
326              currentListGame = (ListGame *) currentListGame->node.succ) {
327
328             fprintf(debugFP, "Parsed game number %d, offset %ld:\n",
329                     currentListGame->number, currentListGame->offset);
330             PrintPGNTags(debugFP, &currentListGame->gameInfo);
331         }
332     }
333
334     rewind(f);
335     yyskipmoves = FALSE;
336     return 0;
337 }
338
339
340 /* Clear an existing GameInfo structure.
341  */
342 void ClearGameInfo(gameInfo)
343     GameInfo *gameInfo;
344 {
345     if (gameInfo->event != NULL) {
346         free(gameInfo->event);
347     }
348     if (gameInfo->site != NULL) {
349         free(gameInfo->site);
350     }
351     if (gameInfo->date != NULL) {
352         free(gameInfo->date);
353     }
354     if (gameInfo->round != NULL) {
355         free(gameInfo->round);
356     }
357     if (gameInfo->white != NULL) {
358         free(gameInfo->white);
359     }
360     if (gameInfo->black != NULL) {
361         free(gameInfo->black);
362     }
363     if (gameInfo->resultDetails != NULL) {
364         free(gameInfo->resultDetails);
365     }
366     if (gameInfo->fen != NULL) {
367         free(gameInfo->fen);
368     }
369     if (gameInfo->timeControl != NULL) {
370         free(gameInfo->timeControl);
371     }
372     if (gameInfo->extraTags != NULL) {
373         free(gameInfo->extraTags);
374     }
375     if (gameInfo->outOfBook != NULL) {
376         free(gameInfo->outOfBook);
377     }
378     GameListInitGameInfo(gameInfo);
379 }
380
381 /* [AS] Replaced by "dynamic" tag selection below */
382 char *
383 GameListLineOld(number, gameInfo)
384      int number;
385      GameInfo *gameInfo;
386 {
387     char *event = (gameInfo->event && strcmp(gameInfo->event, "?") != 0) ?
388                      gameInfo->event : gameInfo->site ? gameInfo->site : "?";
389     char *white = gameInfo->white ? gameInfo->white : "?";
390     char *black = gameInfo->black ? gameInfo->black : "?";
391     char *date = gameInfo->date ? gameInfo->date : "?";
392     int len = 10 + strlen(event) + 2 + strlen(white) + 1 +
393       strlen(black) + 11 + strlen(date) + 1;
394     char *ret = (char *) malloc(len);
395     sprintf(ret, "%d. %s, %s-%s, %s, %s",
396             number, event, white, black, PGNResult(gameInfo->result), date);
397     return ret;
398 }
399
400 #define MAX_FIELD_LEN   80  /* To avoid overflowing the buffer */
401
402 char * GameListLine( int number, GameInfo * gameInfo )
403 {
404     char buffer[2*MSG_SIZ];
405     char * buf = buffer;
406     char * glt = appData.gameListTags;
407
408     buf += sprintf( buffer, "%d.", number );
409
410     while( *glt != '\0' ) {
411         *buf++ = ' ';
412
413         switch( *glt ) {
414         case GLT_EVENT:
415             strncpy( buf, gameInfo->event ? gameInfo->event : "?", MAX_FIELD_LEN );
416             break;
417         case GLT_SITE:
418             strncpy( buf, gameInfo->site ? gameInfo->site : "?", MAX_FIELD_LEN );
419             break;
420         case GLT_DATE:
421             strncpy( buf, gameInfo->date ? gameInfo->date : "?", MAX_FIELD_LEN );
422             break;
423         case GLT_ROUND:
424             strncpy( buf, gameInfo->round ? gameInfo->round : "?", MAX_FIELD_LEN );
425             break;
426         case GLT_PLAYERS:
427             strncpy( buf, gameInfo->white ? gameInfo->white : "?", MAX_FIELD_LEN );
428             buf[ MAX_FIELD_LEN-1 ] = '\0';
429             buf += strlen( buf );
430             *buf++ = '-';
431             strncpy( buf, gameInfo->black ? gameInfo->black : "?", MAX_FIELD_LEN );
432             break;
433         case GLT_RESULT:
434             safeStrCpy( buf, PGNResult(gameInfo->result), 2*MSG_SIZ );
435             break;
436         case GLT_WHITE_ELO:
437             if( gameInfo->whiteRating > 0 )
438               sprintf( buf,  "%d", gameInfo->whiteRating );
439             else
440               safeStrCpy( buf, "?" , 2*MSG_SIZ);
441             break;
442         case GLT_BLACK_ELO:
443             if( gameInfo->blackRating > 0 )
444                 sprintf( buf, "%d", gameInfo->blackRating );
445             else
446               safeStrCpy( buf, "?" , 2*MSG_SIZ);
447             break;
448         case GLT_TIME_CONTROL:
449             strncpy( buf, gameInfo->timeControl ? gameInfo->timeControl : "?", MAX_FIELD_LEN );
450             break;
451         case GLT_VARIANT:
452             break;
453         case GLT_OUT_OF_BOOK:
454             strncpy( buf, gameInfo->outOfBook ? gameInfo->outOfBook : "?", MAX_FIELD_LEN );
455             break;
456         case GLT_RESULT_COMMENT:
457             strncpy( buf, gameInfo->resultDetails ? gameInfo->resultDetails : "res?", MAX_FIELD_LEN );
458             break;
459         default:
460             break;
461         }
462
463         buf[MAX_FIELD_LEN-1] = '\0';
464
465         buf += strlen( buf );
466
467         glt++;
468
469         if( *glt != '\0' ) {
470             *buf++ = ',';
471         }
472     }
473
474     *buf = '\0';
475
476     return strdup( buffer );
477 }
478
479 char * GameListLineFull( int number, GameInfo * gameInfo )
480 {
481     char * event = gameInfo->event ? gameInfo->event : "?";
482     char * site = gameInfo->site ? gameInfo->site : "?";
483     char * white = gameInfo->white ? gameInfo->white : "?";
484     char * black = gameInfo->black ? gameInfo->black : "?";
485     char * round = gameInfo->round ? gameInfo->round : "?";
486     char * date = gameInfo->date ? gameInfo->date : "?";
487     char * oob = gameInfo->outOfBook ? gameInfo->outOfBook : "";
488     char * reason = gameInfo->resultDetails ? gameInfo->resultDetails : "";
489
490     int len = 64 + strlen(event) + strlen(site) + strlen(white) + strlen(black) + strlen(date) + strlen(oob) + strlen(reason);
491
492     char *ret = (char *) malloc(len);
493
494     sprintf(ret, "%d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"",
495         number, event, site, round, white, black, PGNResult(gameInfo->result), reason, date, oob );
496
497     return ret;
498 }
499
500 // --------------------------------------- Game-List options dialog --------------------------------------
501
502 // back-end
503 typedef struct {
504     char id;
505     char * name;
506 } GLT_Item;
507
508 // back-end: translation table tag id-char <-> full tag name
509 static GLT_Item GLT_ItemInfo[] = {
510     { GLT_EVENT,      "Event" },
511     { GLT_SITE,       "Site" },
512     { GLT_DATE,       "Date" },
513     { GLT_ROUND,      "Round" },
514     { GLT_PLAYERS,    "Players" },
515     { GLT_RESULT,     "Result" },
516     { GLT_WHITE_ELO,  "White Rating" },
517     { GLT_BLACK_ELO,  "Black Rating" },
518     { GLT_TIME_CONTROL,"Time Control" },
519     { GLT_VARIANT,    "Variant" },
520     { GLT_OUT_OF_BOOK,PGN_OUT_OF_BOOK },
521     { GLT_RESULT_COMMENT, "Result Comment" }, // [HGM] rescom
522     { 0, 0 }
523 };
524
525 char lpUserGLT[LPUSERGLT_SIZE];
526
527 // back-end: convert the tag id-char to a full tag name
528 char * GLT_FindItem( char id )
529 {
530     char * result = 0;
531
532     GLT_Item * list = GLT_ItemInfo;
533
534     while( list->id != 0 ) {
535         if( list->id == id ) {
536             result = list->name;
537             break;
538         }
539
540         list++;
541     }
542
543     return result;
544 }
545
546 // back-end: build the list of tag names
547 void
548 GLT_TagsToList( char * tags )
549 {
550     char * pc = tags;
551
552     GLT_ClearList();
553
554     while( *pc ) {
555         GLT_AddToList( GLT_FindItem(*pc) );
556         pc++;
557     }
558
559     GLT_AddToList( "     --- Hidden tags ---     " );
560
561     pc = GLT_ALL_TAGS;
562
563     while( *pc ) {
564         if( strchr( tags, *pc ) == 0 ) {
565             GLT_AddToList( GLT_FindItem(*pc) );
566         }
567         pc++;
568     }
569
570     GLT_DeSelectList();
571 }
572
573 // back-end: retrieve item from dialog and translate to id-char
574 char
575 GLT_ListItemToTag( int index )
576 {
577     char result = '\0';
578     char name[MSG_SIZ];
579
580     GLT_Item * list = GLT_ItemInfo;
581
582     if( GLT_GetFromList(index, name) ) {
583         while( list->id != 0 ) {
584             if( strcmp( list->name, name ) == 0 ) {
585                 result = list->id;
586                 break;
587             }
588
589             list++;
590         }
591     }
592
593     return result;
594 }
595
596 // back-end: add items id-chars one-by-one to temp tags string
597 void
598 GLT_ParseList()
599 {
600     char * pc = lpUserGLT;
601     int idx = 0;
602     char id;
603
604     do {
605         id = GLT_ListItemToTag( idx );
606         *pc++ = id;
607         idx++;
608     } while( id != '\0' );
609 }
610