Merge leftovers of 0e1a86bc845 in 3-0-ctdb
[Samba/bjacke.git] / source / locking / locking.c
blob782e10fb7cd9ea73f6b095a32ca493bc9bae1d45
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 #define NO_LOCKING_COUNT (-1)
45 /* the locking database handle */
46 static struct db_context *lock_db;
48 /****************************************************************************
49 Debugging aids :-).
50 ****************************************************************************/
52 const char *lock_type_name(enum brl_type lock_type)
54 switch (lock_type) {
55 case READ_LOCK:
56 return "READ";
57 case WRITE_LOCK:
58 return "WRITE";
59 case PENDING_READ_LOCK:
60 return "PENDING_READ";
61 case PENDING_WRITE_LOCK:
62 return "PENDING_WRITE";
63 default:
64 return "other";
68 const char *lock_flav_name(enum brl_flavour lock_flav)
70 return (lock_flav == WINDOWS_LOCK) ? "WINDOWS_LOCK" : "POSIX_LOCK";
73 /****************************************************************************
74 Utility function called to see if a file region is locked.
75 Called in the read/write codepath.
76 ****************************************************************************/
78 bool is_locked(files_struct *fsp,
79 uint32 smbpid,
80 SMB_BIG_UINT count,
81 SMB_BIG_UINT offset,
82 enum brl_type lock_type)
84 int strict_locking = lp_strict_locking(fsp->conn->params);
85 enum brl_flavour lock_flav = lp_posix_cifsu_locktype(fsp);
86 bool ret = True;
88 if (count == 0) {
89 return False;
92 if (!lp_locking(fsp->conn->params) || !strict_locking) {
93 return False;
96 if (strict_locking == Auto) {
97 if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && (lock_type == READ_LOCK || lock_type == WRITE_LOCK)) {
98 DEBUG(10,("is_locked: optimisation - exclusive oplock on file %s\n", fsp->fsp_name ));
99 ret = False;
100 } else if ((fsp->oplock_type == LEVEL_II_OPLOCK) &&
101 (lock_type == READ_LOCK)) {
102 DEBUG(10,("is_locked: optimisation - level II oplock on file %s\n", fsp->fsp_name ));
103 ret = False;
104 } else {
105 struct byte_range_lock *br_lck = brl_get_locks_readonly(talloc_tos(), fsp);
106 if (!br_lck) {
107 return False;
109 ret = !brl_locktest(br_lck,
110 smbpid,
111 procid_self(),
112 offset,
113 count,
114 lock_type,
115 lock_flav);
116 TALLOC_FREE(br_lck);
118 } else {
119 struct byte_range_lock *br_lck = brl_get_locks_readonly(talloc_tos(), fsp);
120 if (!br_lck) {
121 return False;
123 ret = !brl_locktest(br_lck,
124 smbpid,
125 procid_self(),
126 offset,
127 count,
128 lock_type,
129 lock_flav);
130 TALLOC_FREE(br_lck);
133 DEBUG(10,("is_locked: flavour = %s brl start=%.0f len=%.0f %s for fnum %d file %s\n",
134 lock_flav_name(lock_flav),
135 (double)offset, (double)count, ret ? "locked" : "unlocked",
136 fsp->fnum, fsp->fsp_name ));
138 return ret;
141 /****************************************************************************
142 Find out if a lock could be granted - return who is blocking us if we can't.
143 ****************************************************************************/
145 NTSTATUS query_lock(files_struct *fsp,
146 uint32 *psmbpid,
147 SMB_BIG_UINT *pcount,
148 SMB_BIG_UINT *poffset,
149 enum brl_type *plock_type,
150 enum brl_flavour lock_flav)
152 struct byte_range_lock *br_lck = NULL;
153 NTSTATUS status = NT_STATUS_LOCK_NOT_GRANTED;
155 if (!fsp->can_lock) {
156 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
159 if (!lp_locking(fsp->conn->params)) {
160 return NT_STATUS_OK;
163 br_lck = brl_get_locks_readonly(talloc_tos(), fsp);
164 if (!br_lck) {
165 return NT_STATUS_NO_MEMORY;
168 status = brl_lockquery(br_lck,
169 psmbpid,
170 procid_self(),
171 poffset,
172 pcount,
173 plock_type,
174 lock_flav);
176 TALLOC_FREE(br_lck);
177 return status;
180 /****************************************************************************
181 Utility function called by locking requests.
182 ****************************************************************************/
184 struct byte_range_lock *do_lock(struct messaging_context *msg_ctx,
185 files_struct *fsp,
186 uint32 lock_pid,
187 SMB_BIG_UINT count,
188 SMB_BIG_UINT offset,
189 enum brl_type lock_type,
190 enum brl_flavour lock_flav,
191 bool blocking_lock,
192 NTSTATUS *perr,
193 uint32 *plock_pid)
195 struct byte_range_lock *br_lck = NULL;
197 if (!fsp->can_lock) {
198 *perr = fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
199 return NULL;
202 if (!lp_locking(fsp->conn->params)) {
203 *perr = NT_STATUS_OK;
204 return NULL;
207 /* NOTE! 0 byte long ranges ARE allowed and should be stored */
209 DEBUG(10,("do_lock: lock flavour %s lock type %s start=%.0f len=%.0f requested for fnum %d file %s\n",
210 lock_flav_name(lock_flav), lock_type_name(lock_type),
211 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
213 br_lck = brl_get_locks(talloc_tos(), fsp);
214 if (!br_lck) {
215 *perr = NT_STATUS_NO_MEMORY;
216 return NULL;
219 *perr = brl_lock(msg_ctx,
220 br_lck,
221 lock_pid,
222 procid_self(),
223 offset,
224 count,
225 lock_type,
226 lock_flav,
227 blocking_lock,
228 plock_pid);
230 if (lock_flav == WINDOWS_LOCK &&
231 fsp->current_lock_count != NO_LOCKING_COUNT) {
232 /* blocking ie. pending, locks also count here,
233 * as this is an efficiency counter to avoid checking
234 * the lock db. on close. JRA. */
236 fsp->current_lock_count++;
237 } else {
238 /* Notice that this has had a POSIX lock request.
239 * We can't count locks after this so forget them.
241 fsp->current_lock_count = NO_LOCKING_COUNT;
244 return br_lck;
247 /****************************************************************************
248 Utility function called by unlocking requests.
249 ****************************************************************************/
251 NTSTATUS do_unlock(struct messaging_context *msg_ctx,
252 files_struct *fsp,
253 uint32 lock_pid,
254 SMB_BIG_UINT count,
255 SMB_BIG_UINT offset,
256 enum brl_flavour lock_flav)
258 bool ok = False;
259 struct byte_range_lock *br_lck = NULL;
261 if (!fsp->can_lock) {
262 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
265 if (!lp_locking(fsp->conn->params)) {
266 return NT_STATUS_OK;
269 DEBUG(10,("do_unlock: unlock start=%.0f len=%.0f requested for fnum %d file %s\n",
270 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
272 br_lck = brl_get_locks(talloc_tos(), fsp);
273 if (!br_lck) {
274 return NT_STATUS_NO_MEMORY;
277 ok = brl_unlock(msg_ctx,
278 br_lck,
279 lock_pid,
280 procid_self(),
281 offset,
282 count,
283 lock_flav);
285 TALLOC_FREE(br_lck);
287 if (!ok) {
288 DEBUG(10,("do_unlock: returning ERRlock.\n" ));
289 return NT_STATUS_RANGE_NOT_LOCKED;
292 if (lock_flav == WINDOWS_LOCK &&
293 fsp->current_lock_count != NO_LOCKING_COUNT) {
294 SMB_ASSERT(fsp->current_lock_count > 0);
295 fsp->current_lock_count--;
298 return NT_STATUS_OK;
301 /****************************************************************************
302 Cancel any pending blocked locks.
303 ****************************************************************************/
305 NTSTATUS do_lock_cancel(files_struct *fsp,
306 uint32 lock_pid,
307 SMB_BIG_UINT count,
308 SMB_BIG_UINT offset,
309 enum brl_flavour lock_flav)
311 bool ok = False;
312 struct byte_range_lock *br_lck = NULL;
314 if (!fsp->can_lock) {
315 return fsp->is_directory ?
316 NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
319 if (!lp_locking(fsp->conn->params)) {
320 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
323 DEBUG(10,("do_lock_cancel: cancel start=%.0f len=%.0f requested for fnum %d file %s\n",
324 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
326 br_lck = brl_get_locks(talloc_tos(), fsp);
327 if (!br_lck) {
328 return NT_STATUS_NO_MEMORY;
331 ok = brl_lock_cancel(br_lck,
332 lock_pid,
333 procid_self(),
334 offset,
335 count,
336 lock_flav);
338 TALLOC_FREE(br_lck);
340 if (!ok) {
341 DEBUG(10,("do_lock_cancel: returning ERRcancelviolation.\n" ));
342 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
345 if (lock_flav == WINDOWS_LOCK &&
346 fsp->current_lock_count != NO_LOCKING_COUNT) {
347 SMB_ASSERT(fsp->current_lock_count > 0);
348 fsp->current_lock_count--;
351 return NT_STATUS_OK;
354 /****************************************************************************
355 Remove any locks on this fd. Called from file_close().
356 ****************************************************************************/
358 void locking_close_file(struct messaging_context *msg_ctx,
359 files_struct *fsp)
361 struct byte_range_lock *br_lck;
363 if (!lp_locking(fsp->conn->params)) {
364 return;
367 /* If we have not outstanding locks or pending
368 * locks then we don't need to look in the lock db.
371 if (fsp->current_lock_count == 0) {
372 return;
375 br_lck = brl_get_locks(talloc_tos(),fsp);
377 if (br_lck) {
378 cancel_pending_lock_requests_by_fid(fsp, br_lck);
379 brl_close_fnum(msg_ctx, br_lck);
380 TALLOC_FREE(br_lck);
384 /****************************************************************************
385 Initialise the locking functions.
386 ****************************************************************************/
388 static bool locking_init_internal(bool read_only)
390 brl_init(read_only);
392 if (lock_db)
393 return True;
395 lock_db = db_open(NULL, lock_path("locking.tdb"),
396 lp_open_files_db_hash_size(),
397 TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST,
398 read_only?O_RDONLY:O_RDWR|O_CREAT, 0644);
400 if (!lock_db) {
401 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
402 return False;
405 if (!posix_locking_init(read_only))
406 return False;
408 return True;
411 bool locking_init(void)
413 return locking_init_internal(false);
416 bool locking_init_readonly(void)
418 return locking_init_internal(true);
421 /*******************************************************************
422 Deinitialize the share_mode management.
423 ******************************************************************/
425 bool locking_end(void)
427 brl_shutdown();
428 TALLOC_FREE(lock_db);
429 return true;
432 /*******************************************************************
433 Form a static locking key for a dev/inode pair.
434 ******************************************************************/
436 static TDB_DATA locking_key(const struct file_id *id, struct file_id *tmp)
438 *tmp = *id;
439 return make_tdb_data((const uint8_t *)tmp, sizeof(*tmp));
442 /*******************************************************************
443 Print out a share mode.
444 ********************************************************************/
446 char *share_mode_str(TALLOC_CTX *ctx, int num, struct share_mode_entry *e)
448 return talloc_asprintf(ctx, "share_mode_entry[%d]: %s "
449 "pid = %s, share_access = 0x%x, private_options = 0x%x, "
450 "access_mask = 0x%x, mid = 0x%x, type= 0x%x, gen_id = %lu, "
451 "uid = %u, flags = %u, file_id %s",
452 num,
453 e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
454 procid_str_static(&e->pid),
455 e->share_access, e->private_options,
456 e->access_mask, e->op_mid, e->op_type, e->share_file_id,
457 (unsigned int)e->uid, (unsigned int)e->flags,
458 file_id_string_tos(&e->id));
461 /*******************************************************************
462 Print out a share mode table.
463 ********************************************************************/
465 static void print_share_mode_table(struct locking_data *data)
467 int num_share_modes = data->u.s.num_share_mode_entries;
468 struct share_mode_entry *shares =
469 (struct share_mode_entry *)(data + 1);
470 int i;
472 for (i = 0; i < num_share_modes; i++) {
473 struct share_mode_entry entry;
474 char *str;
477 * We need to memcpy the entry here due to alignment
478 * restrictions that are not met when directly accessing
479 * shares[i]
482 memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
483 str = share_mode_str(talloc_tos(), i, &entry);
485 DEBUG(10,("print_share_mode_table: %s\n", str ? str : ""));
486 TALLOC_FREE(str);
490 /*******************************************************************
491 Get all share mode entries for a dev/inode pair.
492 ********************************************************************/
494 static bool parse_share_modes(TDB_DATA dbuf, struct share_mode_lock *lck)
496 struct locking_data *data;
497 int i;
499 if (dbuf.dsize < sizeof(struct locking_data)) {
500 smb_panic("parse_share_modes: buffer too short");
503 data = (struct locking_data *)dbuf.dptr;
505 lck->delete_on_close = data->u.s.delete_on_close;
506 lck->num_share_modes = data->u.s.num_share_mode_entries;
508 DEBUG(10, ("parse_share_modes: delete_on_close: %d, "
509 "num_share_modes: %d\n",
510 lck->delete_on_close,
511 lck->num_share_modes));
513 if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
514 DEBUG(0, ("invalid number of share modes: %d\n",
515 lck->num_share_modes));
516 smb_panic("parse_share_modes: invalid number of share modes");
519 lck->share_modes = NULL;
521 if (lck->num_share_modes != 0) {
523 if (dbuf.dsize < (sizeof(struct locking_data) +
524 (lck->num_share_modes *
525 sizeof(struct share_mode_entry)))) {
526 smb_panic("parse_share_modes: buffer too short");
529 lck->share_modes = (struct share_mode_entry *)
530 TALLOC_MEMDUP(lck, dbuf.dptr+sizeof(*data),
531 lck->num_share_modes *
532 sizeof(struct share_mode_entry));
534 if (lck->share_modes == NULL) {
535 smb_panic("parse_share_modes: talloc failed");
539 /* Get any delete token. */
540 if (data->u.s.delete_token_size) {
541 uint8 *p = dbuf.dptr + sizeof(*data) +
542 (lck->num_share_modes *
543 sizeof(struct share_mode_entry));
545 if ((data->u.s.delete_token_size < sizeof(uid_t) + sizeof(gid_t)) ||
546 ((data->u.s.delete_token_size - sizeof(uid_t)) % sizeof(gid_t)) != 0) {
547 DEBUG(0, ("parse_share_modes: invalid token size %d\n",
548 data->u.s.delete_token_size));
549 smb_panic("parse_share_modes: invalid token size");
552 lck->delete_token = TALLOC_P(lck, UNIX_USER_TOKEN);
553 if (!lck->delete_token) {
554 smb_panic("parse_share_modes: talloc failed");
557 /* Copy out the uid and gid. */
558 memcpy(&lck->delete_token->uid, p, sizeof(uid_t));
559 p += sizeof(uid_t);
560 memcpy(&lck->delete_token->gid, p, sizeof(gid_t));
561 p += sizeof(gid_t);
563 /* Any supplementary groups ? */
564 lck->delete_token->ngroups = (data->u.s.delete_token_size > (sizeof(uid_t) + sizeof(gid_t))) ?
565 ((data->u.s.delete_token_size -
566 (sizeof(uid_t) + sizeof(gid_t)))/sizeof(gid_t)) : 0;
568 if (lck->delete_token->ngroups) {
569 /* Make this a talloc child of lck->delete_token. */
570 lck->delete_token->groups = TALLOC_ARRAY(lck->delete_token, gid_t,
571 lck->delete_token->ngroups);
572 if (!lck->delete_token) {
573 smb_panic("parse_share_modes: talloc failed");
576 for (i = 0; i < lck->delete_token->ngroups; i++) {
577 memcpy(&lck->delete_token->groups[i], p, sizeof(gid_t));
578 p += sizeof(gid_t);
582 } else {
583 lck->delete_token = NULL;
586 /* Save off the associated service path and filename. */
587 lck->servicepath = (const char *)dbuf.dptr + sizeof(*data) +
588 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
589 data->u.s.delete_token_size;
591 lck->filename = (const char *)dbuf.dptr + sizeof(*data) +
592 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
593 data->u.s.delete_token_size +
594 strlen(lck->servicepath) + 1;
597 * Ensure that each entry has a real process attached.
600 for (i = 0; i < lck->num_share_modes; i++) {
601 struct share_mode_entry *entry_p = &lck->share_modes[i];
602 char *str = NULL;
603 if (DEBUGLEVEL >= 10) {
604 str = share_mode_str(NULL, i, entry_p);
606 DEBUG(10,("parse_share_modes: %s\n",
607 str ? str : ""));
608 if (!process_exists(entry_p->pid)) {
609 DEBUG(10,("parse_share_modes: deleted %s\n",
610 str ? str : ""));
611 entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
612 lck->modified = True;
614 TALLOC_FREE(str);
617 return True;
620 static TDB_DATA unparse_share_modes(struct share_mode_lock *lck)
622 TDB_DATA result;
623 int num_valid = 0;
624 int i;
625 struct locking_data *data;
626 ssize_t offset;
627 ssize_t sp_len;
628 uint32 delete_token_size;
630 result.dptr = NULL;
631 result.dsize = 0;
633 for (i=0; i<lck->num_share_modes; i++) {
634 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
635 num_valid += 1;
639 if (num_valid == 0) {
640 return result;
643 sp_len = strlen(lck->servicepath);
644 delete_token_size = (lck->delete_token ?
645 (sizeof(uid_t) + sizeof(gid_t) + (lck->delete_token->ngroups*sizeof(gid_t))) : 0);
647 result.dsize = sizeof(*data) +
648 lck->num_share_modes * sizeof(struct share_mode_entry) +
649 delete_token_size +
650 sp_len + 1 +
651 strlen(lck->filename) + 1;
652 result.dptr = TALLOC_ARRAY(lck, uint8, result.dsize);
654 if (result.dptr == NULL) {
655 smb_panic("talloc failed");
658 data = (struct locking_data *)result.dptr;
659 ZERO_STRUCTP(data);
660 data->u.s.num_share_mode_entries = lck->num_share_modes;
661 data->u.s.delete_on_close = lck->delete_on_close;
662 data->u.s.delete_token_size = delete_token_size;
663 DEBUG(10, ("unparse_share_modes: del: %d, tok = %u, num: %d\n",
664 data->u.s.delete_on_close,
665 (unsigned int)data->u.s.delete_token_size,
666 data->u.s.num_share_mode_entries));
667 memcpy(result.dptr + sizeof(*data), lck->share_modes,
668 sizeof(struct share_mode_entry)*lck->num_share_modes);
669 offset = sizeof(*data) +
670 sizeof(struct share_mode_entry)*lck->num_share_modes;
672 /* Store any delete on close token. */
673 if (lck->delete_token) {
674 uint8 *p = result.dptr + offset;
676 memcpy(p, &lck->delete_token->uid, sizeof(uid_t));
677 p += sizeof(uid_t);
679 memcpy(p, &lck->delete_token->gid, sizeof(gid_t));
680 p += sizeof(gid_t);
682 for (i = 0; i < lck->delete_token->ngroups; i++) {
683 memcpy(p, &lck->delete_token->groups[i], sizeof(gid_t));
684 p += sizeof(gid_t);
686 offset = p - result.dptr;
689 safe_strcpy((char *)result.dptr + offset, lck->servicepath,
690 result.dsize - offset - 1);
691 offset += sp_len + 1;
692 safe_strcpy((char *)result.dptr + offset, lck->filename,
693 result.dsize - offset - 1);
695 if (DEBUGLEVEL >= 10) {
696 print_share_mode_table(data);
699 return result;
702 static int share_mode_lock_destructor(struct share_mode_lock *lck)
704 NTSTATUS status;
705 TDB_DATA data;
707 if (!lck->modified) {
708 return 0;
711 data = unparse_share_modes(lck);
713 if (data.dptr == NULL) {
714 if (!lck->fresh) {
715 /* There has been an entry before, delete it */
717 status = lck->record->delete_rec(lck->record);
718 if (!NT_STATUS_IS_OK(status)) {
719 DEBUG(0, ("delete_rec returned %s\n",
720 nt_errstr(status)));
721 smb_panic("could not delete share entry");
724 goto done;
727 status = lck->record->store(lck->record, data, TDB_REPLACE);
728 if (!NT_STATUS_IS_OK(status)) {
729 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
730 smb_panic("could not store share mode entry");
733 done:
735 return 0;
738 static bool fill_share_mode_lock(struct share_mode_lock *lck,
739 struct file_id id,
740 const char *servicepath,
741 const char *fname,
742 TDB_DATA share_mode_data)
744 /* Ensure we set every field here as the destructor must be
745 valid even if parse_share_modes fails. */
747 lck->servicepath = NULL;
748 lck->filename = NULL;
749 lck->id = id;
750 lck->num_share_modes = 0;
751 lck->share_modes = NULL;
752 lck->delete_token = NULL;
753 lck->delete_on_close = False;
754 lck->fresh = False;
755 lck->modified = False;
757 lck->fresh = (share_mode_data.dptr == NULL);
759 if (lck->fresh) {
760 if (fname == NULL || servicepath == NULL) {
761 return False;
763 lck->filename = talloc_strdup(lck, fname);
764 lck->servicepath = talloc_strdup(lck, servicepath);
765 if (lck->filename == NULL || lck->servicepath == NULL) {
766 DEBUG(0, ("talloc failed\n"));
767 return False;
769 } else {
770 if (!parse_share_modes(share_mode_data, lck)) {
771 DEBUG(0, ("Could not parse share modes\n"));
772 return False;
776 return True;
779 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
780 const struct file_id id,
781 const char *servicepath,
782 const char *fname)
784 struct share_mode_lock *lck;
785 struct file_id tmp;
786 TDB_DATA key = locking_key(&id, &tmp);
788 if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
789 DEBUG(0, ("talloc failed\n"));
790 return NULL;
793 if (!(lck->record = lock_db->fetch_locked(lock_db, lck, key))) {
794 DEBUG(3, ("Could not lock share entry\n"));
795 TALLOC_FREE(lck);
796 return NULL;
799 if (!fill_share_mode_lock(lck, id, servicepath, fname,
800 lck->record->value)) {
801 DEBUG(3, ("fill_share_mode_lock failed\n"));
802 TALLOC_FREE(lck);
803 return NULL;
806 talloc_set_destructor(lck, share_mode_lock_destructor);
808 return lck;
811 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
812 const struct file_id id,
813 const char *servicepath,
814 const char *fname)
816 struct share_mode_lock *lck;
817 struct file_id tmp;
818 TDB_DATA key = locking_key(&id, &tmp);
819 TDB_DATA data;
821 if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
822 DEBUG(0, ("talloc failed\n"));
823 return NULL;
826 if (lock_db->fetch(lock_db, lck, key, &data) == -1) {
827 DEBUG(3, ("Could not fetch share entry\n"));
828 TALLOC_FREE(lck);
829 return NULL;
832 if (!fill_share_mode_lock(lck, id, servicepath, fname, data)) {
833 DEBUG(3, ("fill_share_mode_lock failed\n"));
834 TALLOC_FREE(lck);
835 return NULL;
838 return lck;
841 /*******************************************************************
842 Sets the service name and filename for rename.
843 At this point we emit "file renamed" messages to all
844 process id's that have this file open.
845 Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
846 ********************************************************************/
848 bool rename_share_filename(struct messaging_context *msg_ctx,
849 struct share_mode_lock *lck,
850 const char *servicepath,
851 const char *newname)
853 size_t sp_len;
854 size_t fn_len;
855 size_t msg_len;
856 char *frm = NULL;
857 int i;
859 DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
860 servicepath, newname));
863 * rename_internal_fsp() and rename_internals() add './' to
864 * head of newname if newname does not contain a '/'.
866 while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
867 newname += 2;
870 lck->servicepath = talloc_strdup(lck, servicepath);
871 lck->filename = talloc_strdup(lck, newname);
872 if (lck->filename == NULL || lck->servicepath == NULL) {
873 DEBUG(0, ("rename_share_filename: talloc failed\n"));
874 return False;
876 lck->modified = True;
878 sp_len = strlen(lck->servicepath);
879 fn_len = strlen(lck->filename);
881 msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1;
883 /* Set up the name changed message. */
884 frm = TALLOC_ARRAY(lck, char, msg_len);
885 if (!frm) {
886 return False;
889 push_file_id_16(frm, &lck->id);
891 DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
893 safe_strcpy(&frm[16], lck->servicepath, sp_len);
894 safe_strcpy(&frm[16 + sp_len + 1], lck->filename, fn_len);
896 /* Send the messages. */
897 for (i=0; i<lck->num_share_modes; i++) {
898 struct share_mode_entry *se = &lck->share_modes[i];
899 if (!is_valid_share_mode_entry(se)) {
900 continue;
902 /* But not to ourselves... */
903 if (procid_is_me(&se->pid)) {
904 continue;
907 DEBUG(10,("rename_share_filename: sending rename message to pid %s "
908 "file_id %s sharepath %s newname %s\n",
909 procid_str_static(&se->pid),
910 file_id_string_tos(&lck->id),
911 lck->servicepath, lck->filename ));
913 messaging_send_buf(msg_ctx, se->pid, MSG_SMB_FILE_RENAME,
914 (uint8 *)frm, msg_len);
917 return True;
920 bool get_delete_on_close_flag(struct file_id id)
922 bool result;
923 struct share_mode_lock *lck;
925 if (!(lck = fetch_share_mode_unlocked(talloc_tos(), id, NULL, NULL))) {
926 return False;
928 result = lck->delete_on_close;
929 TALLOC_FREE(lck);
930 return result;
933 bool is_valid_share_mode_entry(const struct share_mode_entry *e)
935 int num_props = 0;
937 if (e->op_type == UNUSED_SHARE_MODE_ENTRY) {
938 /* cope with dead entries from the process not
939 existing. These should not be considered valid,
940 otherwise we end up doing zero timeout sharing
941 violation */
942 return False;
945 num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
946 num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
947 num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
949 SMB_ASSERT(num_props <= 1);
950 return (num_props != 0);
953 bool is_deferred_open_entry(const struct share_mode_entry *e)
955 return (e->op_type == DEFERRED_OPEN_ENTRY);
958 bool is_unused_share_mode_entry(const struct share_mode_entry *e)
960 return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
963 /*******************************************************************
964 Fill a share mode entry.
965 ********************************************************************/
967 static void fill_share_mode_entry(struct share_mode_entry *e,
968 files_struct *fsp,
969 uid_t uid, uint16 mid, uint16 op_type)
971 ZERO_STRUCTP(e);
972 e->pid = procid_self();
973 e->share_access = fsp->share_access;
974 e->private_options = fsp->fh->private_options;
975 e->access_mask = fsp->access_mask;
976 e->op_mid = mid;
977 e->op_type = op_type;
978 e->time.tv_sec = fsp->open_time.tv_sec;
979 e->time.tv_usec = fsp->open_time.tv_usec;
980 e->id = fsp->file_id;
981 e->share_file_id = fsp->fh->gen_id;
982 e->uid = (uint32)uid;
983 e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
986 static void fill_deferred_open_entry(struct share_mode_entry *e,
987 const struct timeval request_time,
988 struct file_id id, uint16 mid)
990 ZERO_STRUCTP(e);
991 e->pid = procid_self();
992 e->op_mid = mid;
993 e->op_type = DEFERRED_OPEN_ENTRY;
994 e->time.tv_sec = request_time.tv_sec;
995 e->time.tv_usec = request_time.tv_usec;
996 e->id = id;
997 e->uid = (uint32)-1;
998 e->flags = 0;
1001 static void add_share_mode_entry(struct share_mode_lock *lck,
1002 const struct share_mode_entry *entry)
1004 int i;
1006 for (i=0; i<lck->num_share_modes; i++) {
1007 struct share_mode_entry *e = &lck->share_modes[i];
1008 if (is_unused_share_mode_entry(e)) {
1009 *e = *entry;
1010 break;
1014 if (i == lck->num_share_modes) {
1015 /* No unused entry found */
1016 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
1017 &lck->share_modes, &lck->num_share_modes);
1019 lck->modified = True;
1022 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
1023 uid_t uid, uint16 mid, uint16 op_type, bool initial_delete_on_close_allowed)
1025 struct share_mode_entry entry;
1026 fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1027 if (initial_delete_on_close_allowed) {
1028 entry.flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1030 add_share_mode_entry(lck, &entry);
1033 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
1034 struct timeval request_time,
1035 struct file_id id)
1037 struct share_mode_entry entry;
1038 fill_deferred_open_entry(&entry, request_time, id, mid);
1039 add_share_mode_entry(lck, &entry);
1042 /*******************************************************************
1043 Check if two share mode entries are identical, ignoring oplock
1044 and mid info and desired_access. (Removed paranoia test - it's
1045 not automatically a logic error if they are identical. JRA.)
1046 ********************************************************************/
1048 static bool share_modes_identical(struct share_mode_entry *e1,
1049 struct share_mode_entry *e2)
1051 /* We used to check for e1->share_access == e2->share_access here
1052 as well as the other fields but 2 different DOS or FCB opens
1053 sharing the same share mode entry may validly differ in
1054 fsp->share_access field. */
1056 return (procid_equal(&e1->pid, &e2->pid) &&
1057 file_id_equal(&e1->id, &e2->id) &&
1058 e1->share_file_id == e2->share_file_id );
1061 static bool deferred_open_identical(struct share_mode_entry *e1,
1062 struct share_mode_entry *e2)
1064 return (procid_equal(&e1->pid, &e2->pid) &&
1065 (e1->op_mid == e2->op_mid) &&
1066 file_id_equal(&e1->id, &e2->id));
1069 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1070 struct share_mode_entry *entry)
1072 int i;
1074 for (i=0; i<lck->num_share_modes; i++) {
1075 struct share_mode_entry *e = &lck->share_modes[i];
1076 if (is_valid_share_mode_entry(entry) &&
1077 is_valid_share_mode_entry(e) &&
1078 share_modes_identical(e, entry)) {
1079 return e;
1081 if (is_deferred_open_entry(entry) &&
1082 is_deferred_open_entry(e) &&
1083 deferred_open_identical(e, entry)) {
1084 return e;
1087 return NULL;
1090 /*******************************************************************
1091 Del the share mode of a file for this process. Return the number of
1092 entries left.
1093 ********************************************************************/
1095 bool del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1097 struct share_mode_entry entry, *e;
1099 /* Don't care about the pid owner being correct here - just a search. */
1100 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1102 e = find_share_mode_entry(lck, &entry);
1103 if (e == NULL) {
1104 return False;
1107 e->op_type = UNUSED_SHARE_MODE_ENTRY;
1108 lck->modified = True;
1109 return True;
1112 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
1114 struct share_mode_entry entry, *e;
1116 fill_deferred_open_entry(&entry, timeval_zero(),
1117 lck->id, mid);
1119 e = find_share_mode_entry(lck, &entry);
1120 if (e == NULL) {
1121 return;
1124 e->op_type = UNUSED_SHARE_MODE_ENTRY;
1125 lck->modified = True;
1128 /*******************************************************************
1129 Remove an oplock mid and mode entry from a share mode.
1130 ********************************************************************/
1132 bool remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1134 struct share_mode_entry entry, *e;
1136 /* Don't care about the pid owner being correct here - just a search. */
1137 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1139 e = find_share_mode_entry(lck, &entry);
1140 if (e == NULL) {
1141 return False;
1144 e->op_mid = 0;
1145 e->op_type = NO_OPLOCK;
1146 lck->modified = True;
1147 return True;
1150 /*******************************************************************
1151 Downgrade a oplock type from exclusive to level II.
1152 ********************************************************************/
1154 bool downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1156 struct share_mode_entry entry, *e;
1158 /* Don't care about the pid owner being correct here - just a search. */
1159 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1161 e = find_share_mode_entry(lck, &entry);
1162 if (e == NULL) {
1163 return False;
1166 e->op_type = LEVEL_II_OPLOCK;
1167 lck->modified = True;
1168 return True;
1171 /****************************************************************************
1172 Deal with the internal needs of setting the delete on close flag. Note that
1173 as the tdb locking is recursive, it is safe to call this from within
1174 open_file_ntcreate. JRA.
1175 ****************************************************************************/
1177 NTSTATUS can_set_delete_on_close(files_struct *fsp, bool delete_on_close,
1178 uint32 dosmode)
1180 if (!delete_on_close) {
1181 return NT_STATUS_OK;
1185 * Only allow delete on close for writable files.
1188 if ((dosmode & aRONLY) &&
1189 !lp_delete_readonly(SNUM(fsp->conn))) {
1190 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1191 "flag set but file attribute is readonly.\n",
1192 fsp->fsp_name ));
1193 return NT_STATUS_CANNOT_DELETE;
1197 * Only allow delete on close for writable shares.
1200 if (!CAN_WRITE(fsp->conn)) {
1201 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1202 "close flag set but write access denied on share.\n",
1203 fsp->fsp_name ));
1204 return NT_STATUS_ACCESS_DENIED;
1208 * Only allow delete on close for files/directories opened with delete
1209 * intent.
1212 if (!(fsp->access_mask & DELETE_ACCESS)) {
1213 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1214 "close flag set but delete access denied.\n",
1215 fsp->fsp_name ));
1216 return NT_STATUS_ACCESS_DENIED;
1219 /* Don't allow delete on close for non-empty directories. */
1220 if (fsp->is_directory) {
1221 return can_delete_directory(fsp->conn, fsp->fsp_name);
1224 return NT_STATUS_OK;
1227 /****************************************************************************
1228 Do we have an open file handle that created this entry ?
1229 ****************************************************************************/
1231 bool can_set_initial_delete_on_close(const struct share_mode_lock *lck)
1233 int i;
1235 for (i=0; i<lck->num_share_modes; i++) {
1236 if (lck->share_modes[i].flags & SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE) {
1237 return True;
1240 return False;
1243 /*************************************************************************
1244 Return a talloced copy of a UNIX_USER_TOKEN. NULL on fail.
1245 (Should this be in locking.c.... ?).
1246 *************************************************************************/
1248 static UNIX_USER_TOKEN *copy_unix_token(TALLOC_CTX *ctx, UNIX_USER_TOKEN *tok)
1250 UNIX_USER_TOKEN *cpy;
1252 if (tok == NULL) {
1253 return NULL;
1256 cpy = TALLOC_P(ctx, UNIX_USER_TOKEN);
1257 if (!cpy) {
1258 return NULL;
1261 cpy->uid = tok->uid;
1262 cpy->gid = tok->gid;
1263 cpy->ngroups = tok->ngroups;
1264 if (tok->ngroups) {
1265 /* Make this a talloc child of cpy. */
1266 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1267 if (!cpy->groups) {
1268 return NULL;
1270 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1272 return cpy;
1275 /****************************************************************************
1276 Replace the delete on close token.
1277 ****************************************************************************/
1279 void set_delete_on_close_token(struct share_mode_lock *lck, UNIX_USER_TOKEN *tok)
1281 TALLOC_FREE(lck->delete_token); /* Also deletes groups... */
1283 /* Copy the new token (can be NULL). */
1284 lck->delete_token = copy_unix_token(lck, tok);
1285 lck->modified = True;
1288 /****************************************************************************
1289 Sets the delete on close flag over all share modes on this file.
1290 Modify the share mode entry for all files open
1291 on this device and inode to tell other smbds we have
1292 changed the delete on close flag. This will be noticed
1293 in the close code, the last closer will delete the file
1294 if flag is set.
1295 This makes a copy of any UNIX_USER_TOKEN into the
1296 lck entry. This function is used when the lock is already granted.
1297 ****************************************************************************/
1299 void set_delete_on_close_lck(struct share_mode_lock *lck, bool delete_on_close, UNIX_USER_TOKEN *tok)
1301 if (lck->delete_on_close != delete_on_close) {
1302 set_delete_on_close_token(lck, tok);
1303 lck->delete_on_close = delete_on_close;
1304 if (delete_on_close) {
1305 SMB_ASSERT(lck->delete_token != NULL);
1307 lck->modified = True;
1311 bool set_delete_on_close(files_struct *fsp, bool delete_on_close, UNIX_USER_TOKEN *tok)
1313 struct share_mode_lock *lck;
1315 DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1316 "fnum = %d, file %s\n",
1317 delete_on_close ? "Adding" : "Removing", fsp->fnum,
1318 fsp->fsp_name ));
1320 if (fsp->is_stat) {
1321 return True;
1324 lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL);
1325 if (lck == NULL) {
1326 return False;
1329 set_delete_on_close_lck(lck, delete_on_close, tok);
1331 if (fsp->is_directory) {
1332 send_stat_cache_delete_message(fsp->fsp_name);
1335 TALLOC_FREE(lck);
1336 return True;
1339 /****************************************************************************
1340 Sets the allow initial delete on close flag for this share mode.
1341 ****************************************************************************/
1343 bool set_allow_initial_delete_on_close(struct share_mode_lock *lck, files_struct *fsp, bool delete_on_close)
1345 struct share_mode_entry entry, *e;
1347 /* Don't care about the pid owner being correct here - just a search. */
1348 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1350 e = find_share_mode_entry(lck, &entry);
1351 if (e == NULL) {
1352 return False;
1355 if (delete_on_close) {
1356 e->flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1357 } else {
1358 e->flags &= ~SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1360 lck->modified = True;
1361 return True;
1364 struct forall_state {
1365 void (*fn)(const struct share_mode_entry *entry,
1366 const char *sharepath,
1367 const char *fname,
1368 void *private_data);
1369 void *private_data;
1372 static int traverse_fn(struct db_record *rec, void *_state)
1374 struct forall_state *state = (struct forall_state *)_state;
1375 struct locking_data *data;
1376 struct share_mode_entry *shares;
1377 const char *sharepath;
1378 const char *fname;
1379 int i;
1381 /* Ensure this is a locking_key record. */
1382 if (rec->key.dsize != sizeof(struct file_id))
1383 return 0;
1385 data = (struct locking_data *)rec->value.dptr;
1386 shares = (struct share_mode_entry *)(rec->value.dptr + sizeof(*data));
1387 sharepath = (const char *)rec->value.dptr + sizeof(*data) +
1388 data->u.s.num_share_mode_entries*sizeof(*shares) +
1389 data->u.s.delete_token_size;
1390 fname = (const char *)rec->value.dptr + sizeof(*data) +
1391 data->u.s.num_share_mode_entries*sizeof(*shares) +
1392 data->u.s.delete_token_size +
1393 strlen(sharepath) + 1;
1395 for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1396 state->fn(&shares[i], sharepath, fname,
1397 state->private_data);
1399 return 0;
1402 /*******************************************************************
1403 Call the specified function on each entry under management by the
1404 share mode system.
1405 ********************************************************************/
1407 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1408 const char *, void *),
1409 void *private_data)
1411 struct forall_state state;
1413 if (lock_db == NULL)
1414 return 0;
1416 state.fn = fn;
1417 state.private_data = private_data;
1419 return lock_db->traverse_read(lock_db, traverse_fn, (void *)&state);