summaryrefslogtreecommitdiff
path: root/comm/Multiplexer.cc
blob: 1823705e550a45535d623081a3e1a30519d3807a (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
/*
 *	The Unix Channel
 *
 *	by Michel Beaudouin-Lafon
 *
 *	Copyright 1990-1993
 *	Laboratoire de Recherche en Informatique (LRI)
 *
 *	Channel sets, or multiplexers
 *
 *	$Id$
 *	$CurLog$
 */

#include "Multiplexer.h"
#include "TimeOut.h"
#include "SignalHandler.h"

#include <signal.h>	// for NSIG
#include <sys/errno.h>
#include <sys/time.h>
#include <sys/socket.h>

#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <setjmp.h>

#if defined(__hpux) && !defined(__GNUG__)
#define FD_SET_TYPE(x) ((int*) x)
#else
#define FD_SET_TYPE(x) (x)
#endif

#ifdef __osf__
extern "C" int select (int, fd_set*, fd_set*, fd_set*, struct timeval*);
#endif

extern int	errno;

#ifndef FD_SET
#ifndef NFDBITS
#define	FD_SET(n, p)	((p)->fds_bits[0] |= (1 << (n)))
#define	FD_CLR(n, p)	((p)->fds_bits[0] &= ~(1 << (n)))
#define	FD_ISSET(n, p)	((p)->fds_bits[0] & (1 << (n)))
#define	FD_ZERO(p)	((p)->fds_bits[0] = 0)
#else
#define	FD_SET(n, p)	((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
#define	FD_CLR(n, p)	((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
#define	FD_ISSET(n, p)	((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
#define	FD_ZERO(p)	memset((char *)(p), 0, sizeof(*(p)))
#endif
#endif


/*?class UchBaseMultiplexer
Multiplexers make it possible to handle several communication channels at the
same time; their implementation is based on the Unix \com{select} system call
or similar mechanisms. Multiplexers are also able to implement safe (ie. not
interruption-based) timers and signal handlers.
Some of the channels in the set are active, others can be inactive.
A multiplexer can be scanned so that the functions \fun{HandleRead}
and \fun{HandleWrite} are called for every active channel that is ready to read or write.
The functions \fun{HandleSelect} of each channel is called before actually scanning
so that each channel can perform a background task or buffer input/output.

Multiplexers may have different implementations, depending on the environment.
When no other library is involved, they are simply implemented on top of Unix.
But if \uch\ channels have to be mixed with the X Toolkit for instance, the
implementation uses the mechanisms provided by the X Toolkit to add new channels.
The same holds for Tcl/Tk or other environments. Every such implentation corresponds
to a derived class of \typ{UchBaseMultiplexer}, which offers a uniform interface
that hides the implementation differences. See the class \typ{UchMultiplexer} for
a ``pure \uch'' implementation of multiplexers.

Note that the functions that take an integer file descriptor as argument can be passed
a \typ{FILDES} or a \typ{UchChannel} because the corresponding conversion operators are defined.
?*/

/*?
Create an empty channel set.
?*/
UchBaseMultiplexer :: UchBaseMultiplexer ()
: Channels (new pUchChannel [NFILE]),
  Timers (),
  ReadCount (0),
  WriteCount (0),
  SelectCount (0),
  Looping (false),
  SigFired (false),
  Handlers (new UchBaseSignalHandler* [NSIG]),
  NbSignals (new int [NSIG])
{
	memset (Handlers, 0, NSIG * sizeof (UchBaseSignalHandler*));
	memset (NbSignals, 0, NSIG * sizeof (int));
}

/*?nodoc?*/
UchBaseMultiplexer :: ~UchBaseMultiplexer ()
{
#ifdef CPLUS_BUG4
	delete [NFILE] Channels;
#else
	delete [] Channels;
	delete [] NbSignals;
	delete [] Handlers;
#endif
	Channels = 0;
}

/*?
Add a channel to the set.
Note that the argument is a pointer to the channel; no copy is made by this function.
If a channel with the same file descriptor as the one being added is already in the set,
the old channel is first removed.
?*/
void
UchBaseMultiplexer :: Add (UchChannel* chan)
{
	int fd = chan->FilDes ();
	if (fd < 0)
		return;
	pUchChannel ochan = Channels [fd];
	if (ochan)
		Remove (fd);
	chan->Added (*this);
	Channels [fd] = chan;
	SetMasks (fd, chan->IOMode ());
}

pUchChannel NIL_CHAN (0);

/*?
Remove a channel from the set. This function can be passed a \var{UchChannel}.
?*/
void
UchBaseMultiplexer :: Remove (int fd)
{
	if (fd < 0)
		return;
	UchChannel* ch = Channels [fd];
	if (ch) {
		ch->Removed (*this);
		SetMasks (fd, IONone);
		Channels [fd] = 0;
	}
}

/*?
Remove all channels from this channel set.
This function calls \fun{Remove} for all channels of the set.
This is a way of exiting from \fun{LoopScan}.
?*/
void
UchBaseMultiplexer :: RemoveAll ()
{
	for (int fd = 0; fd < NFILE; fd++)
		Remove (fd);
}

/*?
Change the mode of a channel in the set.
Mode \var{IONone} makes the channel inactive (without removing it).
This function can be passed a \var{UchChannel}.
?*/
void
UchBaseMultiplexer :: SetMode (int fd, IOMODE mode)
{
	if (fd < 0)
		return;
	
	SetMasks (fd, mode);
	Channels [fd] -> SetMode (mode);
}

#ifdef DOC

/*?
This array operator returns a (smart) pointer to the channel corresponding to file descriptor \var{fd}.
If there is no such channel in this channel set, the operator returns NIL.
?*/
pUchChannel
UchBaseMultiplexer :: operator [] (int fd)
{ }

/*?
Add a channel to the set.
Here the argument is a reference, and a dynamically allocated copy of it is actually added.
Compare with previous function.
?*/
void
UchBaseMultiplexer :: Add (const UchChannel& ch)
{ }

#endif	/* DOC */

/*!
This function is called by UchSignalHandlers when a signal is
received. It just stores the signal for future (and safe) handling.
!*/
/*?hidden?*/
void
UchBaseMultiplexer :: HandleSignal (UchBaseSignalHandler& h)
{
	if (!SigFired)
		AddSignalHook ();
	SigFired = true;
	int sig = h.GetSignal () - 1;
	/* We have to work with arrays, because we are in a signal
	   handler, and we cannot use lists */
	Handlers [sig] = &h;
	NbSignals [sig]++;

}

/*!
This virtual function is called the first time when a signal is received by a
signal handler associated to the multiplexer. It makes it possible
to call implementation-dependant functions that defer the handling to
safer times.
!*/
/*
Does not need to be defined in UchMultiplexer, because
they use the flag SigFired.
*/
/*?hidden?*/
void
UchBaseMultiplexer :: AddSignalHook ()
{
}

/*!
This function triggers the handling of all deferred signals. It should be
called when \fun{AddSignalHook} has been called and the times are safe.
!*/
/*?hidden?*/
void
UchBaseMultiplexer :: HandleDeferredSignals ()
{
	CcuSignalBlocker b (AllSigs);
	int c;
	for (int i = 0; i < NSIG; ++i)
		if (c = NbSignals [i]) {
			Handlers [i]->DeferredHandle (c);
			NbSignals [i] = 0;
			Handlers [i] = 0;
		}
}

/*?hidden?*/
void
UchBaseMultiplexer :: SetMasks (int, IOMODE)
{
}

static jmp_buf reset_run;

class UchMpxAborter : public UchBaseSignalHandler {
public:
	UchMpxAborter (UchBaseMultiplexer& m, int s) : UchBaseSignalHandler (m, s) {}
	void	DeferredHandle (int)	{ MyMpx.Abort (); }
};

/*?
Run a multiplexer: make it repeatedly scan its channels, and take the
appropriate actions. This function will exit under a number of
circumstances, reflected by its return value.
\small
\begin{tabular}{ll}
\var{isMpxTerminated}&the method \fun{Close} has been called.\\
\var{isMpxEmpty}&there are no more channels in the set.\\
\var{isMpxAborted}&the method \fun{Abort} has been called,
or signals SIGINT or SIGTERM were received.\\
\var{isMpxError}&an error has occured.
\end{tabular}
?*/
MPX_RES
UchBaseMultiplexer :: Run ()
{
	if (setjmp (reset_run))
		return isMpxAborted;

	UchMpxAborter h1 (*this, SigTerm);
	UchMpxAborter h2 (*this, SigInt);

	return Loop ();
}

/*?
Remove all channels from the multiplexer, thus stopping it if running.
?*/
void
UchBaseMultiplexer :: Close ()
{
	RemoveAll ();
	Looping = false;
}

/*?
Stop the multiplexer, without cleaning it.
?*/
void
UchBaseMultiplexer :: Abort ()
{
	if (Looping)
		longjmp (reset_run, 1);
}

/*?class UchMultiplexer
The class \typ{UchMultiplexer} is the default implementation of multiplexers,
used when there are no compatibility needs. For historical reasons, it offers
a number of additional methods.
?*/

/*?
Build an empty multiplexer.
?*/
UchMultiplexer :: UchMultiplexer ()
: UchBaseMultiplexer (),
  TimeOut (-1)
{
	FD_ZERO (&ReadMask);
	FD_ZERO (&WriteMask);
	FD_ZERO (&SelectMask);
}

/*?nodoc?*/
UchMultiplexer :: ~UchMultiplexer ()
{
}



// update the masks when channel fd changes its mode
//
/*?hidden?*/
void
UchMultiplexer :: SetMasks (int fd, IOMODE mode)
{
	if (mode & IORead) {
		if (! FD_ISSET (fd, &ReadMask)) {
			ReadCount ++;
			FD_SET (fd, &ReadMask);
		}
	} else {
		if (FD_ISSET (fd, &ReadMask)) {
			FD_CLR (fd, &ReadMask);
			ReadCount --;
		}
	}
	
	if (mode & IOWrite) {
		if (! FD_ISSET (fd, &WriteMask)) {
			WriteCount ++;
			FD_SET (fd, &WriteMask);
		}
	} else {
		if (FD_ISSET (fd, &WriteMask)) {
			FD_CLR (fd, &WriteMask);
			WriteCount --;
		}
	}
	
	if (mode & IOSelect) {
		if (! FD_ISSET (fd, &SelectMask)) {
			SelectCount ++;
			FD_SET (fd, &SelectMask);
		}
	} else {
		if (FD_ISSET (fd, &SelectMask)) {
			FD_CLR (fd, &SelectMask);
			SelectCount --;
		}
	}
	
}

/*?
This function calls the select handler of each channel of the set in select mode.
It returns true as soon as one select handler returns true,
else it returns false when the select handlers have been called.
?*/
bool
UchMultiplexer :: HandleSelect ()
{
	int	fd, nfd;
	
	if (fd0 >= NFILE)
		fd0 = 0;
	for (fd = fd0++, nfd = SelectCount; nfd; (fd < NFILE) ? fd++ : (fd = 0)) {
		if (! FD_ISSET (fd, &SelectMask))
			continue;
		if (Channels [fd] -> HandleSelect ())
			return true;
		nfd--;
		if (! Looping)
			return false;
	}
	return false;
}


////// should add signal handling
/*?nextdoc?*/
int
UchMultiplexer :: Scan (bool nointr, bool poll)
{
	fd_set rmsk, wmsk;
	int nfd, ret = -1;
	register int fd;
	struct timeval tout;
	struct timeval* timeout = 0;
	
	if (poll) {
		timeout = &tout;
		tout.tv_sec = tout.tv_usec = 0;
	}
	
	while (ret <= 0) {
		CcuCoreTimer::Fire (&Timers);
	
		if (ReadCount == 0 && WriteCount == 0 && SelectCount == 0)
			return 0;
		
		for (fd = 0, nfd = SelectCount; nfd; fd++) {
			if (! FD_ISSET (fd, &SelectMask))
				continue;
			UchChannel* ch = Channels [fd];
			if (ch && ch->HandleSelect ())
				return -2;
			nfd--;
		}
	
//printf ("Scan: read %x, write %x, TimeOut %d", ReadMask, WriteMask, TimeOut);
		rmsk = ReadMask;
		wmsk = WriteMask;
		if (!poll && TimeOut != -1) {
			CcuTimeStamp now;
			Millisecond delay = TimeOut - now;
//printf (", timeout in %d ms", delay);
			tout.tv_sec = delay / 1000;
			tout.tv_usec = 1000 * (delay % 1000);
			timeout = &tout;
		}
//printf ("\n");
		
		ret = select (NFILE, FD_SET_TYPE(&rmsk) /*read*/,  FD_SET_TYPE(&wmsk) /*write*/, 0 /*except*/, timeout);
		if (ret < 0 || ret == 0 && poll) {
//printf ("select failed: %d, errno %d\n", ret, errno);
			if (nointr && ret == -1 && errno == EINTR)
				continue;
			return ret;
		}
	}
	
	for (fd = 0, nfd = ret; nfd; fd++) {
//printf ("Scan: handle %d: r %d, w %d\n", fd, FD_ISSET (fd, &rmsk), FD_ISSET (fd, &wmsk));
		if (FD_ISSET (fd, &wmsk)) {
			nfd --;
			UchChannel* ch = Channels [fd];
			if (ch)
				ch->HandleWrite ();
		}
		if (FD_ISSET (fd, &rmsk)) {
			nfd--;
			UchChannel* ch = Channels [fd];
			if (ch)
				ch->HandleRead ();
		}
	}
	
	return ret;
}

/*?
Scan the channels in the set and call the channel's handlers.
First the select handler (\fun{UchChannel::HandleSelect}) of each channel with mode
\var{IOSelect} is called.
If it returns true, \fun{Scan} exits immediately, while \fun{LoopScan} loops immediately.
If no select handler returns true, the system call \fun{select} is used to poll or
wait for the channels that are ready.
When the select returns normally, the write handlers \fun{HandleWrite} of the
channels in mode \var{IOWrite} that are ready to write are called, and 
the read handlers (\fun{HandleRead}) of the channels in mode \fun{IORead}
that are ready to read are called.
If \var{nointr} is true, ignore the interrupted system calls, else return an error
whenever the \fun{select} system call is interrupted.
If \var{poll} is true, the call is non-blocking, else it is blocking.
\fun{Scan} calls \fun{select} only once;
it returns -2 if a select handler returns, it returns 0 if the channel set has no active channels,
else it returns the return code of \fun{select}.
\fun{LoopScan} calls \fun{select} repeatedly until \var{LoopEnd} is called, or
an error occurs, the channel set has no more active channel
This can occur because the select, read or write handler of a channel may remove
the channel or change its mode.
This is usually done when the read handler detects an end of file.
\fun{LoopScan} returns \var{isMpxEmpty} when there are no more active channel in the set,
it returns \var{isMpxError} when an error occured (the code is in \var{errno}),
and it returns \var{isMpxTerminated} if \fun{LoopEnd} or \fun{Close} was called.
?*/
MPX_RES
UchMultiplexer :: LoopScan (bool nointr)
{
	fd_set rmsk, wmsk;
	register int nfd, fd;
	Looping = true;
	
	for (fd0 = 0; Looping; fd0 < NFILE ? fd0++ : (fd0 = 0)) {
		
		/* First, handle signals */
		if (SigFired)
			HandleDeferredSignals ();

		/* Then, timers */
		CcuCoreTimer::Fire (&Timers);

		/* Then, I/Os */
		if (ReadCount == 0 && WriteCount == 0 && SelectCount == 0)
			return isMpxEmpty;
		
		for (fd = fd0, nfd = SelectCount; nfd; (fd < NFILE) ? fd++ : (fd = 0)) {
			if (! FD_ISSET (fd, &SelectMask))
				continue;
			UchChannel* ch = Channels [fd];
			if (ch && ch->HandleSelect ())
				break;
			nfd--;
			if (! Looping)
				return isMpxTerminated;
		}
		if (nfd)	// a handler returned true.
			continue;
		
		rmsk = ReadMask;
		wmsk = WriteMask;
		struct timeval tv;
		struct timeval* timeout = 0;
		if (TimeOut != -1) {
			CcuTimeStamp now;
			Millisecond delay = TimeOut - now;
			tv.tv_sec = delay / 1000;
			tv.tv_usec = 1000 * (delay % 1000);
			timeout = &tv;
		}
		nfd = select (NFILE, FD_SET_TYPE(&rmsk) /*read*/, FD_SET_TYPE(&wmsk) /*write*/, 0 /*except*/, timeout);
		if (nfd < 0) {
			if (nointr && nfd == -1 && errno == EINTR)
				continue;
			return isMpxError;
		}

		for (fd = fd0; nfd; (fd < NFILE) ? fd++ : (fd = 0)) {
			if (FD_ISSET (fd, &wmsk)) {
				nfd--;
				Channels [fd] -> HandleWrite ();
				if (! Looping)
					return isMpxTerminated;
			}
			if (FD_ISSET (fd, &rmsk)) {
				nfd--;
				Channels [fd] -> HandleRead ();
				if (! Looping)
					return isMpxTerminated;
			}
		}
	}
	return isMpxTerminated;
}

/*?nodoc?*/
char*
UchMultiplexer :: StrRepr (char* buf)
{
	sprintf (buf, "R:%ux W:%ux", ReadMask, WriteMask);
	return buf;
}

#ifdef DOC
// fake entries for inline functions
/*?
This function makes \fun{LoopScan} exit immediately.
Thus it must be called from within a channel's handler.
?*/
void
UchMultiplexer :: LoopEnd ()
{ }

#endif /* DOC */

/*?hidden?*/
void
UchMultiplexer :: SetTimeOut (Millisecond delay)
{
	CcuTimeStamp now;
	TimeOut = now + delay;
}

/*?hidden?*/
void
UchMultiplexer :: SuppressTimeOut ()
{
	TimeOut = -1;
}

/*?hidden?*/
MPX_RES
UchMultiplexer :: Loop ()
{
	return LoopScan ();
}