summaryrefslogtreecommitdiff
path: root/omapip/dispatch.c
blob: 644ab43ffc47b8cb8bf6c4e726d62cff5d59dfa0 (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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
/* dispatch.c

   I/O dispatcher. */

/*
 * Copyright (C) 2004-2022 Internet Systems Consortium, Inc. ("ISC")
 * Copyright (c) 1999-2003 by Internet Software Consortium
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 *   Internet Systems Consortium, Inc.
 *   PO Box 360
 *   Newmarket, NH 03857 USA
 *   <info@isc.org>
 *   https://www.isc.org/
 *
 */

#include "dhcpd.h"

#include <omapip/omapip_p.h>
#include <sys/time.h>

static omapi_io_object_t omapi_io_states;
struct timeval cur_tv;

struct eventqueue *rw_queue_empty;

OMAPI_OBJECT_ALLOC (omapi_io,
		    omapi_io_object_t, omapi_type_io_object)
OMAPI_OBJECT_ALLOC (omapi_waiter,
		    omapi_waiter_object_t, omapi_type_waiter)

void
register_eventhandler(struct eventqueue **queue, void (*handler)(void *))
{
	struct eventqueue *t, *q;

	/* traverse to end of list */
	t = NULL;
	for (q = *queue ; q ; q = q->next) {
		if (q->handler == handler)
			return; /* handler already registered */
		t = q;
	}

	q = ((struct eventqueue *)dmalloc(sizeof(struct eventqueue), MDL));
	if (!q)
		log_fatal("register_eventhandler: no memory!");
	memset(q, 0, sizeof *q);
	if (t)
		t->next = q;
	else
		*queue	= q;
	q->handler = handler;
	return;
}

void
unregister_eventhandler(struct eventqueue **queue, void (*handler)(void *))
{
	struct eventqueue *t, *q;

	/* traverse to end of list */
	t= NULL;
	for (q = *queue ; q ; q = q->next) {
		if (q->handler == handler) {
			if (t)
				t->next = q->next;
			else
				*queue = q->next;
			dfree(q, MDL); /* Don't access q after this!*/
			break;
		}
		t = q;
	}
	return;
}

void
trigger_event(struct eventqueue **queue)
{
	struct eventqueue *q;

	for (q=*queue ; q ; q=q->next) {
		if (q->handler)
			(*q->handler)(NULL);
	}
}

/*
 * Callback routine to connect the omapi I/O object and socket with
 * the isc socket code.  The isc socket code will call this routine
 * which will then call the correct local routine to process the bytes.
 *
 * Currently we are always willing to read more data, this should be modified
 * so that on connections we don't read more if we already have enough.
 *
 * If we have more bytes to write we ask the library to call us when
 * we can write more.  If we indicate we don't have more to write we need
 * to poke the library via isc_socket_fdwatchpoke.
 */

/*
 * sockdelete indicates if we are deleting the socket or leaving it in place
 * 1 is delete, 0 is leave in place
 */
#define SOCKDELETE 1
int
omapi_iscsock_cb(isc_task_t   *task,
		 isc_socket_t *socket,
		 void         *cbarg,
		 int           flags)
{
	omapi_io_object_t *obj;
	isc_result_t status;

	/* Get the current time... */
	gettimeofday (&cur_tv, (struct timezone *)0);

	/* isc socket stuff */
#if SOCKDELETE
	/*
	 * walk through the io states list, if our object is on there
	 * service it.  if not ignore it.
	 */
	for (obj = omapi_io_states.next; obj != NULL; obj = obj->next) {
		if (obj == cbarg)
			break;
	}

	if (obj == NULL) {
		return(0);
	}
#else
	/* Not much to be done if we have the wrong type of object. */
	if (((omapi_object_t *)cbarg) -> type != omapi_type_io_object) {
		log_fatal ("Incorrect object type, must be of type io_object");
	}
	obj = (omapi_io_object_t *)cbarg;

	/*
	 * If the object is marked as closed don't try and process
	 * anything just indicate that we don't want any more.
	 *
	 * This should be a temporary fix until we arrange to properly
	 * close the socket.
	 */
	if (obj->closed == ISC_TRUE) {
		return(0);
	}
#endif

	if ((flags == ISC_SOCKFDWATCH_READ) &&
	    (obj->reader != NULL) &&
	    (obj->inner != NULL)) {
		status = obj->reader(obj->inner);
		/*
		 * If we are shutting down (basically tried to
		 * read and got no bytes) we don't need to try
		 * again.
		 */
		if (status == ISC_R_SHUTTINGDOWN)
			return (0);
		/* Otherwise We always ask for more when reading */
		return (1);
	} else if ((flags == ISC_SOCKFDWATCH_WRITE) &&
		 (obj->writer != NULL) &&
		 (obj->inner != NULL)) {
		status = obj->writer(obj->inner);
		/* If the writer has more to write they should return
		 * ISC_R_INPROGRESS */
		if (status == ISC_R_INPROGRESS) {
			return (1);
		}
	}

	/*
	 * We get here if we either had an error (inconsistent
	 * structures etc) or no more to write, tell the socket
	 * lib we don't have more to do right now.
	 */
	return (0);
}

/* Register an I/O handle so that we can do asynchronous I/O on it. */

isc_result_t omapi_register_io_object (omapi_object_t *h,
				       int (*readfd) (omapi_object_t *),
				       int (*writefd) (omapi_object_t *),
				       isc_result_t (*reader)
						(omapi_object_t *),
				       isc_result_t (*writer)
						(omapi_object_t *),
				       isc_result_t (*reaper)
						(omapi_object_t *))
{
	isc_result_t status;
	omapi_io_object_t *obj, *p;
	int fd_flags = 0, fd = 0;

	/* omapi_io_states is a static object.   If its reference count
	   is zero, this is the first I/O handle to be registered, so
	   we need to initialize it.   Because there is no inner or outer
	   pointer on this object, and we're setting its refcnt to 1, it
	   will never be freed. */
	if (!omapi_io_states.refcnt) {
		omapi_io_states.refcnt = 1;
		omapi_io_states.type = omapi_type_io_object;
	}

	obj = (omapi_io_object_t *)0;
	status = omapi_io_allocate (&obj, MDL);
	if (status != ISC_R_SUCCESS)
		return status;
	obj->closed = ISC_FALSE;  /* mark as open */

	status = omapi_object_reference (&obj -> inner, h, MDL);
	if (status != ISC_R_SUCCESS) {
		omapi_io_dereference (&obj, MDL);
		return status;
	}

	status = omapi_object_reference (&h -> outer,
					 (omapi_object_t *)obj, MDL);
	if (status != ISC_R_SUCCESS) {
		omapi_io_dereference (&obj, MDL);
		return status;
	}

	/*
	 * Attach the I/O object to the isc socket library via the
	 * fdwatch function.  This allows the socket library to watch
	 * over a socket that we built.  If there are both a read and
	 * a write socket we asssume they are the same socket.
	 */

	if (readfd) {
		fd_flags |= ISC_SOCKFDWATCH_READ;
		fd = readfd(h);
	}

	if (writefd) {
		fd_flags |= ISC_SOCKFDWATCH_WRITE;
		fd = writefd(h);
	}

	if (fd_flags != 0) {
		status = isc_socket_fdwatchcreate(dhcp_gbl_ctx.socketmgr,
						  fd, fd_flags,
						  omapi_iscsock_cb,
						  obj,
						  dhcp_gbl_ctx.task,
						  &obj->fd);
		if (status != ISC_R_SUCCESS) {
			log_error("Unable to register fd with library %s",
				   isc_result_totext(status));

			/*sar*/
			/* is this the cleanup we need? */
			omapi_object_dereference(&h->outer, MDL);
			omapi_io_dereference (&obj, MDL);
			return (status);
		}
	}


	/* Find the last I/O state, if there are any. */
	for (p = omapi_io_states.next;
	     p && p -> next; p = p -> next)
		;
	if (p)
		omapi_io_reference (&p -> next, obj, MDL);
	else
		omapi_io_reference (&omapi_io_states.next, obj, MDL);

	obj -> readfd = readfd;
	obj -> writefd = writefd;
	obj -> reader = reader;
	obj -> writer = writer;
	obj -> reaper = reaper;

	omapi_io_dereference(&obj, MDL);
	return ISC_R_SUCCESS;
}

/*
 * ReRegister an I/O handle so that we can do asynchronous I/O on it.
 * If the handle doesn't exist we call the register routine to build it.
 * If it does exist we change the functions associated with it, and
 * repoke the fd code to make it happy.  Neither the objects nor the
 * fd are allowed to have changed.
 */

isc_result_t omapi_reregister_io_object (omapi_object_t *h,
					 int (*readfd) (omapi_object_t *),
					 int (*writefd) (omapi_object_t *),
					 isc_result_t (*reader)
					 	(omapi_object_t *),
					 isc_result_t (*writer)
					 	(omapi_object_t *),
					 isc_result_t (*reaper)
					 	(omapi_object_t *))
{
	omapi_io_object_t *obj;
	int fd_flags = 0;

	if ((!h -> outer) || (h -> outer -> type != omapi_type_io_object)) {
		/*
		 * If we don't have an object or if the type isn't what
		 * we expect do the normal registration (which will overwrite
		 * an incorrect type, that's what we did historically, may
		 * want to change that)
		 */
		return (omapi_register_io_object (h, readfd, writefd,
						  reader, writer, reaper));
	}

	/* We have an io object of the correct type, try to update it */
	/*sar*/
	/* Should we validate that the fd matches the previous one?
	 * It's suppossed to, that's a requirement, don't bother yet */

	obj = (omapi_io_object_t *)h->outer;

	obj->readfd = readfd;
	obj->writefd = writefd;
	obj->reader = reader;
	obj->writer = writer;
	obj->reaper = reaper;

	if (readfd) {
		fd_flags |= ISC_SOCKFDWATCH_READ;
	}

	if (writefd) {
		fd_flags |= ISC_SOCKFDWATCH_WRITE;
	}

	isc_socket_fdwatchpoke(obj->fd, fd_flags);

	return (ISC_R_SUCCESS);
}

isc_result_t omapi_unregister_io_object (omapi_object_t *h)
{
	omapi_io_object_t *obj, *ph;
#if SOCKDELETE
	omapi_io_object_t *p, *last;
#endif

	if (!h -> outer || h -> outer -> type != omapi_type_io_object)
		return DHCP_R_INVALIDARG;
	obj = (omapi_io_object_t *)h -> outer;
	ph = (omapi_io_object_t *)0;
	omapi_io_reference (&ph, obj, MDL);

#if SOCKDELETE
	/*
	 * For now we leave this out.  We can't clean up the isc socket
	 * structure cleanly yet so we need to leave the io object in place.
	 * By leaving it on the io states list we avoid it being freed.
	 * We also mark it as closed to avoid using it.
	 */

	/* remove from the list of I/O states */
        last = &omapi_io_states;
	for (p = omapi_io_states.next; p; p = p -> next) {
		if (p == obj) {
			omapi_io_dereference (&last -> next, MDL);
			omapi_io_reference (&last -> next, p -> next, MDL);
			break;
		}
		last = p;
	}
	if (obj -> next)
		omapi_io_dereference (&obj -> next, MDL);
#endif

	if (obj -> outer) {
		if (obj -> outer -> inner == (omapi_object_t *)obj)
			omapi_object_dereference (&obj -> outer -> inner,
						  MDL);
		omapi_object_dereference (&obj -> outer, MDL);
	}
	omapi_object_dereference (&obj -> inner, MDL);
	omapi_object_dereference (&h -> outer, MDL);

#if SOCKDELETE
	/* remove isc socket associations */
	if (obj->fd != NULL) {
		isc_socket_cancel(obj->fd, dhcp_gbl_ctx.task,
				  ISC_SOCKCANCEL_ALL);
		isc_socket_detach(&obj->fd);
	}
#else
	obj->closed = ISC_TRUE;
#endif

	omapi_io_dereference (&ph, MDL);
	return ISC_R_SUCCESS;
}

isc_result_t omapi_dispatch (struct timeval *t)
{
#ifdef DEBUG_PROTOCOL
	log_debug("omapi_dispatch()");
#endif
	return omapi_wait_for_completion ((omapi_object_t *)&omapi_io_states,

					  t);
}

isc_result_t omapi_wait_for_completion (omapi_object_t *object,
					struct timeval *t)
{
#ifdef DEBUG_PROTOCOL
	if (t) {
        	log_debug ("omapi_wait_for_completion(%u.%u secs)",
			   (unsigned int)(t->tv_sec),
			   (unsigned int)(t->tv_usec));
	} else {
        	log_debug ("omapi_wait_for_completion(no timeout)");
	}
#endif
	isc_result_t status;
	omapi_waiter_object_t *waiter;
	omapi_object_t *inner;

	if (object) {
		waiter = (omapi_waiter_object_t *)0;
		status = omapi_waiter_allocate (&waiter, MDL);
		if (status != ISC_R_SUCCESS)
			return status;

		/* Paste the waiter object onto the inner object we're
		   waiting on. */
		for (inner = object; inner -> inner; inner = inner -> inner)
			;

		status = omapi_object_reference (&waiter -> outer, inner, MDL);
		if (status != ISC_R_SUCCESS) {
			omapi_waiter_dereference (&waiter, MDL);
			return status;
		}

		status = omapi_object_reference (&inner -> inner,
						 (omapi_object_t *)waiter,
						 MDL);
		if (status != ISC_R_SUCCESS) {
			omapi_waiter_dereference (&waiter, MDL);
			return status;
		}
	} else
		waiter = (omapi_waiter_object_t *)0;

	do {
		status = omapi_one_dispatch ((omapi_object_t *)waiter, t);
		if (status != ISC_R_SUCCESS) {
#ifdef DEBUG_PROTOCOL
			log_debug ("- call to omapi_one_dispatch failed: %s",
				   isc_result_totext (status));
#endif
			/* Break out on failure, to ensure we free up the waiter(s) */
			break;
		}
	} while (!waiter || !waiter -> ready);


	if (waiter -> outer) {
		if (waiter -> outer -> inner) {
			omapi_object_dereference (&waiter -> outer -> inner,
						  MDL);
			if (waiter -> inner)
				omapi_object_reference
					(&waiter -> outer -> inner,
					 waiter -> inner, MDL);
		}
		omapi_object_dereference (&waiter -> outer, MDL);
	}
	if (waiter -> inner)
		omapi_object_dereference (&waiter -> inner, MDL);

	if (status == ISC_R_SUCCESS) {
		/* If the invocation worked, return the server's
		 * execution status */
		status = waiter -> waitstatus;
	}

	omapi_waiter_dereference (&waiter, MDL);
	return status;
}

isc_result_t omapi_one_dispatch (omapi_object_t *wo,
				 struct timeval *t)
{
#ifdef DEBUG_PROTOCOL
        log_debug ("omapi_one_dispatch()");
#endif
	fd_set r, w, x, rr, ww, xx;
	int max = 0;
	int count;
	int desc;
	struct timeval now, to;
	omapi_io_object_t *io, *prev, *next;
	omapi_waiter_object_t *waiter;
	omapi_object_t *tmp = (omapi_object_t *)0;

	if (!wo || wo -> type != omapi_type_waiter)
		waiter = (omapi_waiter_object_t *)0;
	else
		waiter = (omapi_waiter_object_t *)wo;

	FD_ZERO (&x);

	/* First, see if the timeout has expired, and if so return. */
	if (t) {
		gettimeofday (&now, (struct timezone *)0);
		cur_tv.tv_sec = now.tv_sec;
		cur_tv.tv_usec = now.tv_usec;
		if (now.tv_sec > t -> tv_sec ||
		    (now.tv_sec == t -> tv_sec && now.tv_usec >= t -> tv_usec))
			return ISC_R_TIMEDOUT;

		/* We didn't time out, so figure out how long until
		   we do. */
		to.tv_sec = t -> tv_sec - now.tv_sec;
		to.tv_usec = t -> tv_usec - now.tv_usec;
		if (to.tv_usec < 0) {
			to.tv_usec += 1000000;
			to.tv_sec--;
		}

		/* It is possible for the timeout to get set larger than
		   the largest time select() is willing to accept.
		   Restricting the timeout to a maximum of one day should
		   work around this.  -DPN.  (Ref: Bug #416) */
		if (to.tv_sec > (60 * 60 * 24))
			to.tv_sec = 60 * 60 * 24;
	}

	/* If the object we're waiting on has reached completion,
	   return now. */
	if (waiter && waiter -> ready)
		return ISC_R_SUCCESS;

      again:
	/* If we have no I/O state, we can't proceed. */
	if (!(io = omapi_io_states.next))
		return ISC_R_NOMORE;

	/* Set up the read and write masks. */
	FD_ZERO (&r);
	FD_ZERO (&w);

	for (; io; io = io -> next) {
		/* Check for a read socket.   If we shouldn't be
		   trying to read for this I/O object, either there
		   won't be a readfd function, or it'll return -1. */
		if (io -> readfd && io -> inner &&
		    (desc = (*(io -> readfd)) (io -> inner)) >= 0) {
			FD_SET (desc, &r);
			if (desc > max)
				max = desc;
		}

		/* Same deal for write fdets. */
		if (io -> writefd && io -> inner &&
		    (desc = (*(io -> writefd)) (io -> inner)) >= 0) {
			/* This block avoids adding writefds that are already connected
			 * but that do not have data waiting to write.  This avoids
			 * select() calls dropping immediately simply because the
			 * the writefd is ready to write.  Without this synchronous
			 * waiting becomes CPU intensive polling */
			if (io->inner && io->inner->type == omapi_type_connection) {
				omapi_connection_object_t* c;
				c = (omapi_connection_object_t *)(io->inner);
				if (c->state == omapi_connection_connected && c->out_bytes == 0) {
					/* We are already connected and have no data waiting to
					 * be written, so we avoid registering the fd. */
#ifdef DEBUG_PROTOCOL
					log_debug ("--- Connected, nothing to write, skip writefd\n");
#endif
					continue;
				}
			}


			FD_SET (desc, &w);
			if (desc > max)
				max = desc;
		}
	}

	/* poll if all reader are dry */
	now.tv_sec = 0;
	now.tv_usec = 0;
	rr=r;
	ww=w;
	xx=x;

	/* poll once */
	count = select(max + 1, &r, &w, &x, &now);
	if (!count) {
		/* We are dry now */
		trigger_event(&rw_queue_empty);
		/* Wait for a packet or a timeout... XXX */
		r = rr;
		w = ww;
		x = xx;

#ifdef DEBUG_PROTOCOL
		if (t) {
			log_debug ("  calling select with timout: %u.%u secs",
			   	   (unsigned int)(to.tv_sec),
			   	   (unsigned int)(to.tv_usec));
		}
#endif
		count = select(max + 1, &r, &w, &x, t ? &to : NULL);
	}

	/* Get the current time... */
	gettimeofday (&cur_tv, (struct timezone *)0);

	/* We probably have a bad file descriptor.   Figure out which one.
	   When we find it, call the reaper function on it, which will
	   maybe make it go away, and then try again. */
	if (count < 0) {
		struct timeval t0;
		omapi_io_object_t *prev = (omapi_io_object_t *)0;
		io = (omapi_io_object_t *)0;
		if (omapi_io_states.next)
			omapi_io_reference (&io, omapi_io_states.next, MDL);

		while (io) {
			omapi_object_t *obj;
			FD_ZERO (&r);
			FD_ZERO (&w);
			t0.tv_sec = t0.tv_usec = 0;

			if (io -> readfd && io -> inner &&
			    (desc = (*(io -> readfd)) (io -> inner)) >= 0) {
			    FD_SET (desc, &r);
			    count = select (desc + 1, &r, &w, &x, &t0);
			   bogon:
			    if (count < 0) {
				log_error ("Bad descriptor %d.", desc);
				for (obj = (omapi_object_t *)io;
				     obj -> outer;
				     obj = obj -> outer)
					;
				for (; obj; obj = obj -> inner) {
				    omapi_value_t *ov;
				    int len;
				    const char *s;
				    ov = (omapi_value_t *)0;
				    omapi_get_value_str (obj,
							 (omapi_object_t *)0,
							 "name", &ov);
				    if (ov && ov -> value &&
					(ov -> value -> type ==
					 omapi_datatype_string)) {
					s = (char *)
						ov -> value -> u.buffer.value;
					len = ov -> value -> u.buffer.len;
				    } else {
					s = "";
					len = 0;
				    }
				    log_error ("Object %lx %s%s%.*s",
					       (unsigned long)obj,
					       obj -> type -> name,
					       len ? " " : "",
					       len, s);
				    if (len)
					omapi_value_dereference (&ov, MDL);
				}
				(*(io -> reaper)) (io -> inner);
				if (prev) {
				    omapi_io_dereference (&prev -> next, MDL);
				    if (io -> next)
					omapi_io_reference (&prev -> next,
							    io -> next, MDL);
				} else {
				    omapi_io_dereference
					    (&omapi_io_states.next, MDL);
				    if (io -> next)
					omapi_io_reference
						(&omapi_io_states.next,
						 io -> next, MDL);
				}
				omapi_io_dereference (&io, MDL);
				goto again;
			    }
			}

			FD_ZERO (&r);
			FD_ZERO (&w);
			t0.tv_sec = t0.tv_usec = 0;

			/* Same deal for write fdets. */
			if (io -> writefd && io -> inner &&
			    (desc = (*(io -> writefd)) (io -> inner)) >= 0) {
				FD_SET (desc, &w);
				count = select (desc + 1, &r, &w, &x, &t0);
				if (count < 0)
					goto bogon;
			}
			if (prev)
				omapi_io_dereference (&prev, MDL);
			omapi_io_reference (&prev, io, MDL);
			omapi_io_dereference (&io, MDL);
			if (prev -> next)
			    omapi_io_reference (&io, prev -> next, MDL);
		}
		if (prev)
			omapi_io_dereference (&prev, MDL);

	}

	for (io = omapi_io_states.next; io; io = io -> next) {
		if (!io -> inner)
			continue;
		omapi_object_reference (&tmp, io -> inner, MDL);
		/* Check for a read descriptor, and if there is one,
		   see if we got input on that socket. */
		if (io -> readfd &&
		    (desc = (*(io -> readfd)) (tmp)) >= 0) {
			if (FD_ISSET (desc, &r)) {
				((*(io -> reader)) (tmp));
			}
		}

		/* Same deal for write descriptors. */
		if (io -> writefd &&
		    (desc = (*(io -> writefd)) (tmp)) >= 0)
		{
			if (FD_ISSET (desc, &w)) {
				((*(io -> writer)) (tmp));
			}
		}
		omapi_object_dereference (&tmp, MDL);
	}

	/* Now check for I/O handles that are no longer valid,
	   and remove them from the list. */
	prev = NULL;
	io = NULL;
	if (omapi_io_states.next != NULL) {
		omapi_io_reference(&io, omapi_io_states.next, MDL);
	}
	while (io != NULL) {
		if ((io->inner == NULL) ||
		    ((io->reaper != NULL) &&
		     ((io->reaper)(io->inner) != ISC_R_SUCCESS)))
		{

			omapi_io_object_t *tmp = NULL;
			/* Save a reference to the next
			   pointer, if there is one. */
			if (io->next != NULL) {
				omapi_io_reference(&tmp, io->next, MDL);
				omapi_io_dereference(&io->next, MDL);
			}
			if (prev != NULL) {
				omapi_io_dereference(&prev->next, MDL);
				if (tmp != NULL)
					omapi_io_reference(&prev->next,
							   tmp, MDL);
			} else {
				omapi_io_dereference(&omapi_io_states.next,
						     MDL);
				if (tmp != NULL)
					omapi_io_reference
					    (&omapi_io_states.next,
					     tmp, MDL);
				else
					omapi_signal_in(
							(omapi_object_t *)
						 	&omapi_io_states,
							"ready");
			}
			if (tmp != NULL)
				omapi_io_dereference(&tmp, MDL);

		} else {

			if (prev != NULL) {
				omapi_io_dereference(&prev, MDL);
			}
			omapi_io_reference(&prev, io, MDL);
		}

		/*
		 * Equivalent to:
		 *   io = io->next
		 * But using our reference counting voodoo.
		 */
		next = NULL;
		if (io->next != NULL) {
			omapi_io_reference(&next, io->next, MDL);
		}
		omapi_io_dereference(&io, MDL);
		if (next != NULL) {
			omapi_io_reference(&io, next, MDL);
			omapi_io_dereference(&next, MDL);
		}
	}
	if (prev != NULL) {
		omapi_io_dereference(&prev, MDL);
	}

	return ISC_R_SUCCESS;
}

isc_result_t omapi_io_set_value (omapi_object_t *h,
				 omapi_object_t *id,
				 omapi_data_string_t *name,
				 omapi_typed_data_t *value)
{
	if (h -> type != omapi_type_io_object)
		return DHCP_R_INVALIDARG;

	if (h -> inner && h -> inner -> type -> set_value)
		return (*(h -> inner -> type -> set_value))
			(h -> inner, id, name, value);
	return ISC_R_NOTFOUND;
}

isc_result_t omapi_io_get_value (omapi_object_t *h,
				 omapi_object_t *id,
				 omapi_data_string_t *name,
				 omapi_value_t **value)
{
	if (h -> type != omapi_type_io_object)
		return DHCP_R_INVALIDARG;

	if (h -> inner && h -> inner -> type -> get_value)
		return (*(h -> inner -> type -> get_value))
			(h -> inner, id, name, value);
	return ISC_R_NOTFOUND;
}

/* omapi_io_destroy (object, MDL);
 *
 *	Find the requested IO [object] and remove it from the list of io
 * states, causing the cleanup functions to destroy it.  Note that we must
 * hold a reference on the object while moving its ->next reference and
 * removing the reference in the chain to the target object...otherwise it
 * may be cleaned up from under us.
 */
isc_result_t omapi_io_destroy (omapi_object_t *h, const char *file, int line)
{
	omapi_io_object_t *obj = NULL, *p, *last = NULL, **holder;

	if (h -> type != omapi_type_io_object)
		return DHCP_R_INVALIDARG;

	/* remove from the list of I/O states */
	for (p = omapi_io_states.next; p; p = p -> next) {
		if (p == (omapi_io_object_t *)h) {
			omapi_io_reference (&obj, p, MDL);

			if (last)
				holder = &last -> next;
			else
				holder = &omapi_io_states.next;

			omapi_io_dereference (holder, MDL);

			if (obj -> next) {
				omapi_io_reference (holder, obj -> next, MDL);
				omapi_io_dereference (&obj -> next, MDL);
			}

			return omapi_io_dereference (&obj, MDL);
		}
		last = p;
	}

	return ISC_R_NOTFOUND;
}

isc_result_t omapi_io_signal_handler (omapi_object_t *h,
				      const char *name, va_list ap)
{
#ifdef DEBUG_PROTOCOL
        log_debug ("omapi_io_signal_handler(%s)", name);
#endif
	if (h -> type != omapi_type_io_object)
		return DHCP_R_INVALIDARG;

	if (h -> inner && h -> inner -> type -> signal_handler)
		return (*(h -> inner -> type -> signal_handler)) (h -> inner,
								  name, ap);
	return ISC_R_NOTFOUND;
}

isc_result_t omapi_io_stuff_values (omapi_object_t *c,
				    omapi_object_t *id,
				    omapi_object_t *i)
{
	if (i -> type != omapi_type_io_object)
		return DHCP_R_INVALIDARG;

	if (i -> inner && i -> inner -> type -> stuff_values)
		return (*(i -> inner -> type -> stuff_values)) (c, id,
								i -> inner);
	return ISC_R_SUCCESS;
}

isc_result_t omapi_waiter_signal_handler (omapi_object_t *h,
					  const char *name, va_list ap)
{
	omapi_waiter_object_t *waiter;

#ifdef DEBUG_PROTOCOL
        log_debug ("omapi_waiter_signal_handler(%s)", name);
#endif
	if (h -> type != omapi_type_waiter)
		return DHCP_R_INVALIDARG;

	if (!strcmp (name, "ready")) {
		waiter = (omapi_waiter_object_t *)h;
		waiter -> ready = 1;
		waiter -> waitstatus = ISC_R_SUCCESS;
		return ISC_R_SUCCESS;
	}

	if (!strcmp(name, "status")) {
		waiter = (omapi_waiter_object_t *)h;
		waiter->ready = 1;
		waiter->waitstatus = va_arg(ap, isc_result_t);
		return ISC_R_SUCCESS;
	}

	if (!strcmp (name, "disconnect")) {
		waiter = (omapi_waiter_object_t *)h;
		waiter -> ready = 1;
		waiter -> waitstatus = DHCP_R_CONNRESET;
		return ISC_R_SUCCESS;
	}

	if (h -> inner && h -> inner -> type -> signal_handler)
		return (*(h -> inner -> type -> signal_handler)) (h -> inner,
								  name, ap);
	return ISC_R_NOTFOUND;
}

/** @brief calls a given function on every object
 *
 * @param func function to be called
 * @param p parameter to be passed to each function instance
 *
 * @return result (ISC_R_SUCCESS if successful, error code otherwise)
 */
isc_result_t omapi_io_state_foreach (isc_result_t (*func) (omapi_object_t *,
							   void *),
				     void *p)
{
	omapi_io_object_t *io = NULL;
	isc_result_t status;
	omapi_io_object_t *next = NULL;

	/*
	 * This just calls func on every inner object on the list. It would
	 * be much simpler in general case, but one of the operations could be
	 * release of the objects. Therefore we need to ref count the io and
	 * io->next pointers.
	 */

	if (omapi_io_states.next) {
		omapi_object_reference((omapi_object_t**)&io,
				       (omapi_object_t*)omapi_io_states.next,
				       MDL);
	}

	while(io) {
	    /* If there's a next object, save it */
	    if (io->next) {
		omapi_object_reference((omapi_object_t**)&next,
				       (omapi_object_t*)io->next, MDL);
	    }
	    if (io->inner) {
		status = (*func) (io->inner, p);
		if (status != ISC_R_SUCCESS) {
		    /* Something went wrong. Let's stop using io & next pointer
		     * and bail out */
		    omapi_object_dereference((omapi_object_t**)&io, MDL);
		    if (next) {
			omapi_object_dereference((omapi_object_t**)&next, MDL);
		    }
		    return status;
		}
	    }
	    /* Update the io pointer and free the next pointer */
	    omapi_object_dereference((omapi_object_t**)&io, MDL);
	    if (next) {
		omapi_object_reference((omapi_object_t**)&io,
				       (omapi_object_t*)next,
				       MDL);
		omapi_object_dereference((omapi_object_t**)&next, MDL);
	    }
	}

	/*
	 * The only way to get here is when next is NULL. There's no need
	 * to dereference it.
	 */
	return ISC_R_SUCCESS;
}