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