s4:libcli/ldap: remove reference to DEBUG()
[Samba/gbeck.git] / source3 / locking / locking.c
blob1737eab1c6f32df43ac205b09d98002d3455fcba
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 uint64_t count,
81 uint64_t 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 uint64_t *pcount,
148 uint64_t *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 static void increment_current_lock_count(files_struct *fsp,
181 enum brl_flavour lock_flav)
183 if (lock_flav == WINDOWS_LOCK &&
184 fsp->current_lock_count != NO_LOCKING_COUNT) {
185 /* blocking ie. pending, locks also count here,
186 * as this is an efficiency counter to avoid checking
187 * the lock db. on close. JRA. */
189 fsp->current_lock_count++;
190 } else {
191 /* Notice that this has had a POSIX lock request.
192 * We can't count locks after this so forget them.
194 fsp->current_lock_count = NO_LOCKING_COUNT;
198 static void decrement_current_lock_count(files_struct *fsp,
199 enum brl_flavour lock_flav)
201 if (lock_flav == WINDOWS_LOCK &&
202 fsp->current_lock_count != NO_LOCKING_COUNT) {
203 SMB_ASSERT(fsp->current_lock_count > 0);
204 fsp->current_lock_count--;
208 /****************************************************************************
209 Utility function called by locking requests.
210 ****************************************************************************/
212 struct byte_range_lock *do_lock(struct messaging_context *msg_ctx,
213 files_struct *fsp,
214 uint32 lock_pid,
215 uint64_t count,
216 uint64_t offset,
217 enum brl_type lock_type,
218 enum brl_flavour lock_flav,
219 bool blocking_lock,
220 NTSTATUS *perr,
221 uint32 *plock_pid,
222 struct blocking_lock_record *blr)
224 struct byte_range_lock *br_lck = NULL;
226 if (!fsp->can_lock) {
227 *perr = fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
228 return NULL;
231 if (!lp_locking(fsp->conn->params)) {
232 *perr = NT_STATUS_OK;
233 return NULL;
236 /* NOTE! 0 byte long ranges ARE allowed and should be stored */
238 DEBUG(10,("do_lock: lock flavour %s lock type %s start=%.0f len=%.0f "
239 "blocking_lock=%s requested for fnum %d file %s\n",
240 lock_flav_name(lock_flav), lock_type_name(lock_type),
241 (double)offset, (double)count, blocking_lock ? "true" :
242 "false", fsp->fnum, fsp->fsp_name));
244 br_lck = brl_get_locks(talloc_tos(), fsp);
245 if (!br_lck) {
246 *perr = NT_STATUS_NO_MEMORY;
247 return NULL;
250 *perr = brl_lock(msg_ctx,
251 br_lck,
252 lock_pid,
253 procid_self(),
254 offset,
255 count,
256 lock_type,
257 lock_flav,
258 blocking_lock,
259 plock_pid,
260 blr);
262 DEBUG(10, ("do_lock: returning status=%s\n", nt_errstr(*perr)));
264 increment_current_lock_count(fsp, lock_flav);
265 return br_lck;
268 /****************************************************************************
269 Utility function called by unlocking requests.
270 ****************************************************************************/
272 NTSTATUS do_unlock(struct messaging_context *msg_ctx,
273 files_struct *fsp,
274 uint32 lock_pid,
275 uint64_t count,
276 uint64_t offset,
277 enum brl_flavour lock_flav)
279 bool ok = False;
280 struct byte_range_lock *br_lck = NULL;
282 if (!fsp->can_lock) {
283 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
286 if (!lp_locking(fsp->conn->params)) {
287 return NT_STATUS_OK;
290 DEBUG(10,("do_unlock: unlock start=%.0f len=%.0f requested for fnum %d file %s\n",
291 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
293 br_lck = brl_get_locks(talloc_tos(), fsp);
294 if (!br_lck) {
295 return NT_STATUS_NO_MEMORY;
298 ok = brl_unlock(msg_ctx,
299 br_lck,
300 lock_pid,
301 procid_self(),
302 offset,
303 count,
304 lock_flav);
306 TALLOC_FREE(br_lck);
308 if (!ok) {
309 DEBUG(10,("do_unlock: returning ERRlock.\n" ));
310 return NT_STATUS_RANGE_NOT_LOCKED;
313 decrement_current_lock_count(fsp, lock_flav);
314 return NT_STATUS_OK;
317 /****************************************************************************
318 Cancel any pending blocked locks.
319 ****************************************************************************/
321 NTSTATUS do_lock_cancel(files_struct *fsp,
322 uint32 lock_pid,
323 uint64_t count,
324 uint64_t offset,
325 enum brl_flavour lock_flav,
326 struct blocking_lock_record *blr)
328 bool ok = False;
329 struct byte_range_lock *br_lck = NULL;
331 if (!fsp->can_lock) {
332 return fsp->is_directory ?
333 NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
336 if (!lp_locking(fsp->conn->params)) {
337 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
340 DEBUG(10,("do_lock_cancel: cancel start=%.0f len=%.0f requested for fnum %d file %s\n",
341 (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
343 br_lck = brl_get_locks(talloc_tos(), fsp);
344 if (!br_lck) {
345 return NT_STATUS_NO_MEMORY;
348 ok = brl_lock_cancel(br_lck,
349 lock_pid,
350 procid_self(),
351 offset,
352 count,
353 lock_flav,
354 blr);
356 TALLOC_FREE(br_lck);
358 if (!ok) {
359 DEBUG(10,("do_lock_cancel: returning ERRcancelviolation.\n" ));
360 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
363 decrement_current_lock_count(fsp, lock_flav);
364 return NT_STATUS_OK;
367 /****************************************************************************
368 Remove any locks on this fd. Called from file_close().
369 ****************************************************************************/
371 void locking_close_file(struct messaging_context *msg_ctx,
372 files_struct *fsp)
374 struct byte_range_lock *br_lck;
376 if (!lp_locking(fsp->conn->params)) {
377 return;
380 /* If we have not outstanding locks or pending
381 * locks then we don't need to look in the lock db.
384 if (fsp->current_lock_count == 0) {
385 return;
388 br_lck = brl_get_locks(talloc_tos(),fsp);
390 if (br_lck) {
391 cancel_pending_lock_requests_by_fid(fsp, br_lck);
392 brl_close_fnum(msg_ctx, br_lck);
393 TALLOC_FREE(br_lck);
397 /****************************************************************************
398 Initialise the locking functions.
399 ****************************************************************************/
401 static bool locking_init_internal(bool read_only)
403 brl_init(read_only);
405 if (lock_db)
406 return True;
408 lock_db = db_open(NULL, lock_path("locking.tdb"),
409 lp_open_files_db_hash_size(),
410 TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST,
411 read_only?O_RDONLY:O_RDWR|O_CREAT, 0644);
413 if (!lock_db) {
414 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
415 return False;
418 if (!posix_locking_init(read_only))
419 return False;
421 return True;
424 bool locking_init(void)
426 return locking_init_internal(false);
429 bool locking_init_readonly(void)
431 return locking_init_internal(true);
434 /*******************************************************************
435 Deinitialize the share_mode management.
436 ******************************************************************/
438 bool locking_end(void)
440 brl_shutdown();
441 TALLOC_FREE(lock_db);
442 return true;
445 /*******************************************************************
446 Form a static locking key for a dev/inode pair.
447 ******************************************************************/
449 static TDB_DATA locking_key(const struct file_id *id, struct file_id *tmp)
451 *tmp = *id;
452 return make_tdb_data((const uint8_t *)tmp, sizeof(*tmp));
455 /*******************************************************************
456 Print out a share mode.
457 ********************************************************************/
459 char *share_mode_str(TALLOC_CTX *ctx, int num, const struct share_mode_entry *e)
461 return talloc_asprintf(ctx, "share_mode_entry[%d]: %s "
462 "pid = %s, share_access = 0x%x, private_options = 0x%x, "
463 "access_mask = 0x%x, mid = 0x%x, type= 0x%x, gen_id = %lu, "
464 "uid = %u, flags = %u, file_id %s",
465 num,
466 e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
467 procid_str_static(&e->pid),
468 e->share_access, e->private_options,
469 e->access_mask, e->op_mid, e->op_type, e->share_file_id,
470 (unsigned int)e->uid, (unsigned int)e->flags,
471 file_id_string_tos(&e->id));
474 /*******************************************************************
475 Print out a share mode table.
476 ********************************************************************/
478 static void print_share_mode_table(struct locking_data *data)
480 int num_share_modes = data->u.s.num_share_mode_entries;
481 struct share_mode_entry *shares =
482 (struct share_mode_entry *)(data + 1);
483 int i;
485 for (i = 0; i < num_share_modes; i++) {
486 struct share_mode_entry entry;
487 char *str;
490 * We need to memcpy the entry here due to alignment
491 * restrictions that are not met when directly accessing
492 * shares[i]
495 memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
496 str = share_mode_str(talloc_tos(), i, &entry);
498 DEBUG(10,("print_share_mode_table: %s\n", str ? str : ""));
499 TALLOC_FREE(str);
503 /*******************************************************************
504 Get all share mode entries for a dev/inode pair.
505 ********************************************************************/
507 static bool parse_share_modes(TDB_DATA dbuf, struct share_mode_lock *lck)
509 struct locking_data data;
510 int i;
512 if (dbuf.dsize < sizeof(struct locking_data)) {
513 smb_panic("parse_share_modes: buffer too short");
516 memcpy(&data, dbuf.dptr, sizeof(data));
518 lck->delete_on_close = data.u.s.delete_on_close;
519 lck->old_write_time = data.u.s.old_write_time;
520 lck->changed_write_time = data.u.s.changed_write_time;
521 lck->num_share_modes = data.u.s.num_share_mode_entries;
523 DEBUG(10, ("parse_share_modes: delete_on_close: %d, owrt: %s, "
524 "cwrt: %s, tok: %u, num_share_modes: %d\n",
525 lck->delete_on_close,
526 timestring(debug_ctx(),
527 convert_timespec_to_time_t(lck->old_write_time)),
528 timestring(debug_ctx(),
529 convert_timespec_to_time_t(
530 lck->changed_write_time)),
531 (unsigned int)data.u.s.delete_token_size,
532 lck->num_share_modes));
534 if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
535 DEBUG(0, ("invalid number of share modes: %d\n",
536 lck->num_share_modes));
537 smb_panic("parse_share_modes: invalid number of share modes");
540 lck->share_modes = NULL;
542 if (lck->num_share_modes != 0) {
544 if (dbuf.dsize < (sizeof(struct locking_data) +
545 (lck->num_share_modes *
546 sizeof(struct share_mode_entry)))) {
547 smb_panic("parse_share_modes: buffer too short");
550 lck->share_modes = (struct share_mode_entry *)
551 TALLOC_MEMDUP(lck,
552 dbuf.dptr+sizeof(struct locking_data),
553 lck->num_share_modes *
554 sizeof(struct share_mode_entry));
556 if (lck->share_modes == NULL) {
557 smb_panic("parse_share_modes: talloc failed");
561 /* Get any delete token. */
562 if (data.u.s.delete_token_size) {
563 uint8 *p = dbuf.dptr + sizeof(struct locking_data) +
564 (lck->num_share_modes *
565 sizeof(struct share_mode_entry));
567 if ((data.u.s.delete_token_size < sizeof(uid_t) + sizeof(gid_t)) ||
568 ((data.u.s.delete_token_size - sizeof(uid_t)) % sizeof(gid_t)) != 0) {
569 DEBUG(0, ("parse_share_modes: invalid token size %d\n",
570 data.u.s.delete_token_size));
571 smb_panic("parse_share_modes: invalid token size");
574 lck->delete_token = TALLOC_P(lck, UNIX_USER_TOKEN);
575 if (!lck->delete_token) {
576 smb_panic("parse_share_modes: talloc failed");
579 /* Copy out the uid and gid. */
580 memcpy(&lck->delete_token->uid, p, sizeof(uid_t));
581 p += sizeof(uid_t);
582 memcpy(&lck->delete_token->gid, p, sizeof(gid_t));
583 p += sizeof(gid_t);
585 /* Any supplementary groups ? */
586 lck->delete_token->ngroups = (data.u.s.delete_token_size > (sizeof(uid_t) + sizeof(gid_t))) ?
587 ((data.u.s.delete_token_size -
588 (sizeof(uid_t) + sizeof(gid_t)))/sizeof(gid_t)) : 0;
590 if (lck->delete_token->ngroups) {
591 /* Make this a talloc child of lck->delete_token. */
592 lck->delete_token->groups = TALLOC_ARRAY(lck->delete_token, gid_t,
593 lck->delete_token->ngroups);
594 if (!lck->delete_token) {
595 smb_panic("parse_share_modes: talloc failed");
598 for (i = 0; i < lck->delete_token->ngroups; i++) {
599 memcpy(&lck->delete_token->groups[i], p, sizeof(gid_t));
600 p += sizeof(gid_t);
604 } else {
605 lck->delete_token = NULL;
608 /* Save off the associated service path and filename. */
609 lck->servicepath = (const char *)dbuf.dptr + sizeof(struct locking_data) +
610 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
611 data.u.s.delete_token_size;
613 lck->filename = (const char *)dbuf.dptr + sizeof(struct locking_data) +
614 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
615 data.u.s.delete_token_size +
616 strlen(lck->servicepath) + 1;
619 * Ensure that each entry has a real process attached.
622 for (i = 0; i < lck->num_share_modes; i++) {
623 struct share_mode_entry *entry_p = &lck->share_modes[i];
624 char *str = NULL;
625 if (DEBUGLEVEL >= 10) {
626 str = share_mode_str(NULL, i, entry_p);
628 DEBUG(10,("parse_share_modes: %s\n",
629 str ? str : ""));
630 if (!process_exists(entry_p->pid)) {
631 DEBUG(10,("parse_share_modes: deleted %s\n",
632 str ? str : ""));
633 entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
634 lck->modified = True;
636 TALLOC_FREE(str);
639 return True;
642 static TDB_DATA unparse_share_modes(struct share_mode_lock *lck)
644 TDB_DATA result;
645 int num_valid = 0;
646 int i;
647 struct locking_data *data;
648 ssize_t offset;
649 ssize_t sp_len;
650 uint32 delete_token_size;
652 result.dptr = NULL;
653 result.dsize = 0;
655 for (i=0; i<lck->num_share_modes; i++) {
656 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
657 num_valid += 1;
661 if (num_valid == 0) {
662 return result;
665 sp_len = strlen(lck->servicepath);
666 delete_token_size = (lck->delete_token ?
667 (sizeof(uid_t) + sizeof(gid_t) + (lck->delete_token->ngroups*sizeof(gid_t))) : 0);
669 result.dsize = sizeof(*data) +
670 lck->num_share_modes * sizeof(struct share_mode_entry) +
671 delete_token_size +
672 sp_len + 1 +
673 strlen(lck->filename) + 1;
674 result.dptr = TALLOC_ARRAY(lck, uint8, result.dsize);
676 if (result.dptr == NULL) {
677 smb_panic("talloc failed");
680 data = (struct locking_data *)result.dptr;
681 ZERO_STRUCTP(data);
682 data->u.s.num_share_mode_entries = lck->num_share_modes;
683 data->u.s.delete_on_close = lck->delete_on_close;
684 data->u.s.old_write_time = lck->old_write_time;
685 data->u.s.changed_write_time = lck->changed_write_time;
686 data->u.s.delete_token_size = delete_token_size;
688 DEBUG(10,("unparse_share_modes: del: %d, owrt: %s cwrt: %s, tok: %u, "
689 "num: %d\n", data->u.s.delete_on_close,
690 timestring(debug_ctx(),
691 convert_timespec_to_time_t(lck->old_write_time)),
692 timestring(debug_ctx(),
693 convert_timespec_to_time_t(
694 lck->changed_write_time)),
695 (unsigned int)data->u.s.delete_token_size,
696 data->u.s.num_share_mode_entries));
698 memcpy(result.dptr + sizeof(*data), lck->share_modes,
699 sizeof(struct share_mode_entry)*lck->num_share_modes);
700 offset = sizeof(*data) +
701 sizeof(struct share_mode_entry)*lck->num_share_modes;
703 /* Store any delete on close token. */
704 if (lck->delete_token) {
705 uint8 *p = result.dptr + offset;
707 memcpy(p, &lck->delete_token->uid, sizeof(uid_t));
708 p += sizeof(uid_t);
710 memcpy(p, &lck->delete_token->gid, sizeof(gid_t));
711 p += sizeof(gid_t);
713 for (i = 0; i < lck->delete_token->ngroups; i++) {
714 memcpy(p, &lck->delete_token->groups[i], sizeof(gid_t));
715 p += sizeof(gid_t);
717 offset = p - result.dptr;
720 safe_strcpy((char *)result.dptr + offset, lck->servicepath,
721 result.dsize - offset - 1);
722 offset += sp_len + 1;
723 safe_strcpy((char *)result.dptr + offset, lck->filename,
724 result.dsize - offset - 1);
726 if (DEBUGLEVEL >= 10) {
727 print_share_mode_table(data);
730 return result;
733 static int share_mode_lock_destructor(struct share_mode_lock *lck)
735 NTSTATUS status;
736 TDB_DATA data;
738 if (!lck->modified) {
739 return 0;
742 data = unparse_share_modes(lck);
744 if (data.dptr == NULL) {
745 if (!lck->fresh) {
746 /* There has been an entry before, delete it */
748 status = lck->record->delete_rec(lck->record);
749 if (!NT_STATUS_IS_OK(status)) {
750 DEBUG(0, ("delete_rec returned %s\n",
751 nt_errstr(status)));
752 smb_panic("could not delete share entry");
755 goto done;
758 status = lck->record->store(lck->record, data, TDB_REPLACE);
759 if (!NT_STATUS_IS_OK(status)) {
760 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
761 smb_panic("could not store share mode entry");
764 done:
766 return 0;
769 static bool fill_share_mode_lock(struct share_mode_lock *lck,
770 struct file_id id,
771 const char *servicepath,
772 const char *fname,
773 TDB_DATA share_mode_data,
774 const struct timespec *old_write_time)
776 /* Ensure we set every field here as the destructor must be
777 valid even if parse_share_modes fails. */
779 lck->servicepath = NULL;
780 lck->filename = NULL;
781 lck->id = id;
782 lck->num_share_modes = 0;
783 lck->share_modes = NULL;
784 lck->delete_token = NULL;
785 lck->delete_on_close = False;
786 ZERO_STRUCT(lck->old_write_time);
787 ZERO_STRUCT(lck->changed_write_time);
788 lck->fresh = False;
789 lck->modified = False;
791 lck->fresh = (share_mode_data.dptr == NULL);
793 if (lck->fresh) {
794 if (fname == NULL || servicepath == NULL
795 || old_write_time == NULL) {
796 return False;
798 lck->filename = talloc_strdup(lck, fname);
799 lck->servicepath = talloc_strdup(lck, servicepath);
800 if (lck->filename == NULL || lck->servicepath == NULL) {
801 DEBUG(0, ("talloc failed\n"));
802 return False;
804 lck->old_write_time = *old_write_time;
805 } else {
806 if (!parse_share_modes(share_mode_data, lck)) {
807 DEBUG(0, ("Could not parse share modes\n"));
808 return False;
812 return True;
815 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
816 const struct file_id id,
817 const char *servicepath,
818 const char *fname,
819 const struct timespec *old_write_time)
821 struct share_mode_lock *lck;
822 struct file_id tmp;
823 TDB_DATA key = locking_key(&id, &tmp);
825 if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
826 DEBUG(0, ("talloc failed\n"));
827 return NULL;
830 if (!(lck->record = lock_db->fetch_locked(lock_db, lck, key))) {
831 DEBUG(3, ("Could not lock share entry\n"));
832 TALLOC_FREE(lck);
833 return NULL;
836 if (!fill_share_mode_lock(lck, id, servicepath, fname,
837 lck->record->value, old_write_time)) {
838 DEBUG(3, ("fill_share_mode_lock failed\n"));
839 TALLOC_FREE(lck);
840 return NULL;
843 talloc_set_destructor(lck, share_mode_lock_destructor);
845 return lck;
848 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
849 const struct file_id id,
850 const char *servicepath,
851 const char *fname)
853 struct share_mode_lock *lck;
854 struct file_id tmp;
855 TDB_DATA key = locking_key(&id, &tmp);
856 TDB_DATA data;
858 if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
859 DEBUG(0, ("talloc failed\n"));
860 return NULL;
863 if (lock_db->fetch(lock_db, lck, key, &data) == -1) {
864 DEBUG(3, ("Could not fetch share entry\n"));
865 TALLOC_FREE(lck);
866 return NULL;
869 if (!fill_share_mode_lock(lck, id, servicepath, fname, data, NULL)) {
870 DEBUG(3, ("fill_share_mode_lock failed\n"));
871 TALLOC_FREE(lck);
872 return NULL;
875 return lck;
878 /*******************************************************************
879 Sets the service name and filename for rename.
880 At this point we emit "file renamed" messages to all
881 process id's that have this file open.
882 Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
883 ********************************************************************/
885 bool rename_share_filename(struct messaging_context *msg_ctx,
886 struct share_mode_lock *lck,
887 const char *servicepath,
888 const char *newname)
890 size_t sp_len;
891 size_t fn_len;
892 size_t msg_len;
893 char *frm = NULL;
894 int i;
896 DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
897 servicepath, newname));
900 * rename_internal_fsp() and rename_internals() add './' to
901 * head of newname if newname does not contain a '/'.
903 while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
904 newname += 2;
907 lck->servicepath = talloc_strdup(lck, servicepath);
908 lck->filename = talloc_strdup(lck, newname);
909 if (lck->filename == NULL || lck->servicepath == NULL) {
910 DEBUG(0, ("rename_share_filename: talloc failed\n"));
911 return False;
913 lck->modified = True;
915 sp_len = strlen(lck->servicepath);
916 fn_len = strlen(lck->filename);
918 msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1;
920 /* Set up the name changed message. */
921 frm = TALLOC_ARRAY(lck, char, msg_len);
922 if (!frm) {
923 return False;
926 push_file_id_24(frm, &lck->id);
928 DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
930 safe_strcpy(&frm[24], lck->servicepath, sp_len);
931 safe_strcpy(&frm[24 + sp_len + 1], lck->filename, fn_len);
933 /* Send the messages. */
934 for (i=0; i<lck->num_share_modes; i++) {
935 struct share_mode_entry *se = &lck->share_modes[i];
936 if (!is_valid_share_mode_entry(se)) {
937 continue;
939 /* But not to ourselves... */
940 if (procid_is_me(&se->pid)) {
941 continue;
944 DEBUG(10,("rename_share_filename: sending rename message to pid %s "
945 "file_id %s sharepath %s newname %s\n",
946 procid_str_static(&se->pid),
947 file_id_string_tos(&lck->id),
948 lck->servicepath, lck->filename ));
950 messaging_send_buf(msg_ctx, se->pid, MSG_SMB_FILE_RENAME,
951 (uint8 *)frm, msg_len);
954 return True;
957 void get_file_infos(struct file_id id,
958 bool *delete_on_close,
959 struct timespec *write_time)
961 struct share_mode_lock *lck;
963 if (delete_on_close) {
964 *delete_on_close = false;
967 if (write_time) {
968 ZERO_STRUCTP(write_time);
971 if (!(lck = fetch_share_mode_unlocked(talloc_tos(), id, NULL, NULL))) {
972 return;
975 if (delete_on_close) {
976 *delete_on_close = lck->delete_on_close;
979 if (write_time) {
980 struct timespec wt;
982 wt = lck->changed_write_time;
983 if (null_timespec(wt)) {
984 wt = lck->old_write_time;
987 *write_time = wt;
990 TALLOC_FREE(lck);
993 bool is_valid_share_mode_entry(const struct share_mode_entry *e)
995 int num_props = 0;
997 if (e->op_type == UNUSED_SHARE_MODE_ENTRY) {
998 /* cope with dead entries from the process not
999 existing. These should not be considered valid,
1000 otherwise we end up doing zero timeout sharing
1001 violation */
1002 return False;
1005 num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
1006 num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1007 num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1009 SMB_ASSERT(num_props <= 1);
1010 return (num_props != 0);
1013 bool is_deferred_open_entry(const struct share_mode_entry *e)
1015 return (e->op_type == DEFERRED_OPEN_ENTRY);
1018 bool is_unused_share_mode_entry(const struct share_mode_entry *e)
1020 return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
1023 /*******************************************************************
1024 Fill a share mode entry.
1025 ********************************************************************/
1027 static void fill_share_mode_entry(struct share_mode_entry *e,
1028 files_struct *fsp,
1029 uid_t uid, uint16 mid, uint16 op_type)
1031 ZERO_STRUCTP(e);
1032 e->pid = procid_self();
1033 e->share_access = fsp->share_access;
1034 e->private_options = fsp->fh->private_options;
1035 e->access_mask = fsp->access_mask;
1036 e->op_mid = mid;
1037 e->op_type = op_type;
1038 e->time.tv_sec = fsp->open_time.tv_sec;
1039 e->time.tv_usec = fsp->open_time.tv_usec;
1040 e->id = fsp->file_id;
1041 e->share_file_id = fsp->fh->gen_id;
1042 e->uid = (uint32)uid;
1043 e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
1046 static void fill_deferred_open_entry(struct share_mode_entry *e,
1047 const struct timeval request_time,
1048 struct file_id id, uint16 mid)
1050 ZERO_STRUCTP(e);
1051 e->pid = procid_self();
1052 e->op_mid = mid;
1053 e->op_type = DEFERRED_OPEN_ENTRY;
1054 e->time.tv_sec = request_time.tv_sec;
1055 e->time.tv_usec = request_time.tv_usec;
1056 e->id = id;
1057 e->uid = (uint32)-1;
1058 e->flags = 0;
1061 static void add_share_mode_entry(struct share_mode_lock *lck,
1062 const struct share_mode_entry *entry)
1064 int i;
1066 for (i=0; i<lck->num_share_modes; i++) {
1067 struct share_mode_entry *e = &lck->share_modes[i];
1068 if (is_unused_share_mode_entry(e)) {
1069 *e = *entry;
1070 break;
1074 if (i == lck->num_share_modes) {
1075 /* No unused entry found */
1076 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
1077 &lck->share_modes, &lck->num_share_modes);
1079 lck->modified = True;
1082 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
1083 uid_t uid, uint16 mid, uint16 op_type)
1085 struct share_mode_entry entry;
1086 fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1087 add_share_mode_entry(lck, &entry);
1090 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
1091 struct timeval request_time,
1092 struct file_id id)
1094 struct share_mode_entry entry;
1095 fill_deferred_open_entry(&entry, request_time, id, mid);
1096 add_share_mode_entry(lck, &entry);
1099 /*******************************************************************
1100 Check if two share mode entries are identical, ignoring oplock
1101 and mid info and desired_access. (Removed paranoia test - it's
1102 not automatically a logic error if they are identical. JRA.)
1103 ********************************************************************/
1105 static bool share_modes_identical(struct share_mode_entry *e1,
1106 struct share_mode_entry *e2)
1108 /* We used to check for e1->share_access == e2->share_access here
1109 as well as the other fields but 2 different DOS or FCB opens
1110 sharing the same share mode entry may validly differ in
1111 fsp->share_access field. */
1113 return (procid_equal(&e1->pid, &e2->pid) &&
1114 file_id_equal(&e1->id, &e2->id) &&
1115 e1->share_file_id == e2->share_file_id );
1118 static bool deferred_open_identical(struct share_mode_entry *e1,
1119 struct share_mode_entry *e2)
1121 return (procid_equal(&e1->pid, &e2->pid) &&
1122 (e1->op_mid == e2->op_mid) &&
1123 file_id_equal(&e1->id, &e2->id));
1126 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1127 struct share_mode_entry *entry)
1129 int i;
1131 for (i=0; i<lck->num_share_modes; i++) {
1132 struct share_mode_entry *e = &lck->share_modes[i];
1133 if (is_valid_share_mode_entry(entry) &&
1134 is_valid_share_mode_entry(e) &&
1135 share_modes_identical(e, entry)) {
1136 return e;
1138 if (is_deferred_open_entry(entry) &&
1139 is_deferred_open_entry(e) &&
1140 deferred_open_identical(e, entry)) {
1141 return e;
1144 return NULL;
1147 /*******************************************************************
1148 Del the share mode of a file for this process. Return the number of
1149 entries left.
1150 ********************************************************************/
1152 bool del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1154 struct share_mode_entry entry, *e;
1156 /* Don't care about the pid owner being correct here - just a search. */
1157 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1159 e = find_share_mode_entry(lck, &entry);
1160 if (e == NULL) {
1161 return False;
1164 e->op_type = UNUSED_SHARE_MODE_ENTRY;
1165 lck->modified = True;
1166 return True;
1169 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
1171 struct share_mode_entry entry, *e;
1173 fill_deferred_open_entry(&entry, timeval_zero(),
1174 lck->id, mid);
1176 e = find_share_mode_entry(lck, &entry);
1177 if (e == NULL) {
1178 return;
1181 e->op_type = UNUSED_SHARE_MODE_ENTRY;
1182 lck->modified = True;
1185 /*******************************************************************
1186 Remove an oplock mid and mode entry from a share mode.
1187 ********************************************************************/
1189 bool remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1191 struct share_mode_entry entry, *e;
1193 /* Don't care about the pid owner being correct here - just a search. */
1194 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1196 e = find_share_mode_entry(lck, &entry);
1197 if (e == NULL) {
1198 return False;
1201 e->op_mid = 0;
1202 if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1204 * Going from exclusive or batch,
1205 * we always go through FAKE_LEVEL_II
1206 * first.
1208 e->op_type = FAKE_LEVEL_II_OPLOCK;
1209 } else {
1210 e->op_type = NO_OPLOCK;
1212 lck->modified = True;
1213 return True;
1216 /*******************************************************************
1217 Downgrade a oplock type from exclusive to level II.
1218 ********************************************************************/
1220 bool downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1222 struct share_mode_entry entry, *e;
1224 /* Don't care about the pid owner being correct here - just a search. */
1225 fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1227 e = find_share_mode_entry(lck, &entry);
1228 if (e == NULL) {
1229 return False;
1232 e->op_type = LEVEL_II_OPLOCK;
1233 lck->modified = True;
1234 return True;
1237 /****************************************************************************
1238 Deal with the internal needs of setting the delete on close flag. Note that
1239 as the tdb locking is recursive, it is safe to call this from within
1240 open_file_ntcreate. JRA.
1241 ****************************************************************************/
1243 NTSTATUS can_set_delete_on_close(files_struct *fsp, bool delete_on_close,
1244 uint32 dosmode)
1246 if (!delete_on_close) {
1247 return NT_STATUS_OK;
1251 * Only allow delete on close for writable files.
1254 if ((dosmode & aRONLY) &&
1255 !lp_delete_readonly(SNUM(fsp->conn))) {
1256 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1257 "flag set but file attribute is readonly.\n",
1258 fsp->fsp_name ));
1259 return NT_STATUS_CANNOT_DELETE;
1263 * Only allow delete on close for writable shares.
1266 if (!CAN_WRITE(fsp->conn)) {
1267 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1268 "close flag set but write access denied on share.\n",
1269 fsp->fsp_name ));
1270 return NT_STATUS_ACCESS_DENIED;
1274 * Only allow delete on close for files/directories opened with delete
1275 * intent.
1278 if (!(fsp->access_mask & DELETE_ACCESS)) {
1279 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1280 "close flag set but delete access denied.\n",
1281 fsp->fsp_name ));
1282 return NT_STATUS_ACCESS_DENIED;
1285 /* Don't allow delete on close for non-empty directories. */
1286 if (fsp->is_directory) {
1287 return can_delete_directory(fsp->conn, fsp->fsp_name);
1290 return NT_STATUS_OK;
1293 /*************************************************************************
1294 Return a talloced copy of a UNIX_USER_TOKEN. NULL on fail.
1295 (Should this be in locking.c.... ?).
1296 *************************************************************************/
1298 static UNIX_USER_TOKEN *copy_unix_token(TALLOC_CTX *ctx, UNIX_USER_TOKEN *tok)
1300 UNIX_USER_TOKEN *cpy;
1302 if (tok == NULL) {
1303 return NULL;
1306 cpy = TALLOC_P(ctx, UNIX_USER_TOKEN);
1307 if (!cpy) {
1308 return NULL;
1311 cpy->uid = tok->uid;
1312 cpy->gid = tok->gid;
1313 cpy->ngroups = tok->ngroups;
1314 if (tok->ngroups) {
1315 /* Make this a talloc child of cpy. */
1316 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1317 if (!cpy->groups) {
1318 return NULL;
1320 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1322 return cpy;
1325 /****************************************************************************
1326 Replace the delete on close token.
1327 ****************************************************************************/
1329 void set_delete_on_close_token(struct share_mode_lock *lck, UNIX_USER_TOKEN *tok)
1331 TALLOC_FREE(lck->delete_token); /* Also deletes groups... */
1333 /* Copy the new token (can be NULL). */
1334 lck->delete_token = copy_unix_token(lck, tok);
1335 lck->modified = True;
1338 /****************************************************************************
1339 Sets the delete on close flag over all share modes on this file.
1340 Modify the share mode entry for all files open
1341 on this device and inode to tell other smbds we have
1342 changed the delete on close flag. This will be noticed
1343 in the close code, the last closer will delete the file
1344 if flag is set.
1345 This makes a copy of any UNIX_USER_TOKEN into the
1346 lck entry. This function is used when the lock is already granted.
1347 ****************************************************************************/
1349 void set_delete_on_close_lck(struct share_mode_lock *lck, bool delete_on_close, UNIX_USER_TOKEN *tok)
1351 if (lck->delete_on_close != delete_on_close) {
1352 set_delete_on_close_token(lck, tok);
1353 lck->delete_on_close = delete_on_close;
1354 if (delete_on_close) {
1355 SMB_ASSERT(lck->delete_token != NULL);
1357 lck->modified = True;
1361 bool set_delete_on_close(files_struct *fsp, bool delete_on_close, UNIX_USER_TOKEN *tok)
1363 struct share_mode_lock *lck;
1365 DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1366 "fnum = %d, file %s\n",
1367 delete_on_close ? "Adding" : "Removing", fsp->fnum,
1368 fsp->fsp_name ));
1370 lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
1371 NULL);
1372 if (lck == NULL) {
1373 return False;
1376 set_delete_on_close_lck(lck, delete_on_close, tok);
1378 if (fsp->is_directory) {
1379 send_stat_cache_delete_message(fsp->fsp_name);
1382 TALLOC_FREE(lck);
1383 return True;
1386 bool set_sticky_write_time(struct file_id fileid, struct timespec write_time)
1388 struct share_mode_lock *lck;
1390 DEBUG(5,("set_sticky_write_time: %s id=%s\n",
1391 timestring(debug_ctx(),
1392 convert_timespec_to_time_t(write_time)),
1393 file_id_string_tos(&fileid)));
1395 lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1396 if (lck == NULL) {
1397 return False;
1400 if (timespec_compare(&lck->changed_write_time, &write_time) != 0) {
1401 lck->modified = True;
1402 lck->changed_write_time = write_time;
1405 TALLOC_FREE(lck);
1406 return True;
1409 bool set_write_time(struct file_id fileid, struct timespec write_time)
1411 struct share_mode_lock *lck;
1413 DEBUG(5,("set_write_time: %s id=%s\n",
1414 timestring(debug_ctx(),
1415 convert_timespec_to_time_t(write_time)),
1416 file_id_string_tos(&fileid)));
1418 lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1419 if (lck == NULL) {
1420 return False;
1423 if (timespec_compare(&lck->old_write_time, &write_time) != 0) {
1424 lck->modified = True;
1425 lck->old_write_time = write_time;
1428 TALLOC_FREE(lck);
1429 return True;
1433 struct forall_state {
1434 void (*fn)(const struct share_mode_entry *entry,
1435 const char *sharepath,
1436 const char *fname,
1437 void *private_data);
1438 void *private_data;
1441 static int traverse_fn(struct db_record *rec, void *_state)
1443 struct forall_state *state = (struct forall_state *)_state;
1444 struct locking_data *data;
1445 struct share_mode_entry *shares;
1446 const char *sharepath;
1447 const char *fname;
1448 int i;
1450 /* Ensure this is a locking_key record. */
1451 if (rec->key.dsize != sizeof(struct file_id))
1452 return 0;
1454 data = (struct locking_data *)rec->value.dptr;
1455 shares = (struct share_mode_entry *)(rec->value.dptr + sizeof(*data));
1456 sharepath = (const char *)rec->value.dptr + sizeof(*data) +
1457 data->u.s.num_share_mode_entries*sizeof(*shares) +
1458 data->u.s.delete_token_size;
1459 fname = (const char *)rec->value.dptr + sizeof(*data) +
1460 data->u.s.num_share_mode_entries*sizeof(*shares) +
1461 data->u.s.delete_token_size +
1462 strlen(sharepath) + 1;
1464 for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1465 state->fn(&shares[i], sharepath, fname,
1466 state->private_data);
1468 return 0;
1471 /*******************************************************************
1472 Call the specified function on each entry under management by the
1473 share mode system.
1474 ********************************************************************/
1476 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1477 const char *, void *),
1478 void *private_data)
1480 struct forall_state state;
1482 if (lock_db == NULL)
1483 return 0;
1485 state.fn = fn;
1486 state.private_data = private_data;
1488 return lock_db->traverse_read(lock_db, traverse_fn, (void *)&state);