r23784: use the GPLv3 boilerplate as recommended by the FSF and the license text
[Samba/bb.git] / source / locking / locking.c
blobc7fb572b1ddcb53a4f78ae33f5e64a0caba1d5e3
1 /*
2 Unix SMB/CIFS implementation.
3 Locking functions
4 Copyright (C) Andrew Tridgell 1992-2000
5 Copyright (C) Jeremy Allison 1992-2006
6 Copyright (C) Volker Lendecke 2005
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 Revision History:
23 12 aug 96: Erik.Devriendt@te6.siemens.be
24 added support for shared memory implementation of share mode locking
26 May 1997. Jeremy Allison (jallison@whistle.com). Modified share mode
27 locking to deal with multiple share modes per open file.
29 September 1997. Jeremy Allison (jallison@whistle.com). Added oplock
30 support.
32 rewrtten completely to use new tdb code. Tridge, Dec '99
34 Added POSIX locking support. Jeremy Allison (jeremy@valinux.com), Apr. 2000.
35 Added Unix Extensions POSIX locking support. Jeremy Allison Mar 2006.
38 #include "includes.h"
40 #undef DBGC_CLASS
41 #define DBGC_CLASS DBGC_LOCKING
43 /* the locking database handle */
44 static struct db_context *lock_db;
46 /****************************************************************************
47 Debugging aids :-).
48 ****************************************************************************/
50 const char *lock_type_name(enum brl_type lock_type)
52 switch (lock_type) {
53 case READ_LOCK:
54 return "READ";
55 case WRITE_LOCK:
56 return "WRITE";
57 case PENDING_READ_LOCK:
58 return "PENDING_READ";
59 case PENDING_WRITE_LOCK:
60 return "PENDING_WRITE";
61 default:
62 return "other";
66 const char *lock_flav_name(enum brl_flavour lock_flav)
68 return (lock_flav == WINDOWS_LOCK) ? "WINDOWS_LOCK" : "POSIX_LOCK";
71 /****************************************************************************
72 Utility function called to see if a file region is locked.
73 Called in the read/write codepath.
74 ****************************************************************************/
76 BOOL is_locked(files_struct *fsp,
77 uint32 smbpid,
78 SMB_BIG_UINT count,
79 SMB_BIG_UINT offset,
80 enum brl_type lock_type)
82 int strict_locking = lp_strict_locking(fsp->conn->params);
83 enum brl_flavour lock_flav = lp_posix_cifsu_locktype(fsp);
84 BOOL ret = True;
86 if (count == 0) {
87 return False;
90 if (!lp_locking(fsp->conn->params) || !strict_locking) {
91 return False;
94 if (strict_locking == Auto) {
95 if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && (lock_type == READ_LOCK || lock_type == WRITE_LOCK)) {
96 DEBUG(10,("is_locked: optimisation - exclusive oplock on file %s\n", fsp->fsp_name ));
97 ret = False;
98 } else if ((fsp->oplock_type == LEVEL_II_OPLOCK) &&
99 (lock_type == READ_LOCK)) {
100 DEBUG(10,("is_locked: optimisation - level II oplock on file %s\n", fsp->fsp_name ));
101 ret = False;
102 } else {
103 struct byte_range_lock *br_lck = brl_get_locks_readonly(NULL, fsp);
104 if (!br_lck) {
105 return False;
107 ret = !brl_locktest(br_lck,
108 smbpid,
109 procid_self(),
110 offset,
111 count,
112 lock_type,
113 lock_flav);
114 TALLOC_FREE(br_lck);
116 } else {
117 struct byte_range_lock *br_lck = brl_get_locks_readonly(NULL, fsp);
118 if (!br_lck) {
119 return False;
121 ret = !brl_locktest(br_lck,
122 smbpid,
123 procid_self(),
124 offset,
125 count,
126 lock_type,
127 lock_flav);
128 TALLOC_FREE(br_lck);
131 DEBUG(10,("is_locked: flavour = %s brl start=%.0f len=%.0f %s for fnum %d file %s\n",
132 lock_flav_name(lock_flav),
133 (double)offset, (double)count, ret ? "locked" : "unlocked",
134 fsp->fnum, fsp->fsp_name ));
136 return ret;
139 /****************************************************************************
140 Find out if a lock could be granted - return who is blocking us if we can't.
141 ****************************************************************************/
143 NTSTATUS query_lock(files_struct *fsp,
144 uint32 *psmbpid,
145 SMB_BIG_UINT *pcount,
146 SMB_BIG_UINT *poffset,
147 enum brl_type *plock_type,
148 enum brl_flavour lock_flav)
150 struct byte_range_lock *br_lck = NULL;
151 NTSTATUS status = NT_STATUS_LOCK_NOT_GRANTED;
153 if (!fsp->can_lock) {
154 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
157 if (!lp_locking(fsp->conn->params)) {
158 return NT_STATUS_OK;
161 br_lck = brl_get_locks_readonly(NULL, fsp);
162 if (!br_lck) {
163 return NT_STATUS_NO_MEMORY;
166 status = brl_lockquery(br_lck,
167 psmbpid,
168 procid_self(),
169 poffset,
170 pcount,
171 plock_type,
172 lock_flav);
174 TALLOC_FREE(br_lck);
175 return status;
178 /****************************************************************************
179 Utility function called by locking requests.
180 ****************************************************************************/
182 struct byte_range_lock *do_lock(struct messaging_context *msg_ctx,
183 files_struct *fsp,
184 uint32 lock_pid,
185 SMB_BIG_UINT count,
186 SMB_BIG_UINT offset,
187 enum brl_type lock_type,
188 enum brl_flavour lock_flav,
189 BOOL blocking_lock,
190 NTSTATUS *perr,
191 uint32 *plock_pid)
193 struct byte_range_lock *br_lck = NULL;
195 if (!fsp->can_lock) {
196 *perr = fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
197 return NULL;
200 if (!lp_locking(fsp->conn->params)) {
201 *perr = NT_STATUS_OK;
202 return NULL;
205 /* NOTE! 0 byte long ranges ARE allowed and should be stored */
207 DEBUG(10,("do_lock: lock flavour %s lock type %s start=%.0f len=%.0f requested for fnum %d file %s\n",
208 lock_flav_name(lock_flav), lock_type_name(lock_type),
209 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
211 br_lck = brl_get_locks(NULL, fsp);
212 if (!br_lck) {
213 *perr = NT_STATUS_NO_MEMORY;
214 return NULL;
217 *perr = brl_lock(msg_ctx,
218 br_lck,
219 lock_pid,
220 procid_self(),
221 offset,
222 count,
223 lock_type,
224 lock_flav,
225 blocking_lock,
226 plock_pid);
228 /* blocking ie. pending, locks also count here,
229 * as this is an efficiency counter to avoid checking
230 * the lock db. on close. JRA. */
232 fsp->current_lock_count++;
234 return br_lck;
237 /****************************************************************************
238 Utility function called by unlocking requests.
239 ****************************************************************************/
241 NTSTATUS do_unlock(struct messaging_context *msg_ctx,
242 files_struct *fsp,
243 uint32 lock_pid,
244 SMB_BIG_UINT count,
245 SMB_BIG_UINT offset,
246 enum brl_flavour lock_flav)
248 BOOL ok = False;
249 struct byte_range_lock *br_lck = NULL;
251 if (!fsp->can_lock) {
252 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
255 if (!lp_locking(fsp->conn->params)) {
256 return NT_STATUS_OK;
259 DEBUG(10,("do_unlock: unlock start=%.0f len=%.0f requested for fnum %d file %s\n",
260 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
262 br_lck = brl_get_locks(NULL, fsp);
263 if (!br_lck) {
264 return NT_STATUS_NO_MEMORY;
267 ok = brl_unlock(msg_ctx,
268 br_lck,
269 lock_pid,
270 procid_self(),
271 offset,
272 count,
273 lock_flav);
275 TALLOC_FREE(br_lck);
277 if (!ok) {
278 DEBUG(10,("do_unlock: returning ERRlock.\n" ));
279 return NT_STATUS_RANGE_NOT_LOCKED;
282 SMB_ASSERT(fsp->current_lock_count > 0);
283 fsp->current_lock_count--;
285 return NT_STATUS_OK;
288 /****************************************************************************
289 Cancel any pending blocked locks.
290 ****************************************************************************/
292 NTSTATUS do_lock_cancel(files_struct *fsp,
293 uint32 lock_pid,
294 SMB_BIG_UINT count,
295 SMB_BIG_UINT offset,
296 enum brl_flavour lock_flav)
298 BOOL ok = False;
299 struct byte_range_lock *br_lck = NULL;
301 if (!fsp->can_lock) {
302 return fsp->is_directory ?
303 NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
306 if (!lp_locking(fsp->conn->params)) {
307 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
310 DEBUG(10,("do_lock_cancel: cancel start=%.0f len=%.0f requested for fnum %d file %s\n",
311 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
313 br_lck = brl_get_locks(NULL, fsp);
314 if (!br_lck) {
315 return NT_STATUS_NO_MEMORY;
318 ok = brl_lock_cancel(br_lck,
319 lock_pid,
320 procid_self(),
321 offset,
322 count,
323 lock_flav);
325 TALLOC_FREE(br_lck);
327 if (!ok) {
328 DEBUG(10,("do_lock_cancel: returning ERRcancelviolation.\n" ));
329 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
332 SMB_ASSERT(fsp->current_lock_count > 0);
333 fsp->current_lock_count--;
335 return NT_STATUS_OK;
338 /****************************************************************************
339 Remove any locks on this fd. Called from file_close().
340 ****************************************************************************/
342 void locking_close_file(struct messaging_context *msg_ctx,
343 files_struct *fsp)
345 struct byte_range_lock *br_lck;
347 if (!lp_locking(fsp->conn->params)) {
348 return;
351 /* If we have not outstanding locks or pending
352 * locks then we don't need to look in the lock db.
355 if (fsp->current_lock_count == 0) {
356 return;
359 br_lck = brl_get_locks(NULL,fsp);
361 if (br_lck) {
362 cancel_pending_lock_requests_by_fid(fsp, br_lck);
363 brl_close_fnum(msg_ctx, br_lck);
364 TALLOC_FREE(br_lck);
368 /****************************************************************************
369 Initialise the locking functions.
370 ****************************************************************************/
372 static int open_read_only;
374 BOOL locking_init(int read_only)
376 brl_init(read_only);
378 if (lock_db)
379 return True;
381 lock_db = db_open(NULL, lock_path("locking.tdb"),
382 lp_open_files_db_hash_size(),
383 TDB_DEFAULT
384 |TDB_VOLATILE
385 |(read_only?0x0:TDB_CLEAR_IF_FIRST),
386 read_only?O_RDONLY:O_RDWR|O_CREAT, 0644);
388 if (!lock_db) {
389 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
390 return False;
393 if (!posix_locking_init(read_only))
394 return False;
396 open_read_only = read_only;
398 return True;
401 /*******************************************************************
402 Deinitialize the share_mode management.
403 ******************************************************************/
405 BOOL locking_end(void)
407 brl_shutdown(open_read_only);
408 if (lock_db) {
409 TALLOC_FREE(lock_db);
411 return True;
414 /*******************************************************************
415 Form a static locking key for a dev/inode pair.
416 ******************************************************************/
418 static TDB_DATA locking_key(struct file_id id)
420 static struct file_id key;
421 TDB_DATA kbuf;
422 key = id;
423 kbuf.dptr = (uint8 *)&key;
424 kbuf.dsize = sizeof(key);
425 return kbuf;
428 /*******************************************************************
429 Print out a share mode.
430 ********************************************************************/
432 char *share_mode_str(int num, struct share_mode_entry *e)
434 static pstring share_str;
436 slprintf(share_str, sizeof(share_str)-1, "share_mode_entry[%d]: %s "
437 "pid = %s, share_access = 0x%x, private_options = 0x%x, "
438 "access_mask = 0x%x, mid = 0x%x, type= 0x%x, gen_id = %lu, "
439 "uid = %u, flags = %u, file_id %s",
440 num,
441 e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
442 procid_str_static(&e->pid),
443 e->share_access, e->private_options,
444 e->access_mask, e->op_mid, e->op_type, e->share_file_id,
445 (unsigned int)e->uid, (unsigned int)e->flags,
446 file_id_static_string(&e->id));
448 return share_str;
451 /*******************************************************************
452 Print out a share mode table.
453 ********************************************************************/
455 static void print_share_mode_table(struct locking_data *data)
457 int num_share_modes = data->u.s.num_share_mode_entries;
458 struct share_mode_entry *shares =
459 (struct share_mode_entry *)(data + 1);
460 int i;
462 for (i = 0; i < num_share_modes; i++) {
463 struct share_mode_entry entry;
465 memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
466 DEBUG(10,("print_share_mode_table: %s\n",
467 share_mode_str(i, &entry)));
471 /*******************************************************************
472 Get all share mode entries for a dev/inode pair.
473 ********************************************************************/
475 static BOOL parse_share_modes(TDB_DATA dbuf, struct share_mode_lock *lck)
477 struct locking_data *data;
478 int i;
480 if (dbuf.dsize < sizeof(struct locking_data)) {
481 smb_panic("parse_share_modes: buffer too short");
484 data = (struct locking_data *)dbuf.dptr;
486 lck->delete_on_close = data->u.s.delete_on_close;
487 lck->num_share_modes = data->u.s.num_share_mode_entries;
489 DEBUG(10, ("parse_share_modes: delete_on_close: %d, "
490 "num_share_modes: %d\n",
491 lck->delete_on_close,
492 lck->num_share_modes));
494 if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
495 DEBUG(0, ("invalid number of share modes: %d\n",
496 lck->num_share_modes));
497 smb_panic("parse_share_modes: invalid number of share modes");
500 lck->share_modes = NULL;
502 if (lck->num_share_modes != 0) {
504 if (dbuf.dsize < (sizeof(struct locking_data) +
505 (lck->num_share_modes *
506 sizeof(struct share_mode_entry)))) {
507 smb_panic("parse_share_modes: buffer too short");
510 lck->share_modes = (struct share_mode_entry *)
511 TALLOC_MEMDUP(lck, dbuf.dptr+sizeof(*data),
512 lck->num_share_modes *
513 sizeof(struct share_mode_entry));
515 if (lck->share_modes == NULL) {
516 smb_panic("parse_share_modes: talloc failed");
520 /* Get any delete token. */
521 if (data->u.s.delete_token_size) {
522 uint8 *p = dbuf.dptr + sizeof(*data) +
523 (lck->num_share_modes *
524 sizeof(struct share_mode_entry));
526 if ((data->u.s.delete_token_size < sizeof(uid_t) + sizeof(gid_t)) ||
527 ((data->u.s.delete_token_size - sizeof(uid_t)) % sizeof(gid_t)) != 0) {
528 DEBUG(0, ("parse_share_modes: invalid token size %d\n",
529 data->u.s.delete_token_size));
530 smb_panic("parse_share_modes: invalid token size");
533 lck->delete_token = TALLOC_P(lck, UNIX_USER_TOKEN);
534 if (!lck->delete_token) {
535 smb_panic("parse_share_modes: talloc failed");
538 /* Copy out the uid and gid. */
539 memcpy(&lck->delete_token->uid, p, sizeof(uid_t));
540 p += sizeof(uid_t);
541 memcpy(&lck->delete_token->gid, p, sizeof(gid_t));
542 p += sizeof(gid_t);
544 /* Any supplementary groups ? */
545 lck->delete_token->ngroups = (data->u.s.delete_token_size > (sizeof(uid_t) + sizeof(gid_t))) ?
546 ((data->u.s.delete_token_size -
547 (sizeof(uid_t) + sizeof(gid_t)))/sizeof(gid_t)) : 0;
549 if (lck->delete_token->ngroups) {
550 /* Make this a talloc child of lck->delete_token. */
551 lck->delete_token->groups = TALLOC_ARRAY(lck->delete_token, gid_t,
552 lck->delete_token->ngroups);
553 if (!lck->delete_token) {
554 smb_panic("parse_share_modes: talloc failed");
557 for (i = 0; i < lck->delete_token->ngroups; i++) {
558 memcpy(&lck->delete_token->groups[i], p, sizeof(gid_t));
559 p += sizeof(gid_t);
563 } else {
564 lck->delete_token = NULL;
567 /* Save off the associated service path and filename. */
568 lck->servicepath = talloc_strdup(lck, (const char *)dbuf.dptr + sizeof(*data) +
569 (lck->num_share_modes *
570 sizeof(struct share_mode_entry)) +
571 data->u.s.delete_token_size );
572 if (lck->servicepath == NULL) {
573 smb_panic("parse_share_modes: talloc_strdup failed");
576 lck->filename = talloc_strdup(lck, (const char *)dbuf.dptr + sizeof(*data) +
577 (lck->num_share_modes *
578 sizeof(struct share_mode_entry)) +
579 data->u.s.delete_token_size +
580 strlen(lck->servicepath) + 1 );
581 if (lck->filename == NULL) {
582 smb_panic("parse_share_modes: talloc_strdup failed");
586 * Ensure that each entry has a real process attached.
589 for (i = 0; i < lck->num_share_modes; i++) {
590 struct share_mode_entry *entry_p = &lck->share_modes[i];
591 DEBUG(10,("parse_share_modes: %s\n",
592 share_mode_str(i, entry_p) ));
593 if (!process_exists(entry_p->pid)) {
594 DEBUG(10,("parse_share_modes: deleted %s\n",
595 share_mode_str(i, entry_p) ));
596 entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
597 lck->modified = True;
601 return True;
604 static TDB_DATA unparse_share_modes(struct share_mode_lock *lck)
606 TDB_DATA result;
607 int num_valid = 0;
608 int i;
609 struct locking_data *data;
610 ssize_t offset;
611 ssize_t sp_len;
612 uint32 delete_token_size;
614 result.dptr = NULL;
615 result.dsize = 0;
617 for (i=0; i<lck->num_share_modes; i++) {
618 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
619 num_valid += 1;
623 if (num_valid == 0) {
624 return result;
627 sp_len = strlen(lck->servicepath);
628 delete_token_size = (lck->delete_token ?
629 (sizeof(uid_t) + sizeof(gid_t) + (lck->delete_token->ngroups*sizeof(gid_t))) : 0);
631 result.dsize = sizeof(*data) +
632 lck->num_share_modes * sizeof(struct share_mode_entry) +
633 delete_token_size +
634 sp_len + 1 +
635 strlen(lck->filename) + 1;
636 result.dptr = TALLOC_ARRAY(lck, uint8, result.dsize);
638 if (result.dptr == NULL) {
639 smb_panic("talloc failed");
642 data = (struct locking_data *)result.dptr;
643 ZERO_STRUCTP(data);
644 data->u.s.num_share_mode_entries = lck->num_share_modes;
645 data->u.s.delete_on_close = lck->delete_on_close;
646 data->u.s.delete_token_size = delete_token_size;
647 DEBUG(10, ("unparse_share_modes: del: %d, tok = %u, num: %d\n",
648 data->u.s.delete_on_close,
649 (unsigned int)data->u.s.delete_token_size,
650 data->u.s.num_share_mode_entries));
651 memcpy(result.dptr + sizeof(*data), lck->share_modes,
652 sizeof(struct share_mode_entry)*lck->num_share_modes);
653 offset = sizeof(*data) +
654 sizeof(struct share_mode_entry)*lck->num_share_modes;
656 /* Store any delete on close token. */
657 if (lck->delete_token) {
658 uint8 *p = result.dptr + offset;
660 memcpy(p, &lck->delete_token->uid, sizeof(uid_t));
661 p += sizeof(uid_t);
663 memcpy(p, &lck->delete_token->gid, sizeof(gid_t));
664 p += sizeof(gid_t);
666 for (i = 0; i < lck->delete_token->ngroups; i++) {
667 memcpy(p, &lck->delete_token->groups[i], sizeof(gid_t));
668 p += sizeof(gid_t);
670 offset = p - result.dptr;
673 safe_strcpy((char *)result.dptr + offset, lck->servicepath,
674 result.dsize - offset - 1);
675 offset += sp_len + 1;
676 safe_strcpy((char *)result.dptr + offset, lck->filename,
677 result.dsize - offset - 1);
679 if (DEBUGLEVEL >= 10) {
680 print_share_mode_table(data);
683 return result;
686 static int share_mode_lock_destructor(struct share_mode_lock *lck)
688 NTSTATUS status;
689 TDB_DATA data;
691 if (!lck->modified) {
692 return 0;
695 data = unparse_share_modes(lck);
697 if (data.dptr == NULL) {
698 if (!lck->fresh) {
699 /* There has been an entry before, delete it */
701 status = lck->record->delete_rec(lck->record);
702 if (!NT_STATUS_IS_OK(status)) {
703 DEBUG(0, ("delete_rec returned %s\n",
704 nt_errstr(status)));
705 smb_panic("could not delete share entry");
708 goto done;
711 status = lck->record->store(lck->record, data, TDB_REPLACE);
712 if (!NT_STATUS_IS_OK(status)) {
713 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
714 smb_panic("could not store share mode entry");
717 done:
719 return 0;
722 static BOOL fill_share_mode_lock(struct share_mode_lock *lck,
723 struct file_id id,
724 const char *servicepath,
725 const char *fname,
726 TDB_DATA share_mode_data)
728 /* Ensure we set every field here as the destructor must be
729 valid even if parse_share_modes fails. */
731 lck->servicepath = NULL;
732 lck->filename = NULL;
733 lck->id = id;
734 lck->num_share_modes = 0;
735 lck->share_modes = NULL;
736 lck->delete_token = NULL;
737 lck->delete_on_close = False;
738 lck->fresh = False;
739 lck->modified = False;
741 lck->fresh = (share_mode_data.dptr == NULL);
743 if (lck->fresh) {
744 if (fname == NULL || servicepath == NULL) {
745 return False;
747 lck->filename = talloc_strdup(lck, fname);
748 lck->servicepath = talloc_strdup(lck, servicepath);
749 if (lck->filename == NULL || lck->servicepath == NULL) {
750 DEBUG(0, ("talloc failed\n"));
751 return False;
753 } else {
754 if (!parse_share_modes(share_mode_data, lck)) {
755 DEBUG(0, ("Could not parse share modes\n"));
756 return False;
760 return True;
763 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
764 struct file_id id,
765 const char *servicepath,
766 const char *fname)
768 struct share_mode_lock *lck;
769 TDB_DATA key;
771 key.dptr = (unsigned char *)&id;
772 key.dsize = sizeof(id);
774 if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
775 DEBUG(0, ("talloc failed\n"));
776 return NULL;
779 if (!(lck->record = lock_db->fetch_locked(lock_db, lck, key))) {
780 DEBUG(3, ("Could not lock share entry\n"));
781 TALLOC_FREE(lck);
782 return NULL;
785 if (!fill_share_mode_lock(lck, id, servicepath, fname,
786 lck->record->value)) {
787 DEBUG(3, ("fill_share_mode_lock failed\n"));
788 TALLOC_FREE(lck);
789 return NULL;
792 talloc_set_destructor(lck, share_mode_lock_destructor);
794 return lck;
797 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
798 struct file_id id,
799 const char *servicepath,
800 const char *fname)
802 struct share_mode_lock *lck;
803 TDB_DATA key = locking_key(id);
804 TDB_DATA data;
806 if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
807 DEBUG(0, ("talloc failed\n"));
808 return NULL;
811 if (lock_db->fetch(lock_db, lck, key, &data) == -1) {
812 DEBUG(3, ("Could not fetch share entry\n"));
813 TALLOC_FREE(lck);
814 return NULL;
817 if (!fill_share_mode_lock(lck, id, servicepath, fname, data)) {
818 DEBUG(3, ("fill_share_mode_lock failed\n"));
819 TALLOC_FREE(lck);
820 return NULL;
823 TALLOC_FREE(data.dptr);
825 return lck;
828 /*******************************************************************
829 Sets the service name and filename for rename.
830 At this point we emit "file renamed" messages to all
831 process id's that have this file open.
832 Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
833 ********************************************************************/
835 BOOL rename_share_filename(struct messaging_context *msg_ctx,
836 struct share_mode_lock *lck,
837 const char *servicepath,
838 const char *newname)
840 size_t sp_len;
841 size_t fn_len;
842 size_t msg_len;
843 char *frm = NULL;
844 int i;
846 DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
847 servicepath, newname));
850 * rename_internal_fsp() and rename_internals() add './' to
851 * head of newname if newname does not contain a '/'.
853 while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
854 newname += 2;
857 lck->servicepath = talloc_strdup(lck, servicepath);
858 lck->filename = talloc_strdup(lck, newname);
859 if (lck->filename == NULL || lck->servicepath == NULL) {
860 DEBUG(0, ("rename_share_filename: talloc failed\n"));
861 return False;
863 lck->modified = True;
865 sp_len = strlen(lck->servicepath);
866 fn_len = strlen(lck->filename);
868 msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1;
870 /* Set up the name changed message. */
871 frm = TALLOC_ARRAY(lck, char, msg_len);
872 if (!frm) {
873 return False;
876 push_file_id_16(frm, &lck->id);
878 DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
880 safe_strcpy(&frm[16], lck->servicepath, sp_len);
881 safe_strcpy(&frm[16 + sp_len + 1], lck->filename, fn_len);
883 /* Send the messages. */
884 for (i=0; i<lck->num_share_modes; i++) {
885 struct share_mode_entry *se = &lck->share_modes[i];
886 if (!is_valid_share_mode_entry(se)) {
887 continue;
889 /* But not to ourselves... */
890 if (procid_is_me(&se->pid)) {
891 continue;
894 DEBUG(10,("rename_share_filename: sending rename message to pid %s "
895 "file_id %s sharepath %s newname %s\n",
896 procid_str_static(&se->pid),
897 file_id_static_string(&lck->id),
898 lck->servicepath, lck->filename ));
900 messaging_send_buf(msg_ctx, se->pid, MSG_SMB_FILE_RENAME,
901 (uint8 *)frm, msg_len);
904 return True;
907 BOOL get_delete_on_close_flag(struct file_id id)
909 BOOL result;
910 struct share_mode_lock *lck;
912 if (!(lck = fetch_share_mode_unlocked(NULL, id, NULL, NULL))) {
913 return False;
915 result = lck->delete_on_close;
916 TALLOC_FREE(lck);
917 return result;
920 BOOL is_valid_share_mode_entry(const struct share_mode_entry *e)
922 int num_props = 0;
924 num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
925 num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
926 num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
928 SMB_ASSERT(num_props <= 1);
929 return (num_props != 0);
932 BOOL is_deferred_open_entry(const struct share_mode_entry *e)
934 return (e->op_type == DEFERRED_OPEN_ENTRY);
937 BOOL is_unused_share_mode_entry(const struct share_mode_entry *e)
939 return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
942 /*******************************************************************
943 Fill a share mode entry.
944 ********************************************************************/
946 static void fill_share_mode_entry(struct share_mode_entry *e,
947 files_struct *fsp,
948 uid_t uid, uint16 mid, uint16 op_type)
950 ZERO_STRUCTP(e);
951 e->pid = procid_self();
952 e->share_access = fsp->share_access;
953 e->private_options = fsp->fh->private_options;
954 e->access_mask = fsp->access_mask;
955 e->op_mid = mid;
956 e->op_type = op_type;
957 e->time.tv_sec = fsp->open_time.tv_sec;
958 e->time.tv_usec = fsp->open_time.tv_usec;
959 e->id = fsp->file_id;
960 e->share_file_id = fsp->fh->gen_id;
961 e->uid = (uint32)uid;
962 e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
965 static void fill_deferred_open_entry(struct share_mode_entry *e,
966 const struct timeval request_time,
967 struct file_id id, uint16 mid)
969 ZERO_STRUCTP(e);
970 e->pid = procid_self();
971 e->op_mid = mid;
972 e->op_type = DEFERRED_OPEN_ENTRY;
973 e->time.tv_sec = request_time.tv_sec;
974 e->time.tv_usec = request_time.tv_usec;
975 e->id = id;
976 e->uid = (uint32)-1;
977 e->flags = 0;
980 static void add_share_mode_entry(struct share_mode_lock *lck,
981 const struct share_mode_entry *entry)
983 int i;
985 for (i=0; i<lck->num_share_modes; i++) {
986 struct share_mode_entry *e = &lck->share_modes[i];
987 if (is_unused_share_mode_entry(e)) {
988 *e = *entry;
989 break;
993 if (i == lck->num_share_modes) {
994 /* No unused entry found */
995 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
996 &lck->share_modes, &lck->num_share_modes);
998 lck->modified = True;
1001 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
1002 uid_t uid, uint16 mid, uint16 op_type, BOOL initial_delete_on_close_allowed)
1004 struct share_mode_entry entry;
1005 fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1006 if (initial_delete_on_close_allowed) {
1007 entry.flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1009 add_share_mode_entry(lck, &entry);
1012 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
1013 struct timeval request_time,
1014 struct file_id id)
1016 struct share_mode_entry entry;
1017 fill_deferred_open_entry(&entry, request_time, id, mid);
1018 add_share_mode_entry(lck, &entry);
1021 /*******************************************************************
1022 Check if two share mode entries are identical, ignoring oplock
1023 and mid info and desired_access. (Removed paranoia test - it's
1024 not automatically a logic error if they are identical. JRA.)
1025 ********************************************************************/
1027 static BOOL share_modes_identical(struct share_mode_entry *e1,
1028 struct share_mode_entry *e2)
1030 /* We used to check for e1->share_access == e2->share_access here
1031 as well as the other fields but 2 different DOS or FCB opens
1032 sharing the same share mode entry may validly differ in
1033 fsp->share_access field. */
1035 return (procid_equal(&e1->pid, &e2->pid) &&
1036 file_id_equal(&e1->id, &e2->id) &&
1037 e1->share_file_id == e2->share_file_id );
1040 static BOOL deferred_open_identical(struct share_mode_entry *e1,
1041 struct share_mode_entry *e2)
1043 return (procid_equal(&e1->pid, &e2->pid) &&
1044 (e1->op_mid == e2->op_mid) &&
1045 file_id_equal(&e1->id, &e2->id));
1048 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1049 struct share_mode_entry *entry)
1051 int i;
1053 for (i=0; i<lck->num_share_modes; i++) {
1054 struct share_mode_entry *e = &lck->share_modes[i];
1055 if (is_valid_share_mode_entry(entry) &&
1056 is_valid_share_mode_entry(e) &&
1057 share_modes_identical(e, entry)) {
1058 return e;
1060 if (is_deferred_open_entry(entry) &&
1061 is_deferred_open_entry(e) &&
1062 deferred_open_identical(e, entry)) {
1063 return e;
1066 return NULL;
1069 /*******************************************************************
1070 Del the share mode of a file for this process. Return the number of
1071 entries left.
1072 ********************************************************************/
1074 BOOL del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1076 struct share_mode_entry entry, *e;
1078 /* Don't care about the pid owner being correct here - just a search. */
1079 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1081 e = find_share_mode_entry(lck, &entry);
1082 if (e == NULL) {
1083 return False;
1086 e->op_type = UNUSED_SHARE_MODE_ENTRY;
1087 lck->modified = True;
1088 return True;
1091 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
1093 struct share_mode_entry entry, *e;
1095 fill_deferred_open_entry(&entry, timeval_zero(),
1096 lck->id, mid);
1098 e = find_share_mode_entry(lck, &entry);
1099 if (e == NULL) {
1100 return;
1103 e->op_type = UNUSED_SHARE_MODE_ENTRY;
1104 lck->modified = True;
1107 /*******************************************************************
1108 Remove an oplock mid and mode entry from a share mode.
1109 ********************************************************************/
1111 BOOL remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1113 struct share_mode_entry entry, *e;
1115 /* Don't care about the pid owner being correct here - just a search. */
1116 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1118 e = find_share_mode_entry(lck, &entry);
1119 if (e == NULL) {
1120 return False;
1123 e->op_mid = 0;
1124 e->op_type = NO_OPLOCK;
1125 lck->modified = True;
1126 return True;
1129 /*******************************************************************
1130 Downgrade a oplock type from exclusive to level II.
1131 ********************************************************************/
1133 BOOL downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1135 struct share_mode_entry entry, *e;
1137 /* Don't care about the pid owner being correct here - just a search. */
1138 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1140 e = find_share_mode_entry(lck, &entry);
1141 if (e == NULL) {
1142 return False;
1145 e->op_type = LEVEL_II_OPLOCK;
1146 lck->modified = True;
1147 return True;
1150 /****************************************************************************
1151 Deal with the internal needs of setting the delete on close flag. Note that
1152 as the tdb locking is recursive, it is safe to call this from within
1153 open_file_ntcreate. JRA.
1154 ****************************************************************************/
1156 NTSTATUS can_set_delete_on_close(files_struct *fsp, BOOL delete_on_close,
1157 uint32 dosmode)
1159 if (!delete_on_close) {
1160 return NT_STATUS_OK;
1164 * Only allow delete on close for writable files.
1167 if ((dosmode & aRONLY) &&
1168 !lp_delete_readonly(SNUM(fsp->conn))) {
1169 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1170 "flag set but file attribute is readonly.\n",
1171 fsp->fsp_name ));
1172 return NT_STATUS_CANNOT_DELETE;
1176 * Only allow delete on close for writable shares.
1179 if (!CAN_WRITE(fsp->conn)) {
1180 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1181 "close flag set but write access denied on share.\n",
1182 fsp->fsp_name ));
1183 return NT_STATUS_ACCESS_DENIED;
1187 * Only allow delete on close for files/directories opened with delete
1188 * intent.
1191 if (!(fsp->access_mask & DELETE_ACCESS)) {
1192 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1193 "close flag set but delete access denied.\n",
1194 fsp->fsp_name ));
1195 return NT_STATUS_ACCESS_DENIED;
1198 /* Don't allow delete on close for non-empty directories. */
1199 if (fsp->is_directory) {
1200 return can_delete_directory(fsp->conn, fsp->fsp_name);
1203 return NT_STATUS_OK;
1206 /****************************************************************************
1207 Do we have an open file handle that created this entry ?
1208 ****************************************************************************/
1210 BOOL can_set_initial_delete_on_close(const struct share_mode_lock *lck)
1212 int i;
1214 for (i=0; i<lck->num_share_modes; i++) {
1215 if (lck->share_modes[i].flags & SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE) {
1216 return True;
1219 return False;
1222 /*************************************************************************
1223 Return a talloced copy of a UNIX_USER_TOKEN. NULL on fail.
1224 (Should this be in locking.c.... ?).
1225 *************************************************************************/
1227 static UNIX_USER_TOKEN *copy_unix_token(TALLOC_CTX *ctx, UNIX_USER_TOKEN *tok)
1229 UNIX_USER_TOKEN *cpy;
1231 if (tok == NULL) {
1232 return NULL;
1235 cpy = TALLOC_P(ctx, UNIX_USER_TOKEN);
1236 if (!cpy) {
1237 return NULL;
1240 cpy->uid = tok->uid;
1241 cpy->gid = tok->gid;
1242 cpy->ngroups = tok->ngroups;
1243 if (tok->ngroups) {
1244 /* Make this a talloc child of cpy. */
1245 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1246 if (!cpy->groups) {
1247 return NULL;
1249 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1251 return cpy;
1254 /****************************************************************************
1255 Replace the delete on close token.
1256 ****************************************************************************/
1258 void set_delete_on_close_token(struct share_mode_lock *lck, UNIX_USER_TOKEN *tok)
1260 /* Ensure there's no token. */
1261 if (lck->delete_token) {
1262 TALLOC_FREE(lck->delete_token); /* Also deletes groups... */
1263 lck->delete_token = NULL;
1266 /* Copy the new token (can be NULL). */
1267 lck->delete_token = copy_unix_token(lck, tok);
1268 lck->modified = True;
1271 /****************************************************************************
1272 Sets the delete on close flag over all share modes on this file.
1273 Modify the share mode entry for all files open
1274 on this device and inode to tell other smbds we have
1275 changed the delete on close flag. This will be noticed
1276 in the close code, the last closer will delete the file
1277 if flag is set.
1278 This makes a copy of any UNIX_USER_TOKEN into the
1279 lck entry. This function is used when the lock is already granted.
1280 ****************************************************************************/
1282 void set_delete_on_close_lck(struct share_mode_lock *lck, BOOL delete_on_close, UNIX_USER_TOKEN *tok)
1284 if (lck->delete_on_close != delete_on_close) {
1285 set_delete_on_close_token(lck, tok);
1286 lck->delete_on_close = delete_on_close;
1287 if (delete_on_close) {
1288 SMB_ASSERT(lck->delete_token != NULL);
1290 lck->modified = True;
1294 BOOL set_delete_on_close(files_struct *fsp, BOOL delete_on_close, UNIX_USER_TOKEN *tok)
1296 struct share_mode_lock *lck;
1298 DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1299 "fnum = %d, file %s\n",
1300 delete_on_close ? "Adding" : "Removing", fsp->fnum,
1301 fsp->fsp_name ));
1303 if (fsp->is_stat) {
1304 return True;
1307 lck = get_share_mode_lock(NULL, fsp->file_id, NULL, NULL);
1308 if (lck == NULL) {
1309 return False;
1312 set_delete_on_close_lck(lck, delete_on_close, tok);
1314 if (fsp->is_directory) {
1315 send_stat_cache_delete_message(fsp->fsp_name);
1318 TALLOC_FREE(lck);
1319 return True;
1322 /****************************************************************************
1323 Sets the allow initial delete on close flag for this share mode.
1324 ****************************************************************************/
1326 BOOL set_allow_initial_delete_on_close(struct share_mode_lock *lck, files_struct *fsp, BOOL delete_on_close)
1328 struct share_mode_entry entry, *e;
1330 /* Don't care about the pid owner being correct here - just a search. */
1331 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1333 e = find_share_mode_entry(lck, &entry);
1334 if (e == NULL) {
1335 return False;
1338 if (delete_on_close) {
1339 e->flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1340 } else {
1341 e->flags &= ~SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1343 lck->modified = True;
1344 return True;
1347 struct forall_state {
1348 void (*fn)(const struct share_mode_entry *entry,
1349 const char *sharepath,
1350 const char *fname,
1351 void *private_data);
1352 void *private_data;
1355 static int traverse_fn(struct db_record *rec, void *_state)
1357 struct forall_state *state = (struct forall_state *)_state;
1358 struct locking_data *data;
1359 struct share_mode_entry *shares;
1360 const char *sharepath;
1361 const char *fname;
1362 int i;
1364 /* Ensure this is a locking_key record. */
1365 if (rec->key.dsize != sizeof(struct file_id))
1366 return 0;
1368 data = (struct locking_data *)rec->value.dptr;
1369 shares = (struct share_mode_entry *)(rec->value.dptr + sizeof(*data));
1370 sharepath = (const char *)rec->value.dptr + sizeof(*data) +
1371 data->u.s.num_share_mode_entries*sizeof(*shares) +
1372 data->u.s.delete_token_size;
1373 fname = (const char *)rec->value.dptr + sizeof(*data) +
1374 data->u.s.num_share_mode_entries*sizeof(*shares) +
1375 data->u.s.delete_token_size +
1376 strlen(sharepath) + 1;
1378 for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1379 state->fn(&shares[i], sharepath, fname,
1380 state->private_data);
1382 return 0;
1385 /*******************************************************************
1386 Call the specified function on each entry under management by the
1387 share mode system.
1388 ********************************************************************/
1390 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1391 const char *, void *),
1392 void *private_data)
1394 struct forall_state state;
1396 if (lock_db == NULL)
1397 return 0;
1399 state.fn = fn;
1400 state.private_data = private_data;
1402 return lock_db->traverse_read(lock_db, traverse_fn, (void *)&state);