summaryrefslogtreecommitdiff
path: root/comm/MsgStream.cc
blob: 47a2a74372405e651579c7bcfa5e4d4c862ddf61 (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
/*
 *	The Unix Channel
 *
 *	by Michel Beaudouin-Lafon
 *
 *	Copyright 1990-1997
 *	Laboratoire de Recherche en Informatique (LRI)
 *
 *	Message streams
 *
 *	$Id$
 *	$CurLog$
 */

#include "MsgStream.h"
#include "Message.h"
#include "error.h"


/*?
These constructors are similar to those of class \typ{UchSocket}.
?*/
UchBufStream :: UchBufStream (UchAddress* bindTo, UchAddress* connectTo)
: UchStream (bindTo, connectTo),
  InBuffer (),
  OutBuffer (),
  OutSize (128),
  Sync (false)
{
}

// *** this copy constructor might be automatically generated
/*?nodoc?*/
UchBufStream :: UchBufStream (const UchBufStream& ms)
: UchStream (ms),
  InBuffer (),
  OutBuffer (),
  OutSize (ms.OutSize),
  Sync (ms.Sync)
{
}

/*?nodoc?*/
UchBufStream :: ~UchBufStream ()
{
	Flush ();
	InBuffer.Clear ();
	OutBuffer.Clear ();
}

/*?nextdoc?*/
void
UchBufStream :: InputBuffer (int min, int grow, int max)
{
	InBuffer.SetSizes (min, grow, max);
}

/*?
Set the input and output buffer sizes.
Default sizes are used if these functions are not called.
?*/
void
UchBufStream :: OutputBuffer (int min, int grow, int max)
{
	OutBuffer.SetSizes (min, grow, max);
	OutSize = max;
}

/*?
Flush the output buffer.
This function is called automatically when the buffer exceeds its flush size,
or after each message when this stream is in synchronous mode.
It is also called from \fun{Ask} to wait for the answer.
?*/
void
UchBufStream :: Flush ()
{
	if (OutBuffer.BufLength () == 0)
		return;
	int n = Write (OutBuffer);
	OutBuffer.Flush (n);
}

/*?nodoc?*/
void
UchBufStream :: HandleWrite ()
{
	Flush ();
}


// read stream into input buffer
// delete the stream when an eof is received
// return the number of bytes read
//
/*?hidden?*/
int
UchBufStream :: ReadInput ()
{
	if (InBuffer.BufLength () == 0)
		InBuffer.NeedSize (128);
	int n = Read (InBuffer);
	if (n <= 0) {
		if (n == -2) {
			InBuffer.Grow ();
			n = Read (InBuffer);
		}
		if (n < 0)
			SysError (ErrWarn, "UchBufStream::ReadInput");
		if (n <= 0)
			Closing (n < 0 ? false : true);
	}
	return n;
}

/*?
This virtual function is called when an end of file is read, 
meaning that the communication is terminated.
It is also called if an error occurs while reading.
You can check the value of the global variable \var{errno}:
if it is non zero, \fun{Closing} was called because of an error. % wrong
By default this function does nothing.
?*/
void
UchBufStream :: Closing (bool)
{
}


void
UchBufStream :: WriteLong (lword l)
{
	OutBuffer << l;
}

void
UchBufStream :: WriteShort (sword s)
{
	OutBuffer << s;
}

void
UchBufStream :: WriteByte (byte b)
{
	OutBuffer << b;
}

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

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

void
UchBufStream :: WriteBuf (const byte* b, int n)
{
	OutBuffer.WriteBuf (b, n);
}

bool
UchBufStream :: ReadLong (lword& l)
{
	return InBuffer.ReadLong (l);
}

bool
UchBufStream :: ReadShort (sword& s)
{
	return InBuffer.ReadShort (s);
}

bool
UchBufStream :: ReadByte (byte& b)
{
	return InBuffer.ReadByte (b);
}

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

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

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

bool
UchBufStream :: ReadBuf (byte* b, int n)
{
	return InBuffer.ReadBuf (b, n);
}



/*?class UchMsgStream
An object of class \typ{UchMsgStream} is a stream that sends and receives messages:
we call it a message stream.

Messages are sent with the function \fun{Send}.
Output messages are normally buffered to increase performance, but synchronous mode is available.
The output buffer can be flushed by the application, or by the stream itself if needed
(for instance when the buffer is full, or when a synchronous communication is needed).

Incoming messages are handled by the virtual function \fun{HandleRead} of class \typ{UchChannel}:
it is redefined so that incoming bytes are packed into messages.
When a full message is available, \fun{HandleRead} calls the virtual
function \fun{DecodeMessage} that instantiates a message, then calls the virtual function \fun{Activate} for that
message. Messages are not automatically destroyed.

Messages that need an answer are handled in the following way:
the sender calls the function\fun{Ask}, and is blocked until the answer is received;
any incoming messages are stored for later processing.
When the answer arrives, \fun{Ask} calls the virtual function \fun{DecodeAnswer}.
The returned value of \fun{DecodeAnswer} is then returned by \fun{Ask},
thus returning to the application the reply to its question.

On the receiver's side, the following happens:
when a message sent with \fun{Ask} is received, \fun{DecodeMessage} is called as usual,
but an argument indicates that it is a question that needs an answer.
The receiver must then use \fun{Reply} to send its answer.
Messages can be sent before replying, but it is not possible to send a question
on a message stream that is waiting for an answer:
this would result in a deadlock since the other party is already waiting for an answer
and is buffering other incoming messages.

The default output mode is buffered (i.e. asynchronous).
The buffered output is automatically flushed when a question is sent,
or when the output buffer is full, or explicitly with \fun{Flush}, or with the second argument of \fun{Send}.
The output mode can be switched to a synchronous mode where each message is sent immediately.
% It can also be switched to a locked synchronous mode: this is a synchronous mode where
% the sender waits for each message to be processed before proceeding its execution.
% This is mainly useful for debugging purposes.

\medskip
To use a message stream, a program needs to derive the class \typ{UchMsgStream}
in order to redefine the virtual functions \fun{DecodeMessage} and \fun{DecodeAnswer}.
\fun{DecodeMessage} treats the incoming message, and will probably call \fun{Send} and \fun{Ask}.
The top level of the program needs just call \fun{HandleRead} in a forever loop.

Most of the time, a program will use several message streams
(for instance to manage several clients).
In this case a channel set is the best way to implement the application:
the definitions in the class \typ{UchMsgStream} of the functions
\fun{HandleRead}, \fun{HandleWrite} and \fun{HandleSelect} make it easy
to use this class in combination with the class \typ{UchMultiplexer}.
The virtual function \fun{HandeWrite} of channels is redefined to flush the output buffer.
The virtual function \fun{HandleSelect} of channels is redefined to handle the incoming messages
that were buffered while waiting for an answer.
As for the single stream situation, you need just derive the class \fun{UchMsgStream} to
redefine the virtual functions \fun{DecodeMessage} and \fun{DecodeAnswer}.
?*/

// ---- no byte swapping ...
// ---- no locked sync mode ...

/*?
These constructors are similar to those of class \typ{UchSocket}.
?*/
UchMsgStream :: UchMsgStream (UchAddress* bindTo, UchAddress* connectTo)
: UchBufStream (bindTo, connectTo),
  Buffered ()
{
	State = WAITING;
	BufferedMessages = false;
	WaitingReply = false;
}

// *** this copy constructor might be automatically generated
/*?nodoc?*/
UchMsgStream :: UchMsgStream (const UchMsgStream& ms)
: UchBufStream (ms), Buffered (*(UchMsgBuffer*)&ms.Buffered)
{
      State = ms.State;
      BufferedMessages = ms.BufferedMessages;
      WaitingReply = ms.WaitingReply;
}


/*?nodoc?*/
UchMsgStream :: ~UchMsgStream ()
{
	Buffered.Clear ();
}

#if 0
/*?nodoc?*/
UchChannel*
UchMsgStream :: Copy () const
{
	return new UchMsgStream (*this);
}
#endif

// process the input buffer
// waitAnswer indicates whether we are waiting for an answer
// this functions uses a very simple automaton:
//	WAITING:	nothing in the buffer
//	GOT_TYPE:	read the 1 byte header mark of a message
//			MSG / ASK / ANS for messages, questions, answers
//			SYNC / ASYNC / OK for sync management
//	GOT_LENGTH:	read the 4 byte header fo a message
//	DONE:		a full message is in the buffer
//
// WaitingReply is true if a question has been received and Reply has not been called yet
//
/*?hidden?*/
/*!
Return a message when it's been fully read.
!*/
UchMessage*
UchMsgStream :: Process (UchMsgBuffer& buf, bool waitAnswer)
{
	for (;;) {
		switch (State) {
		case WAITING:
			buf.ReadByte (InType);
			if (buf.Error ())
				return 0;
			WaitingReply = false;
			switch (InType) {
			case ASK:
				WaitingReply = true;
			case ANS:
			case MSG:
				State = GOT_TYPE;
				break;
			case SYNC:
			case ASYNC:
			case OK:
			default:
				State = WAITING;
			}
			if (State != GOT_TYPE)
				break;
			// fallthrough
			
		case GOT_TYPE:
			if (! buf.PeekLong ((lword&) InLength))
				return 0;
			buf.NeedSize ((int) InLength - buf.BufLength ());
			State = GOT_LENGTH;
			// fallthrough
			
		case GOT_LENGTH:
			if (buf.BufLength () < InLength)
				return 0;
			State = DONE;
			// fallthrough
		
		case DONE:
			if (waitAnswer) {
				if (InType == ANS) {
					UchMsgBuffer fake (buf, InLength);
					UchMessage* ans = DecodeAnswer (fake);
					buf.Flush (InLength);
					State = WAITING;
					return ans;
				} else {
					// store incoming message in a separate buffer
					BufferedMessages = true;
					Buffered.WriteByte (InType);
					Buffered.WriteBuf (buf.Buffer (), InLength);
				}
			} else {
				if (InType == MSG || InType == ASK) {
					// pass a fake buffer to the handler
					UchMsgBuffer fake (buf, InLength);
					UchMessage* msg = DecodeMessage (fake);
					if (! msg || !msg->Activate (*this, WaitingReply))
						return 0;
					// *** these returns break the assumption that
					// *** Process empties the buffer.
					// *** this is assumed in HandleRead/HandleSelect
					// *** because BufferedMessages is reset to false;
						
				}
			}
			buf.Flush (InLength);
			State = WAITING;
			// fallthrough
		}
	}
}

/*?nodoc?*/
void
UchMsgStream :: HandleRead ()
{
	if (BufferedMessages) {
		Process (Buffered, false);
		BufferedMessages = false;
	}
	if (ReadInput () <= 0)
		return;

	Process (InBuffer, false);
}

#if 0
/*?nodoc?*/
bool
UchMsgStream :: HandleSelect ()
{
	if (BufferedMessages) {
		Process (Buffered, false);
		BufferedMessages = false;
	}
	return false;
}
#endif

/*?
This virtual function is called whenever a complete message is in the buffer.
The buffer contains exactly one message, so that you can use \com{buf.ReadMsg (msg)}
to extract the message from the buffer.
\fun{DecodeMessage} must return the extracted message. The default version returns a dummy \typ{UchMessage}.
If it returns false, it will be called again with the same arguments next time data arrives on this channel.
The function \typ{MyClient}::\fun{DecodeMessage}
may look like:
\begin{ccode}
UchMessage*
MyClient :: DecodeMessage (UchMsgBuffer& buffer)
{
    MyRequest* m = 0;
    lword type;
    buffer.Peek (type, lwsize);
    switch (type) {
    case MyFirstReqType:
        m = new MyFirstRequest;
        break;
    case ...
       ...
    }
    if (m)
        buffer.Get (m);

    return m;
}
\end{ccode}
?*/
UchMessage*
UchMsgStream :: DecodeMessage (UchMsgBuffer&)
{
	return new UchMessage;
}

/*?
Send a message.
If \var{flush} is true, the output buffer will be flushed.
This also happens when the message stream is in synchronous mode,
or if the output buffer has exceeded its flush size (see \fun{FlushSize}).
?*/
void
UchMsgStream :: Send (UchMessage& msg, bool flush)
{
	OutBuffer.WriteByte (MSG);
	WriteMsg (msg);
	if (flush || Sync || OutBuffer.BufLength () >= OutSize)
		Flush ();
}

void
UchMsgStream :: WriteMsg (UchMessage& msg)
{
	OutBuffer.WriteMsg (msg);
}

bool
UchMsgStream :: ReadMsg (UchMessage& msg)
{
	UchMsgBuffer& buf = BufferedMessages ? Buffered : InBuffer;
	int l = buf.BufLength (); // store current offset in the buffer
	lword msglen;
	buf >> msglen;
	if (l < msglen)
		return false;
	msg.ReadFrom (*this, msglen);
	/* skip end of msg if necessary */
	int rl = l - buf.BufLength ();
	if (rl == msglen)
		return true;
	else if (rl < msglen) {
		buf.Flush ((int)(msglen) - rl);
		return true;
	} else
		return false;
}

/*?
Send a message and wait for an answer.
Incoming messages that are received while waiting for the answer are kept for later processing.
The answer message is returned by calling the virtual function \fun{DecodeAnswer}.
?*/
UchMessage*
UchMsgStream :: Ask (UchMessage& msg)
{
	if (WaitingReply) {
		::Error (ErrWarn, "UchMsgStream::Ask", "cannot ask before replying");
		return 0;
	}
	OutBuffer.WriteByte (ASK);
	WriteMsg (msg);
	Flush ();

	UchMessage* ans = 0;
	do {
		if (ReadInput () <= 0)
			return 0;
		ans = Process (InBuffer, true);
	} while (!ans);
	
	return ans;
}

/*?
This function must be used instead of \fun{Send} to send a reply to a message sent by \fun{Ask}.
?*/
void
UchMsgStream :: Reply (UchMessage& msg)
{
	if (! WaitingReply) {
		::Error (ErrWarn, "UchMsgStream::Reply", "out of phase reply discarded");
		return;
	}
	OutBuffer.WriteByte ((byte) ANS);
	WriteMsg (msg);
	Flush ();
	WaitingReply = false;
}


/*?
This function is called by \fun{Ask} when the answer is in the buffer,
in order to convert it into an object usable by the application.
?*/
UchMessage*
UchMsgStream :: DecodeAnswer (UchMsgBuffer&)
{
	return 0;
}

/*?
Send a buffer containing a message.
If \var{flush} is true, the output buffer will be flushed.
This also happens when the message stream is in synchronous mode,
or if the output UchMsgBuffer.has exceeded its flush size (see \fun{FlushSize}).
The buffer {\em must} contain a converted message.
This can be used for instance from inside \fun{DecodeMessage} to resend
the incoming message to another client, without having to convert
the buffer to a message.
?*/
void
UchMsgStream :: Send (UchMsgBuffer& buf, bool flush)
{
	OutBuffer.WriteByte ((byte) MSG);
	OutBuffer.WriteBuf (buf.Buffer (), buf.BufLength ());
	if (flush || Sync || OutBuffer.BufLength () >= OutSize)
		Flush ();
}

#ifdef DOC
/*?
This function defines the size of the output buffer that triggers automatic flushing
in asynchronous mode. By default the flush size is the maximum size of the
output buffer. As a consequence, it is changed by \fun{OutBuffer}.
?*/
void
UchMsgStream :: FlushSize (int n)
{ }

/*?nextdoc?*/
void
UchMsgStream :: SetSyncMode (bool s)
{ }

/*?
A message stream can be in synchronous or asynchronous mode.
In asynchronous mode output is buffered while in synchronous mode it is not.
Synchronous mode is usually less efficient than asynchronous mode
because it makes more system calls to transfer data;
however synchronous mode can be useful for debugging applications.
?*/
bool
UchMsgStream :: GetSyncMode ()
{ }

#endif /* DOC */