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
7 
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.
12 
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.
17 
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/>.
20 */
21 
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"
33 
client_addr(int fd,char * addr,size_t addrlen)34 const char *client_addr(int fd, char *addr, size_t addrlen)
35 {
36 	return get_peer_addr(fd,addr,addrlen);
37 }
38 
39 #if 0
40 /* Not currently used. JRA. */
41 int client_socket_port(int fd)
42 {
43 	return get_socket_port(fd);
44 }
45 #endif
46 
47 /****************************************************************************
48  Determine if a file descriptor is in fact a socket.
49 ****************************************************************************/
50 
is_a_socket(int fd)51 bool is_a_socket(int fd)
52 {
53 	int v;
54 	socklen_t l;
55 	l = sizeof(int);
56 	return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
57 }
58 
59 /****************************************************************************
60  Read from a socket.
61 ****************************************************************************/
62 
read_udp_v4_socket(int fd,char * buf,size_t len,struct sockaddr_storage * psa)63 ssize_t read_udp_v4_socket(int fd,
64 			char *buf,
65 			size_t len,
66 			struct sockaddr_storage *psa)
67 {
68 	ssize_t ret;
69 	socklen_t socklen = sizeof(*psa);
70 	struct sockaddr_in *si = (struct sockaddr_in *)psa;
71 
72 	memset((char *)psa,'\0',socklen);
73 
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)));
83 		}
84 		return 0;
85 	}
86 
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;
91 	}
92 
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));
97 
98 	return ret;
99 }
100 
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 ****************************************************************************/
109 
read_fd_with_timeout(int fd,char * buf,size_t mincnt,size_t maxcnt,unsigned int time_out,size_t * size_ret)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)
114 {
115 	int pollrtn;
116 	ssize_t readret;
117 	size_t nread = 0;
118 
119 	/* just checking .... */
120 	if (maxcnt <= 0)
121 		return NT_STATUS_OK;
122 
123 	/* Blocking read */
124 	if (time_out == 0) {
125 		if (mincnt == 0) {
126 			mincnt = maxcnt;
127 		}
128 
129 		while (nread < mincnt) {
130 			readret = sys_read(fd, buf + nread, maxcnt - nread);
131 
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;
136 			}
137 
138 			if (readret == -1) {
139 				return map_nt_error_from_unix(errno);
140 			}
141 			nread += readret;
142 		}
143 		goto done;
144 	}
145 
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 */
151 
152 	for (nread=0; nread < mincnt; ) {
153 		int revents;
154 
155 		pollrtn = poll_intr_one_fd(fd, POLLIN|POLLHUP, time_out,
156 					   &revents);
157 
158 		/* Check if error */
159 		if (pollrtn == -1) {
160 			return map_nt_error_from_unix(errno);
161 		}
162 
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;
169 		}
170 
171 		readret = sys_read(fd, buf+nread, maxcnt-nread);
172 
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;
178 		}
179 
180 		if (readret == -1) {
181 			return map_nt_error_from_unix(errno);
182 		}
183 
184 		nread += readret;
185 	}
186 
187  done:
188 	/* Return the number we got */
189 	if (size_ret) {
190 		*size_ret = nread;
191 	}
192 	return NT_STATUS_OK;
193 }
194 
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 ****************************************************************************/
200 
read_data_ntstatus(int fd,char * buffer,size_t N)201 NTSTATUS read_data_ntstatus(int fd, char *buffer, size_t N)
202 {
203 	return read_fd_with_timeout(fd, buffer, N, N, 0, NULL);
204 }
205 
206 /****************************************************************************
207  Send a keepalive packet (rfc1002).
208 ****************************************************************************/
209 
send_keepalive(int client)210 bool send_keepalive(int client)
211 {
212 	unsigned char buf[4];
213 
214 	buf[0] = NBSSkeepalive;
215 	buf[1] = buf[2] = buf[3] = 0;
216 
217 	return(write_data(client,(char *)buf,4) == 4);
218 }
219 
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 ****************************************************************************/
227 
read_smb_length_return_keepalive(int fd,char * inbuf,unsigned int timeout,size_t * len)228 NTSTATUS read_smb_length_return_keepalive(int fd, char *inbuf,
229 					  unsigned int timeout,
230 					  size_t *len)
231 {
232 	int msg_type;
233 	NTSTATUS status;
234 
235 	status = read_fd_with_timeout(fd, inbuf, 4, 4, timeout, NULL);
236 
237 	if (!NT_STATUS_IS_OK(status)) {
238 		return status;
239 	}
240 
241 	*len = smb_len(inbuf);
242 	msg_type = CVAL(inbuf,0);
243 
244 	if (msg_type == NBSSkeepalive) {
245 		DEBUG(5,("Got keepalive packet\n"));
246 	}
247 
248 	DEBUG(10,("got smb length of %lu\n",(unsigned long)(*len)));
249 
250 	return NT_STATUS_OK;
251 }
252 
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 ****************************************************************************/
261 
receive_smb_raw(int fd,char * buffer,size_t buflen,unsigned int timeout,size_t maxlen,size_t * p_len)262 NTSTATUS receive_smb_raw(int fd, char *buffer, size_t buflen, unsigned int timeout,
263 			 size_t maxlen, size_t *p_len)
264 {
265 	size_t len;
266 	NTSTATUS status;
267 
268 	status = read_smb_length_return_keepalive(fd,buffer,timeout,&len);
269 
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;
274 	}
275 
276 	if (len > buflen) {
277 		DEBUG(0,("Invalid packet length! (%lu bytes).\n",
278 					(unsigned long)len));
279 		return NT_STATUS_INVALID_PARAMETER;
280 	}
281 
282 	if(len > 0) {
283 		if (maxlen) {
284 			len = MIN(len,maxlen);
285 		}
286 
287 		status = read_fd_with_timeout(
288 			fd, buffer+4, len, len, timeout, &len);
289 
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;
294 		}
295 
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);
300 	}
301 
302 	*p_len = len;
303 	return NT_STATUS_OK;
304 }
305 
306 /****************************************************************************
307  Open a socket of the specified type, port, and address for incoming data.
308 ****************************************************************************/
309 
open_socket_in(int type,uint16_t port,int dlevel,const struct sockaddr_storage * psock,bool rebind)310 int open_socket_in(int type,
311 		uint16_t port,
312 		int dlevel,
313 		const struct sockaddr_storage *psock,
314 		bool rebind)
315 {
316 	struct sockaddr_storage sock;
317 	int res;
318 	socklen_t slen = sizeof(struct sockaddr_in);
319 
320 	sock = *psock;
321 
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);
326 	}
327 #endif
328 	if (sock.ss_family == AF_INET) {
329 		((struct sockaddr_in *)&sock)->sin_port = htons(port);
330 	}
331 
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 ) );
337 		}
338 		return -1;
339 	}
340 
341 	/* This block sets/clears the SO_REUSEADDR and possibly SO_REUSEPORT. */
342 	{
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) );
352 			}
353 		}
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));
363 			}
364 		}
365 #endif /* SO_REUSEPORT */
366 	}
367 
368 #ifdef HAVE_IPV6
369 	/*
370 	 * As IPV6_V6ONLY is the default on some systems,
371 	 * we better try to be consistent and always use it.
372 	 *
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.
376 	 */
377 	if (sock.ss_family == AF_INET6) {
378 		int val = 1;
379 		int ret;
380 
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));
387 			}
388 			close(res);
389 			return -1;
390 		}
391 	}
392 #endif
393 
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));
405 		}
406 		close(res);
407 		return -1;
408 	}
409 
410 	DEBUG( 10, ( "bind succeeded on port %d\n", port ) );
411 	return( res );
412  }
413 
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;
422 };
423 
424 static void open_socket_out_connected(struct tevent_req *subreq);
425 
open_socket_out_cleanup(struct tevent_req * req,enum tevent_req_state req_state)426 static void open_socket_out_cleanup(struct tevent_req *req,
427 				    enum tevent_req_state req_state)
428 {
429 	struct open_socket_out_state *state =
430 		tevent_req_data(req, struct open_socket_out_state);
431 
432 	/*
433 	 * Make sure that the async_connect_send subreq has a chance to reset
434 	 * fcntl before the socket goes away.
435 	 */
436 	TALLOC_FREE(state->connect_subreq);
437 
438 	if (req_state == TEVENT_REQ_DONE) {
439 		/*
440 		 * we keep the socket open for the caller to use
441 		 */
442 		return;
443 	}
444 
445 	if (state->fd != -1) {
446 		close(state->fd);
447 		state->fd = -1;
448 	}
449 }
450 
451 /****************************************************************************
452  Create an outgoing socket. timeout is in milliseconds.
453 **************************************************************************/
454 
open_socket_out_send(TALLOC_CTX * mem_ctx,struct tevent_context * ev,const struct sockaddr_storage * pss,uint16_t port,int timeout)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)
460 {
461 	char addr[INET6_ADDRSTRLEN];
462 	struct tevent_req *result;
463 	struct open_socket_out_state *state;
464 	NTSTATUS status;
465 
466 	result = tevent_req_create(mem_ctx, &state,
467 				   struct open_socket_out_state);
468 	if (result == NULL) {
469 		return NULL;
470 	}
471 	state->ev = ev;
472 	state->ss = *pss;
473 	state->port = port;
474 	state->wait_usec = 10000;
475 	state->salen = -1;
476 
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;
481 	}
482 
483 	tevent_req_set_cleanup_fn(result, open_socket_out_cleanup);
484 
485 	if (!tevent_req_set_endtime(
486 		    result, ev, timeval_current_ofs_msec(timeout))) {
487 		goto fail;
488 	}
489 
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));
499 		}
500 		state->salen = sizeof(struct sockaddr_in6);
501 	}
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);
508 	}
509 
510 	if (pss->ss_family == AF_UNIX) {
511 		state->salen = sizeof(struct sockaddr_un);
512 	}
513 
514 	print_sockaddr(addr, sizeof(addr), &state->ss);
515 	DEBUG(3,("Connecting to %s at port %u\n", addr,	(unsigned int)port));
516 
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;
525 	}
526 	tevent_req_set_callback(state->connect_subreq,
527 				open_socket_out_connected, result);
528 	return result;
529 
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;
536 }
537 
open_socket_out_connected(struct tevent_req * subreq)538 static void open_socket_out_connected(struct tevent_req *subreq)
539 {
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;
546 
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;
553 	}
554 
555 	if (
556 #ifdef ETIMEDOUT
557 		(sys_errno == ETIMEDOUT) ||
558 #endif
559 		(sys_errno == EINPROGRESS) ||
560 		(sys_errno == EALREADY) ||
561 		(sys_errno == EAGAIN)) {
562 
563 		/*
564 		 * retry
565 		 */
566 
567 		if (state->wait_usec < 250000) {
568 			state->wait_usec *= 1.5;
569 		}
570 
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;
576 		}
577 		if (!tevent_req_set_endtime(
578 			    subreq, state->ev,
579 			    timeval_current_ofs_usec(state->wait_usec))) {
580 			return;
581 		}
582 		state->connect_subreq = subreq;
583 		tevent_req_set_callback(subreq, open_socket_out_connected, req);
584 		return;
585 	}
586 
587 #ifdef EISCONN
588 	if (sys_errno == EISCONN) {
589 		tevent_req_done(req);
590 		return;
591 	}
592 #endif
593 
594 	/* real error */
595 	tevent_req_nterror(req, map_nt_error_from_unix(sys_errno));
596 }
597 
open_socket_out_recv(struct tevent_req * req,int * pfd)598 NTSTATUS open_socket_out_recv(struct tevent_req *req, int *pfd)
599 {
600 	struct open_socket_out_state *state =
601 		tevent_req_data(req, struct open_socket_out_state);
602 	NTSTATUS status;
603 
604 	if (tevent_req_is_nterror(req, &status)) {
605 		tevent_req_received(req);
606 		return status;
607 	}
608 	*pfd = state->fd;
609 	state->fd = -1;
610 	tevent_req_received(req);
611 	return NT_STATUS_OK;
612 }
613 
614 /**
615 * @brief open a socket
616 *
617 * @param pss a struct sockaddr_storage defining the address to connect to
618 * @param port to connect to
619 * @param timeout in MILLISECONDS
620 * @param pfd file descriptor returned
621 *
622 * @return NTSTATUS code
623 */
open_socket_out(const struct sockaddr_storage * pss,uint16_t port,int timeout,int * pfd)624 NTSTATUS open_socket_out(const struct sockaddr_storage *pss, uint16_t port,
625 			 int timeout, int *pfd)
626 {
627 	TALLOC_CTX *frame = talloc_stackframe();
628 	struct tevent_context *ev;
629 	struct tevent_req *req;
630 	NTSTATUS status = NT_STATUS_NO_MEMORY;
631 
632 	ev = samba_tevent_context_init(frame);
633 	if (ev == NULL) {
634 		goto fail;
635 	}
636 
637 	req = open_socket_out_send(frame, ev, pss, port, timeout);
638 	if (req == NULL) {
639 		goto fail;
640 	}
641 	if (!tevent_req_poll(req, ev)) {
642 		status = NT_STATUS_INTERNAL_ERROR;
643 		goto fail;
644 	}
645 	status = open_socket_out_recv(req, pfd);
646  fail:
647 	TALLOC_FREE(frame);
648 	return status;
649 }
650 
651 struct open_socket_out_defer_state {
652 	struct tevent_context *ev;
653 	struct sockaddr_storage ss;
654 	uint16_t port;
655 	int timeout;
656 	int fd;
657 };
658 
659 static void open_socket_out_defer_waited(struct tevent_req *subreq);
660 static void open_socket_out_defer_connected(struct tevent_req *subreq);
661 
open_socket_out_defer_send(TALLOC_CTX * mem_ctx,struct tevent_context * ev,struct timeval wait_time,const struct sockaddr_storage * pss,uint16_t port,int timeout)662 struct tevent_req *open_socket_out_defer_send(TALLOC_CTX *mem_ctx,
663 					      struct tevent_context *ev,
664 					      struct timeval wait_time,
665 					      const struct sockaddr_storage *pss,
666 					      uint16_t port,
667 					      int timeout)
668 {
669 	struct tevent_req *req, *subreq;
670 	struct open_socket_out_defer_state *state;
671 
672 	req = tevent_req_create(mem_ctx, &state,
673 				struct open_socket_out_defer_state);
674 	if (req == NULL) {
675 		return NULL;
676 	}
677 	state->ev = ev;
678 	state->ss = *pss;
679 	state->port = port;
680 	state->timeout = timeout;
681 
682 	subreq = tevent_wakeup_send(
683 		state, ev,
684 		timeval_current_ofs(wait_time.tv_sec, wait_time.tv_usec));
685 	if (subreq == NULL) {
686 		goto fail;
687 	}
688 	tevent_req_set_callback(subreq, open_socket_out_defer_waited, req);
689 	return req;
690  fail:
691 	TALLOC_FREE(req);
692 	return NULL;
693 }
694 
open_socket_out_defer_waited(struct tevent_req * subreq)695 static void open_socket_out_defer_waited(struct tevent_req *subreq)
696 {
697 	struct tevent_req *req = tevent_req_callback_data(
698 		subreq, struct tevent_req);
699 	struct open_socket_out_defer_state *state = tevent_req_data(
700 		req, struct open_socket_out_defer_state);
701 	bool ret;
702 
703 	ret = tevent_wakeup_recv(subreq);
704 	TALLOC_FREE(subreq);
705 	if (!ret) {
706 		tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
707 		return;
708 	}
709 
710 	subreq = open_socket_out_send(state, state->ev, &state->ss,
711 				      state->port, state->timeout);
712 	if (tevent_req_nomem(subreq, req)) {
713 		return;
714 	}
715 	tevent_req_set_callback(subreq, open_socket_out_defer_connected, req);
716 }
717 
open_socket_out_defer_connected(struct tevent_req * subreq)718 static void open_socket_out_defer_connected(struct tevent_req *subreq)
719 {
720 	struct tevent_req *req = tevent_req_callback_data(
721 		subreq, struct tevent_req);
722 	struct open_socket_out_defer_state *state = tevent_req_data(
723 		req, struct open_socket_out_defer_state);
724 	NTSTATUS status;
725 
726 	status = open_socket_out_recv(subreq, &state->fd);
727 	TALLOC_FREE(subreq);
728 	if (!NT_STATUS_IS_OK(status)) {
729 		tevent_req_nterror(req, status);
730 		return;
731 	}
732 	tevent_req_done(req);
733 }
734 
open_socket_out_defer_recv(struct tevent_req * req,int * pfd)735 NTSTATUS open_socket_out_defer_recv(struct tevent_req *req, int *pfd)
736 {
737 	struct open_socket_out_defer_state *state = tevent_req_data(
738 		req, struct open_socket_out_defer_state);
739 	NTSTATUS status;
740 
741 	if (tevent_req_is_nterror(req, &status)) {
742 		return status;
743 	}
744 	*pfd = state->fd;
745 	state->fd = -1;
746 	return NT_STATUS_OK;
747 }
748 
749 /****************************************************************************
750  Open a connected UDP socket to host on port
751 **************************************************************************/
752 
open_udp_socket(const char * host,int port)753 int open_udp_socket(const char *host, int port)
754 {
755 	struct sockaddr_storage ss;
756 	int res;
757 	socklen_t salen;
758 
759 	if (!interpret_string_addr(&ss, host, 0)) {
760 		DEBUG(10,("open_udp_socket: can't resolve name %s\n",
761 			host));
762 		return -1;
763 	}
764 
765 	res = socket(ss.ss_family, SOCK_DGRAM, 0);
766 	if (res == -1) {
767 		return -1;
768 	}
769 
770 #if defined(HAVE_IPV6)
771 	if (ss.ss_family == AF_INET6) {
772 		struct sockaddr_in6 *psa6;
773 		psa6 = (struct sockaddr_in6 *)&ss;
774 		psa6->sin6_port = htons(port);
775 		if (psa6->sin6_scope_id == 0
776 				&& IN6_IS_ADDR_LINKLOCAL(&psa6->sin6_addr)) {
777 			setup_linklocal_scope_id(
778 				(struct sockaddr *)&ss);
779 		}
780 		salen = sizeof(struct sockaddr_in6);
781 	} else
782 #endif
783 	if (ss.ss_family == AF_INET) {
784 		struct sockaddr_in *psa;
785 		psa = (struct sockaddr_in *)&ss;
786 		psa->sin_port = htons(port);
787 	    salen = sizeof(struct sockaddr_in);
788 	} else {
789 		DEBUG(1, ("unknown socket family %d", ss.ss_family));
790 		close(res);
791 		return -1;
792 	}
793 
794 	if (connect(res, (struct sockaddr *)&ss, salen)) {
795 		close(res);
796 		return -1;
797 	}
798 
799 	return res;
800 }
801 
802 /*******************************************************************
803  Return the IP addr of the remote end of a socket as a string.
804  Optionally return the struct sockaddr_storage.
805  ******************************************************************/
806 
get_peer_addr_internal(int fd,char * addr_buf,size_t addr_buf_len,struct sockaddr * pss,socklen_t * plength)807 static const char *get_peer_addr_internal(int fd,
808 				char *addr_buf,
809 				size_t addr_buf_len,
810 				struct sockaddr *pss,
811 				socklen_t *plength)
812 {
813 	struct sockaddr_storage ss;
814 	socklen_t length = sizeof(ss);
815 
816 	strlcpy(addr_buf,"0.0.0.0",addr_buf_len);
817 
818 	if (fd == -1) {
819 		return addr_buf;
820 	}
821 
822 	if (pss == NULL) {
823 		pss = (struct sockaddr *)&ss;
824 		plength = &length;
825 	}
826 
827 	if (getpeername(fd, (struct sockaddr *)pss, plength) < 0) {
828 		int level = (errno == ENOTCONN) ? 2 : 0;
829 		DEBUG(level, ("getpeername failed. Error was %s\n",
830 			       strerror(errno)));
831 		return addr_buf;
832 	}
833 
834 	print_sockaddr_len(addr_buf,
835 			addr_buf_len,
836 			pss,
837 			*plength);
838 	return addr_buf;
839 }
840 
841 /*******************************************************************
842  Matchname - determine if host name matches IP address. Used to
843  confirm a hostname lookup to prevent spoof attacks.
844 ******************************************************************/
845 
matchname(const char * remotehost,const struct sockaddr * pss,socklen_t len)846 static bool matchname(const char *remotehost,
847 		const struct sockaddr *pss,
848 		socklen_t len)
849 {
850 	struct addrinfo *res = NULL;
851 	struct addrinfo *ailist = NULL;
852 	char addr_buf[INET6_ADDRSTRLEN];
853 	bool ret = interpret_string_addr_internal(&ailist,
854 			remotehost,
855 			AI_ADDRCONFIG|AI_CANONNAME);
856 
857 	if (!ret || ailist == NULL) {
858 		DEBUG(3,("matchname: getaddrinfo failed for "
859 			"name %s [%s]\n",
860 			remotehost,
861 			gai_strerror(ret) ));
862 		return false;
863 	}
864 
865 	/*
866 	 * Make sure that getaddrinfo() returns the "correct" host name.
867 	 */
868 
869 	if (ailist->ai_canonname == NULL ||
870 		(!strequal(remotehost, ailist->ai_canonname) &&
871 		 !strequal(remotehost, "localhost"))) {
872 		DEBUG(0,("matchname: host name/name mismatch: %s != %s\n",
873 			 remotehost,
874 			 ailist->ai_canonname ?
875 				 ailist->ai_canonname : "(NULL)"));
876 		freeaddrinfo(ailist);
877 		return false;
878 	}
879 
880 	/* Look up the host address in the address list we just got. */
881 	for (res = ailist; res; res = res->ai_next) {
882 		if (!res->ai_addr) {
883 			continue;
884 		}
885 		if (sockaddr_equal((const struct sockaddr *)res->ai_addr,
886 					(const struct sockaddr *)pss)) {
887 			freeaddrinfo(ailist);
888 			return true;
889 		}
890 	}
891 
892 	/*
893 	 * The host name does not map to the original host address. Perhaps
894 	 * someone has compromised a name server. More likely someone botched
895 	 * it, but that could be dangerous, too.
896 	 */
897 
898 	DEBUG(0,("matchname: host name/address mismatch: %s != %s\n",
899 		print_sockaddr_len(addr_buf,
900 			sizeof(addr_buf),
901 			pss,
902 			len),
903 		 ailist->ai_canonname ? ailist->ai_canonname : "(NULL)"));
904 
905 	if (ailist) {
906 		freeaddrinfo(ailist);
907 	}
908 	return false;
909 }
910 
911 /*******************************************************************
912  Deal with the singleton cache.
913 ******************************************************************/
914 
915 struct name_addr_pair {
916 	struct sockaddr_storage ss;
917 	const char *name;
918 };
919 
920 /*******************************************************************
921  Lookup a name/addr pair. Returns memory allocated from memcache.
922 ******************************************************************/
923 
lookup_nc(struct name_addr_pair * nc)924 static bool lookup_nc(struct name_addr_pair *nc)
925 {
926 	DATA_BLOB tmp;
927 
928 	ZERO_STRUCTP(nc);
929 
930 	if (!memcache_lookup(
931 			NULL, SINGLETON_CACHE,
932 			data_blob_string_const_null("get_peer_name"),
933 			&tmp)) {
934 		return false;
935 	}
936 
937 	memcpy(&nc->ss, tmp.data, sizeof(nc->ss));
938 	nc->name = (const char *)tmp.data + sizeof(nc->ss);
939 	return true;
940 }
941 
942 /*******************************************************************
943  Save a name/addr pair.
944 ******************************************************************/
945 
store_nc(const struct name_addr_pair * nc)946 static void store_nc(const struct name_addr_pair *nc)
947 {
948 	DATA_BLOB tmp;
949 	size_t namelen = strlen(nc->name);
950 
951 	tmp = data_blob(NULL, sizeof(nc->ss) + namelen + 1);
952 	if (!tmp.data) {
953 		return;
954 	}
955 	memcpy(tmp.data, &nc->ss, sizeof(nc->ss));
956 	memcpy(tmp.data+sizeof(nc->ss), nc->name, namelen+1);
957 
958 	memcache_add(NULL, SINGLETON_CACHE,
959 			data_blob_string_const_null("get_peer_name"),
960 			tmp);
961 	data_blob_free(&tmp);
962 }
963 
964 /*******************************************************************
965  Return the IP addr of the remote end of a socket as a string.
966  ******************************************************************/
967 
get_peer_addr(int fd,char * addr,size_t addr_len)968 const char *get_peer_addr(int fd, char *addr, size_t addr_len)
969 {
970 	return get_peer_addr_internal(fd, addr, addr_len, NULL, NULL);
971 }
972 
get_remote_hostname(const struct tsocket_address * remote_address,char ** name,TALLOC_CTX * mem_ctx)973 int get_remote_hostname(const struct tsocket_address *remote_address,
974 			char **name,
975 			TALLOC_CTX *mem_ctx)
976 {
977 	char name_buf[MAX_DNS_NAME_LENGTH];
978 	char tmp_name[MAX_DNS_NAME_LENGTH];
979 	struct name_addr_pair nc;
980 	struct sockaddr_storage ss;
981 	ssize_t len;
982 	int rc;
983 
984 	if (!lp_hostname_lookups()) {
985 		nc.name = tsocket_address_inet_addr_string(remote_address,
986 							   mem_ctx);
987 		if (nc.name == NULL) {
988 			return -1;
989 		}
990 
991 		len = tsocket_address_bsd_sockaddr(remote_address,
992 						   (struct sockaddr *) &nc.ss,
993 						   sizeof(struct sockaddr_storage));
994 		if (len < 0) {
995 			return -1;
996 		}
997 
998 		store_nc(&nc);
999 		lookup_nc(&nc);
1000 
1001 		if (nc.name == NULL) {
1002 			*name = talloc_strdup(mem_ctx, "UNKNOWN");
1003 		} else {
1004 			*name = talloc_strdup(mem_ctx, nc.name);
1005 		}
1006 		return 0;
1007 	}
1008 
1009 	lookup_nc(&nc);
1010 
1011 	ZERO_STRUCT(ss);
1012 
1013 	len = tsocket_address_bsd_sockaddr(remote_address,
1014 					   (struct sockaddr *) &ss,
1015 					   sizeof(struct sockaddr_storage));
1016 	if (len < 0) {
1017 		return -1;
1018 	}
1019 
1020 	/* it might be the same as the last one - save some DNS work */
1021 	if (sockaddr_equal((struct sockaddr *)&ss, (struct sockaddr *)&nc.ss)) {
1022 		if (nc.name == NULL) {
1023 			*name = talloc_strdup(mem_ctx, "UNKNOWN");
1024 		} else {
1025 			*name = talloc_strdup(mem_ctx, nc.name);
1026 		}
1027 		return 0;
1028 	}
1029 
1030 	/* Look up the remote host name. */
1031 	rc = sys_getnameinfo((struct sockaddr *) &ss,
1032 			     len,
1033 			     name_buf,
1034 			     sizeof(name_buf),
1035 			     NULL,
1036 			     0,
1037 			     0);
1038 	if (rc < 0) {
1039 		char *p;
1040 
1041 		p = tsocket_address_inet_addr_string(remote_address, mem_ctx);
1042 		if (p == NULL) {
1043 			return -1;
1044 		}
1045 
1046 		DEBUG(1,("getnameinfo failed for %s with error %s\n",
1047 			 p,
1048 			 gai_strerror(rc)));
1049 		strlcpy(name_buf, p, sizeof(name_buf));
1050 
1051 		TALLOC_FREE(p);
1052 	} else {
1053 		if (!matchname(name_buf, (struct sockaddr *)&ss, len)) {
1054 			DEBUG(0,("matchname failed on %s\n", name_buf));
1055 			strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1056 		}
1057 	}
1058 
1059 	strlcpy(tmp_name, name_buf, sizeof(tmp_name));
1060 	alpha_strcpy(name_buf, tmp_name, "_-.", sizeof(name_buf));
1061 	if (strstr(name_buf,"..")) {
1062 		strlcpy(name_buf, "UNKNOWN", sizeof(name_buf));
1063 	}
1064 
1065 	nc.name = name_buf;
1066 	nc.ss = ss;
1067 
1068 	store_nc(&nc);
1069 	lookup_nc(&nc);
1070 
1071 	if (nc.name == NULL) {
1072 		*name = talloc_strdup(mem_ctx, "UNKNOWN");
1073 	} else {
1074 		*name = talloc_strdup(mem_ctx, nc.name);
1075 	}
1076 
1077 	return 0;
1078 }
1079 
1080 /*******************************************************************
1081  Create protected unix domain socket.
1082 
1083  Some unixes cannot set permissions on a ux-dom-sock, so we
1084  have to make sure that the directory contains the protection
1085  permissions instead.
1086  ******************************************************************/
1087 
create_pipe_sock(const char * socket_dir,const char * socket_name,mode_t dir_perms)1088 int create_pipe_sock(const char *socket_dir,
1089 		     const char *socket_name,
1090 		     mode_t dir_perms)
1091 {
1092 #ifdef HAVE_UNIXSOCKET
1093 	struct sockaddr_un sunaddr;
1094 	bool ok;
1095 	int sock = -1;
1096 	mode_t old_umask;
1097 	char *path = NULL;
1098 	size_t path_len;
1099 
1100 	old_umask = umask(0);
1101 
1102 	ok = directory_create_or_exist_strict(socket_dir,
1103 					      sec_initial_uid(),
1104 					      dir_perms);
1105 	if (!ok) {
1106 		goto out_close;
1107 	}
1108 
1109 	/* Create the socket file */
1110 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
1111 
1112 	if (sock == -1) {
1113 		DEBUG(0, ("create_pipe_sock: socket error %s\n",
1114 			strerror(errno) ));
1115                 goto out_close;
1116 	}
1117 
1118 	if (asprintf(&path, "%s/%s", socket_dir, socket_name) == -1) {
1119                 goto out_close;
1120 	}
1121 
1122 	unlink(path);
1123 	memset(&sunaddr, 0, sizeof(sunaddr));
1124 	sunaddr.sun_family = AF_UNIX;
1125 
1126 	path_len = strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path));
1127 	if (path_len > sizeof(sunaddr.sun_path)) {
1128 		DBG_ERR("Refusing to attempt to create pipe socket "
1129 			"%s.  Path is longer than permitted for a "
1130 			"unix domain socket.  It would truncate to "
1131 			"%s\n",
1132 			path,
1133 			sunaddr.sun_path);
1134 		goto out_close;
1135 	}
1136 
1137 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1138 		DEBUG(0, ("bind failed on pipe socket %s: %s\n", path,
1139 			strerror(errno)));
1140 		goto out_close;
1141 	}
1142 
1143 	SAFE_FREE(path);
1144 
1145 	umask(old_umask);
1146 	return sock;
1147 
1148 out_close:
1149 	SAFE_FREE(path);
1150 	if (sock != -1)
1151 		close(sock);
1152 
1153 	umask(old_umask);
1154 	return -1;
1155 
1156 #else
1157         DEBUG(0, ("create_pipe_sock: No Unix sockets on this system\n"));
1158         return -1;
1159 #endif /* HAVE_UNIXSOCKET */
1160 }
1161 
1162 /****************************************************************************
1163  Get my own canonical name, including domain.
1164 ****************************************************************************/
1165 
get_mydnsfullname(void)1166 const char *get_mydnsfullname(void)
1167 {
1168 	struct addrinfo *res = NULL;
1169 	char my_hostname[HOST_NAME_MAX];
1170 	bool ret;
1171 	DATA_BLOB tmp;
1172 
1173 	if (memcache_lookup(NULL, SINGLETON_CACHE,
1174 			data_blob_string_const_null("get_mydnsfullname"),
1175 			&tmp)) {
1176 		SMB_ASSERT(tmp.length > 0);
1177 		return (const char *)tmp.data;
1178 	}
1179 
1180 	/* get my host name */
1181 	if (gethostname(my_hostname, sizeof(my_hostname)) == -1) {
1182 		DEBUG(0,("get_mydnsfullname: gethostname failed\n"));
1183 		return NULL;
1184 	}
1185 
1186 	/* Ensure null termination. */
1187 	my_hostname[sizeof(my_hostname)-1] = '\0';
1188 
1189 	ret = interpret_string_addr_internal(&res,
1190 				my_hostname,
1191 				AI_ADDRCONFIG|AI_CANONNAME);
1192 
1193 	if (!ret || res == NULL) {
1194 		DEBUG(3,("get_mydnsfullname: getaddrinfo failed for "
1195 			"name %s [%s]\n",
1196 			my_hostname,
1197 			gai_strerror(ret) ));
1198 		return NULL;
1199 	}
1200 
1201 	/*
1202 	 * Make sure that getaddrinfo() returns the "correct" host name.
1203 	 */
1204 
1205 	if (res->ai_canonname == NULL) {
1206 		DEBUG(3,("get_mydnsfullname: failed to get "
1207 			"canonical name for %s\n",
1208 			my_hostname));
1209 		freeaddrinfo(res);
1210 		return NULL;
1211 	}
1212 
1213 	/* This copies the data, so we must do a lookup
1214 	 * afterwards to find the value to return.
1215 	 */
1216 
1217 	memcache_add(NULL, SINGLETON_CACHE,
1218 			data_blob_string_const_null("get_mydnsfullname"),
1219 			data_blob_string_const_null(res->ai_canonname));
1220 
1221 	if (!memcache_lookup(NULL, SINGLETON_CACHE,
1222 			data_blob_string_const_null("get_mydnsfullname"),
1223 			&tmp)) {
1224 		tmp = data_blob_talloc(talloc_tos(), res->ai_canonname,
1225 				strlen(res->ai_canonname) + 1);
1226 	}
1227 
1228 	freeaddrinfo(res);
1229 
1230 	return (const char *)tmp.data;
1231 }
1232 
1233 /************************************************************
1234  Is this my ip address ?
1235 ************************************************************/
1236 
is_my_ipaddr(const char * ipaddr_str)1237 static bool is_my_ipaddr(const char *ipaddr_str)
1238 {
1239 	struct sockaddr_storage ss;
1240 	struct iface_struct *nics;
1241 	int i, n;
1242 
1243 	if (!interpret_string_addr(&ss, ipaddr_str, AI_NUMERICHOST)) {
1244 		return false;
1245 	}
1246 
1247 	if (is_zero_addr(&ss)) {
1248 		return false;
1249 	}
1250 
1251 	if (ismyaddr((struct sockaddr *)&ss) ||
1252 			is_loopback_addr((struct sockaddr *)&ss)) {
1253 		return true;
1254 	}
1255 
1256 	n = get_interfaces(talloc_tos(), &nics);
1257 	for (i=0; i<n; i++) {
1258 		if (sockaddr_equal((struct sockaddr *)&nics[i].ip, (struct sockaddr *)&ss)) {
1259 			TALLOC_FREE(nics);
1260 			return true;
1261 		}
1262 	}
1263 	TALLOC_FREE(nics);
1264 	return false;
1265 }
1266 
1267 /************************************************************
1268  Is this my name ?
1269 ************************************************************/
1270 
is_myname_or_ipaddr(const char * s)1271 bool is_myname_or_ipaddr(const char *s)
1272 {
1273 	TALLOC_CTX *ctx = talloc_tos();
1274 	char *name = NULL;
1275 	const char *dnsname;
1276 	char *servername = NULL;
1277 
1278 	if (!s) {
1279 		return false;
1280 	}
1281 
1282 	/* Santize the string from '\\name' */
1283 	name = talloc_strdup(ctx, s);
1284 	if (!name) {
1285 		return false;
1286 	}
1287 
1288 	servername = strrchr_m(name, '\\' );
1289 	if (!servername) {
1290 		servername = name;
1291 	} else {
1292 		servername++;
1293 	}
1294 
1295 	/* Optimize for the common case */
1296 	if (strequal(servername, lp_netbios_name())) {
1297 		return true;
1298 	}
1299 
1300 	/* Check for an alias */
1301 	if (is_myname(servername)) {
1302 		return true;
1303 	}
1304 
1305 	/* Check for loopback */
1306 	if (strequal(servername, "127.0.0.1") ||
1307 			strequal(servername, "::1")) {
1308 		return true;
1309 	}
1310 
1311 	if (strequal(servername, "localhost")) {
1312 		return true;
1313 	}
1314 
1315 	/* Maybe it's my dns name */
1316 	dnsname = get_mydnsfullname();
1317 	if (dnsname && strequal(servername, dnsname)) {
1318 		return true;
1319 	}
1320 
1321 	/* Maybe its an IP address? */
1322 	if (is_ipaddress(servername)) {
1323 		return is_my_ipaddr(servername);
1324 	}
1325 
1326 	/* Handle possible CNAME records - convert to an IP addr. list. */
1327 	{
1328 		/* Use DNS to resolve the name, check all addresses. */
1329 		struct addrinfo *p = NULL;
1330 		struct addrinfo *res = NULL;
1331 
1332 		if (!interpret_string_addr_internal(&res,
1333 				servername,
1334 				AI_ADDRCONFIG)) {
1335 			return false;
1336 		}
1337 
1338 		for (p = res; p; p = p->ai_next) {
1339 			char addr[INET6_ADDRSTRLEN];
1340 			struct sockaddr_storage ss;
1341 
1342 			ZERO_STRUCT(ss);
1343 			memcpy(&ss, p->ai_addr, p->ai_addrlen);
1344 			print_sockaddr(addr,
1345 					sizeof(addr),
1346 					&ss);
1347 			if (is_my_ipaddr(addr)) {
1348 				freeaddrinfo(res);
1349 				return true;
1350 			}
1351 		}
1352 		freeaddrinfo(res);
1353 	}
1354 
1355 	/* No match */
1356 	return false;
1357 }
1358 
poll_one_fd(int fd,int events,int timeout,int * revents)1359 int poll_one_fd(int fd, int events, int timeout, int *revents)
1360 {
1361 	struct pollfd pfd;
1362 	int ret;
1363 
1364 	pfd.fd = fd;
1365 	pfd.events = events;
1366 
1367 	ret = poll(&pfd, 1, timeout);
1368 
1369 	/*
1370 	 * Assign whatever poll did, even in the ret<=0 case.
1371 	 */
1372 	*revents = pfd.revents;
1373 
1374 	return ret;
1375 }
1376 
poll_intr_one_fd(int fd,int events,int timeout,int * revents)1377 int poll_intr_one_fd(int fd, int events, int timeout, int *revents)
1378 {
1379 	struct pollfd pfd;
1380 	int ret;
1381 
1382 	pfd.fd = fd;
1383 	pfd.events = events;
1384 
1385 	ret = sys_poll_intr(&pfd, 1, timeout);
1386 	if (ret <= 0) {
1387 		*revents = 0;
1388 		return ret;
1389 	}
1390 	*revents = pfd.revents;
1391 	return 1;
1392 }
1393