summaryrefslogtreecommitdiff
path: root/comm/OLD/TextStream.cc
blob: 7f1764f36f74e50d4982430c90f1f054a02bb223 (plain)
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
/*
 *	The Unix Channel
 *
 *	by Michel Beaudouin-Lafon
 *
 *	Copyright 1990-1993
 *	Laboratoire de Recherche en Informatique (LRI)
 *
 *	Text streams
 *
 *	$Id$
 *	$CurLog$
 */

#include "TextStream.h"
#include "Multiplexer.h"
#include "error.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>

extern int windex (const char* list, const char* word);

#ifdef __osf__
extern "C" {
	int socket (int, int, int);
}
#endif

/*?
Construct a \typ{UchTextStream}.
?*/
UchTextStream :: UchTextStream (UchAddress* bindTo, UchAddress* connectTo)
: UchBufStream (bindTo, connectTo)
{
}

/*?
Protected destructor.
\fun{Close} must be used instead to properly close down a \typ{UchTextStream}
?*/
UchTextStream :: ~UchTextStream ()
{
}

/*?
This virtual function is called by \fun{HandleRead} when an end of file
is read (the argument is then \var{true}), or when an error occured while
reading (the argument is then \var{false}).
The default action is to call \fun{Close}.
?*/
void
UchTextStream :: Closing (bool)
{
	Close ();
}

/*?
Read and decode input. When a complete line (terminated either by
a newline or cr-newline) is in the input buffer, it is parsed.
If parsing is successful, \fun{Execute} is called with the line as argument.
If \fun{Execute} returns \var{isCmdUnknown}, \fun{TryPredefined} is called
to decode the predefined commands.
Finally, \fun{ProcessCmdResult} is called and the line is flushed from
the input buffer.
Note that since the parsed line passed to \fun{Execute} contains pointers
to the input buffer, \fun{Execute} {\em must not} keep copies of these
pointers, but copy the contents instead.
?*/
void
UchTextStream :: HandleRead ()
{
	if (ReadInput () <= 0)
		return;

	Process (InBuffer);
}

void
UchTextStream :: Process (UchMsgBuffer& buf)
{
	// scan buffer for complete commands
	char* start = (char*) buf.Buffer ();
	char* stop = start + buf.BufLength ();
	for (char* p = start; p < stop; p++) {
		if (*p == '\n') {
			*p = '\0';
			// check cr-nl sequence
			if (p > start && *(p-1) == '\r')
				*(p-1) = '\0';
			// parse line, lookup command
			UchTextLine line;
			cmd_res res = isCmdUnknown;
			if (line.Parse (start)) {
				if (line.NumWords () == 0)
					res = isCmdOk;
				else
					res = Execute (line);
				if (res == isCmdUnknown)
					res = TryPredefined (line);
			} else
				res = isCmdSyntax;
			ProcessCmdResult (res, line);
			// reset for scanning rest of buffer
			start = p+1;
			buf.Flush ((byte*) start);
		}
	}
}

/*?
Process the result \var{res} of the execution of the line \var{line}.
If \var{res} is one of \var{isCmdSyntax}, \var{isCmdUnknown}, \var{isCmdError},
a warning message is issued.
If \var{res} is \var{isCmdClose} (resp. \var{isCmdQuit}), the virtual function
\fun{Close} (resp. \fun{Quit}) is called.
If \var{res} is \var{isCmdTerminate} (resp. \var{isCmdAbort}),
the global function \fun{MpxTerminate} (resp. \fun{MpxAbort}) is called.
If \var{res} is \var{isCmdExit}, \fun{exit(1)} is called.
Finally, if \var{res} is \var{isCmdOk}, nothing happens.
?*/
void
UchTextStream :: ProcessCmdResult (cmd_res res, const UchTextLine& line)
{
	const char* msg = 0;
	switch (res) {
		case isCmdSyntax:
			msg = "syntax error in <%s>";
			break;
		case isCmdUnknown:
			msg = "unknown command: <%s>";
			break;
		case isCmdOk:
			return;
		case isCmdError:
			msg = "error while executing command <%s>";
			break;
		case isCmdClose:
			// like eof (but smarter for the session)
			Close ();
			return;
		case isCmdQuit:
			//quit application
			Quit ();
			return;
		case isCmdTerminate:
			// terminate the multiplexer
			if (Mpx)
				Mpx->Close ();
			return;
		case isCmdAbort:
			// abort the multiplexer
			if (Mpx)
				Mpx->Abort ();
			return;
		case isCmdExit:
			exit (1);
	}
	if (msg) {
		char buf [64];
		line.Unparse (buf, sizeof (buf));
		fprintf (stderr, "UchTextStream::ProcessCmdResult\n", msg, buf);
	}
}	

/*?
If \var{line} is one of the words
\com{Close}, \com{Quit}, \com{Terminate}, \com{Abort}, \com{Exit},
the corresponding code is returned (\var{isCmdClose}, etc.),
otherwise, \var{isCmdUnknown} is returned.
?*/
UchTextStream::cmd_res
UchTextStream :: TryPredefined (const UchTextLine& line)
{
	const char* cname = line [0];
	
	if (line.NumWords () != 1)
		return isCmdUnknown;
	switch (windex (":Close:Quit:Terminate:Abort:Exit:", cname)) {
		case 1: return isCmdClose;
		case 2: return isCmdQuit;
		case 3: return isCmdTerminate;
		case 4: return isCmdAbort;
		case 5: return isCmdExit;
	}
	return isCmdUnknown;
}

void
UchTextStream :: Send (const char* l, bool flush)
{
	OutBuffer.Append (l, false);
	if (flush || Sync || OutBuffer.BufLength () >= OutSize)
		Flush ();
}

void
UchTextStream :: Send (const UchTextLine& l, bool flush)
{
	l.Unparse (&OutBuffer);
	OutBuffer.WriteChar ('\n');
	if (flush || Sync || OutBuffer.BufLength () >= OutSize)
		Flush ();
}

/*?
By default, it writes the output buffer on the stream.
?*/
void
UchTextStream :: Flush ()
{
	Write (OutBuffer);
}

/*?
This virtual function is called by \fun{ProcessCmdResult} when a \com{close}
command has been received.
It can be called directly by the application to close down the connection
(remember that the destructor is private and cannot be called directly).
By default it calls \fun{MpxRemoveChannel} to unregister this stream from the
multiplexer.
This will trigger deletion of the stream is the multiplexer holds the last
smart pointer to it.
Derived classes can redefine this function, but the redefinition
should call the default implementation.
?*/
void
UchTextStream :: Close ()
{
	Remove ();
}

/*?
This virtual function is called by \fun{ProcessCmdResult} when a \com{quit}
command has been received.
By default is calls \fun{MpxTerminate}.
Derived classes can redefine this function if they want to terminate more
gracefully.
?*/
void
UchTextStream :: Quit ()
{
	Mpx->Close ();
}


void
UchTextStream :: WriteLong (lword l)
{
	
	char c [64];
	sprintf (c, "%d", l);
	OutBuffer << c;
}

void
UchTextStream :: WriteShort (sword s)
{
	char c [64];
	sprintf (c, "%d", s);
	OutBuffer << c;
}

void
UchTextStream :: WriteByte (byte b)
{
	char c [8];
	sprintf (c, "%d", b);
	OutBuffer << c;
}

void
UchTextStream :: WriteChar (char c)
{
	OutBuffer << c;
}

void
UchTextStream :: WriteString (const char* s)
{
	OutBuffer << s;
}



bool
UchTextStream :: ReadLong (lword& l)
{
	char c [64];
	InBuffer.ReadString (c, 64);
	l = (lword) atol (c);
	return true;
}

bool
UchTextStream :: ReadShort (sword& s)
{
	char c [64];
	InBuffer.ReadString (c, 64);
	s = (sword) atoi (c);
	return true;
}

bool
UchTextStream :: ReadByte (byte& b)
{
	char c [8];
	InBuffer.ReadString (c, 8);
	b = (byte) atoi (c);
	return true;
}

bool
UchTextStream :: ReadChar (char& c)
{
	return InBuffer.ReadChar (c);
}

int
UchTextStream :: ReadString (char* s, int n)
{
	return InBuffer.ReadString (s, n);
}

int
UchTextStream :: ReadString (CcuString& s)
{
	return InBuffer.ReadString (s);
}



// list is a set of words
// the separator must be the first and last char of the string:
//	e.g.  :yes:no:   /foo/bar/toto/
// word is a word to be looked up in the list.
// we use the same kind of comparison as in cmpname, provided that the words
// in the list are capitalized.
// windex returns 0 if the word was not found, otherwise its index in the list.
int
windex (const char* list, const char* word)
{
	if (! list || ! word)
		return 0;
	char sep = *list;
	if (! sep)
		return 0;
	register const char* p;
	register const char* w = word;
	int ind = 1;
	for (p = list+1; *p; p++) {
		if (w) {	// so far the word matches
			if (!*w && *p == sep)	// found !
				return ind;
			if (*w == *p)		// still ok
				w++;
			else if (isupper (*p)) {
				if (*w == '-' || *w == '_')
					w++;
				if (*p == *w || tolower (*p) == *w)
					w++;	
				else
					w = 0;
			} else			// not this item
				w = 0;
		} else {
			if (*p == sep) {	// start new item
				ind++;
				w = word;
			}
		}
	}
	return 0;
}

// compare two names
// an uppercase letter can match the same uppercase letter,
// or an optional hyphen or underscore followed by the lowercase letter.
// if the name starts with an uppercase, it matches the lowercase
//	FooBar == foo-bar, foo_bar, foobar
// returns like strcmp
int
cmpname (register const char* s1, register const char* s2)
{
	for (; *s1 && *s2; s1++, s2++) {
		if (*s1 == *s2)
			continue;
		if (isupper (*s1)) {
			if (*s2 == '-' || *s2 == '_')
				s2++;
			if (*s1 == *s2 || tolower (*s1) == *s2)
				continue;
			else
				break;
		} else if (isupper (*s2)) {
			if (*s1 == '-' || *s1 == '_')
				s1++;
			if (*s2 == *s1 || tolower (*s2) == *s1)
				continue;
			else
				break;
		} else
			break;
	}
	
	if (*s1 == '\0' && *s2 == '\0')
		return 0;
	if (*s1 == '\0')
		return -1;
	if (*s2 == '\0')
		return 1;
	if (tolower (*s1) < tolower (*s2))
		return -1;
	return 1;	
}

// sprintf a message (up to 5 args) and return the formatted string
// the address of a static string is returned
const char*
stringf (const char* fmt, const void* a1, const void* a2, const void* a3, const void* a4, const void* a5)
{
	static char msg [1024];
	sprintf (msg, fmt, a1, a2, a3, a4, a5);
	return msg;
}


void
UchTextWord :: SetVal (const char* val)
{
	// if Sval is null, then it's an integer, whose value is in Ival
	// if Sval is non null, then it's a string, whose value is in Sval
	Ival = atoi (val);
	if (Ival == 0 && strcmp (val, "0") != 0) {
		Sval = val;	// word is a string: atoi returned 0 and val is not "0"
	} else if (strlen (val) < 10) {
		Sval = 0;	// word is an integer
	} else {
		Sval = val;
		Ival = 0;
	}
}

const char*
UchTextWord :: GetQuotes () const
{
	if (! Sval)
		return "";	/* no quotes */
	if (! *Sval)
		return "\'\'";	/* empty string */
	if (strchr (Sval, ' ') == 0)
		return "";	/* no quotes */
	if (strchr (Sval, '\'') == 0)
		return "\'\'";	/* 'hello' */
	if (strchr (Sval, '\"') == 0)
		return "\"\"";	/* "hello" */
	return 0;		/* cannot quote */
}


void
UchTextLine :: NewWord (const char* s, int i)
{
	if (Num >= Max) {
		if (Max == 0) {
			Max = 16;
			Words = new UchTextWord [Max];
		} else {
			UchTextWord*	old = Words;
			Words = new UchTextWord [Max *= 2];
			UchTextWord* po = old;
			UchTextWord* pn = Words;
			for (int i = 0; i < Num; i++)
				*pn++ = *po++;
			delete [] old;
		}
	}
	if (s)
		Words [Num++].SetVal (s);
	else
		Words [Num++].SetVal (i);
}

UchTextLine :: UchTextLine ()
: Num (0),
  Max (0),
  Words (0)
{
}

UchTextLine :: ~UchTextLine ()
{
	if (Words)
		delete [] Words;
}

void
UchTextLine :: AddTrailer (const UchTextLine& line, int first)
{
	for (; first < line.Num; first++) {
		UchTextWord& word = line [first];
		NewWord (word, word);
	}
}

bool
UchTextLine :: Parse (char* line)
{
	enum WHERE { IN_SPACE, IN_WORD, IN_QUOTE };
	char quote = '\0';
	register char*	s = line;
	register char*	word = line;
	register WHERE	where = IN_SPACE;
	
	// split a line into words
	// a word is a sequence of non blank characters,
	// or a quoted string (' or ").
	// '(', ')' and ',' are also ignored to allow for function like notation
	for (; *s; s++) {
		switch (where) {
		case IN_WORD:
			if (strchr (" \t(),", *s)) {
				*s = '\0';
				where = IN_SPACE;
				AddWord (word);
			}
			break;
		case IN_QUOTE:
			if (*s == quote) {
				*s = '\0';
				where = IN_SPACE;
				AddWord (word);
			}
			break;
		case IN_SPACE:
			if (*s == '\'' || *s == '\"') {
				quote = *s;
				*s = '\0';
				where = IN_QUOTE;
				word = s+1;
			} else
			if (strchr (" \t(),", *s)) {
				*s = '\0';
			} else {
				where = IN_WORD;
				word = s;
			}
			break;
		}
	}
	if (where != IN_SPACE)
		AddWord (word);
	if (where == IN_QUOTE)
		return false;
	return true;
}

// decompile line into buffer
// if the line does not fit in the buffer, it ends with '...'
// the return value is dest, or a pointer to a static string "..."
// if dest or len is 0.
char*
UchTextLine :: Unparse (char* dest, int len) const
{
	UchTextWord*	pa = Words;
	char*	p = dest;
	char*	lim = dest + len -1;
	
	if (! dest || ! len)
		return "...";
	
	for (int i = 0; i < Num; i++, pa++) {
		// convert arg to string
		const char* sa;
		const char* quotes = "";
		if (pa->IsInt ()) {
			char num [32];
			sprintf (num, "%d", int (*pa));
			sa = num;
		} else {
			sa = *pa;
			quotes = pa->GetQuotes ();
			if (! quotes) {
				fprintf (stderr, "UchTextLine::Unparse, cannot quote word\n");
				quotes = "";
				sa = "(unquotable)";
			}
		}
		// try to append
		if (p + strlen (sa) + strlen (quotes) < lim) {
			if (*quotes)
				*p++ = quotes [0];
			strcpy (p, sa);
			p += strlen (p);
			if (*quotes)
				*p++ = quotes [1];
		} else {
			if (*quotes)
				*p++ = quotes [0];
			strncpy (p, sa, (lim - p) - 3);
			strcpy (lim -3, "...");
			p = lim;
			break;
		}
		// separator with next one
		if (i < Num -1 && p < lim)
			*p++ = ' ';
	}
	*p = '\0';
	return dest;
}

// unparse the line in a buffer.
// the unparsed string is _not_ terminated by a null
// the return value is a pointer to the beginning of the string in the buffer
char*
UchTextLine :: Unparse (UchMsgBuffer* buf) const
{
	UchTextWord*	pa = Words;
	char*	start = (char*) buf->Buffer ();
	
	for (int i = 0; i < Num; i++, pa++) {
		// convert arg to string and append it
		const char* sa;
		const char* quotes = "";
		if (pa->IsInt ()) {
			char num [32];
			sprintf (num, "%d", int (*pa));
			sa = num;
		} else {
			sa = *pa;
			quotes = pa->GetQuotes ();
			if (! quotes) {
				fprintf (stderr, "UchTextLine::Unparse, cannot quote word <%s>\n", sa);
				quotes = "";
				sa = "(unquotable)";
			}
		}
		if (*quotes)
			buf->WriteChar (quotes [0]);
		buf->Append (sa, false /*no newline*/);
		if (*quotes)
			buf->WriteChar (quotes [1]);
		// separator with next one
		if (i < Num -1)
			buf->WriteChar (' ');
	}
	return start;
}

bool
UchTextLine :: Match (const char* cmdname, const char* profile) const
{
	if (Num <= 0)
		return false;	// no word on line
	const char* myname = Words [0];
	if (! myname || cmpname (myname, cmdname) != 0)
		return false;	// wrong command name
	
	// check the profile, if it is non null.
	// each letter in the profile corresponds to one argument:
	// 'i' for integer, 's' for string, 'b' for bool.
	// the value for a boolean can be an integer (0=false, otherwise true)
	// or a string: yes, y, true, t, on, no, n, false, f, off
	// if the last character of the profile is '+', then the extra arguments
	// are not checked.
	// a null profile is identical to the profile "+".
	// an empty profile ("") describes a command with no argument.
	// *** we'll probably add features for repeated arguments,
	// *** enums (mapping strings to ints), etc.
	if (! profile)
		return true;
	const char* p = profile;
	for (int i = 1; i < Num; i++) {
		switch (*p) {
			case 'i':
				if (! Words [i].IsInt ())
					return false;
				break;
			case 's':
				if (! Words [i].IsString ())
					return false;
				break;
			case 'b':
				{
				if (Words [i].IsInt ())
					break;
				const char* sval = Words [i];
				if (windex (":Yes:Y:True:T:On:", sval)) {
					Words[i].SetVal (1);
					break;
				} else if (windex (":No:N:False:F:Off:", sval)) {
					Words[i].SetVal (0);
					break;
				}
				return false;
				}
			case '+':
				if (*(p+1))	// not at end of profile
					fprintf (stderr, "UchTextLine::Match, invalid command profile: <%s>\n", profile);
				return true;
			case '\0':
				// profile shorter than arg list
				return false;
			default:
				fprintf (stderr, "UchTextLine::Match, invalid command profile: <%s>\n", profile);

				return false;
		}
		p++;
	}
	if (*p)
		return false;	// arg list shorter than profile
	return true;
}

// return -1 if word is not in the line, otherwise return its index
int
UchTextLine :: Index (const char* word) const
{
	UchTextWord*	w = Words;
	int	i = 0;
	
	for (; i < Num; i++, w++)
		if (w->IsString () && strcmp (*w, word) == 0)
			return i;
	return -1;
}

// return -1 if value is not in the line, otherwise return its index
int
UchTextLine :: Index (int value) const
{
	UchTextWord*	w = Words;
	int	i = 0;
	
	for (; i < Num; i++, w++)
		if (w->IsInt () && value == int (*w))
			return i;
	return -1;
}