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/>.
24 #include "../lib/async_req/async_sock.h"
25 #include "../lib/util/select.h"
27 /****************************************************************************
28 Get a port number in host byte order from a sockaddr_storage.
29 ****************************************************************************/
31 uint16_t get_sockaddr_port(const struct sockaddr_storage *pss)
35 if (pss->ss_family != AF_INET) {
36 #if defined(HAVE_IPV6)
38 const struct sockaddr_in6 *sa6 =
39 (const struct sockaddr_in6 *)pss;
40 port = ntohs(sa6->sin6_port);
43 const struct sockaddr_in *sa =
44 (const struct sockaddr_in *)pss;
45 port = ntohs(sa->sin_port);
50 /****************************************************************************
51 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
52 ****************************************************************************/
54 static char *print_sockaddr_len(char *dest,
56 const struct sockaddr *psa,
62 (void)sys_getnameinfo(psa,
70 /****************************************************************************
71 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
72 ****************************************************************************/
74 char *print_sockaddr(char *dest,
76 const struct sockaddr_storage *psa)
78 return print_sockaddr_len(dest, destlen, (struct sockaddr *)psa,
79 sizeof(struct sockaddr_storage));
82 /****************************************************************************
83 Print out a canonical IPv4 or IPv6 address from a struct sockaddr_storage.
84 ****************************************************************************/
86 char *print_canonical_sockaddr(TALLOC_CTX *ctx,
87 const struct sockaddr_storage *pss)
89 char addr[INET6_ADDRSTRLEN];
93 /* Linux getnameinfo() man pages says port is unitialized if
94 service name is NULL. */
96 ret = sys_getnameinfo((const struct sockaddr *)pss,
97 sizeof(struct sockaddr_storage),
105 if (pss->ss_family != AF_INET) {
106 #if defined(HAVE_IPV6)
107 dest = talloc_asprintf(ctx, "[%s]", addr);
112 dest = talloc_asprintf(ctx, "%s", addr);
118 /****************************************************************************
119 Return the string of an IP address (IPv4 or IPv6).
120 ****************************************************************************/
122 static const char *get_socket_addr(int fd, char *addr_buf, size_t addr_len)
124 struct sockaddr_storage sa;
125 socklen_t length = sizeof(sa);
127 /* Ok, returning a hard coded IPv4 address
128 * is bogus, but it's just as bogus as a
129 * zero IPv6 address. No good choice here.
132 strlcpy(addr_buf, "0.0.0.0", addr_len);
138 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
139 DEBUG(0,("getsockname failed. Error was %s\n",
144 return print_sockaddr_len(addr_buf, addr_len, (struct sockaddr *)&sa, length);
147 /****************************************************************************
148 Return the port number we've bound to on a socket.
149 ****************************************************************************/
151 int get_socket_port(int fd)
153 struct sockaddr_storage sa;
154 socklen_t length = sizeof(sa);
160 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
161 int level = (errno == ENOTCONN) ? 2 : 0;
162 DEBUG(level, ("getsockname failed. Error was %s\n",
167 #if defined(HAVE_IPV6)
168 if (sa.ss_family == AF_INET6) {
169 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
172 if (sa.ss_family == AF_INET) {
173 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
178 const char *client_name(int fd)
180 return get_peer_name(fd,false);
183 const char *client_addr(int fd, char *addr, size_t addrlen)
185 return get_peer_addr(fd,addr,addrlen);
188 const char *client_socket_addr(int fd, char *addr, size_t addr_len)
190 return get_socket_addr(fd, addr, addr_len);
194 /* Not currently used. JRA. */
195 int client_socket_port(int fd)
197 return get_socket_port(fd);
201 /****************************************************************************
202 Accessor functions to make thread-safe code easier later...
203 ****************************************************************************/
205 void set_smb_read_error(enum smb_read_errors *pre,
206 enum smb_read_errors newerr)
213 void cond_set_smb_read_error(enum smb_read_errors *pre,
214 enum smb_read_errors newerr)
216 if (pre && *pre == SMB_READ_OK) {
221 /****************************************************************************
222 Determine if a file descriptor is in fact a socket.
223 ****************************************************************************/
225 bool is_a_socket(int fd)
230 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
233 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
235 typedef struct smb_socket_option {
243 static const smb_socket_option socket_options[] = {
244 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
245 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
246 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
248 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
251 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
254 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
257 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
259 #ifdef IPTOS_LOWDELAY
260 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
262 #ifdef IPTOS_THROUGHPUT
263 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
266 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
269 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
272 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
275 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
278 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
281 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
284 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
287 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
290 {"TCP_QUICKACK", IPPROTO_TCP, TCP_QUICKACK, 0, OPT_BOOL},
292 #ifdef TCP_KEEPALIVE_THRESHOLD
293 {"TCP_KEEPALIVE_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, 0, OPT_INT},
295 #ifdef TCP_KEEPALIVE_ABORT_THRESHOLD
296 {"TCP_KEEPALIVE_ABORT_THRESHOLD", IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, 0, OPT_INT},
300 /****************************************************************************
301 Print socket options.
302 ****************************************************************************/
304 static void print_socket_options(int s)
308 const smb_socket_option *p = &socket_options[0];
310 /* wrapped in if statement to prevent streams
311 * leak in SCO Openserver 5.0 */
312 /* reported on samba-technical --jerry */
313 if ( DEBUGLEVEL >= 5 ) {
314 DEBUG(5,("Socket options:\n"));
315 for (; p->name != NULL; p++) {
316 if (getsockopt(s, p->level, p->option,
317 (void *)&value, &vlen) == -1) {
318 DEBUGADD(5,("\tCould not test socket option %s.\n",
321 DEBUGADD(5,("\t%s = %d\n",
328 /****************************************************************************
329 Set user socket options.
330 ****************************************************************************/
332 void set_socket_options(int fd, const char *options)
334 TALLOC_CTX *ctx = talloc_stackframe();
337 while (next_token_talloc(ctx, &options, &tok," \t,")) {
341 bool got_value = false;
343 if ((p = strchr_m(tok,'='))) {
349 for (i=0;socket_options[i].name;i++)
350 if (strequal(socket_options[i].name,tok))
353 if (!socket_options[i].name) {
354 DEBUG(0,("Unknown socket option %s\n",tok));
358 switch (socket_options[i].opttype) {
361 ret = setsockopt(fd,socket_options[i].level,
362 socket_options[i].option,
363 (char *)&value,sizeof(int));
368 DEBUG(0,("syntax error - %s "
369 "does not take a value\n",tok));
372 int on = socket_options[i].value;
373 ret = setsockopt(fd,socket_options[i].level,
374 socket_options[i].option,
375 (char *)&on,sizeof(int));
381 /* be aware that some systems like Solaris return
382 * EINVAL to a setsockopt() call when the client
383 * sent a RST previously - no need to worry */
384 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
385 tok, strerror(errno) ));
390 print_socket_options(fd);
393 /****************************************************************************
395 ****************************************************************************/
397 ssize_t read_udp_v4_socket(int fd,
400 struct sockaddr_storage *psa)
403 socklen_t socklen = sizeof(*psa);
404 struct sockaddr_in *si = (struct sockaddr_in *)psa;
406 memset((char *)psa,'\0',socklen);
408 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
409 (struct sockaddr *)psa,&socklen);
411 /* Don't print a low debug error for a non-blocking socket. */
412 if (errno == EAGAIN) {
413 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
415 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
421 if (psa->ss_family != AF_INET) {
422 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
423 "(not IPv4)\n", (int)psa->ss_family));
427 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
428 inet_ntoa(si->sin_addr),
430 (unsigned long)ret));
435 /****************************************************************************
436 Read data from a file descriptor with a timout in msec.
437 mincount = if timeout, minimum to read before returning
438 maxcount = number to be read.
439 time_out = timeout in milliseconds
440 NB. This can be called with a non-socket fd, don't change
441 sys_read() to sys_recv() or other socket call.
442 ****************************************************************************/
444 NTSTATUS read_fd_with_timeout(int fd, char *buf,
445 size_t mincnt, size_t maxcnt,
446 unsigned int time_out,
453 /* just checking .... */
463 while (nread < mincnt) {
464 readret = sys_read(fd, buf + nread, maxcnt - nread);
467 DEBUG(5,("read_fd_with_timeout: "
468 "blocking read. EOF from client.\n"));
469 return NT_STATUS_END_OF_FILE;
473 return map_nt_error_from_unix(errno);
480 /* Most difficult - timeout read */
481 /* If this is ever called on a disk file and
482 mincnt is greater then the filesize then
483 system performance will suffer severely as
484 select always returns true on disk files */
486 for (nread=0; nread < mincnt; ) {
489 pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
494 return map_nt_error_from_unix(errno);
497 /* Did we timeout ? */
498 if ((pollrtn == 0) ||
499 ((revents & (POLLIN|POLLHUP|POLLERR)) == 0)) {
500 DEBUG(10,("read_fd_with_timeout: timeout read. "
501 "select timed out.\n"));
502 return NT_STATUS_IO_TIMEOUT;
505 readret = sys_read(fd, buf+nread, maxcnt-nread);
508 /* we got EOF on the file descriptor */
509 DEBUG(5,("read_fd_with_timeout: timeout read. "
510 "EOF from client.\n"));
511 return NT_STATUS_END_OF_FILE;
515 return map_nt_error_from_unix(errno);
522 /* Return the number we got */
529 /****************************************************************************
530 Read data from an fd, reading exactly N bytes.
531 NB. This can be called with a non-socket fd, don't add dependencies
533 ****************************************************************************/
535 NTSTATUS read_data(int fd, char *buffer, size_t N)
537 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
540 /****************************************************************************
541 Write all data from an iov array
542 NB. This can be called with a non-socket fd, don't add dependencies
544 ****************************************************************************/
546 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
552 struct iovec *iov_copy, *iov;
555 for (i=0; i<iovcnt; i++) {
556 to_send += orig_iov[i].iov_len;
559 thistime = sys_writev(fd, orig_iov, iovcnt);
560 if ((thistime <= 0) || (thistime == to_send)) {
566 * We could not send everything in one call. Make a copy of iov that
567 * we can mess with. We keep a copy of the array start in iov_copy for
568 * the TALLOC_FREE, because we're going to modify iov later on,
569 * discarding elements.
572 iov_copy = (struct iovec *)TALLOC_MEMDUP(
573 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
575 if (iov_copy == NULL) {
581 while (sent < to_send) {
583 * We have to discard "thistime" bytes from the beginning
584 * iov array, "thistime" contains the number of bytes sent
587 while (thistime > 0) {
588 if (thistime < iov[0].iov_len) {
590 (char *)iov[0].iov_base + thistime;
591 iov[0].iov_base = (void *)new_base;
592 iov[0].iov_len -= thistime;
595 thistime -= iov[0].iov_len;
600 thistime = sys_writev(fd, iov, iovcnt);
607 TALLOC_FREE(iov_copy);
611 /****************************************************************************
613 NB. This can be called with a non-socket fd, don't add dependencies
615 ****************************************************************************/
617 ssize_t write_data(int fd, const char *buffer, size_t N)
621 iov.iov_base = CONST_DISCARD(void *, buffer);
623 return write_data_iov(fd, &iov, 1);
626 /****************************************************************************
627 Send a keepalive packet (rfc1002).
628 ****************************************************************************/
630 bool send_keepalive(int client)
632 unsigned char buf[4];
634 buf[0] = SMBkeepalive;
635 buf[1] = buf[2] = buf[3] = 0;
637 return(write_data(client,(char *)buf,4) == 4);
640 /****************************************************************************
641 Read 4 bytes of a smb packet and return the smb length of the packet.
642 Store the result in the buffer.
643 This version of the function will return a length of zero on receiving
645 Timeout is in milliseconds.
646 ****************************************************************************/
648 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
649 unsigned int timeout,
655 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
657 if (!NT_STATUS_IS_OK(status)) {
661 *len = smb_len(inbuf);
662 msg_type = CVAL(inbuf,0);
664 if (msg_type == SMBkeepalive) {
665 DEBUG(5,("Got keepalive packet\n"));
668 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
673 /****************************************************************************
674 Read an smb from a fd.
675 The timeout is in milliseconds.
676 This function will return on receipt of a session keepalive packet.
677 maxlen is the max number of bytes to return, not including the 4 byte
678 length. If zero it means buflen limit.
679 Doesn't check the MAC on signed packets.
680 ****************************************************************************/
682 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
683 size_t maxlen, size_t *p_len)
688 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
690 if (!NT_STATUS_IS_OK(status)) {
691 DEBUG(0, ("read_fd_with_timeout failed, read "
692 "error = %s.\n", nt_errstr(status)));
697 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
698 (unsigned long)len));
699 return NT_STATUS_INVALID_PARAMETER;
704 len = MIN(len,maxlen);
707 status = read_fd_with_timeout(
708 fd, buffer+4, len, len, timeout, &len);
710 if (!NT_STATUS_IS_OK(status)) {
711 DEBUG(0, ("read_fd_with_timeout failed, read error = "
712 "%s.\n", nt_errstr(status)));
716 /* not all of samba3 properly checks for packet-termination
717 * of strings. This ensures that we don't run off into
719 SSVAL(buffer+4,len, 0);
726 /****************************************************************************
727 Open a socket of the specified type, port, and address for incoming data.
728 ****************************************************************************/
730 int open_socket_in(int type,
733 const struct sockaddr_storage *psock,
736 struct sockaddr_storage sock;
738 socklen_t slen = sizeof(struct sockaddr_in);
742 #if defined(HAVE_IPV6)
743 if (sock.ss_family == AF_INET6) {
744 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
745 slen = sizeof(struct sockaddr_in6);
748 if (sock.ss_family == AF_INET) {
749 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
752 res = socket(sock.ss_family, type, 0 );
755 dbgtext( "open_socket_in(): socket() call failed: " );
756 dbgtext( "%s\n", strerror( errno ) );
761 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
763 int val = rebind ? 1 : 0;
764 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
765 (char *)&val,sizeof(val)) == -1 ) {
766 if( DEBUGLVL( dlevel ) ) {
767 dbgtext( "open_socket_in(): setsockopt: " );
768 dbgtext( "SO_REUSEADDR = %s ",
769 val?"true":"false" );
770 dbgtext( "on port %d failed ", port );
771 dbgtext( "with error = %s\n", strerror(errno) );
775 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
776 (char *)&val,sizeof(val)) == -1 ) {
777 if( DEBUGLVL( dlevel ) ) {
778 dbgtext( "open_socket_in(): setsockopt: ");
779 dbgtext( "SO_REUSEPORT = %s ",
781 dbgtext( "on port %d failed ", port);
782 dbgtext( "with error = %s\n", strerror(errno));
785 #endif /* SO_REUSEPORT */
788 /* now we've got a socket - we need to bind it */
789 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
790 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
791 port == SMB_PORT2 || port == NMB_PORT) ) {
792 char addr[INET6_ADDRSTRLEN];
793 print_sockaddr(addr, sizeof(addr),
795 dbgtext( "bind failed on port %d ", port);
796 dbgtext( "socket_addr = %s.\n", addr);
797 dbgtext( "Error = %s\n", strerror(errno));
803 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
807 struct open_socket_out_state {
809 struct event_context *ev;
810 struct sockaddr_storage ss;
816 static void open_socket_out_connected(struct tevent_req *subreq);
818 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
826 /****************************************************************************
827 Create an outgoing socket. timeout is in milliseconds.
828 **************************************************************************/
830 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
831 struct event_context *ev,
832 const struct sockaddr_storage *pss,
836 char addr[INET6_ADDRSTRLEN];
837 struct tevent_req *result, *subreq;
838 struct open_socket_out_state *state;
841 result = tevent_req_create(mem_ctx, &state,
842 struct open_socket_out_state);
843 if (result == NULL) {
849 state->wait_nsec = 10000;
852 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
853 if (state->fd == -1) {
854 status = map_nt_error_from_unix(errno);
857 talloc_set_destructor(state, open_socket_out_state_destructor);
859 if (!tevent_req_set_endtime(
860 result, ev, timeval_current_ofs(0, timeout*1000))) {
864 #if defined(HAVE_IPV6)
865 if (pss->ss_family == AF_INET6) {
866 struct sockaddr_in6 *psa6;
867 psa6 = (struct sockaddr_in6 *)&state->ss;
868 psa6->sin6_port = htons(port);
869 if (psa6->sin6_scope_id == 0
870 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
871 setup_linklocal_scope_id(
872 (struct sockaddr *)&(state->ss));
874 state->salen = sizeof(struct sockaddr_in6);
877 if (pss->ss_family == AF_INET) {
878 struct sockaddr_in *psa;
879 psa = (struct sockaddr_in *)&state->ss;
880 psa->sin_port = htons(port);
881 state->salen = sizeof(struct sockaddr_in);
884 if (pss->ss_family == AF_UNIX) {
885 state->salen = sizeof(struct sockaddr_un);
888 print_sockaddr(addr, sizeof(addr), &state->ss);
889 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
891 subreq = async_connect_send(state, state->ev, state->fd,
892 (struct sockaddr *)&state->ss,
895 || !tevent_req_set_endtime(
897 timeval_current_ofs(0, state->wait_nsec))) {
900 tevent_req_set_callback(subreq, open_socket_out_connected, result);
904 tevent_req_nterror(result, status);
905 return tevent_req_post(result, ev);
911 static void open_socket_out_connected(struct tevent_req *subreq)
913 struct tevent_req *req =
914 tevent_req_callback_data(subreq, struct tevent_req);
915 struct open_socket_out_state *state =
916 tevent_req_data(req, struct open_socket_out_state);
920 ret = async_connect_recv(subreq, &sys_errno);
923 tevent_req_done(req);
929 (sys_errno == ETIMEDOUT) ||
931 (sys_errno == EINPROGRESS) ||
932 (sys_errno == EALREADY) ||
933 (sys_errno == EAGAIN)) {
939 if (state->wait_nsec < 250000) {
940 state->wait_nsec *= 1.5;
943 subreq = async_connect_send(state, state->ev, state->fd,
944 (struct sockaddr *)&state->ss,
946 if (tevent_req_nomem(subreq, req)) {
949 if (!tevent_req_set_endtime(
951 timeval_current_ofs(0, state->wait_nsec))) {
952 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
955 tevent_req_set_callback(subreq, open_socket_out_connected, req);
960 if (sys_errno == EISCONN) {
961 tevent_req_done(req);
967 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
970 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
972 struct open_socket_out_state *state =
973 tevent_req_data(req, struct open_socket_out_state);
976 if (tevent_req_is_nterror(req, &status)) {
984 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
985 int timeout, int *pfd)
987 TALLOC_CTX *frame = talloc_stackframe();
988 struct event_context *ev;
989 struct tevent_req *req;
990 NTSTATUS status = NT_STATUS_NO_MEMORY;
992 ev = event_context_init(frame);
997 req = open_socket_out_send(frame, ev, pss, port, timeout);
1001 if (!tevent_req_poll(req, ev)) {
1002 status = NT_STATUS_INTERNAL_ERROR;
1005 status = open_socket_out_recv(req, pfd);
1011 struct open_socket_out_defer_state {
1012 struct event_context *ev;
1013 struct sockaddr_storage ss;
1019 static void open_socket_out_defer_waited(struct tevent_req *subreq);
1020 static void open_socket_out_defer_connected(struct tevent_req *subreq);
1022 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
1023 struct event_context *ev,
1024 struct timeval wait_time,
1025 const struct sockaddr_storage *pss,
1029 struct tevent_req *req, *subreq;
1030 struct open_socket_out_defer_state *state;
1032 req = tevent_req_create(mem_ctx, &state,
1033 struct open_socket_out_defer_state);
1040 state->timeout = timeout;
1042 subreq = tevent_wakeup_send(
1044 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
1045 if (subreq == NULL) {
1048 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
1055 static void open_socket_out_defer_waited(struct tevent_req *subreq)
1057 struct tevent_req *req = tevent_req_callback_data(
1058 subreq, struct tevent_req);
1059 struct open_socket_out_defer_state *state = tevent_req_data(
1060 req, struct open_socket_out_defer_state);
1063 ret = tevent_wakeup_recv(subreq);
1064 TALLOC_FREE(subreq);
1066 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1070 subreq = open_socket_out_send(state, state->ev, &state->ss,
1071 state->port, state->timeout);
1072 if (tevent_req_nomem(subreq, req)) {
1075 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
1078 static void open_socket_out_defer_connected(struct tevent_req *subreq)
1080 struct tevent_req *req = tevent_req_callback_data(
1081 subreq, struct tevent_req);
1082 struct open_socket_out_defer_state *state = tevent_req_data(
1083 req, struct open_socket_out_defer_state);
1086 status = open_socket_out_recv(subreq, &state->fd);
1087 TALLOC_FREE(subreq);
1088 if (!NT_STATUS_IS_OK(status)) {
1089 tevent_req_nterror(req, status);
1092 tevent_req_done(req);
1095 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
1097 struct open_socket_out_defer_state *state = tevent_req_data(
1098 req, struct open_socket_out_defer_state);
1101 if (tevent_req_is_nterror(req, &status)) {
1106 return NT_STATUS_OK;
1109 /****************************************************************************
1110 Open a connected UDP socket to host on port
1111 **************************************************************************/
1113 int open_udp_socket(const char *host, int port)
1115 struct sockaddr_storage ss;
1118 if (!interpret_string_addr(&ss, host, 0)) {
1119 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1124 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1129 #if defined(HAVE_IPV6)
1130 if (ss.ss_family == AF_INET6) {
1131 struct sockaddr_in6 *psa6;
1132 psa6 = (struct sockaddr_in6 *)&ss;
1133 psa6->sin6_port = htons(port);
1134 if (psa6->sin6_scope_id == 0
1135 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1136 setup_linklocal_scope_id(
1137 (struct sockaddr *)&ss);
1141 if (ss.ss_family == AF_INET) {
1142 struct sockaddr_in *psa;
1143 psa = (struct sockaddr_in *)&ss;
1144 psa->sin_port = htons(port);
1147 if (sys_connect(res,(struct sockaddr *)&ss)) {
1155 /*******************************************************************
1156 Return the IP addr of the remote end of a socket as a string.
1157 Optionally return the struct sockaddr_storage.
1158 ******************************************************************/
1160 static const char *get_peer_addr_internal(int fd,
1162 size_t addr_buf_len,
1163 struct sockaddr *pss,
1166 struct sockaddr_storage ss;
1167 socklen_t length = sizeof(ss);
1169 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1176 pss = (struct sockaddr *)&ss;
1180 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1181 int level = (errno == ENOTCONN) ? 2 : 0;
1182 DEBUG(level, ("getpeername failed. Error was %s\n",
1187 print_sockaddr_len(addr_buf,
1194 /*******************************************************************
1195 Matchname - determine if host name matches IP address. Used to
1196 confirm a hostname lookup to prevent spoof attacks.
1197 ******************************************************************/
1199 static bool matchname(const char *remotehost,
1200 const struct sockaddr *pss,
1203 struct addrinfo *res = NULL;
1204 struct addrinfo *ailist = NULL;
1205 char addr_buf[INET6_ADDRSTRLEN];
1206 bool ret = interpret_string_addr_internal(&ailist,
1208 AI_ADDRCONFIG|AI_CANONNAME);
1210 if (!ret || ailist == NULL) {
1211 DEBUG(3,("matchname: getaddrinfo failed for "
1214 gai_strerror(ret) ));
1219 * Make sure that getaddrinfo() returns the "correct" host name.
1222 if (ailist->ai_canonname == NULL ||
1223 (!strequal(remotehost, ailist->ai_canonname) &&
1224 !strequal(remotehost, "localhost"))) {
1225 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1227 ailist->ai_canonname ?
1228 ailist->ai_canonname : "(NULL)"));
1229 freeaddrinfo(ailist);
1233 /* Look up the host address in the address list we just got. */
1234 for (res = ailist; res; res = res->ai_next) {
1235 if (!res->ai_addr) {
1238 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1239 (struct sockaddr *)pss)) {
1240 freeaddrinfo(ailist);
1246 * The host name does not map to the original host address. Perhaps
1247 * someone has compromised a name server. More likely someone botched
1248 * it, but that could be dangerous, too.
1251 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1252 print_sockaddr_len(addr_buf,
1256 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1259 freeaddrinfo(ailist);
1264 /*******************************************************************
1265 Deal with the singleton cache.
1266 ******************************************************************/
1268 struct name_addr_pair {
1269 struct sockaddr_storage ss;
1273 /*******************************************************************
1274 Lookup a name/addr pair. Returns memory allocated from memcache.
1275 ******************************************************************/
1277 static bool lookup_nc(struct name_addr_pair *nc)
1283 if (!memcache_lookup(
1284 NULL, SINGLETON_CACHE,
1285 data_blob_string_const_null("get_peer_name"),
1290 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1291 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1295 /*******************************************************************
1296 Save a name/addr pair.
1297 ******************************************************************/
1299 static void store_nc(const struct name_addr_pair *nc)
1302 size_t namelen = strlen(nc->name);
1304 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1308 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1309 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1311 memcache_add(NULL, SINGLETON_CACHE,
1312 data_blob_string_const_null("get_peer_name"),
1314 data_blob_free(&tmp);
1317 /*******************************************************************
1318 Return the DNS name of the remote end of a socket.
1319 ******************************************************************/
1321 const char *get_peer_name(int fd, bool force_lookup)
1323 struct name_addr_pair nc;
1324 char addr_buf[INET6_ADDRSTRLEN];
1325 struct sockaddr_storage ss;
1326 socklen_t length = sizeof(ss);
1329 char name_buf[MAX_DNS_NAME_LENGTH];
1330 char tmp_name[MAX_DNS_NAME_LENGTH];
1332 /* reverse lookups can be *very* expensive, and in many
1333 situations won't work because many networks don't link dhcp
1334 with dns. To avoid the delay we avoid the lookup if
1336 if (!lp_hostname_lookups() && (force_lookup == false)) {
1337 length = sizeof(nc.ss);
1338 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1339 (struct sockaddr *)&nc.ss, &length);
1342 return nc.name ? nc.name : "UNKNOWN";
1347 memset(&ss, '\0', sizeof(ss));
1348 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1350 /* it might be the same as the last one - save some DNS work */
1351 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1352 return nc.name ? nc.name : "UNKNOWN";
1355 /* Not the same. We need to lookup. */
1360 /* Look up the remote host name. */
1361 ret = sys_getnameinfo((struct sockaddr *)&ss,
1370 DEBUG(1,("get_peer_name: getnameinfo failed "
1371 "for %s with error %s\n",
1373 gai_strerror(ret)));
1374 strlcpy(name_buf, p, sizeof(name_buf));
1376 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1377 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1378 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1382 /* can't pass the same source and dest strings in when you
1383 use --enable-developer or the clobber_region() call will
1386 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1387 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1388 if (strstr(name_buf,"..")) {
1389 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1397 return nc.name ? nc.name : "UNKNOWN";
1400 /*******************************************************************
1401 Return the IP addr of the remote end of a socket as a string.
1402 ******************************************************************/
1404 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1406 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1409 /*******************************************************************
1410 Create protected unix domain socket.
1412 Some unixes cannot set permissions on a ux-dom-sock, so we
1413 have to make sure that the directory contains the protection
1414 permissions instead.
1415 ******************************************************************/
1417 int create_pipe_sock(const char *socket_dir,
1418 const char *socket_name,
1421 #ifdef HAVE_UNIXSOCKET
1422 struct sockaddr_un sunaddr;
1428 old_umask = umask(0);
1430 /* Create the socket directory or reuse the existing one */
1432 if (lstat(socket_dir, &st) == -1) {
1433 if (errno == ENOENT) {
1434 /* Create directory */
1435 if (mkdir(socket_dir, dir_perms) == -1) {
1436 DEBUG(0, ("error creating socket directory "
1437 "%s: %s\n", socket_dir,
1442 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1443 socket_dir, strerror(errno)));
1447 /* Check ownership and permission on existing directory */
1448 if (!S_ISDIR(st.st_mode)) {
1449 DEBUG(0, ("socket directory %s isn't a directory\n",
1453 if ((st.st_uid != sec_initial_uid()) ||
1454 ((st.st_mode & 0777) != dir_perms)) {
1455 DEBUG(0, ("invalid permissions on socket directory "
1456 "%s\n", socket_dir));
1461 /* Create the socket file */
1463 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1466 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1471 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1476 memset(&sunaddr, 0, sizeof(sunaddr));
1477 sunaddr.sun_family = AF_UNIX;
1478 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1480 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1481 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1486 if (listen(sock, 5) == -1) {
1487 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1507 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1509 #endif /* HAVE_UNIXSOCKET */
1512 /****************************************************************************
1513 Get my own canonical name, including domain.
1514 ****************************************************************************/
1516 const char *get_mydnsfullname(void)
1518 struct addrinfo *res = NULL;
1519 char my_hostname[HOST_NAME_MAX];
1523 if (memcache_lookup(NULL, SINGLETON_CACHE,
1524 data_blob_string_const_null("get_mydnsfullname"),
1526 SMB_ASSERT(tmp.length > 0);
1527 return (const char *)tmp.data;
1530 /* get my host name */
1531 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1532 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1536 /* Ensure null termination. */
1537 my_hostname[sizeof(my_hostname)-1] = '\0';
1539 ret = interpret_string_addr_internal(&res,
1541 AI_ADDRCONFIG|AI_CANONNAME);
1543 if (!ret || res == NULL) {
1544 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1547 gai_strerror(ret) ));
1552 * Make sure that getaddrinfo() returns the "correct" host name.
1555 if (res->ai_canonname == NULL) {
1556 DEBUG(3,("get_mydnsfullname: failed to get "
1557 "canonical name for %s\n",
1563 /* This copies the data, so we must do a lookup
1564 * afterwards to find the value to return.
1567 memcache_add(NULL, SINGLETON_CACHE,
1568 data_blob_string_const_null("get_mydnsfullname"),
1569 data_blob_string_const_null(res->ai_canonname));
1571 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1572 data_blob_string_const_null("get_mydnsfullname"),
1574 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1575 strlen(res->ai_canonname) + 1);
1580 return (const char *)tmp.data;
1583 /************************************************************
1585 ************************************************************/
1587 bool is_myname_or_ipaddr(const char *s)
1589 TALLOC_CTX *ctx = talloc_tos();
1590 char addr[INET6_ADDRSTRLEN];
1592 const char *dnsname;
1593 char *servername = NULL;
1599 /* Santize the string from '\\name' */
1600 name = talloc_strdup(ctx, s);
1605 servername = strrchr_m(name, '\\' );
1612 /* Optimize for the common case */
1613 if (strequal(servername, global_myname())) {
1617 /* Check for an alias */
1618 if (is_myname(servername)) {
1622 /* Check for loopback */
1623 if (strequal(servername, "127.0.0.1") ||
1624 strequal(servername, "::1")) {
1628 if (strequal(servername, "localhost")) {
1632 /* Maybe it's my dns name */
1633 dnsname = get_mydnsfullname();
1634 if (dnsname && strequal(servername, dnsname)) {
1638 /* Handle possible CNAME records - convert to an IP addr. */
1639 if (!is_ipaddress(servername)) {
1640 /* Use DNS to resolve the name, but only the first address */
1641 struct sockaddr_storage ss;
1642 if (interpret_string_addr(&ss, servername, 0)) {
1643 print_sockaddr(addr,
1650 /* Maybe its an IP address? */
1651 if (is_ipaddress(servername)) {
1652 struct sockaddr_storage ss;
1653 struct iface_struct *nics;
1656 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
1660 if (ismyaddr((struct sockaddr *)&ss)) {
1664 if (is_zero_addr(&ss) ||
1665 is_loopback_addr((struct sockaddr *)&ss)) {
1669 n = get_interfaces(talloc_tos(), &nics);
1670 for (i=0; i<n; i++) {
1671 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1683 struct getaddrinfo_state {
1685 const char *service;
1686 const struct addrinfo *hints;
1687 struct addrinfo *res;
1691 static void getaddrinfo_do(void *private_data);
1692 static void getaddrinfo_done(struct tevent_req *subreq);
1694 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1695 struct tevent_context *ev,
1696 struct fncall_context *ctx,
1698 const char *service,
1699 const struct addrinfo *hints)
1701 struct tevent_req *req, *subreq;
1702 struct getaddrinfo_state *state;
1704 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1710 state->service = service;
1711 state->hints = hints;
1713 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1714 if (tevent_req_nomem(subreq, req)) {
1715 return tevent_req_post(req, ev);
1717 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1721 static void getaddrinfo_do(void *private_data)
1723 struct getaddrinfo_state *state =
1724 (struct getaddrinfo_state *)private_data;
1726 state->ret = getaddrinfo(state->node, state->service, state->hints,
1730 static void getaddrinfo_done(struct tevent_req *subreq)
1732 struct tevent_req *req = tevent_req_callback_data(
1733 subreq, struct tevent_req);
1736 ret = fncall_recv(subreq, &err);
1737 TALLOC_FREE(subreq);
1739 tevent_req_error(req, err);
1742 tevent_req_done(req);
1745 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1747 struct getaddrinfo_state *state = tevent_req_data(
1748 req, struct getaddrinfo_state);
1751 if (tevent_req_is_unix_error(req, &err)) {
1759 if (state->ret == 0) {
1765 int poll_one_fd(int fd, int events, int timeout, int *revents)
1771 fds = TALLOC_ZERO_ARRAY(talloc_tos(), struct pollfd, 2);
1777 fds[0].events = events;
1779 ret = sys_poll(fds, 1, timeout);
1782 * Assign whatever poll did, even in the ret<=0 case.
1784 *revents = fds[0].revents;
1785 saved_errno = errno;
1787 errno = saved_errno;
1792 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1798 pfd.events = events;
1800 ret = sys_poll_intr(&pfd, 1, timeout);
1805 *revents = pfd.revents;