xref: /titanic_50/usr/src/uts/common/fs/smbsrv/smb_session.c (revision a7fe1d5bb55904d4c79638b8778bc9dd8ed7fd7b)
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 <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 		/*
396 		 * This request is waiting in change notify.
397 		 */
398 		sr->sr_state = SMB_REQ_STATE_CANCELED;
399 		cv_signal(&sr->sr_ncr.nc_cv);
400 		break;
401 
402 	case SMB_REQ_STATE_EVENT_OCCURRED:
403 	case SMB_REQ_STATE_COMPLETED:
404 	case SMB_REQ_STATE_CANCELED:
405 		/*
406 		 * No action required for these states since the request
407 		 * is completing.
408 		 */
409 		break;
410 
411 	case SMB_REQ_STATE_FREE:
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_slist_enter(&session->s_req_list);
790 	sr = smb_slist_head(&session->s_req_list);
791 
792 	while (sr) {
793 		ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
794 		if ((sr != exclude_sr) &&
795 		    (tree == NULL || sr->tid_tree == tree))
796 			smb_request_cancel(sr);
797 
798 		sr = smb_slist_next(&session->s_req_list, sr);
799 	}
800 
801 	smb_slist_exit(&session->s_req_list);
802 }
803 
804 void
805 smb_session_worker(void	*arg)
806 {
807 	smb_request_t	*sr;
808 	smb_srqueue_t	*srq;
809 
810 	sr = (smb_request_t *)arg;
811 	SMB_REQ_VALID(sr);
812 
813 	srq = sr->session->s_srqueue;
814 	smb_srqueue_waitq_to_runq(srq);
815 	sr->sr_worker = curthread;
816 	mutex_enter(&sr->sr_mutex);
817 	sr->sr_time_active = gethrtime();
818 	switch (sr->sr_state) {
819 	case SMB_REQ_STATE_SUBMITTED:
820 		mutex_exit(&sr->sr_mutex);
821 		if (smb_dispatch_request(sr)) {
822 			mutex_enter(&sr->sr_mutex);
823 			sr->sr_state = SMB_REQ_STATE_COMPLETED;
824 			mutex_exit(&sr->sr_mutex);
825 			smb_request_free(sr);
826 		}
827 		break;
828 
829 	default:
830 		ASSERT(sr->sr_state == SMB_REQ_STATE_CANCELED);
831 		sr->sr_state = SMB_REQ_STATE_COMPLETED;
832 		mutex_exit(&sr->sr_mutex);
833 		smb_request_free(sr);
834 		break;
835 	}
836 	smb_srqueue_runq_exit(srq);
837 }
838 
839 /*
840  * smb_session_lookup_user
841  */
842 static smb_user_t *
843 smb_session_lookup_user(smb_session_t *session, char *domain, char *name)
844 {
845 	smb_user_t	*user;
846 	smb_llist_t	*ulist;
847 
848 	ulist = &session->s_user_list;
849 	smb_llist_enter(ulist, RW_READER);
850 	user = smb_llist_head(ulist);
851 	while (user) {
852 		ASSERT(user->u_magic == SMB_USER_MAGIC);
853 		if (!smb_strcasecmp(user->u_name, name, 0) &&
854 		    !smb_strcasecmp(user->u_domain, domain, 0)) {
855 			if (smb_user_hold(user))
856 				break;
857 		}
858 		user = smb_llist_next(ulist, user);
859 	}
860 	smb_llist_exit(ulist);
861 
862 	return (user);
863 }
864 
865 /*
866  * If a user attempts to log in subsequently from the specified session,
867  * duplicates the existing SMB user instance such that all SMB user
868  * instances that corresponds to the same user on the given session
869  * reference the same user's cred.
870  *
871  * Returns NULL if the given user hasn't yet logged in from this
872  * specified session.  Otherwise, returns a user instance that corresponds
873  * to this subsequent login.
874  */
875 smb_user_t *
876 smb_session_dup_user(smb_session_t *session, char *domain, char *account_name)
877 {
878 	smb_user_t *orig_user = NULL;
879 	smb_user_t *user = NULL;
880 
881 	orig_user = smb_session_lookup_user(session, domain,
882 	    account_name);
883 
884 	if (orig_user) {
885 		user = smb_user_dup(orig_user);
886 		smb_user_release(orig_user);
887 	}
888 
889 	return (user);
890 }
891 
892 /*
893  * Find a user on the specified session by SMB UID.
894  */
895 smb_user_t *
896 smb_session_lookup_uid(smb_session_t *session, uint16_t uid)
897 {
898 	smb_user_t	*user;
899 	smb_llist_t	*user_list;
900 
901 	SMB_SESSION_VALID(session);
902 
903 	user_list = &session->s_user_list;
904 	smb_llist_enter(user_list, RW_READER);
905 
906 	user = smb_llist_head(user_list);
907 	while (user) {
908 		SMB_USER_VALID(user);
909 		ASSERT(user->u_session == session);
910 
911 		if (user->u_uid == uid) {
912 			if (!smb_user_hold(user))
913 				break;
914 
915 			smb_llist_exit(user_list);
916 			return (user);
917 		}
918 
919 		user = smb_llist_next(user_list, user);
920 	}
921 
922 	smb_llist_exit(user_list);
923 	return (NULL);
924 }
925 
926 void
927 smb_session_post_user(smb_session_t *session, smb_user_t *user)
928 {
929 	SMB_USER_VALID(user);
930 	ASSERT(user->u_refcnt == 0);
931 	ASSERT(user->u_state == SMB_USER_STATE_LOGGED_OFF);
932 	ASSERT(user->u_session == session);
933 
934 	smb_llist_post(&session->s_user_list, user, smb_user_delete);
935 }
936 
937 /*
938  * Logoff all users associated with the specified session.
939  */
940 static void
941 smb_session_logoff(smb_session_t *session)
942 {
943 	smb_user_t	*user;
944 
945 	SMB_SESSION_VALID(session);
946 
947 	smb_llist_enter(&session->s_user_list, RW_READER);
948 
949 	user = smb_llist_head(&session->s_user_list);
950 	while (user) {
951 		SMB_USER_VALID(user);
952 		ASSERT(user->u_session == session);
953 
954 		if (smb_user_hold(user)) {
955 			smb_user_logoff(user);
956 			smb_user_release(user);
957 		}
958 
959 		user = smb_llist_next(&session->s_user_list, user);
960 	}
961 
962 	smb_llist_exit(&session->s_user_list);
963 }
964 
965 /*
966  * Disconnect any trees associated with the specified share.
967  * Iterate through the users on this session and tell each user
968  * to disconnect from the share.
969  */
970 void
971 smb_session_disconnect_share(smb_session_t *session, const char *sharename)
972 {
973 	smb_user_t	*user;
974 
975 	SMB_SESSION_VALID(session);
976 
977 	smb_llist_enter(&session->s_user_list, RW_READER);
978 
979 	user = smb_llist_head(&session->s_user_list);
980 	while (user) {
981 		SMB_USER_VALID(user);
982 		ASSERT(user->u_session == session);
983 
984 		if (smb_user_hold(user)) {
985 			smb_user_disconnect_share(user, sharename);
986 			smb_user_release(user);
987 		}
988 
989 		user = smb_llist_next(&session->s_user_list, user);
990 	}
991 
992 	smb_llist_exit(&session->s_user_list);
993 }
994 
995 /*
996  * Copy the session workstation/client name to buf.  If the workstation
997  * is an empty string (which it will be on TCP connections), use the
998  * client IP address.
999  */
1000 void
1001 smb_session_getclient(smb_session_t *sn, char *buf, size_t buflen)
1002 {
1003 	char		ipbuf[INET6_ADDRSTRLEN];
1004 	smb_inaddr_t	*ipaddr;
1005 
1006 	ASSERT(sn);
1007 	ASSERT(buf);
1008 	ASSERT(buflen);
1009 
1010 	*buf = '\0';
1011 
1012 	if (sn->workstation[0] != '\0') {
1013 		(void) strlcpy(buf, sn->workstation, buflen);
1014 		return;
1015 	}
1016 
1017 	ipaddr = &sn->ipaddr;
1018 	if (smb_inet_ntop(ipaddr, ipbuf, SMB_IPSTRLEN(ipaddr->a_family)))
1019 		(void) strlcpy(buf, ipbuf, buflen);
1020 }
1021 
1022 /*
1023  * Check whether or not the specified client name is the client of this
1024  * session.  The name may be in UNC format (\\CLIENT).
1025  *
1026  * A workstation/client name is setup on NBT connections as part of the
1027  * NetBIOS session request but that isn't available on TCP connections.
1028  * If the session doesn't have a client name we typically return the
1029  * client IP address as the workstation name on MSRPC requests.  So we
1030  * check for the IP address here in addition to the workstation name.
1031  */
1032 boolean_t
1033 smb_session_isclient(smb_session_t *sn, const char *client)
1034 {
1035 	char		buf[INET6_ADDRSTRLEN];
1036 	smb_inaddr_t	*ipaddr;
1037 
1038 	client += strspn(client, "\\");
1039 
1040 	if (smb_strcasecmp(client, sn->workstation, 0) == 0)
1041 		return (B_TRUE);
1042 
1043 	ipaddr = &sn->ipaddr;
1044 	if (smb_inet_ntop(ipaddr, buf, SMB_IPSTRLEN(ipaddr->a_family)) == NULL)
1045 		return (B_FALSE);
1046 
1047 	if (smb_strcasecmp(client, buf, 0) == 0)
1048 		return (B_TRUE);
1049 
1050 	return (B_FALSE);
1051 }
1052 
1053 /*
1054  * smb_request_alloc
1055  *
1056  * Allocate an smb_request_t structure from the kmem_cache.  Partially
1057  * initialize the found/new request.
1058  *
1059  * Returns pointer to a request
1060  */
1061 smb_request_t *
1062 smb_request_alloc(smb_session_t *session, int req_length)
1063 {
1064 	smb_request_t	*sr;
1065 
1066 	ASSERT(session->s_magic == SMB_SESSION_MAGIC);
1067 
1068 	sr = kmem_cache_alloc(session->s_cache_request, KM_SLEEP);
1069 
1070 	/*
1071 	 * Future:  Use constructor to pre-initialize some fields.  For now
1072 	 * there are so many fields that it is easiest just to zero the
1073 	 * whole thing and start over.
1074 	 */
1075 	bzero(sr, sizeof (smb_request_t));
1076 
1077 	mutex_init(&sr->sr_mutex, NULL, MUTEX_DEFAULT, NULL);
1078 	cv_init(&sr->sr_ncr.nc_cv, NULL, CV_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 	ASSERT(sr->sr_ncr.nc_fname == 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 	cv_destroy(&sr->sr_ncr.nc_cv);
1137 	mutex_destroy(&sr->sr_mutex);
1138 	kmem_cache_free(sr->sr_cache, sr);
1139 }
1140 
1141 void
1142 dump_smb_inaddr(smb_inaddr_t *ipaddr)
1143 {
1144 	char ipstr[INET6_ADDRSTRLEN];
1145 
1146 	if (smb_inet_ntop(ipaddr, ipstr, SMB_IPSTRLEN(ipaddr->a_family)))
1147 		cmn_err(CE_WARN, "error ipstr=%s", ipstr);
1148 	else
1149 		cmn_err(CE_WARN, "error converting ip address");
1150 }
1151 
1152 boolean_t
1153 smb_session_oplocks_enable(smb_session_t *session)
1154 {
1155 	SMB_SESSION_VALID(session);
1156 	if (session->s_cfg.skc_oplock_enable == 0)
1157 		return (B_FALSE);
1158 	else
1159 		return (B_TRUE);
1160 }
1161 
1162 boolean_t
1163 smb_session_levelII_oplocks(smb_session_t *session)
1164 {
1165 	SMB_SESSION_VALID(session);
1166 	return (session->capabilities & CAP_LEVEL_II_OPLOCKS);
1167 }
1168 
1169 /*
1170  * smb_session_oplock_break
1171  *
1172  * The session lock must NOT be held by the caller of this thread;
1173  * as this would cause a deadlock.
1174  */
1175 void
1176 smb_session_oplock_break(smb_session_t *session,
1177     uint16_t tid, uint16_t fid, uint8_t brk)
1178 {
1179 	mbuf_chain_t	*mbc;
1180 
1181 	SMB_SESSION_VALID(session);
1182 
1183 	mbc = smb_mbc_alloc(MLEN);
1184 
1185 	(void) smb_mbc_encodef(mbc, "Mb19.wwwwbb3.wbb10.",
1186 	    SMB_COM_LOCKING_ANDX,
1187 	    tid,
1188 	    0xFFFF, 0, 0xFFFF, 8, 0xFF,
1189 	    fid,
1190 	    LOCKING_ANDX_OPLOCK_RELEASE,
1191 	    (brk == SMB_OPLOCK_BREAK_TO_LEVEL_II) ? 1 : 0);
1192 
1193 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1194 	switch (session->s_state) {
1195 	case SMB_SESSION_STATE_NEGOTIATED:
1196 	case SMB_SESSION_STATE_OPLOCK_BREAKING:
1197 	case SMB_SESSION_STATE_WRITE_RAW_ACTIVE:
1198 		session->s_state = SMB_SESSION_STATE_OPLOCK_BREAKING;
1199 		(void) smb_session_send(session, 0, mbc);
1200 		smb_mbc_free(mbc);
1201 		break;
1202 
1203 	case SMB_SESSION_STATE_READ_RAW_ACTIVE:
1204 		list_insert_tail(&session->s_oplock_brkreqs, mbc);
1205 		break;
1206 
1207 	case SMB_SESSION_STATE_DISCONNECTED:
1208 	case SMB_SESSION_STATE_TERMINATED:
1209 		smb_mbc_free(mbc);
1210 		break;
1211 
1212 	default:
1213 		SMB_PANIC();
1214 	}
1215 	smb_rwx_rwexit(&session->s_lock);
1216 }
1217