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/>.
25 /****************************************************************************
26 Get a port number in host byte order from a sockaddr_storage.
27 ****************************************************************************/
29 uint16_t get_sockaddr_port(const struct sockaddr_storage *pss)
33 if (pss->ss_family != AF_INET) {
34 #if defined(HAVE_IPV6)
36 const struct sockaddr_in6 *sa6 =
37 (const struct sockaddr_in6 *)pss;
38 port = ntohs(sa6->sin6_port);
41 const struct sockaddr_in *sa =
42 (const struct sockaddr_in *)pss;
43 port = ntohs(sa->sin_port);
48 /****************************************************************************
49 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
50 ****************************************************************************/
52 static char *print_sockaddr_len(char *dest,
54 const struct sockaddr *psa,
60 (void)sys_getnameinfo(psa,
68 /****************************************************************************
69 Print out an IPv4 or IPv6 address from a struct sockaddr_storage.
70 ****************************************************************************/
72 char *print_sockaddr(char *dest,
74 const struct sockaddr_storage *psa)
76 return print_sockaddr_len(dest, destlen, (struct sockaddr *)psa,
77 sizeof(struct sockaddr_storage));
80 /****************************************************************************
81 Print out a canonical IPv4 or IPv6 address from a struct sockaddr_storage.
82 ****************************************************************************/
84 char *print_canonical_sockaddr(TALLOC_CTX *ctx,
85 const struct sockaddr_storage *pss)
87 char addr[INET6_ADDRSTRLEN];
91 /* Linux getnameinfo() man pages says port is unitialized if
92 service name is NULL. */
94 ret = sys_getnameinfo((const struct sockaddr *)pss,
95 sizeof(struct sockaddr_storage),
103 if (pss->ss_family != AF_INET) {
104 #if defined(HAVE_IPV6)
105 dest = talloc_asprintf(ctx, "[%s]", addr);
110 dest = talloc_asprintf(ctx, "%s", addr);
116 /****************************************************************************
117 Return the string of an IP address (IPv4 or IPv6).
118 ****************************************************************************/
120 static const char *get_socket_addr(int fd, char *addr_buf, size_t addr_len)
122 struct sockaddr_storage sa;
123 socklen_t length = sizeof(sa);
125 /* Ok, returning a hard coded IPv4 address
126 * is bogus, but it's just as bogus as a
127 * zero IPv6 address. No good choice here.
130 strlcpy(addr_buf, "0.0.0.0", addr_len);
136 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
137 DEBUG(0,("getsockname failed. Error was %s\n",
142 return print_sockaddr_len(addr_buf, addr_len, (struct sockaddr *)&sa, length);
145 /****************************************************************************
146 Return the port number we've bound to on a socket.
147 ****************************************************************************/
149 int get_socket_port(int fd)
151 struct sockaddr_storage sa;
152 socklen_t length = sizeof(sa);
158 if (getsockname(fd, (struct sockaddr *)&sa, &length) < 0) {
159 int level = (errno == ENOTCONN) ? 2 : 0;
160 DEBUG(level, ("getpeername failed. Error was %s\n",
165 #if defined(HAVE_IPV6)
166 if (sa.ss_family == AF_INET6) {
167 return ntohs(((struct sockaddr_in6 *)&sa)->sin6_port);
170 if (sa.ss_family == AF_INET) {
171 return ntohs(((struct sockaddr_in *)&sa)->sin_port);
176 const char *client_name(int fd)
178 return get_peer_name(fd,false);
181 const char *client_addr(int fd, char *addr, size_t addrlen)
183 return get_peer_addr(fd,addr,addrlen);
186 const char *client_socket_addr(int fd, char *addr, size_t addr_len)
188 return get_socket_addr(fd, addr, addr_len);
192 /* Not currently used. JRA. */
193 int client_socket_port(int fd)
195 return get_socket_port(fd);
199 /****************************************************************************
200 Accessor functions to make thread-safe code easier later...
201 ****************************************************************************/
203 void set_smb_read_error(enum smb_read_errors *pre,
204 enum smb_read_errors newerr)
211 void cond_set_smb_read_error(enum smb_read_errors *pre,
212 enum smb_read_errors newerr)
214 if (pre && *pre == SMB_READ_OK) {
219 /****************************************************************************
220 Determine if a file descriptor is in fact a socket.
221 ****************************************************************************/
223 bool is_a_socket(int fd)
228 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
231 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
233 typedef struct smb_socket_option {
241 static const smb_socket_option socket_options[] = {
242 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
243 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
244 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
246 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
249 {"TCP_KEEPCNT", IPPROTO_TCP, TCP_KEEPCNT, 0, OPT_INT},
252 {"TCP_KEEPIDLE", IPPROTO_TCP, TCP_KEEPIDLE, 0, OPT_INT},
255 {"TCP_KEEPINTVL", IPPROTO_TCP, TCP_KEEPINTVL, 0, OPT_INT},
257 #ifdef IPTOS_LOWDELAY
258 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
260 #ifdef IPTOS_THROUGHPUT
261 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
264 {"SO_REUSEPORT", SOL_SOCKET, SO_REUSEPORT, 0, OPT_BOOL},
267 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
270 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
273 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
276 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
279 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
282 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
285 {"TCP_FASTACK", IPPROTO_TCP, TCP_FASTACK, 0, OPT_INT},
288 {"TCP_QUICKACK", IPPROTO_TCP, TCP_QUICKACK, 0, OPT_BOOL},
292 /****************************************************************************
293 Print socket options.
294 ****************************************************************************/
296 static void print_socket_options(int s)
300 const smb_socket_option *p = &socket_options[0];
302 /* wrapped in if statement to prevent streams
303 * leak in SCO Openserver 5.0 */
304 /* reported on samba-technical --jerry */
305 if ( DEBUGLEVEL >= 5 ) {
306 DEBUG(5,("Socket options:\n"));
307 for (; p->name != NULL; p++) {
308 if (getsockopt(s, p->level, p->option,
309 (void *)&value, &vlen) == -1) {
310 DEBUGADD(5,("\tCould not test socket option %s.\n",
313 DEBUGADD(5,("\t%s = %d\n",
320 /****************************************************************************
321 Set user socket options.
322 ****************************************************************************/
324 void set_socket_options(int fd, const char *options)
326 TALLOC_CTX *ctx = talloc_stackframe();
329 while (next_token_talloc(ctx, &options, &tok," \t,")) {
333 bool got_value = false;
335 if ((p = strchr_m(tok,'='))) {
341 for (i=0;socket_options[i].name;i++)
342 if (strequal(socket_options[i].name,tok))
345 if (!socket_options[i].name) {
346 DEBUG(0,("Unknown socket option %s\n",tok));
350 switch (socket_options[i].opttype) {
353 ret = setsockopt(fd,socket_options[i].level,
354 socket_options[i].option,
355 (char *)&value,sizeof(int));
360 DEBUG(0,("syntax error - %s "
361 "does not take a value\n",tok));
364 int on = socket_options[i].value;
365 ret = setsockopt(fd,socket_options[i].level,
366 socket_options[i].option,
367 (char *)&on,sizeof(int));
373 /* be aware that some systems like Solaris return
374 * EINVAL to a setsockopt() call when the client
375 * sent a RST previously - no need to worry */
376 DEBUG(2,("Failed to set socket option %s (Error %s)\n",
377 tok, strerror(errno) ));
382 print_socket_options(fd);
385 /****************************************************************************
387 ****************************************************************************/
389 ssize_t read_udp_v4_socket(int fd,
392 struct sockaddr_storage *psa)
395 socklen_t socklen = sizeof(*psa);
396 struct sockaddr_in *si = (struct sockaddr_in *)psa;
398 memset((char *)psa,'\0',socklen);
400 ret = (ssize_t)sys_recvfrom(fd,buf,len,0,
401 (struct sockaddr *)psa,&socklen);
403 /* Don't print a low debug error for a non-blocking socket. */
404 if (errno == EAGAIN) {
405 DEBUG(10,("read_udp_v4_socket: returned EAGAIN\n"));
407 DEBUG(2,("read_udp_v4_socket: failed. errno=%s\n",
413 if (psa->ss_family != AF_INET) {
414 DEBUG(2,("read_udp_v4_socket: invalid address family %d "
415 "(not IPv4)\n", (int)psa->ss_family));
419 DEBUG(10,("read_udp_v4_socket: ip %s port %d read: %lu\n",
420 inet_ntoa(si->sin_addr),
422 (unsigned long)ret));
427 /****************************************************************************
428 Read data from a file descriptor with a timout in msec.
429 mincount = if timeout, minimum to read before returning
430 maxcount = number to be read.
431 time_out = timeout in milliseconds
432 NB. This can be called with a non-socket fd, don't change
433 sys_read() to sys_recv() or other socket call.
434 ****************************************************************************/
436 NTSTATUS read_fd_with_timeout(int fd, char *buf,
437 size_t mincnt, size_t maxcnt,
438 unsigned int time_out,
445 struct timeval timeout;
447 /* just checking .... */
457 while (nread < mincnt) {
458 readret = sys_read(fd, buf + nread, maxcnt - nread);
461 DEBUG(5,("read_fd_with_timeout: "
462 "blocking read. EOF from client.\n"));
463 return NT_STATUS_END_OF_FILE;
467 return map_nt_error_from_unix(errno);
474 /* Most difficult - timeout read */
475 /* If this is ever called on a disk file and
476 mincnt is greater then the filesize then
477 system performance will suffer severely as
478 select always returns true on disk files */
480 /* Set initial timeout */
481 timeout.tv_sec = (time_t)(time_out / 1000);
482 timeout.tv_usec = (long)(1000 * (time_out % 1000));
484 for (nread=0; nread < mincnt; ) {
488 selrtn = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout);
492 return map_nt_error_from_unix(errno);
495 /* Did we timeout ? */
497 DEBUG(10,("read_fd_with_timeout: timeout read. "
498 "select timed out.\n"));
499 return NT_STATUS_IO_TIMEOUT;
502 readret = sys_read(fd, buf+nread, maxcnt-nread);
505 /* we got EOF on the file descriptor */
506 DEBUG(5,("read_fd_with_timeout: timeout read. "
507 "EOF from client.\n"));
508 return NT_STATUS_END_OF_FILE;
512 return map_nt_error_from_unix(errno);
519 /* Return the number we got */
526 /****************************************************************************
527 Read data from an fd, reading exactly N bytes.
528 NB. This can be called with a non-socket fd, don't add dependencies
530 ****************************************************************************/
532 NTSTATUS read_data(int fd, char *buffer, size_t N)
534 return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
537 /****************************************************************************
538 Write all data from an iov array
539 NB. This can be called with a non-socket fd, don't add dependencies
541 ****************************************************************************/
543 ssize_t write_data_iov(int fd, const struct iovec *orig_iov, int iovcnt)
549 struct iovec *iov_copy, *iov;
552 for (i=0; i<iovcnt; i++) {
553 to_send += orig_iov[i].iov_len;
556 thistime = sys_writev(fd, orig_iov, iovcnt);
557 if ((thistime <= 0) || (thistime == to_send)) {
563 * We could not send everything in one call. Make a copy of iov that
564 * we can mess with. We keep a copy of the array start in iov_copy for
565 * the TALLOC_FREE, because we're going to modify iov later on,
566 * discarding elements.
569 iov_copy = (struct iovec *)TALLOC_MEMDUP(
570 talloc_tos(), orig_iov, sizeof(struct iovec) * iovcnt);
572 if (iov_copy == NULL) {
578 while (sent < to_send) {
580 * We have to discard "thistime" bytes from the beginning
581 * iov array, "thistime" contains the number of bytes sent
584 while (thistime > 0) {
585 if (thistime < iov[0].iov_len) {
587 (char *)iov[0].iov_base + thistime;
588 iov[0].iov_base = (void *)new_base;
589 iov[0].iov_len -= thistime;
592 thistime -= iov[0].iov_len;
597 thistime = sys_writev(fd, iov, iovcnt);
604 TALLOC_FREE(iov_copy);
608 /****************************************************************************
610 NB. This can be called with a non-socket fd, don't add dependencies
612 ****************************************************************************/
614 ssize_t write_data(int fd, const char *buffer, size_t N)
618 iov.iov_base = CONST_DISCARD(void *, buffer);
620 return write_data_iov(fd, &iov, 1);
623 /****************************************************************************
624 Send a keepalive packet (rfc1002).
625 ****************************************************************************/
627 bool send_keepalive(int client)
629 unsigned char buf[4];
631 buf[0] = SMBkeepalive;
632 buf[1] = buf[2] = buf[3] = 0;
634 return(write_data(client,(char *)buf,4) == 4);
637 /****************************************************************************
638 Read 4 bytes of a smb packet and return the smb length of the packet.
639 Store the result in the buffer.
640 This version of the function will return a length of zero on receiving
642 Timeout is in milliseconds.
643 ****************************************************************************/
645 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
646 unsigned int timeout,
652 status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
654 if (!NT_STATUS_IS_OK(status)) {
658 *len = smb_len(inbuf);
659 msg_type = CVAL(inbuf,0);
661 if (msg_type == SMBkeepalive) {
662 DEBUG(5,("Got keepalive packet\n"));
665 DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
670 /****************************************************************************
671 Read an smb from a fd.
672 The timeout is in milliseconds.
673 This function will return on receipt of a session keepalive packet.
674 maxlen is the max number of bytes to return, not including the 4 byte
675 length. If zero it means buflen limit.
676 Doesn't check the MAC on signed packets.
677 ****************************************************************************/
679 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
680 size_t maxlen, size_t *p_len)
685 status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
687 if (!NT_STATUS_IS_OK(status)) {
688 DEBUG(0, ("read_fd_with_timeout failed, read "
689 "error = %s.\n", nt_errstr(status)));
694 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
695 (unsigned long)len));
696 return NT_STATUS_INVALID_PARAMETER;
701 len = MIN(len,maxlen);
704 status = read_fd_with_timeout(
705 fd, buffer+4, len, len, timeout, &len);
707 if (!NT_STATUS_IS_OK(status)) {
708 DEBUG(0, ("read_fd_with_timeout failed, read error = "
709 "%s.\n", nt_errstr(status)));
713 /* not all of samba3 properly checks for packet-termination
714 * of strings. This ensures that we don't run off into
716 SSVAL(buffer+4,len, 0);
723 /****************************************************************************
724 Open a socket of the specified type, port, and address for incoming data.
725 ****************************************************************************/
727 int open_socket_in(int type,
730 const struct sockaddr_storage *psock,
733 struct sockaddr_storage sock;
735 socklen_t slen = sizeof(struct sockaddr_in);
739 #if defined(HAVE_IPV6)
740 if (sock.ss_family == AF_INET6) {
741 ((struct sockaddr_in6 *)&sock)->sin6_port = htons(port);
742 slen = sizeof(struct sockaddr_in6);
745 if (sock.ss_family == AF_INET) {
746 ((struct sockaddr_in *)&sock)->sin_port = htons(port);
749 res = socket(sock.ss_family, type, 0 );
752 dbgtext( "open_socket_in(): socket() call failed: " );
753 dbgtext( "%s\n", strerror( errno ) );
758 /* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
760 int val = rebind ? 1 : 0;
761 if( setsockopt(res,SOL_SOCKET,SO_REUSEADDR,
762 (char *)&val,sizeof(val)) == -1 ) {
763 if( DEBUGLVL( dlevel ) ) {
764 dbgtext( "open_socket_in(): setsockopt: " );
765 dbgtext( "SO_REUSEADDR = %s ",
766 val?"true":"false" );
767 dbgtext( "on port %d failed ", port );
768 dbgtext( "with error = %s\n", strerror(errno) );
772 if( setsockopt(res,SOL_SOCKET,SO_REUSEPORT,
773 (char *)&val,sizeof(val)) == -1 ) {
774 if( DEBUGLVL( dlevel ) ) {
775 dbgtext( "open_socket_in(): setsockopt: ");
776 dbgtext( "SO_REUSEPORT = %s ",
778 dbgtext( "on port %d failed ", port);
779 dbgtext( "with error = %s\n", strerror(errno));
782 #endif /* SO_REUSEPORT */
785 /* now we've got a socket - we need to bind it */
786 if (bind(res, (struct sockaddr *)&sock, slen) == -1 ) {
787 if( DEBUGLVL(dlevel) && (port == SMB_PORT1 ||
788 port == SMB_PORT2 || port == NMB_PORT) ) {
789 char addr[INET6_ADDRSTRLEN];
790 print_sockaddr(addr, sizeof(addr),
792 dbgtext( "bind failed on port %d ", port);
793 dbgtext( "socket_addr = %s.\n", addr);
794 dbgtext( "Error = %s\n", strerror(errno));
800 DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
804 struct open_socket_out_state {
806 struct event_context *ev;
807 struct sockaddr_storage ss;
813 static void open_socket_out_connected(struct tevent_req *subreq);
815 static int open_socket_out_state_destructor(struct open_socket_out_state *s)
823 /****************************************************************************
824 Create an outgoing socket. timeout is in milliseconds.
825 **************************************************************************/
827 struct tevent_req *open_socket_out_send(TALLOC_CTX *mem_ctx,
828 struct event_context *ev,
829 const struct sockaddr_storage *pss,
833 char addr[INET6_ADDRSTRLEN];
834 struct tevent_req *result, *subreq;
835 struct open_socket_out_state *state;
838 result = tevent_req_create(mem_ctx, &state,
839 struct open_socket_out_state);
840 if (result == NULL) {
846 state->wait_nsec = 10000;
849 state->fd = socket(state->ss.ss_family, SOCK_STREAM, 0);
850 if (state->fd == -1) {
851 status = map_nt_error_from_unix(errno);
854 talloc_set_destructor(state, open_socket_out_state_destructor);
856 if (!tevent_req_set_endtime(
857 result, ev, timeval_current_ofs(0, timeout*1000))) {
861 #if defined(HAVE_IPV6)
862 if (pss->ss_family == AF_INET6) {
863 struct sockaddr_in6 *psa6;
864 psa6 = (struct sockaddr_in6 *)&state->ss;
865 psa6->sin6_port = htons(port);
866 if (psa6->sin6_scope_id == 0
867 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
868 setup_linklocal_scope_id(
869 (struct sockaddr *)&(state->ss));
871 state->salen = sizeof(struct sockaddr_in6);
874 if (pss->ss_family == AF_INET) {
875 struct sockaddr_in *psa;
876 psa = (struct sockaddr_in *)&state->ss;
877 psa->sin_port = htons(port);
878 state->salen = sizeof(struct sockaddr_in);
881 if (pss->ss_family == AF_UNIX) {
882 state->salen = sizeof(struct sockaddr_un);
885 print_sockaddr(addr, sizeof(addr), &state->ss);
886 DEBUG(3,("Connecting to %s at port %u\n", addr, (unsigned int)port));
888 subreq = async_connect_send(state, state->ev, state->fd,
889 (struct sockaddr *)&state->ss,
892 || !tevent_req_set_endtime(
894 timeval_current_ofs(0, state->wait_nsec))) {
897 tevent_req_set_callback(subreq, open_socket_out_connected, result);
901 tevent_req_nterror(result, status);
902 return tevent_req_post(result, ev);
908 static void open_socket_out_connected(struct tevent_req *subreq)
910 struct tevent_req *req =
911 tevent_req_callback_data(subreq, struct tevent_req);
912 struct open_socket_out_state *state =
913 tevent_req_data(req, struct open_socket_out_state);
917 ret = async_connect_recv(subreq, &sys_errno);
920 tevent_req_done(req);
926 (sys_errno == ETIMEDOUT) ||
928 (sys_errno == EINPROGRESS) ||
929 (sys_errno == EALREADY) ||
930 (sys_errno == EAGAIN)) {
936 if (state->wait_nsec < 250000) {
937 state->wait_nsec *= 1.5;
940 subreq = async_connect_send(state, state->ev, state->fd,
941 (struct sockaddr *)&state->ss,
943 if (tevent_req_nomem(subreq, req)) {
946 if (!tevent_req_set_endtime(
948 timeval_current_ofs(0, state->wait_nsec))) {
949 tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
952 tevent_req_set_callback(subreq, open_socket_out_connected, req);
957 if (sys_errno == EISCONN) {
958 tevent_req_done(req);
964 tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
967 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
969 struct open_socket_out_state *state =
970 tevent_req_data(req, struct open_socket_out_state);
973 if (tevent_req_is_nterror(req, &status)) {
981 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
982 int timeout, int *pfd)
984 TALLOC_CTX *frame = talloc_stackframe();
985 struct event_context *ev;
986 struct tevent_req *req;
987 NTSTATUS status = NT_STATUS_NO_MEMORY;
989 ev = event_context_init(frame);
994 req = open_socket_out_send(frame, ev, pss, port, timeout);
998 if (!tevent_req_poll(req, ev)) {
999 status = NT_STATUS_INTERNAL_ERROR;
1002 status = open_socket_out_recv(req, pfd);
1008 struct open_socket_out_defer_state {
1009 struct event_context *ev;
1010 struct sockaddr_storage ss;
1016 static void open_socket_out_defer_waited(struct tevent_req *subreq);
1017 static void open_socket_out_defer_connected(struct tevent_req *subreq);
1019 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
1020 struct event_context *ev,
1021 struct timeval wait_time,
1022 const struct sockaddr_storage *pss,
1026 struct tevent_req *req, *subreq;
1027 struct open_socket_out_defer_state *state;
1029 req = tevent_req_create(mem_ctx, &state,
1030 struct open_socket_out_defer_state);
1037 state->timeout = timeout;
1039 subreq = tevent_wakeup_send(
1041 timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
1042 if (subreq == NULL) {
1045 tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
1052 static void open_socket_out_defer_waited(struct tevent_req *subreq)
1054 struct tevent_req *req = tevent_req_callback_data(
1055 subreq, struct tevent_req);
1056 struct open_socket_out_defer_state *state = tevent_req_data(
1057 req, struct open_socket_out_defer_state);
1060 ret = tevent_wakeup_recv(subreq);
1061 TALLOC_FREE(subreq);
1063 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1067 subreq = open_socket_out_send(state, state->ev, &state->ss,
1068 state->port, state->timeout);
1069 if (tevent_req_nomem(subreq, req)) {
1072 tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
1075 static void open_socket_out_defer_connected(struct tevent_req *subreq)
1077 struct tevent_req *req = tevent_req_callback_data(
1078 subreq, struct tevent_req);
1079 struct open_socket_out_defer_state *state = tevent_req_data(
1080 req, struct open_socket_out_defer_state);
1083 status = open_socket_out_recv(subreq, &state->fd);
1084 TALLOC_FREE(subreq);
1085 if (!NT_STATUS_IS_OK(status)) {
1086 tevent_req_nterror(req, status);
1089 tevent_req_done(req);
1092 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
1094 struct open_socket_out_defer_state *state = tevent_req_data(
1095 req, struct open_socket_out_defer_state);
1098 if (tevent_req_is_nterror(req, &status)) {
1103 return NT_STATUS_OK;
1106 /*******************************************************************
1107 Create an outgoing TCP socket to the first addr that connects.
1109 This is for simultaneous connection attempts to port 445 and 139 of a host
1110 or for simultatneous connection attempts to multiple DCs at once. We return
1111 a socket fd of the first successful connection.
1113 @param[in] addrs list of Internet addresses and ports to connect to
1114 @param[in] num_addrs number of address/port pairs in the addrs list
1115 @param[in] timeout time after which we stop waiting for a socket connection
1116 to succeed, given in milliseconds
1117 @param[out] fd_index the entry in addrs which we successfully connected to
1118 @param[out] fd fd of the open and connected socket
1119 @return true on a successful connection, false if all connection attempts
1120 failed or we timed out
1121 *******************************************************************/
1123 bool open_any_socket_out(struct sockaddr_storage *addrs, int num_addrs,
1124 int timeout, int *fd_index, int *fd)
1126 int i, resulting_index, res;
1130 fd_set r_fds, wr_fds;
1134 int connect_loop = 10000; /* 10 milliseconds */
1136 timeout *= 1000; /* convert to microseconds */
1138 sockets = SMB_MALLOC_ARRAY(int, num_addrs);
1140 if (sockets == NULL)
1143 resulting_index = -1;
1145 for (i=0; i<num_addrs; i++)
1148 for (i=0; i<num_addrs; i++) {
1149 sockets[i] = socket(addrs[i].ss_family, SOCK_STREAM, 0);
1152 set_blocking(sockets[i], false);
1156 good_connect = false;
1158 for (i=0; i<num_addrs; i++) {
1159 const struct sockaddr * a =
1160 (const struct sockaddr *)&(addrs[i]);
1162 if (sockets[i] == -1)
1165 if (sys_connect(sockets[i], a) == 0) {
1166 /* Rather unlikely as we are non-blocking, but it
1167 * might actually happen. */
1168 resulting_index = i;
1172 if (errno == EINPROGRESS || errno == EALREADY ||
1176 errno == EAGAIN || errno == EINTR) {
1177 /* These are the error messages that something is
1179 good_connect = true;
1180 } else if (errno != 0) {
1181 /* There was a direct error */
1187 if (!good_connect) {
1188 /* All of the connect's resulted in real error conditions */
1192 /* Lets see if any of the connect attempts succeeded */
1198 for (i=0; i<num_addrs; i++) {
1199 if (sockets[i] == -1)
1201 FD_SET(sockets[i], &wr_fds);
1202 FD_SET(sockets[i], &r_fds);
1203 if (sockets[i]>maxfd)
1208 tv.tv_usec = connect_loop;
1210 res = sys_select_intr(maxfd+1, &r_fds, &wr_fds, NULL, &tv);
1218 for (i=0; i<num_addrs; i++) {
1220 if (sockets[i] == -1)
1223 /* Stevens, Network Programming says that if there's a
1224 * successful connect, the socket is only writable. Upon an
1225 * error, it's both readable and writable. */
1227 if (FD_ISSET(sockets[i], &r_fds) &&
1228 FD_ISSET(sockets[i], &wr_fds)) {
1229 /* readable and writable, so it's an error */
1235 if (!FD_ISSET(sockets[i], &r_fds) &&
1236 FD_ISSET(sockets[i], &wr_fds)) {
1237 /* Only writable, so it's connected */
1238 resulting_index = i;
1245 timeout -= connect_loop;
1248 connect_loop *= 1.5;
1249 if (connect_loop > timeout)
1250 connect_loop = timeout;
1254 for (i=0; i<num_addrs; i++) {
1255 if (i == resulting_index)
1257 if (sockets[i] >= 0)
1261 if (resulting_index >= 0) {
1262 *fd_index = resulting_index;
1263 *fd = sockets[*fd_index];
1264 set_blocking(*fd, true);
1269 return (resulting_index >= 0);
1271 /****************************************************************************
1272 Open a connected UDP socket to host on port
1273 **************************************************************************/
1275 int open_udp_socket(const char *host, int port)
1277 struct sockaddr_storage ss;
1280 if (!interpret_string_addr(&ss, host, 0)) {
1281 DEBUG(10,("open_udp_socket: can't resolve name %s\n",
1286 res = socket(ss.ss_family, SOCK_DGRAM, 0);
1291 #if defined(HAVE_IPV6)
1292 if (ss.ss_family == AF_INET6) {
1293 struct sockaddr_in6 *psa6;
1294 psa6 = (struct sockaddr_in6 *)&ss;
1295 psa6->sin6_port = htons(port);
1296 if (psa6->sin6_scope_id == 0
1297 && IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
1298 setup_linklocal_scope_id(
1299 (struct sockaddr *)&ss);
1303 if (ss.ss_family == AF_INET) {
1304 struct sockaddr_in *psa;
1305 psa = (struct sockaddr_in *)&ss;
1306 psa->sin_port = htons(port);
1309 if (sys_connect(res,(struct sockaddr *)&ss)) {
1317 /*******************************************************************
1318 Return the IP addr of the remote end of a socket as a string.
1319 Optionally return the struct sockaddr_storage.
1320 ******************************************************************/
1322 static const char *get_peer_addr_internal(int fd,
1324 size_t addr_buf_len,
1325 struct sockaddr *pss,
1328 struct sockaddr_storage ss;
1329 socklen_t length = sizeof(ss);
1331 strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
1338 pss = (struct sockaddr *)&ss;
1342 if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
1343 int level = (errno == ENOTCONN) ? 2 : 0;
1344 DEBUG(level, ("getpeername failed. Error was %s\n",
1349 print_sockaddr_len(addr_buf,
1356 /*******************************************************************
1357 Matchname - determine if host name matches IP address. Used to
1358 confirm a hostname lookup to prevent spoof attacks.
1359 ******************************************************************/
1361 static bool matchname(const char *remotehost,
1362 const struct sockaddr *pss,
1365 struct addrinfo *res = NULL;
1366 struct addrinfo *ailist = NULL;
1367 char addr_buf[INET6_ADDRSTRLEN];
1368 bool ret = interpret_string_addr_internal(&ailist,
1370 AI_ADDRCONFIG|AI_CANONNAME);
1372 if (!ret || ailist == NULL) {
1373 DEBUG(3,("matchname: getaddrinfo failed for "
1376 gai_strerror(ret) ));
1381 * Make sure that getaddrinfo() returns the "correct" host name.
1384 if (ailist->ai_canonname == NULL ||
1385 (!strequal(remotehost, ailist->ai_canonname) &&
1386 !strequal(remotehost, "localhost"))) {
1387 DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
1389 ailist->ai_canonname ?
1390 ailist->ai_canonname : "(NULL)"));
1391 freeaddrinfo(ailist);
1395 /* Look up the host address in the address list we just got. */
1396 for (res = ailist; res; res = res->ai_next) {
1397 if (!res->ai_addr) {
1400 if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
1401 (struct sockaddr *)pss)) {
1402 freeaddrinfo(ailist);
1408 * The host name does not map to the original host address. Perhaps
1409 * someone has compromised a name server. More likely someone botched
1410 * it, but that could be dangerous, too.
1413 DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
1414 print_sockaddr_len(addr_buf,
1418 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
1421 freeaddrinfo(ailist);
1426 /*******************************************************************
1427 Deal with the singleton cache.
1428 ******************************************************************/
1430 struct name_addr_pair {
1431 struct sockaddr_storage ss;
1435 /*******************************************************************
1436 Lookup a name/addr pair. Returns memory allocated from memcache.
1437 ******************************************************************/
1439 static bool lookup_nc(struct name_addr_pair *nc)
1445 if (!memcache_lookup(
1446 NULL, SINGLETON_CACHE,
1447 data_blob_string_const_null("get_peer_name"),
1452 memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
1453 nc->name = (const char *)tmp.data + sizeof(nc->ss);
1457 /*******************************************************************
1458 Save a name/addr pair.
1459 ******************************************************************/
1461 static void store_nc(const struct name_addr_pair *nc)
1464 size_t namelen = strlen(nc->name);
1466 tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
1470 memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
1471 memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
1473 memcache_add(NULL, SINGLETON_CACHE,
1474 data_blob_string_const_null("get_peer_name"),
1476 data_blob_free(&tmp);
1479 /*******************************************************************
1480 Return the DNS name of the remote end of a socket.
1481 ******************************************************************/
1483 const char *get_peer_name(int fd, bool force_lookup)
1485 struct name_addr_pair nc;
1486 char addr_buf[INET6_ADDRSTRLEN];
1487 struct sockaddr_storage ss;
1488 socklen_t length = sizeof(ss);
1491 char name_buf[MAX_DNS_NAME_LENGTH];
1492 char tmp_name[MAX_DNS_NAME_LENGTH];
1494 /* reverse lookups can be *very* expensive, and in many
1495 situations won't work because many networks don't link dhcp
1496 with dns. To avoid the delay we avoid the lookup if
1498 if (!lp_hostname_lookups() && (force_lookup == false)) {
1499 length = sizeof(nc.ss);
1500 nc.name = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf),
1501 (struct sockaddr *)&nc.ss, &length);
1504 return nc.name ? nc.name : "UNKNOWN";
1509 memset(&ss, '\0', sizeof(ss));
1510 p = get_peer_addr_internal(fd, addr_buf, sizeof(addr_buf), (struct sockaddr *)&ss, &length);
1512 /* it might be the same as the last one - save some DNS work */
1513 if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1514 return nc.name ? nc.name : "UNKNOWN";
1517 /* Not the same. We need to lookup. */
1522 /* Look up the remote host name. */
1523 ret = sys_getnameinfo((struct sockaddr *)&ss,
1532 DEBUG(1,("get_peer_name: getnameinfo failed "
1533 "for %s with error %s\n",
1535 gai_strerror(ret)));
1536 strlcpy(name_buf, p, sizeof(name_buf));
1538 if (!matchname(name_buf, (struct sockaddr *)&ss, length)) {
1539 DEBUG(0,("Matchname failed on %s %s\n",name_buf,p));
1540 strlcpy(name_buf,"UNKNOWN",sizeof(name_buf));
1544 /* can't pass the same source and dest strings in when you
1545 use --enable-developer or the clobber_region() call will
1548 strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1549 alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1550 if (strstr(name_buf,"..")) {
1551 strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1559 return nc.name ? nc.name : "UNKNOWN";
1562 /*******************************************************************
1563 Return the IP addr of the remote end of a socket as a string.
1564 ******************************************************************/
1566 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
1568 return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
1571 /*******************************************************************
1572 Create protected unix domain socket.
1574 Some unixes cannot set permissions on a ux-dom-sock, so we
1575 have to make sure that the directory contains the protection
1576 permissions instead.
1577 ******************************************************************/
1579 int create_pipe_sock(const char *socket_dir,
1580 const char *socket_name,
1583 #ifdef HAVE_UNIXSOCKET
1584 struct sockaddr_un sunaddr;
1590 old_umask = umask(0);
1592 /* Create the socket directory or reuse the existing one */
1594 if (lstat(socket_dir, &st) == -1) {
1595 if (errno == ENOENT) {
1596 /* Create directory */
1597 if (mkdir(socket_dir, dir_perms) == -1) {
1598 DEBUG(0, ("error creating socket directory "
1599 "%s: %s\n", socket_dir,
1604 DEBUG(0, ("lstat failed on socket directory %s: %s\n",
1605 socket_dir, strerror(errno)));
1609 /* Check ownership and permission on existing directory */
1610 if (!S_ISDIR(st.st_mode)) {
1611 DEBUG(0, ("socket directory %s isn't a directory\n",
1615 if ((st.st_uid != sec_initial_uid()) ||
1616 ((st.st_mode & 0777) != dir_perms)) {
1617 DEBUG(0, ("invalid permissions on socket directory "
1618 "%s\n", socket_dir));
1623 /* Create the socket file */
1625 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1628 DEBUG(0, ("create_pipe_sock: socket error %s\n",
1633 if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1638 memset(&sunaddr, 0, sizeof(sunaddr));
1639 sunaddr.sun_family = AF_UNIX;
1640 strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1642 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1643 DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1648 if (listen(sock, 5) == -1) {
1649 DEBUG(0, ("listen failed on pipe socket %s: %s\n", path,
1669 DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1671 #endif /* HAVE_UNIXSOCKET */
1674 /****************************************************************************
1675 Get my own canonical name, including domain.
1676 ****************************************************************************/
1678 const char *get_mydnsfullname(void)
1680 struct addrinfo *res = NULL;
1681 char my_hostname[HOST_NAME_MAX];
1685 if (memcache_lookup(NULL, SINGLETON_CACHE,
1686 data_blob_string_const_null("get_mydnsfullname"),
1688 SMB_ASSERT(tmp.length > 0);
1689 return (const char *)tmp.data;
1692 /* get my host name */
1693 if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1694 DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1698 /* Ensure null termination. */
1699 my_hostname[sizeof(my_hostname)-1] = '\0';
1701 ret = interpret_string_addr_internal(&res,
1703 AI_ADDRCONFIG|AI_CANONNAME);
1705 if (!ret || res == NULL) {
1706 DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1709 gai_strerror(ret) ));
1714 * Make sure that getaddrinfo() returns the "correct" host name.
1717 if (res->ai_canonname == NULL) {
1718 DEBUG(3,("get_mydnsfullname: failed to get "
1719 "canonical name for %s\n",
1725 /* This copies the data, so we must do a lookup
1726 * afterwards to find the value to return.
1729 memcache_add(NULL, SINGLETON_CACHE,
1730 data_blob_string_const_null("get_mydnsfullname"),
1731 data_blob_string_const_null(res->ai_canonname));
1733 if (!memcache_lookup(NULL, SINGLETON_CACHE,
1734 data_blob_string_const_null("get_mydnsfullname"),
1736 tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1737 strlen(res->ai_canonname) + 1);
1742 return (const char *)tmp.data;
1745 /************************************************************
1747 ************************************************************/
1749 bool is_myname_or_ipaddr(const char *s)
1751 TALLOC_CTX *ctx = talloc_tos();
1752 char addr[INET6_ADDRSTRLEN];
1754 const char *dnsname;
1755 char *servername = NULL;
1761 /* Santize the string from '\\name' */
1762 name = talloc_strdup(ctx, s);
1767 servername = strrchr_m(name, '\\' );
1774 /* Optimize for the common case */
1775 if (strequal(servername, global_myname())) {
1779 /* Check for an alias */
1780 if (is_myname(servername)) {
1784 /* Check for loopback */
1785 if (strequal(servername, "127.0.0.1") ||
1786 strequal(servername, "::1")) {
1790 if (strequal(servername, "localhost")) {
1794 /* Maybe it's my dns name */
1795 dnsname = get_mydnsfullname();
1796 if (dnsname && strequal(servername, dnsname)) {
1800 /* Handle possible CNAME records - convert to an IP addr. */
1801 if (!is_ipaddress(servername)) {
1802 /* Use DNS to resolve the name, but only the first address */
1803 struct sockaddr_storage ss;
1804 if (interpret_string_addr(&ss, servername, 0)) {
1805 print_sockaddr(addr,
1812 /* Maybe its an IP address? */
1813 if (is_ipaddress(servername)) {
1814 struct sockaddr_storage ss;
1815 struct iface_struct *nics;
1818 if (!interpret_string_addr(&ss, servername, AI_NUMERICHOST)) {
1822 if (ismyaddr((struct sockaddr *)&ss)) {
1826 if (is_zero_addr((struct sockaddr *)&ss) ||
1827 is_loopback_addr((struct sockaddr *)&ss)) {
1831 n = get_interfaces(talloc_tos(), &nics);
1832 for (i=0; i<n; i++) {
1833 if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1845 struct getaddrinfo_state {
1847 const char *service;
1848 const struct addrinfo *hints;
1849 struct addrinfo *res;
1853 static void getaddrinfo_do(void *private_data);
1854 static void getaddrinfo_done(struct tevent_req *subreq);
1856 struct tevent_req *getaddrinfo_send(TALLOC_CTX *mem_ctx,
1857 struct tevent_context *ev,
1858 struct fncall_context *ctx,
1860 const char *service,
1861 const struct addrinfo *hints)
1863 struct tevent_req *req, *subreq;
1864 struct getaddrinfo_state *state;
1866 req = tevent_req_create(mem_ctx, &state, struct getaddrinfo_state);
1872 state->service = service;
1873 state->hints = hints;
1875 subreq = fncall_send(state, ev, ctx, getaddrinfo_do, state);
1876 if (tevent_req_nomem(subreq, req)) {
1877 return tevent_req_post(req, ev);
1879 tevent_req_set_callback(subreq, getaddrinfo_done, req);
1883 static void getaddrinfo_do(void *private_data)
1885 struct getaddrinfo_state *state =
1886 (struct getaddrinfo_state *)private_data;
1888 state->ret = getaddrinfo(state->node, state->service, state->hints,
1892 static void getaddrinfo_done(struct tevent_req *subreq)
1894 struct tevent_req *req = tevent_req_callback_data(
1895 subreq, struct tevent_req);
1898 ret = fncall_recv(subreq, &err);
1899 TALLOC_FREE(subreq);
1901 tevent_req_error(req, err);
1904 tevent_req_done(req);
1907 int getaddrinfo_recv(struct tevent_req *req, struct addrinfo **res)
1909 struct getaddrinfo_state *state = tevent_req_data(
1910 req, struct getaddrinfo_state);
1913 if (tevent_req_is_unix_error(req, &err)) {
1921 if (state->ret == 0) {