xref: /netbsd-src/external/bsd/openldap/dist/libraries/liblutil/sockpair.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /* $OpenLDAP: pkg/ldap/libraries/liblutil/sockpair.c,v 1.17.2.3 2008/02/11 23:26:42 kurt Exp $ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2008 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 
16 #include "portable.h"
17 #include <ac/socket.h>
18 #include <ac/unistd.h>
19 
20 #include <lutil.h>
21 
22 /* Return a pair of socket descriptors that are connected to each other.
23  * The returned descriptors are suitable for use with select(). The two
24  * descriptors may or may not be identical; the function may return
25  * the same descriptor number in both slots. It is guaranteed that
26  * data written on sds[1] will be readable on sds[0]. The returned
27  * descriptors may be datagram oriented, so data should be written
28  * in reasonably small pieces and read all at once. On Unix systems
29  * this function is best implemented using a single pipe() call.
30  */
31 
32 int lutil_pair( ber_socket_t sds[2] )
33 {
34 #ifdef USE_PIPE
35 	return pipe( sds );
36 #else
37 	struct sockaddr_in si;
38 	int rc;
39 	ber_socklen_t len = sizeof(si);
40 	ber_socket_t sd;
41 
42 	sd = socket( AF_INET, SOCK_DGRAM, 0 );
43 	if ( sd == AC_SOCKET_INVALID ) {
44 		return sd;
45 	}
46 
47 	(void) memset( (void*) &si, '\0', len );
48 	si.sin_family = AF_INET;
49 	si.sin_port = 0;
50 	si.sin_addr.s_addr = htonl( INADDR_LOOPBACK );
51 
52 	rc = bind( sd, (struct sockaddr *)&si, len );
53 	if ( rc == AC_SOCKET_ERROR ) {
54 		tcp_close(sd);
55 		return rc;
56 	}
57 
58 	rc = getsockname( sd, (struct sockaddr *)&si, &len );
59 	if ( rc == AC_SOCKET_ERROR ) {
60 		tcp_close(sd);
61 		return rc;
62 	}
63 
64 	rc = connect( sd, (struct sockaddr *)&si, len );
65 	if ( rc == AC_SOCKET_ERROR ) {
66 		tcp_close(sd);
67 		return rc;
68 	}
69 
70 	sds[0] = sd;
71 #if !HAVE_WINSOCK
72 	sds[1] = dup( sds[0] );
73 #else
74 	sds[1] = sds[0];
75 #endif
76 	return 0;
77 #endif
78 }
79