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