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 2019 Nexenta Systems, Inc.  All rights reserved.
  24  */
  25 
  26 #include <sys/atomic.h>
  27 #include <sys/synch.h>
  28 #include <sys/types.h>
  29 #include <sys/sdt.h>
  30 #include <sys/random.h>
  31 #include <smbsrv/netbios.h>
  32 #include <smbsrv/smb2_kproto.h>
  33 #include <smbsrv/string.h>
  34 #include <netinet/tcp.h>
  35 
  36 /* How many iovec we'll handle as a local array (no allocation) */
  37 #define SMB_LOCAL_IOV_MAX       16
  38 
  39 #define SMB_NEW_KID()   atomic_inc_64_nv(&smb_kids)
  40 
  41 static volatile uint64_t smb_kids;
  42 
  43 /*
  44  * We track the keepalive in minutes, but this constant
  45  * specifies it in seconds, so convert to minutes.
  46  */
  47 uint32_t smb_keep_alive = SMB_PI_KEEP_ALIVE_MIN / 60;
  48 
  49 /*
  50  * There are many smbtorture test cases that send
  51  * racing requests, and where the tests fail if we
  52  * don't execute them in exactly the order sent.
  53  * These are test bugs.  The protocol makes no
  54  * guarantees about execution order of requests
  55  * that are concurrently active.
  56  *
  57  * Nonetheless, smbtorture has many useful tests,
  58  * so we have this work-around we can enable to
  59  * basically force sequential execution.  When
  60  * enabled, insert a delay after each request is
  61  * issued a taskq job.  Enable this with mdb by
  62  * setting smb_reader_delay to 10.  Don't make it
  63  * more than 500 or so or the server will appear
  64  * to be so slow that tests may time out.
  65  */
  66 int smb_reader_delay = 0;  /* mSec. */
  67 
  68 static int  smbsr_newrq_initial(smb_request_t *);
  69 
  70 static void smb_session_cancel(smb_session_t *);
  71 static int smb_session_reader(smb_session_t *);
  72 static int smb_session_xprt_puthdr(smb_session_t *,
  73     uint8_t msg_type, uint32_t msg_len,
  74     uint8_t *dst, size_t dstlen);
  75 static void smb_session_disconnect_trees(smb_session_t  *);
  76 static void smb_request_init_command_mbuf(smb_request_t *sr);
  77 static void smb_session_genkey(smb_session_t *);
  78 static int smb_session_kstat_update(kstat_t *, int);
  79 void session_stats_init(smb_server_t *, smb_session_t *);
  80 void session_stats_fini(smb_session_t *);
  81 
  82 /*
  83  * This (legacy) code is in support of an "idle timeout" feature,
  84  * which is apparently incomplete.  To complete it, we should:
  85  * when the keep_alive timer expires, check whether the client
  86  * has any open files, and if not then kill their session.
  87  * Right now the timers are there, but nothing happens when
  88  * a timer expires.
  89  *
  90  * Todo: complete logic to kill idle sessions.
  91  *
  92  * Only called when sv_cfg.skc_keepalive != 0
  93  */
  94 void
  95 smb_session_timers(smb_server_t *sv)
  96 {
  97         smb_session_t   *session;
  98         smb_llist_t     *ll;
  99 
 100         ll = &sv->sv_session_list;
 101         smb_llist_enter(ll, RW_READER);
 102         session = smb_llist_head(ll);
 103         while (session != NULL) {
 104                 /*
 105                  * Walk through the table and decrement each keep_alive
 106                  * timer that has not timed out yet. (keepalive > 0)
 107                  */
 108                 SMB_SESSION_VALID(session);
 109                 if (session->keep_alive &&
 110                     (session->keep_alive != (uint32_t)-1))
 111                         session->keep_alive--;
 112 
 113                 session = smb_llist_next(ll, session);
 114         }
 115         smb_llist_exit(ll);
 116 }
 117 
 118 /*
 119  * Send a session message - supports SMB-over-NBT and SMB-over-TCP.
 120  * If an mbuf chain is provided (optional), it will be freed and
 121  * set to NULL -- unconditionally!  (error or not)
 122  *
 123  * Builds a I/O vector (uio/iov) to do the send from mbufs, plus one
 124  * segment for the 4-byte NBT header.
 125  */
 126 int
 127 smb_session_send(smb_session_t *session, uint8_t nbt_type, mbuf_chain_t *mbc)
 128 {
 129         uio_t           uio;
 130         iovec_t         local_iov[SMB_LOCAL_IOV_MAX];
 131         iovec_t         *alloc_iov = NULL;
 132         int             alloc_sz = 0;
 133         mbuf_t          *m;
 134         uint8_t         nbt_hdr[NETBIOS_HDR_SZ];
 135         uint32_t        nbt_len;
 136         int             i, nseg;
 137         int             rc;
 138 
 139         switch (session->s_state) {
 140         case SMB_SESSION_STATE_DISCONNECTED:
 141         case SMB_SESSION_STATE_TERMINATED:
 142                 rc = ENOTCONN;
 143                 goto out;
 144         default:
 145                 break;
 146         }
 147 
 148         /*
 149          * Setup the IOV.  First, count the number of IOV segments
 150          * (plus one for the NBT header) and decide whether we
 151          * need to allocate an iovec or can use local_iov;
 152          */
 153         bzero(&uio, sizeof (uio));
 154         nseg = 1;
 155         m = (mbc != NULL) ? mbc->chain : NULL;
 156         while (m != NULL) {
 157                 nseg++;
 158                 m = m->m_next;
 159         }
 160         if (nseg <= SMB_LOCAL_IOV_MAX) {
 161                 uio.uio_iov = local_iov;
 162         } else {
 163                 alloc_sz = nseg * sizeof (iovec_t);
 164                 alloc_iov = kmem_alloc(alloc_sz, KM_SLEEP);
 165                 uio.uio_iov = alloc_iov;
 166         }
 167         uio.uio_iovcnt = nseg;
 168         uio.uio_segflg = UIO_SYSSPACE;
 169         uio.uio_extflg = UIO_COPY_DEFAULT;
 170 
 171         /*
 172          * Build the iov list, meanwhile computing the length of
 173          * the SMB payload (to put in the NBT header).
 174          */
 175         uio.uio_iov[0].iov_base = (void *)nbt_hdr;
 176         uio.uio_iov[0].iov_len = sizeof (nbt_hdr);
 177         i = 1;
 178         nbt_len = 0;
 179         m = (mbc != NULL) ? mbc->chain : NULL;
 180         while (m != NULL) {
 181                 uio.uio_iov[i].iov_base = m->m_data;
 182                 uio.uio_iov[i++].iov_len = m->m_len;
 183                 nbt_len += m->m_len;
 184                 m = m->m_next;
 185         }
 186         ASSERT3S(i, ==, nseg);
 187 
 188         /*
 189          * Set the NBT header, set uio_resid
 190          */
 191         uio.uio_resid = nbt_len + NETBIOS_HDR_SZ;
 192         rc = smb_session_xprt_puthdr(session, nbt_type, nbt_len,
 193             nbt_hdr, NETBIOS_HDR_SZ);
 194         if (rc != 0)
 195                 goto out;
 196 
 197         smb_server_add_txb(session->s_server, (int64_t)uio.uio_resid);
 198         rc = smb_net_send_uio(session, &uio);
 199 
 200 out:
 201         if (alloc_iov != NULL)
 202                 kmem_free(alloc_iov, alloc_sz);
 203         if ((mbc != NULL) && (mbc->chain != NULL)) {
 204                 m_freem(mbc->chain);
 205                 mbc->chain = NULL;
 206                 mbc->flags = 0;
 207         }
 208         return (rc);
 209 }
 210 
 211 /*
 212  * Read, process and respond to a NetBIOS session request.
 213  *
 214  * A NetBIOS session must be established for SMB-over-NetBIOS.  Validate
 215  * the calling and called name format and save the client NetBIOS name,
 216  * which is used when a NetBIOS session is established to check for and
 217  * cleanup leftover state from a previous session.
 218  *
 219  * Session requests are not valid for SMB-over-TCP, which is unfortunate
 220  * because without the client name leftover state cannot be cleaned up
 221  * if the client is behind a NAT server.
 222  */
 223 static int
 224 smb_netbios_session_request(struct smb_session *session)
 225 {
 226         int                     rc;
 227         char                    *calling_name;
 228         char                    *called_name;
 229         char                    client_name[NETBIOS_NAME_SZ];
 230         struct mbuf_chain       mbc;
 231         char                    *names = NULL;
 232         smb_wchar_t             *wbuf = NULL;
 233         smb_xprt_t              hdr;
 234         char *p;
 235         int rc1, rc2;
 236 
 237         session->keep_alive = smb_keep_alive;
 238 
 239         if ((rc = smb_session_xprt_gethdr(session, &hdr)) != 0)
 240                 return (rc);
 241 
 242         DTRACE_PROBE2(receive__session__req__xprthdr, struct session *, session,
 243             smb_xprt_t *, &hdr);
 244 
 245         if ((hdr.xh_type != SESSION_REQUEST) ||
 246             (hdr.xh_length != NETBIOS_SESSION_REQUEST_DATA_LENGTH)) {
 247                 DTRACE_PROBE1(receive__session__req__failed,
 248                     struct session *, session);
 249                 return (EINVAL);
 250         }
 251 
 252         names = kmem_alloc(hdr.xh_length, KM_SLEEP);
 253 
 254         if ((rc = smb_sorecv(session->sock, names, hdr.xh_length)) != 0) {
 255                 kmem_free(names, hdr.xh_length);
 256                 DTRACE_PROBE1(receive__session__req__failed,
 257                     struct session *, session);
 258                 return (rc);
 259         }
 260 
 261         DTRACE_PROBE3(receive__session__req__data, struct session *, session,
 262             char *, names, uint32_t, hdr.xh_length);
 263 
 264         called_name = &names[0];
 265         calling_name = &names[NETBIOS_ENCODED_NAME_SZ + 2];
 266 
 267         rc1 = netbios_name_isvalid(called_name, 0);
 268         rc2 = netbios_name_isvalid(calling_name, client_name);
 269 
 270         if (rc1 == 0 || rc2 == 0) {
 271 
 272                 DTRACE_PROBE3(receive__invalid__session__req,
 273                     struct session *, session, char *, names,
 274                     uint32_t, hdr.xh_length);
 275 
 276                 kmem_free(names, hdr.xh_length);
 277                 MBC_INIT(&mbc, MAX_DATAGRAM_LENGTH);
 278                 (void) smb_mbc_encodef(&mbc, "b",
 279                     DATAGRAM_INVALID_SOURCE_NAME_FORMAT);
 280                 (void) smb_session_send(session, NEGATIVE_SESSION_RESPONSE,
 281                     &mbc);
 282                 return (EINVAL);
 283         }
 284 
 285         DTRACE_PROBE3(receive__session__req__calling__decoded,
 286             struct session *, session,
 287             char *, calling_name, char *, client_name);
 288 
 289         /*
 290          * The client NetBIOS name is in oem codepage format.
 291          * We need to convert it to unicode and store it in
 292          * multi-byte format.  We also need to strip off any
 293          * spaces added as part of the NetBIOS name encoding.
 294          */
 295         wbuf = kmem_alloc((SMB_PI_MAX_HOST * sizeof (smb_wchar_t)), KM_SLEEP);
 296         (void) oemtoucs(wbuf, client_name, SMB_PI_MAX_HOST, OEM_CPG_850);
 297         (void) smb_wcstombs(session->workstation, wbuf, SMB_PI_MAX_HOST);
 298         kmem_free(wbuf, (SMB_PI_MAX_HOST * sizeof (smb_wchar_t)));
 299 
 300         if ((p = strchr(session->workstation, ' ')) != 0)
 301                 *p = '\0';
 302 
 303         kmem_free(names, hdr.xh_length);
 304         return (smb_session_send(session, POSITIVE_SESSION_RESPONSE, NULL));
 305 }
 306 
 307 /*
 308  * Read 4-byte header from the session socket and build an in-memory
 309  * session transport header.  See smb_xprt_t definition for header
 310  * format information.
 311  *
 312  * Direct hosted NetBIOS-less SMB (SMB-over-TCP) uses port 445.  The
 313  * first byte of the four-byte header must be 0 and the next three
 314  * bytes contain the length of the remaining data.
 315  */
 316 int
 317 smb_session_xprt_gethdr(smb_session_t *session, smb_xprt_t *ret_hdr)
 318 {
 319         int             rc;
 320         unsigned char   buf[NETBIOS_HDR_SZ];
 321 
 322         if ((rc = smb_sorecv(session->sock, buf, NETBIOS_HDR_SZ)) != 0)
 323                 return (rc);
 324 
 325         switch (session->s_local_port) {
 326         case IPPORT_NETBIOS_SSN:
 327                 ret_hdr->xh_type = buf[0];
 328                 ret_hdr->xh_length = (((uint32_t)buf[1] & 1) << 16) |
 329                     ((uint32_t)buf[2] << 8) |
 330                     ((uint32_t)buf[3]);
 331                 break;
 332 
 333         case IPPORT_SMB:
 334                 ret_hdr->xh_type = buf[0];
 335 
 336                 if (ret_hdr->xh_type != 0) {
 337                         cmn_err(CE_WARN, "invalid NBT type (%u) from %s",
 338                             ret_hdr->xh_type, session->ip_addr_str);
 339                         return (EPROTO);
 340                 }
 341 
 342                 ret_hdr->xh_length = ((uint32_t)buf[1] << 16) |
 343                     ((uint32_t)buf[2] << 8) |
 344                     ((uint32_t)buf[3]);
 345                 break;
 346 
 347         default:
 348                 cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
 349                 return (EPROTO);
 350         }
 351 
 352         return (0);
 353 }
 354 
 355 /*
 356  * Encode a transport session packet header into a 4-byte buffer.
 357  */
 358 static int
 359 smb_session_xprt_puthdr(smb_session_t *session,
 360     uint8_t msg_type, uint32_t msg_length,
 361     uint8_t *buf, size_t buflen)
 362 {
 363         if (buf == NULL || buflen < NETBIOS_HDR_SZ) {
 364                 return (-1);
 365         }
 366 
 367         switch (session->s_local_port) {
 368         case IPPORT_NETBIOS_SSN:
 369                 /* Per RFC 1001, 1002: msg. len < 128KB */
 370                 if (msg_length >= (1 << 17))
 371                         return (-1);
 372                 buf[0] = msg_type;
 373                 buf[1] = ((msg_length >> 16) & 1);
 374                 buf[2] = (msg_length >> 8) & 0xff;
 375                 buf[3] = msg_length & 0xff;
 376                 break;
 377 
 378         case IPPORT_SMB:
 379                 /*
 380                  * SMB over TCP is like NetBIOS but the one byte
 381                  * message type is always zero, and the length
 382                  * part is three bytes.  It could actually use
 383                  * longer messages, but this is conservative.
 384                  */
 385                 if (msg_length >= (1 << 24))
 386                         return (-1);
 387                 buf[0] = msg_type;
 388                 buf[1] = (msg_length >> 16) & 0xff;
 389                 buf[2] = (msg_length >> 8) & 0xff;
 390                 buf[3] = msg_length & 0xff;
 391                 break;
 392 
 393         default:
 394                 cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
 395                 return (-1);
 396         }
 397 
 398         return (0);
 399 }
 400 
 401 static void
 402 smb_request_init_command_mbuf(smb_request_t *sr)
 403 {
 404 
 405         /*
 406          * Setup mbuf using the buffer we allocated.
 407          */
 408         MBC_ATTACH_BUF(&sr->command, sr->sr_request_buf, sr->sr_req_length);
 409 
 410         sr->command.flags = 0;
 411         sr->command.shadow_of = NULL;
 412 }
 413 
 414 /*
 415  * smb_request_cancel
 416  *
 417  * Handle a cancel for a request properly depending on the current request
 418  * state.
 419  */
 420 void
 421 smb_request_cancel(smb_request_t *sr)
 422 {
 423         void (*cancel_method)(smb_request_t *) = NULL;
 424 
 425         mutex_enter(&sr->sr_mutex);
 426         switch (sr->sr_state) {
 427 
 428         case SMB_REQ_STATE_INITIALIZING:
 429         case SMB_REQ_STATE_SUBMITTED:
 430         case SMB_REQ_STATE_ACTIVE:
 431         case SMB_REQ_STATE_CLEANED_UP:
 432                 sr->sr_state = SMB_REQ_STATE_CANCELLED;
 433                 break;
 434 
 435         case SMB_REQ_STATE_WAITING_AUTH:
 436         case SMB_REQ_STATE_WAITING_FCN1:
 437         case SMB_REQ_STATE_WAITING_LOCK:
 438         case SMB_REQ_STATE_WAITING_PIPE:
 439                 /*
 440                  * These are states that have a cancel_method.
 441                  * Make the state change now, to ensure that
 442                  * we call cancel_method exactly once.  Do the
 443                  * method call below, after we drop sr_mutex.
 444                  * When the cancelled request thread resumes,
 445                  * it should re-take sr_mutex and set sr_state
 446                  * to CANCELLED, then return STATUS_CANCELLED.
 447                  */
 448                 sr->sr_state = SMB_REQ_STATE_CANCEL_PENDING;
 449                 cancel_method = sr->cancel_method;
 450                 VERIFY(cancel_method != NULL);
 451                 break;
 452 
 453         case SMB_REQ_STATE_WAITING_FCN2:
 454         case SMB_REQ_STATE_COMPLETED:
 455         case SMB_REQ_STATE_CANCEL_PENDING:
 456         case SMB_REQ_STATE_CANCELLED:
 457                 /*
 458                  * No action required for these states since the request
 459                  * is completing.
 460                  */
 461                 break;
 462 
 463         case SMB_REQ_STATE_FREE:
 464         default:
 465                 SMB_PANIC();
 466         }
 467         mutex_exit(&sr->sr_mutex);
 468 
 469         if (cancel_method != NULL) {
 470                 cancel_method(sr);
 471         }
 472 }
 473 
 474 /*
 475  * smb_session_receiver
 476  *
 477  * Receives request from the network and dispatches them to a worker.
 478  *
 479  * When we receive a disconnect here, it _could_ be due to the server
 480  * having initiated disconnect, in which case the session state will be
 481  * SMB_SESSION_STATE_TERMINATED and we want to keep that state so later
 482  * tear-down logic will know which side initiated.
 483  */
 484 void
 485 smb_session_receiver(smb_session_t *session)
 486 {
 487         int     rc = 0;
 488 
 489         SMB_SESSION_VALID(session);
 490 
 491         session->s_thread = curthread;
 492 
 493         if (session->s_local_port == IPPORT_NETBIOS_SSN) {
 494                 rc = smb_netbios_session_request(session);
 495                 if (rc != 0) {
 496                         smb_rwx_rwenter(&session->s_lock, RW_WRITER);
 497                         if (session->s_state != SMB_SESSION_STATE_TERMINATED)
 498                                 session->s_state =
 499                                     SMB_SESSION_STATE_DISCONNECTED;
 500                         smb_rwx_rwexit(&session->s_lock);
 501                         return;
 502                 }
 503         }
 504 
 505         smb_rwx_rwenter(&session->s_lock, RW_WRITER);
 506         session->s_state = SMB_SESSION_STATE_ESTABLISHED;
 507         smb_rwx_rwexit(&session->s_lock);
 508 
 509         (void) smb_session_reader(session);
 510 
 511         smb_rwx_rwenter(&session->s_lock, RW_WRITER);
 512         if (session->s_state != SMB_SESSION_STATE_TERMINATED)
 513                 session->s_state = SMB_SESSION_STATE_DISCONNECTED;
 514         smb_rwx_rwexit(&session->s_lock);
 515 
 516         smb_soshutdown(session->sock);
 517 
 518         DTRACE_PROBE2(session__drop, struct session *, session, int, rc);
 519 
 520         smb_session_cancel(session);
 521         /*
 522          * At this point everything related to the session should have been
 523          * cleaned up and we expect that nothing will attempt to use the
 524          * socket.
 525          */
 526 }
 527 
 528 /*
 529  * smb_session_disconnect
 530  *
 531  * Server-initiated disconnect (i.e. server shutdown)
 532  */
 533 void
 534 smb_session_disconnect(smb_session_t *session)
 535 {
 536         SMB_SESSION_VALID(session);
 537 
 538         smb_rwx_rwenter(&session->s_lock, RW_WRITER);
 539         switch (session->s_state) {
 540         case SMB_SESSION_STATE_INITIALIZED:
 541         case SMB_SESSION_STATE_CONNECTED:
 542         case SMB_SESSION_STATE_ESTABLISHED:
 543         case SMB_SESSION_STATE_NEGOTIATED:
 544                 smb_soshutdown(session->sock);
 545                 session->s_state = SMB_SESSION_STATE_TERMINATED;
 546                 break;
 547         case SMB_SESSION_STATE_DISCONNECTED:
 548         case SMB_SESSION_STATE_TERMINATED:
 549                 break;
 550         }
 551         smb_rwx_rwexit(&session->s_lock);
 552 }
 553 
 554 /*
 555  * Read and process SMB requests.
 556  *
 557  * Returns:
 558  *      0       Success
 559  *      1       Unable to read transport header
 560  *      2       Invalid transport header type
 561  *      3       Invalid SMB length (too small)
 562  *      4       Unable to read SMB header
 563  *      5       Invalid SMB header (bad magic number)
 564  *      6       Unable to read SMB data
 565  */
 566 static int
 567 smb_session_reader(smb_session_t *session)
 568 {
 569         smb_server_t    *sv;
 570         smb_request_t   *sr = NULL;
 571         smb_xprt_t      hdr;
 572         uint8_t         *req_buf;
 573         uint32_t        resid;
 574         int             rc;
 575 
 576         sv = session->s_server;
 577 
 578         for (;;) {
 579 
 580                 rc = smb_session_xprt_gethdr(session, &hdr);
 581                 if (rc)
 582                         return (rc);
 583 
 584                 DTRACE_PROBE2(session__receive__xprthdr, session_t *, session,
 585                     smb_xprt_t *, &hdr);
 586 
 587                 if (hdr.xh_type != SESSION_MESSAGE) {
 588                         /*
 589                          * Anything other than SESSION_MESSAGE or
 590                          * SESSION_KEEP_ALIVE is an error.  A SESSION_REQUEST
 591                          * may indicate a new session request but we need to
 592                          * close this session and we can treat it as an error
 593                          * here.
 594                          */
 595                         if (hdr.xh_type == SESSION_KEEP_ALIVE) {
 596                                 session->keep_alive = smb_keep_alive;
 597                                 continue;
 598                         }
 599                         return (EPROTO);
 600                 }
 601 
 602                 if (hdr.xh_length == 0) {
 603                         /* zero length is another form of keep alive */
 604                         session->keep_alive = smb_keep_alive;
 605                         continue;
 606                 }
 607 
 608                 if (hdr.xh_length < SMB_HEADER_LEN)
 609                         return (EPROTO);
 610                 if (hdr.xh_length > session->cmd_max_bytes)
 611                         return (EPROTO);
 612 
 613                 session->keep_alive = smb_keep_alive;
 614 
 615                 /*
 616                  * Allocate a request context, read the whole message.
 617                  * If the request alloc fails, we've disconnected
 618                  * and won't be able to send the reply anyway, so bail now.
 619                  */
 620                 if ((sr = smb_request_alloc(session, hdr.xh_length)) == NULL)
 621                         break;
 622 
 623                 req_buf = (uint8_t *)sr->sr_request_buf;
 624                 resid = hdr.xh_length;
 625 
 626                 rc = smb_sorecv(session->sock, req_buf, resid);
 627                 if (rc) {
 628                         smb_request_free(sr);
 629                         break;
 630                 }
 631 
 632                 /* accounting: received bytes */
 633                 smb_server_add_rxb(sv,
 634                     (int64_t)(hdr.xh_length + NETBIOS_HDR_SZ));
 635 
 636                 /*
 637                  * Initialize command MBC to represent the received data.
 638                  */
 639                 smb_request_init_command_mbuf(sr);
 640 
 641                 DTRACE_PROBE1(session__receive__smb, smb_request_t *, sr);
 642 
 643                 rc = session->newrq_func(sr);
 644                 sr = NULL;      /* enqueued or freed */
 645                 if (rc != 0)
 646                         break;
 647 
 648                 /* See notes where this is defined (above). */
 649                 if (smb_reader_delay) {
 650                         delay(MSEC_TO_TICK(smb_reader_delay));
 651                 }
 652         }
 653         return (rc);
 654 }
 655 
 656 /*
 657  * This is the initial handler for new smb requests, called from
 658  * from smb_session_reader when we have not yet seen any requests.
 659  * The first SMB request must be "negotiate", which determines
 660  * which protocol and dialect we'll be using.  That's the ONLY
 661  * request type handled here, because with all later requests,
 662  * we know the protocol and handle those with either the SMB1 or
 663  * SMB2 handlers:  smb1sr_post() or smb2sr_post().
 664  * Those do NOT allow SMB negotiate, because that's only allowed
 665  * as the first request on new session.
 666  *
 667  * This and other "post a request" handlers must either enqueue
 668  * the new request for the session taskq, or smb_request_free it
 669  * (in case we've decided to drop this connection).  In this
 670  * (special) new request handler, we always free the request.
 671  *
 672  * Return value is 0 for success, and anything else will
 673  * terminate the reader thread (drop the connection).
 674  */
 675 static int
 676 smbsr_newrq_initial(smb_request_t *sr)
 677 {
 678         uint32_t magic;
 679         int rc = EPROTO;
 680 
 681         mutex_enter(&sr->sr_mutex);
 682         sr->sr_state = SMB_REQ_STATE_ACTIVE;
 683         mutex_exit(&sr->sr_mutex);
 684 
 685         magic = SMB_READ_PROTOCOL(sr->sr_request_buf);
 686         if (magic == SMB_PROTOCOL_MAGIC)
 687                 rc = smb1_newrq_negotiate(sr);
 688         if (magic == SMB2_PROTOCOL_MAGIC)
 689                 rc = smb2_newrq_negotiate(sr);
 690 
 691         mutex_enter(&sr->sr_mutex);
 692         sr->sr_state = SMB_REQ_STATE_COMPLETED;
 693         mutex_exit(&sr->sr_mutex);
 694 
 695         smb_request_free(sr);
 696         return (rc);
 697 }
 698 
 699 /*
 700  * Port will be IPPORT_NETBIOS_SSN or IPPORT_SMB.
 701  */
 702 smb_session_t *
 703 smb_session_create(ksocket_t new_so, uint16_t port, smb_server_t *sv,
 704     int family)
 705 {
 706         struct sockaddr_in      sin;
 707         socklen_t               slen;
 708         struct sockaddr_in6     sin6;
 709         smb_session_t           *session;
 710         int64_t                 now;
 711         uint16_t                rport;
 712 
 713         session = kmem_cache_alloc(smb_cache_session, KM_SLEEP);
 714         bzero(session, sizeof (smb_session_t));
 715 
 716         if (smb_idpool_constructor(&session->s_uid_pool)) {
 717                 kmem_cache_free(smb_cache_session, session);
 718                 return (NULL);
 719         }
 720         if (smb_idpool_constructor(&session->s_tid_pool)) {
 721                 smb_idpool_destructor(&session->s_uid_pool);
 722                 kmem_cache_free(smb_cache_session, session);
 723                 return (NULL);
 724         }
 725 
 726         now = ddi_get_lbolt64();
 727 
 728         session->s_server = sv;
 729         session->s_kid = SMB_NEW_KID();
 730         session->s_state = SMB_SESSION_STATE_INITIALIZED;
 731         session->native_os = NATIVE_OS_UNKNOWN;
 732         session->opentime = now;
 733         session->keep_alive = smb_keep_alive;
 734         session->activity_timestamp = now;
 735         smb_session_genkey(session);
 736 
 737         mutex_init(&session->s_credits_mutex, NULL, MUTEX_DEFAULT, NULL);
 738 
 739         smb_slist_constructor(&session->s_req_list, sizeof (smb_request_t),
 740             offsetof(smb_request_t, sr_session_lnd));
 741 
 742         smb_llist_constructor(&session->s_user_list, sizeof (smb_user_t),
 743             offsetof(smb_user_t, u_lnd));
 744 
 745         smb_llist_constructor(&session->s_tree_list, sizeof (smb_tree_t),
 746             offsetof(smb_tree_t, t_lnd));
 747 
 748         smb_llist_constructor(&session->s_xa_list, sizeof (smb_xa_t),
 749             offsetof(smb_xa_t, xa_lnd));
 750 
 751         smb_net_txl_constructor(&session->s_txlst);
 752 
 753         smb_rwx_init(&session->s_lock);
 754 
 755         session->s_srqueue = &sv->sv_srqueue;
 756         smb_server_get_cfg(sv, &session->s_cfg);
 757 
 758         if (new_so == NULL) {
 759                 /*
 760                  * This call is creating the special "server" session,
 761                  * used for kshare export, oplock breaks, CA import.
 762                  * CA import creates temporary trees on this session
 763                  * and those should never get map/unmap up-calls, so
 764                  * force the map/unmap flags zero on this session.
 765                  * Set a "modern" dialect for CA import too, so
 766                  * pathname parse doesn't do OS/2 stuff, etc.
 767                  */
 768                 session->s_cfg.skc_execflags = 0;
 769                 session->dialect = session->s_cfg.skc_max_protocol;
 770         } else {
 771                 if (family == AF_INET) {
 772                         slen = sizeof (sin);
 773                         (void) ksocket_getsockname(new_so,
 774                             (struct sockaddr *)&sin, &slen, CRED());
 775                         bcopy(&sin.sin_addr,
 776                             &session->local_ipaddr.au_addr.au_ipv4,
 777                             sizeof (in_addr_t));
 778                         slen = sizeof (sin);
 779                         (void) ksocket_getpeername(new_so,
 780                             (struct sockaddr *)&sin, &slen, CRED());
 781                         bcopy(&sin.sin_addr,
 782                             &session->ipaddr.au_addr.au_ipv4,
 783                             sizeof (in_addr_t));
 784                         rport = sin.sin_port;
 785                 } else {
 786                         slen = sizeof (sin6);
 787                         (void) ksocket_getsockname(new_so,
 788                             (struct sockaddr *)&sin6, &slen, CRED());
 789                         bcopy(&sin6.sin6_addr,
 790                             &session->local_ipaddr.au_addr.au_ipv6,
 791                             sizeof (in6_addr_t));
 792                         slen = sizeof (sin6);
 793                         (void) ksocket_getpeername(new_so,
 794                             (struct sockaddr *)&sin6, &slen, CRED());
 795                         bcopy(&sin6.sin6_addr,
 796                             &session->ipaddr.au_addr.au_ipv6,
 797                             sizeof (in6_addr_t));
 798                         rport = sin6.sin6_port;
 799                 }
 800                 session->ipaddr.a_family = family;
 801                 session->local_ipaddr.a_family = family;
 802                 session->s_local_port = port;
 803                 session->s_remote_port = ntohs(rport);
 804                 session->sock = new_so;
 805                 (void) smb_inet_ntop(&session->ipaddr,
 806                     session->ip_addr_str, INET6_ADDRSTRLEN);
 807                 if (port == IPPORT_NETBIOS_SSN)
 808                         smb_server_inc_nbt_sess(sv);
 809                 else
 810                         smb_server_inc_tcp_sess(sv);
 811         }
 812 
 813         /*
 814          * The initial new request handler is special,
 815          * and only accepts negotiation requests.
 816          */
 817         session->newrq_func = smbsr_newrq_initial;
 818 
 819         /* These may increase in SMB2 negotiate. */
 820         session->cmd_max_bytes = SMB_REQ_MAX_SIZE;
 821         session->reply_max_bytes = SMB_REQ_MAX_SIZE;
 822 
 823         session_stats_init(sv, session);
 824 
 825         session->s_magic = SMB_SESSION_MAGIC;
 826 
 827         return (session);
 828 }
 829 
 830 void
 831 session_stats_init(smb_server_t *sv, smb_session_t *ss)
 832 {
 833         static const char       *kr_names[] = SMBSRV_CLSH__NAMES;
 834         char                    ks_name[KSTAT_STRLEN];
 835         char                    *ipaddr_str = ss->ip_addr_str;
 836         smbsrv_clsh_kstats_t    *ksr;
 837         int                     idx;
 838 
 839         /* Don't include the special internal session (sv->sv_session). */
 840         if (ss->sock == NULL)
 841                 return;
 842 
 843         /*
 844          * If ipv6_enable is set to true, IPv4 addresses will be prefixed
 845          * with ::ffff: (IPv4-mapped IPv6 address), strip it.
 846          */
 847         if (strncasecmp(ipaddr_str, "::ffff:", 7) == 0)
 848                 ipaddr_str += 7;
 849 
 850         /*
 851          * Create raw kstats for sessions with a name composed as:
 852          * cl/$IPADDR  and instance ss->s_kid
 853          * These will look like: smbsrv:0:cl/10.10.0.5
 854          */
 855         (void) snprintf(ks_name, sizeof (ks_name), "cl/%s", ipaddr_str);
 856 
 857         ss->s_ksp = kstat_create_zone(SMBSRV_KSTAT_MODULE, ss->s_kid,
 858             ks_name, SMBSRV_KSTAT_CLASS, KSTAT_TYPE_RAW,
 859             sizeof (smbsrv_clsh_kstats_t), 0, sv->sv_zid);
 860 
 861         if (ss->s_ksp == NULL)
 862                 return;
 863 
 864         ss->s_ksp->ks_update = smb_session_kstat_update;
 865         ss->s_ksp->ks_private = ss;
 866 
 867         /*
 868          * In-line equivalent of smb_dispatch_stats_init
 869          */
 870         ksr = (smbsrv_clsh_kstats_t *)ss->s_ksp->ks_data;
 871         for (idx = 0; idx < SMBSRV_CLSH__NREQ; idx++) {
 872                 smb_latency_init(&ss->s_stats[idx].sdt_lat);
 873                 (void) strlcpy(ksr->ks_clsh[idx].kr_name, kr_names[idx],
 874                     KSTAT_STRLEN);
 875         }
 876 
 877         kstat_install(ss->s_ksp);
 878 }
 879 
 880 void
 881 session_stats_fini(smb_session_t *ss)
 882 {
 883         int     idx;
 884 
 885         for (idx = 0; idx < SMBSRV_CLSH__NREQ; idx++)
 886                 smb_latency_destroy(&ss->s_stats[idx].sdt_lat);
 887 }
 888 
 889 /*
 890  * Update the kstat data from our private stats.
 891  */
 892 static int
 893 smb_session_kstat_update(kstat_t *ksp, int rw)
 894 {
 895         smb_session_t *session;
 896         smb_disp_stats_t *sds;
 897         smbsrv_clsh_kstats_t    *clsh;
 898         smb_kstat_req_t *ksr;
 899         int i;
 900 
 901         if (rw == KSTAT_WRITE)
 902                 return (EACCES);
 903 
 904         session = ksp->ks_private;
 905         SMB_SESSION_VALID(session);
 906         sds = session->s_stats;
 907 
 908         clsh = (smbsrv_clsh_kstats_t *)ksp->ks_data;
 909         ksr = clsh->ks_clsh;
 910 
 911         for (i = 0; i < SMBSRV_CLSH__NREQ; i++, ksr++, sds++) {
 912                 ksr->kr_rxb = sds->sdt_rxb;
 913                 ksr->kr_txb = sds->sdt_txb;
 914                 mutex_enter(&sds->sdt_lat.ly_mutex);
 915                 ksr->kr_nreq = sds->sdt_lat.ly_a_nreq;
 916                 ksr->kr_sum = sds->sdt_lat.ly_a_sum;
 917                 ksr->kr_a_mean = sds->sdt_lat.ly_a_mean;
 918                 ksr->kr_a_stddev = sds->sdt_lat.ly_a_stddev;
 919                 ksr->kr_d_mean = sds->sdt_lat.ly_d_mean;
 920                 ksr->kr_d_stddev = sds->sdt_lat.ly_d_stddev;
 921                 sds->sdt_lat.ly_d_mean = 0;
 922                 sds->sdt_lat.ly_d_nreq = 0;
 923                 sds->sdt_lat.ly_d_stddev = 0;
 924                 sds->sdt_lat.ly_d_sum = 0;
 925                 mutex_exit(&sds->sdt_lat.ly_mutex);
 926         }
 927 
 928         return (0);
 929 }
 930 
 931 void
 932 smb_session_delete(smb_session_t *session)
 933 {
 934 
 935         ASSERT(session->s_magic == SMB_SESSION_MAGIC);
 936 
 937         if (session->s_ksp != NULL) {
 938                 kstat_delete(session->s_ksp);
 939                 session->s_ksp = NULL;
 940                 session_stats_fini(session);
 941         }
 942 
 943         if (session->enc_mech != NULL)
 944                 smb3_encrypt_fini(session);
 945 
 946         if (session->sign_fini != NULL)
 947                 session->sign_fini(session);
 948 
 949         if (session->signing.mackey != NULL) {
 950                 kmem_free(session->signing.mackey,
 951                     session->signing.mackey_len);
 952         }
 953 
 954         session->s_magic = 0;
 955 
 956         smb_rwx_destroy(&session->s_lock);
 957         smb_net_txl_destructor(&session->s_txlst);
 958 
 959         mutex_destroy(&session->s_credits_mutex);
 960 
 961         smb_slist_destructor(&session->s_req_list);
 962         smb_llist_destructor(&session->s_tree_list);
 963         smb_llist_destructor(&session->s_user_list);
 964         smb_llist_destructor(&session->s_xa_list);
 965 
 966         ASSERT(session->s_tree_cnt == 0);
 967         ASSERT(session->s_file_cnt == 0);
 968         ASSERT(session->s_dir_cnt == 0);
 969 
 970         smb_idpool_destructor(&session->s_tid_pool);
 971         smb_idpool_destructor(&session->s_uid_pool);
 972         if (session->sock != NULL) {
 973                 if (session->s_local_port == IPPORT_NETBIOS_SSN)
 974                         smb_server_dec_nbt_sess(session->s_server);
 975                 else
 976                         smb_server_dec_tcp_sess(session->s_server);
 977                 smb_sodestroy(session->sock);
 978         }
 979         kmem_cache_free(smb_cache_session, session);
 980 }
 981 
 982 static void
 983 smb_session_cancel(smb_session_t *session)
 984 {
 985         smb_xa_t        *xa, *nextxa;
 986 
 987         /* All the request currently being treated must be canceled. */
 988         smb_session_cancel_requests(session, NULL, NULL);
 989 
 990         /*
 991          * We wait for the completion of all the requests associated with
 992          * this session.
 993          */
 994         smb_slist_wait_for_empty(&session->s_req_list);
 995 
 996         /*
 997          * Cleanup transact state objects
 998          */
 999         xa = smb_llist_head(&session->s_xa_list);
1000         while (xa) {
1001                 nextxa = smb_llist_next(&session->s_xa_list, xa);
1002                 smb_xa_close(xa);
1003                 xa = nextxa;
1004         }
1005 
1006         /*
1007          * At this point the reference count of the files and directories
1008          * should be zero. It should be possible to destroy them without
1009          * any problem, which should trigger the destruction of other objects.
1010          */
1011         smb_session_logoff(session);
1012 }
1013 
1014 /*
1015  * Cancel requests.  If a non-null tree is specified, only requests specific
1016  * to that tree will be cancelled.  If a non-null sr is specified, that sr
1017  * will be not be cancelled - this would typically be the caller's sr.
1018  */
1019 void
1020 smb_session_cancel_requests(
1021     smb_session_t       *session,
1022     smb_tree_t          *tree,
1023     smb_request_t       *exclude_sr)
1024 {
1025         smb_request_t   *sr;
1026 
1027         smb_slist_enter(&session->s_req_list);
1028         sr = smb_slist_head(&session->s_req_list);
1029 
1030         while (sr) {
1031                 ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
1032                 if ((sr != exclude_sr) &&
1033                     (tree == NULL || sr->tid_tree == tree))
1034                         smb_request_cancel(sr);
1035 
1036                 sr = smb_slist_next(&session->s_req_list, sr);
1037         }
1038 
1039         smb_slist_exit(&session->s_req_list);
1040 }
1041 
1042 /*
1043  * Find a user on the specified session by SMB UID.
1044  */
1045 smb_user_t *
1046 smb_session_lookup_uid(smb_session_t *session, uint16_t uid)
1047 {
1048         return (smb_session_lookup_uid_st(session, 0, uid,
1049             SMB_USER_STATE_LOGGED_ON));
1050 }
1051 
1052 /*
1053  * Find a user on the specified session by SMB2 SSNID.
1054  */
1055 smb_user_t *
1056 smb_session_lookup_ssnid(smb_session_t *session, uint64_t ssnid)
1057 {
1058         return (smb_session_lookup_uid_st(session, ssnid, 0,
1059             SMB_USER_STATE_LOGGED_ON));
1060 }
1061 
1062 smb_user_t *
1063 smb_session_lookup_uid_st(smb_session_t *session, uint64_t ssnid,
1064     uint16_t uid, smb_user_state_t st)
1065 {
1066         smb_user_t      *user;
1067         smb_llist_t     *user_list;
1068 
1069         SMB_SESSION_VALID(session);
1070 
1071         user_list = &session->s_user_list;
1072         smb_llist_enter(user_list, RW_READER);
1073 
1074         for (user = smb_llist_head(user_list);
1075             user != NULL;
1076             user = smb_llist_next(user_list, user)) {
1077 
1078                 SMB_USER_VALID(user);
1079                 ASSERT(user->u_session == session);
1080 
1081                 if (user->u_ssnid != ssnid && user->u_uid != uid)
1082                         continue;
1083 
1084                 mutex_enter(&user->u_mutex);
1085                 if (user->u_state == st) {
1086                         // smb_user_hold_internal(user);
1087                         user->u_refcnt++;
1088                         mutex_exit(&user->u_mutex);
1089                         break;
1090                 }
1091                 mutex_exit(&user->u_mutex);
1092         }
1093 
1094         smb_llist_exit(user_list);
1095         return (user);
1096 }
1097 
1098 /*
1099  * Find a tree by tree-id.
1100  */
1101 smb_tree_t *
1102 smb_session_lookup_tree(
1103     smb_session_t       *session,
1104     uint16_t            tid)
1105 {
1106         smb_tree_t      *tree;
1107 
1108         SMB_SESSION_VALID(session);
1109 
1110         smb_llist_enter(&session->s_tree_list, RW_READER);
1111         tree = smb_llist_head(&session->s_tree_list);
1112 
1113         while (tree) {
1114                 ASSERT3U(tree->t_magic, ==, SMB_TREE_MAGIC);
1115                 ASSERT(tree->t_session == session);
1116 
1117                 if (tree->t_tid == tid) {
1118                         if (smb_tree_hold(tree)) {
1119                                 smb_llist_exit(&session->s_tree_list);
1120                                 return (tree);
1121                         } else {
1122                                 smb_llist_exit(&session->s_tree_list);
1123                                 return (NULL);
1124                         }
1125                 }
1126 
1127                 tree = smb_llist_next(&session->s_tree_list, tree);
1128         }
1129 
1130         smb_llist_exit(&session->s_tree_list);
1131         return (NULL);
1132 }
1133 
1134 /*
1135  * Disconnect all trees that match the specified client process-id.
1136  * Used by the SMB1 "process exit" request.
1137  */
1138 void
1139 smb_session_close_pid(
1140     smb_session_t       *session,
1141     uint32_t            pid)
1142 {
1143         smb_llist_t     *tree_list = &session->s_tree_list;
1144         smb_tree_t      *tree;
1145 
1146         smb_llist_enter(tree_list, RW_READER);
1147 
1148         tree = smb_llist_head(tree_list);
1149         while (tree) {
1150                 if (smb_tree_hold(tree)) {
1151                         smb_tree_close_pid(tree, pid);
1152                         smb_tree_release(tree);
1153                 }
1154                 tree = smb_llist_next(tree_list, tree);
1155         }
1156 
1157         smb_llist_exit(tree_list);
1158 }
1159 
1160 static void
1161 smb_session_tree_dtor(void *arg)
1162 {
1163         smb_tree_t      *tree = arg;
1164 
1165         smb_tree_disconnect(tree, B_TRUE);
1166         /* release the ref acquired during the traversal loop */
1167         smb_tree_release(tree);
1168 }
1169 
1170 
1171 /*
1172  * Disconnect all trees that this user has connected.
1173  */
1174 void
1175 smb_session_disconnect_owned_trees(
1176     smb_session_t       *session,
1177     smb_user_t          *owner)
1178 {
1179         smb_tree_t      *tree;
1180         smb_llist_t     *tree_list = &session->s_tree_list;
1181 
1182         SMB_SESSION_VALID(session);
1183         SMB_USER_VALID(owner);
1184 
1185         smb_llist_enter(tree_list, RW_READER);
1186 
1187         tree = smb_llist_head(tree_list);
1188         while (tree) {
1189                 if ((tree->t_owner == owner) &&
1190                     smb_tree_hold(tree)) {
1191                         /*
1192                          * smb_tree_hold() succeeded, hence we are in state
1193                          * SMB_TREE_STATE_CONNECTED; schedule this tree
1194                          * for disconnect after smb_llist_exit because
1195                          * the "unmap exec" up-call can block, and we'd
1196                          * rather not block with the tree list locked.
1197                          */
1198                         smb_llist_post(tree_list, tree, smb_session_tree_dtor);
1199                 }
1200                 tree = smb_llist_next(tree_list, tree);
1201         }
1202 
1203         /* drop the lock and flush the dtor queue */
1204         smb_llist_exit(tree_list);
1205 }
1206 
1207 /*
1208  * Disconnect all trees that this user has connected.
1209  */
1210 static void
1211 smb_session_disconnect_trees(
1212     smb_session_t       *session)
1213 {
1214         smb_llist_t     *tree_list = &session->s_tree_list;
1215         smb_tree_t      *tree;
1216 
1217         smb_llist_enter(tree_list, RW_READER);
1218 
1219         tree = smb_llist_head(tree_list);
1220         while (tree) {
1221                 if (smb_tree_hold(tree)) {
1222                         smb_llist_post(tree_list, tree,
1223                             smb_session_tree_dtor);
1224                 }
1225                 tree = smb_llist_next(tree_list, tree);
1226         }
1227 
1228         /* drop the lock and flush the dtor queue */
1229         smb_llist_exit(tree_list);
1230 }
1231 
1232 /*
1233  * Variant of smb_session_tree_dtor that also
1234  * cancels requests using this tree.
1235  */
1236 static void
1237 smb_session_tree_kill(void *arg)
1238 {
1239         smb_tree_t      *tree = arg;
1240 
1241         SMB_TREE_VALID(tree);
1242 
1243         smb_tree_disconnect(tree, B_TRUE);
1244         smb_session_cancel_requests(tree->t_session, tree, NULL);
1245 
1246         /* release the ref acquired during the traversal loop */
1247         smb_tree_release(tree);
1248 }
1249 
1250 /*
1251  * Disconnect all trees that match the specified share name,
1252  * and kill requests using those trees.
1253  */
1254 void
1255 smb_session_disconnect_share(
1256     smb_session_t       *session,
1257     const char          *sharename)
1258 {
1259         smb_llist_t     *ll;
1260         smb_tree_t      *tree;
1261 
1262         SMB_SESSION_VALID(session);
1263 
1264         ll = &session->s_tree_list;
1265         smb_llist_enter(ll, RW_READER);
1266 
1267         for (tree = smb_llist_head(ll);
1268             tree != NULL;
1269             tree = smb_llist_next(ll, tree)) {
1270 
1271                 SMB_TREE_VALID(tree);
1272                 ASSERT(tree->t_session == session);
1273 
1274                 if (smb_strcasecmp(tree->t_sharename, sharename, 0) != 0)
1275                         continue;
1276 
1277                 if (smb_tree_hold(tree)) {
1278                         smb_llist_post(ll, tree,
1279                             smb_session_tree_kill);
1280                 }
1281         }
1282 
1283         smb_llist_exit(ll);
1284 }
1285 
1286 /*
1287  * Logoff all users associated with the specified session.
1288  *
1289  * This is called for both server-initiated disconnect
1290  * (SMB_SESSION_STATE_TERMINATED) and client-initiated
1291  * disconnect (SMB_SESSION_STATE_DISCONNECTED).
1292  * If client-initiated, save durable handles.
1293  */
1294 void
1295 smb_session_logoff(smb_session_t *session)
1296 {
1297         smb_llist_t     *ulist;
1298         smb_user_t      *user;
1299 
1300         SMB_SESSION_VALID(session);
1301 
1302 top:
1303         ulist = &session->s_user_list;
1304         smb_llist_enter(ulist, RW_READER);
1305 
1306         user = smb_llist_head(ulist);
1307         while (user) {
1308                 SMB_USER_VALID(user);
1309                 ASSERT(user->u_session == session);
1310 
1311                 mutex_enter(&user->u_mutex);
1312                 switch (user->u_state) {
1313                 case SMB_USER_STATE_LOGGING_ON:
1314                 case SMB_USER_STATE_LOGGED_ON:
1315                         // smb_user_hold_internal(user);
1316                         user->u_refcnt++;
1317                         mutex_exit(&user->u_mutex);
1318                         smb_user_logoff(user);
1319                         smb_user_release(user);
1320                         break;
1321 
1322                 case SMB_USER_STATE_LOGGED_OFF:
1323                 case SMB_USER_STATE_LOGGING_OFF:
1324                         mutex_exit(&user->u_mutex);
1325                         break;
1326 
1327                 default:
1328                         mutex_exit(&user->u_mutex);
1329                         ASSERT(0);
1330                         break;
1331                 }
1332 
1333                 user = smb_llist_next(ulist, user);
1334         }
1335 
1336         /* Needed below (Was the list empty?) */
1337         user = smb_llist_head(ulist);
1338 
1339         smb_llist_exit(ulist);
1340 
1341         /*
1342          * It's possible for user objects to remain due to references
1343          * obtained via smb_server_lookup_ssnid(), when an SMB2
1344          * session setup is destroying a previous session.
1345          *
1346          * Wait for user objects to clear out (last refs. go away,
1347          * then smb_user_delete takes them out of the list).  When
1348          * the last user object is removed, the session state is
1349          * set to SHUTDOWN and s_lock is signaled.
1350          *
1351          * Not all places that call smb_user_release necessarily
1352          * flush the delete queue, so after we wait for the list
1353          * to empty out, go back to the top and recheck the list
1354          * delete queue to make sure smb_user_delete happens.
1355          */
1356         if (user == NULL) {
1357                 /* User list is empty. */
1358                 smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1359                 session->s_state = SMB_SESSION_STATE_SHUTDOWN;
1360                 smb_rwx_rwexit(&session->s_lock);
1361         } else {
1362                 smb_rwx_rwenter(&session->s_lock, RW_READER);
1363                 if (session->s_state != SMB_SESSION_STATE_SHUTDOWN) {
1364                         (void) smb_rwx_cvwait(&session->s_lock,
1365                             MSEC_TO_TICK(200));
1366                         smb_rwx_rwexit(&session->s_lock);
1367                         goto top;
1368                 }
1369                 smb_rwx_rwexit(&session->s_lock);
1370         }
1371         ASSERT(session->s_state == SMB_SESSION_STATE_SHUTDOWN);
1372 
1373         /*
1374          * User list should be empty now.
1375          */
1376 #ifdef  DEBUG
1377         if (ulist->ll_count != 0) {
1378                 cmn_err(CE_WARN, "user list not empty?");
1379                 debug_enter("s_user_list");
1380         }
1381 #endif
1382 
1383         /*
1384          * User logoff happens first so we'll set preserve_opens
1385          * for client-initiated disconnect.  When that's done
1386          * there should be no trees left, but check anyway.
1387          */
1388         smb_session_disconnect_trees(session);
1389 }
1390 
1391 /*
1392  * Copy the session workstation/client name to buf.  If the workstation
1393  * is an empty string (which it will be on TCP connections), use the
1394  * client IP address.
1395  */
1396 void
1397 smb_session_getclient(smb_session_t *sn, char *buf, size_t buflen)
1398 {
1399 
1400         *buf = '\0';
1401 
1402         if (sn->workstation[0] != '\0') {
1403                 (void) strlcpy(buf, sn->workstation, buflen);
1404                 return;
1405         }
1406 
1407         (void) strlcpy(buf, sn->ip_addr_str, buflen);
1408 }
1409 
1410 /*
1411  * Check whether or not the specified client name is the client of this
1412  * session.  The name may be in UNC format (\\CLIENT).
1413  *
1414  * A workstation/client name is setup on NBT connections as part of the
1415  * NetBIOS session request but that isn't available on TCP connections.
1416  * If the session doesn't have a client name we typically return the
1417  * client IP address as the workstation name on MSRPC requests.  So we
1418  * check for the IP address here in addition to the workstation name.
1419  */
1420 boolean_t
1421 smb_session_isclient(smb_session_t *sn, const char *client)
1422 {
1423 
1424         client += strspn(client, "\\");
1425 
1426         if (smb_strcasecmp(client, sn->workstation, 0) == 0)
1427                 return (B_TRUE);
1428 
1429         if (smb_strcasecmp(client, sn->ip_addr_str, 0) == 0)
1430                 return (B_TRUE);
1431 
1432         return (B_FALSE);
1433 }
1434 
1435 /*
1436  * smb_request_alloc
1437  *
1438  * Allocate an smb_request_t structure from the kmem_cache.  Partially
1439  * initialize the found/new request.
1440  *
1441  * Returns pointer to a request, or NULL if the session state is
1442  * one in which new requests are no longer allowed.
1443  */
1444 smb_request_t *
1445 smb_request_alloc(smb_session_t *session, int req_length)
1446 {
1447         smb_request_t   *sr;
1448 
1449         ASSERT(session->s_magic == SMB_SESSION_MAGIC);
1450         ASSERT(req_length <= session->cmd_max_bytes);
1451 
1452         sr = kmem_cache_alloc(smb_cache_request, KM_SLEEP);
1453 
1454         /*
1455          * Future:  Use constructor to pre-initialize some fields.  For now
1456          * there are so many fields that it is easiest just to zero the
1457          * whole thing and start over.
1458          */
1459         bzero(sr, sizeof (smb_request_t));
1460 
1461         mutex_init(&sr->sr_mutex, NULL, MUTEX_DEFAULT, NULL);
1462         smb_srm_init(sr);
1463         sr->session = session;
1464         sr->sr_server = session->s_server;
1465         sr->sr_gmtoff = session->s_server->si_gmtoff;
1466         sr->sr_cfg = &session->s_cfg;
1467         sr->command.max_bytes = req_length;
1468         sr->reply.max_bytes = session->reply_max_bytes;
1469         sr->sr_req_length = req_length;
1470         if (req_length)
1471                 sr->sr_request_buf = kmem_alloc(req_length, KM_SLEEP);
1472         sr->sr_magic = SMB_REQ_MAGIC;
1473         sr->sr_state = SMB_REQ_STATE_INITIALIZING;
1474 
1475         /*
1476          * Only allow new SMB requests in some states.
1477          */
1478         smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1479         switch (session->s_state) {
1480         case SMB_SESSION_STATE_CONNECTED:
1481         case SMB_SESSION_STATE_INITIALIZED:
1482         case SMB_SESSION_STATE_ESTABLISHED:
1483         case SMB_SESSION_STATE_NEGOTIATED:
1484                 smb_slist_insert_tail(&session->s_req_list, sr);
1485                 break;
1486 
1487         default:
1488                 ASSERT(0);
1489                 /* FALLTHROUGH */
1490         case SMB_SESSION_STATE_DISCONNECTED:
1491         case SMB_SESSION_STATE_SHUTDOWN:
1492         case SMB_SESSION_STATE_TERMINATED:
1493                 /* Disallow new requests in these states. */
1494                 if (sr->sr_request_buf)
1495                         kmem_free(sr->sr_request_buf, sr->sr_req_length);
1496                 sr->session = NULL;
1497                 sr->sr_magic = 0;
1498                 mutex_destroy(&sr->sr_mutex);
1499                 kmem_cache_free(smb_cache_request, sr);
1500                 sr = NULL;
1501                 break;
1502         }
1503         smb_rwx_rwexit(&session->s_lock);
1504 
1505         return (sr);
1506 }
1507 
1508 /*
1509  * smb_request_free
1510  *
1511  * release the memories which have been allocated for a smb request.
1512  */
1513 void
1514 smb_request_free(smb_request_t *sr)
1515 {
1516         ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
1517         ASSERT(sr->session);
1518         ASSERT(sr->r_xa == NULL);
1519 
1520         if (sr->fid_ofile != NULL) {
1521                 smb_ofile_release(sr->fid_ofile);
1522         }
1523 
1524         if (sr->tid_tree != NULL)
1525                 smb_tree_release(sr->tid_tree);
1526 
1527         if (sr->uid_user != NULL)
1528                 smb_user_release(sr->uid_user);
1529 
1530         if (sr->tform_ssn != NULL)
1531                 smb_user_release(sr->tform_ssn);
1532 
1533         /*
1534          * The above may have left work on the delete queues
1535          */
1536         smb_llist_flush(&sr->session->s_tree_list);
1537         smb_llist_flush(&sr->session->s_user_list);
1538 
1539         smb_slist_remove(&sr->session->s_req_list, sr);
1540 
1541         sr->session = NULL;
1542 
1543         smb_srm_fini(sr);
1544 
1545         if (sr->sr_request_buf)
1546                 kmem_free(sr->sr_request_buf, sr->sr_req_length);
1547         if (sr->command.chain)
1548                 m_freem(sr->command.chain);
1549         if (sr->reply.chain)
1550                 m_freem(sr->reply.chain);
1551         if (sr->raw_data.chain)
1552                 m_freem(sr->raw_data.chain);
1553 
1554         sr->sr_magic = 0;
1555         mutex_destroy(&sr->sr_mutex);
1556         kmem_cache_free(smb_cache_request, sr);
1557 }
1558 
1559 boolean_t
1560 smb_session_oplocks_enable(smb_session_t *session)
1561 {
1562         SMB_SESSION_VALID(session);
1563         if (session->s_cfg.skc_oplock_enable == 0)
1564                 return (B_FALSE);
1565         else
1566                 return (B_TRUE);
1567 }
1568 
1569 boolean_t
1570 smb_session_levelII_oplocks(smb_session_t *session)
1571 {
1572         SMB_SESSION_VALID(session);
1573 
1574         /* Older clients only do Level II oplocks if negotiated. */
1575         if ((session->capabilities & CAP_LEVEL_II_OPLOCKS) != 0)
1576                 return (B_TRUE);
1577 
1578         return (B_FALSE);
1579 }
1580 
1581 static void
1582 smb_session_genkey(smb_session_t *session)
1583 {
1584         uint8_t         tmp_key[SMB_CHALLENGE_SZ];
1585 
1586         (void) random_get_pseudo_bytes(tmp_key, SMB_CHALLENGE_SZ);
1587         bcopy(tmp_key, &session->challenge_key, SMB_CHALLENGE_SZ);
1588         session->challenge_len = SMB_CHALLENGE_SZ;
1589 
1590         (void) random_get_pseudo_bytes(tmp_key, 4);
1591         session->sesskey = tmp_key[0] | tmp_key[1] << 8 |
1592             tmp_key[2] << 16 | tmp_key[3] << 24;
1593 }