xref: /titanic_52/usr/src/uts/common/fs/smbsrv/smb_session.c (revision 9ef283481583d677cd2cf5449ef49b90eacc97d4)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2012 Nexenta Systems, Inc.  All rights reserved.
24  */
25 #include <sys/atomic.h>
26 #include <sys/strsubr.h>
27 #include <sys/synch.h>
28 #include <sys/types.h>
29 #include <sys/socketvar.h>
30 #include <sys/sdt.h>
31 #include <sys/random.h>
32 #include <smbsrv/netbios.h>
33 #include <smbsrv/smb_kproto.h>
34 #include <smbsrv/string.h>
35 #include <inet/tcp.h>
36 
37 static volatile uint64_t smb_kids;
38 
39 uint32_t smb_keep_alive = SSN_KEEP_ALIVE_TIMEOUT;
40 
41 static void smb_session_cancel(smb_session_t *);
42 static int smb_session_message(smb_session_t *);
43 static int smb_session_xprt_puthdr(smb_session_t *, smb_xprt_t *,
44     uint8_t *, size_t);
45 static smb_user_t *smb_session_lookup_user(smb_session_t *, char *, char *);
46 static void smb_session_logoff(smb_session_t *);
47 static void smb_request_init_command_mbuf(smb_request_t *sr);
48 void dump_smb_inaddr(smb_inaddr_t *ipaddr);
49 static void smb_session_genkey(smb_session_t *);
50 
51 void
52 smb_session_timers(smb_llist_t *ll)
53 {
54 	smb_session_t	*session;
55 
56 	smb_llist_enter(ll, RW_READER);
57 	session = smb_llist_head(ll);
58 	while (session != NULL) {
59 		/*
60 		 * Walk through the table and decrement each keep_alive
61 		 * timer that has not timed out yet. (keepalive > 0)
62 		 */
63 		SMB_SESSION_VALID(session);
64 		if (session->keep_alive &&
65 		    (session->keep_alive != (uint32_t)-1))
66 			session->keep_alive--;
67 		session = smb_llist_next(ll, session);
68 	}
69 	smb_llist_exit(ll);
70 }
71 
72 void
73 smb_session_correct_keep_alive_values(smb_llist_t *ll, uint32_t new_keep_alive)
74 {
75 	smb_session_t		*sn;
76 
77 	if (new_keep_alive == smb_keep_alive)
78 		return;
79 	/*
80 	 * keep alive == 0 means do not drop connection if it's idle
81 	 */
82 	smb_keep_alive = (new_keep_alive) ? new_keep_alive : -1;
83 
84 	/*
85 	 * Walk through the table and set each session to the new keep_alive
86 	 * value if they have not already timed out.  Block clock interrupts.
87 	 */
88 	smb_llist_enter(ll, RW_READER);
89 	sn = smb_llist_head(ll);
90 	while (sn != NULL) {
91 		SMB_SESSION_VALID(sn);
92 		if (sn->keep_alive != 0)
93 			sn->keep_alive = new_keep_alive;
94 		sn = smb_llist_next(ll, sn);
95 	}
96 	smb_llist_exit(ll);
97 }
98 
99 /*
100  * Send a session message - supports SMB-over-NBT and SMB-over-TCP.
101  *
102  * The mbuf chain is copied into a contiguous buffer so that the whole
103  * message is submitted to smb_sosend as a single request.  This should
104  * help Ethereal/Wireshark delineate the packets correctly even though
105  * TCP_NODELAY has been set on the socket.
106  *
107  * If an mbuf chain is provided, it will be freed and set to NULL here.
108  */
109 int
110 smb_session_send(smb_session_t *session, uint8_t type, mbuf_chain_t *mbc)
111 {
112 	smb_txreq_t	*txr;
113 	smb_xprt_t	hdr;
114 	int		rc;
115 
116 	switch (session->s_state) {
117 	case SMB_SESSION_STATE_DISCONNECTED:
118 	case SMB_SESSION_STATE_TERMINATED:
119 		if ((mbc != NULL) && (mbc->chain != NULL)) {
120 			m_freem(mbc->chain);
121 			mbc->chain = NULL;
122 			mbc->flags = 0;
123 		}
124 		return (ENOTCONN);
125 	default:
126 		break;
127 	}
128 
129 	txr = smb_net_txr_alloc();
130 
131 	if ((mbc != NULL) && (mbc->chain != NULL)) {
132 		rc = mbc_moveout(mbc, (caddr_t)&txr->tr_buf[NETBIOS_HDR_SZ],
133 		    sizeof (txr->tr_buf) - NETBIOS_HDR_SZ, &txr->tr_len);
134 		if (rc != 0) {
135 			smb_net_txr_free(txr);
136 			return (rc);
137 		}
138 	}
139 
140 	hdr.xh_type = type;
141 	hdr.xh_length = (uint32_t)txr->tr_len;
142 
143 	rc = smb_session_xprt_puthdr(session, &hdr, txr->tr_buf,
144 	    NETBIOS_HDR_SZ);
145 
146 	if (rc != 0) {
147 		smb_net_txr_free(txr);
148 		return (rc);
149 	}
150 	txr->tr_len += NETBIOS_HDR_SZ;
151 	smb_server_add_txb(session->s_server, (int64_t)txr->tr_len);
152 	return (smb_net_txr_send(session->sock, &session->s_txlst, txr));
153 }
154 
155 /*
156  * Read, process and respond to a NetBIOS session request.
157  *
158  * A NetBIOS session must be established for SMB-over-NetBIOS.  Validate
159  * the calling and called name format and save the client NetBIOS name,
160  * which is used when a NetBIOS session is established to check for and
161  * cleanup leftover state from a previous session.
162  *
163  * Session requests are not valid for SMB-over-TCP, which is unfortunate
164  * because without the client name leftover state cannot be cleaned up
165  * if the client is behind a NAT server.
166  */
167 static int
168 smb_session_request(struct smb_session *session)
169 {
170 	int			rc;
171 	char			*calling_name;
172 	char			*called_name;
173 	char 			client_name[NETBIOS_NAME_SZ];
174 	struct mbuf_chain 	mbc;
175 	char 			*names = NULL;
176 	smb_wchar_t		*wbuf = NULL;
177 	smb_xprt_t		hdr;
178 	char *p;
179 	int rc1, rc2;
180 
181 	session->keep_alive = smb_keep_alive;
182 
183 	if ((rc = smb_session_xprt_gethdr(session, &hdr)) != 0)
184 		return (rc);
185 
186 	DTRACE_PROBE2(receive__session__req__xprthdr, struct session *, session,
187 	    smb_xprt_t *, &hdr);
188 
189 	if ((hdr.xh_type != SESSION_REQUEST) ||
190 	    (hdr.xh_length != NETBIOS_SESSION_REQUEST_DATA_LENGTH)) {
191 		DTRACE_PROBE1(receive__session__req__failed,
192 		    struct session *, session);
193 		return (EINVAL);
194 	}
195 
196 	names = kmem_alloc(hdr.xh_length, KM_SLEEP);
197 
198 	if ((rc = smb_sorecv(session->sock, names, hdr.xh_length)) != 0) {
199 		kmem_free(names, hdr.xh_length);
200 		DTRACE_PROBE1(receive__session__req__failed,
201 		    struct session *, session);
202 		return (rc);
203 	}
204 
205 	DTRACE_PROBE3(receive__session__req__data, struct session *, session,
206 	    char *, names, uint32_t, hdr.xh_length);
207 
208 	called_name = &names[0];
209 	calling_name = &names[NETBIOS_ENCODED_NAME_SZ + 2];
210 
211 	rc1 = netbios_name_isvalid(called_name, 0);
212 	rc2 = netbios_name_isvalid(calling_name, client_name);
213 
214 	if (rc1 == 0 || rc2 == 0) {
215 
216 		DTRACE_PROBE3(receive__invalid__session__req,
217 		    struct session *, session, char *, names,
218 		    uint32_t, hdr.xh_length);
219 
220 		kmem_free(names, hdr.xh_length);
221 		MBC_INIT(&mbc, MAX_DATAGRAM_LENGTH);
222 		(void) smb_mbc_encodef(&mbc, "b",
223 		    DATAGRAM_INVALID_SOURCE_NAME_FORMAT);
224 		(void) smb_session_send(session, NEGATIVE_SESSION_RESPONSE,
225 		    &mbc);
226 		return (EINVAL);
227 	}
228 
229 	DTRACE_PROBE3(receive__session__req__calling__decoded,
230 	    struct session *, session,
231 	    char *, calling_name, char *, client_name);
232 
233 	/*
234 	 * The client NetBIOS name is in oem codepage format.
235 	 * We need to convert it to unicode and store it in
236 	 * multi-byte format.  We also need to strip off any
237 	 * spaces added as part of the NetBIOS name encoding.
238 	 */
239 	wbuf = kmem_alloc((SMB_PI_MAX_HOST * sizeof (smb_wchar_t)), KM_SLEEP);
240 	(void) oemtoucs(wbuf, client_name, SMB_PI_MAX_HOST, OEM_CPG_850);
241 	(void) smb_wcstombs(session->workstation, wbuf, SMB_PI_MAX_HOST);
242 	kmem_free(wbuf, (SMB_PI_MAX_HOST * sizeof (smb_wchar_t)));
243 
244 	if ((p = strchr(session->workstation, ' ')) != 0)
245 		*p = '\0';
246 
247 	kmem_free(names, hdr.xh_length);
248 	return (smb_session_send(session, POSITIVE_SESSION_RESPONSE, NULL));
249 }
250 
251 /*
252  * Read 4-byte header from the session socket and build an in-memory
253  * session transport header.  See smb_xprt_t definition for header
254  * format information.
255  *
256  * Direct hosted NetBIOS-less SMB (SMB-over-TCP) uses port 445.  The
257  * first byte of the four-byte header must be 0 and the next three
258  * bytes contain the length of the remaining data.
259  */
260 int
261 smb_session_xprt_gethdr(smb_session_t *session, smb_xprt_t *ret_hdr)
262 {
263 	int		rc;
264 	unsigned char	buf[NETBIOS_HDR_SZ];
265 
266 	if ((rc = smb_sorecv(session->sock, buf, NETBIOS_HDR_SZ)) != 0)
267 		return (rc);
268 
269 	switch (session->s_local_port) {
270 	case IPPORT_NETBIOS_SSN:
271 		ret_hdr->xh_type = buf[0];
272 		ret_hdr->xh_length = (((uint32_t)buf[1] & 1) << 16) |
273 		    ((uint32_t)buf[2] << 8) |
274 		    ((uint32_t)buf[3]);
275 		break;
276 
277 	case IPPORT_SMB:
278 		ret_hdr->xh_type = buf[0];
279 
280 		if (ret_hdr->xh_type != 0) {
281 			cmn_err(CE_WARN, "invalid type (%u)", ret_hdr->xh_type);
282 			dump_smb_inaddr(&session->ipaddr);
283 			return (EPROTO);
284 		}
285 
286 		ret_hdr->xh_length = ((uint32_t)buf[1] << 16) |
287 		    ((uint32_t)buf[2] << 8) |
288 		    ((uint32_t)buf[3]);
289 		break;
290 
291 	default:
292 		cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
293 		dump_smb_inaddr(&session->ipaddr);
294 		return (EPROTO);
295 	}
296 
297 	return (0);
298 }
299 
300 /*
301  * Encode a transport session packet header into a 4-byte buffer.
302  * See smb_xprt_t definition for header format information.
303  */
304 static int
305 smb_session_xprt_puthdr(smb_session_t *session, smb_xprt_t *hdr,
306     uint8_t *buf, size_t buflen)
307 {
308 	if (session == NULL || hdr == NULL ||
309 	    buf == NULL || buflen < NETBIOS_HDR_SZ) {
310 		return (-1);
311 	}
312 
313 	switch (session->s_local_port) {
314 	case IPPORT_NETBIOS_SSN:
315 		buf[0] = hdr->xh_type;
316 		buf[1] = ((hdr->xh_length >> 16) & 1);
317 		buf[2] = (hdr->xh_length >> 8) & 0xff;
318 		buf[3] = hdr->xh_length & 0xff;
319 		break;
320 
321 	case IPPORT_SMB:
322 		buf[0] = hdr->xh_type;
323 		buf[1] = (hdr->xh_length >> 16) & 0xff;
324 		buf[2] = (hdr->xh_length >> 8) & 0xff;
325 		buf[3] = hdr->xh_length & 0xff;
326 		break;
327 
328 	default:
329 		cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
330 		dump_smb_inaddr(&session->ipaddr);
331 		return (-1);
332 	}
333 
334 	return (0);
335 }
336 
337 static void
338 smb_request_init_command_mbuf(smb_request_t *sr)
339 {
340 
341 	/*
342 	 * Setup mbuf using the buffer we allocated.
343 	 */
344 	MBC_ATTACH_BUF(&sr->command, sr->sr_request_buf, sr->sr_req_length);
345 
346 	sr->command.flags = 0;
347 	sr->command.shadow_of = NULL;
348 }
349 
350 /*
351  * smb_request_cancel
352  *
353  * Handle a cancel for a request properly depending on the current request
354  * state.
355  */
356 void
357 smb_request_cancel(smb_request_t *sr)
358 {
359 	mutex_enter(&sr->sr_mutex);
360 	switch (sr->sr_state) {
361 
362 	case SMB_REQ_STATE_INITIALIZING:
363 	case SMB_REQ_STATE_SUBMITTED:
364 	case SMB_REQ_STATE_ACTIVE:
365 	case SMB_REQ_STATE_CLEANED_UP:
366 		sr->sr_state = SMB_REQ_STATE_CANCELED;
367 		break;
368 
369 	case SMB_REQ_STATE_WAITING_LOCK:
370 		/*
371 		 * This request is waiting on a lock.  Wakeup everything
372 		 * waiting on the lock so that the relevant thread regains
373 		 * control and notices that is has been canceled.  The
374 		 * other lock request threads waiting on this lock will go
375 		 * back to sleep when they discover they are still blocked.
376 		 */
377 		sr->sr_state = SMB_REQ_STATE_CANCELED;
378 
379 		ASSERT(sr->sr_awaiting != NULL);
380 		mutex_enter(&sr->sr_awaiting->l_mutex);
381 		cv_broadcast(&sr->sr_awaiting->l_cv);
382 		mutex_exit(&sr->sr_awaiting->l_mutex);
383 		break;
384 
385 	case SMB_REQ_STATE_WAITING_EVENT:
386 		/*
387 		 * This request is waiting in change notify.
388 		 */
389 		sr->sr_state = SMB_REQ_STATE_CANCELED;
390 		cv_signal(&sr->sr_ncr.nc_cv);
391 		break;
392 
393 	case SMB_REQ_STATE_EVENT_OCCURRED:
394 	case SMB_REQ_STATE_COMPLETED:
395 	case SMB_REQ_STATE_CANCELED:
396 		/*
397 		 * No action required for these states since the request
398 		 * is completing.
399 		 */
400 		break;
401 
402 	case SMB_REQ_STATE_FREE:
403 	default:
404 		SMB_PANIC();
405 	}
406 	mutex_exit(&sr->sr_mutex);
407 }
408 
409 /*
410  * smb_session_receiver
411  *
412  * Receives request from the network and dispatches them to a worker.
413  */
414 void
415 smb_session_receiver(smb_session_t *session)
416 {
417 	int	rc;
418 
419 	SMB_SESSION_VALID(session);
420 
421 	session->s_thread = curthread;
422 
423 	if (session->s_local_port == IPPORT_NETBIOS_SSN) {
424 		rc = smb_session_request(session);
425 		if (rc != 0) {
426 			smb_rwx_rwenter(&session->s_lock, RW_WRITER);
427 			session->s_state = SMB_SESSION_STATE_DISCONNECTED;
428 			smb_rwx_rwexit(&session->s_lock);
429 			return;
430 		}
431 	}
432 
433 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
434 	session->s_state = SMB_SESSION_STATE_ESTABLISHED;
435 	smb_rwx_rwexit(&session->s_lock);
436 
437 	(void) smb_session_message(session);
438 
439 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
440 	session->s_state = SMB_SESSION_STATE_DISCONNECTED;
441 	smb_rwx_rwexit(&session->s_lock);
442 
443 	smb_soshutdown(session->sock);
444 
445 	DTRACE_PROBE2(session__drop, struct session *, session, int, rc);
446 
447 	smb_session_cancel(session);
448 	/*
449 	 * At this point everything related to the session should have been
450 	 * cleaned up and we expect that nothing will attempt to use the
451 	 * socket.
452 	 */
453 }
454 
455 /*
456  * smb_session_disconnect
457  *
458  * Disconnects the session passed in.
459  */
460 void
461 smb_session_disconnect(smb_session_t *session)
462 {
463 	SMB_SESSION_VALID(session);
464 
465 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
466 	switch (session->s_state) {
467 	case SMB_SESSION_STATE_INITIALIZED:
468 	case SMB_SESSION_STATE_CONNECTED:
469 	case SMB_SESSION_STATE_ESTABLISHED:
470 	case SMB_SESSION_STATE_NEGOTIATED:
471 	case SMB_SESSION_STATE_OPLOCK_BREAKING:
472 	case SMB_SESSION_STATE_WRITE_RAW_ACTIVE:
473 	case SMB_SESSION_STATE_READ_RAW_ACTIVE:
474 		smb_soshutdown(session->sock);
475 		session->s_state = SMB_SESSION_STATE_DISCONNECTED;
476 		_NOTE(FALLTHRU)
477 	case SMB_SESSION_STATE_DISCONNECTED:
478 	case SMB_SESSION_STATE_TERMINATED:
479 		break;
480 	}
481 	smb_rwx_rwexit(&session->s_lock);
482 }
483 
484 /*
485  * Read and process SMB requests.
486  *
487  * Returns:
488  *	0	Success
489  *	1	Unable to read transport header
490  *	2	Invalid transport header type
491  *	3	Invalid SMB length (too small)
492  *	4	Unable to read SMB header
493  *	5	Invalid SMB header (bad magic number)
494  *	6	Unable to read SMB data
495  *	2x	Write raw failed
496  */
497 static int
498 smb_session_message(smb_session_t *session)
499 {
500 	smb_server_t	*sv;
501 	smb_request_t	*sr = NULL;
502 	smb_xprt_t	hdr;
503 	uint8_t		*req_buf;
504 	uint32_t	resid;
505 	int		rc;
506 
507 	sv = session->s_server;
508 
509 	for (;;) {
510 
511 		rc = smb_session_xprt_gethdr(session, &hdr);
512 		if (rc)
513 			return (rc);
514 
515 		DTRACE_PROBE2(session__receive__xprthdr, session_t *, session,
516 		    smb_xprt_t *, &hdr);
517 
518 		if (hdr.xh_type != SESSION_MESSAGE) {
519 			/*
520 			 * Anything other than SESSION_MESSAGE or
521 			 * SESSION_KEEP_ALIVE is an error.  A SESSION_REQUEST
522 			 * may indicate a new session request but we need to
523 			 * close this session and we can treat it as an error
524 			 * here.
525 			 */
526 			if (hdr.xh_type == SESSION_KEEP_ALIVE) {
527 				session->keep_alive = smb_keep_alive;
528 				continue;
529 			}
530 			return (EPROTO);
531 		}
532 
533 		if (hdr.xh_length < SMB_HEADER_LEN)
534 			return (EPROTO);
535 
536 		session->keep_alive = smb_keep_alive;
537 		/*
538 		 * Allocate a request context, read the SMB header and validate
539 		 * it. The sr includes a buffer large enough to hold the SMB
540 		 * request payload.  If the header looks valid, read any
541 		 * remaining data.
542 		 */
543 		sr = smb_request_alloc(session, hdr.xh_length);
544 
545 		req_buf = (uint8_t *)sr->sr_request_buf;
546 		resid = hdr.xh_length;
547 
548 		rc = smb_sorecv(session->sock, req_buf, SMB_HEADER_LEN);
549 		if (rc) {
550 			smb_request_free(sr);
551 			return (rc);
552 		}
553 
554 		if (SMB_PROTOCOL_MAGIC_INVALID(sr)) {
555 			smb_request_free(sr);
556 			return (EPROTO);
557 		}
558 
559 		if (resid > SMB_HEADER_LEN) {
560 			req_buf += SMB_HEADER_LEN;
561 			resid -= SMB_HEADER_LEN;
562 
563 			rc = smb_sorecv(session->sock, req_buf, resid);
564 			if (rc) {
565 				smb_request_free(sr);
566 				return (rc);
567 			}
568 		}
569 		smb_server_add_rxb(sv,
570 		    (int64_t)(hdr.xh_length + NETBIOS_HDR_SZ));
571 		/*
572 		 * Initialize command MBC to represent the received data.
573 		 */
574 		smb_request_init_command_mbuf(sr);
575 
576 		DTRACE_PROBE1(session__receive__smb, smb_request_t *, sr);
577 
578 		/*
579 		 * If this is a raw write, hand off the request.  The handler
580 		 * will retrieve the remaining raw data and process the request.
581 		 */
582 		if (SMB_IS_WRITERAW(sr)) {
583 			rc = smb_handle_write_raw(session, sr);
584 			if (rc == 0)
585 				continue;
586 			return (rc);
587 		}
588 		if (sr->session->signing.flags & SMB_SIGNING_ENABLED) {
589 			if (SMB_IS_NT_CANCEL(sr)) {
590 				sr->session->signing.seqnum++;
591 				sr->sr_seqnum = sr->session->signing.seqnum + 1;
592 				sr->reply_seqnum = 0;
593 			} else {
594 				sr->session->signing.seqnum += 2;
595 				sr->sr_seqnum = sr->session->signing.seqnum;
596 				sr->reply_seqnum = sr->sr_seqnum + 1;
597 			}
598 		}
599 		sr->sr_time_submitted = gethrtime();
600 		sr->sr_state = SMB_REQ_STATE_SUBMITTED;
601 		smb_srqueue_waitq_enter(session->s_srqueue);
602 		(void) taskq_dispatch(session->s_server->sv_worker_pool,
603 		    smb_session_worker, sr, TQ_SLEEP);
604 	}
605 }
606 
607 /*
608  * Port will be IPPORT_NETBIOS_SSN or IPPORT_SMB.
609  */
610 smb_session_t *
611 smb_session_create(ksocket_t new_so, uint16_t port, smb_server_t *sv,
612     int family)
613 {
614 	struct sockaddr_in	sin;
615 	socklen_t		slen;
616 	struct sockaddr_in6	sin6;
617 	smb_session_t		*session;
618 	int64_t			now;
619 
620 	session = kmem_cache_alloc(sv->si_cache_session, KM_SLEEP);
621 	bzero(session, sizeof (smb_session_t));
622 
623 	if (smb_idpool_constructor(&session->s_uid_pool)) {
624 		kmem_cache_free(sv->si_cache_session, session);
625 		return (NULL);
626 	}
627 
628 	now = ddi_get_lbolt64();
629 
630 	session->s_kid = SMB_NEW_KID();
631 	session->s_state = SMB_SESSION_STATE_INITIALIZED;
632 	session->native_os = NATIVE_OS_UNKNOWN;
633 	session->opentime = now;
634 	session->keep_alive = smb_keep_alive;
635 	session->activity_timestamp = now;
636 
637 	smb_session_genkey(session);
638 
639 	smb_slist_constructor(&session->s_req_list, sizeof (smb_request_t),
640 	    offsetof(smb_request_t, sr_session_lnd));
641 
642 	smb_llist_constructor(&session->s_user_list, sizeof (smb_user_t),
643 	    offsetof(smb_user_t, u_lnd));
644 
645 	smb_llist_constructor(&session->s_xa_list, sizeof (smb_xa_t),
646 	    offsetof(smb_xa_t, xa_lnd));
647 
648 	list_create(&session->s_oplock_brkreqs, sizeof (mbuf_chain_t),
649 	    offsetof(mbuf_chain_t, mbc_lnd));
650 
651 	smb_net_txl_constructor(&session->s_txlst);
652 
653 	smb_rwx_init(&session->s_lock);
654 
655 	if (new_so != NULL) {
656 		if (family == AF_INET) {
657 			slen = sizeof (sin);
658 			(void) ksocket_getsockname(new_so,
659 			    (struct sockaddr *)&sin, &slen, CRED());
660 			bcopy(&sin.sin_addr,
661 			    &session->local_ipaddr.au_addr.au_ipv4,
662 			    sizeof (in_addr_t));
663 			slen = sizeof (sin);
664 			(void) ksocket_getpeername(new_so,
665 			    (struct sockaddr *)&sin, &slen, CRED());
666 			bcopy(&sin.sin_addr,
667 			    &session->ipaddr.au_addr.au_ipv4,
668 			    sizeof (in_addr_t));
669 		} else {
670 			slen = sizeof (sin6);
671 			(void) ksocket_getsockname(new_so,
672 			    (struct sockaddr *)&sin6, &slen, CRED());
673 			bcopy(&sin6.sin6_addr,
674 			    &session->local_ipaddr.au_addr.au_ipv6,
675 			    sizeof (in6_addr_t));
676 			slen = sizeof (sin6);
677 			(void) ksocket_getpeername(new_so,
678 			    (struct sockaddr *)&sin6, &slen, CRED());
679 			bcopy(&sin6.sin6_addr,
680 			    &session->ipaddr.au_addr.au_ipv6,
681 			    sizeof (in6_addr_t));
682 		}
683 		session->ipaddr.a_family = family;
684 		session->local_ipaddr.a_family = family;
685 		session->s_local_port = port;
686 		session->sock = new_so;
687 		if (port == IPPORT_NETBIOS_SSN)
688 			smb_server_inc_nbt_sess(sv);
689 		else
690 			smb_server_inc_tcp_sess(sv);
691 	}
692 	session->s_server = sv;
693 	smb_server_get_cfg(sv, &session->s_cfg);
694 	session->s_srqueue = &sv->sv_srqueue;
695 
696 	session->s_cache_request = sv->si_cache_request;
697 	session->s_cache = sv->si_cache_session;
698 	session->s_magic = SMB_SESSION_MAGIC;
699 	return (session);
700 }
701 
702 void
703 smb_session_delete(smb_session_t *session)
704 {
705 	mbuf_chain_t	*mbc;
706 
707 	ASSERT(session->s_magic == SMB_SESSION_MAGIC);
708 
709 	session->s_magic = 0;
710 
711 	smb_rwx_destroy(&session->s_lock);
712 	smb_net_txl_destructor(&session->s_txlst);
713 
714 	while ((mbc = list_head(&session->s_oplock_brkreqs)) != NULL) {
715 		SMB_MBC_VALID(mbc);
716 		list_remove(&session->s_oplock_brkreqs, mbc);
717 		smb_mbc_free(mbc);
718 	}
719 	list_destroy(&session->s_oplock_brkreqs);
720 
721 	smb_slist_destructor(&session->s_req_list);
722 	smb_llist_destructor(&session->s_user_list);
723 	smb_llist_destructor(&session->s_xa_list);
724 
725 	ASSERT(session->s_tree_cnt == 0);
726 	ASSERT(session->s_file_cnt == 0);
727 	ASSERT(session->s_dir_cnt == 0);
728 
729 	smb_idpool_destructor(&session->s_uid_pool);
730 	if (session->sock != NULL) {
731 		if (session->s_local_port == IPPORT_NETBIOS_SSN)
732 			smb_server_dec_nbt_sess(session->s_server);
733 		else
734 			smb_server_dec_tcp_sess(session->s_server);
735 		smb_sodestroy(session->sock);
736 	}
737 	kmem_cache_free(session->s_cache, session);
738 }
739 
740 static void
741 smb_session_cancel(smb_session_t *session)
742 {
743 	smb_xa_t	*xa, *nextxa;
744 
745 	/* All the request currently being treated must be canceled. */
746 	smb_session_cancel_requests(session, NULL, NULL);
747 
748 	/*
749 	 * We wait for the completion of all the requests associated with
750 	 * this session.
751 	 */
752 	smb_slist_wait_for_empty(&session->s_req_list);
753 
754 	/*
755 	 * At this point the reference count of the users, trees, files,
756 	 * directories should be zero. It should be possible to destroy them
757 	 * without any problem.
758 	 */
759 	xa = smb_llist_head(&session->s_xa_list);
760 	while (xa) {
761 		nextxa = smb_llist_next(&session->s_xa_list, xa);
762 		smb_xa_close(xa);
763 		xa = nextxa;
764 	}
765 
766 	smb_session_logoff(session);
767 }
768 
769 /*
770  * Cancel requests.  If a non-null tree is specified, only requests specific
771  * to that tree will be cancelled.  If a non-null sr is specified, that sr
772  * will be not be cancelled - this would typically be the caller's sr.
773  */
774 void
775 smb_session_cancel_requests(
776     smb_session_t	*session,
777     smb_tree_t		*tree,
778     smb_request_t	*exclude_sr)
779 {
780 	smb_request_t	*sr;
781 
782 	smb_slist_enter(&session->s_req_list);
783 	sr = smb_slist_head(&session->s_req_list);
784 
785 	while (sr) {
786 		ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
787 		if ((sr != exclude_sr) &&
788 		    (tree == NULL || sr->tid_tree == tree))
789 			smb_request_cancel(sr);
790 
791 		sr = smb_slist_next(&session->s_req_list, sr);
792 	}
793 
794 	smb_slist_exit(&session->s_req_list);
795 }
796 
797 void
798 smb_session_worker(void	*arg)
799 {
800 	smb_request_t	*sr;
801 	smb_srqueue_t	*srq;
802 
803 	sr = (smb_request_t *)arg;
804 	SMB_REQ_VALID(sr);
805 
806 	srq = sr->session->s_srqueue;
807 	smb_srqueue_waitq_to_runq(srq);
808 	sr->sr_worker = curthread;
809 	mutex_enter(&sr->sr_mutex);
810 	sr->sr_time_active = gethrtime();
811 	switch (sr->sr_state) {
812 	case SMB_REQ_STATE_SUBMITTED:
813 		mutex_exit(&sr->sr_mutex);
814 		if (smb_dispatch_request(sr)) {
815 			mutex_enter(&sr->sr_mutex);
816 			sr->sr_state = SMB_REQ_STATE_COMPLETED;
817 			mutex_exit(&sr->sr_mutex);
818 			smb_request_free(sr);
819 		}
820 		break;
821 
822 	default:
823 		ASSERT(sr->sr_state == SMB_REQ_STATE_CANCELED);
824 		sr->sr_state = SMB_REQ_STATE_COMPLETED;
825 		mutex_exit(&sr->sr_mutex);
826 		smb_request_free(sr);
827 		break;
828 	}
829 	smb_srqueue_runq_exit(srq);
830 }
831 
832 /*
833  * smb_session_lookup_user
834  */
835 static smb_user_t *
836 smb_session_lookup_user(smb_session_t *session, char *domain, char *name)
837 {
838 	smb_user_t	*user;
839 	smb_llist_t	*ulist;
840 
841 	ulist = &session->s_user_list;
842 	smb_llist_enter(ulist, RW_READER);
843 	user = smb_llist_head(ulist);
844 	while (user) {
845 		ASSERT(user->u_magic == SMB_USER_MAGIC);
846 		if (!smb_strcasecmp(user->u_name, name, 0) &&
847 		    !smb_strcasecmp(user->u_domain, domain, 0)) {
848 			if (smb_user_hold(user))
849 				break;
850 		}
851 		user = smb_llist_next(ulist, user);
852 	}
853 	smb_llist_exit(ulist);
854 
855 	return (user);
856 }
857 
858 /*
859  * If a user attempts to log in subsequently from the specified session,
860  * duplicates the existing SMB user instance such that all SMB user
861  * instances that corresponds to the same user on the given session
862  * reference the same user's cred.
863  *
864  * Returns NULL if the given user hasn't yet logged in from this
865  * specified session.  Otherwise, returns a user instance that corresponds
866  * to this subsequent login.
867  */
868 smb_user_t *
869 smb_session_dup_user(smb_session_t *session, char *domain, char *account_name)
870 {
871 	smb_user_t *orig_user = NULL;
872 	smb_user_t *user = NULL;
873 
874 	orig_user = smb_session_lookup_user(session, domain,
875 	    account_name);
876 
877 	if (orig_user) {
878 		user = smb_user_dup(orig_user);
879 		smb_user_release(orig_user);
880 	}
881 
882 	return (user);
883 }
884 
885 /*
886  * Find a user on the specified session by SMB UID.
887  */
888 smb_user_t *
889 smb_session_lookup_uid(smb_session_t *session, uint16_t uid)
890 {
891 	smb_user_t	*user;
892 	smb_llist_t	*user_list;
893 
894 	SMB_SESSION_VALID(session);
895 
896 	user_list = &session->s_user_list;
897 	smb_llist_enter(user_list, RW_READER);
898 
899 	user = smb_llist_head(user_list);
900 	while (user) {
901 		SMB_USER_VALID(user);
902 		ASSERT(user->u_session == session);
903 
904 		if (user->u_uid == uid) {
905 			if (!smb_user_hold(user))
906 				break;
907 
908 			smb_llist_exit(user_list);
909 			return (user);
910 		}
911 
912 		user = smb_llist_next(user_list, user);
913 	}
914 
915 	smb_llist_exit(user_list);
916 	return (NULL);
917 }
918 
919 void
920 smb_session_post_user(smb_session_t *session, smb_user_t *user)
921 {
922 	SMB_USER_VALID(user);
923 	ASSERT(user->u_refcnt == 0);
924 	ASSERT(user->u_state == SMB_USER_STATE_LOGGED_OFF);
925 	ASSERT(user->u_session == session);
926 
927 	smb_llist_post(&session->s_user_list, user, smb_user_delete);
928 }
929 
930 /*
931  * Logoff all users associated with the specified session.
932  */
933 static void
934 smb_session_logoff(smb_session_t *session)
935 {
936 	smb_user_t	*user;
937 
938 	SMB_SESSION_VALID(session);
939 
940 	smb_llist_enter(&session->s_user_list, RW_READER);
941 
942 	user = smb_llist_head(&session->s_user_list);
943 	while (user) {
944 		SMB_USER_VALID(user);
945 		ASSERT(user->u_session == session);
946 
947 		if (smb_user_hold(user)) {
948 			smb_user_logoff(user);
949 			smb_user_release(user);
950 		}
951 
952 		user = smb_llist_next(&session->s_user_list, user);
953 	}
954 
955 	smb_llist_exit(&session->s_user_list);
956 }
957 
958 /*
959  * Disconnect any trees associated with the specified share.
960  * Iterate through the users on this session and tell each user
961  * to disconnect from the share.
962  */
963 void
964 smb_session_disconnect_share(smb_session_t *session, const char *sharename)
965 {
966 	smb_user_t	*user;
967 
968 	SMB_SESSION_VALID(session);
969 
970 	smb_llist_enter(&session->s_user_list, RW_READER);
971 
972 	user = smb_llist_head(&session->s_user_list);
973 	while (user) {
974 		SMB_USER_VALID(user);
975 		ASSERT(user->u_session == session);
976 
977 		if (smb_user_hold(user)) {
978 			smb_user_disconnect_share(user, sharename);
979 			smb_user_release(user);
980 		}
981 
982 		user = smb_llist_next(&session->s_user_list, user);
983 	}
984 
985 	smb_llist_exit(&session->s_user_list);
986 }
987 
988 /*
989  * Copy the session workstation/client name to buf.  If the workstation
990  * is an empty string (which it will be on TCP connections), use the
991  * client IP address.
992  */
993 void
994 smb_session_getclient(smb_session_t *sn, char *buf, size_t buflen)
995 {
996 	char		ipbuf[INET6_ADDRSTRLEN];
997 	smb_inaddr_t	*ipaddr;
998 
999 	ASSERT(sn);
1000 	ASSERT(buf);
1001 	ASSERT(buflen);
1002 
1003 	*buf = '\0';
1004 
1005 	if (sn->workstation[0] != '\0') {
1006 		(void) strlcpy(buf, sn->workstation, buflen);
1007 		return;
1008 	}
1009 
1010 	ipaddr = &sn->ipaddr;
1011 	if (smb_inet_ntop(ipaddr, ipbuf, SMB_IPSTRLEN(ipaddr->a_family)))
1012 		(void) strlcpy(buf, ipbuf, buflen);
1013 }
1014 
1015 /*
1016  * Check whether or not the specified client name is the client of this
1017  * session.  The name may be in UNC format (\\CLIENT).
1018  *
1019  * A workstation/client name is setup on NBT connections as part of the
1020  * NetBIOS session request but that isn't available on TCP connections.
1021  * If the session doesn't have a client name we typically return the
1022  * client IP address as the workstation name on MSRPC requests.  So we
1023  * check for the IP address here in addition to the workstation name.
1024  */
1025 boolean_t
1026 smb_session_isclient(smb_session_t *sn, const char *client)
1027 {
1028 	char		buf[INET6_ADDRSTRLEN];
1029 	smb_inaddr_t	*ipaddr;
1030 
1031 	client += strspn(client, "\\");
1032 
1033 	if (smb_strcasecmp(client, sn->workstation, 0) == 0)
1034 		return (B_TRUE);
1035 
1036 	ipaddr = &sn->ipaddr;
1037 	if (smb_inet_ntop(ipaddr, buf, SMB_IPSTRLEN(ipaddr->a_family)) == NULL)
1038 		return (B_FALSE);
1039 
1040 	if (smb_strcasecmp(client, buf, 0) == 0)
1041 		return (B_TRUE);
1042 
1043 	return (B_FALSE);
1044 }
1045 
1046 /*
1047  * smb_request_alloc
1048  *
1049  * Allocate an smb_request_t structure from the kmem_cache.  Partially
1050  * initialize the found/new request.
1051  *
1052  * Returns pointer to a request
1053  */
1054 smb_request_t *
1055 smb_request_alloc(smb_session_t *session, int req_length)
1056 {
1057 	smb_request_t	*sr;
1058 
1059 	ASSERT(session->s_magic == SMB_SESSION_MAGIC);
1060 
1061 	sr = kmem_cache_alloc(session->s_cache_request, KM_SLEEP);
1062 
1063 	/*
1064 	 * Future:  Use constructor to pre-initialize some fields.  For now
1065 	 * there are so many fields that it is easiest just to zero the
1066 	 * whole thing and start over.
1067 	 */
1068 	bzero(sr, sizeof (smb_request_t));
1069 
1070 	mutex_init(&sr->sr_mutex, NULL, MUTEX_DEFAULT, NULL);
1071 	cv_init(&sr->sr_ncr.nc_cv, NULL, CV_DEFAULT, NULL);
1072 	smb_srm_init(sr);
1073 	sr->session = session;
1074 	sr->sr_server = session->s_server;
1075 	sr->sr_gmtoff = session->s_server->si_gmtoff;
1076 	sr->sr_cache = session->s_server->si_cache_request;
1077 	sr->sr_cfg = &session->s_cfg;
1078 	sr->command.max_bytes = req_length;
1079 	sr->reply.max_bytes = smb_maxbufsize;
1080 	sr->sr_req_length = req_length;
1081 	if (req_length)
1082 		sr->sr_request_buf = kmem_alloc(req_length, KM_SLEEP);
1083 	sr->sr_magic = SMB_REQ_MAGIC;
1084 	sr->sr_state = SMB_REQ_STATE_INITIALIZING;
1085 	smb_slist_insert_tail(&session->s_req_list, sr);
1086 	return (sr);
1087 }
1088 
1089 /*
1090  * smb_request_free
1091  *
1092  * release the memories which have been allocated for a smb request.
1093  */
1094 void
1095 smb_request_free(smb_request_t *sr)
1096 {
1097 	ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
1098 	ASSERT(sr->session);
1099 	ASSERT(sr->r_xa == NULL);
1100 	ASSERT(sr->sr_ncr.nc_fname == NULL);
1101 
1102 	if (sr->fid_ofile != NULL) {
1103 		smb_ofile_request_complete(sr->fid_ofile);
1104 		smb_ofile_release(sr->fid_ofile);
1105 	}
1106 
1107 	if (sr->tid_tree != NULL)
1108 		smb_tree_release(sr->tid_tree);
1109 
1110 	if (sr->uid_user != NULL)
1111 		smb_user_release(sr->uid_user);
1112 
1113 	smb_slist_remove(&sr->session->s_req_list, sr);
1114 
1115 	sr->session = NULL;
1116 
1117 	smb_srm_fini(sr);
1118 
1119 	if (sr->sr_request_buf)
1120 		kmem_free(sr->sr_request_buf, sr->sr_req_length);
1121 	if (sr->command.chain)
1122 		m_freem(sr->command.chain);
1123 	if (sr->reply.chain)
1124 		m_freem(sr->reply.chain);
1125 	if (sr->raw_data.chain)
1126 		m_freem(sr->raw_data.chain);
1127 
1128 	sr->sr_magic = 0;
1129 	cv_destroy(&sr->sr_ncr.nc_cv);
1130 	mutex_destroy(&sr->sr_mutex);
1131 	kmem_cache_free(sr->sr_cache, sr);
1132 }
1133 
1134 void
1135 dump_smb_inaddr(smb_inaddr_t *ipaddr)
1136 {
1137 	char ipstr[INET6_ADDRSTRLEN];
1138 
1139 	if (smb_inet_ntop(ipaddr, ipstr, SMB_IPSTRLEN(ipaddr->a_family)))
1140 		cmn_err(CE_WARN, "error ipstr=%s", ipstr);
1141 	else
1142 		cmn_err(CE_WARN, "error converting ip address");
1143 }
1144 
1145 boolean_t
1146 smb_session_oplocks_enable(smb_session_t *session)
1147 {
1148 	SMB_SESSION_VALID(session);
1149 	if (session->s_cfg.skc_oplock_enable == 0)
1150 		return (B_FALSE);
1151 	else
1152 		return (B_TRUE);
1153 }
1154 
1155 boolean_t
1156 smb_session_levelII_oplocks(smb_session_t *session)
1157 {
1158 	SMB_SESSION_VALID(session);
1159 	return (session->capabilities & CAP_LEVEL_II_OPLOCKS);
1160 }
1161 
1162 /*
1163  * smb_session_oplock_break
1164  *
1165  * The session lock must NOT be held by the caller of this thread;
1166  * as this would cause a deadlock.
1167  */
1168 void
1169 smb_session_oplock_break(smb_session_t *session,
1170     uint16_t tid, uint16_t fid, uint8_t brk)
1171 {
1172 	mbuf_chain_t	*mbc;
1173 
1174 	SMB_SESSION_VALID(session);
1175 
1176 	mbc = smb_mbc_alloc(MLEN);
1177 
1178 	(void) smb_mbc_encodef(mbc, "Mb19.wwwwbb3.wbb10.",
1179 	    SMB_COM_LOCKING_ANDX,
1180 	    tid,
1181 	    0xFFFF, 0, 0xFFFF, 8, 0xFF,
1182 	    fid,
1183 	    LOCKING_ANDX_OPLOCK_RELEASE,
1184 	    (brk == SMB_OPLOCK_BREAK_TO_LEVEL_II) ? 1 : 0);
1185 
1186 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1187 	switch (session->s_state) {
1188 	case SMB_SESSION_STATE_NEGOTIATED:
1189 	case SMB_SESSION_STATE_OPLOCK_BREAKING:
1190 	case SMB_SESSION_STATE_WRITE_RAW_ACTIVE:
1191 		session->s_state = SMB_SESSION_STATE_OPLOCK_BREAKING;
1192 		(void) smb_session_send(session, 0, mbc);
1193 		smb_mbc_free(mbc);
1194 		break;
1195 
1196 	case SMB_SESSION_STATE_READ_RAW_ACTIVE:
1197 		list_insert_tail(&session->s_oplock_brkreqs, mbc);
1198 		break;
1199 
1200 	case SMB_SESSION_STATE_DISCONNECTED:
1201 	case SMB_SESSION_STATE_TERMINATED:
1202 		smb_mbc_free(mbc);
1203 		break;
1204 
1205 	default:
1206 		SMB_PANIC();
1207 	}
1208 	smb_rwx_rwexit(&session->s_lock);
1209 }
1210 
1211 static void
1212 smb_session_genkey(smb_session_t *session)
1213 {
1214 	uint8_t		tmp_key[SMB_CHALLENGE_SZ];
1215 
1216 	(void) random_get_pseudo_bytes(tmp_key, SMB_CHALLENGE_SZ);
1217 	bcopy(tmp_key, &session->challenge_key, SMB_CHALLENGE_SZ);
1218 	session->challenge_len = SMB_CHALLENGE_SZ;
1219 
1220 	(void) random_get_pseudo_bytes(tmp_key, 4);
1221 	session->sesskey = tmp_key[0] | tmp_key[1] << 8 |
1222 	    tmp_key[2] << 16 | tmp_key[3] << 24;
1223 }
1224