summaryrefslogtreecommitdiff
path: root/omapip/connection.c
blob: 7fffb5fe5317a756fc580e4a47405cf2047dce31 (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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
/* connection.c

   Subroutines for dealing with connections. */

/*
 * 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 <isc/util.h>
#include <omapip/omapip_p.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>
#include <errno.h>

#if defined (TRACING)
static void trace_connect_input (trace_type_t *, unsigned, char *);
static void trace_connect_stop (trace_type_t *);
static void trace_disconnect_input (trace_type_t *, unsigned, char *);
static void trace_disconnect_stop (trace_type_t *);
trace_type_t *trace_connect;
trace_type_t *trace_disconnect;
extern omapi_array_t *trace_listeners;
#endif
static isc_result_t omapi_connection_connect_internal (omapi_object_t *);

static isc_result_t ctring_from_attribute(omapi_object_t *obj, char *attr_name,
                                          char **cstr);

OMAPI_OBJECT_ALLOC (omapi_connection,
		    omapi_connection_object_t, omapi_type_connection)

isc_result_t omapi_connect (omapi_object_t *c,
			    const char *server_name,
			    unsigned port)
{
	struct hostent *he;
	unsigned i, hix;
	omapi_addr_list_t *addrs = (omapi_addr_list_t *)0;
	struct in_addr foo;
	isc_result_t status;

#ifdef DEBUG_PROTOCOL
	log_debug ("omapi_connect(%s, port=%d)", server_name, port);
#endif

	if (!inet_aton (server_name, &foo)) {
		/* If we didn't get a numeric address, try for a domain
		   name.  It's okay for this call to block. */
		he = gethostbyname (server_name);
		if (!he)
			return DHCP_R_HOSTUNKNOWN;
		for (i = 0; he -> h_addr_list [i]; i++)
			;
		if (i == 0)
			return DHCP_R_HOSTUNKNOWN;
		hix = i;

		status = omapi_addr_list_new (&addrs, hix, MDL);
		if (status != ISC_R_SUCCESS)
			return status;
		for (i = 0; i < hix; i++) {
			addrs -> addresses [i].addrtype = he -> h_addrtype;
			addrs -> addresses [i].addrlen = he -> h_length;
			memcpy (addrs -> addresses [i].address,
				he -> h_addr_list [i],
				(unsigned)he -> h_length);
			addrs -> addresses [i].port = port;
		}
	} else {
		status = omapi_addr_list_new (&addrs, 1, MDL);
		if (status != ISC_R_SUCCESS)
			return status;
		addrs -> addresses [0].addrtype = AF_INET;
		addrs -> addresses [0].addrlen = sizeof foo;
		memcpy (addrs -> addresses [0].address, &foo, sizeof foo);
		addrs -> addresses [0].port = port;
	}
	status = omapi_connect_list (c, addrs, (omapi_addr_t *)0);
	omapi_addr_list_dereference (&addrs, MDL);
	return status;
}

isc_result_t omapi_connect_list (omapi_object_t *c,
				 omapi_addr_list_t *remote_addrs,
				 omapi_addr_t *local_addr)
{
	isc_result_t status;
	omapi_connection_object_t *obj;
	int flag;
	struct sockaddr_in local_sin;

	obj = (omapi_connection_object_t *)0;
	status = omapi_connection_allocate (&obj, MDL);
	if (status != ISC_R_SUCCESS)
		return status;

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

	/* Store the address list on the object. */
	omapi_addr_list_reference (&obj -> connect_list, remote_addrs, MDL);
	obj -> cptr = 0;
	obj -> state = omapi_connection_unconnected;

#if defined (TRACING)
	/* If we're playing back, don't actually try to connect - just leave
	   the object available for a subsequent connect or disconnect. */
	if (!trace_playback ()) {
#endif
		/* Create a socket on which to communicate. */
		obj -> socket =
			socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (obj -> socket < 0) {
			omapi_connection_dereference (&obj, MDL);
			if (errno == EMFILE || errno == ENFILE
			    || errno == ENOBUFS)
				return ISC_R_NORESOURCES;
			return ISC_R_UNEXPECTED;
		}

		/* Set up the local address, if any. */
		if (local_addr) {
			/* Only do TCPv4 so far. */
			if (local_addr -> addrtype != AF_INET) {
				close(obj->socket);
				omapi_connection_dereference (&obj, MDL);
				return DHCP_R_INVALIDARG;
			}
			local_sin.sin_port = htons (local_addr -> port);
			memcpy (&local_sin.sin_addr,
				local_addr -> address,
				local_addr -> addrlen);
#if defined (HAVE_SA_LEN)
			local_sin.sin_len = sizeof local_addr;
#endif
			local_sin.sin_family = AF_INET;
			memset (&local_sin.sin_zero, 0,
				sizeof local_sin.sin_zero);

			if (bind (obj -> socket, (struct sockaddr *)&local_sin,
				  sizeof local_sin) < 0) {
				omapi_connection_object_t **objp = &obj;
				omapi_object_t **o = (omapi_object_t **)objp;
				close(obj->socket);
				omapi_object_dereference(o, MDL);
				if (errno == EADDRINUSE)
					return ISC_R_ADDRINUSE;
				if (errno == EADDRNOTAVAIL)
					return ISC_R_ADDRNOTAVAIL;
				if (errno == EACCES)
					return ISC_R_NOPERM;
				return ISC_R_UNEXPECTED;
			}
			obj -> local_addr = local_sin;
		}

#if defined(F_SETFD)
		if (fcntl (obj -> socket, F_SETFD, 1) < 0) {
			close (obj -> socket);
			omapi_connection_dereference (&obj, MDL);
			return ISC_R_UNEXPECTED;
		}
#endif

		/* Set the SO_REUSEADDR flag (this should not fail). */
		flag = 1;
		if (setsockopt (obj -> socket, SOL_SOCKET, SO_REUSEADDR,
				(char *)&flag, sizeof flag) < 0) {
			omapi_connection_dereference (&obj, MDL);
			return ISC_R_UNEXPECTED;
		}

		/* Set the file to nonblocking mode. */
		if (fcntl (obj -> socket, F_SETFL, O_NONBLOCK) < 0) {
			omapi_connection_dereference (&obj, MDL);
			return ISC_R_UNEXPECTED;
		}

#ifdef SO_NOSIGPIPE
		/*
		 * If available stop the OS from killing our
		 * program on a SIGPIPE failure
		 */
		flag = 1;
		if (setsockopt(obj->socket, SOL_SOCKET, SO_NOSIGPIPE,
			       (char *)&flag, sizeof(flag)) < 0) {
			omapi_connection_dereference (&obj, MDL);
			return ISC_R_UNEXPECTED;
		}
#endif

		status = (omapi_register_io_object
			  ((omapi_object_t *)obj,
			   0, omapi_connection_writefd,
			   0, omapi_connection_connect,
			   omapi_connection_reaper));
		if (status != ISC_R_SUCCESS)
			goto out;
		status = omapi_connection_connect_internal ((omapi_object_t *)
							    obj);
		/*
		 * inprogress is the same as success but used
		 * to indicate to the dispatch code that we should
		 * mark the socket as requiring more attention.
		 * Routines calling this function should handle
		 * success properly.
		 */
		if (status == ISC_R_INPROGRESS) {
			status = ISC_R_SUCCESS;
		}
#if defined (TRACING)
	}
	omapi_connection_register (obj, MDL);
#endif

      out:
	omapi_connection_dereference (&obj, MDL);
	return status;
}

#if defined (TRACING)
omapi_array_t *omapi_connections;

OMAPI_ARRAY_TYPE(omapi_connection, omapi_connection_object_t)

void omapi_connection_trace_setup (void) {
	trace_connect = trace_type_register ("connect", (void *)0,
					     trace_connect_input,
					     trace_connect_stop, MDL);
	trace_disconnect = trace_type_register ("disconnect", (void *)0,
						trace_disconnect_input,
						trace_disconnect_stop, MDL);
}

void omapi_connection_register (omapi_connection_object_t *obj,
				const char *file, int line)
{
	isc_result_t status;
	trace_iov_t iov [6];
	int iov_count = 0;
	int32_t connect_index, listener_index;
	static int32_t index;

	if (!omapi_connections) {
		status = omapi_connection_array_allocate (&omapi_connections,
							  file, line);
		if (status != ISC_R_SUCCESS)
			return;
	}

	status = omapi_connection_array_extend (omapi_connections, obj,
						(int *)0, file, line);
	if (status != ISC_R_SUCCESS) {
		obj -> index = -1;
		return;
	}

#if defined (TRACING)
	if (trace_record ()) {
		/* Connection registration packet:

		     int32_t index
		     int32_t listener_index [-1 means no listener]
		   u_int16_t remote_port
		   u_int16_t local_port
		   u_int32_t remote_addr
		   u_int32_t local_addr */

		connect_index = htonl (index);
		index++;
		if (obj -> listener)
			listener_index = htonl (obj -> listener -> index);
		else
			listener_index = htonl (-1);
		iov [iov_count].buf = (char *)&connect_index;
		iov [iov_count++].len = sizeof connect_index;
		iov [iov_count].buf = (char *)&listener_index;
		iov [iov_count++].len = sizeof listener_index;
		iov [iov_count].buf = (char *)&obj -> remote_addr.sin_port;
		iov [iov_count++].len = sizeof obj -> remote_addr.sin_port;
		iov [iov_count].buf = (char *)&obj -> local_addr.sin_port;
		iov [iov_count++].len = sizeof obj -> local_addr.sin_port;
		iov [iov_count].buf = (char *)&obj -> remote_addr.sin_addr;
		iov [iov_count++].len = sizeof obj -> remote_addr.sin_addr;
		iov [iov_count].buf = (char *)&obj -> local_addr.sin_addr;
		iov [iov_count++].len = sizeof obj -> local_addr.sin_addr;

		status = trace_write_packet_iov (trace_connect,
						 iov_count, iov, file, line);
	}
#endif
}

static void trace_connect_input (trace_type_t *ttype,
				 unsigned length, char *buf)
{
	struct sockaddr_in remote, local;
	int32_t connect_index, listener_index;
	char *s = buf;
	omapi_connection_object_t *obj;
	isc_result_t status;
	int i;

	if (length != ((sizeof connect_index) +
		       (sizeof remote.sin_port) +
		       (sizeof remote.sin_addr)) * 2) {
		log_error ("Trace connect: invalid length %d", length);
		return;
	}

	memset (&remote, 0, sizeof remote);
	memset (&local, 0, sizeof local);
	memcpy (&connect_index, s, sizeof connect_index);
	s += sizeof connect_index;
	memcpy (&listener_index, s, sizeof listener_index);
	s += sizeof listener_index;
	memcpy (&remote.sin_port, s, sizeof remote.sin_port);
	s += sizeof remote.sin_port;
	memcpy (&local.sin_port, s, sizeof local.sin_port);
	s += sizeof local.sin_port;
	memcpy (&remote.sin_addr, s, sizeof remote.sin_addr);
	s += sizeof remote.sin_addr;
	memcpy (&local.sin_addr, s, sizeof local.sin_addr);
	s += sizeof local.sin_addr;
	POST(s);

	connect_index = ntohl (connect_index);
	listener_index = ntohl (listener_index);

	/* If this was a connect to a listener, then we just slap together
	   a new connection. */
	if (listener_index != -1) {
		omapi_listener_object_t *listener;
		listener = (omapi_listener_object_t *)0;
		omapi_array_foreach_begin (trace_listeners,
					   omapi_listener_object_t, lp) {
			if (lp -> address.sin_port == local.sin_port) {
				omapi_listener_reference (&listener, lp, MDL);
				omapi_listener_dereference (&lp, MDL);
				break;
			}
		} omapi_array_foreach_end (trace_listeners,
					   omapi_listener_object_t, lp);
		if (!listener) {
			log_error ("%s%ld, addr %s, port %d",
				   "Spurious traced listener connect - index ",
				   (long int)listener_index,
				   inet_ntoa (local.sin_addr),
				   ntohs (local.sin_port));
			return;
		}
		obj = (omapi_connection_object_t *)0;
		status = omapi_listener_connect (&obj, listener, -1, &remote);
		if (status != ISC_R_SUCCESS) {
			log_error ("traced listener connect: %s",
				   isc_result_totext (status));
		}
		if (obj)
			omapi_connection_dereference (&obj, MDL);
		omapi_listener_dereference (&listener, MDL);
		return;
	}

	/* Find the matching connect object, if there is one. */
	omapi_array_foreach_begin (omapi_connections,
				   omapi_connection_object_t, lp) {
	    for (i = 0; (lp->connect_list &&
			 i < lp->connect_list->count); i++) {
		    if (!memcmp (&remote.sin_addr,
				 &lp->connect_list->addresses[i].address,
				 sizeof remote.sin_addr) &&
			(ntohs (remote.sin_port) ==
			 lp->connect_list->addresses[i].port)) {
			    lp->state = omapi_connection_connected;
			    lp->remote_addr = remote;
			    lp->remote_addr.sin_family = AF_INET;
			    omapi_addr_list_dereference(&lp->connect_list, MDL);
			    lp->index = connect_index;
			    status = omapi_signal_in((omapi_object_t *)lp,
						     "connect");
			    omapi_connection_dereference (&lp, MDL);
			    return;
		    }
		}
	} omapi_array_foreach_end (omapi_connections,
				   omapi_connection_object_t, lp);

	log_error ("Spurious traced connect - index %ld, addr %s, port %d",
		   (long int)connect_index, inet_ntoa (remote.sin_addr),
		   ntohs (remote.sin_port));
	return;
}

static void trace_connect_stop (trace_type_t *ttype) { }

static void trace_disconnect_input (trace_type_t *ttype,
				    unsigned length, char *buf)
{
	int32_t *index;
	if (length != sizeof *index) {
		log_error ("trace disconnect: wrong length %d", length);
		return;
	}

	index = (int32_t *)buf;

	omapi_array_foreach_begin (omapi_connections,
				   omapi_connection_object_t, lp) {
		if (lp -> index == ntohl (*index)) {
			omapi_disconnect ((omapi_object_t *)lp, 1);
			omapi_connection_dereference (&lp, MDL);
			return;
		}
	} omapi_array_foreach_end (omapi_connections,
				   omapi_connection_object_t, lp);

	log_error ("trace disconnect: no connection matching index %ld",
		   (long int)ntohl (*index));
}

static void trace_disconnect_stop (trace_type_t *ttype) { }
#endif

/* Disconnect a connection object from the remote end.   If force is nonzero,
   close the connection immediately.   Otherwise, shut down the receiving end
   but allow any unsent data to be sent before actually closing the socket. */

isc_result_t omapi_disconnect (omapi_object_t *h,
			       int force)
{
	omapi_connection_object_t *c;

#ifdef DEBUG_PROTOCOL
	log_debug ("omapi_disconnect(force=%d)", force);
#endif

	c = (omapi_connection_object_t *)h;
	if (c -> type != omapi_type_connection)
		return DHCP_R_INVALIDARG;

#if defined (TRACING)
	if (trace_record ()) {
		isc_result_t status;
		int32_t index;

		index = htonl (c -> index);
		status = trace_write_packet (trace_disconnect,
					     sizeof index, (char *)&index,
					     MDL);
		if (status != ISC_R_SUCCESS) {
			trace_stop ();
			log_error ("trace_write_packet: %s",
				   isc_result_totext (status));
		}
	}
	if (!trace_playback ()) {
#endif
		if (!force) {
			/* If we're already disconnecting, we don't have to do
			   anything. */
			if (c -> state == omapi_connection_disconnecting)
				return ISC_R_SUCCESS;

			/* Try to shut down the socket - this sends a FIN to
			   the remote end, so that it won't send us any more
			   data.   If the shutdown succeeds, and we still
			   have bytes left to write, defer closing the socket
			   until that's done. */
			if (!shutdown (c -> socket, SHUT_RD)) {
				if (c -> out_bytes > 0) {
					c -> state =
						omapi_connection_disconnecting;
					return ISC_R_SUCCESS;
				}
			}
		}
		close (c -> socket);
#if defined (TRACING)
	}
#endif
	c -> state = omapi_connection_closed;

#if 0
	/*
	 * Disconnecting from the I/O object seems incorrect as it doesn't
	 * cause the I/O object to be cleaned and released.  Previous to
	 * using the isc socket library this wouldn't have caused a problem
	 * with the socket library we would have a reference to a closed
	 * socket.  Instead we now do an unregister to properly free the
	 * I/O object.
	 */

	/* Disconnect from I/O object, if any. */
	if (h -> outer) {
		if (h -> outer -> inner)
			omapi_object_dereference (&h -> outer -> inner, MDL);
		omapi_object_dereference (&h -> outer, MDL);
	}
#else
	if (h->outer) {
		omapi_unregister_io_object(h);
	}
#endif

	/* If whatever created us registered a signal handler, send it
	   a disconnect signal. */
	omapi_signal (h, "disconnect", h);

	/* Disconnect from protocol object, if any. */
	if (h->inner != NULL) {
		if (h->inner->outer != NULL) {
			omapi_object_dereference(&h->inner->outer, MDL);
		}
		omapi_object_dereference(&h->inner, MDL);
	}

	/* XXX: the code to free buffers should be in the dereference
		function, but there is no special-purpose function to
		dereference connections, so these just get leaked */
	/* Free any buffers */
	if (c->inbufs != NULL) {
		omapi_buffer_dereference(&c->inbufs, MDL);
	}
	c->in_bytes = 0;
	if (c->outbufs != NULL) {
		omapi_buffer_dereference(&c->outbufs, MDL);
	}
	c->out_bytes = 0;

	return ISC_R_SUCCESS;
}

isc_result_t omapi_connection_require (omapi_object_t *h, unsigned bytes)
{
	omapi_connection_object_t *c;

	if (h -> type != omapi_type_connection)
		return DHCP_R_INVALIDARG;
	c = (omapi_connection_object_t *)h;

	c -> bytes_needed = bytes;
	if (c -> bytes_needed <= c -> in_bytes) {
		return ISC_R_SUCCESS;
	}
	return DHCP_R_NOTYET;
}

/* Return the socket on which the dispatcher should wait for readiness
   to read, for a connection object.  */
int omapi_connection_readfd (omapi_object_t *h)
{
	omapi_connection_object_t *c;
	if (h -> type != omapi_type_connection)
		return -1;
	c = (omapi_connection_object_t *)h;
	if (c -> state != omapi_connection_connected)
		return -1;
	return c -> socket;
}

/*
 * Return the socket on which the dispatcher should wait for readiness
 * to write, for a connection object.  When bytes are buffered we should
 * also poke the dispatcher to tell it to start or re-start watching the
 * socket.
 */
int omapi_connection_writefd (omapi_object_t *h)
{
	omapi_connection_object_t *c;
	if (h -> type != omapi_type_connection)
		return -1;
	c = (omapi_connection_object_t *)h;
	return c->socket;
}

isc_result_t omapi_connection_connect (omapi_object_t *h)
{
	isc_result_t status;

	/*
	 * We use the INPROGRESS status to indicate that
	 * we want more from the socket.  In this case we
	 * have now connected and are trying to write to
	 * the socket for the first time.  For the signaling
	 * code this is the same as a SUCCESS so we don't
	 * pass it on as a signal.
	 */
	status = omapi_connection_connect_internal (h);
	if (status == ISC_R_INPROGRESS)
		return ISC_R_INPROGRESS;

	if (status != ISC_R_SUCCESS)
		omapi_signal (h, "status", status);

	return ISC_R_SUCCESS;
}

static isc_result_t omapi_connection_connect_internal (omapi_object_t *h)
{
	int error = 0;
	omapi_connection_object_t *c;
	socklen_t sl;
	isc_result_t status;

	if (h -> type != omapi_type_connection)
		return DHCP_R_INVALIDARG;
	c = (omapi_connection_object_t *)h;

	if (c -> state == omapi_connection_connecting) {
		sl = sizeof error;
		if (getsockopt (c -> socket, SOL_SOCKET, SO_ERROR,
				(char *)&error, &sl) < 0) {
			omapi_disconnect (h, 1);
			return ISC_R_SUCCESS;
		}
		if (!error)
			c -> state = omapi_connection_connected;
	}
	if (c -> state == omapi_connection_connecting ||
	    c -> state == omapi_connection_unconnected) {
		if (c -> cptr >= c -> connect_list -> count) {
			switch (error) {
			      case ECONNREFUSED:
				status = ISC_R_CONNREFUSED;
				break;
			      case ENETUNREACH:
				status = ISC_R_NETUNREACH;
				break;
			      default:
				status = uerr2isc (error);
				break;
			}
			omapi_disconnect (h, 1);
			return status;
		}

		if (c -> connect_list -> addresses [c -> cptr].addrtype !=
		    AF_INET) {
			omapi_disconnect (h, 1);
			return DHCP_R_INVALIDARG;
		}

		memcpy (&c -> remote_addr.sin_addr,
			&c -> connect_list -> addresses [c -> cptr].address,
			sizeof c -> remote_addr.sin_addr);
		c -> remote_addr.sin_family = AF_INET;
		c -> remote_addr.sin_port =
		       htons (c -> connect_list -> addresses [c -> cptr].port);
#if defined (HAVE_SA_LEN)
		c -> remote_addr.sin_len = sizeof c -> remote_addr;
#endif
		memset (&c -> remote_addr.sin_zero, 0,
			sizeof c -> remote_addr.sin_zero);
		++c -> cptr;

		error = connect (c -> socket,
				 (struct sockaddr *)&c -> remote_addr,
				 sizeof c -> remote_addr);
		if (error < 0) {
			error = errno;
			if (error != EINPROGRESS) {
				omapi_disconnect (h, 1);
				switch (error) {
				      case ECONNREFUSED:
					status = ISC_R_CONNREFUSED;
					break;
				      case ENETUNREACH:
					status = ISC_R_NETUNREACH;
					break;
				      default:
					status = uerr2isc (error);
					break;
				}
				return status;
			}
			c -> state = omapi_connection_connecting;
			return DHCP_R_INCOMPLETE;
		}
		c -> state = omapi_connection_connected;
	}

	/* I don't know why this would fail, so I'm tempted not to test
	   the return value. */
	sl = sizeof (c -> local_addr);
	if (getsockname (c -> socket,
			 (struct sockaddr *)&c -> local_addr, &sl) < 0) {
	}

	/* Reregister with the I/O object.  If we don't already have an
	   I/O object this turns into a register call, otherwise we simply
	   modify the pointers in the I/O object. */

	status = omapi_reregister_io_object (h,
					     omapi_connection_readfd,
					     omapi_connection_writefd,
					     omapi_connection_reader,
					     omapi_connection_writer,
					     omapi_connection_reaper);

	if (status != ISC_R_SUCCESS) {
		omapi_disconnect (h, 1);
		return status;
	}

	omapi_signal_in (h, "connect");
	omapi_addr_list_dereference (&c -> connect_list, MDL);
	return ISC_R_INPROGRESS;
}

/* Reaper function for connection - if the connection is completely closed,
   reap it.   If it's in the disconnecting state, there were bytes left
   to write when the user closed it, so if there are now no bytes left to
   write, we can close it. */
isc_result_t omapi_connection_reaper (omapi_object_t *h)
{
	omapi_connection_object_t *c;

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

	c = (omapi_connection_object_t *)h;
	if (c -> state == omapi_connection_disconnecting &&
	    c -> out_bytes == 0) {
#ifdef DEBUG_PROTOCOL
		log_debug ("omapi_connection_reaper(): disconnect");
#endif
		omapi_disconnect (h, 1);
	}
	if (c -> state == omapi_connection_closed) {
#ifdef DEBUG_PROTOCOL
		log_debug ("omapi_connection_reaper(): closed");
#endif
		return ISC_R_NOTCONNECTED;
	}
	return ISC_R_SUCCESS;
}

static isc_result_t make_dst_key (dst_key_t **dst_key, omapi_object_t *a) {
	omapi_value_t *key = 0;
	char *name_str = 0;
	char *algorithm_str = 0;
	isc_result_t status = ISC_R_SUCCESS;

	/* Get the key name as a C string. */
	status = ctring_from_attribute(a, "name", &name_str);
	if (status == ISC_R_SUCCESS) {
		/* Get the algorithm name as a C string. */
		status = ctring_from_attribute(a, "algorithm", &algorithm_str);
		if (status == ISC_R_SUCCESS) {
			/* Get the key secret value */
			status = omapi_get_value_str(a, 0, "key", &key);
			if (status == ISC_R_SUCCESS) {
				/* Now let's try and create the key */
				status = isclib_make_dst_key(
						name_str,
						algorithm_str,
						key->value->u.buffer.value,
						key->value->u.buffer.len,
						dst_key);

				if (*dst_key == NULL) {
					status = ISC_R_NOMEMORY;
				}
			}
		}
	}

	if (name_str)
		dfree (name_str, MDL);
	if (algorithm_str)
		dfree (algorithm_str, MDL);
	if (key)
		omapi_value_dereference (&key, MDL);

	return status;
}

isc_result_t omapi_connection_sign_data (int mode,
					 dst_key_t *key,
					 void **context,
					 const unsigned char *data,
					 const unsigned len,
					 omapi_typed_data_t **result)
{
	omapi_typed_data_t *td = (omapi_typed_data_t *)0;
	isc_result_t status;
	dst_context_t **dctx = (dst_context_t **)context;

	/* Create the context for the dst module */
	if (mode & SIG_MODE_INIT) {
		status = dst_context_create(key, dhcp_gbl_ctx.mctx, dctx);
		if (status != ISC_R_SUCCESS) {
			return status;
		}
	}

	/* If we have any data add it to the context */
	if (len != 0) {
		isc_region_t region;
		region.base   = (unsigned char *)data;
		region.length = len;
		dst_context_adddata(*dctx, &region);
	}

	/* Finish the signature and clean up the context */
	if (mode & SIG_MODE_FINAL) {
		unsigned int sigsize;
		isc_buffer_t sigbuf;

		status = dst_key_sigsize(key, &sigsize);
		if (status != ISC_R_SUCCESS) {
			goto cleanup;
		}

		status = omapi_typed_data_new (MDL, &td,
					       omapi_datatype_data,
					       sigsize);
		if (status != ISC_R_SUCCESS) {
			goto cleanup;
		}

		isc_buffer_init(&sigbuf, td->u.buffer.value, td->u.buffer.len);
		status = dst_context_sign(*dctx, &sigbuf);
		if (status != ISC_R_SUCCESS) {
			goto cleanup;
		}

		if (result) {
			omapi_typed_data_reference (result, td, MDL);
		}

	cleanup:
		/* We are done with the context and the td.  On success
		 * the td is now referenced from result, on failure we
		 * don't need it any more */
		if (td) {
			omapi_typed_data_dereference (&td, MDL);
		}
		dst_context_destroy(dctx);
		return status;
	}

	return ISC_R_SUCCESS;
}

isc_result_t omapi_connection_output_auth_length (omapi_object_t *h,
						  unsigned *l)
{
	omapi_connection_object_t *c;

	if (h->type != omapi_type_connection)
		return DHCP_R_INVALIDARG;
	c = (omapi_connection_object_t *)h;

	if (c->out_key == NULL)
		return ISC_R_NOTFOUND;

	return(dst_key_sigsize(c->out_key, l));
}

isc_result_t omapi_connection_set_value (omapi_object_t *h,
					 omapi_object_t *id,
					 omapi_data_string_t *name,
					 omapi_typed_data_t *value)
{
	omapi_connection_object_t *c;
	isc_result_t status;

	if (h -> type != omapi_type_connection)
		return DHCP_R_INVALIDARG;
	c = (omapi_connection_object_t *)h;

	if (omapi_ds_strcmp (name, "input-authenticator") == 0) {
		if (value && value -> type != omapi_datatype_object)
			return DHCP_R_INVALIDARG;

		if (c -> in_context) {
			omapi_connection_sign_data (SIG_MODE_FINAL,
						    c -> in_key,
						    &c -> in_context,
						    0, 0,
						    (omapi_typed_data_t **) 0);
		}

		if (c->in_key != NULL) {
			dst_key_free(&c->in_key);
		}

		if (value) {
			status = make_dst_key (&c -> in_key,
					       value -> u.object);
			if (status != ISC_R_SUCCESS)
				return status;
		}

		return ISC_R_SUCCESS;
	}
	else if (omapi_ds_strcmp (name, "output-authenticator") == 0) {
		if (value && value -> type != omapi_datatype_object)
			return DHCP_R_INVALIDARG;

		if (c -> out_context) {
			omapi_connection_sign_data (SIG_MODE_FINAL,
						    c -> out_key,
						    &c -> out_context,
						    0, 0,
						    (omapi_typed_data_t **) 0);
		}

		if (c->out_key != NULL) {
			dst_key_free(&c->out_key);
		}

		if (value) {
			status = make_dst_key (&c -> out_key,
					       value -> u.object);
			if (status != ISC_R_SUCCESS)
				return status;
		}

		return ISC_R_SUCCESS;
	}

	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_connection_get_value (omapi_object_t *h,
					 omapi_object_t *id,
					 omapi_data_string_t *name,
					 omapi_value_t **value)
{
	omapi_connection_object_t *c;
	omapi_typed_data_t *td = (omapi_typed_data_t *)0;
	isc_result_t status;
	unsigned int sigsize;

	if (h -> type != omapi_type_connection)
		return DHCP_R_INVALIDARG;
	c = (omapi_connection_object_t *)h;

	if (omapi_ds_strcmp (name, "input-signature") == 0) {
		if (!c -> in_key || !c -> in_context)
			return ISC_R_NOTFOUND;

		status = omapi_connection_sign_data (SIG_MODE_FINAL,
						     c -> in_key,
						     &c -> in_context,
						     0, 0, &td);
		if (status != ISC_R_SUCCESS)
			return status;

		status = omapi_make_value (value, name, td, MDL);
		omapi_typed_data_dereference (&td, MDL);
		return status;

	} else if (omapi_ds_strcmp (name, "input-signature-size") == 0) {
		if (c->in_key == NULL)
			return ISC_R_NOTFOUND;

		status = dst_key_sigsize(c->in_key, &sigsize);
		if (status != ISC_R_SUCCESS) {
			return(status);
		}

		return omapi_make_int_value(value, name, sigsize, MDL);

	} else if (omapi_ds_strcmp (name, "output-signature") == 0) {
		if (!c -> out_key || !c -> out_context)
			return ISC_R_NOTFOUND;

		status = omapi_connection_sign_data (SIG_MODE_FINAL,
						     c -> out_key,
						     &c -> out_context,
						     0, 0, &td);
		if (status != ISC_R_SUCCESS)
			return status;

		status = omapi_make_value (value, name, td, MDL);
		omapi_typed_data_dereference (&td, MDL);
		return status;

	} else if (omapi_ds_strcmp (name, "output-signature-size") == 0) {
		if (c->out_key == NULL)
			return ISC_R_NOTFOUND;


		status = dst_key_sigsize(c->out_key, &sigsize);
		if (status != ISC_R_SUCCESS) {
			return(status);
		}

		return omapi_make_int_value(value, name, sigsize, MDL);
	}

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

isc_result_t omapi_connection_destroy (omapi_object_t *h,
				       const char *file, int line)
{
	omapi_connection_object_t *c;

#ifdef DEBUG_PROTOCOL
	log_debug ("omapi_connection_destroy()");
#endif

	if (h -> type != omapi_type_connection)
		return ISC_R_UNEXPECTED;
	c = (omapi_connection_object_t *)(h);
	if (c -> state == omapi_connection_connected)
		omapi_disconnect (h, 1);
	if (c -> listener)
		omapi_listener_dereference (&c -> listener, file, line);
	if (c -> connect_list)
		omapi_addr_list_dereference (&c -> connect_list, file, line);
	return ISC_R_SUCCESS;
}

isc_result_t omapi_connection_signal_handler (omapi_object_t *h,
					      const char *name, va_list ap)
{
	if (h -> type != omapi_type_connection)
		return DHCP_R_INVALIDARG;

#ifdef DEBUG_PROTOCOL
	log_debug ("omapi_connection_signal_handler(%s)", name);
#endif

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

/* Write all the published values associated with the object through the
   specified connection. */

isc_result_t omapi_connection_stuff_values (omapi_object_t *c,
					    omapi_object_t *id,
					    omapi_object_t *m)
{
	if (m -> type != omapi_type_connection)
		return DHCP_R_INVALIDARG;

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

/* @brief Fetches the value of an attribute in an object as an allocated
 * C string
 *
 * @param obj ompapi object containing the desire attribute
 * @param attr_name  name of the desired attribute
 * @param[out] cstr pointer in which to place the allocated C string's address
 *
 * Caller is responsible for freeing (via dfree) the allocated string.
 *
 * @return ISC_R_SUCCESS if successful, otherwise indicates the type of failure
*/
static isc_result_t ctring_from_attribute(omapi_object_t *obj, char *attr_name,
                                          char **cstr) {
	isc_result_t status = ISC_R_SUCCESS;
	omapi_value_t *attr = 0;

	/* Find the attribute in the object. */
	status = omapi_get_value_str(obj, (omapi_object_t *)0, attr_name,
                                 &attr);
	if (status != ISC_R_SUCCESS) {
		return (status);
	}

	/* Got it, let's make sure it's either data or string type. */
	if (attr->value->type != omapi_datatype_data &&
            attr->value->type != omapi_datatype_string) {
		return (DHCP_R_INVALIDARG);
        }

	/* Make a C string from the attribute value. */
	*cstr = dmalloc (attr->value->u.buffer.len + 1, MDL);
	if (!(*cstr)) {
		status = ISC_R_NOMEMORY;
        } else {
	        memcpy (*cstr, attr->value->u.buffer.value,
		            attr->value->u.buffer.len);
	        (*cstr)[attr->value->u.buffer.len] = 0;
	}

	/* Get rid of the attribute reference */
	if (attr) {
		omapi_value_dereference (&attr, MDL);
	}

	return (status);
}