s4:selftest: explicitly set NSS/RESOLV_WAPPER_* in wait_for_start
[Samba.git] / source3 / lib / util_sock.c
blobc74fcd9138dc1c7ee32d25de6f08b19dfc79057f
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Tim Potter 2000-2001
6 Copyright (C) Jeremy Allison 1992-2007
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "../lib/util/memcache.h"
25 #include "../lib/async_req/async_sock.h"
26 #include "../lib/util/select.h"
27 #include "lib/socket/interfaces.h"
28 #include "../lib/util/tevent_unix.h"
29 #include "../lib/util/tevent_ntstatus.h"
30 #include "../lib/tsocket/tsocket.h"
31 #include "lib/util/sys_rw.h"
32 #include "lib/util/sys_rw_data.h"
34 const char *client_addr(int fd, char *addr, size_t addrlen)
36 return get_peer_addr(fd,addr,addrlen);
39 #if 0
40 /* Not currently used. JRA. */
41 int client_socket_port(int fd)
43 return get_socket_port(fd);
45 #endif
47 /****************************************************************************
48 Determine if a file descriptor is in fact a socket.
49 ****************************************************************************/
51 bool is_a_socket(int fd)
53 int v;
54 socklen_t l;
55 l = sizeof(int);
56 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
59 /****************************************************************************
60 Read from a socket.
61 ****************************************************************************/
63 ssize_t read_udp_v4_socket(int fd,
64 char *buf,
65 size_t len,
66 struct sockaddr_storage *psa)
68 ssize_t ret;
69 socklen_t socklen = sizeof(*psa);
70 struct sockaddr_in *si = (struct sockaddr_in *)psa;
72 memset((char *)psa,'\0',socklen);
74 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
75 (struct sockaddr *)psa,&socklen);
76 if (ret <= 0) {
77 /* Don't print a low debug error for a non-blocking socket. */
78 if (errno == EAGAIN) {
79 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
80 } else {
81 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
82 strerror(errno)));
84 return 0;
87 if (psa->ss_family != AF_INET) {
88 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
89 "(not IPv4)\n", (int)psa->ss_family));
90 return 0;
93 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
94 inet_ntoa(si->sin_addr),
95 si->sin_port,
96 (unsigned long)ret));
98 return ret;
101 /****************************************************************************
102 Read data from a file descriptor with a timout in msec.
103 mincount = if timeout, minimum to read before returning
104 maxcount = number to be read.
105 time_out = timeout in milliseconds
106 NB. This can be called with a non-socket fd, don't change
107 sys_read() to sys_recv() or other socket call.
108 ****************************************************************************/
110 NTSTATUS read_fd_with_timeout(int fd, char *buf,
111 size_t mincnt, size_t maxcnt,
112 unsigned int time_out,
113 size_t *size_ret)
115 int pollrtn;
116 ssize_t readret;
117 size_t nread = 0;
119 /* just checking .... */
120 if (maxcnt <= 0)
121 return NT_STATUS_OK;
123 /* Blocking read */
124 if (time_out == 0) {
125 if (mincnt == 0) {
126 mincnt = maxcnt;
129 while (nread < mincnt) {
130 readret = sys_read(fd, buf + nread, maxcnt - nread);
132 if (readret == 0) {
133 DEBUG(5,("read_fd_with_timeout: "
134 "blocking read. EOF from client.\n"));
135 return NT_STATUS_END_OF_FILE;
138 if (readret == -1) {
139 return map_nt_error_from_unix(errno);
141 nread += readret;
143 goto done;
146 /* Most difficult - timeout read */
147 /* If this is ever called on a disk file and
148 mincnt is greater then the filesize then
149 system performance will suffer severely as
150 select always returns true on disk files */
152 for (nread=0; nread < mincnt; ) {
153 int revents;
155 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
156 &revents);
158 /* Check if error */
159 if (pollrtn == -1) {
160 return map_nt_error_from_unix(errno);
163 /* Did we timeout ? */
164 if ((pollrtn == 0) ||
165 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
166 DEBUG(10,("read_fd_with_timeout: timeout read. "
167 "select timed out.\n"));
168 return NT_STATUS_IO_TIMEOUT;
171 readret = sys_read(fd, buf+nread, maxcnt-nread);
173 if (readret == 0) {
174 /* we got EOF on the file descriptor */
175 DEBUG(5,("read_fd_with_timeout: timeout read. "
176 "EOF from client.\n"));
177 return NT_STATUS_END_OF_FILE;
180 if (readret == -1) {
181 return map_nt_error_from_unix(errno);
184 nread += readret;
187 done:
188 /* Return the number we got */
189 if (size_ret) {
190 *size_ret = nread;
192 return NT_STATUS_OK;
195 /****************************************************************************
196 Read data from an fd, reading exactly N bytes.
197 NB. This can be called with a non-socket fd, don't add dependencies
198 on socket calls.
199 ****************************************************************************/
201 NTSTATUS read_data_ntstatus(int fd, char *buffer, size_t N)
203 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
206 /****************************************************************************
207 Send a keepalive packet (rfc1002).
208 ****************************************************************************/
210 bool send_keepalive(int client)
212 unsigned char buf[4];
214 buf[0] = NBSSkeepalive;
215 buf[1] = buf[2] = buf[3] = 0;
217 return(write_data(client,(char *)buf,4) == 4);
220 /****************************************************************************
221 Read 4 bytes of a smb packet and return the smb length of the packet.
222 Store the result in the buffer.
223 This version of the function will return a length of zero on receiving
224 a keepalive packet.
225 Timeout is in milliseconds.
226 ****************************************************************************/
228 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
229 unsigned int timeout,
230 size_t *len)
232 int msg_type;
233 NTSTATUS status;
235 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
237 if (!NT_STATUS_IS_OK(status)) {
238 return status;
241 *len = smb_len(inbuf);
242 msg_type = CVAL(inbuf,0);
244 if (msg_type == NBSSkeepalive) {
245 DEBUG(5,("Got keepalive packet\n"));
248 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
250 return NT_STATUS_OK;
253 /****************************************************************************
254 Read an smb from a fd.
255 The timeout is in milliseconds.
256 This function will return on receipt of a session keepalive packet.
257 maxlen is the max number of bytes to return, not including the 4 byte
258 length. If zero it means buflen limit.
259 Doesn't check the MAC on signed packets.
260 ****************************************************************************/
262 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
263 size_t maxlen, size_t *p_len)
265 size_t len;
266 NTSTATUS status;
268 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
270 if (!NT_STATUS_IS_OK(status)) {
271 DEBUG(0, ("read_fd_with_timeout failed, read "
272 "error = %s.\n", nt_errstr(status)));
273 return status;
276 if (len > buflen) {
277 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
278 (unsigned long)len));
279 return NT_STATUS_INVALID_PARAMETER;
282 if(len > 0) {
283 if (maxlen) {
284 len = MIN(len,maxlen);
287 status = read_fd_with_timeout(
288 fd, buffer+4, len, len, timeout, &len);
290 if (!NT_STATUS_IS_OK(status)) {
291 DEBUG(0, ("read_fd_with_timeout failed, read error = "
292 "%s.\n", nt_errstr(status)));
293 return status;
296 /* not all of samba3 properly checks for packet-termination
297 * of strings. This ensures that we don't run off into
298 * empty space. */
299 SSVAL(buffer+4,len, 0);
302 *p_len = len;
303 return NT_STATUS_OK;
306 /****************************************************************************
307 Open a socket of the specified type, port, and address for incoming data.
308 ****************************************************************************/
310 int open_socket_in(int type,
311 uint16_t port,
312 int dlevel,
313 const struct sockaddr_storage *psock,
314 bool rebind)
316 struct sockaddr_storage sock;
317 int res;
318 socklen_t slen = sizeof(struct sockaddr_in);
320 sock = *psock;
322 #if defined(HAVE_IPV6)
323 if (sock.ss_family == AF_INET6) {
324 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
325 slen = sizeof(struct sockaddr_in6);
327 #endif
328 if (sock.ss_family == AF_INET) {
329 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
332 res = socket(sock.ss_family, type, 0 );
333 if( res == -1 ) {
334 if( DEBUGLVL(0) ) {
335 dbgtext( "open_socket_in(): socket() call failed: " );
336 dbgtext( "%s\n", strerror( errno ) );
338 return -1;
341 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
343 int val = rebind ? 1 : 0;
344 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
345 (char *)&val,sizeof(val)) == -1 ) {
346 if( DEBUGLVL( dlevel ) ) {
347 dbgtext( "open_socket_in(): setsockopt: " );
348 dbgtext( "SO_REUSEADDR = %s ",
349 val?"true":"false" );
350 dbgtext( "on port %d failed ", port );
351 dbgtext( "with error = %s\n", strerror(errno) );
354 #ifdef SO_REUSEPORT
355 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
356 (char *)&val,sizeof(val)) == -1 ) {
357 if( DEBUGLVL( dlevel ) ) {
358 dbgtext( "open_socket_in(): setsockopt: ");
359 dbgtext( "SO_REUSEPORT = %s ",
360 val?"true":"false");
361 dbgtext( "on port %d failed ", port);
362 dbgtext( "with error = %s\n", strerror(errno));
365 #endif /* SO_REUSEPORT */
368 #ifdef HAVE_IPV6
370 * As IPV6_V6ONLY is the default on some systems,
371 * we better try to be consistent and always use it.
373 * This also avoids using IPv4 via AF_INET6 sockets
374 * and makes sure %I never resolves to a '::ffff:192.168.0.1'
375 * string.
377 if (sock.ss_family == AF_INET6) {
378 int val = 1;
379 int ret;
381 ret = setsockopt(res, IPPROTO_IPV6, IPV6_V6ONLY,
382 (const void *)&val, sizeof(val));
383 if (ret == -1) {
384 if(DEBUGLVL(0)) {
385 dbgtext("open_socket_in(): IPV6_ONLY failed: ");
386 dbgtext("%s\n", strerror(errno));
388 close(res);
389 return -1;
392 #endif
394 /* now we've got a socket - we need to bind it */
395 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
396 if( DEBUGLVL(dlevel) && (port == NMB_PORT ||
397 port == NBT_SMB_PORT ||
398 port == TCP_SMB_PORT) ) {
399 char addr[INET6_ADDRSTRLEN];
400 print_sockaddr(addr, sizeof(addr),
401 &sock);
402 dbgtext( "bind failed on port %d ", port);
403 dbgtext( "socket_addr = %s.\n", addr);
404 dbgtext( "Error = %s\n", strerror(errno));
406 close(res);
407 return -1;
410 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
411 return( res );
414 struct open_socket_out_state {
415 int fd;
416 struct tevent_context *ev;
417 struct sockaddr_storage ss;
418 socklen_t salen;
419 uint16_t port;
420 int wait_usec;
421 struct tevent_req *connect_subreq;
424 static void open_socket_out_connected(struct tevent_req *subreq);
426 static void open_socket_out_cleanup(struct tevent_req *req,
427 enum tevent_req_state req_state)
429 struct open_socket_out_state *state =
430 tevent_req_data(req, struct open_socket_out_state);
433 * Make sure that the async_connect_send subreq has a chance to reset
434 * fcntl before the socket goes away.
436 TALLOC_FREE(state->connect_subreq);
438 if (req_state == TEVENT_REQ_DONE) {
440 * we keep the socket open for the caller to use
442 return;
445 if (state->fd != -1) {
446 close(state->fd);
447 state->fd = -1;
451 /****************************************************************************
452 Create an outgoing socket. timeout is in milliseconds.
453 **************************************************************************/
455 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
456 struct tevent_context *ev,
457 const struct sockaddr_storage *pss,
458 uint16_t port,
459 int timeout)
461 char addr[INET6_ADDRSTRLEN];
462 struct tevent_req *result;
463 struct open_socket_out_state *state;
464 NTSTATUS status;
466 result = tevent_req_create(mem_ctx, &state,
467 struct open_socket_out_state);
468 if (result == NULL) {
469 return NULL;
471 state->ev = ev;
472 state->ss = *pss;
473 state->port = port;
474 state->wait_usec = 10000;
475 state->salen = -1;
477 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
478 if (state->fd == -1) {
479 status = map_nt_error_from_unix(errno);
480 goto post_status;
483 tevent_req_set_cleanup_fn(result, open_socket_out_cleanup);
485 if (!tevent_req_set_endtime(
486 result, ev, timeval_current_ofs_msec(timeout))) {
487 goto fail;
490 #if defined(HAVE_IPV6)
491 if (pss->ss_family == AF_INET6) {
492 struct sockaddr_in6 *psa6;
493 psa6 = (struct sockaddr_in6 *)&state->ss;
494 psa6->sin6_port = htons(port);
495 if (psa6->sin6_scope_id == 0
496 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
497 setup_linklocal_scope_id(
498 (struct sockaddr *)&(state->ss));
500 state->salen = sizeof(struct sockaddr_in6);
502 #endif
503 if (pss->ss_family == AF_INET) {
504 struct sockaddr_in *psa;
505 psa = (struct sockaddr_in *)&state->ss;
506 psa->sin_port = htons(port);
507 state->salen = sizeof(struct sockaddr_in);
510 if (pss->ss_family == AF_UNIX) {
511 state->salen = sizeof(struct sockaddr_un);
514 print_sockaddr(addr, sizeof(addr), &state->ss);
515 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
517 state->connect_subreq = async_connect_send(
518 state, state->ev, state->fd, (struct sockaddr *)&state->ss,
519 state->salen, NULL, NULL, NULL);
520 if ((state->connect_subreq == NULL)
521 || !tevent_req_set_endtime(
522 state->connect_subreq, state->ev,
523 timeval_current_ofs(0, state->wait_usec))) {
524 goto fail;
526 tevent_req_set_callback(state->connect_subreq,
527 open_socket_out_connected, result);
528 return result;
530 post_status:
531 tevent_req_nterror(result, status);
532 return tevent_req_post(result, ev);
533 fail:
534 TALLOC_FREE(result);
535 return NULL;
538 static void open_socket_out_connected(struct tevent_req *subreq)
540 struct tevent_req *req =
541 tevent_req_callback_data(subreq, struct tevent_req);
542 struct open_socket_out_state *state =
543 tevent_req_data(req, struct open_socket_out_state);
544 int ret;
545 int sys_errno;
547 ret = async_connect_recv(subreq, &sys_errno);
548 TALLOC_FREE(subreq);
549 state->connect_subreq = NULL;
550 if (ret == 0) {
551 tevent_req_done(req);
552 return;
555 if (
556 #ifdef ETIMEDOUT
557 (sys_errno == ETIMEDOUT) ||
558 #endif
559 (sys_errno == EINPROGRESS) ||
560 (sys_errno == EALREADY) ||
561 (sys_errno == EAGAIN)) {
564 * retry
567 if (state->wait_usec < 250000) {
568 state->wait_usec *= 1.5;
571 subreq = async_connect_send(state, state->ev, state->fd,
572 (struct sockaddr *)&state->ss,
573 state->salen, NULL, NULL, NULL);
574 if (tevent_req_nomem(subreq, req)) {
575 return;
577 if (!tevent_req_set_endtime(
578 subreq, state->ev,
579 timeval_current_ofs_usec(state->wait_usec))) {
580 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
581 return;
583 state->connect_subreq = subreq;
584 tevent_req_set_callback(subreq, open_socket_out_connected, req);
585 return;
588 #ifdef EISCONN
589 if (sys_errno == EISCONN) {
590 tevent_req_done(req);
591 return;
593 #endif
595 /* real error */
596 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
599 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
601 struct open_socket_out_state *state =
602 tevent_req_data(req, struct open_socket_out_state);
603 NTSTATUS status;
605 if (tevent_req_is_nterror(req, &status)) {
606 tevent_req_received(req);
607 return status;
609 *pfd = state->fd;
610 state->fd = -1;
611 tevent_req_received(req);
612 return NT_STATUS_OK;
616 * @brief open a socket
618 * @param pss a struct sockaddr_storage defining the address to connect to
619 * @param port to connect to
620 * @param timeout in MILLISECONDS
621 * @param pfd file descriptor returned
623 * @return NTSTATUS code
625 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
626 int timeout, int *pfd)
628 TALLOC_CTX *frame = talloc_stackframe();
629 struct tevent_context *ev;
630 struct tevent_req *req;
631 NTSTATUS status = NT_STATUS_NO_MEMORY;
633 ev = samba_tevent_context_init(frame);
634 if (ev == NULL) {
635 goto fail;
638 req = open_socket_out_send(frame, ev, pss, port, timeout);
639 if (req == NULL) {
640 goto fail;
642 if (!tevent_req_poll(req, ev)) {
643 status = NT_STATUS_INTERNAL_ERROR;
644 goto fail;
646 status = open_socket_out_recv(req, pfd);
647 fail:
648 TALLOC_FREE(frame);
649 return status;
652 struct open_socket_out_defer_state {
653 struct tevent_context *ev;
654 struct sockaddr_storage ss;
655 uint16_t port;
656 int timeout;
657 int fd;
660 static void open_socket_out_defer_waited(struct tevent_req *subreq);
661 static void open_socket_out_defer_connected(struct tevent_req *subreq);
663 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
664 struct tevent_context *ev,
665 struct timeval wait_time,
666 const struct sockaddr_storage *pss,
667 uint16_t port,
668 int timeout)
670 struct tevent_req *req, *subreq;
671 struct open_socket_out_defer_state *state;
673 req = tevent_req_create(mem_ctx, &state,
674 struct open_socket_out_defer_state);
675 if (req == NULL) {
676 return NULL;
678 state->ev = ev;
679 state->ss = *pss;
680 state->port = port;
681 state->timeout = timeout;
683 subreq = tevent_wakeup_send(
684 state, ev,
685 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
686 if (subreq == NULL) {
687 goto fail;
689 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
690 return req;
691 fail:
692 TALLOC_FREE(req);
693 return NULL;
696 static void open_socket_out_defer_waited(struct tevent_req *subreq)
698 struct tevent_req *req = tevent_req_callback_data(
699 subreq, struct tevent_req);
700 struct open_socket_out_defer_state *state = tevent_req_data(
701 req, struct open_socket_out_defer_state);
702 bool ret;
704 ret = tevent_wakeup_recv(subreq);
705 TALLOC_FREE(subreq);
706 if (!ret) {
707 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
708 return;
711 subreq = open_socket_out_send(state, state->ev, &state->ss,
712 state->port, state->timeout);
713 if (tevent_req_nomem(subreq, req)) {
714 return;
716 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
719 static void open_socket_out_defer_connected(struct tevent_req *subreq)
721 struct tevent_req *req = tevent_req_callback_data(
722 subreq, struct tevent_req);
723 struct open_socket_out_defer_state *state = tevent_req_data(
724 req, struct open_socket_out_defer_state);
725 NTSTATUS status;
727 status = open_socket_out_recv(subreq, &state->fd);
728 TALLOC_FREE(subreq);
729 if (!NT_STATUS_IS_OK(status)) {
730 tevent_req_nterror(req, status);
731 return;
733 tevent_req_done(req);
736 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
738 struct open_socket_out_defer_state *state = tevent_req_data(
739 req, struct open_socket_out_defer_state);
740 NTSTATUS status;
742 if (tevent_req_is_nterror(req, &status)) {
743 return status;
745 *pfd = state->fd;
746 state->fd = -1;
747 return NT_STATUS_OK;
750 /****************************************************************************
751 Open a connected UDP socket to host on port
752 **************************************************************************/
754 int open_udp_socket(const char *host, int port)
756 struct sockaddr_storage ss;
757 int res;
758 socklen_t salen;
760 if (!interpret_string_addr(&ss, host, 0)) {
761 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
762 host));
763 return -1;
766 res = socket(ss.ss_family, SOCK_DGRAM, 0);
767 if (res == -1) {
768 return -1;
771 #if defined(HAVE_IPV6)
772 if (ss.ss_family == AF_INET6) {
773 struct sockaddr_in6 *psa6;
774 psa6 = (struct sockaddr_in6 *)&ss;
775 psa6->sin6_port = htons(port);
776 if (psa6->sin6_scope_id == 0
777 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
778 setup_linklocal_scope_id(
779 (struct sockaddr *)&ss);
781 salen = sizeof(struct sockaddr_in6);
782 } else
783 #endif
784 if (ss.ss_family == AF_INET) {
785 struct sockaddr_in *psa;
786 psa = (struct sockaddr_in *)&ss;
787 psa->sin_port = htons(port);
788 salen = sizeof(struct sockaddr_in);
789 } else {
790 DEBUG(1, ("unknown socket family %d", ss.ss_family));
791 close(res);
792 return -1;
795 if (connect(res, (struct sockaddr *)&ss, salen)) {
796 close(res);
797 return -1;
800 return res;
803 /*******************************************************************
804 Return the IP addr of the remote end of a socket as a string.
805 Optionally return the struct sockaddr_storage.
806 ******************************************************************/
808 static const char *get_peer_addr_internal(int fd,
809 char *addr_buf,
810 size_t addr_buf_len,
811 struct sockaddr *pss,
812 socklen_t *plength)
814 struct sockaddr_storage ss;
815 socklen_t length = sizeof(ss);
817 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
819 if (fd == -1) {
820 return addr_buf;
823 if (pss == NULL) {
824 pss = (struct sockaddr *)&ss;
825 plength = &length;
828 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
829 int level = (errno == ENOTCONN) ? 2 : 0;
830 DEBUG(level, ("getpeername failed. Error was %s\n",
831 strerror(errno)));
832 return addr_buf;
835 print_sockaddr_len(addr_buf,
836 addr_buf_len,
837 pss,
838 *plength);
839 return addr_buf;
842 /*******************************************************************
843 Matchname - determine if host name matches IP address. Used to
844 confirm a hostname lookup to prevent spoof attacks.
845 ******************************************************************/
847 static bool matchname(const char *remotehost,
848 const struct sockaddr *pss,
849 socklen_t len)
851 struct addrinfo *res = NULL;
852 struct addrinfo *ailist = NULL;
853 char addr_buf[INET6_ADDRSTRLEN];
854 bool ret = interpret_string_addr_internal(&ailist,
855 remotehost,
856 AI_ADDRCONFIG|AI_CANONNAME);
858 if (!ret || ailist == NULL) {
859 DEBUG(3,("matchname: getaddrinfo failed for "
860 "name %s [%s]\n",
861 remotehost,
862 gai_strerror(ret) ));
863 return false;
867 * Make sure that getaddrinfo() returns the "correct" host name.
870 if (ailist->ai_canonname == NULL ||
871 (!strequal(remotehost, ailist->ai_canonname) &&
872 !strequal(remotehost, "localhost"))) {
873 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
874 remotehost,
875 ailist->ai_canonname ?
876 ailist->ai_canonname : "(NULL)"));
877 freeaddrinfo(ailist);
878 return false;
881 /* Look up the host address in the address list we just got. */
882 for (res = ailist; res; res = res->ai_next) {
883 if (!res->ai_addr) {
884 continue;
886 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
887 (const struct sockaddr *)pss)) {
888 freeaddrinfo(ailist);
889 return true;
894 * The host name does not map to the original host address. Perhaps
895 * someone has compromised a name server. More likely someone botched
896 * it, but that could be dangerous, too.
899 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
900 print_sockaddr_len(addr_buf,
901 sizeof(addr_buf),
902 pss,
903 len),
904 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
906 if (ailist) {
907 freeaddrinfo(ailist);
909 return false;
912 /*******************************************************************
913 Deal with the singleton cache.
914 ******************************************************************/
916 struct name_addr_pair {
917 struct sockaddr_storage ss;
918 const char *name;
921 /*******************************************************************
922 Lookup a name/addr pair. Returns memory allocated from memcache.
923 ******************************************************************/
925 static bool lookup_nc(struct name_addr_pair *nc)
927 DATA_BLOB tmp;
929 ZERO_STRUCTP(nc);
931 if (!memcache_lookup(
932 NULL, SINGLETON_CACHE,
933 data_blob_string_const_null("get_peer_name"),
934 &tmp)) {
935 return false;
938 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
939 nc->name = (const char *)tmp.data + sizeof(nc->ss);
940 return true;
943 /*******************************************************************
944 Save a name/addr pair.
945 ******************************************************************/
947 static void store_nc(const struct name_addr_pair *nc)
949 DATA_BLOB tmp;
950 size_t namelen = strlen(nc->name);
952 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
953 if (!tmp.data) {
954 return;
956 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
957 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
959 memcache_add(NULL, SINGLETON_CACHE,
960 data_blob_string_const_null("get_peer_name"),
961 tmp);
962 data_blob_free(&tmp);
965 /*******************************************************************
966 Return the IP addr of the remote end of a socket as a string.
967 ******************************************************************/
969 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
971 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
974 int get_remote_hostname(const struct tsocket_address *remote_address,
975 char **name,
976 TALLOC_CTX *mem_ctx)
978 char name_buf[MAX_DNS_NAME_LENGTH];
979 char tmp_name[MAX_DNS_NAME_LENGTH];
980 struct name_addr_pair nc;
981 struct sockaddr_storage ss;
982 ssize_t len;
983 int rc;
985 if (!lp_hostname_lookups()) {
986 nc.name = tsocket_address_inet_addr_string(remote_address,
987 mem_ctx);
988 if (nc.name == NULL) {
989 return -1;
992 len = tsocket_address_bsd_sockaddr(remote_address,
993 (struct sockaddr *) &nc.ss,
994 sizeof(struct sockaddr_storage));
995 if (len < 0) {
996 return -1;
999 store_nc(&nc);
1000 lookup_nc(&nc);
1002 if (nc.name == NULL) {
1003 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1004 } else {
1005 *name = talloc_strdup(mem_ctx, nc.name);
1007 return 0;
1010 lookup_nc(&nc);
1012 ZERO_STRUCT(ss);
1014 len = tsocket_address_bsd_sockaddr(remote_address,
1015 (struct sockaddr *) &ss,
1016 sizeof(struct sockaddr_storage));
1017 if (len < 0) {
1018 return -1;
1021 /* it might be the same as the last one - save some DNS work */
1022 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1023 if (nc.name == NULL) {
1024 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1025 } else {
1026 *name = talloc_strdup(mem_ctx, nc.name);
1028 return 0;
1031 /* Look up the remote host name. */
1032 rc = sys_getnameinfo((struct sockaddr *) &ss,
1033 len,
1034 name_buf,
1035 sizeof(name_buf),
1036 NULL,
1039 if (rc < 0) {
1040 char *p;
1042 p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1043 if (p == NULL) {
1044 return -1;
1047 DEBUG(1,("getnameinfo failed for %s with error %s\n",
1049 gai_strerror(rc)));
1050 strlcpy(name_buf, p, sizeof(name_buf));
1052 TALLOC_FREE(p);
1053 } else {
1054 if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1055 DEBUG(0,("matchname failed on %s\n", name_buf));
1056 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1060 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1061 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1062 if (strstr(name_buf,"..")) {
1063 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1066 nc.name = name_buf;
1067 nc.ss = ss;
1069 store_nc(&nc);
1070 lookup_nc(&nc);
1072 if (nc.name == NULL) {
1073 *name = talloc_strdup(mem_ctx, "UNKNOWN");
1074 } else {
1075 *name = talloc_strdup(mem_ctx, nc.name);
1078 return 0;
1081 /*******************************************************************
1082 Create protected unix domain socket.
1084 Some unixes cannot set permissions on a ux-dom-sock, so we
1085 have to make sure that the directory contains the protection
1086 permissions instead.
1087 ******************************************************************/
1089 int create_pipe_sock(const char *socket_dir,
1090 const char *socket_name,
1091 mode_t dir_perms)
1093 #ifdef HAVE_UNIXSOCKET
1094 struct sockaddr_un sunaddr;
1095 bool ok;
1096 int sock = -1;
1097 mode_t old_umask;
1098 char *path = NULL;
1100 old_umask = umask(0);
1102 ok = directory_create_or_exist_strict(socket_dir,
1103 sec_initial_uid(),
1104 dir_perms);
1105 if (!ok) {
1106 goto out_close;
1109 /* Create the socket file */
1110 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1112 if (sock == -1) {
1113 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1114 strerror(errno) ));
1115 goto out_close;
1118 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1119 goto out_close;
1122 unlink(path);
1123 memset(&sunaddr, 0, sizeof(sunaddr));
1124 sunaddr.sun_family = AF_UNIX;
1125 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1127 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1128 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1129 strerror(errno)));
1130 goto out_close;
1133 SAFE_FREE(path);
1135 umask(old_umask);
1136 return sock;
1138 out_close:
1139 SAFE_FREE(path);
1140 if (sock != -1)
1141 close(sock);
1143 umask(old_umask);
1144 return -1;
1146 #else
1147 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1148 return -1;
1149 #endif /* HAVE_UNIXSOCKET */
1152 /****************************************************************************
1153 Get my own canonical name, including domain.
1154 ****************************************************************************/
1156 const char *get_mydnsfullname(void)
1158 struct addrinfo *res = NULL;
1159 char my_hostname[HOST_NAME_MAX];
1160 bool ret;
1161 DATA_BLOB tmp;
1163 if (memcache_lookup(NULL, SINGLETON_CACHE,
1164 data_blob_string_const_null("get_mydnsfullname"),
1165 &tmp)) {
1166 SMB_ASSERT(tmp.length > 0);
1167 return (const char *)tmp.data;
1170 /* get my host name */
1171 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1172 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1173 return NULL;
1176 /* Ensure null termination. */
1177 my_hostname[sizeof(my_hostname)-1] = '\0';
1179 ret = interpret_string_addr_internal(&res,
1180 my_hostname,
1181 AI_ADDRCONFIG|AI_CANONNAME);
1183 if (!ret || res == NULL) {
1184 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1185 "name %s [%s]\n",
1186 my_hostname,
1187 gai_strerror(ret) ));
1188 return NULL;
1192 * Make sure that getaddrinfo() returns the "correct" host name.
1195 if (res->ai_canonname == NULL) {
1196 DEBUG(3,("get_mydnsfullname: failed to get "
1197 "canonical name for %s\n",
1198 my_hostname));
1199 freeaddrinfo(res);
1200 return NULL;
1203 /* This copies the data, so we must do a lookup
1204 * afterwards to find the value to return.
1207 memcache_add(NULL, SINGLETON_CACHE,
1208 data_blob_string_const_null("get_mydnsfullname"),
1209 data_blob_string_const_null(res->ai_canonname));
1211 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1212 data_blob_string_const_null("get_mydnsfullname"),
1213 &tmp)) {
1214 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1215 strlen(res->ai_canonname) + 1);
1218 freeaddrinfo(res);
1220 return (const char *)tmp.data;
1223 /************************************************************
1224 Is this my ip address ?
1225 ************************************************************/
1227 static bool is_my_ipaddr(const char *ipaddr_str)
1229 struct sockaddr_storage ss;
1230 struct iface_struct *nics;
1231 int i, n;
1233 if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1234 return false;
1237 if (is_zero_addr(&ss)) {
1238 return false;
1241 if (ismyaddr((struct sockaddr *)&ss) ||
1242 is_loopback_addr((struct sockaddr *)&ss)) {
1243 return true;
1246 n = get_interfaces(talloc_tos(), &nics);
1247 for (i=0; i<n; i++) {
1248 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1249 TALLOC_FREE(nics);
1250 return true;
1253 TALLOC_FREE(nics);
1254 return false;
1257 /************************************************************
1258 Is this my name ?
1259 ************************************************************/
1261 bool is_myname_or_ipaddr(const char *s)
1263 TALLOC_CTX *ctx = talloc_tos();
1264 char *name = NULL;
1265 const char *dnsname;
1266 char *servername = NULL;
1268 if (!s) {
1269 return false;
1272 /* Santize the string from '\\name' */
1273 name = talloc_strdup(ctx, s);
1274 if (!name) {
1275 return false;
1278 servername = strrchr_m(name, '\\' );
1279 if (!servername) {
1280 servername = name;
1281 } else {
1282 servername++;
1285 /* Optimize for the common case */
1286 if (strequal(servername, lp_netbios_name())) {
1287 return true;
1290 /* Check for an alias */
1291 if (is_myname(servername)) {
1292 return true;
1295 /* Check for loopback */
1296 if (strequal(servername, "127.0.0.1") ||
1297 strequal(servername, "::1")) {
1298 return true;
1301 if (strequal(servername, "localhost")) {
1302 return true;
1305 /* Maybe it's my dns name */
1306 dnsname = get_mydnsfullname();
1307 if (dnsname && strequal(servername, dnsname)) {
1308 return true;
1311 /* Maybe its an IP address? */
1312 if (is_ipaddress(servername)) {
1313 return is_my_ipaddr(servername);
1316 /* Handle possible CNAME records - convert to an IP addr. list. */
1318 /* Use DNS to resolve the name, check all addresses. */
1319 struct addrinfo *p = NULL;
1320 struct addrinfo *res = NULL;
1322 if (!interpret_string_addr_internal(&res,
1323 servername,
1324 AI_ADDRCONFIG)) {
1325 return false;
1328 for (p = res; p; p = p->ai_next) {
1329 char addr[INET6_ADDRSTRLEN];
1330 struct sockaddr_storage ss;
1332 ZERO_STRUCT(ss);
1333 memcpy(&ss, p->ai_addr, p->ai_addrlen);
1334 print_sockaddr(addr,
1335 sizeof(addr),
1336 &ss);
1337 if (is_my_ipaddr(addr)) {
1338 freeaddrinfo(res);
1339 return true;
1342 freeaddrinfo(res);
1345 /* No match */
1346 return false;
1349 int poll_one_fd(int fd, int events, int timeout, int *revents)
1351 struct pollfd pfd;
1352 int ret;
1354 pfd.fd = fd;
1355 pfd.events = events;
1357 ret = poll(&pfd, 1, timeout);
1360 * Assign whatever poll did, even in the ret<=0 case.
1362 *revents = pfd.revents;
1364 return ret;
1367 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1369 struct pollfd pfd;
1370 int ret;
1372 pfd.fd = fd;
1373 pfd.events = events;
1375 ret = sys_poll_intr(&pfd, 1, timeout);
1376 if (ret <= 0) {
1377 *revents = 0;
1378 return ret;
1380 *revents = pfd.revents;
1381 return 1;