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