xref: /illumos-gate/usr/src/uts/common/fs/smbsrv/smb_session.c (revision f82c7503d8cd13735eecb42e3242a78db240250d)
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 2011-2021 Tintri by DDN, Inc. All rights reserved.
24  * Copyright 2021-2023 RackTop Systems, Inc.
25  */
26 
27 #include <sys/atomic.h>
28 #include <sys/synch.h>
29 #include <sys/types.h>
30 #include <sys/sdt.h>
31 #include <sys/random.h>
32 #include <smbsrv/netbios.h>
33 #include <smbsrv/smb2_kproto.h>
34 #include <smbsrv/string.h>
35 #include <netinet/tcp.h>
36 
37 #define	SMB_NEW_KID()	atomic_inc_64_nv(&smb_kids)
38 
39 static volatile uint64_t smb_kids;
40 
41 /*
42  * We track the keepalive in minutes, but this constant
43  * specifies it in seconds, so convert to minutes.
44  */
45 uint32_t smb_keep_alive = SMB_PI_KEEP_ALIVE_MIN / 60;
46 
47 /*
48  * This is the maximum time we'll allow a "session" to exist with no
49  * authenticated smb_user_t objects on it.  This allows a client to
50  * logoff their "one and only" user session and then logon as some
51  * different user.  (There are some tests that do that.)  The same
52  * timeout mechanism also reduces the impact of clients that might
53  * open TCP connections but never authenticate.
54  */
55 int smb_session_auth_tmo = 30; /* sec. */
56 
57 /*
58  * There are many smbtorture test cases that send
59  * racing requests, and where the tests fail if we
60  * don't execute them in exactly the order sent.
61  * These are test bugs.  The protocol makes no
62  * guarantees about execution order of requests
63  * that are concurrently active.
64  *
65  * Nonetheless, smbtorture has many useful tests,
66  * so we have this work-around we can enable to
67  * basically force sequential execution.  When
68  * enabled, insert a delay after each request is
69  * issued a taskq job.  Enable this with mdb by
70  * setting smb_reader_delay to 10.  Don't make it
71  * more than 500 or so or the server will appear
72  * to be so slow that tests may time out.
73  */
74 int smb_reader_delay = 0;  /* mSec. */
75 
76 static int  smbsr_newrq_initial(smb_request_t *);
77 
78 static void smb_session_cancel(smb_session_t *);
79 static int smb_session_reader(smb_session_t *);
80 static int smb_session_xprt_puthdr(smb_session_t *,
81     uint8_t msg_type, uint32_t msg_len,
82     uint8_t *dst, size_t dstlen);
83 static void smb_session_disconnect_trees(smb_session_t	*);
84 static void smb_session_genkey(smb_session_t *);
85 
86 /*
87  * This (legacy) code is in support of an "idle timeout" feature,
88  * which is apparently incomplete.  To complete it, we should:
89  * when the keep_alive timer expires, check whether the client
90  * has any open files, and if not then kill their session.
91  * Right now the timers are there, but nothing happens when
92  * a timer expires.
93  *
94  * Todo: complete logic to kill idle sessions.
95  *
96  * Only called when sv_cfg.skc_keepalive != 0
97  */
98 void
99 smb_session_timers(smb_server_t *sv)
100 {
101 	smb_session_t	*session;
102 	smb_llist_t	*ll;
103 
104 	ll = &sv->sv_session_list;
105 	smb_llist_enter(ll, RW_READER);
106 	session = smb_llist_head(ll);
107 	while (session != NULL) {
108 		/*
109 		 * Walk through the table and decrement each keep_alive
110 		 * timer that has not timed out yet. (keepalive > 0)
111 		 */
112 		SMB_SESSION_VALID(session);
113 		if (session->keep_alive &&
114 		    (session->keep_alive != (uint32_t)-1))
115 			session->keep_alive--;
116 
117 		session = smb_llist_next(ll, session);
118 	}
119 	smb_llist_exit(ll);
120 }
121 
122 /*
123  * Send a session message - supports SMB-over-NBT and SMB-over-TCP.
124  * If an mbuf chain is provided (optional), it will be freed and
125  * set to NULL -- unconditionally!  (error or not)
126  *
127  * Prepends the 4-byte NBT header before sending.
128  */
129 int
130 smb_session_send(smb_session_t *session, uint8_t nbt_type, mbuf_chain_t *mbc)
131 {
132 	mbuf_t		*m = NULL;
133 	uint32_t	nbt_len;
134 	int		rc;
135 
136 	switch (session->s_state) {
137 	case SMB_SESSION_STATE_DISCONNECTED:
138 	case SMB_SESSION_STATE_TERMINATED:
139 		rc = ENOTCONN;
140 		goto out;
141 	default:
142 		break;
143 	}
144 
145 	/*
146 	 * Prepend the NBT header (NetBIOS or SMB/TCP)
147 	 * and fill it in.
148 	 *
149 	 * After this, we "own" the mbuf chain (m) and must
150 	 * either consume it (via send) or free it.
151 	 */
152 	if (mbc != NULL && (m = mbc->chain) != NULL) {
153 		nbt_len = MBC_LENGTH(mbc);
154 		m = m_prepend(mbc->chain, NETBIOS_HDR_SZ, M_WAIT);
155 		mbc->chain = NULL;
156 	} else {
157 		nbt_len = 0;
158 		MGET(m, M_WAIT, MT_DATA);
159 		m->m_len = NETBIOS_HDR_SZ;
160 	}
161 	ASSERT(m->m_len >= NETBIOS_HDR_SZ);
162 	rc = smb_session_xprt_puthdr(session, nbt_type, nbt_len,
163 	    mtod(m, uint8_t *), NETBIOS_HDR_SZ);
164 	if (rc != 0)
165 		goto out;
166 
167 	/* Send "consumes" m unconditionally */
168 	rc = smb_net_send_mbufs(session, m);
169 	if (rc == 0) {
170 		smb_server_add_txb(session->s_server,
171 		    nbt_len + NETBIOS_HDR_SZ);
172 	}
173 	m = NULL; // consumed
174 
175 out:
176 	if (m != NULL)
177 		m_freem(m);
178 	if (mbc != NULL && mbc->chain != NULL) {
179 		m_freem(mbc->chain);
180 		mbc->chain = NULL;
181 	}
182 
183 	return (rc);
184 }
185 
186 /*
187  * Read, process and respond to a NetBIOS session request.
188  *
189  * A NetBIOS session must be established for SMB-over-NetBIOS.  Validate
190  * the calling and called name format and save the client NetBIOS name,
191  * which is used when a NetBIOS session is established to check for and
192  * cleanup leftover state from a previous session.
193  *
194  * Session requests are not valid for SMB-over-TCP, which is unfortunate
195  * because without the client name leftover state cannot be cleaned up
196  * if the client is behind a NAT server.
197  */
198 static int
199 smb_netbios_session_request(struct smb_session *session)
200 {
201 	int			rc;
202 	char			*calling_name;
203 	char			*called_name;
204 	char			client_name[NETBIOS_NAME_SZ];
205 	struct mbuf_chain	mbc;
206 	char			*names = NULL;
207 	smb_wchar_t		*wbuf = NULL;
208 	smb_xprt_t		hdr;
209 	char *p;
210 	int rc1, rc2;
211 
212 	session->keep_alive = smb_keep_alive;
213 
214 	if ((rc = smb_session_xprt_gethdr(session, &hdr)) != 0)
215 		return (rc);
216 
217 	DTRACE_PROBE2(receive__session__req__xprthdr, struct session *, session,
218 	    smb_xprt_t *, &hdr);
219 
220 	if ((hdr.xh_type != SESSION_REQUEST) ||
221 	    (hdr.xh_length != NETBIOS_SESSION_REQUEST_DATA_LENGTH)) {
222 		DTRACE_PROBE1(receive__session__req__failed,
223 		    struct session *, session);
224 		return (EINVAL);
225 	}
226 
227 	names = kmem_alloc(hdr.xh_length, KM_SLEEP);
228 
229 	if ((rc = smb_sorecv(session->sock, names, hdr.xh_length)) != 0) {
230 		kmem_free(names, hdr.xh_length);
231 		DTRACE_PROBE1(receive__session__req__failed,
232 		    struct session *, session);
233 		return (rc);
234 	}
235 
236 	DTRACE_PROBE3(receive__session__req__data, struct session *, session,
237 	    char *, names, uint32_t, hdr.xh_length);
238 
239 	called_name = &names[0];
240 	calling_name = &names[NETBIOS_ENCODED_NAME_SZ + 2];
241 
242 	rc1 = netbios_name_isvalid(called_name, 0);
243 	rc2 = netbios_name_isvalid(calling_name, client_name);
244 
245 	if (rc1 == 0 || rc2 == 0) {
246 
247 		DTRACE_PROBE3(receive__invalid__session__req,
248 		    struct session *, session, char *, names,
249 		    uint32_t, hdr.xh_length);
250 
251 		kmem_free(names, hdr.xh_length);
252 		MBC_INIT(&mbc, MAX_DATAGRAM_LENGTH);
253 		(void) smb_mbc_encodef(&mbc, "b",
254 		    DATAGRAM_INVALID_SOURCE_NAME_FORMAT);
255 		(void) smb_session_send(session, NEGATIVE_SESSION_RESPONSE,
256 		    &mbc);
257 		return (EINVAL);
258 	}
259 
260 	DTRACE_PROBE3(receive__session__req__calling__decoded,
261 	    struct session *, session,
262 	    char *, calling_name, char *, client_name);
263 
264 	/*
265 	 * The client NetBIOS name is in oem codepage format.
266 	 * We need to convert it to unicode and store it in
267 	 * multi-byte format.  We also need to strip off any
268 	 * spaces added as part of the NetBIOS name encoding.
269 	 */
270 	wbuf = kmem_alloc((SMB_PI_MAX_HOST * sizeof (smb_wchar_t)), KM_SLEEP);
271 	(void) oemtoucs(wbuf, client_name, SMB_PI_MAX_HOST, OEM_CPG_850);
272 	(void) smb_wcstombs(session->workstation, wbuf, SMB_PI_MAX_HOST);
273 	kmem_free(wbuf, (SMB_PI_MAX_HOST * sizeof (smb_wchar_t)));
274 
275 	if ((p = strchr(session->workstation, ' ')) != 0)
276 		*p = '\0';
277 
278 	kmem_free(names, hdr.xh_length);
279 	return (smb_session_send(session, POSITIVE_SESSION_RESPONSE, NULL));
280 }
281 
282 /*
283  * Read 4-byte header from the session socket and build an in-memory
284  * session transport header.  See smb_xprt_t definition for header
285  * format information.
286  *
287  * Direct hosted NetBIOS-less SMB (SMB-over-TCP) uses port 445.  The
288  * first byte of the four-byte header must be 0 and the next three
289  * bytes contain the length of the remaining data.
290  */
291 int
292 smb_session_xprt_gethdr(smb_session_t *session, smb_xprt_t *ret_hdr)
293 {
294 	int		rc;
295 	unsigned char	buf[NETBIOS_HDR_SZ];
296 
297 	if ((rc = smb_sorecv(session->sock, buf, NETBIOS_HDR_SZ)) != 0)
298 		return (rc);
299 
300 	switch (session->s_local_port) {
301 	case IPPORT_NETBIOS_SSN:
302 		ret_hdr->xh_type = buf[0];
303 		ret_hdr->xh_length = (((uint32_t)buf[1] & 1) << 16) |
304 		    ((uint32_t)buf[2] << 8) |
305 		    ((uint32_t)buf[3]);
306 		break;
307 
308 	case IPPORT_SMB:
309 		ret_hdr->xh_type = buf[0];
310 
311 		if (ret_hdr->xh_type != 0) {
312 			cmn_err(CE_WARN, "invalid NBT type (%u) from %s",
313 			    ret_hdr->xh_type, session->ip_addr_str);
314 			return (EPROTO);
315 		}
316 
317 		ret_hdr->xh_length = ((uint32_t)buf[1] << 16) |
318 		    ((uint32_t)buf[2] << 8) |
319 		    ((uint32_t)buf[3]);
320 		break;
321 
322 	default:
323 		cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
324 		return (EPROTO);
325 	}
326 
327 	return (0);
328 }
329 
330 /*
331  * Encode a transport session packet header into a 4-byte buffer.
332  */
333 static int
334 smb_session_xprt_puthdr(smb_session_t *session,
335     uint8_t msg_type, uint32_t msg_length,
336     uint8_t *buf, size_t buflen)
337 {
338 	if (buf == NULL || buflen < NETBIOS_HDR_SZ) {
339 		return (-1);
340 	}
341 
342 	switch (session->s_local_port) {
343 	case IPPORT_NETBIOS_SSN:
344 		/* Per RFC 1001, 1002: msg. len < 128KB */
345 		if (msg_length >= (1 << 17))
346 			return (-1);
347 		buf[0] = msg_type;
348 		buf[1] = ((msg_length >> 16) & 1);
349 		buf[2] = (msg_length >> 8) & 0xff;
350 		buf[3] = msg_length & 0xff;
351 		break;
352 
353 	case IPPORT_SMB:
354 		/*
355 		 * SMB over TCP is like NetBIOS but the one byte
356 		 * message type is always zero, and the length
357 		 * part is three bytes.  It could actually use
358 		 * longer messages, but this is conservative.
359 		 */
360 		if (msg_length >= (1 << 24))
361 			return (-1);
362 		buf[0] = msg_type;
363 		buf[1] = (msg_length >> 16) & 0xff;
364 		buf[2] = (msg_length >> 8) & 0xff;
365 		buf[3] = msg_length & 0xff;
366 		break;
367 
368 	default:
369 		cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
370 		return (-1);
371 	}
372 
373 	return (0);
374 }
375 
376 static int
377 smb_request_recv(smb_request_t *sr, uint32_t len)
378 {
379 	mbuf_t *mhead = NULL;
380 	int rc;
381 
382 	rc = smb_net_recv_mbufs(sr->session, &mhead, len);
383 	if (rc != 0)
384 		return (rc);
385 
386 	/*
387 	 * Setup command mbuf chain received.
388 	 */
389 	MBC_ATTACH_MBUF(&sr->command, mhead);
390 	sr->command.max_bytes = len;
391 
392 	return (0);
393 }
394 
395 /*
396  * smb_request_cancel
397  *
398  * Handle a cancel for a request properly depending on the current request
399  * state.
400  */
401 void
402 smb_request_cancel(smb_request_t *sr)
403 {
404 	void (*cancel_method)(smb_request_t *) = NULL;
405 
406 	mutex_enter(&sr->sr_mutex);
407 	switch (sr->sr_state) {
408 
409 	case SMB_REQ_STATE_INITIALIZING:
410 	case SMB_REQ_STATE_SUBMITTED:
411 	case SMB_REQ_STATE_ACTIVE:
412 	case SMB_REQ_STATE_CLEANED_UP:
413 		sr->sr_state = SMB_REQ_STATE_CANCELLED;
414 		break;
415 
416 	case SMB_REQ_STATE_WAITING_AUTH:
417 	case SMB_REQ_STATE_WAITING_FCN1:
418 	case SMB_REQ_STATE_WAITING_LOCK:
419 	case SMB_REQ_STATE_WAITING_PIPE:
420 	case SMB_REQ_STATE_WAITING_OLBRK:
421 		/*
422 		 * These are states that have a cancel_method.
423 		 * Make the state change now, to ensure that
424 		 * we call cancel_method exactly once.  Do the
425 		 * method call below, after we drop sr_mutex.
426 		 * When the cancelled request thread resumes,
427 		 * it should re-take sr_mutex and set sr_state
428 		 * to CANCELLED, then return STATUS_CANCELLED.
429 		 */
430 		sr->sr_state = SMB_REQ_STATE_CANCEL_PENDING;
431 		cancel_method = sr->cancel_method;
432 		VERIFY(cancel_method != NULL);
433 		break;
434 
435 	case SMB_REQ_STATE_WAITING_FCN2:
436 	case SMB_REQ_STATE_COMPLETED:
437 	case SMB_REQ_STATE_CANCEL_PENDING:
438 	case SMB_REQ_STATE_CANCELLED:
439 		/*
440 		 * No action required for these states since the request
441 		 * is completing.
442 		 */
443 		break;
444 
445 	case SMB_REQ_STATE_FREE:
446 	default:
447 		SMB_PANIC();
448 	}
449 	mutex_exit(&sr->sr_mutex);
450 
451 	if (cancel_method != NULL) {
452 		cancel_method(sr);
453 	}
454 }
455 
456 /*
457  * smb_session_receiver
458  *
459  * Receives request from the network and dispatches them to a worker.
460  *
461  * When we receive a disconnect here, it _could_ be due to the server
462  * having initiated disconnect, in which case the session state will be
463  * SMB_SESSION_STATE_TERMINATED and we want to keep that state so later
464  * tear-down logic will know which side initiated.
465  */
466 void
467 smb_session_receiver(smb_session_t *session)
468 {
469 	int	rc = 0;
470 	timeout_id_t tmo = NULL;
471 
472 	SMB_SESSION_VALID(session);
473 
474 	session->s_thread = curthread;
475 
476 	if (session->s_local_port == IPPORT_NETBIOS_SSN) {
477 		rc = smb_netbios_session_request(session);
478 		if (rc != 0) {
479 			smb_rwx_rwenter(&session->s_lock, RW_WRITER);
480 			if (session->s_state != SMB_SESSION_STATE_TERMINATED)
481 				session->s_state =
482 				    SMB_SESSION_STATE_DISCONNECTED;
483 			smb_rwx_rwexit(&session->s_lock);
484 			return;
485 		}
486 	}
487 
488 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
489 	session->s_state = SMB_SESSION_STATE_ESTABLISHED;
490 	session->s_auth_tmo = timeout((tmo_func_t)smb_session_disconnect,
491 	    session, SEC_TO_TICK(smb_session_auth_tmo));
492 	smb_rwx_rwexit(&session->s_lock);
493 
494 	(void) smb_session_reader(session);
495 
496 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
497 	if (session->s_state != SMB_SESSION_STATE_TERMINATED)
498 		session->s_state = SMB_SESSION_STATE_DISCONNECTED;
499 	tmo = session->s_auth_tmo;
500 	session->s_auth_tmo = NULL;
501 	smb_rwx_rwexit(&session->s_lock);
502 
503 	/* Timeout callback takes s_lock. See untimeout(9f) */
504 	if (tmo != NULL)
505 		(void) untimeout(tmo);
506 
507 	smb_soshutdown(session->sock);
508 
509 	DTRACE_PROBE2(session__drop, struct session *, session, int, rc);
510 
511 	smb_session_cancel(session);
512 	/*
513 	 * At this point everything related to the session should have been
514 	 * cleaned up and we expect that nothing will attempt to use the
515 	 * socket.
516 	 */
517 }
518 
519 /*
520  * smb_session_disconnect
521  *
522  * Server-initiated disconnect (i.e. server shutdown)
523  */
524 void
525 smb_session_disconnect(smb_session_t *session)
526 {
527 	SMB_SESSION_VALID(session);
528 
529 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
530 	switch (session->s_state) {
531 	case SMB_SESSION_STATE_INITIALIZED:
532 	case SMB_SESSION_STATE_CONNECTED:
533 	case SMB_SESSION_STATE_ESTABLISHED:
534 	case SMB_SESSION_STATE_NEGOTIATED:
535 		smb_soshutdown(session->sock);
536 		session->s_state = SMB_SESSION_STATE_TERMINATED;
537 		break;
538 	case SMB_SESSION_STATE_DISCONNECTED:
539 	case SMB_SESSION_STATE_TERMINATED:
540 		break;
541 	}
542 	smb_rwx_rwexit(&session->s_lock);
543 }
544 
545 /*
546  * Read and process SMB requests.
547  *
548  * Returns:
549  *	0	Success
550  *	1	Unable to read transport header
551  *	2	Invalid transport header type
552  *	3	Invalid SMB length (too small)
553  *	4	Unable to read SMB header
554  *	5	Invalid SMB header (bad magic number)
555  *	6	Unable to read SMB data
556  */
557 static int
558 smb_session_reader(smb_session_t *session)
559 {
560 	smb_server_t	*sv;
561 	smb_request_t	*sr = NULL;
562 	smb_xprt_t	hdr;
563 	int		rc;
564 
565 	sv = session->s_server;
566 
567 	for (;;) {
568 
569 		rc = smb_session_xprt_gethdr(session, &hdr);
570 		if (rc)
571 			return (rc);
572 
573 		DTRACE_PROBE2(session__receive__xprthdr, session_t *, session,
574 		    smb_xprt_t *, &hdr);
575 
576 		if (hdr.xh_type != SESSION_MESSAGE) {
577 			/*
578 			 * Anything other than SESSION_MESSAGE or
579 			 * SESSION_KEEP_ALIVE is an error.  A SESSION_REQUEST
580 			 * may indicate a new session request but we need to
581 			 * close this session and we can treat it as an error
582 			 * here.
583 			 */
584 			if (hdr.xh_type == SESSION_KEEP_ALIVE) {
585 				session->keep_alive = smb_keep_alive;
586 				continue;
587 			}
588 			return (EPROTO);
589 		}
590 
591 		if (hdr.xh_length == 0) {
592 			/* zero length is another form of keep alive */
593 			session->keep_alive = smb_keep_alive;
594 			continue;
595 		}
596 
597 		if (hdr.xh_length < SMB_HEADER_LEN)
598 			return (EPROTO);
599 		if (hdr.xh_length > session->cmd_max_bytes)
600 			return (EPROTO);
601 
602 		session->keep_alive = smb_keep_alive;
603 
604 		/*
605 		 * Allocate a request context, read the whole message.
606 		 * If the request alloc fails, we've disconnected
607 		 * and won't be able to send the reply anyway, so bail now.
608 		 */
609 		if ((sr = smb_request_alloc(session, hdr.xh_length)) == NULL)
610 			break;
611 		if ((rc = smb_request_recv(sr, hdr.xh_length)) != 0) {
612 			smb_request_free(sr);
613 			break;
614 		}
615 
616 		/* accounting: received bytes */
617 		smb_server_add_rxb(sv,
618 		    (int64_t)(hdr.xh_length + NETBIOS_HDR_SZ));
619 
620 		DTRACE_PROBE1(session__receive__smb, smb_request_t *, sr);
621 
622 		rc = session->newrq_func(sr);
623 		sr = NULL;	/* enqueued or freed */
624 		if (rc != 0)
625 			break;
626 
627 		/* See notes where this is defined (above). */
628 		if (smb_reader_delay) {
629 			delay(MSEC_TO_TICK(smb_reader_delay));
630 		}
631 	}
632 	return (rc);
633 }
634 
635 /*
636  * This is the initial handler for new smb requests, called from
637  * from smb_session_reader when we have not yet seen any requests.
638  * The first SMB request must be "negotiate", which determines
639  * which protocol and dialect we'll be using.  That's the ONLY
640  * request type handled here, because with all later requests,
641  * we know the protocol and handle those with either the SMB1 or
642  * SMB2 handlers:  smb1sr_post() or smb2sr_post().
643  * Those do NOT allow SMB negotiate, because that's only allowed
644  * as the first request on new session.
645  *
646  * This and other "post a request" handlers must either enqueue
647  * the new request for the session taskq, or smb_request_free it
648  * (in case we've decided to drop this connection).  In this
649  * (special) new request handler, we always free the request.
650  *
651  * Return value is 0 for success, and anything else will
652  * terminate the reader thread (drop the connection).
653  */
654 static int
655 smbsr_newrq_initial(smb_request_t *sr)
656 {
657 	uint32_t magic;
658 	int rc;
659 
660 	mutex_enter(&sr->sr_mutex);
661 	sr->sr_state = SMB_REQ_STATE_ACTIVE;
662 	mutex_exit(&sr->sr_mutex);
663 
664 	if ((rc = smb_mbc_peek(&sr->command, 0, "l", &magic)) != 0)
665 		goto done;
666 
667 	switch (magic) {
668 	case SMB_PROTOCOL_MAGIC:
669 		rc = smb1_newrq_negotiate(sr);
670 		break;
671 	case SMB2_PROTOCOL_MAGIC:
672 		rc = smb2_newrq_negotiate(sr);
673 		break;
674 	default:
675 		rc = EPROTO;
676 	}
677 
678 done:
679 	mutex_enter(&sr->sr_mutex);
680 	sr->sr_state = SMB_REQ_STATE_COMPLETED;
681 	mutex_exit(&sr->sr_mutex);
682 
683 	smb_request_free(sr);
684 	return (rc);
685 }
686 
687 /*
688  * Port will be IPPORT_NETBIOS_SSN or IPPORT_SMB.
689  */
690 smb_session_t *
691 smb_session_create(ksocket_t new_so, uint16_t port, smb_server_t *sv,
692     int family)
693 {
694 	struct sockaddr_in	sin;
695 	socklen_t		slen;
696 	struct sockaddr_in6	sin6;
697 	smb_session_t		*session;
698 	int64_t			now;
699 	uint16_t		rport;
700 
701 	session = kmem_cache_alloc(smb_cache_session, KM_SLEEP);
702 	bzero(session, sizeof (smb_session_t));
703 
704 	if (smb_idpool_constructor(&session->s_uid_pool)) {
705 		kmem_cache_free(smb_cache_session, session);
706 		return (NULL);
707 	}
708 	if (smb_idpool_constructor(&session->s_tid_pool)) {
709 		smb_idpool_destructor(&session->s_uid_pool);
710 		kmem_cache_free(smb_cache_session, session);
711 		return (NULL);
712 	}
713 
714 	now = ddi_get_lbolt64();
715 
716 	session->s_server = sv;
717 	session->s_kid = SMB_NEW_KID();
718 	session->s_state = SMB_SESSION_STATE_INITIALIZED;
719 	session->native_os = NATIVE_OS_UNKNOWN;
720 	session->opentime = now;
721 	session->keep_alive = smb_keep_alive;
722 	session->activity_timestamp = now;
723 	smb_session_genkey(session);
724 
725 	mutex_init(&session->s_credits_mutex, NULL, MUTEX_DEFAULT, NULL);
726 
727 	smb_slist_constructor(&session->s_req_list, sizeof (smb_request_t),
728 	    offsetof(smb_request_t, sr_session_lnd));
729 
730 	smb_llist_constructor(&session->s_user_list, sizeof (smb_user_t),
731 	    offsetof(smb_user_t, u_lnd));
732 
733 	smb_llist_constructor(&session->s_tree_list, sizeof (smb_tree_t),
734 	    offsetof(smb_tree_t, t_lnd));
735 
736 	smb_llist_constructor(&session->s_xa_list, sizeof (smb_xa_t),
737 	    offsetof(smb_xa_t, xa_lnd));
738 
739 	smb_net_txl_constructor(&session->s_txlst);
740 
741 	smb_rwx_init(&session->s_lock);
742 
743 	session->s_srqueue = &sv->sv_srqueue;
744 	smb_server_get_cfg(sv, &session->s_cfg);
745 
746 	if (new_so == NULL) {
747 		/*
748 		 * This call is creating the special "server" session,
749 		 * used for kshare export, oplock breaks, CA import.
750 		 * CA import creates temporary trees on this session
751 		 * and those should never get map/unmap up-calls, so
752 		 * force the map/unmap flags zero on this session.
753 		 * Set a "modern" dialect for CA import too, so
754 		 * pathname parse doesn't do OS/2 stuff, etc.
755 		 */
756 		session->s_cfg.skc_execflags = 0;
757 		session->dialect = session->s_cfg.skc_max_protocol;
758 	} else {
759 		if (family == AF_INET) {
760 			slen = sizeof (sin);
761 			(void) ksocket_getsockname(new_so,
762 			    (struct sockaddr *)&sin, &slen, CRED());
763 			bcopy(&sin.sin_addr,
764 			    &session->local_ipaddr.au_addr.au_ipv4,
765 			    sizeof (in_addr_t));
766 			slen = sizeof (sin);
767 			(void) ksocket_getpeername(new_so,
768 			    (struct sockaddr *)&sin, &slen, CRED());
769 			bcopy(&sin.sin_addr,
770 			    &session->ipaddr.au_addr.au_ipv4,
771 			    sizeof (in_addr_t));
772 			rport = sin.sin_port;
773 		} else {
774 			slen = sizeof (sin6);
775 			(void) ksocket_getsockname(new_so,
776 			    (struct sockaddr *)&sin6, &slen, CRED());
777 			bcopy(&sin6.sin6_addr,
778 			    &session->local_ipaddr.au_addr.au_ipv6,
779 			    sizeof (in6_addr_t));
780 			slen = sizeof (sin6);
781 			(void) ksocket_getpeername(new_so,
782 			    (struct sockaddr *)&sin6, &slen, CRED());
783 			bcopy(&sin6.sin6_addr,
784 			    &session->ipaddr.au_addr.au_ipv6,
785 			    sizeof (in6_addr_t));
786 			rport = sin6.sin6_port;
787 		}
788 		session->ipaddr.a_family = family;
789 		session->local_ipaddr.a_family = family;
790 		session->s_local_port = port;
791 		session->s_remote_port = ntohs(rport);
792 		session->sock = new_so;
793 		(void) smb_inet_ntop(&session->ipaddr,
794 		    session->ip_addr_str, INET6_ADDRSTRLEN);
795 		if (port == IPPORT_NETBIOS_SSN)
796 			smb_server_inc_nbt_sess(sv);
797 		else
798 			smb_server_inc_tcp_sess(sv);
799 	}
800 
801 	/*
802 	 * The initial new request handler is special,
803 	 * and only accepts negotiation requests.
804 	 */
805 	session->newrq_func = smbsr_newrq_initial;
806 
807 	/* These may increase in SMB2 negotiate. */
808 	session->cmd_max_bytes = SMB_REQ_MAX_SIZE;
809 	session->reply_max_bytes = SMB_REQ_MAX_SIZE;
810 
811 	session->s_magic = SMB_SESSION_MAGIC;
812 	return (session);
813 }
814 
815 void
816 smb_session_delete(smb_session_t *session)
817 {
818 
819 	ASSERT(session->s_magic == SMB_SESSION_MAGIC);
820 
821 	if (session->enc_mech != NULL)
822 		smb3_encrypt_ssn_fini(session);
823 
824 	if (session->sign_fini != NULL)
825 		session->sign_fini(session);
826 
827 	if (session->signing.mackey != NULL) {
828 		kmem_free(session->signing.mackey,
829 		    session->signing.mackey_len);
830 	}
831 
832 	if (session->preauth_mech != NULL)
833 		smb31_preauth_fini(session);
834 
835 	session->s_magic = 0;
836 
837 	smb_rwx_destroy(&session->s_lock);
838 	smb_net_txl_destructor(&session->s_txlst);
839 
840 	mutex_destroy(&session->s_credits_mutex);
841 
842 	smb_slist_destructor(&session->s_req_list);
843 	smb_llist_destructor(&session->s_tree_list);
844 	smb_llist_destructor(&session->s_user_list);
845 	smb_llist_destructor(&session->s_xa_list);
846 
847 	ASSERT(session->s_tree_cnt == 0);
848 	ASSERT(session->s_file_cnt == 0);
849 	ASSERT(session->s_dir_cnt == 0);
850 
851 	smb_idpool_destructor(&session->s_tid_pool);
852 	smb_idpool_destructor(&session->s_uid_pool);
853 	if (session->sock != NULL) {
854 		if (session->s_local_port == IPPORT_NETBIOS_SSN)
855 			smb_server_dec_nbt_sess(session->s_server);
856 		else
857 			smb_server_dec_tcp_sess(session->s_server);
858 		smb_sodestroy(session->sock);
859 	}
860 	kmem_cache_free(smb_cache_session, session);
861 }
862 
863 static void
864 smb_session_cancel(smb_session_t *session)
865 {
866 	smb_xa_t	*xa, *nextxa;
867 
868 	/* All the request currently being treated must be canceled. */
869 	smb_session_cancel_requests(session, NULL, NULL);
870 
871 	/*
872 	 * We wait for the completion of all the requests associated with
873 	 * this session.
874 	 */
875 	smb_slist_wait_for_empty(&session->s_req_list);
876 
877 	/*
878 	 * Cleanup transact state objects
879 	 */
880 	xa = smb_llist_head(&session->s_xa_list);
881 	while (xa) {
882 		nextxa = smb_llist_next(&session->s_xa_list, xa);
883 		smb_xa_close(xa);
884 		xa = nextxa;
885 	}
886 
887 	/*
888 	 * At this point the reference count of the files and directories
889 	 * should be zero. It should be possible to destroy them without
890 	 * any problem, which should trigger the destruction of other objects.
891 	 */
892 	smb_session_logoff(session);
893 }
894 
895 /*
896  * Cancel requests.  If a non-null tree is specified, only requests specific
897  * to that tree will be cancelled.  If a non-null sr is specified, that sr
898  * will be not be cancelled - this would typically be the caller's sr.
899  */
900 void
901 smb_session_cancel_requests(
902     smb_session_t	*session,
903     smb_tree_t		*tree,
904     smb_request_t	*exclude_sr)
905 {
906 	smb_request_t	*sr;
907 
908 	smb_slist_enter(&session->s_req_list);
909 	sr = smb_slist_head(&session->s_req_list);
910 
911 	while (sr) {
912 		ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
913 		if ((sr != exclude_sr) &&
914 		    (tree == NULL || sr->tid_tree == tree))
915 			smb_request_cancel(sr);
916 
917 		sr = smb_slist_next(&session->s_req_list, sr);
918 	}
919 
920 	smb_slist_exit(&session->s_req_list);
921 }
922 
923 /*
924  * Find a user on the specified session by SMB UID.
925  */
926 smb_user_t *
927 smb_session_lookup_uid(smb_session_t *session, uint16_t uid)
928 {
929 	return (smb_session_lookup_uid_st(session, 0, uid,
930 	    SMB_USER_STATE_LOGGED_ON));
931 }
932 
933 /*
934  * Find a user on the specified session by SMB2 SSNID.
935  */
936 smb_user_t *
937 smb_session_lookup_ssnid(smb_session_t *session, uint64_t ssnid)
938 {
939 	return (smb_session_lookup_uid_st(session, ssnid, 0,
940 	    SMB_USER_STATE_LOGGED_ON));
941 }
942 
943 smb_user_t *
944 smb_session_lookup_uid_st(smb_session_t *session, uint64_t ssnid,
945     uint16_t uid, smb_user_state_t st)
946 {
947 	smb_user_t	*user;
948 	smb_llist_t	*user_list;
949 
950 	SMB_SESSION_VALID(session);
951 
952 	user_list = &session->s_user_list;
953 	smb_llist_enter(user_list, RW_READER);
954 
955 	for (user = smb_llist_head(user_list);
956 	    user != NULL;
957 	    user = smb_llist_next(user_list, user)) {
958 
959 		SMB_USER_VALID(user);
960 		ASSERT(user->u_session == session);
961 
962 		if (user->u_ssnid != ssnid && user->u_uid != uid)
963 			continue;
964 
965 		mutex_enter(&user->u_mutex);
966 		if (user->u_state == st) {
967 			// smb_user_hold_internal(user);
968 			user->u_refcnt++;
969 			mutex_exit(&user->u_mutex);
970 			break;
971 		}
972 		mutex_exit(&user->u_mutex);
973 	}
974 
975 	smb_llist_exit(user_list);
976 	return (user);
977 }
978 
979 /*
980  * Find a tree by tree-id.
981  */
982 smb_tree_t *
983 smb_session_lookup_tree(
984     smb_session_t	*session,
985     uint16_t		tid)
986 {
987 	smb_tree_t	*tree;
988 
989 	SMB_SESSION_VALID(session);
990 
991 	smb_llist_enter(&session->s_tree_list, RW_READER);
992 	tree = smb_llist_head(&session->s_tree_list);
993 
994 	while (tree) {
995 		ASSERT3U(tree->t_magic, ==, SMB_TREE_MAGIC);
996 		ASSERT(tree->t_session == session);
997 
998 		if (tree->t_tid == tid) {
999 			if (smb_tree_hold(tree)) {
1000 				smb_llist_exit(&session->s_tree_list);
1001 				return (tree);
1002 			} else {
1003 				smb_llist_exit(&session->s_tree_list);
1004 				return (NULL);
1005 			}
1006 		}
1007 
1008 		tree = smb_llist_next(&session->s_tree_list, tree);
1009 	}
1010 
1011 	smb_llist_exit(&session->s_tree_list);
1012 	return (NULL);
1013 }
1014 
1015 /*
1016  * Disconnect all trees that match the specified client process-id.
1017  * Used by the SMB1 "process exit" request.
1018  */
1019 void
1020 smb_session_close_pid(
1021     smb_session_t	*session,
1022     uint32_t		pid)
1023 {
1024 	smb_llist_t	*tree_list = &session->s_tree_list;
1025 	smb_tree_t	*tree;
1026 
1027 	smb_llist_enter(tree_list, RW_READER);
1028 
1029 	tree = smb_llist_head(tree_list);
1030 	while (tree) {
1031 		if (smb_tree_hold(tree)) {
1032 			smb_tree_close_pid(tree, pid);
1033 			smb_tree_release(tree);
1034 		}
1035 		tree = smb_llist_next(tree_list, tree);
1036 	}
1037 
1038 	smb_llist_exit(tree_list);
1039 }
1040 
1041 static void
1042 smb_session_tree_dtor(void *arg)
1043 {
1044 	smb_tree_t	*tree = arg;
1045 
1046 	smb_tree_disconnect(tree, B_TRUE);
1047 	/* release the ref acquired during the traversal loop */
1048 	smb_tree_release(tree);
1049 }
1050 
1051 
1052 /*
1053  * Disconnect all trees that this user has connected.
1054  */
1055 void
1056 smb_session_disconnect_owned_trees(
1057     smb_session_t	*session,
1058     smb_user_t		*owner)
1059 {
1060 	smb_tree_t	*tree;
1061 	smb_llist_t	*tree_list = &session->s_tree_list;
1062 
1063 	SMB_SESSION_VALID(session);
1064 	SMB_USER_VALID(owner);
1065 
1066 	smb_llist_enter(tree_list, RW_READER);
1067 
1068 	tree = smb_llist_head(tree_list);
1069 	while (tree) {
1070 		if ((tree->t_owner == owner) &&
1071 		    smb_tree_hold(tree)) {
1072 			/*
1073 			 * smb_tree_hold() succeeded, hence we are in state
1074 			 * SMB_TREE_STATE_CONNECTED; schedule this tree
1075 			 * for disconnect after smb_llist_exit because
1076 			 * the "unmap exec" up-call can block, and we'd
1077 			 * rather not block with the tree list locked.
1078 			 */
1079 			smb_llist_post(tree_list, tree, smb_session_tree_dtor);
1080 		}
1081 		tree = smb_llist_next(tree_list, tree);
1082 	}
1083 
1084 	/* drop the lock and flush the dtor queue */
1085 	smb_llist_exit(tree_list);
1086 }
1087 
1088 /*
1089  * Disconnect all trees that this user has connected.
1090  */
1091 static void
1092 smb_session_disconnect_trees(
1093     smb_session_t	*session)
1094 {
1095 	smb_llist_t	*tree_list = &session->s_tree_list;
1096 	smb_tree_t	*tree;
1097 
1098 	smb_llist_enter(tree_list, RW_READER);
1099 
1100 	tree = smb_llist_head(tree_list);
1101 	while (tree) {
1102 		if (smb_tree_hold(tree)) {
1103 			smb_llist_post(tree_list, tree,
1104 			    smb_session_tree_dtor);
1105 		}
1106 		tree = smb_llist_next(tree_list, tree);
1107 	}
1108 
1109 	/* drop the lock and flush the dtor queue */
1110 	smb_llist_exit(tree_list);
1111 }
1112 
1113 /*
1114  * Variant of smb_session_tree_dtor that also
1115  * cancels requests using this tree.
1116  */
1117 static void
1118 smb_session_tree_kill(void *arg)
1119 {
1120 	smb_tree_t	*tree = arg;
1121 
1122 	SMB_TREE_VALID(tree);
1123 
1124 	smb_tree_disconnect(tree, B_TRUE);
1125 	smb_session_cancel_requests(tree->t_session, tree, NULL);
1126 
1127 	/* release the ref acquired during the traversal loop */
1128 	smb_tree_release(tree);
1129 }
1130 
1131 /*
1132  * Disconnect all trees that match the specified share name,
1133  * and kill requests using those trees.
1134  */
1135 void
1136 smb_session_disconnect_share(
1137     smb_session_t	*session,
1138     const char		*sharename)
1139 {
1140 	smb_llist_t	*ll;
1141 	smb_tree_t	*tree;
1142 
1143 	SMB_SESSION_VALID(session);
1144 
1145 	ll = &session->s_tree_list;
1146 	smb_llist_enter(ll, RW_READER);
1147 
1148 	for (tree = smb_llist_head(ll);
1149 	    tree != NULL;
1150 	    tree = smb_llist_next(ll, tree)) {
1151 
1152 		SMB_TREE_VALID(tree);
1153 		ASSERT(tree->t_session == session);
1154 
1155 		if (smb_strcasecmp(tree->t_sharename, sharename, 0) != 0)
1156 			continue;
1157 
1158 		if (smb_tree_hold(tree)) {
1159 			smb_llist_post(ll, tree,
1160 			    smb_session_tree_kill);
1161 		}
1162 	}
1163 
1164 	smb_llist_exit(ll);
1165 }
1166 
1167 int smb_session_logoff_maxwait = 5;	/* seconds */
1168 
1169 /*
1170  * Logoff all users associated with the specified session.
1171  *
1172  * This is called for both server-initiated disconnect
1173  * (SMB_SESSION_STATE_TERMINATED) and client-initiated
1174  * disconnect (SMB_SESSION_STATE_DISCONNECTED).
1175  * If client-initiated, save durable handles.
1176  * All requests on this session have finished.
1177  */
1178 void
1179 smb_session_logoff(smb_session_t *session)
1180 {
1181 	smb_llist_t	*ulist;
1182 	smb_user_t	*user;
1183 	int		count;
1184 	int		timeleft = SEC_TO_TICK(smb_session_logoff_maxwait);
1185 
1186 	SMB_SESSION_VALID(session);
1187 
1188 top:
1189 	ulist = &session->s_user_list;
1190 	smb_llist_enter(ulist, RW_READER);
1191 
1192 	user = smb_llist_head(ulist);
1193 	while (user) {
1194 		SMB_USER_VALID(user);
1195 		ASSERT(user->u_session == session);
1196 
1197 		mutex_enter(&user->u_mutex);
1198 		switch (user->u_state) {
1199 		case SMB_USER_STATE_LOGGING_ON:
1200 		case SMB_USER_STATE_LOGGED_ON:
1201 			// smb_user_hold_internal(user);
1202 			user->u_refcnt++;
1203 			mutex_exit(&user->u_mutex);
1204 			smb_user_logoff(user);
1205 			smb_user_release(user);
1206 			break;
1207 
1208 		case SMB_USER_STATE_LOGGED_OFF:
1209 		case SMB_USER_STATE_LOGGING_OFF:
1210 			mutex_exit(&user->u_mutex);
1211 			break;
1212 
1213 		default:
1214 			mutex_exit(&user->u_mutex);
1215 			ASSERT(0);
1216 			break;
1217 		}
1218 
1219 		user = smb_llist_next(ulist, user);
1220 	}
1221 
1222 	count = smb_llist_get_count(ulist);
1223 
1224 	/* drop the lock and flush the dtor queue */
1225 	smb_llist_exit(ulist);
1226 
1227 	/*
1228 	 * Wait (briefly) for user objects to go away.
1229 	 * They might linger, eg. if some ofile ref has been
1230 	 * forgotten, which holds, a tree and a user.
1231 	 * See smb_session_destroy.
1232 	 */
1233 	if (count == 0) {
1234 		/* User list is empty. */
1235 		smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1236 		session->s_state = SMB_SESSION_STATE_SHUTDOWN;
1237 		smb_rwx_rwexit(&session->s_lock);
1238 	} else {
1239 		smb_rwx_rwenter(&session->s_lock, RW_READER);
1240 		if (session->s_state != SMB_SESSION_STATE_SHUTDOWN &&
1241 		    timeleft > 0) {
1242 			/* May be signaled in smb_user_delete */
1243 			(void) smb_rwx_cvwait(&session->s_lock,
1244 			    MSEC_TO_TICK(200));
1245 			timeleft -= 200;
1246 			smb_rwx_rwexit(&session->s_lock);
1247 			goto top;
1248 		}
1249 		smb_rwx_rwexit(&session->s_lock);
1250 
1251 		cmn_err(CE_NOTE, "!session logoff waited %d seconds"
1252 		    " with %d logons remaining",
1253 		    smb_session_logoff_maxwait, count);
1254 		DTRACE_PROBE1(max__wait, smb_session_t *, session);
1255 	}
1256 
1257 	/*
1258 	 * User list should be empty now, but might not be if we
1259 	 * timed out waiting for smb_user objects to go away.
1260 	 * Checked in smb_server_destroy_session
1261 	 *
1262 	 * User logoff happens first so we'll set preserve_opens
1263 	 * for client-initiated disconnect.  When that's done
1264 	 * there should be no trees left, but check anyway.
1265 	 */
1266 	smb_session_disconnect_trees(session);
1267 }
1268 
1269 /*
1270  * Copy the session workstation/client name to buf.  If the workstation
1271  * is an empty string (which it will be on TCP connections), use the
1272  * client IP address.
1273  */
1274 void
1275 smb_session_getclient(smb_session_t *sn, char *buf, size_t buflen)
1276 {
1277 
1278 	*buf = '\0';
1279 
1280 	if (sn->workstation[0] != '\0') {
1281 		(void) strlcpy(buf, sn->workstation, buflen);
1282 		return;
1283 	}
1284 
1285 	(void) strlcpy(buf, sn->ip_addr_str, buflen);
1286 }
1287 
1288 /*
1289  * Check whether or not the specified client name is the client of this
1290  * session.  The name may be in UNC format (\\CLIENT).
1291  *
1292  * A workstation/client name is setup on NBT connections as part of the
1293  * NetBIOS session request but that isn't available on TCP connections.
1294  * If the session doesn't have a client name we typically return the
1295  * client IP address as the workstation name on MSRPC requests.  So we
1296  * check for the IP address here in addition to the workstation name.
1297  */
1298 boolean_t
1299 smb_session_isclient(smb_session_t *sn, const char *client)
1300 {
1301 
1302 	client += strspn(client, "\\");
1303 
1304 	if (smb_strcasecmp(client, sn->workstation, 0) == 0)
1305 		return (B_TRUE);
1306 
1307 	if (smb_strcasecmp(client, sn->ip_addr_str, 0) == 0)
1308 		return (B_TRUE);
1309 
1310 	return (B_FALSE);
1311 }
1312 
1313 /*
1314  * smb_request_alloc
1315  *
1316  * Allocate an smb_request_t structure from the kmem_cache.  Partially
1317  * initialize the found/new request.
1318  *
1319  * Returns pointer to a request, or NULL if the session state is
1320  * one in which new requests are no longer allowed.
1321  */
1322 smb_request_t *
1323 smb_request_alloc(smb_session_t *session, int req_length)
1324 {
1325 	smb_request_t	*sr;
1326 
1327 	ASSERT(session->s_magic == SMB_SESSION_MAGIC);
1328 	ASSERT(req_length <= session->cmd_max_bytes);
1329 
1330 	sr = kmem_cache_alloc(smb_cache_request, KM_SLEEP);
1331 
1332 	/*
1333 	 * Future:  Use constructor to pre-initialize some fields.  For now
1334 	 * there are so many fields that it is easiest just to zero the
1335 	 * whole thing and start over.
1336 	 */
1337 	bzero(sr, sizeof (smb_request_t));
1338 
1339 	mutex_init(&sr->sr_mutex, NULL, MUTEX_DEFAULT, NULL);
1340 	smb_srm_init(sr);
1341 	sr->session = session;
1342 	sr->sr_server = session->s_server;
1343 	sr->sr_gmtoff = session->s_server->si_gmtoff;
1344 	sr->sr_cfg = &session->s_cfg;
1345 	sr->reply.max_bytes = session->reply_max_bytes;
1346 
1347 	sr->sr_magic = SMB_REQ_MAGIC;
1348 	sr->sr_state = SMB_REQ_STATE_INITIALIZING;
1349 
1350 	/*
1351 	 * Only allow new SMB requests in some states.
1352 	 */
1353 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1354 	switch (session->s_state) {
1355 	case SMB_SESSION_STATE_CONNECTED:
1356 	case SMB_SESSION_STATE_INITIALIZED:
1357 	case SMB_SESSION_STATE_ESTABLISHED:
1358 	case SMB_SESSION_STATE_NEGOTIATED:
1359 		smb_slist_insert_tail(&session->s_req_list, sr);
1360 		break;
1361 
1362 	default:
1363 		ASSERT(0);
1364 		/* FALLTHROUGH */
1365 	case SMB_SESSION_STATE_DISCONNECTED:
1366 	case SMB_SESSION_STATE_SHUTDOWN:
1367 	case SMB_SESSION_STATE_TERMINATED:
1368 		/* Disallow new requests in these states. */
1369 		sr->session = NULL;
1370 		sr->sr_magic = 0;
1371 		mutex_destroy(&sr->sr_mutex);
1372 		kmem_cache_free(smb_cache_request, sr);
1373 		sr = NULL;
1374 		break;
1375 	}
1376 	smb_rwx_rwexit(&session->s_lock);
1377 
1378 	return (sr);
1379 }
1380 
1381 /*
1382  * smb_request_free
1383  *
1384  * release the memories which have been allocated for a smb request.
1385  */
1386 void
1387 smb_request_free(smb_request_t *sr)
1388 {
1389 	ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
1390 	ASSERT(sr->session);
1391 	ASSERT(sr->r_xa == NULL);
1392 
1393 	if (sr->fid_ofile != NULL) {
1394 		smb_ofile_release(sr->fid_ofile);
1395 	}
1396 
1397 	if (sr->tid_tree != NULL)
1398 		smb_tree_release(sr->tid_tree);
1399 
1400 	if (sr->uid_user != NULL)
1401 		smb_user_release(sr->uid_user);
1402 
1403 	if (sr->th_sid_user != NULL)
1404 		smb_user_release(sr->th_sid_user);
1405 
1406 	/*
1407 	 * The above may have left work on the delete queues
1408 	 */
1409 	smb_llist_flush(&sr->session->s_tree_list);
1410 	smb_llist_flush(&sr->session->s_user_list);
1411 
1412 	smb_slist_remove(&sr->session->s_req_list, sr);
1413 
1414 	sr->session = NULL;
1415 
1416 	smb_srm_fini(sr);
1417 
1418 	if (sr->command.chain)
1419 		m_freem(sr->command.chain);
1420 	if (sr->reply.chain)
1421 		m_freem(sr->reply.chain);
1422 	if (sr->raw_data.chain)
1423 		m_freem(sr->raw_data.chain);
1424 
1425 	sr->sr_magic = 0;
1426 	mutex_destroy(&sr->sr_mutex);
1427 	kmem_cache_free(smb_cache_request, sr);
1428 }
1429 
1430 boolean_t
1431 smb_session_oplocks_enable(smb_session_t *session)
1432 {
1433 	SMB_SESSION_VALID(session);
1434 	if (session->s_cfg.skc_oplock_enable == 0)
1435 		return (B_FALSE);
1436 	else
1437 		return (B_TRUE);
1438 }
1439 
1440 boolean_t
1441 smb_session_levelII_oplocks(smb_session_t *session)
1442 {
1443 	SMB_SESSION_VALID(session);
1444 
1445 	/* Older clients only do Level II oplocks if negotiated. */
1446 	if ((session->capabilities & CAP_LEVEL_II_OPLOCKS) != 0)
1447 		return (B_TRUE);
1448 
1449 	return (B_FALSE);
1450 }
1451 
1452 static void
1453 smb_session_genkey(smb_session_t *session)
1454 {
1455 	uint8_t		tmp_key[SMB_CHALLENGE_SZ];
1456 
1457 	(void) random_get_pseudo_bytes(tmp_key, SMB_CHALLENGE_SZ);
1458 	bcopy(tmp_key, &session->challenge_key, SMB_CHALLENGE_SZ);
1459 	session->challenge_len = SMB_CHALLENGE_SZ;
1460 
1461 	(void) random_get_pseudo_bytes(tmp_key, 4);
1462 	session->sesskey = tmp_key[0] | tmp_key[1] << 8 |
1463 	    tmp_key[2] << 16 | tmp_key[3] << 24;
1464 }
1465