Debian Codegraph @

libhylafax/Dispatcher.c++

raw
1 /*
2 * Copyright (c) 1987-1991 Stanford University
3 * Copyright (c) 1991-1996 Silicon Graphics, Inc.
4 * HylaFAX is a trademark of Silicon Graphics
5 *
6 * Permission to use, copy, modify, distribute, and sell this software and
7 * its documentation for any purpose is hereby granted without fee, provided
8 * that (i) the above copyright notices and this permission notice appear in
9 * all copies of the software and related documentation, and (ii) the names of
10 * Stanford and Silicon Graphics may not be used in any advertising or
11 * publicity relating to the software without the specific, prior written
12 * permission of Stanford and Silicon Graphics.
13 *
14 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
16 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
17 *
18 * IN NO EVENT SHALL STANFORD OR SILICON GRAPHICS BE LIABLE FOR
19 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
20 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
21 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
22 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
23 * OF THIS SOFTWARE.
24 */
25
26 // Dispatcher provides an interface to the "select" system call.
27 #include "Sys.h" // NB: must be first
28
29 #include <errno.h>
30 #include <sys/param.h>
31 extern "C" {
32 #include <sys/time.h>
33 }
34 #include <limits.h>
35
36 #include "Dispatcher.h"
37 #include "IOHandler.h"
38
39 Dispatcher* Dispatcher::_instance;
40
41
42 /*
43 * Operations on timeval structures.
44 */
45
46 const long ONE_SECOND = 1000000;
47
48 timeval operator+(timeval src1, timeval src2) {
49 timeval sum;
50 sum.tv_sec = src1.tv_sec + src2.tv_sec;
51 sum.tv_usec = src1.tv_usec + src2.tv_usec;
52 if (sum.tv_usec >= ONE_SECOND) {
53 sum.tv_usec -= ONE_SECOND;
54 sum.tv_sec++;
55 } else if (sum.tv_sec >= 1 && sum.tv_usec < 0) {
56 sum.tv_usec += ONE_SECOND;
57 sum.tv_sec--;
58 }
59 return sum;
60 }
61
62 timeval operator-(timeval src1, timeval src2) {
63 timeval delta;
64 delta.tv_sec = src1.tv_sec - src2.tv_sec;
65 delta.tv_usec = src1.tv_usec - src2.tv_usec;
66 if (delta.tv_usec < 0) {
67 delta.tv_usec += ONE_SECOND;
68 delta.tv_sec--;
69 } else if (delta.tv_usec >= ONE_SECOND) {
70 delta.tv_usec -= ONE_SECOND;
71 delta.tv_sec++;
72 }
73 return delta;
74 }
75
76 bool operator>(timeval src1, timeval src2) {
77 if (src1.tv_sec > src2.tv_sec) {
78 return true;
79 } else if (src1.tv_sec == src2.tv_sec && src1.tv_usec > src2.tv_usec) {
80 return true;
81 } else {
82 return false;
83 }
84 }
85
86 bool operator<(timeval src1, timeval src2) {
87 if (src1.tv_sec < src2.tv_sec) {
88 return true;
89 } else if (src1.tv_sec == src2.tv_sec && src1.tv_usec < src2.tv_usec) {
90 return true;
91 } else {
92 return false;
93 }
94 }
95
96 /*
97 * Interface to timers.
98 */
99
100 struct Timer {
101 Timer(timeval t, IOHandler* h, Timer* n);
102
103 timeval timerValue;
104 IOHandler* handler;
105 Timer* next;
106 };
107
108 class TimerQueue {
109 public:
110 TimerQueue();
111 virtual ~TimerQueue();
112
113 bool isEmpty() const;
114 static timeval zeroTime();
115 timeval earliestTime() const;
116 static timeval currentTime();
117
118 void insert(timeval, IOHandler*);
119 void remove(IOHandler*);
120 void expire(timeval);
121 private:
122 Timer* _first;
123 static timeval _zeroTime;
124 };
125
126 Timer::Timer(timeval t, IOHandler* h, Timer* n) :
127 timerValue(t),
128 handler(h),
129 next(n) {}
130
131 timeval TimerQueue::_zeroTime;
132
133 TimerQueue::TimerQueue() :
134 _first(NULL) {}
135
136 TimerQueue::~TimerQueue() {
137 Timer* doomed = _first;
138 while (doomed != NULL) {
139 Timer* next = doomed->next;
140 delete doomed;
141 doomed = next;
142 }
143 }
144
145 inline bool TimerQueue::isEmpty() const {
146 return _first == NULL;
147 }
148
149 inline timeval TimerQueue::zeroTime() {
150 return _zeroTime;
151 }
152
153 inline timeval TimerQueue::earliestTime() const {
154 return _first->timerValue;
155 }
156
157 timeval TimerQueue::currentTime() {
158 timeval curTime;
159 gettimeofday(&curTime, 0);
160 return curTime;
161 }
162
163 void TimerQueue::insert(timeval futureTime, IOHandler* handler) {
164 if (isEmpty() || futureTime < earliestTime()) {
165 _first = new Timer(futureTime, handler, _first);
166 } else {
167 Timer* before = _first;
168 Timer* after = _first->next;
169 while (after != NULL && futureTime > after->timerValue) {
170 before = after;
171 after = after->next;
172 }
173 before->next = new Timer(futureTime, handler, after);
174 }
175 }
176
177 void TimerQueue::remove(IOHandler* handler) {
178 Timer* before = NULL;
179 Timer* doomed = _first;
180 while (doomed != NULL && doomed->handler != handler) {
181 before = doomed;
182 doomed = doomed->next;
183 }
184 if (doomed != NULL) {
185 if (before == NULL) {
186 _first = doomed->next;
187 } else {
188 before->next = doomed->next;
189 }
190 delete doomed;
191 }
192 }
193
194 void TimerQueue::expire(timeval curTime) {
195 while (!isEmpty() && earliestTime() < curTime) {
196 Timer* expired = _first;
197 _first = _first->next;
198 expired->handler->timerExpired(curTime.tv_sec, curTime.tv_usec);
199 delete expired;
200 }
201 }
202
203 /*
204 * Interface to child process handling.
205 */
206
207 struct Child {
208 Child(pid_t pid, IOHandler* h, Child* n);
209
210 pid_t pid; // process's PID
211 int status; // wait status
212 IOHandler* handler; // associated handler
213 Child* next;
214 };
215
216 class ChildQueue {
217 public:
218 ChildQueue();
219 virtual ~ChildQueue();
220
221 bool isEmpty() const;
222 bool isReady() const;
223
224 void insert(pid_t, IOHandler*);
225 void remove(IOHandler*);
226 void notify();
227 void setStatus(pid_t, int status);
228 private:
229 Child* _first; // queue head
230 bool _ready; // something is ready
231 };
232
233 Child::Child(pid_t p, IOHandler* h, Child* n)
234 {
235 pid = p;
236 status = -1;
237 handler = h;
238 next = n;
239 }
240
241 ChildQueue::ChildQueue()
242 {
243 _first = NULL;
244 _ready = false;
245 }
246
247 ChildQueue::~ChildQueue() {
248 Child* doomed = _first;
249 while (doomed != NULL) {
250 Child* next = doomed->next;
251 delete doomed;
252 doomed = next;
253 }
254 }
255
256 inline bool ChildQueue::isEmpty() const { return _first == NULL; }
257 inline bool ChildQueue::isReady() const { return _ready; }
258
259 void ChildQueue::insert(pid_t p, IOHandler* handler) {
260 /*
261 * Place the entry at the end. This is intentional
262 * so that the work done in the notify method below
263 * functions correctly when entries are added by
264 * childStatus handlers. On busy systems it may pay
265 * to use a doubly linked list or to otherwise sort
266 * the list to reduce searching, but since there
267 * should never be more than 2x entries where x is
268 * the number of ready modems on the system a singly
269 * linked list should be ok.
270 */
271 Child** prev = &_first;
272 while (*prev != NULL)
273 prev = &(*prev)->next;
274 *prev = new Child(p, handler, NULL);
275 }
276
277 void ChildQueue::remove(IOHandler* handler) {
278 Child* before = NULL;
279 Child* doomed = _first;
280 while (doomed != NULL && doomed->handler != handler) {
281 before = doomed;
282 doomed = doomed->next;
283 }
284 if (doomed != NULL) {
285 if (before == NULL) {
286 _first = doomed->next;
287 } else {
288 before->next = doomed->next;
289 }
290 delete doomed;
291 }
292 }
293
294 void ChildQueue::setStatus(pid_t p, int status) {
295 for (Child* c = _first; c != NULL; c = c->next)
296 if (c->pid == p) {
297 c->status = status;
298 _ready = true;
299 break;
300 }
301 }
302
303 void ChildQueue::notify() {
304 Child** prev = &_first;
305 Child* c;
306
307 while ((c = *prev) != NULL) {
308 if (c->status != -1) {
309 *prev = c->next;
310 c->handler->childStatus(c->pid, c->status);
311 delete c;
312 } else
313 prev = &c->next;
314 }
315 _ready = false;
316 }
317
318 Dispatcher::Dispatcher() {
319 _nfds = 0;
320 FD_ZERO(&_rmask);
321 FD_ZERO(&_wmask);
322 FD_ZERO(&_emask);
323 FD_ZERO(&_rmaskready);
324 FD_ZERO(&_wmaskready);
325 FD_ZERO(&_emaskready);
326 _max_fds = Sys::getOpenMax();
327 _rtable = new IOHandler*[_max_fds];
328 _wtable = new IOHandler*[_max_fds];
329 _etable = new IOHandler*[_max_fds];
330 _queue = new TimerQueue;
331 _cqueue = new ChildQueue;
332 for (u_int i = 0; i < _max_fds; i++) {
333 _rtable[i] = NULL;
334 _wtable[i] = NULL;
335 _etable[i] = NULL;
336 }
337 }
338
339 Dispatcher::~Dispatcher() {
340 delete [] _rtable;
341 delete [] _wtable;
342 delete [] _etable;
343 delete _queue;
344 delete _cqueue;
345 }
346
347 Dispatcher& Dispatcher::instance() {
348 if (_instance == NULL) {
349 _instance = new Dispatcher;
350 }
351 return *_instance;
352 }
353
354 void Dispatcher::instance(Dispatcher* d) { _instance = d; }
355
356 IOHandler* Dispatcher::handler(int fd, DispatcherMask mask) const {
357 if ((unsigned) fd >= _max_fds) {
358 abort();
359 }
360 IOHandler* cur = NULL;
361 if (mask == ReadMask) {
362 cur = _rtable[fd];
363 } else if (mask == WriteMask) {
364 cur = _wtable[fd];
365 } else if (mask == ExceptMask) {
366 cur = _etable[fd];
367 } else {
368 abort();
369 }
370 return cur;
371 }
372
373 void Dispatcher::link(int fd, DispatcherMask mask, IOHandler* handler) {
374 if ((unsigned) fd >= _max_fds) {
375 abort();
376 }
377 attach(fd, mask, handler);
378 }
379
380 void Dispatcher::unlink(int fd) {
381 if ((unsigned) fd >= _max_fds) {
382 abort();
383 }
384 detach(fd);
385 }
386
387 void Dispatcher::attach(int fd, DispatcherMask mask, IOHandler* handler) {
388 if (fd < 0)
389 return;
390
391 if (mask == ReadMask) {
392 FD_SET(fd, &_rmask);
393 _rtable[fd] = handler;
394 } else if (mask == WriteMask) {
395 FD_SET(fd, &_wmask);
396 _wtable[fd] = handler;
397 } else if (mask == ExceptMask) {
398 FD_SET(fd, &_emask);
399 _etable[fd] = handler;
400 } else {
401 abort();
402 }
403 if (_nfds < (unsigned)fd+1) {
404 _nfds = fd+1;
405 }
406 }
407
408 void Dispatcher::detach(int fd) {
409 FD_CLR(fd, &_rmask);
410 _rtable[fd] = NULL;
411 FD_CLR(fd, &_wmask);
412 _wtable[fd] = NULL;
413 FD_CLR(fd, &_emask);
414 _etable[fd] = NULL;
415 if (_nfds == (unsigned)fd+1) {
416 while (_nfds > 0 && _rtable[_nfds-1] == NULL &&
417 _wtable[_nfds-1] == NULL && _etable[_nfds-1] == NULL
418 ) {
419 _nfds--;
420 }
421 }
422 }
423
424 void Dispatcher::startTimer(long sec, long usec, IOHandler* handler) {
425 timeval deltaTime;
426 deltaTime.tv_sec = sec;
427 deltaTime.tv_usec = usec;
428 _queue->insert(TimerQueue::currentTime() + deltaTime, handler);
429 }
430
431 void Dispatcher::stopTimer(IOHandler* handler) {
432 _queue->remove(handler);
433 }
434
435 void Dispatcher::startChild(pid_t pid, IOHandler* handler) {
436 _cqueue->insert(pid, handler);
437 }
438
439 void Dispatcher::stopChild(IOHandler* handler) {
440 _cqueue->remove(handler);
441 }
442
443 bool Dispatcher::setReady(int fd, DispatcherMask mask) {
444 if (handler(fd, mask) == NULL) {
445 return false;
446 }
447 if (mask == ReadMask) {
448 FD_SET(fd, &_rmaskready);
449 } else if (mask == WriteMask) {
450 FD_SET(fd, &_wmaskready);
451 } else if (mask == ExceptMask) {
452 FD_SET(fd, &_emaskready);
453 } else {
454 return false;
455 }
456 return true;
457 }
458
459 void Dispatcher::dispatch() {
460 dispatch(NULL);
461 }
462
463 bool Dispatcher::dispatch(long& sec, long& usec) {
464 timeval howlong;
465 timeval prevTime;
466 timeval elapsedTime;
467
468 howlong.tv_sec = sec;
469 howlong.tv_usec = usec;
470 prevTime = TimerQueue::currentTime();
471
472 bool success = dispatch(&howlong);
473
474 elapsedTime = TimerQueue::currentTime() - prevTime;
475 if (howlong > elapsedTime) {
476 howlong = howlong - elapsedTime;
477 } else {
478 howlong = TimerQueue::zeroTime(); /* Used all of timeout */
479 }
480
481 sec = howlong.tv_sec;
482 usec = howlong.tv_usec;
483 return success;
484 }
485
486 bool Dispatcher::dispatch(timeval* howlong) {
487 fd_set rmask;
488 fd_set wmask;
489 fd_set emask;
490
491 FD_ZERO(&rmask);
492 FD_ZERO(&wmask);
493 FD_ZERO(&emask);
494
495 int nfound = (anyReady()) ?
496 fillInReady(rmask, wmask, emask)
497 : waitFor(rmask, wmask, emask, howlong);
498
499 notify(nfound, rmask, wmask, emask);
500
501 return (nfound != 0);
502 }
503
504 bool Dispatcher::anyReady() const {
505 if (!_cqueue->isEmpty()) {
506 Dispatcher::sigCLD(0); // poll for pending children
507 return _cqueue->isReady();
508 }
509 for (u_int i = 0; i < _nfds; i++) {
510 if (FD_ISSET(i, &_rmaskready) ||
511 FD_ISSET(i, &_wmaskready) || FD_ISSET(i, &_emaskready)) {
512 return true;
513 }
514 }
515 return false;
516 }
517
518 int Dispatcher::fillInReady(
519 fd_set& rmaskret, fd_set& wmaskret, fd_set& emaskret) {
520
521 //note - this is an array copy, not a pointer assignment
522 rmaskret = _rmaskready;
523 wmaskret = _wmaskready;
524 emaskret = _emaskready;
525 FD_ZERO(&_rmaskready);
526 FD_ZERO(&_wmaskready);
527 FD_ZERO(&_emaskready);
528 int n = 0;
529 for (u_int i = 0; i < _nfds; i++) {
530 if (FD_ISSET(i, &rmaskret)) n++;
531 if (FD_ISSET(i, &wmaskret)) n++;
532 if (FD_ISSET(i, &emaskret)) n++;
533 }
534 return n;
535 }
536
537 void Dispatcher::sigCLD(int)
538 {
539 int old_errno = errno;
540 pid_t pid;
541 int status;
542
543 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
544 Dispatcher::instance()._cqueue->setStatus(pid, status);
545 errno = old_errno;
546 }
547
548 #ifndef SA_INTERRUPT
549 #define SA_INTERRUPT 0
550 #endif
551
552 int Dispatcher::waitFor(
553 fd_set& rmaskret, fd_set& wmaskret, fd_set& emaskret, timeval* howlong
554 ) {
555 int nfound = 0;
556 #if defined(SA_NOCLDSTOP) // POSIX
557 static struct sigaction sa, osa;
558 #elif defined(SV_INTERRUPT) // BSD-style
559 static struct sigvec sv, osv;
560 #else // System V-style
561 void (*osig)();
562 #endif
563
564 if (!_cqueue->isEmpty()) {
565 #if defined(SA_NOCLDSTOP) // POSIX
566 sa.sa_handler = fxSIGACTIONHANDLER(&Dispatcher::sigCLD);
567 sa.sa_flags = SA_INTERRUPT;
568 sigaction(SIGCHLD, &sa, &osa);
569 #elif defined(SV_INTERRUPT) // BSD-style
570 sv.sv_handler = fxSIGVECHANDLER(&Dispatcher::sigCLD);
571 sv.sv_flags = SV_INTERRUPT;
572 sigvec(SIGCHLD, &sv, &osv);
573 #else // System V-style
574 osig = (void (*)())signal(SIGCLD, fxSIGHANDLER(&Dispatcher::sigCLD));
575 #endif
576 }
577 /*
578 * If SIGCLD is pending then it may be delivered on
579 * exiting from the kernel after the above sig* call;
580 * if so then we don't want to block in the select.
581 */
582 if (!_cqueue->isReady()) {
583 do {
584 //note - this is an array copy, not a pointer assignment
585 rmaskret = _rmask;
586 wmaskret = _wmask;
587 emaskret = _emask;
588 howlong = calculateTimeout(howlong);
589
590 #if CONFIG_BADSELECTPROTO
591 nfound = select(_nfds,
592 (int*) &rmaskret, (int*) &wmaskret, (int*) &emaskret, howlong);
593 #else
594 nfound = select(_nfds, &rmaskret, &wmaskret, &emaskret, howlong);
595 #endif
596 howlong = calculateTimeout(howlong);
597 } while (nfound < 0 && !handleError());
598 }
599 if (!_cqueue->isEmpty()) {
600 #if defined(SA_NOCLDSTOP) // POSIX
601 sigaction(SIGCHLD, &osa, (struct sigaction*) 0);
602 #elif defined(SV_INTERRUPT) // BSD-style
603 sigvec(SIGCHLD, &osv, (struct sigvec*) 0);
604 #else // System V-style
605 (void) signal(SIGCLD, fxSIGHANDLER(osig));
606 #endif
607 }
608
609 return nfound; // timed out or input available
610 }
611
612 void Dispatcher::notify(int nfound,
613 fd_set& rmaskret, fd_set& wmaskret, fd_set& emaskret) {
614 for (u_int i = 0; i < _nfds && nfound > 0; i++) {
615 if (FD_ISSET(i, &rmaskret)) {
616 if (_rtable[i]) {
617 int status = _rtable[i]->inputReady(i);
618 if (status < 0) {
619 detach(i);
620 } else if (status > 0) {
621 FD_SET(i, &_rmaskready);
622 }
623 }
624 nfound--;
625 }
626 if (FD_ISSET(i, &wmaskret)) {
627 if (_wtable[i]) {
628 int status = _wtable[i]->outputReady(i);
629 if (status < 0) {
630 detach(i);
631 } else if (status > 0) {
632 FD_SET(i, &_wmaskready);
633 }
634 }
635 nfound--;
636 }
637 if (FD_ISSET(i, &emaskret)) {
638 if (_etable[i]) {
639 int status = _etable[i]->exceptionRaised(i);
640 if (status < 0) {
641 detach(i);
642 } else if (status > 0) {
643 FD_SET(i, &_emaskready);
644 }
645 }
646 nfound--;
647 }
648 }
649
650 if (!_queue->isEmpty()) {
651 _queue->expire(TimerQueue::currentTime());
652 }
653 if (_cqueue->isReady()) {
654 _cqueue->notify();
655 }
656 }
657
658 timeval* Dispatcher::calculateTimeout(timeval* howlong) const {
659 static timeval timeout;
660
661 if (!_queue->isEmpty()) {
662 timeval curTime;
663
664 curTime = TimerQueue::currentTime();
665 if (_queue->earliestTime() > curTime) {
666 timeout = _queue->earliestTime() - curTime;
667 if (howlong == NULL || *howlong > timeout) {
668 howlong = &timeout;
669 }
670 } else {
671 timeout = TimerQueue::zeroTime();
672 howlong = &timeout;
673 }
674 }
675 return howlong;
676 }
677
678 extern void fxFatal(const char* fmt, ...);
679
680 bool Dispatcher::handleError() {
681 switch (errno) {
682 case EBADF:
683 checkConnections();
684 break;
685 case EINTR:
686 if (_cqueue->isReady())
687 return true;
688 break;
689 default:
690 fxFatal("Dispatcher: select: %s", strerror(errno));
691 /*NOTREACHED*/
692 }
693 return false; // retry select
694 }
695
696 void Dispatcher::checkConnections() {
697 fd_set rmask;
698 FD_ZERO(&rmask);
699 timeval poll = TimerQueue::zeroTime();
700
701 for (u_int fd = 0; fd < _nfds; fd++) {
702 if (_rtable[fd] != NULL) {
703 FD_SET(fd, &rmask);
704 #if CONFIG_BADSELECTPROTO
705 if (select(fd+1, (int*)&rmask, NULL, NULL, &poll) < 0) {
706 #else
707 if (select(fd+1, &rmask, NULL, NULL, &poll) < 0) {
708 #endif
709 detach(fd);
710 }
711 FD_CLR(fd, &rmask);
712 }
713 }
714 }