File: protocol.c

package info (click to toggle)
mah-jong 1.8-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 2,384 kB
  • ctags: 2,186
  • sloc: ansic: 26,312; perl: 393; makefile: 272; sh: 122
file content (476 lines) | stat: -rw-r--r-- 13,841 bytes parent folder | download | duplicates (2)
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
/* $Header: /home/jcb/newmj/RCS/protocol.c,v 11.7 2004/05/03 06:57:35 jcb Exp $
 * protocol.c 
 * implements the over-the-wire protocol for messages
 */
/****************** COPYRIGHT STATEMENT **********************
 * This file is Copyright (c) 2000 by J. C. Bradfield.       *
 * Distribution and use is governed by the LICENCE file that *
 * accompanies this file.                                    *
 * The moral rights of the author are asserted.              *
 *                                                           *
 ***************** DISCLAIMER OF WARRANTY ********************
 * This code is not warranted fit for any purpose. See the   *
 * LICENCE file for further information.                     *
 *                                                           *
 *************************************************************/

static const char rcs_id[] = "$Header: /home/jcb/newmj/RCS/protocol.c,v 11.7 2004/05/03 06:57:35 jcb Exp $";

#include "protocol.h"
#include "tiles.h"
#include "sysdep.h"

/* See protocol.h for documentation */
int protocol_version = PROTOCOL_VERSION;

/* The protocol is, for all the usual reasons, text-based,
   and human readable. (So all you need to play is telnet...)
   A message usually occupies a single line, terminated by CRLF or LF.
   To transmit messages containing newlines, the internal newlines
   are replaced by backslash-newline pairs; thus a telnet line ending
   in a backslash indicates newline followed by the next telnet line.
   Integers are represented in decimal.
   The message type is given in text, obtained by removing the CMsg
   or PMsg prefix from the type name.
   Tiles are represented as a 2-character code, as follows:
   1C ... 9C   characters
   1D ... 9D   circles (dots)
   1B ... 9B   bamboos
   EW ... NW   winds
   RD, WD, GD  dragons
   1S ... 4S   seasons
   1F ... 4F   flowers
   --          blank
   Winds are represented as single letters.
   The code for representing tiles in this way comes from the tiles 
   module, as it has uses outside this protocol.
   ChowPositions are represented as the words Lower, Middle, Upper,AnyPos.
   Strings are deemed to extend to end of line. This is safe because
   the current protocol has at most one string field per message, which
   is always final. There is unlikely to be a reason to change this
   assumption.
*/

/* Takes a TileWind and returns the corresponding letter */
static char windletter(TileWind w) {
  switch ( w ) {
  case EastWind: return 'E';
  case SouthWind: return 'S';
  case WestWind: return 'W';
  case NorthWind: return 'N';
  default: return '?';
  }
}

/* given a wind letter, return the wind */
static TileWind letterwind(char c) {
  if ( c == 'E' ) return EastWind;
  if ( c == 'S' ) return SouthWind;
  if ( c == 'W' ) return WestWind;
  if ( c == 'N' ) return NorthWind;
  return UnknownWind;
}
				     
/* given a chowposition string, return the chowposition */
/* it is an undocumented :-) fact that this function will
   accept l,m,u,a for Lower, Upper, Middle, AnyPos */
static ChowPosition string_cpos(char *s) {
  if ( strcmp(s,"Lower") == 0 ) return Lower;
  if ( strcmp(s,"l") == 0 ) return Lower;
  if ( strcmp(s,"Middle") == 0 ) return Middle;
  if ( strcmp(s,"m") == 0 ) return Middle;
  if ( strcmp(s,"Upper") == 0 ) return Upper;
  if ( strcmp(s,"u") == 0 ) return Upper;
  if ( strcmp(s,"AnyPos") == 0 ) return AnyPos;
  if ( strcmp(s,"a") == 0 ) return AnyPos;
  return -1;
}


/* return a string code for a chowposition */
static char *cpos_string(ChowPosition r) {
  switch ( r ) {
  case Lower: return "Lower";
  case Middle: return "Middle";
  case Upper: return "Upper";
  case AnyPos: return "AnyPos";
  }
  return "error";
}

/* functions to print and scan a GameOptionEntry; at the end */

static char *protocol_print_GameOptionEntry(const GameOptionEntry *t);
/* This function uses static storage; it's not reentrant */
static GameOptionEntry* protocol_scan_GameOptionEntry(const char *s);

/* This function takes a pointer to a controller message,
   and returns a string (including terminating CRLF) encoding it.
   The returned string is in static storage, and will be overwritten
   the next time this function is called.
*/

char *encode_cmsg(CMsgMsg *msg) {
  static char *buf = NULL;
  static size_t buf_size = 0;
  int badfield; /* used by internal code */

  switch ( msg->type ) {
    /* The body of this switch statement is automatically generated
       from protocol.h by proto-enc-cmsg.pl; */
#   include "enc_cmsg.c"
  default:
    warn("unknown message type %d\n",msg->type);
    return (char *)0;
  }
  return buf;
}

/* This function takes a string, which is expected to be a complete
   line (including terminators, although their absence is ignored).
   It returns a pointer to a message structure.
   Both the message structure and any strings it contains are malloc'd.
   The argument string will be destroyed by this function.
*/
    
CMsgMsg *decode_cmsg(char *arg) {
  char *s;
  char *type;
  int n;
  int i;
  int an_int;
  char a_char;
  char little_string[32];
  GameOptionEntry *goe;

  /* first eliminate the white space from the end of the string */
  i=strlen(arg) - 1;
  while ( i >= 0 && isspace(arg[i]) ) arg[i--] = '\000' ;
  /* first get the type of the message, which is the first word */
  /* SPECIAL hack: the comment message has a non alpha num type */
  type = arg;
  i = 0;
  while ( isalnum(arg[i]) || (arg[i] == '#') ) i++;
  arg[i++] = '\000' ; /* if this wasn't white space, summat's wrong anyway */
  type = arg;
  while ( isspace(arg[i]) ) i++; /* may as well advance to next item */
  s = arg+i; /* s is what the rest of the code uses */
  /* The rest of this function body is generated automatically from
     protocol.h by proto-dec-cmsg.pl */
# include "dec_cmsg.c"
  /* if we come out of this, it's an error because we haven't found
     the keyword */
  warn("decode_cmsg: unknown key in  %s",arg);
  return NULL;
}

/* The next two functions do the same for pmsgs */

/* This function takes a pointer to a player message,
   and returns a string (including terminating CRLF) encoding it.
   The returned string is in static storage, and will be overwritten
   the next time this function is called.
*/

char *encode_pmsg(PMsgMsg *msg) {
  static char *buf = NULL;
  static size_t buf_size = 0;
  int badfield; /* used by internal code */

  switch ( msg->type ) {
    /* The body of this switch statement is automatically generated
       from protocol.h by proto-enc-pmsg.pl; */
#   include "enc_pmsg.c"
  default:
    warn("unknown message type\n");
    return (char *)0;
  }
  return buf;
}

/* This function takes a string, which is expected to be a complete
   line (including terminators, although their absence is ignored).
   It returns a pointer to a message structure.
   Both the message structure and any strings it contains are malloc'd.
   The argument string will be destroyed by this function.
*/
    
PMsgMsg *decode_pmsg(char *arg) {
  char *s;
  char *type;
  int n;
  int i;
  int an_int;
  char little_string[32];

  /* first eliminate the white space from the end of the string */
  i=strlen(arg)-1;
  while ( i >= 0 && isspace(arg[i]) ) arg[i--] = '\000' ;
  /* first get the type of the message, which is the first word */
  type = arg;
  i = 0;
  while ( isalnum(arg[i]) ) i++;
  arg[i++] = '\000' ; /* if this wasn't white space, summat's wrong anyway */
  type = arg;
  while ( isspace(arg[i]) ) i++; /* may as well advance to next item */
  s = arg+i; /* s is what the rest of the code uses */
  /* The rest of this function body is generated automatically from
     protocol.h by proto-dec-pmsg.pl */
# include "dec_pmsg.c"
  /* if we come out of this, it's an error because we haven't found
     the keyword */
  warn("decode_pmsg: unknown key in  %s",arg);
  return NULL;
}

/* the size functions */
#include "cmsg_size.c"
#include "pmsg_size.c"

/* enum functions */
#include "protocol-enums.c"

/* functions for GameOptionEntry */
static GameOptionEntry *protocol_scan_GameOptionEntry(const char *s) {
  const char *sp;
  char tmp[100];
  static GameOptionEntry goe;
  int n;
  sp = s;
  
  if ( sscanf(sp,"%15s%n",goe.name,&n) == 0 ) {
    warn("protocol error");
    return NULL;
  }
  sp += n;

  goe.option = protocol_scan_GameOption(goe.name);
  if ( goe.option == (GameOption)(-1) ) goe.option = GOUnknown;

  if ( sscanf(sp,"%15s%n",tmp,&n) == 0 )  {
    warn("protocol error");
    return NULL;
  }
  sp += n;

  goe.type = protocol_scan_GameOptionType(tmp);
  if ( goe.type == (GameOptionType)(-1) ) {
    warn("unknown game option type");
    return NULL;
  }

  if ( sscanf(sp,"%d%n",&goe.protversion,&n) == 0 )  {
    warn("protocol error");
    return NULL;
  }
  sp += n;

  if ( sscanf(sp,"%d%n",&goe.enabled,&n) == 0 )  {
    warn("protocol error");
    return NULL;
  }
  sp += n;

  switch ( goe.type ) {
  case GOTBool:
    if ( sscanf(sp,"%d%n",&goe.value.optbool,&n) == 0 )  {
      warn("protocol error");
      return NULL;
    }
    if ( goe.value.optbool != 0 && goe.value.optbool != 1 ) {
      warn("bad value for boolean game option");
      return NULL;
    }
    sp += n;
    break;
  case GOTNat:
  case GOTInt:
  case GOTScore:
    if ( sscanf(sp,"%d%n",&goe.value.optint,&n) == 0 )  {
      warn("protocol error");
      return NULL;
    }
    sp += n;
    break;
  case GOTString:
    if ( sscanf(sp,"%127s%n",goe.value.optstring,&n) == 0 )  {
      warn("protocol error");
      return NULL;
    }
    sp += n;
    break;
  }
  if ( sscanf(sp," %127[^\r\n]",goe.desc) == 0 ) {
    warn("protocol error");
    return NULL;
  }
  goe.userdata = NULL;
  return &goe;
}

static char *protocol_print_GameOptionEntry(const GameOptionEntry *goe) {
  static char tmp[2*sizeof(GameOptionEntry)];
  sprintf(tmp,"%s %s %d %d ",
	  goe->name,
	  protocol_print_GameOptionType(goe->type),
	  goe->protversion,
	  goe->enabled);
  switch (goe->type) {
  case GOTBool:
    sprintf(tmp+strlen(tmp),"%d ",goe->value.optbool);
    break;
  case GOTNat:
  case GOTInt:
  case GOTScore:
    sprintf(tmp+strlen(tmp),"%d ",goe->value.optint);
    break;
  case GOTString:
    sprintf(tmp+strlen(tmp),"%s ",goe->value.optstring);
    break;
  }
  strcat(tmp,goe->desc);
  return tmp;
}

  
/* basic_expand_protocol_text: do the expansion of protocol text
   according to the rules set out in protocol.h. We don't recognize
   any codes or types. bloody emacs ' */
int basic_expand_protocol_text(char *dest,const char *src,int n)
{
  int destlen = 0; /* chars placed in destination string */
  const char *argp[10]; /* pointers to start of argument texts (excluding {);
                     arg 0 is replacement text */
  const char *curarg = NULL;
  int i,j;
  int numargs = 0;
  int state= 0; 
  int done;
  
  /* sanity check */
  if ( !dest || !n ) {
    warn("basic_expand_protocol_text: strange args");
    return -1;
  }

  /* null source expands to empty string */
  if ( !src ) {
    dest[0] = 0;
    return 0;
  }

  /* initialization */
  for ( i=0 ; i<10 ; argp[i++] = NULL );
  j = 0; /* current arg */

  done = 0;
  while ( !done ) {
    switch ( state ) {
    case 0: /* outside macro */
      if ( ! *src ) {  done=1 ; break ; }
      if ( *src == '\\' ) {
	src++;
	if ( *src ) dest[destlen++] = *(src++);
      } else if ( *src == '{' ) {
	src++;
	state = 1; /* reading macro defn */
	/* skip the code */
	while ( *src 
		&& (*src != '#') && (*src != ':') && (*src != '}') ) src++;
	numargs = 0;
      }
      else { dest[destlen++] = *(src++); }
      break;
    case 1: /* reading macro definition */
      if ( ! *src ) { done=1; break; }
      if ( *src == '#' ) {
	numargs++;
	src++;
	/* skip the type */
	while ( *src 
		&& (*src != '#') && (*src != ':') && (*src != '}') ) src++;
      } else if ( *src == ':' ) {
	state = 2;
	src++;
	argp[0] = src;
      } else if ( *src == '}' ) {
	state = 2;
	/* and read it again */
      }
      break;
    case 2: /* reading replacement text */
      /* do nothing; we've stored a pointer to it */
      if ( !*src ) { done=1; break;}
      if ( *src == '\\' ) {
	src++;
	if ( *src ) src++;
      } else if ( *src == '}' ) {
	src++;
	/* are there any arguments? */
	if ( numargs > 0 ) {
	  state = 3; /* reading argument texts */
	  j = 1; /* current arg */
	} else {
	  state = 4; /* expanding macro */
	}
      } else src++;
      break;
    case 3: /* reading argument texts */
      if ( !*src ) { done=1; break;}
      if ( *src == '{' ) {
	src++;
	argp[j] = src;
      } else if ( *src == '}' ) {
	src++;
	if ( j == numargs ) {
	  state = 4; /* expand the macro */
	} else j++;
      } else src++;
      break;
    case 4: /* expand the macro */
      /* now we're looking at argp[0] */
      if ( ! *argp[0] ) { state = 0; }
      else if ( *argp[0] == '\\' ) {
	argp[0]++;
	if ( *argp[0] ) dest[destlen++] = *argp[0];
	argp[0]++;
      } else if ( *argp[0] == '}' ) {
	state = 0;
      } else if ( *argp[0] == '#' ) {
	/* expand the argument */
	argp[0]++;
	j = *argp[0] - '0';
	if ( j >= 1 && j <= 9 ) {
	  argp[0]++;
	  curarg = argp[j];
	  state = 5;
	}
      } else dest[destlen++] = *(argp[0]++);
      break;
    case 5: /* copying an argument */
      if ( ! *curarg ) { state = 4; }
      else if ( *curarg == '\\' ) {
	curarg++;
	if ( *curarg ) { dest[destlen++] = *(curarg++); }
      } else if ( *curarg == '}' ) {
	state = 4; 
      } else dest[destlen++] = *(curarg++);
      break;
    }
    if ( destlen >= n - 1 ) { break ; }
  }
  if ( destlen > n-1 ) {
    dest[n-1] = '\000';
    return -1;
  }
  dest[destlen] = '\000';
  if ( state > 0 ) {
    warn("basic_expand_protocol_text: some error in expansion");
    return 0;}
  return 1;
}

int expand_protocol_text(char *dest,const char *src,int n)
{
  return basic_expand_protocol_text(dest,src,n);
}