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