xref: /illumos-gate/usr/src/uts/common/fs/smbsrv/smb_ofile.c (revision a5a9a6bb70826a54a1c35d3b862a927fd22f7b0e)
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 2011-2020 Tintri by DDN, Inc. All rights reserved.
24  * Copyright 2016 Syneto S.R.L. All rights reserved.
25  * Copyright (c) 2016 by Delphix. All rights reserved.
26  * Copyright 2022 RackTop Systems, Inc.
27  */
28 
29 /*
30  * General Structures Layout
31  * -------------------------
32  *
33  * This is a simplified diagram showing the relationship between most of the
34  * main structures.
35  *
36  * +-------------------+
37  * |     SMB_INFO      |
38  * +-------------------+
39  *          |
40  *          |
41  *          v
42  * +-------------------+       +-------------------+      +-------------------+
43  * |     SESSION       |<----->|     SESSION       |......|      SESSION      |
44  * +-------------------+       +-------------------+      +-------------------+
45  *   |          |
46  *   |          |
47  *   |          v
48  *   |  +-------------------+     +-------------------+   +-------------------+
49  *   |  |       USER        |<--->|       USER        |...|       USER        |
50  *   |  +-------------------+     +-------------------+   +-------------------+
51  *   |
52  *   |
53  *   v
54  * +-------------------+       +-------------------+      +-------------------+
55  * |       TREE        |<----->|       TREE        |......|       TREE        |
56  * +-------------------+       +-------------------+      +-------------------+
57  *      |         |
58  *      |         |
59  *      |         v
60  *      |     +-------+       +-------+      +-------+
61  *      |     | OFILE |<----->| OFILE |......| OFILE |
62  *      |     +-------+       +-------+      +-------+
63  *      |
64  *      |
65  *      v
66  *  +-------+       +------+      +------+
67  *  | ODIR  |<----->| ODIR |......| ODIR |
68  *  +-------+       +------+      +------+
69  *
70  *
71  * Ofile State Machine
72  * ------------------
73  *
74  *    +-------------------------+	 T0
75  *    |  SMB_OFILE_STATE_OPEN   |<--+-------- Creation/Allocation
76  *    +-------------------------+   |
77  *	    |		|	    | T5
78  *	    |		|	+---------------------------+
79  *	    |		|	| SMB_OFILE_STATE_RECONNECT |
80  *	    |		|	+---------------------------+
81  *	    |		|	    ^
82  *	    |		v	    |
83  *	    |   +---------------+   |
84  *	    |   | STATE_SAVE_DH |   |
85  *	    |   | STATE_SAVING  |   |
86  *	    |   +---------------+   |
87  *	    |		|	    | T4
88  *	    | T1	| T3	+--------------------------+
89  *	    |		+------>| SMB_OFILE_STATE_ORPHANED |
90  *	    v			+--------------------------+
91  *    +-------------------------+   |		|
92  *    | SMB_OFILE_STATE_CLOSING |<--+ T6	| T7
93  *    +-------------------------+		|
94  *	    |		^			v
95  *	    | T2	| T8	+-------------------------+
96  *	    |		+-------| SMB_OFILE_STATE_EXPIRED |
97  *	    v			+-------------------------+
98  *    +-------------------------+
99  *    | SMB_OFILE_STATE_CLOSED  |----------> Deletion/Free
100  *    +-------------------------+    T9
101  *
102  * SMB_OFILE_STATE_OPEN
103  *
104  *    While in this state:
105  *      - The ofile is queued in the list of ofiles of its tree.
106  *      - References will be given out if the ofile is looked up.
107  *
108  * SMB_OFILE_STATE_SAVE_DH
109  *
110  *    Similar to state _CLOSING, but instead of deleting the ofile,
111  *    it leaves the ofile in state _ORPHANED (for later reclaim).
112  *    Will move to _SAVING after last ref, then _ORPHANED.
113  *
114  *    While in this state:
115  *	- The ofile has been marked for preservation during a
116  *	  walk of the tree ofile list to close multiple files.
117  *	- References will not be given out if the ofile is looked up,
118  *	  except for oplock break processing.
119  *	- Still affects Sharing Violation rules
120  *
121  * SMB_OFILE_STATE_SAVING
122  *
123  *    Transient state used to keep oplock break processing out
124  *    while the ofile moves to state _ORPHANED.
125  *
126  *    While in this state:
127  *	- References will not be given out if the ofile is looked up,
128  *	  except for oplock break processing.
129  *	- Still affects Sharing Violation rules
130  *
131  * SMB_OFILE_STATE_CLOSING
132  *
133  *    Close has been requested.  Stay in this state until the last
134  *    ref. is gone, then move to state _CLOSED
135  *
136  *    While in this state:
137  *      - The ofile is queued in the list of ofiles of its tree.
138  *      - References will not be given out if the ofile is looked up.
139  *      - The file is closed and the locks held are being released.
140  *      - The resources associated with the ofile remain.
141  *
142  * SMB_OFILE_STATE_CLOSED
143  *
144  *    While in this state:
145  *      - The ofile is queued in the list of ofiles of its tree.
146  *      - References will not be given out if the ofile is looked up.
147  *      - The resources associated with the ofile remain.
148  *
149  * SMB_OFILE_STATE_ORPHANED
150  *
151  *    While in this state:
152  *      - The ofile is queued in the list of ofiles of its tree.
153  *      - Can be reclaimed by the original owner
154  *      - References will not be given out if the ofile is looked up.
155  *      - All the tree, user, and session "up" pointers are NULL!
156  *      - Will eventually be "expired" if not reclaimed
157  *      - Can be closed if its oplock is broken
158  *      - Still affects Sharing Violation rules
159  *
160  * SMB_OFILE_STATE_EXPIRED
161  *
162  *    While in this state:
163  *      - The ofile is queued in the list of ofiles of its tree.
164  *      - References will not be given out if the ofile is looked up.
165  *      - The ofile has not been reclaimed and will soon be closed,
166  *        due to, for example, the durable handle timer expiring, or its
167  *        oplock being broken.
168  *      - Cannot be reclaimed at this point
169  *
170  * SMB_OFILE_STATE_RECONNECT
171  *
172  *    Transient state used to keep oplock break processing out
173  *    while the ofile moves from state _ORPHANED to _OPEN.
174  *
175  *    While in this state:
176  *      - The ofile is being reclaimed; do not touch it.
177  *      - References will not be given out if the ofile is looked up.
178  *      - Still affects Sharing Violation rules
179  *	- see smb2_dh_reconnect() for which members need to be avoided
180  *
181  * Transition T0
182  *
183  *    This transition occurs in smb_ofile_open(). A new ofile is created and
184  *    added to the list of ofiles of a tree.
185  *
186  * Transition T1
187  *
188  *    This transition occurs in smb_ofile_close(). Note that this only happens
189  *    when we determine that an ofile should be closed in spite of its durable
190  *    handle properties.
191  *
192  * Transition T2
193  *
194  *    This transition occurs in smb_ofile_release(). The resources associated
195  *    with the ofile are freed as well as the ofile structure. For the
196  *    transition to occur, the ofile must be in the SMB_OFILE_STATE_CLOSED
197  *    state and the reference count be zero.
198  *
199  * Transition T3
200  *
201  *    This transition occurs in smb_ofile_orphan_dh(). It happens during an
202  *    smb2 logoff, or during a session disconnect when certain conditions are
203  *    met. The ofile and structures above it will be kept around until the ofile
204  *    either gets reclaimed, expires after f_timeout_offset nanoseconds, or its
205  *    oplock is broken.
206  *
207  * Transition T4
208  *
209  *    This transition occurs in smb2_dh_reconnect(). An smb2 create request
210  *    with a DURABLE_HANDLE_RECONNECT(_V2) create context has been
211  *    recieved from the original owner. If leases are supported or it's
212  *    RECONNECT_V2, reconnect is subject to additional conditions. The ofile
213  *    will be unwired from the old, disconnected session, tree, and user,
214  *    and wired up to its new context.
215  *
216  * Transition T5
217  *
218  *    This transition occurs in smb2_dh_reconnect(). The ofile has been
219  *    successfully reclaimed.
220  *
221  * Transition T6
222  *
223  *    This transition occurs in smb_ofile_close(). The ofile has been orphaned
224  *    while some thread was blocked, and that thread closes the ofile. Can only
225  *    happen when the ofile is orphaned due to an SMB2 LOGOFF request.
226  *
227  * Transition T7
228  *
229  *    This transition occurs in smb_session_durable_timers() and
230  *    smb_oplock_send_brk(). The ofile will soon be closed.
231  *    In the former case, f_timeout_offset nanoseconds have passed since
232  *    the ofile was orphaned. In the latter, an oplock break occured
233  *    on the ofile while it was orphaned.
234  *
235  * Transition T8
236  *
237  *    This transition occurs in smb_ofile_close().
238  *
239  * Transition T9
240  *
241  *    This transition occurs in smb_ofile_delete().
242  *
243  * Comments
244  * --------
245  *
246  *    The state machine of the ofile structures is controlled by 3 elements:
247  *      - The list of ofiles of the tree it belongs to.
248  *      - The mutex embedded in the structure itself.
249  *      - The reference count.
250  *
251  *    There's a mutex embedded in the ofile structure used to protect its fields
252  *    and there's a lock embedded in the list of ofiles of a tree. To
253  *    increment or to decrement the reference count the mutex must be entered.
254  *    To insert the ofile into the list of ofiles of the tree and to remove
255  *    the ofile from it, the lock must be entered in RW_WRITER mode.
256  *
257  *    Rules of access to a ofile structure:
258  *
259  *    1) In order to avoid deadlocks, when both (mutex and lock of the ofile
260  *       list) have to be entered, the lock must be entered first. Additionally,
261  *       f_mutex must not be held when removing the ofile from sv_persistid_ht.
262  *
263  *    2) All actions applied to an ofile require a reference count.
264  *
265  *    3) There are 2 ways of getting a reference count. One is when the ofile
266  *       is opened. The other one when the ofile is looked up. This translates
267  *       into 2 functions: smb_ofile_open() and smb_ofile_lookup_by_fid().
268  *
269  *    It should be noted that the reference count of an ofile registers the
270  *    number of references to the ofile in other structures (such as an smb
271  *    request). The reference count is not incremented in these 2 instances:
272  *
273  *    1) The ofile is open. An ofile is anchored by its state. If there's
274  *       no activity involving an ofile currently open, the reference count
275  *       of that ofile is zero.
276  *
277  *    2) The ofile is queued in the list of ofiles of its tree. The fact of
278  *       being queued in that list is NOT registered by incrementing the
279  *       reference count.
280  */
281 #include <smbsrv/smb2_kproto.h>
282 #include <smbsrv/smb_fsops.h>
283 #include <sys/time.h>
284 #include <sys/random.h>
285 
286 static boolean_t smb_ofile_is_open_locked(smb_ofile_t *);
287 static void smb_ofile_delete(void *arg);
288 static void smb_ofile_save_dh(void *arg);
289 
290 static int smb_ofile_netinfo_encode(smb_ofile_t *, uint8_t *, size_t,
291     uint32_t *);
292 static int smb_ofile_netinfo_init(smb_ofile_t *, smb_netfileinfo_t *);
293 static void smb_ofile_netinfo_fini(smb_netfileinfo_t *);
294 
295 /*
296  * The uniq_fid is a CIFS-server-wide unique identifier for an ofile
297  * which is used to uniquely identify open instances for the
298  * VFS share reservation and POSIX locks.
299  */
300 static volatile uint32_t smb_fids = 0;
301 #define	SMB_UNIQ_FID()	atomic_inc_32_nv(&smb_fids)
302 
303 /*
304  * smb_ofile_alloc
305  * Allocate an ofile and fill in it's "up" pointers, but
306  * do NOT link it into the tree's list of ofiles or the
307  * node's list of ofiles.  An ofile in this state is a
308  * "proposed" open passed to the oplock break code.
309  *
310  * If we don't get as far as smb_ofile_open with this OF,
311  * call smb_ofile_free() to free this object.
312  *
313  * Note: The following sr members may be null during
314  * persistent handle import: session, uid_usr, tid_tree
315  */
316 smb_ofile_t *
317 smb_ofile_alloc(
318     smb_request_t	*sr,
319     smb_arg_open_t	*op,
320     smb_node_t		*node, /* optional (may be NULL) */
321     uint16_t		ftype,
322     uint16_t		tree_fid)
323 {
324 	smb_user_t	*user = sr->uid_user;	/* optional */
325 	smb_tree_t	*tree = sr->tid_tree;	/* optional */
326 	smb_ofile_t	*of;
327 
328 	of = kmem_cache_alloc(smb_cache_ofile, KM_SLEEP);
329 	bzero(of, sizeof (smb_ofile_t));
330 	of->f_magic = SMB_OFILE_MAGIC;
331 
332 	mutex_init(&of->f_mutex, NULL, MUTEX_DEFAULT, NULL);
333 	list_create(&of->f_notify.nc_waiters, sizeof (smb_request_t),
334 	    offsetof(smb_request_t, sr_waiters));
335 	mutex_init(&of->dh_nvlock, NULL, MUTEX_DEFAULT, NULL);
336 
337 	of->f_state = SMB_OFILE_STATE_ALLOC;
338 	of->f_refcnt = 1;
339 	of->f_ftype = ftype;
340 	of->f_fid = tree_fid;
341 	/* of->f_persistid see smb2_create */
342 	of->f_uniqid = SMB_UNIQ_FID();
343 	of->f_opened_by_pid = sr->smb_pid;
344 	of->f_granted_access = op->desired_access;
345 	of->f_share_access = op->share_access;
346 	of->f_create_options = op->create_options;
347 	if (user != NULL) {
348 		if ((op->create_options & FILE_OPEN_FOR_BACKUP_INTENT) != 0)
349 			of->f_cr = smb_user_getprivcred(user);
350 		else
351 			of->f_cr = user->u_cred;
352 		crhold(of->f_cr);
353 	}
354 	of->f_server = sr->sr_server;
355 	of->f_session = sr->session;	/* may be NULL */
356 
357 	(void) memset(of->f_lock_seq, -1, SMB_OFILE_LSEQ_MAX);
358 
359 	of->f_mode = smb_fsop_amask_to_omode(of->f_granted_access);
360 	if ((of->f_granted_access & FILE_DATA_ALL) == FILE_EXECUTE)
361 		of->f_flags |= SMB_OFLAGS_EXECONLY;
362 
363 	/*
364 	 * In case a lease is requested, copy the lease keys now so
365 	 * any oplock breaks during open don't break those on our
366 	 * other handles that might have the same lease.
367 	 */
368 	bcopy(op->lease_key, of->TargetOplockKey, SMB_LEASE_KEY_SZ);
369 	bcopy(op->parent_lease_key, of->ParentOplockKey, SMB_LEASE_KEY_SZ);
370 
371 	/*
372 	 * grab a ref for of->f_user and of->f_tree
373 	 * We know the user and tree must be "live" because
374 	 * this SR holds references to them.  The node ref. is
375 	 * held by our caller, until smb_ofile_open puts this
376 	 * ofile on the node ofile list with smb_node_add_ofile.
377 	 */
378 	if (user != NULL) {
379 		smb_user_hold_internal(user);
380 		of->f_user = user;
381 	}
382 	if (tree != NULL) {
383 		smb_tree_hold_internal(tree);
384 		of->f_tree = tree;
385 	}
386 	of->f_node = node;	/* may be NULL */
387 
388 	return (of);
389 }
390 
391 /*
392  * smb_ofile_open
393  *
394  * Complete an open on an ofile that was previously allocated by
395  * smb_ofile_alloc, by putting it on the tree ofile list and
396  * (if it's a file) the node ofile list.
397  */
398 void
399 smb_ofile_open(
400     smb_request_t	*sr,
401     smb_arg_open_t	*op,
402     smb_ofile_t		*of)
403 {
404 	smb_tree_t	*tree = sr->tid_tree;
405 	smb_node_t	*node = of->f_node;
406 
407 	ASSERT(of->f_state == SMB_OFILE_STATE_ALLOC);
408 	ASSERT(of->f_fid != 0);
409 
410 	of->f_state = SMB_OFILE_STATE_OPEN;
411 
412 	switch (of->f_ftype) {
413 	case SMB_FTYPE_BYTE_PIPE:
414 	case SMB_FTYPE_MESG_PIPE:
415 		/* See smb_opipe_open. */
416 		of->f_pipe = op->pipe;
417 		smb_server_inc_pipes(of->f_server);
418 		break;
419 	case SMB_FTYPE_DISK:
420 	case SMB_FTYPE_PRINTER:
421 		/* Regular file, not a pipe */
422 		ASSERT(node != NULL);
423 
424 		smb_node_inc_open_ofiles(node);
425 		smb_node_add_ofile(node, of);
426 		smb_node_ref(node);
427 		smb_server_inc_files(of->f_server);
428 		break;
429 	default:
430 		ASSERT(0);
431 	}
432 	smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
433 	smb_llist_insert_tail(&tree->t_ofile_list, of);
434 	smb_llist_exit(&tree->t_ofile_list);
435 	atomic_inc_32(&tree->t_open_files);
436 	atomic_inc_32(&of->f_session->s_file_cnt);
437 
438 }
439 
440 /*
441  * smb_ofile_close
442  *
443  * Incoming states: (where from)
444  *   SMB_OFILE_STATE_OPEN  protocol close, smb_ofile_drop
445  *   SMB_OFILE_STATE_EXPIRED  called via smb2_dh_expire
446  *   SMB_OFILE_STATE_ORPHANED  smb2_dh_shutdown
447  */
448 void
449 smb_ofile_close(smb_ofile_t *of, int32_t mtime_sec)
450 {
451 	smb_attr_t *pa;
452 
453 	SMB_OFILE_VALID(of);
454 
455 	if (of->f_ftype == SMB_FTYPE_DISK) {
456 		smb_node_t *node = of->f_node;
457 
458 		smb_llist_enter(&node->n_ofile_list, RW_READER);
459 		mutex_enter(&node->n_oplock.ol_mutex);
460 
461 		if (of->f_oplock_closing == B_FALSE) {
462 			of->f_oplock_closing = B_TRUE;
463 
464 			if (of->f_lease != NULL)
465 				smb2_lease_ofile_close(of);
466 			smb_oplock_break_CLOSE(node, of);
467 		}
468 
469 		mutex_exit(&node->n_oplock.ol_mutex);
470 		smb_llist_exit(&node->n_ofile_list);
471 	}
472 
473 	mutex_enter(&of->f_mutex);
474 	ASSERT(of->f_refcnt);
475 
476 	switch (of->f_state) {
477 	case SMB_OFILE_STATE_OPEN:
478 	case SMB_OFILE_STATE_ORPHANED:
479 	case SMB_OFILE_STATE_EXPIRED:
480 		of->f_state = SMB_OFILE_STATE_CLOSING;
481 		mutex_exit(&of->f_mutex);
482 		break;
483 	default:
484 		mutex_exit(&of->f_mutex);
485 		return;
486 	}
487 
488 	/*
489 	 * Only one thread here (the one that that set f_state closing)
490 	 */
491 	switch (of->f_ftype) {
492 	case SMB_FTYPE_BYTE_PIPE:
493 	case SMB_FTYPE_MESG_PIPE:
494 		smb_opipe_close(of);
495 		smb_server_dec_pipes(of->f_server);
496 		break;
497 
498 	case SMB_FTYPE_DISK:
499 		if (of->dh_persist)
500 			smb2_dh_close_persistent(of);
501 		if (of->f_persistid != 0)
502 			smb_ofile_del_persistid(of);
503 		/* FALLTHROUGH */
504 
505 	case SMB_FTYPE_PRINTER: /* or FTYPE_DISK */
506 		/*
507 		 * In here we make changes to of->f_pending_attr
508 		 * while not holding of->f_mutex.  This is OK
509 		 * because we've changed f_state to CLOSING,
510 		 * so no more threads will take this path.
511 		 */
512 		pa = &of->f_pending_attr;
513 		if (mtime_sec != 0) {
514 			pa->sa_vattr.va_mtime.tv_sec = mtime_sec;
515 			pa->sa_mask |= SMB_AT_MTIME;
516 		}
517 
518 		if (of->f_flags & SMB_OFLAGS_SET_DELETE_ON_CLOSE) {
519 			/* We delete using the on-disk name. */
520 			uint32_t flags = SMB_CASE_SENSITIVE;
521 			(void) smb_node_set_delete_on_close(of->f_node,
522 			    of->f_cr, flags);
523 		}
524 		smb_fsop_unshrlock(of->f_cr, of->f_node, of->f_uniqid);
525 		smb_node_destroy_lock_by_ofile(of->f_node, of);
526 
527 		if (smb_node_is_file(of->f_node)) {
528 			(void) smb_fsop_close(of->f_node, of->f_mode,
529 			    of->f_cr);
530 		} else {
531 			/*
532 			 * If there was an odir, close it.
533 			 */
534 			if (of->f_odir != NULL)
535 				smb_odir_close(of->f_odir);
536 			/*
537 			 * Cancel any notify change requests that
538 			 * might be watching this open file (dir),
539 			 * and unsubscribe it from node events.
540 			 *
541 			 * Can't hold f_mutex when calling smb_notify_ofile.
542 			 * Don't really need it when unsubscribing, but
543 			 * harmless, and consistent with subscribing.
544 			 */
545 			if (of->f_notify.nc_subscribed)
546 				smb_notify_ofile(of,
547 				    FILE_ACTION_HANDLE_CLOSED, NULL);
548 			mutex_enter(&of->f_mutex);
549 			if (of->f_notify.nc_subscribed) {
550 				of->f_notify.nc_subscribed = B_FALSE;
551 				smb_node_fcn_unsubscribe(of->f_node);
552 				of->f_notify.nc_filter = 0;
553 			}
554 			mutex_exit(&of->f_mutex);
555 		}
556 		if (smb_node_dec_open_ofiles(of->f_node) == 0) {
557 			/*
558 			 * Last close.  If we're not deleting
559 			 * the file, apply any pending attrs.
560 			 * Leave allocsz zero when no open files,
561 			 * just to avoid confusion, because it's
562 			 * only updated when there are opens.
563 			 * XXX: Just do this on _every_ close.
564 			 */
565 			mutex_enter(&of->f_node->n_mutex);
566 			if (of->f_node->flags & NODE_FLAGS_DELETE_ON_CLOSE) {
567 				smb_node_delete_on_close(of->f_node);
568 				pa->sa_mask = 0;
569 			}
570 			of->f_node->n_allocsz = 0;
571 			mutex_exit(&of->f_node->n_mutex);
572 		}
573 		if (pa->sa_mask != 0) {
574 			/*
575 			 * Commit any pending attributes from
576 			 * the ofile we're closing.  Note that
577 			 * we pass NULL as the ofile to setattr
578 			 * so it will write to the file system
579 			 * and not keep anything on the ofile.
580 			 */
581 			(void) smb_node_setattr(NULL, of->f_node,
582 			    of->f_cr, NULL, pa);
583 		}
584 		/*
585 		 * Don't want the performance cost of generating
586 		 * change notify events on every write.  Instead:
587 		 * Keep track of the fact that we have written
588 		 * data via this handle, and do change notify
589 		 * work on the first write, and during close.
590 		 */
591 		if (of->f_written) {
592 			smb_node_notify_modified(of->f_node);
593 		}
594 
595 		smb_server_dec_files(of->f_server);
596 		break;
597 	}
598 
599 	/*
600 	 * Keep f_state == SMB_OFILE_STATE_CLOSING
601 	 * until the last ref. is dropped, in
602 	 * smb_ofile_release()
603 	 */
604 }
605 
606 /*
607  * "Destructor" function for smb_ofile_close_all, and
608  * smb_ofile_close_all_by_pid, called after the llist lock
609  * for tree list has been exited.  Our job is to either
610  * close this ofile, or (if durable) set state _SAVE_DH.
611  *
612  * The next interesting thing happens when the last ref.
613  * on this ofile calls smb_ofile_release(), where we
614  * eihter delete the ofile, or (if durable) leave it
615  * in the persistid hash table for possible reclaim.
616  *
617  * This is run via smb_llist_post (after smb_llist_exit)
618  * because smb_ofile_close can block, and we'd rather not
619  * block while holding the ofile list as reader.
620  */
621 static void
622 smb_ofile_drop(void *arg)
623 {
624 	smb_ofile_t	*of = arg;
625 
626 	SMB_OFILE_VALID(of);
627 
628 	mutex_enter(&of->f_mutex);
629 	switch (of->f_state) {
630 	case SMB_OFILE_STATE_OPEN:
631 		/* DH checks under mutex. */
632 		if (of->f_ftype == SMB_FTYPE_DISK &&
633 		    of->dh_vers != SMB2_NOT_DURABLE &&
634 		    smb_dh_should_save(of)) {
635 			/*
636 			 * Tell smb_ofile_release() to
637 			 * make this an _ORPHANED DH.
638 			 */
639 			of->f_state = SMB_OFILE_STATE_SAVE_DH;
640 			mutex_exit(&of->f_mutex);
641 			break;
642 		}
643 		/* OK close it. */
644 		mutex_exit(&of->f_mutex);
645 		smb_ofile_close(of, 0);
646 		break;
647 
648 	default:
649 		/* Something else closed it already. */
650 		mutex_exit(&of->f_mutex);
651 		break;
652 	}
653 
654 	/*
655 	 * Release the ref acquired during the traversal loop.
656 	 * Note that on the last ref, this ofile will be
657 	 * removed from the tree list etc.
658 	 * See: smb_llist_post, smb_ofile_delete
659 	 */
660 	smb_ofile_release(of);
661 }
662 
663 /*
664  * smb_ofile_close_all
665  *
666  *
667  */
668 void
669 smb_ofile_close_all(
670     smb_tree_t		*tree,
671     uint32_t		pid)
672 {
673 	smb_ofile_t	*of;
674 	smb_llist_t	*ll;
675 
676 	ASSERT(tree);
677 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
678 
679 	ll = &tree->t_ofile_list;
680 
681 	smb_llist_enter(ll, RW_READER);
682 	for (of = smb_llist_head(ll);
683 	    of != NULL;
684 	    of = smb_llist_next(ll, of)) {
685 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
686 		ASSERT(of->f_tree == tree);
687 		if (pid != 0 && of->f_opened_by_pid != pid)
688 			continue;
689 		if (smb_ofile_hold(of)) {
690 			smb_llist_post(ll, of, smb_ofile_drop);
691 		}
692 	}
693 
694 	/*
695 	 * Drop the lock and process the llist dtor queue.
696 	 * Calls smb_ofile_drop on ofiles that were open.
697 	 */
698 	smb_llist_exit(ll);
699 }
700 
701 /*
702  * If the enumeration request is for ofile data, handle it here.
703  * Otherwise, return.
704  *
705  * This function should be called with a hold on the ofile.
706  */
707 int
708 smb_ofile_enum(smb_ofile_t *of, smb_svcenum_t *svcenum)
709 {
710 	uint8_t *pb;
711 	uint_t nbytes;
712 	int rc;
713 
714 	ASSERT(of);
715 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
716 	ASSERT(of->f_refcnt);
717 
718 	if (svcenum->se_type != SMB_SVCENUM_TYPE_FILE)
719 		return (0);
720 
721 	if (svcenum->se_nskip > 0) {
722 		svcenum->se_nskip--;
723 		return (0);
724 	}
725 
726 	if (svcenum->se_nitems >= svcenum->se_nlimit) {
727 		svcenum->se_nitems = svcenum->se_nlimit;
728 		return (0);
729 	}
730 
731 	pb = &svcenum->se_buf[svcenum->se_bused];
732 
733 	rc = smb_ofile_netinfo_encode(of, pb, svcenum->se_bavail,
734 	    &nbytes);
735 	if (rc == 0) {
736 		svcenum->se_bavail -= nbytes;
737 		svcenum->se_bused += nbytes;
738 		svcenum->se_nitems++;
739 	}
740 
741 	return (rc);
742 }
743 
744 /*
745  * Take a reference on an open file, in any of the states:
746  *   RECONNECT, SAVE_DH, OPEN, ORPHANED.
747  * Return TRUE if ref taken.  Used for oplock breaks.
748  *
749  * Note: When the oplock break code calls this, it holds the
750  * node ofile list lock and node oplock mutex.  When we see
751  * an ofile in states RECONNECT or SAVING, we know the ofile
752  * is gaining or losing it's tree, and that happens quickly,
753  * so we just wait for that work to finish.  However, the
754  * waiting for state transitions here means we have to be
755  * careful not to re-enter the node list lock or otherwise
756  * block on things that could cause a deadlock.  Waiting
757  * just on of->f_mutex here is OK.
758  */
759 boolean_t
760 smb_ofile_hold_olbrk(smb_ofile_t *of)
761 {
762 	boolean_t ret = B_FALSE;
763 
764 	ASSERT(of);
765 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
766 
767 	mutex_enter(&of->f_mutex);
768 
769 again:
770 	switch (of->f_state) {
771 	case SMB_OFILE_STATE_RECONNECT:
772 	case SMB_OFILE_STATE_SAVING:
773 		cv_wait(&of->f_cv, &of->f_mutex);
774 		goto again;
775 
776 	case SMB_OFILE_STATE_OPEN:
777 	case SMB_OFILE_STATE_ORPHANED:
778 	case SMB_OFILE_STATE_SAVE_DH:
779 		of->f_refcnt++;
780 		ret = B_TRUE;
781 		break;
782 
783 	default:
784 		break;
785 	}
786 	mutex_exit(&of->f_mutex);
787 
788 	return (ret);
789 }
790 
791 /*
792  * Take a reference on an open file.
793  */
794 boolean_t
795 smb_ofile_hold(smb_ofile_t *of)
796 {
797 	ASSERT(of);
798 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
799 
800 	mutex_enter(&of->f_mutex);
801 
802 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
803 		mutex_exit(&of->f_mutex);
804 		return (B_FALSE);
805 	}
806 	of->f_refcnt++;
807 
808 	mutex_exit(&of->f_mutex);
809 	return (B_TRUE);
810 }
811 
812 /*
813  * Void arg variant of smb_ofile_release for use with smb_llist_post.
814  * This is needed because smb_ofile_release may need to enter the
815  * smb_llist as writer when it drops the last reference, so when
816  * we're in the llist as reader, use smb_llist_post with this
817  * function to arrange for the release call at llist_exit.
818  */
819 void
820 smb_ofile_release_LL(void *arg)
821 {
822 	smb_ofile_t	*of = arg;
823 
824 	SMB_OFILE_VALID(of);
825 	smb_ofile_release(of);
826 }
827 
828 /*
829  * Release a reference on a file.  If the reference count falls to
830  * zero and the file has been closed, post the object for deletion.
831  * Object deletion is deferred to avoid modifying a list while an
832  * iteration may be in progress.
833  *
834  * We're careful to avoid dropping f_session etc. until the last
835  * reference goes away.  The oplock break code depends on that
836  * not changing while it holds a ref. on an ofile.
837  */
838 void
839 smb_ofile_release(smb_ofile_t *of)
840 {
841 	smb_tree_t *tree = of->f_tree;
842 	boolean_t delete = B_FALSE;
843 
844 	SMB_OFILE_VALID(of);
845 
846 	mutex_enter(&of->f_mutex);
847 	ASSERT(of->f_refcnt > 0);
848 	of->f_refcnt--;
849 
850 	switch (of->f_state) {
851 	case SMB_OFILE_STATE_OPEN:
852 	case SMB_OFILE_STATE_ORPHANED:
853 	case SMB_OFILE_STATE_EXPIRED:
854 		break;
855 
856 	case SMB_OFILE_STATE_SAVE_DH:
857 		ASSERT(tree != NULL);
858 		if (of->f_refcnt == 0) {
859 			of->f_state = SMB_OFILE_STATE_SAVING;
860 			smb_llist_post(&tree->t_ofile_list, of,
861 			    smb_ofile_save_dh);
862 		}
863 		break;
864 
865 	case SMB_OFILE_STATE_CLOSING:
866 		/* Note, tree == NULL on _ORPHANED */
867 		if (of->f_refcnt == 0) {
868 			of->f_state = SMB_OFILE_STATE_CLOSED;
869 			if (tree == NULL) {
870 				/* Skip smb_llist_post */
871 				delete = B_TRUE;
872 				break;
873 			}
874 			smb_llist_post(&tree->t_ofile_list, of,
875 			    smb_ofile_delete);
876 		}
877 		break;
878 
879 	default:
880 		ASSERT(0);
881 		break;
882 	}
883 	mutex_exit(&of->f_mutex);
884 
885 	/*
886 	 * When we drop the last ref. on an expired DH, it's no longer
887 	 * in any tree, so skip the smb_llist_post and just call
888 	 * smb_ofile_delete directly.
889 	 */
890 	if (delete) {
891 		smb_ofile_delete(of);
892 	}
893 }
894 
895 /*
896  * smb_ofile_lookup_by_fid
897  *
898  * Find the open file whose fid matches the one specified in the request.
899  * If we can't find the fid or the shares (trees) don't match, we have a
900  * bad fid.
901  */
902 smb_ofile_t *
903 smb_ofile_lookup_by_fid(
904     smb_request_t	*sr,
905     uint16_t		fid)
906 {
907 	smb_tree_t	*tree = sr->tid_tree;
908 	smb_llist_t	*of_list;
909 	smb_ofile_t	*of;
910 
911 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
912 
913 	of_list = &tree->t_ofile_list;
914 
915 	smb_llist_enter(of_list, RW_READER);
916 	of = smb_llist_head(of_list);
917 	while (of) {
918 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
919 		ASSERT(of->f_tree == tree);
920 		if (of->f_fid == fid)
921 			break;
922 		of = smb_llist_next(of_list, of);
923 	}
924 	if (of == NULL)
925 		goto out;
926 
927 	/*
928 	 * Only allow use of a given FID with the same UID that
929 	 * was used to open it.  MS-CIFS 3.3.5.14
930 	 */
931 	if (of->f_user != sr->uid_user) {
932 		of = NULL;
933 		goto out;
934 	}
935 
936 	/* inline smb_ofile_hold() */
937 	mutex_enter(&of->f_mutex);
938 	if (of->f_state != SMB_OFILE_STATE_OPEN) {
939 		mutex_exit(&of->f_mutex);
940 		of = NULL;
941 		goto out;
942 	}
943 	of->f_refcnt++;
944 	mutex_exit(&of->f_mutex);
945 
946 out:
947 	smb_llist_exit(of_list);
948 	return (of);
949 }
950 
951 /*
952  * smb_ofile_lookup_by_uniqid
953  *
954  * Find the open file whose uniqid matches the one specified in the request.
955  */
956 smb_ofile_t *
957 smb_ofile_lookup_by_uniqid(smb_tree_t *tree, uint32_t uniqid)
958 {
959 	smb_llist_t	*of_list;
960 	smb_ofile_t	*of;
961 
962 	ASSERT(tree->t_magic == SMB_TREE_MAGIC);
963 
964 	of_list = &tree->t_ofile_list;
965 	smb_llist_enter(of_list, RW_READER);
966 	of = smb_llist_head(of_list);
967 
968 	while (of) {
969 		ASSERT(of->f_magic == SMB_OFILE_MAGIC);
970 		ASSERT(of->f_tree == tree);
971 
972 		if (of->f_uniqid == uniqid) {
973 			if (smb_ofile_hold(of)) {
974 				smb_llist_exit(of_list);
975 				return (of);
976 			}
977 		}
978 
979 		of = smb_llist_next(of_list, of);
980 	}
981 
982 	smb_llist_exit(of_list);
983 	return (NULL);
984 }
985 
986 /*
987  * Durable ID (or persistent ID)
988  */
989 
990 static smb_ofile_t *
991 smb_ofile_hold_cb(smb_ofile_t *of)
992 {
993 	smb_ofile_t *ret = of;
994 
995 	mutex_enter(&of->f_mutex);
996 	if (of->f_state == SMB_OFILE_STATE_ORPHANED)
997 		/* inline smb_ofile_hold() */
998 		of->f_refcnt++;
999 	else
1000 		ret = NULL;
1001 
1002 	mutex_exit(&of->f_mutex);
1003 	return (ret);
1004 }
1005 
1006 /*
1007  * Lookup an ofile by persistent ID, and return ONLY if in state ORPHANED
1008  * This is used by SMB2 create "reclaim".
1009  */
1010 smb_ofile_t *
1011 smb_ofile_lookup_by_persistid(smb_request_t *sr, uint64_t persistid)
1012 {
1013 	smb_hash_t *hash;
1014 	smb_bucket_t *bucket;
1015 	smb_llist_t *ll;
1016 	smb_ofile_t *of;
1017 	uint_t idx;
1018 
1019 	if (persistid == 0)
1020 		return (NULL);
1021 
1022 	hash = sr->sr_server->sv_persistid_ht;
1023 	idx = smb_hash_uint64(hash, persistid);
1024 	bucket = &hash->buckets[idx];
1025 	ll = &bucket->b_list;
1026 
1027 	smb_llist_enter(ll, RW_READER);
1028 	of = smb_llist_head(ll);
1029 	while (of != NULL) {
1030 		if (of->f_persistid == persistid)
1031 			break;
1032 		of = smb_llist_next(ll, of);
1033 	}
1034 	if (of != NULL)
1035 		of = smb_ofile_hold_cb(of);
1036 	smb_llist_exit(ll);
1037 
1038 	return (of);
1039 }
1040 
1041 /*
1042  * Create a (unique) durable/persistent ID for a new ofile,
1043  * and add this ofile to the persistid hash table.  This ID
1044  * is referred to as the persistent ID in the protocol spec,
1045  * so that's what we call it too, though the persistence may
1046  * vary.  "Durable" handles are persistent across reconnects
1047  * but not server reboots.  Persistent handles are persistent
1048  * across server reboots too.
1049  *
1050  * Note that persistent IDs need to be unique for the lifetime of
1051  * any given ofile.  For normal (non-persistent) ofiles we can just
1052  * use a persistent ID derived from the ofile memory address, as
1053  * these don't ever live beyond the current OS boot lifetime.
1054  *
1055  * Persistent handles are re-imported after server restart, and
1056  * generally have a different memory address after import than
1057  * they had in the previous OS boot lifetime, so for these we
1058  * use a randomly assigned value that won't conflict with any
1059  * non-persistent (durable) handles.  Ensuring that a randomly
1060  * generated ID is unique requires a search of the ofiles in one
1061  * hash bucket, which we'd rather avoid for non-persistent opens.
1062  *
1063  * The solution used here is to divide the persistent ID space
1064  * in half (odd and even values) where durable opens use an ID
1065  * derived from the ofile address (which is always even), and
1066  * persistent opens use an ID generated randomly (always odd).
1067  *
1068  * smb_ofile_set_persistid_dh() sets a durable handle ID and
1069  * smb_ofile_set_persistid_ph() sets a persistent handle ID.
1070  */
1071 void
1072 smb_ofile_set_persistid_dh(smb_ofile_t *of)
1073 {
1074 	smb_hash_t *hash = of->f_server->sv_persistid_ht;
1075 	smb_bucket_t *bucket;
1076 	smb_llist_t *ll;
1077 	uint64_t persistid;
1078 	uint_t idx;
1079 
1080 	persistid = (uintptr_t)of;
1081 	/* Avoid showing object addresses */
1082 	persistid ^= ((uintptr_t)&smb_cache_ofile);
1083 	/* make sure it's even */
1084 	persistid &= ~((uint64_t)1);
1085 
1086 	idx = smb_hash_uint64(hash, persistid);
1087 	bucket = &hash->buckets[idx];
1088 	ll = &bucket->b_list;
1089 	smb_llist_enter(ll, RW_WRITER);
1090 	if (of->f_persistid == 0) {
1091 		of->f_persistid = persistid;
1092 		smb_llist_insert_tail(ll, of);
1093 	}
1094 	smb_llist_exit(ll);
1095 }
1096 
1097 void
1098 smb_ofile_set_persistid_ph(smb_ofile_t *of)
1099 {
1100 	uint64_t persistid;
1101 	int rc;
1102 
1103 top:
1104 	(void) random_get_pseudo_bytes((uint8_t *)&persistid,
1105 	    sizeof (persistid));
1106 	if (persistid == 0) {
1107 		cmn_err(CE_NOTE, "random gave all zeros!");
1108 		goto top;
1109 	}
1110 	/* make sure it's odd */
1111 	persistid |= (uint64_t)1;
1112 
1113 	/*
1114 	 * Try inserting with this persistent ID.
1115 	 */
1116 	rc = smb_ofile_insert_persistid(of, persistid);
1117 	if (rc == EEXIST)
1118 		goto top;
1119 	if (rc != 0) {
1120 		cmn_err(CE_NOTE, "set persistid rc=%d", rc);
1121 	}
1122 }
1123 
1124 /*
1125  * Insert an ofile into the persistid hash table.
1126  * If the persistent ID is in use, error.
1127  */
1128 int
1129 smb_ofile_insert_persistid(smb_ofile_t *new_of, uint64_t persistid)
1130 {
1131 	smb_hash_t *hash = new_of->f_server->sv_persistid_ht;
1132 	smb_bucket_t *bucket;
1133 	smb_llist_t *ll;
1134 	smb_ofile_t *of;
1135 	uint_t idx;
1136 
1137 	ASSERT(persistid != 0);
1138 
1139 	/*
1140 	 * Look to see if this key alreay exists.
1141 	 */
1142 	idx = smb_hash_uint64(hash, persistid);
1143 	bucket = &hash->buckets[idx];
1144 	ll = &bucket->b_list;
1145 
1146 	smb_llist_enter(ll, RW_WRITER);
1147 	of = smb_llist_head(ll);
1148 	while (of != NULL) {
1149 		if (of->f_persistid == persistid) {
1150 			/* already in use */
1151 			smb_llist_exit(ll);
1152 			return (EEXIST);
1153 		}
1154 		of = smb_llist_next(ll, of);
1155 	}
1156 
1157 	/* Not found, so OK to insert. */
1158 	if (new_of->f_persistid == 0) {
1159 		new_of->f_persistid = persistid;
1160 		smb_llist_insert_tail(ll, new_of);
1161 	}
1162 	smb_llist_exit(ll);
1163 
1164 	return (0);
1165 }
1166 
1167 void
1168 smb_ofile_del_persistid(smb_ofile_t *of)
1169 {
1170 	smb_hash_t *hash = of->f_server->sv_persistid_ht;
1171 	smb_bucket_t *bucket;
1172 	smb_llist_t *ll;
1173 	uint_t idx;
1174 
1175 	idx = smb_hash_uint64(hash, of->f_persistid);
1176 	bucket = &hash->buckets[idx];
1177 	ll = &bucket->b_list;
1178 	smb_llist_enter(ll, RW_WRITER);
1179 	if (of->f_persistid != 0) {
1180 		smb_llist_remove(ll, of);
1181 		of->f_persistid = 0;
1182 	}
1183 	smb_llist_exit(ll);
1184 }
1185 
1186 /*
1187  * Disallow NetFileClose on certain ofiles to avoid side-effects.
1188  * Closing a tree root is not allowed: use NetSessionDel or NetShareDel.
1189  * Closing SRVSVC connections is not allowed because this NetFileClose
1190  * request may depend on this ofile.
1191  */
1192 boolean_t
1193 smb_ofile_disallow_fclose(smb_ofile_t *of)
1194 {
1195 	ASSERT(of);
1196 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1197 	ASSERT(of->f_refcnt);
1198 
1199 	switch (of->f_ftype) {
1200 	case SMB_FTYPE_DISK:
1201 		ASSERT(of->f_tree);
1202 		return (of->f_node == of->f_tree->t_snode);
1203 
1204 	case SMB_FTYPE_MESG_PIPE:
1205 		ASSERT(of->f_pipe);
1206 		if (smb_strcasecmp(of->f_pipe->p_name, "SRVSVC", 0) == 0)
1207 			return (B_TRUE);
1208 		break;
1209 	default:
1210 		break;
1211 	}
1212 
1213 	return (B_FALSE);
1214 }
1215 
1216 /*
1217  * smb_ofile_set_flags
1218  *
1219  * Return value:
1220  *
1221  *	Current flags value
1222  *
1223  */
1224 void
1225 smb_ofile_set_flags(
1226     smb_ofile_t		*of,
1227     uint32_t		flags)
1228 {
1229 	ASSERT(of);
1230 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1231 	ASSERT(of->f_refcnt);
1232 
1233 	mutex_enter(&of->f_mutex);
1234 	of->f_flags |= flags;
1235 	mutex_exit(&of->f_mutex);
1236 }
1237 
1238 /*
1239  * smb_ofile_seek
1240  *
1241  * Return value:
1242  *
1243  *	0		Success
1244  *	EINVAL		Unknown mode
1245  *	EOVERFLOW	offset too big
1246  *
1247  */
1248 int
1249 smb_ofile_seek(
1250     smb_ofile_t		*of,
1251     ushort_t		mode,
1252     int32_t		off,
1253     uint32_t		*retoff)
1254 {
1255 	u_offset_t	newoff = 0;
1256 	int		rc = 0;
1257 	smb_attr_t	attr;
1258 
1259 	ASSERT(of);
1260 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1261 	ASSERT(of->f_refcnt);
1262 
1263 	mutex_enter(&of->f_mutex);
1264 	switch (mode) {
1265 	case SMB_SEEK_SET:
1266 		if (off < 0)
1267 			newoff = 0;
1268 		else
1269 			newoff = (u_offset_t)off;
1270 		break;
1271 
1272 	case SMB_SEEK_CUR:
1273 		if (off < 0 && (-off) > of->f_seek_pos)
1274 			newoff = 0;
1275 		else
1276 			newoff = of->f_seek_pos + (u_offset_t)off;
1277 		break;
1278 
1279 	case SMB_SEEK_END:
1280 		bzero(&attr, sizeof (smb_attr_t));
1281 		attr.sa_mask |= SMB_AT_SIZE;
1282 		rc = smb_fsop_getattr(NULL, zone_kcred(), of->f_node, &attr);
1283 		if (rc != 0) {
1284 			mutex_exit(&of->f_mutex);
1285 			return (rc);
1286 		}
1287 		if (off < 0 && (-off) > attr.sa_vattr.va_size)
1288 			newoff = 0;
1289 		else
1290 			newoff = attr.sa_vattr.va_size + (u_offset_t)off;
1291 		break;
1292 
1293 	default:
1294 		mutex_exit(&of->f_mutex);
1295 		return (EINVAL);
1296 	}
1297 
1298 	/*
1299 	 * See comments at the beginning of smb_seek.c.
1300 	 * If the offset is greater than UINT_MAX, we will return an error.
1301 	 */
1302 
1303 	if (newoff > UINT_MAX) {
1304 		rc = EOVERFLOW;
1305 	} else {
1306 		of->f_seek_pos = newoff;
1307 		*retoff = (uint32_t)newoff;
1308 	}
1309 	mutex_exit(&of->f_mutex);
1310 	return (rc);
1311 }
1312 
1313 /*
1314  * smb_ofile_flush
1315  *
1316  * If writes on this file are not synchronous, flush it using the NFSv3
1317  * commit interface.
1318  *
1319  * XXX - todo: Flush named pipe should drain writes.
1320  */
1321 void
1322 smb_ofile_flush(struct smb_request *sr, struct smb_ofile *of)
1323 {
1324 	switch (of->f_ftype) {
1325 	case SMB_FTYPE_DISK:
1326 		if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0)
1327 			(void) smb_fsop_commit(sr, of->f_cr, of->f_node);
1328 		break;
1329 	default:
1330 		break;
1331 	}
1332 }
1333 
1334 /*
1335  * smb_ofile_is_open
1336  */
1337 boolean_t
1338 smb_ofile_is_open(smb_ofile_t *of)
1339 {
1340 	boolean_t	rc;
1341 
1342 	SMB_OFILE_VALID(of);
1343 
1344 	mutex_enter(&of->f_mutex);
1345 	rc = smb_ofile_is_open_locked(of);
1346 	mutex_exit(&of->f_mutex);
1347 	return (rc);
1348 }
1349 
1350 /* *************************** Static Functions ***************************** */
1351 
1352 /*
1353  * Determine whether or not an ofile is open.
1354  * This function must be called with the mutex held.
1355  */
1356 static boolean_t
1357 smb_ofile_is_open_locked(smb_ofile_t *of)
1358 {
1359 	ASSERT(MUTEX_HELD(&of->f_mutex));
1360 
1361 	switch (of->f_state) {
1362 	case SMB_OFILE_STATE_OPEN:
1363 	case SMB_OFILE_STATE_SAVE_DH:
1364 	case SMB_OFILE_STATE_SAVING:
1365 	case SMB_OFILE_STATE_ORPHANED:
1366 	case SMB_OFILE_STATE_RECONNECT:
1367 		return (B_TRUE);
1368 
1369 	case SMB_OFILE_STATE_CLOSING:
1370 	case SMB_OFILE_STATE_CLOSED:
1371 	case SMB_OFILE_STATE_EXPIRED:
1372 		return (B_FALSE);
1373 
1374 	default:
1375 		ASSERT(0);
1376 		return (B_FALSE);
1377 	}
1378 }
1379 
1380 /*
1381  * smb_ofile_save_dh
1382  *
1383  * Called via smb_llist_post (after smb_llist_exit) when the last ref.
1384  * on this ofile has gone, and this ofile is a "durable handle" (DH)
1385  * that has state we've decided to save.
1386  *
1387  * This does parts of what smb_ofile_delete would do, including:
1388  * remove the ofile from the tree ofile list and related.
1389  *
1390  * We leave the ofile in state ORPHANED, ready for reconnect
1391  * or expiration via smb2_dh_expire (see smb_ofile_delete).
1392  */
1393 static void
1394 smb_ofile_save_dh(void *arg)
1395 {
1396 	smb_ofile_t	*of = (smb_ofile_t *)arg;
1397 	smb_tree_t	*tree = of->f_tree;
1398 
1399 	SMB_OFILE_VALID(of);
1400 	ASSERT(of->f_refcnt == 0);
1401 	ASSERT(of->f_ftype == SMB_FTYPE_DISK);
1402 	ASSERT(of->f_state == SMB_OFILE_STATE_SAVING);
1403 
1404 	atomic_dec_32(&of->f_session->s_file_cnt);
1405 	atomic_dec_32(&of->f_tree->t_open_files);
1406 	smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
1407 	smb_llist_remove(&tree->t_ofile_list, of);
1408 	smb_llist_exit(&tree->t_ofile_list);
1409 
1410 	/*
1411 	 * This ofile is no longer on t_ofile_list, however...
1412 	 *
1413 	 * This is called via smb_llist_post, which means it may run
1414 	 * BEFORE smb_ofile_release drops f_mutex (if another thread
1415 	 * flushes the delete queue before we do).  Synchronize.
1416 	 */
1417 	mutex_enter(&of->f_mutex);
1418 	DTRACE_PROBE1(ofile__exit, smb_ofile_t *, of);
1419 	mutex_exit(&of->f_mutex);
1420 
1421 	/*
1422 	 * Keep f_notify state, lease, and
1423 	 * keep on node ofile list.
1424 	 * Keep of->f_cr until reclaim.
1425 	 */
1426 
1427 	ASSERT(of->f_fid != 0);
1428 	smb_idpool_free(&tree->t_fid_pool, of->f_fid);
1429 	of->f_fid = 0;
1430 	smb_tree_release(of->f_tree);
1431 	of->f_tree = NULL;
1432 	smb_user_release(of->f_user);
1433 	of->f_user = NULL;
1434 	of->f_session = NULL;
1435 
1436 	/*
1437 	 * Make it "orphaned" so it can now be reclaimed.
1438 	 * Note that smb_ofile_hold_olbrk() may have blocked
1439 	 * for state SMB_OFILE_STATE_SAVING, so wake it.
1440 	 */
1441 	mutex_enter(&of->f_mutex);
1442 	of->dh_expire_time = gethrtime() + of->dh_timeout_offset;
1443 	of->f_state = SMB_OFILE_STATE_ORPHANED;
1444 	cv_broadcast(&of->f_cv);
1445 	mutex_exit(&of->f_mutex);
1446 }
1447 
1448 /*
1449  * Delete an ofile.
1450  *
1451  * Approximately the inverse of smb_ofile_alloc()
1452  * Called via smb_llist_post (after smb_llist_exit)
1453  * when the last ref. on this ofile has gone.
1454  *
1455  * Normally,this removes the ofile from the tree list and
1456  * then frees resources held on the ofile.  However, when
1457  * we're expiring an orphaned durable handle, the linkage
1458  * into the tree lists etc. have already been destroyed.
1459  * This case is distinguished by of->f_tree == NULL.
1460  */
1461 static void
1462 smb_ofile_delete(void *arg)
1463 {
1464 	smb_ofile_t	*of = (smb_ofile_t *)arg;
1465 	smb_tree_t	*tree = of->f_tree;
1466 
1467 	SMB_OFILE_VALID(of);
1468 	ASSERT(of->f_refcnt == 0);
1469 	ASSERT(of->f_state == SMB_OFILE_STATE_CLOSED);
1470 
1471 	if (tree != NULL) {
1472 		ASSERT(of->f_user != NULL);
1473 		ASSERT(of->f_session != NULL);
1474 		atomic_dec_32(&of->f_session->s_file_cnt);
1475 		atomic_dec_32(&of->f_tree->t_open_files);
1476 		smb_llist_enter(&tree->t_ofile_list, RW_WRITER);
1477 		smb_llist_remove(&tree->t_ofile_list, of);
1478 		smb_llist_exit(&tree->t_ofile_list);
1479 	}
1480 
1481 	/*
1482 	 * Remove this ofile from the node's n_ofile_list so it
1483 	 * can't be found by list walkers like notify or oplock.
1484 	 * Keep the node ref. until later in this function so
1485 	 * of->f_node remains valid while we destroy the ofile.
1486 	 */
1487 	if (of->f_ftype == SMB_FTYPE_DISK ||
1488 	    of->f_ftype == SMB_FTYPE_PRINTER) {
1489 		smb_node_t *node = of->f_node;
1490 
1491 		/*
1492 		 * Oplock cleanup should have made sure that
1493 		 * excl_open does not point to this ofile.
1494 		 */
1495 		VERIFY(node->n_oplock.excl_open != of);
1496 
1497 		/*
1498 		 * Note smb_ofile_close did smb_node_dec_open_ofiles()
1499 		 */
1500 		smb_node_rem_ofile(node, of);
1501 	}
1502 
1503 	/*
1504 	 * This ofile is no longer on any lists, however...
1505 	 *
1506 	 * This is called via smb_llist_post, which means it may run
1507 	 * BEFORE smb_ofile_release drops f_mutex (if another thread
1508 	 * flushes the delete queue before we do).  Synchronize.
1509 	 */
1510 	mutex_enter(&of->f_mutex);
1511 	of->f_state = SMB_OFILE_STATE_ALLOC;
1512 	DTRACE_PROBE1(ofile__exit, smb_ofile_t *, of);
1513 	mutex_exit(&of->f_mutex);
1514 
1515 	switch (of->f_ftype) {
1516 	case SMB_FTYPE_BYTE_PIPE:
1517 	case SMB_FTYPE_MESG_PIPE:
1518 		smb_opipe_dealloc(of->f_pipe);
1519 		of->f_pipe = NULL;
1520 		break;
1521 	case SMB_FTYPE_DISK:
1522 		ASSERT(of->f_notify.nc_subscribed == B_FALSE);
1523 		MBC_FLUSH(&of->f_notify.nc_buffer);
1524 		if (of->f_odir != NULL)
1525 			smb_odir_release(of->f_odir);
1526 		if (of->f_lease != NULL) {
1527 			smb2_lease_rele(of->f_lease);
1528 			of->f_lease = NULL;
1529 		}
1530 		/* FALLTHROUGH */
1531 	case SMB_FTYPE_PRINTER:
1532 		/*
1533 		 * Did smb_node_rem_ofile above.
1534 		 */
1535 		ASSERT(of->f_node != NULL);
1536 		smb_node_release(of->f_node);
1537 		break;
1538 	default:
1539 		ASSERT(!"f_ftype");
1540 		break;
1541 	}
1542 
1543 	smb_ofile_free(of);
1544 }
1545 
1546 void
1547 smb_ofile_free(smb_ofile_t *of)
1548 {
1549 	smb_tree_t	*tree = of->f_tree;
1550 
1551 	ASSERT(of->f_state == SMB_OFILE_STATE_ALLOC);
1552 
1553 	/* Make sure it's not in the persistid hash. */
1554 	ASSERT(of->f_persistid == 0);
1555 
1556 	if (tree != NULL) {
1557 		if (of->f_fid != 0)
1558 			smb_idpool_free(&tree->t_fid_pool, of->f_fid);
1559 		smb_tree_release(of->f_tree);
1560 		smb_user_release(of->f_user);
1561 	}
1562 
1563 	if (of->f_cr != NULL)
1564 		crfree(of->f_cr);
1565 
1566 	of->f_magic = (uint32_t)~SMB_OFILE_MAGIC;
1567 	list_destroy(&of->f_notify.nc_waiters);
1568 	mutex_destroy(&of->dh_nvlock);
1569 	mutex_destroy(&of->f_mutex);
1570 	kmem_cache_free(smb_cache_ofile, of);
1571 }
1572 
1573 /*
1574  * smb_ofile_access
1575  *
1576  * This function will check to see if the access requested is granted.
1577  * Returns NT status codes.
1578  */
1579 uint32_t
1580 smb_ofile_access(smb_ofile_t *of, cred_t *cr, uint32_t access)
1581 {
1582 
1583 	if ((of == NULL) || (cr == zone_kcred()))
1584 		return (NT_STATUS_SUCCESS);
1585 
1586 	/*
1587 	 * If the request is for something
1588 	 * I don't grant it is an error
1589 	 */
1590 	if (~(of->f_granted_access) & access) {
1591 		if (!(of->f_granted_access & ACCESS_SYSTEM_SECURITY) &&
1592 		    (access & ACCESS_SYSTEM_SECURITY)) {
1593 			return (NT_STATUS_PRIVILEGE_NOT_HELD);
1594 		}
1595 		return (NT_STATUS_ACCESS_DENIED);
1596 	}
1597 
1598 	return (NT_STATUS_SUCCESS);
1599 }
1600 
1601 /*
1602  * smb_ofile_share_check
1603  *
1604  * Check if ofile was opened with share access NONE (0).
1605  * Returns: B_TRUE  - share access non-zero
1606  *          B_FALSE - share access NONE
1607  */
1608 boolean_t
1609 smb_ofile_share_check(smb_ofile_t *of)
1610 {
1611 	return (!SMB_DENY_ALL(of->f_share_access));
1612 }
1613 
1614 /*
1615  * check file sharing rules for current open request
1616  * against existing open instances of the same file
1617  *
1618  * Returns NT_STATUS_SHARING_VIOLATION if there is any
1619  * sharing conflict, otherwise returns NT_STATUS_SUCCESS.
1620  */
1621 uint32_t
1622 smb_ofile_open_check(smb_ofile_t *of, uint32_t desired_access,
1623     uint32_t share_access)
1624 {
1625 	uint32_t ret;
1626 
1627 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1628 
1629 	mutex_enter(&of->f_mutex);
1630 
1631 	if (!smb_ofile_is_open_locked(of)) {
1632 		ret = NT_STATUS_INVALID_HANDLE;
1633 		goto out;
1634 	}
1635 
1636 	/* if it's just meta data */
1637 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1638 		ret = NT_STATUS_SUCCESS;
1639 		goto out;
1640 	}
1641 
1642 	/*
1643 	 * Check requested share access against the
1644 	 * open granted (desired) access
1645 	 */
1646 	if (SMB_DENY_DELETE(share_access) && (of->f_granted_access & DELETE)) {
1647 		ret = NT_STATUS_SHARING_VIOLATION;
1648 		goto out;
1649 	}
1650 
1651 	if (SMB_DENY_READ(share_access) &&
1652 	    (of->f_granted_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1653 		ret = NT_STATUS_SHARING_VIOLATION;
1654 		goto out;
1655 	}
1656 
1657 	if (SMB_DENY_WRITE(share_access) &&
1658 	    (of->f_granted_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1659 		ret = NT_STATUS_SHARING_VIOLATION;
1660 		goto out;
1661 	}
1662 
1663 	/* check requested desired access against the open share access */
1664 	if (SMB_DENY_DELETE(of->f_share_access) && (desired_access & DELETE)) {
1665 		ret = NT_STATUS_SHARING_VIOLATION;
1666 		goto out;
1667 	}
1668 
1669 	if (SMB_DENY_READ(of->f_share_access) &&
1670 	    (desired_access & (FILE_READ_DATA | FILE_EXECUTE))) {
1671 		ret = NT_STATUS_SHARING_VIOLATION;
1672 		goto out;
1673 	}
1674 
1675 	if (SMB_DENY_WRITE(of->f_share_access) &&
1676 	    (desired_access & (FILE_WRITE_DATA | FILE_APPEND_DATA))) {
1677 		ret = NT_STATUS_SHARING_VIOLATION;
1678 		goto out;
1679 	}
1680 
1681 	ret = NT_STATUS_SUCCESS;
1682 out:
1683 	mutex_exit(&of->f_mutex);
1684 	return (ret);
1685 }
1686 
1687 /*
1688  * smb_ofile_rename_check
1689  *
1690  * This does the work described in MS-FSA 2.1.5.1.2.2 (Algorithm
1691  * to Check Sharing Access to an Existing Stream or Directory),
1692  * where the "open in-progress" has DesiredAccess = DELETE and
1693  * SharingMode = SHARE_READ | SHARE_WRITE | SHARE_DELETE.
1694  */
1695 
1696 uint32_t
1697 smb_ofile_rename_check(smb_ofile_t *of)
1698 {
1699 	uint32_t ret;
1700 
1701 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1702 
1703 	mutex_enter(&of->f_mutex);
1704 
1705 	if (!smb_ofile_is_open_locked(of)) {
1706 		ret = NT_STATUS_INVALID_HANDLE;
1707 		goto out;
1708 	}
1709 
1710 	if ((of->f_granted_access & FILE_DATA_ALL) == 0) {
1711 		ret = NT_STATUS_SUCCESS;
1712 		goto out;
1713 	}
1714 
1715 	if ((of->f_share_access & FILE_SHARE_DELETE) == 0) {
1716 		ret = NT_STATUS_SHARING_VIOLATION;
1717 		goto out;
1718 	}
1719 
1720 	ret = NT_STATUS_SUCCESS;
1721 out:
1722 	mutex_exit(&of->f_mutex);
1723 	return (ret);
1724 }
1725 
1726 /*
1727  * smb_ofile_delete_check
1728  *
1729  * An open file can be deleted only if opened for
1730  * accessing meta data. Share modes aren't important
1731  * in this case.
1732  *
1733  * NOTE: there is another mechanism for deleting an
1734  * open file that NT clients usually use.
1735  * That's setting "Delete on close" flag for an open
1736  * file.  In this way the file will be deleted after
1737  * last close. This flag can be set by SmbTrans2SetFileInfo
1738  * with FILE_DISPOSITION_INFO information level.
1739  * For setting this flag, the file should be opened by
1740  * DELETE access in the FID that is passed in the Trans2
1741  * request.
1742  */
1743 
1744 uint32_t
1745 smb_ofile_delete_check(smb_ofile_t *of)
1746 {
1747 	uint32_t ret;
1748 
1749 	ASSERT(of->f_magic == SMB_OFILE_MAGIC);
1750 
1751 	mutex_enter(&of->f_mutex);
1752 
1753 	if (!smb_ofile_is_open_locked(of)) {
1754 		ret = NT_STATUS_INVALID_HANDLE;
1755 		goto out;
1756 	}
1757 
1758 	if (of->f_granted_access &
1759 	    (FILE_READ_DATA | FILE_WRITE_DATA |
1760 	    FILE_APPEND_DATA | FILE_EXECUTE | DELETE)) {
1761 		ret = NT_STATUS_SHARING_VIOLATION;
1762 		goto out;
1763 	}
1764 
1765 	ret = NT_STATUS_SUCCESS;
1766 out:
1767 	mutex_exit(&of->f_mutex);
1768 	return (ret);
1769 }
1770 
1771 cred_t *
1772 smb_ofile_getcred(smb_ofile_t *of)
1773 {
1774 	return (of->f_cr);
1775 }
1776 
1777 /*
1778  * smb_ofile_set_delete_on_close
1779  *
1780  * Set the DeleteOnClose flag on the smb file. When the file is closed,
1781  * the flag will be transferred to the smb node, which will commit the
1782  * delete operation and inhibit subsequent open requests.
1783  *
1784  * When DeleteOnClose is set on an smb_node, the common open code will
1785  * reject subsequent open requests for the file. Observation of Windows
1786  * 2000 indicates that subsequent opens should be allowed (assuming
1787  * there would be no sharing violation) until the file is closed using
1788  * the fid on which the DeleteOnClose was requested.
1789  */
1790 void
1791 smb_ofile_set_delete_on_close(smb_request_t *sr, smb_ofile_t *of)
1792 {
1793 	uint32_t	status;
1794 
1795 	/*
1796 	 * Break any oplock handle caching.
1797 	 */
1798 	status = smb_oplock_break_SETINFO(of->f_node, of,
1799 	    FileDispositionInformation);
1800 	if (status == NT_STATUS_OPLOCK_BREAK_IN_PROGRESS) {
1801 		if (sr->session->dialect >= SMB_VERS_2_BASE)
1802 			(void) smb2sr_go_async(sr);
1803 		(void) smb_oplock_wait_break(sr, of->f_node, 0);
1804 	}
1805 
1806 	mutex_enter(&of->f_mutex);
1807 	of->f_flags |= SMB_OFLAGS_SET_DELETE_ON_CLOSE;
1808 	mutex_exit(&of->f_mutex);
1809 }
1810 
1811 /*
1812  * Encode open file information into a buffer; needed in user space to
1813  * support RPC requests.
1814  */
1815 static int
1816 smb_ofile_netinfo_encode(smb_ofile_t *of, uint8_t *buf, size_t buflen,
1817     uint32_t *nbytes)
1818 {
1819 	smb_netfileinfo_t	fi;
1820 	int			rc;
1821 
1822 	rc = smb_ofile_netinfo_init(of, &fi);
1823 	if (rc == 0) {
1824 		rc = smb_netfileinfo_encode(&fi, buf, buflen, nbytes);
1825 		smb_ofile_netinfo_fini(&fi);
1826 	}
1827 
1828 	return (rc);
1829 }
1830 
1831 static int
1832 smb_ofile_netinfo_init(smb_ofile_t *of, smb_netfileinfo_t *fi)
1833 {
1834 	smb_user_t	*user;
1835 	smb_tree_t	*tree;
1836 	smb_node_t	*node;
1837 	char		*path;
1838 	char		*buf;
1839 	int		rc;
1840 
1841 	ASSERT(of);
1842 	user = of->f_user;
1843 	tree = of->f_tree;
1844 	ASSERT(user);
1845 	ASSERT(tree);
1846 
1847 	buf = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1848 
1849 	switch (of->f_ftype) {
1850 	case SMB_FTYPE_DISK:
1851 		node = of->f_node;
1852 		ASSERT(node);
1853 
1854 		fi->fi_permissions = of->f_granted_access;
1855 		fi->fi_numlocks = smb_lock_get_lock_count(node, of);
1856 
1857 		path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1858 
1859 		if (node != tree->t_snode) {
1860 			rc = smb_node_getshrpath(node, tree, path, MAXPATHLEN);
1861 			if (rc != 0)
1862 				(void) strlcpy(path, node->od_name, MAXPATHLEN);
1863 		}
1864 
1865 		(void) snprintf(buf, MAXPATHLEN, "%s:%s", tree->t_sharename,
1866 		    path);
1867 		kmem_free(path, MAXPATHLEN);
1868 		break;
1869 
1870 	case SMB_FTYPE_MESG_PIPE:
1871 		ASSERT(of->f_pipe);
1872 
1873 		fi->fi_permissions = FILE_READ_DATA | FILE_WRITE_DATA |
1874 		    FILE_EXECUTE;
1875 		fi->fi_numlocks = 0;
1876 		(void) snprintf(buf, MAXPATHLEN, "\\PIPE\\%s",
1877 		    of->f_pipe->p_name);
1878 		break;
1879 
1880 	default:
1881 		kmem_free(buf, MAXPATHLEN);
1882 		return (-1);
1883 	}
1884 
1885 	fi->fi_fid = of->f_fid;
1886 	fi->fi_uniqid = of->f_uniqid;
1887 	fi->fi_pathlen = strlen(buf) + 1;
1888 	fi->fi_path = smb_mem_strdup(buf);
1889 	kmem_free(buf, MAXPATHLEN);
1890 
1891 	fi->fi_namelen = user->u_domain_len + user->u_name_len + 2;
1892 	fi->fi_username = kmem_alloc(fi->fi_namelen, KM_SLEEP);
1893 	(void) snprintf(fi->fi_username, fi->fi_namelen, "%s\\%s",
1894 	    user->u_domain, user->u_name);
1895 	return (0);
1896 }
1897 
1898 static void
1899 smb_ofile_netinfo_fini(smb_netfileinfo_t *fi)
1900 {
1901 	if (fi == NULL)
1902 		return;
1903 
1904 	if (fi->fi_path)
1905 		smb_mem_free(fi->fi_path);
1906 	if (fi->fi_username)
1907 		kmem_free(fi->fi_username, fi->fi_namelen);
1908 
1909 	bzero(fi, sizeof (smb_netfileinfo_t));
1910 }
1911 
1912 /*
1913  * A query of user and group quotas may span multiple requests.
1914  * f_quota_resume is used to determine where the query should
1915  * be resumed, in a subsequent request. f_quota_resume contains
1916  * the SID of the last quota entry returned to the client.
1917  */
1918 void
1919 smb_ofile_set_quota_resume(smb_ofile_t *ofile, char *resume)
1920 {
1921 	ASSERT(ofile);
1922 	mutex_enter(&ofile->f_mutex);
1923 	if (resume == NULL)
1924 		bzero(ofile->f_quota_resume, SMB_SID_STRSZ);
1925 	else
1926 		(void) strlcpy(ofile->f_quota_resume, resume, SMB_SID_STRSZ);
1927 	mutex_exit(&ofile->f_mutex);
1928 }
1929 
1930 void
1931 smb_ofile_get_quota_resume(smb_ofile_t *ofile, char *buf, int bufsize)
1932 {
1933 	ASSERT(ofile);
1934 	mutex_enter(&ofile->f_mutex);
1935 	(void) strlcpy(buf, ofile->f_quota_resume, bufsize);
1936 	mutex_exit(&ofile->f_mutex);
1937 }
1938