2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Tim Potter 2000-2001
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "system/network.h"
23 #include "socketpair_tcp.h"
25 /*******************************************************************
26 this is like socketpair but uses tcp. It is used by the Samba
28 The function guarantees that nobody else can attach to the socket,
29 or if they do that this function fails and the socket gets closed
30 returns 0 on success, -1 on failure
31 the resulting file descriptors are symmetrical
32 ******************************************************************/
33 int socketpair_tcp(int fd
[2])
36 struct sockaddr_in sock
;
37 struct sockaddr_in sock2
;
38 socklen_t socklen
= sizeof(sock
);
41 fd
[0] = fd
[1] = listener
= -1;
43 memset(&sock
, 0, sizeof(sock
));
45 if ((listener
= socket(PF_INET
, SOCK_STREAM
, 0)) == -1) goto failed
;
47 memset(&sock2
, 0, sizeof(sock2
));
48 #ifdef HAVE_SOCK_SIN_LEN
49 sock2
.sin_len
= sizeof(sock2
);
51 sock2
.sin_family
= PF_INET
;
53 if (bind(listener
, (struct sockaddr
*)&sock2
, sizeof(sock2
)) != 0) goto failed
;
55 if (listen(listener
, 1) != 0) goto failed
;
57 if (getsockname(listener
, (struct sockaddr
*)&sock
, &socklen
) != 0) goto failed
;
59 if ((fd
[1] = socket(PF_INET
, SOCK_STREAM
, 0)) == -1) goto failed
;
61 set_blocking(fd
[1], 0);
63 sock
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
65 if (connect(fd
[1], (struct sockaddr
*)&sock
, socklen
) == -1) {
66 if (errno
!= EINPROGRESS
) goto failed
;
71 if ((fd
[0] = accept(listener
, (struct sockaddr
*)&sock
, &socklen
)) == -1) goto failed
;
73 if (connect_done
== 0) {
74 if (connect(fd
[1], (struct sockaddr
*)&sock
, socklen
) != 0
75 && errno
!= EISCONN
) goto failed
;
79 set_blocking(fd
[1], 1);
85 if (fd
[0] != -1) close(fd
[0]);
86 if (fd
[1] != -1) close(fd
[1]);
87 if (listener
!= -1) close(listener
);