1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2015-2021 Tintri by DDN, Inc. All rights reserved.
14  * Copyright 2022 RackTop Systems, Inc.
15  */
16 
17 
18 #include <smbsrv/smb2_kproto.h>
19 #include <smbsrv/smb_kstat.h>
20 #include <smbsrv/smb2.h>
21 
22 #define	SMB2_ASYNCID(sr) (sr->smb2_messageid ^ (1ULL << 62))
23 
24 smb_sdrc_t smb2_invalid_cmd(smb_request_t *);
25 static void smb2_tq_work(void *);
26 static void smb2sr_run_postwork(smb_request_t *);
27 static int smb3_decrypt_msg(smb_request_t *);
28 
29 static const smb_disp_entry_t
30 smb2_disp_table[SMB2__NCMDS] = {
31 
32 	/* text-name, pre, func, post, cmd-code, dialect, flags */
33 
34 	{  "smb2_negotiate", NULL,
35 	    smb2_negotiate, NULL, 0, 0,
36 	    SDDF_SUPPRESS_TID | SDDF_SUPPRESS_UID },
37 
38 	{  "smb2_session_setup", NULL,
39 	    smb2_session_setup, NULL, 0, 0,
40 	    SDDF_SUPPRESS_TID | SDDF_SUPPRESS_UID },
41 
42 	{  "smb2_logoff", NULL,
43 	    smb2_logoff, NULL, 0, 0,
44 	    SDDF_SUPPRESS_TID },
45 
46 	{  "smb2_tree_connect", NULL,
47 	    smb2_tree_connect, NULL, 0, 0,
48 	    SDDF_SUPPRESS_TID },
49 
50 	{  "smb2_tree_disconn", NULL,
51 	    smb2_tree_disconn, NULL, 0, 0 },
52 
53 	{  "smb2_create", NULL,
54 	    smb2_create, NULL, 0, 0 },
55 
56 	{  "smb2_close", NULL,
57 	    smb2_close, NULL, 0, 0 },
58 
59 	{  "smb2_flush", NULL,
60 	    smb2_flush, NULL, 0, 0 },
61 
62 	{  "smb2_read", NULL,
63 	    smb2_read, NULL, 0, 0 },
64 
65 	{  "smb2_write", NULL,
66 	    smb2_write, NULL, 0, 0 },
67 
68 	{  "smb2_lock", NULL,
69 	    smb2_lock, NULL, 0, 0 },
70 
71 	{  "smb2_ioctl", NULL,
72 	    smb2_ioctl, NULL, 0, 0 },
73 
74 	{  "smb2_cancel", NULL,
75 	    smb2_cancel, NULL, 0, 0,
76 	    SDDF_SUPPRESS_UID | SDDF_SUPPRESS_TID },
77 
78 	{  "smb2_echo", NULL,
79 	    smb2_echo, NULL, 0, 0,
80 	    SDDF_SUPPRESS_UID | SDDF_SUPPRESS_TID },
81 
82 	{  "smb2_query_dir", NULL,
83 	    smb2_query_dir, NULL, 0, 0 },
84 
85 	{  "smb2_change_notify", NULL,
86 	    smb2_change_notify, NULL, 0, 0 },
87 
88 	{  "smb2_query_info", NULL,
89 	    smb2_query_info, NULL, 0, 0 },
90 
91 	{  "smb2_set_info", NULL,
92 	    smb2_set_info, NULL, 0, 0 },
93 
94 	{  "smb2_oplock_break_ack", NULL,
95 	    smb2_oplock_break_ack, NULL, 0, 0 },
96 
97 	{  "smb2_invalid_cmd", NULL,
98 	    smb2_invalid_cmd, NULL, 0, 0,
99 	    SDDF_SUPPRESS_UID | SDDF_SUPPRESS_TID },
100 };
101 
102 smb_sdrc_t
103 smb2_invalid_cmd(smb_request_t *sr)
104 {
105 #ifdef	DEBUG
106 	cmn_err(CE_NOTE, "clnt %s bad SMB2 cmd code",
107 	    sr->session->ip_addr_str);
108 #endif
109 	sr->smb2_status = NT_STATUS_INVALID_PARAMETER;
110 	return (SDRC_DROP_VC);
111 }
112 
113 /*
114  * This is the SMB2 handler for new smb requests, called from
115  * smb_session_reader after SMB negotiate is done.  For most SMB2
116  * requests, we just enqueue them for the smb_session_worker to
117  * execute via the task queue, so they can block for resources
118  * without stopping the reader thread.  A few protocol messages
119  * are special cases and are handled directly here in the reader
120  * thread so they don't wait for taskq scheduling.
121  *
122  * This function must either enqueue the new request for
123  * execution via the task queue, or execute it directly
124  * and then free it.  If this returns non-zero, the caller
125  * will drop the session.
126  */
127 int
128 smb2sr_newrq(smb_request_t *sr)
129 {
130 	struct mbuf_chain *mbc = &sr->command;
131 	taskqid_t tqid;
132 	uint32_t magic;
133 	int rc, skip;
134 
135 	if (smb_mbc_peek(mbc, 0, "l", &magic) != 0)
136 		goto drop;
137 
138 	/* 0xFD S M B */
139 	if (magic == SMB3_ENCRYPTED_MAGIC) {
140 		if (smb3_decrypt_msg(sr) != 0)
141 			goto drop;
142 		/*
143 		 * Should now be looking at an un-encrypted
144 		 * SMB2 message header.
145 		 */
146 		if (smb_mbc_peek(mbc, 0, "l", &magic) != 0)
147 			goto drop;
148 	}
149 
150 	if (magic != SMB2_PROTOCOL_MAGIC)
151 		goto drop;
152 
153 	/*
154 	 * Walk the SMB2 commands in this compound message and
155 	 * keep track of the range of message IDs it uses.
156 	 */
157 	for (;;) {
158 		if (smb2_decode_header(sr) != 0)
159 			goto drop;
160 
161 		/*
162 		 * Cancel requests are special:  They refer to
163 		 * an earlier message ID (or an async. ID),
164 		 * never a new ID, and are never compounded.
165 		 * This is intentionally not "goto drop"
166 		 * because rc may be zero (success).
167 		 */
168 		if (sr->smb2_cmd_code == SMB2_CANCEL) {
169 			rc = smb2_newrq_cancel(sr);
170 			smb_request_free(sr);
171 			return (rc);
172 		}
173 
174 		/*
175 		 * Keep track of the total credits in this compound
176 		 * and the first (real) message ID (not: 0, -1)
177 		 * While we're looking, verify that all (real) IDs
178 		 * are (first <= ID < (first + msg_credits))
179 		 */
180 		if (sr->smb2_credit_charge == 0)
181 			sr->smb2_credit_charge = 1;
182 		sr->smb2_total_credits += sr->smb2_credit_charge;
183 
184 		if (sr->smb2_messageid != 0 &&
185 		    sr->smb2_messageid != UINT64_MAX) {
186 
187 			if (sr->smb2_first_msgid == 0)
188 				sr->smb2_first_msgid = sr->smb2_messageid;
189 
190 			if (sr->smb2_messageid < sr->smb2_first_msgid ||
191 			    sr->smb2_messageid >= (sr->smb2_first_msgid +
192 			    sr->smb2_total_credits)) {
193 				long long id = (long long) sr->smb2_messageid;
194 				cmn_err(CE_WARN, "clnt %s msg ID 0x%llx "
195 				    "out of sequence in compound",
196 				    sr->session->ip_addr_str, id);
197 			}
198 		}
199 
200 		/* Normal loop exit on next == zero */
201 		if (sr->smb2_next_command == 0)
202 			break;
203 
204 		/* Abundance of caution... */
205 		if (sr->smb2_next_command < SMB2_HDR_SIZE)
206 			goto drop;
207 
208 		/* Advance to the next header. */
209 		skip = sr->smb2_next_command - SMB2_HDR_SIZE;
210 		if (MBC_ROOM_FOR(mbc, skip) == 0)
211 			goto drop;
212 		mbc->chain_offset += skip;
213 	}
214 	/* Rewind back to the top. */
215 	mbc->chain_offset = 0;
216 
217 	/*
218 	 * Submit the request to the task queue, which calls
219 	 * smb2_tq_work when the workload permits.
220 	 */
221 	sr->sr_time_submitted = gethrtime();
222 	sr->sr_state = SMB_REQ_STATE_SUBMITTED;
223 	smb_srqueue_waitq_enter(sr->session->s_srqueue);
224 	tqid = taskq_dispatch(sr->sr_server->sv_worker_pool,
225 	    smb2_tq_work, sr, TQ_SLEEP);
226 	VERIFY(tqid != TASKQID_INVALID);
227 
228 	return (0);
229 
230 drop:
231 	smb_request_free(sr);
232 	return (-1);
233 }
234 
235 static void
236 smb2_tq_work(void *arg)
237 {
238 	smb_request_t	*sr;
239 	smb_srqueue_t	*srq;
240 
241 	sr = (smb_request_t *)arg;
242 	SMB_REQ_VALID(sr);
243 
244 	srq = sr->session->s_srqueue;
245 	smb_srqueue_waitq_to_runq(srq);
246 	sr->sr_worker = curthread;
247 	sr->sr_time_active = gethrtime();
248 
249 	/*
250 	 * Always dispatch to the work function, because cancelled
251 	 * requests need an error reply (NT_STATUS_CANCELLED).
252 	 */
253 	mutex_enter(&sr->sr_mutex);
254 	if (sr->sr_state == SMB_REQ_STATE_SUBMITTED)
255 		sr->sr_state = SMB_REQ_STATE_ACTIVE;
256 	mutex_exit(&sr->sr_mutex);
257 
258 	smb2sr_work(sr);
259 
260 	smb_srqueue_runq_exit(srq);
261 }
262 
263 /*
264  * Wrapper to setup a new mchain for the plaintext request that will
265  * replace the encrypted one.  Returns non-zero to drop the connection.
266  * Error return values here are just for visibility in dtrace.
267  */
268 static int
269 smb3_decrypt_msg(smb_request_t *sr)
270 {
271 	struct mbuf_chain clear_mbc = {0};
272 	struct mbuf_chain tmp_mbc;
273 	mbuf_t *m;
274 	int clearsize;
275 	int rc;
276 
277 	if (sr->session->dialect < SMB_VERS_3_0) {
278 		/* Encrypted message in SMB 2.x */
279 		return (-1);
280 	}
281 	if ((sr->session->srv_cap & SMB2_CAP_ENCRYPTION) == 0) {
282 		/* Should have srv_cap SMB2_CAP_ENCRYPTION flag set! */
283 		return (-2);
284 	}
285 
286 	sr->encrypted = B_TRUE;
287 	if (sr->command.max_bytes <
288 	    (SMB3_TFORM_HDR_SIZE + SMB2_HDR_SIZE)) {
289 		/* Short transform header */
290 		return (-3);
291 	}
292 	clearsize = sr->command.max_bytes - SMB3_TFORM_HDR_SIZE;
293 
294 	clear_mbc.max_bytes = clearsize;
295 	m = smb_mbuf_alloc_chain(clearsize);
296 	MBC_ATTACH_MBUF(&clear_mbc, m);
297 
298 	rc = smb3_decrypt_sr(sr, &sr->command, &clear_mbc);
299 	if (rc != 0) {
300 		MBC_FLUSH(&clear_mbc);
301 		return (rc);
302 	}
303 
304 	/* Swap clear_mbc in place of command */
305 	tmp_mbc = sr->command;
306 	sr->command = clear_mbc;
307 	MBC_FLUSH(&tmp_mbc);	// free old sr->command
308 
309 	return (0);
310 }
311 
312 /*
313  * SMB2 credits determine how many simultaneous commands the
314  * client may issue, and bounds the range of message IDs those
315  * commands may use.  With multi-credit support, commands may
316  * use ranges of message IDs, where the credits used by each
317  * command are proportional to their data transfer size.
318  *
319  * Every command may request an increase or decrease of
320  * the currently granted credits, based on the difference
321  * between the credit request and the credit charge.
322  * [MS-SMB2] 3.3.1.2 Algorithm for the Granting of Credits
323  *
324  * Most commands have credit_request=1, credit_charge=1,
325  * which keeps the credit grant unchanged.
326  *
327  * All we're really doing here (for now) is reducing the
328  * credit_response if the client requests a credit increase
329  * that would take their credit over the maximum, and
330  * limiting the decrease so they don't run out of credits.
331  *
332  * Later, this could do something dynamic based on load.
333  *
334  * One other non-obvious bit about credits: We keep the
335  * session s_max_credits low until the 1st authentication,
336  * at which point we'll set the normal maximum_credits.
337  * Some clients ask for more credits with session setup,
338  * and we need to handle that requested increase _after_
339  * the command-specific handler returns so it won't be
340  * restricted to the lower (pre-auth) limit.
341  */
342 static inline void
343 smb2_credit_decrease(smb_request_t *sr)
344 {
345 	smb_session_t *session = sr->session;
346 	uint16_t cur, d;
347 
348 	ASSERT3U(sr->smb2_credit_request, <, sr->smb2_credit_charge);
349 
350 	mutex_enter(&session->s_credits_mutex);
351 	cur = session->s_cur_credits;
352 	ASSERT(cur > 0);
353 
354 	/* Handle credit decrease. */
355 	d = sr->smb2_credit_charge - sr->smb2_credit_request;
356 
357 	/*
358 	 * Prevent underflow of current credits, and
359 	 * enforce a minimum of one credit, per:
360 	 * [MS-SMB2] 3.3.1.2
361 	 */
362 	if (d >= cur) {
363 		/*
364 		 * Tried to give up more credits than we should.
365 		 * Reduce the decrement.
366 		 */
367 		d = cur - 1;
368 		cur = 1;
369 		DTRACE_PROBE1(smb2__credit__neg, smb_request_t *, sr);
370 	} else {
371 		cur -= d;
372 	}
373 
374 	ASSERT3U(d, <=, sr->smb2_credit_charge);
375 	sr->smb2_credit_response = sr->smb2_credit_charge - d;
376 
377 	DTRACE_PROBE3(smb2__credit__decrease,
378 	    smb_request_t *, sr, int, (int)cur,
379 	    int, (int)session->s_cur_credits);
380 
381 	session->s_cur_credits = cur;
382 	mutex_exit(&session->s_credits_mutex);
383 }
384 
385 /*
386  * Second half of SMB2 credit handling (increases)
387  */
388 static inline void
389 smb2_credit_increase(smb_request_t *sr)
390 {
391 	smb_session_t *session = sr->session;
392 	uint16_t cur, d;
393 
394 	ASSERT3U(sr->smb2_credit_request, >, sr->smb2_credit_charge);
395 
396 	mutex_enter(&session->s_credits_mutex);
397 	cur = session->s_cur_credits;
398 
399 	/* Handle credit increase. */
400 	d = sr->smb2_credit_request - sr->smb2_credit_charge;
401 
402 	/*
403 	 * If new credits would be above max,
404 	 * reduce the credit grant.
405 	 */
406 	if (d > (session->s_max_credits - cur)) {
407 		d = session->s_max_credits - cur;
408 		cur = session->s_max_credits;
409 		DTRACE_PROBE1(smb2__credit__max, smb_request_t *, sr);
410 	} else {
411 		cur += d;
412 	}
413 	sr->smb2_credit_response = sr->smb2_credit_charge + d;
414 
415 	DTRACE_PROBE3(smb2__credit__increase,
416 	    smb_request_t *, sr, int, (int)cur,
417 	    int, (int)session->s_cur_credits);
418 
419 	session->s_cur_credits = cur;
420 	mutex_exit(&session->s_credits_mutex);
421 }
422 
423 /*
424  * Record some statistics:  latency, rx bytes, tx bytes
425  * per:  server, session & kshare.
426  */
427 static inline void
428 smb2_record_stats(smb_request_t *sr, smb_disp_stats_t *sds, boolean_t tx_only)
429 {
430 	hrtime_t	dt;
431 	int64_t		rxb;
432 	int64_t		txb;
433 
434 	dt = gethrtime() - sr->sr_time_start;
435 	rxb = (int64_t)(sr->command.chain_offset - sr->smb2_cmd_hdr);
436 	txb = (int64_t)(sr->reply.chain_offset - sr->smb2_reply_hdr);
437 
438 	if (!tx_only) {
439 		smb_server_inc_req(sr->sr_server);
440 		smb_latency_add_sample(&sds->sdt_lat, dt);
441 		atomic_add_64(&sds->sdt_rxb, rxb);
442 	}
443 	atomic_add_64(&sds->sdt_txb, txb);
444 }
445 
446 /*
447  * smb2sr_work
448  *
449  * This function processes each SMB command in the current request
450  * (which may be a compound request) building a reply containing
451  * SMB reply messages, one-to-one with the SMB commands.  Some SMB
452  * commands (change notify, blocking locks) may require both an
453  * "interim response" and a later "async response" at completion.
454  * In such cases, we'll encode the interim response in the reply
455  * compound we're building, and put the (now async) command on a
456  * list of commands that need further processing.  After we've
457  * finished processing the commands in this compound and building
458  * the compound reply, we'll send the compound reply, and finally
459  * process the list of async commands.
460  *
461  * As we work our way through the compound request and reply,
462  * we need to keep track of the bounds of the current request
463  * and reply.  For the request, this uses an MBC_SHADOW_CHAIN
464  * that begins at smb2_cmd_hdr.  The reply is appended to the
465  * sr->reply chain starting at smb2_reply_hdr.
466  *
467  * This function must always free the smb request, or arrange
468  * for it to be completed and free'd later (if SDRC_SR_KEPT).
469  */
470 void
471 smb2sr_work(struct smb_request *sr)
472 {
473 	const smb_disp_entry_t	*sdd;
474 	smb_disp_stats_t	*sds;
475 	smb_session_t		*session;
476 	uint32_t		msg_len;
477 	uint16_t		cmd_idx;
478 	int			rc = 0;
479 	boolean_t		disconnect = B_FALSE;
480 	boolean_t		related;
481 
482 	session = sr->session;
483 
484 	ASSERT(sr->smb2_async == B_FALSE);
485 	ASSERT(sr->tid_tree == 0);
486 	ASSERT(sr->uid_user == 0);
487 	ASSERT(sr->fid_ofile == 0);
488 	sr->smb_fid = (uint16_t)-1;
489 	sr->smb2_status = 0;
490 
491 	/* temporary until we identify a user */
492 	sr->user_cr = zone_kcred();
493 
494 cmd_start:
495 	/*
496 	 * Note that we don't check sr_state here and abort the
497 	 * compound if cancelled (etc.) because some SMB2 command
498 	 * handlers need to do work even when cancelled.
499 	 *
500 	 * We treat some status codes as if "sticky", meaning
501 	 * once they're set after some command handler returns,
502 	 * all remaining commands get this status without even
503 	 * calling the command-specific handler.
504 	 */
505 	if (sr->smb2_status != NT_STATUS_CANCELLED &&
506 	    sr->smb2_status != NT_STATUS_INSUFFICIENT_RESOURCES)
507 		sr->smb2_status = 0;
508 
509 	/*
510 	 * Decode the request header
511 	 *
512 	 * Most problems with decoding will result in the error
513 	 * STATUS_INVALID_PARAMETER.  If the decoding problem
514 	 * prevents continuing, we'll close the connection.
515 	 * [MS-SMB2] 3.3.5.2.6 Handling Incorrectly Formatted...
516 	 */
517 	sr->smb2_cmd_hdr = sr->command.chain_offset;
518 	if ((rc = smb2_decode_header(sr)) != 0) {
519 		cmn_err(CE_WARN, "clnt %s bad SMB2 header",
520 		    session->ip_addr_str);
521 		disconnect = B_TRUE;
522 		goto cleanup;
523 	}
524 
525 	/*
526 	 * The SMB2_FLAGS_SERVER_TO_REDIR should only appear
527 	 * in messages from the server back to the client.
528 	 */
529 	if ((sr->smb2_hdr_flags & SMB2_FLAGS_SERVER_TO_REDIR) != 0) {
530 		cmn_err(CE_WARN, "clnt %s bad SMB2 flags",
531 		    session->ip_addr_str);
532 		disconnect = B_TRUE;
533 		goto cleanup;
534 	}
535 	related = (sr->smb2_hdr_flags & SMB2_FLAGS_RELATED_OPERATIONS);
536 	sr->smb2_hdr_flags |= SMB2_FLAGS_SERVER_TO_REDIR;
537 	if (sr->smb2_hdr_flags & SMB2_FLAGS_ASYNC_COMMAND) {
538 		/* Probably an async cancel. */
539 		DTRACE_PROBE1(smb2__dispatch__async, smb_request_t *, sr);
540 	} else if (sr->smb2_async) {
541 		/* Previous command in compound went async. */
542 		sr->smb2_hdr_flags |= SMB2_FLAGS_ASYNC_COMMAND;
543 		sr->smb2_async_id = SMB2_ASYNCID(sr);
544 	}
545 
546 	/*
547 	 * In case we bail out with an error before we get to the
548 	 * section that computes the credit grant, initialize the
549 	 * response header fields so that credits won't change.
550 	 * Note: SMB 2.02 clients may send credit charge zero.
551 	 */
552 	if (sr->smb2_credit_charge == 0)
553 		sr->smb2_credit_charge = 1;
554 	sr->smb2_credit_response = sr->smb2_credit_charge;
555 
556 	/*
557 	 * Write a tentative reply header.
558 	 *
559 	 * We could just leave this blank, but if we're using the
560 	 * mdb module feature that extracts packets, it's useful
561 	 * to have the header mostly correct here.
562 	 *
563 	 * If we have already exhausted the output space, then the
564 	 * client is trying something funny.  Log it and kill 'em.
565 	 */
566 	sr->smb2_next_reply = 0;
567 	ASSERT((sr->reply.chain_offset & 7) == 0);
568 	sr->smb2_reply_hdr = sr->reply.chain_offset;
569 	if ((rc = smb2_encode_header(sr, B_FALSE)) != 0) {
570 		cmn_err(CE_WARN, "clnt %s excessive reply",
571 		    session->ip_addr_str);
572 		disconnect = B_TRUE;
573 		goto cleanup;
574 	}
575 
576 	/*
577 	 * Figure out the length of data following the SMB2 header.
578 	 * It ends at either the next SMB2 header if there is one
579 	 * (smb2_next_command != 0) or at the end of the message.
580 	 */
581 	if (sr->smb2_next_command != 0) {
582 		/* [MS-SMB2] says this is 8-byte aligned */
583 		msg_len = sr->smb2_next_command;
584 		if ((msg_len & 7) != 0 || (msg_len < SMB2_HDR_SIZE) ||
585 		    ((sr->smb2_cmd_hdr + msg_len) > sr->command.max_bytes)) {
586 			cmn_err(CE_WARN, "clnt %s bad SMB2 next cmd",
587 			    session->ip_addr_str);
588 			disconnect = B_TRUE;
589 			goto cleanup;
590 		}
591 	} else {
592 		msg_len = sr->command.max_bytes - sr->smb2_cmd_hdr;
593 	}
594 
595 	/*
596 	 * Setup a shadow chain for this SMB2 command, starting
597 	 * with the header and ending at either the next command
598 	 * or the end of the message.  The signing check below
599 	 * needs the entire SMB2 command.  After that's done, we
600 	 * advance chain_offset to the end of the header where
601 	 * the command specific handlers continue decoding.
602 	 */
603 	(void) MBC_SHADOW_CHAIN(&sr->smb_data, &sr->command,
604 	    sr->smb2_cmd_hdr, msg_len);
605 
606 	/*
607 	 * We will consume the data for this request from smb_data.
608 	 * That effectively consumes msg_len bytes from sr->command
609 	 * but doesn't update its chain_offset, so we need to update
610 	 * that here to make later received bytes accounting work.
611 	 */
612 	sr->command.chain_offset = sr->smb2_cmd_hdr + msg_len;
613 	ASSERT(sr->command.chain_offset <= sr->command.max_bytes);
614 
615 	/*
616 	 * Validate the commmand code, get dispatch table entries.
617 	 * [MS-SMB2] 3.3.5.2.6 Handling Incorrectly Formatted...
618 	 *
619 	 * The last slot in the dispatch table is used to handle
620 	 * invalid commands.  Same for statistics.
621 	 */
622 	if (sr->smb2_cmd_code < SMB2_INVALID_CMD)
623 		cmd_idx = sr->smb2_cmd_code;
624 	else
625 		cmd_idx = SMB2_INVALID_CMD;
626 	sdd = &smb2_disp_table[cmd_idx];
627 	sds = &session->s_server->sv_disp_stats2[cmd_idx];
628 
629 	/*
630 	 * If this command is NOT "related" to the previous,
631 	 * clear out the UID, TID, FID state that might be
632 	 * left over from the previous command.
633 	 *
634 	 * If the command IS related, any new IDs are ignored,
635 	 * and we simply continue with the previous user, tree,
636 	 * and open file.
637 	 */
638 	if (!related) {
639 		/*
640 		 * Drop user, tree, file; carefully ordered to
641 		 * avoid dangling references: file, tree, user
642 		 */
643 		if (sr->fid_ofile != NULL) {
644 			smb_ofile_release(sr->fid_ofile);
645 			sr->fid_ofile = NULL;
646 		}
647 		if (sr->tid_tree != NULL) {
648 			smb_tree_release(sr->tid_tree);
649 			sr->tid_tree = NULL;
650 		}
651 		if (sr->uid_user != NULL) {
652 			smb_user_release(sr->uid_user);
653 			sr->uid_user = NULL;
654 			sr->user_cr = zone_kcred();
655 		}
656 	}
657 
658 	/*
659 	 * Make sure we have a user and tree as needed
660 	 * according to the flags for the this command.
661 	 * Note that we may have inherited these.
662 	 */
663 	if ((sdd->sdt_flags & SDDF_SUPPRESS_UID) == 0) {
664 		/*
665 		 * This command requires a user session.
666 		 */
667 		if (related) {
668 			/*
669 			 * Previous command should have given us a user.
670 			 * [MS-SMB2] 3.3.5.2 Handling Related Requests
671 			 */
672 			if (sr->uid_user == NULL) {
673 				smb2sr_put_error(sr,
674 				    NT_STATUS_INVALID_PARAMETER);
675 				goto cmd_done;
676 			}
677 			sr->smb2_ssnid = sr->uid_user->u_ssnid;
678 		} else {
679 			/*
680 			 * Lookup the UID
681 			 * [MS-SMB2] 3.3.5.2 Verifying the Session
682 			 */
683 			ASSERT(sr->uid_user == NULL);
684 			/*
685 			 * [MS-SMB2] 3.3.5.2.7 Handling Compounded Requests
686 			 *
687 			 * If this is an encrypted compound request,
688 			 * ensure that the ssnid in the request
689 			 * is the same as the tform ssnid if this
690 			 * message is not related.
691 			 *
692 			 * The reasons this is done seem to apply equally
693 			 * to uncompounded requests, so we apply it to all.
694 			 */
695 
696 			if (sr->encrypted &&
697 			    sr->smb2_ssnid != sr->th_ssnid) {
698 				disconnect = B_TRUE;
699 				goto cleanup; /* just do this for now */
700 			}
701 
702 			sr->uid_user = smb_session_lookup_ssnid(session,
703 			    sr->smb2_ssnid);
704 			if (sr->uid_user == NULL) {
705 				smb2sr_put_error(sr,
706 				    NT_STATUS_USER_SESSION_DELETED);
707 				goto cmd_done;
708 			}
709 
710 			/*
711 			 * [MS-SMB2] 3.3.5.2.9 Verifying the Session
712 			 *
713 			 * If we're talking 3.x,
714 			 * RejectUnencryptedAccess is TRUE,
715 			 * Session.EncryptData is TRUE,
716 			 * and the message wasn't encrypted,
717 			 * return ACCESS_DENIED.
718 			 *
719 			 * Note that Session.EncryptData can only be TRUE when
720 			 * we're talking 3.x.
721 			 */
722 			if (sr->uid_user->u_encrypt == SMB_CONFIG_REQUIRED &&
723 			    !sr->encrypted) {
724 				smb2sr_put_error(sr,
725 				    NT_STATUS_ACCESS_DENIED);
726 				goto cmd_done;
727 			}
728 
729 			sr->user_cr = smb_user_getcred(sr->uid_user);
730 		}
731 		ASSERT(sr->uid_user != NULL);
732 
733 		/*
734 		 * Encrypt if:
735 		 * - The cmd is not SESSION_SETUP or NEGOTIATE; AND
736 		 * - Session.EncryptData is TRUE
737 		 *
738 		 * Those commands suppress UID, so they can't be the cmd here.
739 		 */
740 		if (sr->uid_user->u_encrypt != SMB_CONFIG_DISABLED &&
741 		    sr->th_sid_user == NULL) {
742 			smb_user_hold_internal(sr->uid_user);
743 			sr->th_sid_user = sr->uid_user;
744 			sr->th_ssnid = sr->smb2_ssnid;
745 		}
746 	}
747 
748 	if ((sdd->sdt_flags & SDDF_SUPPRESS_TID) == 0) {
749 		/*
750 		 * This command requires a tree connection.
751 		 */
752 		if (related) {
753 			/*
754 			 * Previous command should have given us a tree.
755 			 * [MS-SMB2] 3.3.5.2 Handling Related Requests
756 			 */
757 			if (sr->tid_tree == NULL) {
758 				smb2sr_put_error(sr,
759 				    NT_STATUS_INVALID_PARAMETER);
760 				goto cmd_done;
761 			}
762 			sr->smb_tid = sr->tid_tree->t_tid;
763 		} else {
764 			/*
765 			 * Lookup the TID
766 			 * [MS-SMB2] 3.3.5.2 Verifying the Tree Connect
767 			 */
768 			ASSERT(sr->tid_tree == NULL);
769 			sr->tid_tree = smb_session_lookup_tree(session,
770 			    sr->smb_tid);
771 			if (sr->tid_tree == NULL) {
772 				smb2sr_put_error(sr,
773 				    NT_STATUS_NETWORK_NAME_DELETED);
774 				goto cmd_done;
775 			}
776 
777 			/*
778 			 * [MS-SMB2] 3.3.5.2.11 Verifying the Tree Connect
779 			 *
780 			 * If we support 3.x, RejectUnencryptedAccess is TRUE,
781 			 * if Tcon.EncryptData is TRUE or
782 			 * global EncryptData is TRUE and
783 			 * the message wasn't encrypted, or
784 			 * if Tcon.EncryptData is TRUE or
785 			 * global EncryptData is TRUE or
786 			 * the request was encrypted and
787 			 * the connection doesn't support encryption,
788 			 * return ACCESS_DENIED.
789 			 *
790 			 * If RejectUnencryptedAccess is TRUE, we force
791 			 * max_protocol to at least 3.0. Additionally,
792 			 * if the tree requires encryption, we don't care
793 			 * what we support, we still enforce encryption.
794 			 * Since smb3_decrypt_msg() does check session->srv_cap,
795 			 * we only need to check sr->encrypted here.
796 			 */
797 			if (sr->tid_tree->t_encrypt == SMB_CONFIG_REQUIRED &&
798 			    !sr->encrypted) {
799 				smb2sr_put_error(sr,
800 				    NT_STATUS_ACCESS_DENIED);
801 				goto cmd_done;
802 			}
803 		}
804 		ASSERT(sr->tid_tree != NULL);
805 
806 		/*
807 		 * Encrypt if:
808 		 * - The cmd is not TREE_CONNECT; AND
809 		 * - Tree.EncryptData is TRUE
810 		 *
811 		 * TREE_CONNECT suppresses TID, so that can't be the cmd here.
812 		 * NOTE: assumes we can't have a tree without a user
813 		 */
814 		if (sr->tid_tree->t_encrypt != SMB_CONFIG_DISABLED &&
815 		    sr->th_sid_user == NULL) {
816 			smb_user_hold_internal(sr->uid_user);
817 			sr->th_sid_user = sr->uid_user;
818 			sr->th_ssnid = sr->smb2_ssnid;
819 		}
820 	}
821 
822 	/*
823 	 * SMB2 signature verification, two parts:
824 	 * (a) Require SMB2_FLAGS_SIGNED (for most request types)
825 	 * (b) If SMB2_FLAGS_SIGNED is set, check the signature.
826 	 * [MS-SMB2] 3.3.5.2.4 Verifying the Signature
827 	 */
828 
829 	/*
830 	 * No user session means no signature check.  That's OK,
831 	 * i.e. for commands marked SDDF_SUPPRESS_UID above.
832 	 * Note, this also means we won't sign the reply.
833 	 */
834 	if (sr->uid_user == NULL)
835 		sr->smb2_hdr_flags &= ~SMB2_FLAGS_SIGNED;
836 
837 	/*
838 	 * The SDDF_SUPPRESS_UID dispatch is set for requests that
839 	 * don't need a UID (user).  These also don't require a
840 	 * signature check here.
841 	 *
842 	 * [MS-SMB2] 3.3.5.2.4 Verifying the Signature
843 	 *
844 	 * If the packet was successfully decrypted, the message
845 	 * signature has already been verified, so we can skip this.
846 	 */
847 	if ((sdd->sdt_flags & SDDF_SUPPRESS_UID) == 0 &&
848 	    !sr->encrypted && sr->uid_user != NULL &&
849 	    (sr->uid_user->u_sign_flags & SMB_SIGNING_ENABLED) != 0) {
850 		/*
851 		 * If the request is signed, check the signature.
852 		 * Otherwise, if signing is required, deny access.
853 		 */
854 		if ((sr->smb2_hdr_flags & SMB2_FLAGS_SIGNED) != 0) {
855 			if (smb2_sign_check_request(sr) != 0) {
856 				smb2sr_put_error(sr, NT_STATUS_ACCESS_DENIED);
857 				DTRACE_PROBE1(smb2__sign__check,
858 				    smb_request_t *, sr);
859 				goto cmd_done;
860 			}
861 		} else if (
862 		    (sr->uid_user->u_sign_flags & SMB_SIGNING_CHECK) != 0) {
863 			smb2sr_put_error(sr, NT_STATUS_ACCESS_DENIED);
864 			goto cmd_done;
865 		}
866 	}
867 
868 	/*
869 	 * Now that the signing check is done with smb_data,
870 	 * advance past the SMB2 header we decoded earlier.
871 	 * This leaves sr->smb_data correctly positioned
872 	 * for command-specific decoding in the dispatch
873 	 * function called next.
874 	 */
875 	sr->smb_data.chain_offset = sr->smb2_cmd_hdr + SMB2_HDR_SIZE;
876 
877 	/*
878 	 * Credit adjustments (decrease)
879 	 *
880 	 * If we've gone async, credit adjustments were done
881 	 * when we sent the interim reply.
882 	 */
883 	if (!sr->smb2_async) {
884 		if (sr->smb2_credit_request < sr->smb2_credit_charge) {
885 			smb2_credit_decrease(sr);
886 		}
887 	}
888 
889 	/*
890 	 * The real work: call the SMB2 command handler
891 	 * (except for "sticky" smb2_status - see above)
892 	 */
893 	sr->sr_time_start = gethrtime();
894 	rc = SDRC_SUCCESS;
895 	if (sr->smb2_status == 0) {
896 		/* NB: not using pre_op */
897 		rc = (*sdd->sdt_function)(sr);
898 		/* NB: not using post_op */
899 	} else {
900 		smb2sr_put_error(sr, sr->smb2_status);
901 	}
902 
903 	/*
904 	 * When the sdt_function returns SDRC_SR_KEPT, it means
905 	 * this SR may have been passed to another thread so we
906 	 * MUST NOT touch it anymore.
907 	 */
908 	if (rc == SDRC_SR_KEPT)
909 		return;
910 
911 	MBC_FLUSH(&sr->raw_data);
912 
913 	/*
914 	 * Credit adjustments (increase)
915 	 */
916 	if (!sr->smb2_async) {
917 		if (sr->smb2_credit_request > sr->smb2_credit_charge) {
918 			smb2_credit_increase(sr);
919 		}
920 	}
921 
922 cmd_done:
923 	switch (rc) {
924 	case SDRC_SUCCESS:
925 		break;
926 	default:
927 		/*
928 		 * SMB2 does not use the other dispatch return codes.
929 		 * If we see something else, log an event so we'll
930 		 * know something is returning bogus status codes.
931 		 * If you see these in the log, use dtrace to find
932 		 * the code returning something else.
933 		 */
934 #ifdef	DEBUG
935 		cmn_err(CE_NOTE, "handler for %u returned 0x%x",
936 		    sr->smb2_cmd_code, rc);
937 #endif
938 		smb2sr_put_error(sr, NT_STATUS_INTERNAL_ERROR);
939 		break;
940 	case SDRC_ERROR:
941 		/*
942 		 * Many command handlers return SDRC_ERROR for any
943 		 * problems decoding the request, and don't bother
944 		 * setting smb2_status.  For those cases, the best
945 		 * status return would be "invalid parameter".
946 		 */
947 		if (sr->smb2_status == 0)
948 			sr->smb2_status = NT_STATUS_INVALID_PARAMETER;
949 		smb2sr_put_error(sr, sr->smb2_status);
950 		break;
951 	case SDRC_DROP_VC:
952 		disconnect = B_TRUE;
953 		goto cleanup;
954 
955 	case SDRC_NO_REPLY:
956 		/* will free sr */
957 		goto cleanup;
958 	}
959 
960 	/*
961 	 * Pad the reply to align(8) if there will be another.
962 	 * (We don't compound async replies.)
963 	 */
964 	if (!sr->smb2_async && sr->smb2_next_command != 0)
965 		(void) smb_mbc_put_align(&sr->reply, 8);
966 
967 	/*
968 	 * Record some statistics.  Uses:
969 	 *   rxb = command.chain_offset - smb2_cmd_hdr;
970 	 *   txb = reply.chain_offset - smb2_reply_hdr;
971 	 * which at this point represent the current cmd/reply.
972 	 *
973 	 * Note: If async, this does txb only, and
974 	 * skips the smb_latency_add_sample() calls.
975 	 */
976 	smb2_record_stats(sr, sds, sr->smb2_async);
977 
978 	/*
979 	 * If there's a next command, figure out where it starts,
980 	 * and fill in the next header offset for the reply.
981 	 * Note: We sanity checked smb2_next_command above.
982 	 */
983 	if (sr->smb2_next_command != 0) {
984 		sr->command.chain_offset =
985 		    sr->smb2_cmd_hdr + sr->smb2_next_command;
986 		sr->smb2_next_reply =
987 		    sr->reply.chain_offset - sr->smb2_reply_hdr;
988 	} else {
989 		ASSERT(sr->smb2_next_reply == 0);
990 	}
991 
992 	/*
993 	 * Overwrite the (now final) SMB2 header for this response.
994 	 */
995 	(void) smb2_encode_header(sr, B_TRUE);
996 
997 	/*
998 	 * Cannot move this into smb2_session_setup() - encoded header required.
999 	 */
1000 	if (session->dialect >= SMB_VERS_3_11 &&
1001 	    sr->smb2_cmd_code == SMB2_SESSION_SETUP &&
1002 	    sr->smb2_status == NT_STATUS_MORE_PROCESSING_REQUIRED) {
1003 		if (smb31_preauth_sha512_calc(sr, &sr->reply,
1004 		    sr->uid_user->u_preauth_hashval,
1005 		    sr->uid_user->u_preauth_hashval) != 0)
1006 			cmn_err(CE_WARN, "(3) Preauth hash calculation "
1007 			    "failed");
1008 	}
1009 
1010 	/* Don't sign if we're going to encrypt */
1011 	if (sr->th_sid_user == NULL &&
1012 	    (sr->smb2_hdr_flags & SMB2_FLAGS_SIGNED) != 0)
1013 		smb2_sign_reply(sr);
1014 
1015 	/*
1016 	 * Non-async runs the whole compound before send.
1017 	 * When we've gone async, send each individually.
1018 	 */
1019 	if (!sr->smb2_async && sr->smb2_next_command != 0)
1020 		goto cmd_start;
1021 
1022 	/*
1023 	 * If we have a durable handle, and this operation updated
1024 	 * the nvlist, write it out (before smb2_send_reply).
1025 	 */
1026 	if (sr->dh_nvl_dirty) {
1027 		sr->dh_nvl_dirty = B_FALSE;
1028 		smb2_dh_update_nvfile(sr);
1029 	}
1030 
1031 	smb2_send_reply(sr);
1032 	if (sr->smb2_async && sr->smb2_next_command != 0) {
1033 		MBC_FLUSH(&sr->reply);	/* New reply buffer. */
1034 		ASSERT(sr->reply.max_bytes == sr->session->reply_max_bytes);
1035 		goto cmd_start;
1036 	}
1037 
1038 cleanup:
1039 	if (disconnect)
1040 		smb_session_disconnect(session);
1041 
1042 	/*
1043 	 * Do "postwork" for oplock (and maybe other things)
1044 	 */
1045 	if (sr->sr_postwork != NULL)
1046 		smb2sr_run_postwork(sr);
1047 
1048 	mutex_enter(&sr->sr_mutex);
1049 	sr->sr_state = SMB_REQ_STATE_COMPLETED;
1050 	mutex_exit(&sr->sr_mutex);
1051 
1052 	smb_request_free(sr);
1053 }
1054 
1055 /*
1056  * Build interim responses for the current and all following
1057  * requests in this compound, then send the compound response,
1058  * leaving the SR state so that smb2sr_work() can continue its
1059  * processing of this compound in "async mode".
1060  *
1061  * If we agree to "go async", this should return STATUS_SUCCESS.
1062  * Otherwise return STATUS_INSUFFICIENT_RESOURCES for this and
1063  * all requests following this request.  (See the comments re.
1064  * "sticky" smb2_status values in smb2sr_work).
1065  *
1066  * Note: the Async ID we assign here is arbitrary, and need only
1067  * be unique among pending async responses on this connection, so
1068  * this just uses a modified messageID, which is already unique.
1069  *
1070  * Credits:  All credit changes should happen via the interim
1071  * responses, so we have to manage credits here.  After this
1072  * returns to smb2sr_work, the final replies for all these
1073  * commands will have smb2_credit_response = smb2_credit_charge
1074  * (meaning no further changes to the clients' credits).
1075  */
1076 uint32_t
1077 smb2sr_go_async(smb_request_t *sr)
1078 {
1079 	smb_session_t *session;
1080 	smb_disp_stats_t *sds;
1081 	uint16_t cmd_idx;
1082 	int32_t saved_com_offset;
1083 	uint32_t saved_cmd_hdr;
1084 	uint16_t saved_cred_resp;
1085 	uint32_t saved_hdr_flags;
1086 	uint32_t saved_reply_hdr;
1087 	uint32_t msg_len;
1088 	boolean_t disconnect = B_FALSE;
1089 
1090 	if (sr->smb2_async) {
1091 		/* already went async in some previous cmd. */
1092 		return (NT_STATUS_SUCCESS);
1093 	}
1094 	sr->smb2_async = B_TRUE;
1095 
1096 	/* The "server" session always runs async. */
1097 	session = sr->session;
1098 	if (session->sock == NULL)
1099 		return (NT_STATUS_SUCCESS);
1100 
1101 	sds = NULL;
1102 	saved_com_offset = sr->command.chain_offset;
1103 	saved_cmd_hdr = sr->smb2_cmd_hdr;
1104 	saved_cred_resp = sr->smb2_credit_response;
1105 	saved_hdr_flags = sr->smb2_hdr_flags;
1106 	saved_reply_hdr = sr->smb2_reply_hdr;
1107 
1108 	/*
1109 	 * The command-specific handler should not yet have put any
1110 	 * data in the reply except for the (place holder) header.
1111 	 */
1112 	if (sr->reply.chain_offset != sr->smb2_reply_hdr + SMB2_HDR_SIZE) {
1113 		ASSERT3U(sr->reply.chain_offset, ==,
1114 		    sr->smb2_reply_hdr + SMB2_HDR_SIZE);
1115 		return (NT_STATUS_INTERNAL_ERROR);
1116 	}
1117 
1118 	/*
1119 	 * Rewind to the start of the current header in both the
1120 	 * command and reply bufers, so the loop below can just
1121 	 * decode/encode just in every pass.  This means the
1122 	 * current command header is decoded again, but that
1123 	 * avoids having to special-case the first loop pass.
1124 	 */
1125 	sr->command.chain_offset = sr->smb2_cmd_hdr;
1126 	sr->reply.chain_offset = sr->smb2_reply_hdr;
1127 
1128 	/*
1129 	 * This command processing loop is a simplified version of
1130 	 * smb2sr_work() that just puts an "interim response" for
1131 	 * every command in the compound (NT_STATUS_PENDING).
1132 	 */
1133 cmd_start:
1134 	sr->smb2_status = NT_STATUS_PENDING;
1135 
1136 	/*
1137 	 * Decode the request header
1138 	 */
1139 	sr->smb2_cmd_hdr = sr->command.chain_offset;
1140 	if ((smb2_decode_header(sr)) != 0) {
1141 		cmn_err(CE_WARN, "clnt %s bad SMB2 header",
1142 		    session->ip_addr_str);
1143 		disconnect = B_TRUE;
1144 		goto cleanup;
1145 	}
1146 	sr->smb2_hdr_flags |= (SMB2_FLAGS_SERVER_TO_REDIR |
1147 	    SMB2_FLAGS_ASYNC_COMMAND);
1148 	sr->smb2_async_id = SMB2_ASYNCID(sr);
1149 
1150 	/*
1151 	 * In case we bail out...
1152 	 */
1153 	if (sr->smb2_credit_charge == 0)
1154 		sr->smb2_credit_charge = 1;
1155 	sr->smb2_credit_response = sr->smb2_credit_charge;
1156 
1157 	/*
1158 	 * Write a tentative reply header.
1159 	 */
1160 	sr->smb2_next_reply = 0;
1161 	ASSERT((sr->reply.chain_offset & 7) == 0);
1162 	sr->smb2_reply_hdr = sr->reply.chain_offset;
1163 	if ((smb2_encode_header(sr, B_FALSE)) != 0) {
1164 		cmn_err(CE_WARN, "clnt %s excessive reply",
1165 		    session->ip_addr_str);
1166 		disconnect = B_TRUE;
1167 		goto cleanup;
1168 	}
1169 
1170 	/*
1171 	 * Figure out the length of data...
1172 	 */
1173 	if (sr->smb2_next_command != 0) {
1174 		/* [MS-SMB2] says this is 8-byte aligned */
1175 		msg_len = sr->smb2_next_command;
1176 		if ((msg_len & 7) != 0 || (msg_len < SMB2_HDR_SIZE) ||
1177 		    ((sr->smb2_cmd_hdr + msg_len) > sr->command.max_bytes)) {
1178 			cmn_err(CE_WARN, "clnt %s bad SMB2 next cmd",
1179 			    session->ip_addr_str);
1180 			disconnect = B_TRUE;
1181 			goto cleanup;
1182 		}
1183 	} else {
1184 		msg_len = sr->command.max_bytes - sr->smb2_cmd_hdr;
1185 	}
1186 
1187 	/*
1188 	 * We just skip any data, so no shadow chain etc.
1189 	 */
1190 	sr->command.chain_offset = sr->smb2_cmd_hdr + msg_len;
1191 	ASSERT(sr->command.chain_offset <= sr->command.max_bytes);
1192 
1193 	/*
1194 	 * Validate the commmand code...
1195 	 */
1196 	if (sr->smb2_cmd_code < SMB2_INVALID_CMD)
1197 		cmd_idx = sr->smb2_cmd_code;
1198 	else
1199 		cmd_idx = SMB2_INVALID_CMD;
1200 	sds = &session->s_server->sv_disp_stats2[cmd_idx];
1201 
1202 	/*
1203 	 * Don't change (user, tree, file) because we want them
1204 	 * exactly as they were when we entered.  That also means
1205 	 * we may not have the right user in sr->uid_user for
1206 	 * signature checks, so leave that until smb2sr_work
1207 	 * runs these commands "for real".  Therefore, here
1208 	 * we behave as if: (sr->uid_user == NULL)
1209 	 */
1210 	sr->smb2_hdr_flags &= ~SMB2_FLAGS_SIGNED;
1211 
1212 	/*
1213 	 * Credit adjustments (decrease)
1214 	 *
1215 	 * NOTE: interim responses are not signed.
1216 	 * Any attacker can modify the credit grant
1217 	 * in the response. Because of this property,
1218 	 * it is no worse to assume the credit charge and grant
1219 	 * are sane without verifying the signature,
1220 	 * and that saves us a whole lot of work.
1221 	 * If the credits WERE modified, we'll find out
1222 	 * when we verify the signature later,
1223 	 * which nullifies any changes caused here.
1224 	 *
1225 	 * Skip this on the first command, because the
1226 	 * credit decrease was done by the caller.
1227 	 */
1228 	if (sr->smb2_cmd_hdr != saved_cmd_hdr) {
1229 		if (sr->smb2_credit_request < sr->smb2_credit_charge) {
1230 			smb2_credit_decrease(sr);
1231 		}
1232 	}
1233 
1234 	/*
1235 	 * The real work: ... (would be here)
1236 	 */
1237 	smb2sr_put_error(sr, sr->smb2_status);
1238 
1239 	/*
1240 	 * Credit adjustments (increase)
1241 	 */
1242 	if (sr->smb2_credit_request > sr->smb2_credit_charge) {
1243 		smb2_credit_increase(sr);
1244 	}
1245 
1246 	/* cmd_done: label */
1247 
1248 	/*
1249 	 * Pad the reply to align(8) if there will be another.
1250 	 * This (interim) reply uses compounding.
1251 	 */
1252 	if (sr->smb2_next_command != 0)
1253 		(void) smb_mbc_put_align(&sr->reply, 8);
1254 
1255 	/*
1256 	 * Record some statistics.  Uses:
1257 	 *   rxb = command.chain_offset - smb2_cmd_hdr;
1258 	 *   txb = reply.chain_offset - smb2_reply_hdr;
1259 	 * which at this point represent the current cmd/reply.
1260 	 *
1261 	 * Note: We're doing smb_latency_add_sample() for all
1262 	 * remaining commands NOW, which means we won't include
1263 	 * the async part of their work in latency statistics.
1264 	 * That's intentional, as the async part of a command
1265 	 * would otherwise skew our latency statistics.
1266 	 */
1267 	smb2_record_stats(sr, sds, B_FALSE);
1268 
1269 	/*
1270 	 * If there's a next command, figure out where it starts,
1271 	 * and fill in the next header offset for the reply.
1272 	 * Note: We sanity checked smb2_next_command above.
1273 	 */
1274 	if (sr->smb2_next_command != 0) {
1275 		sr->command.chain_offset =
1276 		    sr->smb2_cmd_hdr + sr->smb2_next_command;
1277 		sr->smb2_next_reply =
1278 		    sr->reply.chain_offset - sr->smb2_reply_hdr;
1279 	} else {
1280 		ASSERT(sr->smb2_next_reply == 0);
1281 	}
1282 
1283 	/*
1284 	 * Overwrite the (now final) SMB2 header for this response.
1285 	 */
1286 	(void) smb2_encode_header(sr, B_TRUE);
1287 
1288 	/*
1289 	 * Process whole compound before sending.
1290 	 */
1291 	if (sr->smb2_next_command != 0)
1292 		goto cmd_start;
1293 	smb2_send_reply(sr);
1294 
1295 	ASSERT(!disconnect);
1296 
1297 cleanup:
1298 	/*
1299 	 * Restore caller's command processing state.
1300 	 */
1301 	sr->smb2_cmd_hdr = saved_cmd_hdr;
1302 	sr->command.chain_offset = saved_cmd_hdr;
1303 	(void) smb2_decode_header(sr);
1304 	sr->command.chain_offset = saved_com_offset;
1305 
1306 	sr->smb2_credit_response = saved_cred_resp;
1307 	sr->smb2_hdr_flags = saved_hdr_flags;
1308 	sr->smb2_status = NT_STATUS_SUCCESS;
1309 
1310 	/*
1311 	 * In here, the "disconnect" flag just means we had an
1312 	 * error decoding or encoding something.  Rather than
1313 	 * actually disconnect here, let's assume whatever
1314 	 * problem we encountered will be seen by the caller
1315 	 * as they continue processing the compound, and just
1316 	 * restore everything and return an error.
1317 	 */
1318 	if (disconnect) {
1319 		sr->smb2_async = B_FALSE;
1320 		sr->smb2_reply_hdr = saved_reply_hdr;
1321 		sr->reply.chain_offset = sr->smb2_reply_hdr;
1322 		(void) smb2_encode_header(sr, B_FALSE);
1323 		return (NT_STATUS_INVALID_PARAMETER);
1324 	}
1325 
1326 	/*
1327 	 * The compound reply buffer we sent is now gone.
1328 	 * Setup a new reply buffer for the caller.
1329 	 */
1330 	sr->smb2_hdr_flags |= SMB2_FLAGS_ASYNC_COMMAND;
1331 	sr->smb2_async_id = SMB2_ASYNCID(sr);
1332 	sr->smb2_next_reply = 0;
1333 	MBC_FLUSH(&sr->reply);
1334 	ASSERT(sr->reply.max_bytes == sr->session->reply_max_bytes);
1335 	ASSERT(sr->reply.chain_offset == 0);
1336 	sr->smb2_reply_hdr = 0;
1337 	(void) smb2_encode_header(sr, B_FALSE);
1338 
1339 	return (NT_STATUS_SUCCESS);
1340 }
1341 
1342 int
1343 smb2_decode_header(smb_request_t *sr)
1344 {
1345 	uint32_t pid, tid;
1346 	uint16_t hdr_len;
1347 	int rc;
1348 
1349 	rc = smb_mbc_decodef(
1350 	    &sr->command, "Nwww..wwllqllq16c",
1351 	    &hdr_len,			/* w */
1352 	    &sr->smb2_credit_charge,	/* w */
1353 	    &sr->smb2_chan_seq,		/* w */
1354 	    /* reserved			  .. */
1355 	    &sr->smb2_cmd_code,		/* w */
1356 	    &sr->smb2_credit_request,	/* w */
1357 	    &sr->smb2_hdr_flags,	/* l */
1358 	    &sr->smb2_next_command,	/* l */
1359 	    &sr->smb2_messageid,	/* q */
1360 	    &pid,			/* l */
1361 	    &tid,			/* l */
1362 	    &sr->smb2_ssnid,		/* q */
1363 	    sr->smb2_sig);		/* 16c */
1364 	if (rc)
1365 		return (rc);
1366 
1367 	if (hdr_len != SMB2_HDR_SIZE)
1368 		return (-1);
1369 
1370 	if (sr->smb2_hdr_flags & SMB2_FLAGS_ASYNC_COMMAND) {
1371 		sr->smb2_async_id = pid |
1372 		    ((uint64_t)tid) << 32;
1373 		sr->smb_pid = 0;
1374 		sr->smb_tid = 0;
1375 	} else {
1376 		sr->smb2_async_id = 0;
1377 		sr->smb_pid = pid;
1378 		sr->smb_tid = (uint16_t)tid; /* XXX wide TIDs */
1379 	}
1380 
1381 	return (rc);
1382 }
1383 
1384 int
1385 smb2_encode_header(smb_request_t *sr, boolean_t overwrite)
1386 {
1387 	uint64_t pid_tid_aid; /* pid+tid, or async id */
1388 	int rc;
1389 
1390 	if (sr->smb2_hdr_flags & SMB2_FLAGS_ASYNC_COMMAND) {
1391 		pid_tid_aid = sr->smb2_async_id;
1392 	} else {
1393 		pid_tid_aid = sr->smb_pid |
1394 		    ((uint64_t)sr->smb_tid) << 32;
1395 	}
1396 
1397 	if (overwrite) {
1398 		rc = smb_mbc_poke(&sr->reply,
1399 		    sr->smb2_reply_hdr,
1400 		    "Nwwlwwllqqq16c",
1401 		    SMB2_HDR_SIZE,		/* w */
1402 		    sr->smb2_credit_charge,	/* w */
1403 		    sr->smb2_status,		/* l */
1404 		    sr->smb2_cmd_code,		/* w */
1405 		    sr->smb2_credit_response,	/* w */
1406 		    sr->smb2_hdr_flags,		/* l */
1407 		    sr->smb2_next_reply,	/* l */
1408 		    sr->smb2_messageid,		/* q */
1409 		    pid_tid_aid,		/* q */
1410 		    sr->smb2_ssnid,		/* q */
1411 		    sr->smb2_sig);		/* 16c */
1412 	} else {
1413 		rc = smb_mbc_encodef(&sr->reply,
1414 		    "Nwwlwwllqqq16c",
1415 		    SMB2_HDR_SIZE,		/* w */
1416 		    sr->smb2_credit_charge,	/* w */
1417 		    sr->smb2_status,		/* l */
1418 		    sr->smb2_cmd_code,		/* w */
1419 		    sr->smb2_credit_response,	/* w */
1420 		    sr->smb2_hdr_flags,		/* l */
1421 		    sr->smb2_next_reply,	/* l */
1422 		    sr->smb2_messageid,		/* q */
1423 		    pid_tid_aid,		/* q */
1424 		    sr->smb2_ssnid,		/* q */
1425 		    sr->smb2_sig);		/* 16c */
1426 	}
1427 
1428 	return (rc);
1429 }
1430 
1431 void
1432 smb2_send_reply(smb_request_t *sr)
1433 {
1434 	struct mbuf_chain enc_reply;
1435 	smb_session_t *session = sr->session;
1436 	mbuf_t *m;
1437 
1438 	/*
1439 	 * [MS-SMB2] 3.3.4.1.4 Encrypting the Message
1440 	 *
1441 	 * When the connection supports encryption and the dialect
1442 	 * is 3.x, encrypt if:
1443 	 * - The request was encrypted OR
1444 	 * - The cmd is not SESSION_SETUP or NEGOTIATE AND
1445 	 * -- Session.EncryptData is TRUE OR
1446 	 * -- The cmd is not TREE_CONNECT AND
1447 	 * --- Tree.EncryptData is TRUE
1448 	 *
1449 	 * This boils down to sr->th_sid_user != NULL, and the rest
1450 	 * is enforced when th_sid_user is set.
1451 	 */
1452 
1453 	if ((session->capabilities & SMB2_CAP_ENCRYPTION) == 0 ||
1454 	    sr->th_sid_user == NULL) {
1455 		(void) smb_session_send(sr->session, 0, &sr->reply);
1456 		return;
1457 	}
1458 
1459 	/*
1460 	 * Encrypted send
1461 	 *
1462 	 * Not doing in-place encryption because we may have
1463 	 * loaned buffers (eg. from ZFS) that are read-only.
1464 	 *
1465 	 * Setup the transform header in its own mblk,
1466 	 * with leading space for the netbios header.
1467 	 */
1468 	MBC_INIT(&enc_reply, SMB3_TFORM_HDR_SIZE);
1469 	m = enc_reply.chain;
1470 	m->m_len = SMB3_TFORM_HDR_SIZE;
1471 
1472 	sr->th_msglen = sr->reply.chain_offset;
1473 	m->m_next = smb_mbuf_alloc_chain(sr->th_msglen);
1474 	enc_reply.max_bytes += sr->th_msglen;
1475 
1476 	if (smb3_encrypt_sr(sr, &sr->reply, &enc_reply) != 0) {
1477 		cmn_err(CE_WARN, "smb3 encryption failed");
1478 		smb_session_disconnect(sr->session);
1479 	} else {
1480 		(void) smb_session_send(sr->session, 0, &enc_reply);
1481 	}
1482 	MBC_FLUSH(&enc_reply);
1483 }
1484 
1485 /*
1486  * This wrapper function exists to help catch calls to smbsr_status()
1487  * (which is SMB1-specific) in common code.  See smbsr_status().
1488  * If the log message below is seen, put a dtrace probe on this
1489  * function with a stack() action to see who is calling the SMB1
1490  * "put error" from common code, and fix it.
1491  */
1492 void
1493 smbsr_status_smb2(smb_request_t *sr, DWORD status)
1494 {
1495 	const char *name;
1496 
1497 	if (sr->smb2_cmd_code < SMB2__NCMDS)
1498 		name = smb2_disp_table[sr->smb2_cmd_code].sdt_name;
1499 	else
1500 		name = "<unknown>";
1501 #ifdef	DEBUG
1502 	cmn_err(CE_NOTE, "smbsr_status called for %s", name);
1503 #endif
1504 
1505 	smb2sr_put_error_data(sr, status, NULL);
1506 }
1507 
1508 void
1509 smb2sr_put_errno(struct smb_request *sr, int errnum)
1510 {
1511 	uint32_t status = smb_errno2status(errnum);
1512 	smb2sr_put_error_data(sr, status, NULL);
1513 }
1514 
1515 void
1516 smb2sr_put_error(smb_request_t *sr, uint32_t status)
1517 {
1518 	smb2sr_put_error_data(sr, status, NULL);
1519 }
1520 
1521 /*
1522  * Build an SMB2 error response.  [MS-SMB2] 2.2.2
1523  */
1524 void
1525 smb2sr_put_error_data(smb_request_t *sr, uint32_t status, mbuf_chain_t *mbc)
1526 {
1527 	DWORD len;
1528 
1529 	/*
1530 	 * The common dispatch code writes this when it
1531 	 * updates the SMB2 header before sending.
1532 	 */
1533 	sr->smb2_status = status;
1534 
1535 	/* Rewind to the end of the SMB header. */
1536 	sr->reply.chain_offset = sr->smb2_reply_hdr + SMB2_HDR_SIZE;
1537 
1538 	/*
1539 	 * NB: Must provide at least one byte of error data,
1540 	 * per [MS-SMB2] 2.2.2
1541 	 */
1542 	if (mbc != NULL && (len = MBC_LENGTH(mbc)) != 0) {
1543 		(void) smb_mbc_encodef(
1544 		    &sr->reply,
1545 		    "wwlC",
1546 		    9,	/* StructSize */	/* w */
1547 		    0,	/* reserved */		/* w */
1548 		    len,			/* l */
1549 		    mbc);			/* C */
1550 	} else {
1551 		(void) smb_mbc_encodef(
1552 		    &sr->reply,
1553 		    "wwl.",
1554 		    9,	/* StructSize */	/* w */
1555 		    0,	/* reserved */		/* w */
1556 		    0);				/* l. */
1557 	}
1558 }
1559 
1560 /*
1561  * Build an SMB2 error context response (dialect 3.1.1).
1562  */
1563 void
1564 smb2sr_put_error_ctx(smb_request_t *sr, uint32_t status, uint32_t errid,
1565     mbuf_chain_t *mbc)
1566 {
1567 	DWORD len;
1568 
1569 	/*
1570 	 * The common dispatch code writes this when it
1571 	 * updates the SMB2 header before sending.
1572 	 */
1573 	sr->smb2_status = status;
1574 
1575 	/* Rewind to the end of the SMB header. */
1576 	sr->reply.chain_offset = sr->smb2_reply_hdr + SMB2_HDR_SIZE;
1577 
1578 	/*
1579 	 *  Error Context is 8-byte header plus encaps. data (ErrorContextData),
1580 	 *  which can be zero-length.
1581 	 */
1582 	if (mbc != NULL && (len = MBC_LENGTH(mbc)) != 0) {
1583 		(void) smb_mbc_encodef(
1584 		    &sr->reply,
1585 		    "wbblllC",
1586 		    9,		/* StructSize */	/* w */
1587 		    1,		/* ErrorContextCount */	/* b */
1588 		    0,		/* reserved */		/* b */
1589 		    8+len,	/* ByteCount */		/* l */
1590 		    len,	/* ErrorDataLength */	/* l */
1591 		    errid,	/* ErrorId */		/* l */
1592 		    mbc);				/* C */
1593 	} else {
1594 		(void) smb_mbc_encodef(
1595 		    &sr->reply,
1596 		    "wbblll",
1597 		    9,		/* StructSize */	/* w */
1598 		    1,		/* ErrorContextCount */	/* b */
1599 		    0,		/* reserved */		/* b */
1600 		    8,		/* ByteCount */		/* l */
1601 		    0,		/* ErrorDataLength */	/* l */
1602 		    errid);	/* ErrorId */		/* l */
1603 	}
1604 }
1605 
1606 /*
1607  * Build an SMB2 error context response with SMB2_ERROR_ID_DEFAULT ErrorId.
1608  *
1609  * This only handles the case we currently need, encapsulating a
1610  * single error data section inside an SMB2_ERROR_ID_DEFAULT
1611  * error context type (which is type zero, and that's what
1612  * the zero on the end of this function name refers to).
1613  */
1614 void
1615 smb2sr_put_error_ctx0(smb_request_t *sr, uint32_t status, mbuf_chain_t *mbc)
1616 {
1617 	return (smb2sr_put_error_ctx(sr, status, SMB2_ERROR_ID_DEFAULT, mbc));
1618 }
1619 
1620 /*
1621  * smb2sr_lookup_fid
1622  *
1623  * Setup sr->fid_ofile, either inherited from a related command,
1624  * or obtained via FID lookup.  Similar inheritance logic as in
1625  * smb2sr_work.
1626  */
1627 uint32_t
1628 smb2sr_lookup_fid(smb_request_t *sr, smb2fid_t *fid)
1629 {
1630 	boolean_t related = sr->smb2_hdr_flags &
1631 	    SMB2_FLAGS_RELATED_OPERATIONS;
1632 
1633 	if (related) {
1634 		if (sr->fid_ofile == NULL)
1635 			return (NT_STATUS_INVALID_PARAMETER);
1636 		sr->smb_fid = sr->fid_ofile->f_fid;
1637 		return (0);
1638 	}
1639 
1640 	/*
1641 	 * If we could be sure this is called only once per cmd,
1642 	 * we could simply ASSERT(sr->fid_ofile == NULL) here.
1643 	 * However, there are cases where it can be called again
1644 	 * handling the same command, so let's tolerate that.
1645 	 */
1646 	if (sr->fid_ofile == NULL) {
1647 		sr->smb_fid = (uint16_t)fid->temporal;
1648 		sr->fid_ofile = smb_ofile_lookup_by_fid(sr, sr->smb_fid);
1649 	}
1650 	if (sr->fid_ofile == NULL ||
1651 	    sr->fid_ofile->f_persistid != fid->persistent)
1652 		return (NT_STATUS_FILE_CLOSED);
1653 
1654 	return (0);
1655 }
1656 
1657 /*
1658  * smb2_dispatch_stats_init
1659  *
1660  * Initializes dispatch statistics for SMB2.
1661  * See also smb_dispatch_stats_init(), which fills in
1662  * the lower part of the statistics array, from zero
1663  * through SMB_COM_NUM;
1664  */
1665 void
1666 smb2_dispatch_stats_init(smb_server_t *sv)
1667 {
1668 	smb_disp_stats_t *sds = sv->sv_disp_stats2;
1669 	smb_kstat_req_t *ksr;
1670 	int		i;
1671 
1672 	ksr = ((smbsrv_kstats_t *)sv->sv_ksp->ks_data)->ks_reqs2;
1673 
1674 	for (i = 0; i < SMB2__NCMDS; i++, ksr++) {
1675 		smb_latency_init(&sds[i].sdt_lat);
1676 		(void) strlcpy(ksr->kr_name, smb2_disp_table[i].sdt_name,
1677 		    sizeof (ksr->kr_name));
1678 	}
1679 }
1680 
1681 /*
1682  * smb2_dispatch_stats_fini
1683  *
1684  * Frees and destroyes the resources used for statistics.
1685  */
1686 void
1687 smb2_dispatch_stats_fini(smb_server_t *sv)
1688 {
1689 	smb_disp_stats_t *sds = sv->sv_disp_stats2;
1690 	int	i;
1691 
1692 	for (i = 0; i < SMB2__NCMDS; i++)
1693 		smb_latency_destroy(&sds[i].sdt_lat);
1694 }
1695 
1696 void
1697 smb2_dispatch_stats_update(smb_server_t *sv,
1698     smb_kstat_req_t *ksr, int first, int nreq)
1699 {
1700 	smb_disp_stats_t *sds = sv->sv_disp_stats2;
1701 	int	i;
1702 	int	last;
1703 
1704 	last = first + nreq - 1;
1705 
1706 	if ((first < SMB2__NCMDS) && (last < SMB2__NCMDS))  {
1707 		for (i = first; i <= last; i++, ksr++) {
1708 			ksr->kr_rxb = sds[i].sdt_rxb;
1709 			ksr->kr_txb = sds[i].sdt_txb;
1710 			mutex_enter(&sds[i].sdt_lat.ly_mutex);
1711 			ksr->kr_nreq = sds[i].sdt_lat.ly_a_nreq;
1712 			ksr->kr_sum = sds[i].sdt_lat.ly_a_sum;
1713 			ksr->kr_a_mean = sds[i].sdt_lat.ly_a_mean;
1714 			ksr->kr_a_stddev =
1715 			    sds[i].sdt_lat.ly_a_stddev;
1716 			ksr->kr_d_mean = sds[i].sdt_lat.ly_d_mean;
1717 			ksr->kr_d_stddev =
1718 			    sds[i].sdt_lat.ly_d_stddev;
1719 			sds[i].sdt_lat.ly_d_mean = 0;
1720 			sds[i].sdt_lat.ly_d_nreq = 0;
1721 			sds[i].sdt_lat.ly_d_stddev = 0;
1722 			sds[i].sdt_lat.ly_d_sum = 0;
1723 			mutex_exit(&sds[i].sdt_lat.ly_mutex);
1724 		}
1725 	}
1726 }
1727 
1728 /*
1729  * Append new_sr to the postwork queue.  sr->smb2_cmd_code encodes
1730  * the action that should be run by this sr.
1731  *
1732  * This queue is rarely used (and normally empty) so we're OK
1733  * using a simple "walk to tail and insert" here.
1734  */
1735 void
1736 smb2sr_append_postwork(smb_request_t *top_sr, smb_request_t *new_sr)
1737 {
1738 	smb_request_t *last_sr;
1739 
1740 	ASSERT(top_sr->session->dialect >= SMB_VERS_2_BASE);
1741 
1742 	last_sr = top_sr;
1743 	while (last_sr->sr_postwork != NULL)
1744 		last_sr = last_sr->sr_postwork;
1745 
1746 	last_sr->sr_postwork = new_sr;
1747 }
1748 
1749 /*
1750  * Run any "post work" that was appended to the main SR while it
1751  * was running.  This is called after the request has been sent
1752  * for the main SR, and used in cases i.e. the oplock code, where
1753  * we need to send something to the client only _after_ the main
1754  * sr request has gone out.
1755  */
1756 static void
1757 smb2sr_run_postwork(smb_request_t *top_sr)
1758 {
1759 	smb_request_t *post_sr;	/* the one we're running */
1760 	smb_request_t *next_sr;
1761 
1762 	while ((post_sr = top_sr->sr_postwork) != NULL) {
1763 		next_sr = post_sr->sr_postwork;
1764 		top_sr->sr_postwork = next_sr;
1765 		post_sr->sr_postwork = NULL;
1766 
1767 		post_sr->sr_worker = top_sr->sr_worker;
1768 		post_sr->sr_state = SMB_REQ_STATE_ACTIVE;
1769 
1770 		switch (post_sr->smb2_cmd_code) {
1771 		case SMB2_OPLOCK_BREAK:
1772 			smb_oplock_send_break(post_sr);
1773 			break;
1774 		default:
1775 			ASSERT(0);
1776 		}
1777 
1778 		/*
1779 		 * If we have a durable handle, and this operation
1780 		 * updated the nvlist, write it out.
1781 		 */
1782 		if (post_sr->dh_nvl_dirty) {
1783 			post_sr->dh_nvl_dirty = B_FALSE;
1784 			smb2_dh_update_nvfile(post_sr);
1785 		}
1786 
1787 		post_sr->sr_state = SMB_REQ_STATE_COMPLETED;
1788 		smb_request_free(post_sr);
1789 	}
1790 }
1791