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
7
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 2 of the License, or
11   (at your option) any later version.
12
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.
17
18   You should have received a copy of the GNU General Public License
19   along with this program; if not, write to the Free Software
20   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22   Revision History:
23
24   12 aug 96: Erik.Devriendt@te6.siemens.be
25   added support for shared memory implementation of share mode locking
26
27   May 1997. Jeremy Allison (jallison@whistle.com). Modified share mode
28   locking to deal with multiple share modes per open file.
29
30   September 1997. Jeremy Allison (jallison@whistle.com). Added oplock
31   support.
32
33   rewrtten completely to use new tdb code. Tridge, Dec '99
34
35   Added POSIX locking support. Jeremy Allison (jeremy@valinux.com), Apr. 2000.
36   Added Unix Extensions POSIX locking support. Jeremy Allison Mar 2006.
37*/
38
39#include "includes.h"
40
41#undef DBGC_CLASS
42#define DBGC_CLASS DBGC_LOCKING
43
44/* the locking database handle */
45static TDB_CONTEXT *tdb;
46
47/****************************************************************************
48 Debugging aids :-).
49****************************************************************************/
50
51const char *lock_type_name(enum brl_type lock_type)
52{
53	switch (lock_type) {
54		case READ_LOCK:
55			return "READ";
56		case WRITE_LOCK:
57			return "WRITE";
58		case PENDING_READ_LOCK:
59			return "PENDING_READ";
60		case PENDING_WRITE_LOCK:
61			return "PENDING_WRITE";
62		default:
63			return "other";
64	}
65}
66
67const char *lock_flav_name(enum brl_flavour lock_flav)
68{
69	return (lock_flav == WINDOWS_LOCK) ? "WINDOWS_LOCK" : "POSIX_LOCK";
70}
71
72/****************************************************************************
73 Utility function called to see if a file region is locked.
74 Called in the read/write codepath.
75****************************************************************************/
76
77BOOL is_locked(files_struct *fsp,
78		uint32 smbpid,
79		SMB_BIG_UINT count,
80		SMB_BIG_UINT offset,
81		enum brl_type lock_type)
82{
83	int strict_locking = lp_strict_locking(fsp->conn->params);
84	enum brl_flavour lock_flav = lp_posix_cifsu_locktype(fsp);
85	BOOL ret = True;
86
87	if (count == 0) {
88		return False;
89	}
90
91	if (!lp_locking(fsp->conn->params) || !strict_locking) {
92		return False;
93	}
94
95	if (strict_locking == Auto) {
96		if  (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && (lock_type == READ_LOCK || lock_type == WRITE_LOCK)) {
97			DEBUG(10,("is_locked: optimisation - exclusive oplock on file %s\n", fsp->fsp_name ));
98			ret = False;
99		} else if ((fsp->oplock_type == LEVEL_II_OPLOCK) &&
100			   (lock_type == READ_LOCK)) {
101			DEBUG(10,("is_locked: optimisation - level II oplock on file %s\n", fsp->fsp_name ));
102			ret = False;
103		} else {
104			struct byte_range_lock *br_lck = brl_get_locks_readonly(NULL, fsp);
105			if (!br_lck) {
106				return False;
107			}
108			ret = !brl_locktest(br_lck,
109					smbpid,
110					procid_self(),
111					offset,
112					count,
113					lock_type,
114					lock_flav);
115			TALLOC_FREE(br_lck);
116		}
117	} else {
118		struct byte_range_lock *br_lck = brl_get_locks_readonly(NULL, fsp);
119		if (!br_lck) {
120			return False;
121		}
122		ret = !brl_locktest(br_lck,
123				smbpid,
124				procid_self(),
125				offset,
126				count,
127				lock_type,
128				lock_flav);
129		TALLOC_FREE(br_lck);
130	}
131
132	DEBUG(10,("is_locked: flavour = %s brl start=%.0f len=%.0f %s for fnum %d file %s\n",
133			lock_flav_name(lock_flav),
134			(double)offset, (double)count, ret ? "locked" : "unlocked",
135			fsp->fnum, fsp->fsp_name ));
136
137	return ret;
138}
139
140/****************************************************************************
141 Find out if a lock could be granted - return who is blocking us if we can't.
142****************************************************************************/
143
144NTSTATUS query_lock(files_struct *fsp,
145			uint32 *psmbpid,
146			SMB_BIG_UINT *pcount,
147			SMB_BIG_UINT *poffset,
148			enum brl_type *plock_type,
149			enum brl_flavour lock_flav)
150{
151	struct byte_range_lock *br_lck = NULL;
152	NTSTATUS status = NT_STATUS_LOCK_NOT_GRANTED;
153
154	if (!fsp->can_lock) {
155		return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
156	}
157
158	if (!lp_locking(fsp->conn->params)) {
159		return NT_STATUS_OK;
160	}
161
162	br_lck = brl_get_locks_readonly(NULL, fsp);
163	if (!br_lck) {
164		return NT_STATUS_NO_MEMORY;
165	}
166
167	status = brl_lockquery(br_lck,
168			psmbpid,
169			procid_self(),
170			poffset,
171			pcount,
172			plock_type,
173			lock_flav);
174
175	TALLOC_FREE(br_lck);
176	return status;
177}
178
179/****************************************************************************
180 Utility function called by locking requests.
181****************************************************************************/
182
183struct byte_range_lock *do_lock(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)
192{
193	struct byte_range_lock *br_lck = NULL;
194
195	if (!fsp->can_lock) {
196		*perr = fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
197		return NULL;
198	}
199
200	if (!lp_locking(fsp->conn->params)) {
201		*perr = NT_STATUS_OK;
202		return NULL;
203	}
204
205	/* NOTE! 0 byte long ranges ARE allowed and should be stored  */
206
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 ));
210
211	br_lck = brl_get_locks(NULL, fsp);
212	if (!br_lck) {
213		*perr = NT_STATUS_NO_MEMORY;
214		return NULL;
215	}
216
217	*perr = brl_lock(br_lck,
218			lock_pid,
219			procid_self(),
220			offset,
221			count,
222			lock_type,
223			lock_flav,
224			blocking_lock,
225			plock_pid);
226
227	/* blocking ie. pending, locks also count here,
228	 * as this is an efficiency counter to avoid checking
229	 * the lock db. on close. JRA. */
230
231	fsp->current_lock_count++;
232
233	return br_lck;
234}
235
236/****************************************************************************
237 Utility function called by unlocking requests.
238****************************************************************************/
239
240NTSTATUS do_unlock(files_struct *fsp,
241			uint32 lock_pid,
242			SMB_BIG_UINT count,
243			SMB_BIG_UINT offset,
244			enum brl_flavour lock_flav)
245{
246	BOOL ok = False;
247	struct byte_range_lock *br_lck = NULL;
248
249	if (!fsp->can_lock) {
250		return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
251	}
252
253	if (!lp_locking(fsp->conn->params)) {
254		return NT_STATUS_OK;
255	}
256
257	DEBUG(10,("do_unlock: unlock start=%.0f len=%.0f requested for fnum %d file %s\n",
258		  (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
259
260	br_lck = brl_get_locks(NULL, fsp);
261	if (!br_lck) {
262		return NT_STATUS_NO_MEMORY;
263	}
264
265	ok = brl_unlock(br_lck,
266			lock_pid,
267			procid_self(),
268			offset,
269			count,
270			lock_flav);
271
272	TALLOC_FREE(br_lck);
273
274	if (!ok) {
275		DEBUG(10,("do_unlock: returning ERRlock.\n" ));
276		return NT_STATUS_RANGE_NOT_LOCKED;
277	}
278
279	SMB_ASSERT(fsp->current_lock_count > 0);
280	fsp->current_lock_count--;
281
282	return NT_STATUS_OK;
283}
284
285/****************************************************************************
286 Cancel any pending blocked locks.
287****************************************************************************/
288
289NTSTATUS do_lock_cancel(files_struct *fsp,
290			uint32 lock_pid,
291			SMB_BIG_UINT count,
292			SMB_BIG_UINT offset,
293			enum brl_flavour lock_flav)
294{
295	BOOL ok = False;
296	struct byte_range_lock *br_lck = NULL;
297
298	if (!fsp->can_lock) {
299		return fsp->is_directory ?
300			NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
301	}
302
303	if (!lp_locking(fsp->conn->params)) {
304		return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
305	}
306
307	DEBUG(10,("do_lock_cancel: cancel start=%.0f len=%.0f requested for fnum %d file %s\n",
308		  (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
309
310	br_lck = brl_get_locks(NULL, fsp);
311	if (!br_lck) {
312		return NT_STATUS_NO_MEMORY;
313	}
314
315	ok = brl_lock_cancel(br_lck,
316			lock_pid,
317			procid_self(),
318			offset,
319			count,
320			lock_flav);
321
322	TALLOC_FREE(br_lck);
323
324	if (!ok) {
325		DEBUG(10,("do_lock_cancel: returning ERRcancelviolation.\n" ));
326		return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
327	}
328
329	SMB_ASSERT(fsp->current_lock_count > 0);
330	fsp->current_lock_count--;
331
332	return NT_STATUS_OK;
333}
334
335/****************************************************************************
336 Remove any locks on this fd. Called from file_close().
337****************************************************************************/
338
339void locking_close_file(files_struct *fsp)
340{
341	struct byte_range_lock *br_lck;
342
343	if (!lp_locking(fsp->conn->params)) {
344		return;
345	}
346
347	/* If we have not outstanding locks or pending
348	 * locks then we don't need to look in the lock db.
349	 */
350
351	if (fsp->current_lock_count == 0) {
352		return;
353	}
354
355	br_lck = brl_get_locks(NULL,fsp);
356
357	if (br_lck) {
358		cancel_pending_lock_requests_by_fid(fsp, br_lck);
359		brl_close_fnum(br_lck);
360		TALLOC_FREE(br_lck);
361	}
362}
363
364/****************************************************************************
365 Initialise the locking functions.
366****************************************************************************/
367
368static int open_read_only;
369
370BOOL locking_init(int read_only)
371{
372	brl_init(read_only);
373
374	if (tdb)
375		return True;
376
377	tdb = tdb_open_log(lock_path("locking.tdb"),
378			lp_open_files_db_hash_size(),
379			TDB_DEFAULT|(read_only?0x0:TDB_CLEAR_IF_FIRST),
380			read_only?O_RDONLY:O_RDWR|O_CREAT,
381			0644);
382
383	if (!tdb) {
384		DEBUG(0,("ERROR: Failed to initialise locking database\n"));
385		return False;
386	}
387
388	/* Activate the per-hashchain freelist */
389	tdb_set_max_dead(tdb, 5);
390
391	if (!posix_locking_init(read_only))
392		return False;
393
394	open_read_only = read_only;
395
396	return True;
397}
398
399/*******************************************************************
400 Deinitialize the share_mode management.
401******************************************************************/
402
403BOOL locking_end(void)
404{
405	BOOL ret = True;
406
407	brl_shutdown(open_read_only);
408	if (tdb) {
409		if (tdb_close(tdb) != 0)
410			ret = False;
411	}
412
413	return ret;
414}
415
416/*******************************************************************
417 Form a static locking key for a dev/inode pair.
418******************************************************************/
419
420/* key and data records in the tdb locking database */
421struct locking_key {
422	SMB_DEV_T dev;
423	SMB_INO_T ino;
424};
425
426/*******************************************************************
427 Form a static locking key for a dev/inode pair.
428******************************************************************/
429
430static TDB_DATA locking_key(SMB_DEV_T dev, SMB_INO_T inode)
431{
432	static struct locking_key key;
433	TDB_DATA kbuf;
434
435	memset(&key, '\0', sizeof(key));
436	key.dev = dev;
437	key.ino = inode;
438	kbuf.dptr = (char *)&key;
439	kbuf.dsize = sizeof(key);
440	return kbuf;
441}
442
443/*******************************************************************
444 Print out a share mode.
445********************************************************************/
446
447char *share_mode_str(int num, struct share_mode_entry *e)
448{
449	static pstring share_str;
450
451	slprintf(share_str, sizeof(share_str)-1, "share_mode_entry[%d]: %s "
452		 "pid = %s, share_access = 0x%x, private_options = 0x%x, "
453		 "access_mask = 0x%x, mid = 0x%x, type= 0x%x, file_id = %lu, "
454		 "uid = %u, flags = %u, dev = 0x%x, inode = %.0f",
455		 num,
456		 e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
457		 procid_str_static(&e->pid),
458		 e->share_access, e->private_options,
459		 e->access_mask, e->op_mid, e->op_type, e->share_file_id,
460		 (unsigned int)e->uid, (unsigned int)e->flags,
461		 (unsigned int)e->dev, (double)e->inode );
462
463	return share_str;
464}
465
466/*******************************************************************
467 Print out a share mode table.
468********************************************************************/
469
470static void print_share_mode_table(struct locking_data *data)
471{
472	int num_share_modes = data->u.s.num_share_mode_entries;
473	struct share_mode_entry *shares =
474		(struct share_mode_entry *)(data + 1);
475	int i;
476
477	for (i = 0; i < num_share_modes; i++) {
478		struct share_mode_entry entry;
479
480		memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
481		DEBUG(10,("print_share_mode_table: %s\n",
482			  share_mode_str(i, &entry)));
483	}
484}
485
486/*******************************************************************
487 Get all share mode entries for a dev/inode pair.
488********************************************************************/
489
490static BOOL parse_share_modes(TDB_DATA dbuf, struct share_mode_lock *lck)
491{
492	struct locking_data *data;
493	int i;
494
495	if (dbuf.dsize < sizeof(struct locking_data)) {
496		smb_panic("PANIC: parse_share_modes: buffer too short.\n");
497	}
498
499	data = (struct locking_data *)dbuf.dptr;
500
501	lck->delete_on_close = data->u.s.delete_on_close;
502	lck->num_share_modes = data->u.s.num_share_mode_entries;
503
504	DEBUG(10, ("parse_share_modes: delete_on_close: %d, "
505		   "num_share_modes: %d\n",
506		lck->delete_on_close,
507		lck->num_share_modes));
508
509	if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
510		DEBUG(0, ("invalid number of share modes: %d\n",
511			  lck->num_share_modes));
512		smb_panic("PANIC: invalid number of share modes");
513	}
514
515	lck->share_modes = NULL;
516
517	if (lck->num_share_modes != 0) {
518
519		if (dbuf.dsize < (sizeof(struct locking_data) +
520				  (lck->num_share_modes *
521				   sizeof(struct share_mode_entry)))) {
522			smb_panic("PANIC: parse_share_modes: buffer too short.\n");
523		}
524
525		lck->share_modes = (struct share_mode_entry *)
526			TALLOC_MEMDUP(lck, dbuf.dptr+sizeof(*data),
527				      lck->num_share_modes *
528				      sizeof(struct share_mode_entry));
529
530		if (lck->share_modes == NULL) {
531			smb_panic("talloc failed\n");
532		}
533	}
534
535	/* Get any delete token. */
536	if (data->u.s.delete_token_size) {
537		char *p = dbuf.dptr + sizeof(*data) +
538				(lck->num_share_modes *
539				sizeof(struct share_mode_entry));
540
541		if ((data->u.s.delete_token_size < sizeof(uid_t) + sizeof(gid_t)) ||
542				((data->u.s.delete_token_size - sizeof(uid_t)) % sizeof(gid_t)) != 0) {
543			DEBUG(0, ("parse_share_modes: invalid token size %d\n",
544				data->u.s.delete_token_size));
545			smb_panic("parse_share_modes: invalid token size\n");
546		}
547
548		lck->delete_token = TALLOC_P(lck, UNIX_USER_TOKEN);
549		if (!lck->delete_token) {
550			smb_panic("talloc failed\n");
551		}
552
553		/* Copy out the uid and gid. */
554		memcpy(&lck->delete_token->uid, p, sizeof(uid_t));
555		p += sizeof(uid_t);
556		memcpy(&lck->delete_token->gid, p, sizeof(gid_t));
557		p += sizeof(gid_t);
558
559		/* Any supplementary groups ? */
560		lck->delete_token->ngroups = (data->u.s.delete_token_size > (sizeof(uid_t) + sizeof(gid_t))) ?
561					((data->u.s.delete_token_size -
562						(sizeof(uid_t) + sizeof(gid_t)))/sizeof(gid_t)) : 0;
563
564		if (lck->delete_token->ngroups) {
565			/* Make this a talloc child of lck->delete_token. */
566			lck->delete_token->groups = TALLOC_ARRAY(lck->delete_token, gid_t,
567							lck->delete_token->ngroups);
568			if (!lck->delete_token) {
569				smb_panic("talloc failed\n");
570			}
571
572			for (i = 0; i < lck->delete_token->ngroups; i++) {
573				memcpy(&lck->delete_token->groups[i], p, sizeof(gid_t));
574				p += sizeof(gid_t);
575			}
576		}
577
578	} else {
579		lck->delete_token = NULL;
580	}
581
582	/* Save off the associated service path and filename. */
583	lck->servicepath = talloc_strdup(lck, dbuf.dptr + sizeof(*data) +
584					(lck->num_share_modes *
585					sizeof(struct share_mode_entry)) +
586					data->u.s.delete_token_size );
587	if (lck->servicepath == NULL) {
588		smb_panic("talloc_strdup failed\n");
589	}
590
591	lck->filename = talloc_strdup(lck, dbuf.dptr + sizeof(*data) +
592					(lck->num_share_modes *
593					sizeof(struct share_mode_entry)) +
594					data->u.s.delete_token_size +
595					strlen(lck->servicepath) + 1 );
596	if (lck->filename == NULL) {
597		smb_panic("talloc_strdup failed\n");
598	}
599
600	/*
601	 * Ensure that each entry has a real process attached.
602	 */
603
604	for (i = 0; i < lck->num_share_modes; i++) {
605		struct share_mode_entry *entry_p = &lck->share_modes[i];
606		DEBUG(10,("parse_share_modes: %s\n",
607			  share_mode_str(i, entry_p) ));
608		if (!process_exists(entry_p->pid)) {
609			DEBUG(10,("parse_share_modes: deleted %s\n",
610				  share_mode_str(i, entry_p) ));
611			entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
612			lck->modified = True;
613		}
614	}
615
616	return True;
617}
618
619static TDB_DATA unparse_share_modes(struct share_mode_lock *lck)
620{
621	TDB_DATA result;
622	int num_valid = 0;
623	int i;
624	struct locking_data *data;
625	ssize_t offset;
626	ssize_t sp_len;
627	uint32 delete_token_size;
628
629	result.dptr = NULL;
630	result.dsize = 0;
631
632	for (i=0; i<lck->num_share_modes; i++) {
633		if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
634			num_valid += 1;
635		}
636	}
637
638	if (num_valid == 0) {
639		return result;
640	}
641
642	sp_len = strlen(lck->servicepath);
643	delete_token_size = (lck->delete_token ?
644			(sizeof(uid_t) + sizeof(gid_t) + (lck->delete_token->ngroups*sizeof(gid_t))) : 0);
645
646	result.dsize = sizeof(*data) +
647		lck->num_share_modes * sizeof(struct share_mode_entry) +
648		delete_token_size +
649		sp_len + 1 +
650		strlen(lck->filename) + 1;
651	result.dptr = TALLOC_ARRAY(lck, char, result.dsize);
652
653	if (result.dptr == NULL) {
654		smb_panic("talloc failed\n");
655	}
656
657	data = (struct locking_data *)result.dptr;
658	ZERO_STRUCTP(data);
659	data->u.s.num_share_mode_entries = lck->num_share_modes;
660	data->u.s.delete_on_close = lck->delete_on_close;
661	data->u.s.delete_token_size = delete_token_size;
662	DEBUG(10, ("unparse_share_modes: del: %d, tok = %u, num: %d\n",
663		data->u.s.delete_on_close,
664		(unsigned int)data->u.s.delete_token_size,
665		data->u.s.num_share_mode_entries));
666	memcpy(result.dptr + sizeof(*data), lck->share_modes,
667	       sizeof(struct share_mode_entry)*lck->num_share_modes);
668	offset = sizeof(*data) +
669		sizeof(struct share_mode_entry)*lck->num_share_modes;
670
671	/* Store any delete on close token. */
672	if (lck->delete_token) {
673		char *p = result.dptr + offset;
674
675		memcpy(p, &lck->delete_token->uid, sizeof(uid_t));
676		p += sizeof(uid_t);
677
678		memcpy(p, &lck->delete_token->gid, sizeof(gid_t));
679		p += sizeof(gid_t);
680
681		for (i = 0; i < lck->delete_token->ngroups; i++) {
682			memcpy(p, &lck->delete_token->groups[i], sizeof(gid_t));
683			p += sizeof(gid_t);
684		}
685		offset = p - result.dptr;
686	}
687
688	safe_strcpy(result.dptr + offset, lck->servicepath,
689		    result.dsize - offset - 1);
690	offset += sp_len + 1;
691	safe_strcpy(result.dptr + offset, lck->filename,
692		    result.dsize - offset - 1);
693
694	if (DEBUGLEVEL >= 10) {
695		print_share_mode_table(data);
696	}
697
698	return result;
699}
700
701static int share_mode_lock_destructor(struct share_mode_lock *lck)
702{
703	TDB_DATA key = locking_key(lck->dev, lck->ino);
704	TDB_DATA data;
705
706	if (!lck->modified) {
707		goto done;
708	}
709
710	data = unparse_share_modes(lck);
711
712	if (data.dptr == NULL) {
713		if (!lck->fresh) {
714			/* There has been an entry before, delete it */
715			if (tdb_delete(tdb, key) == -1) {
716				smb_panic("Could not delete share entry\n");
717			}
718		}
719		goto done;
720	}
721
722	if (tdb_store(tdb, key, data, TDB_REPLACE) == -1) {
723		smb_panic("Could not store share mode entry\n");
724	}
725
726 done:
727	tdb_chainunlock(tdb, key);
728
729	return 0;
730}
731
732struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
733						SMB_DEV_T dev, SMB_INO_T ino,
734						const char *servicepath,
735						const char *fname)
736{
737	struct share_mode_lock *lck;
738	TDB_DATA key = locking_key(dev, ino);
739	TDB_DATA data;
740
741	lck = TALLOC_P(mem_ctx, struct share_mode_lock);
742	if (lck == NULL) {
743		DEBUG(0, ("talloc failed\n"));
744		return NULL;
745	}
746
747	/* Ensure we set every field here as the destructor must be
748	   valid even if parse_share_modes fails. */
749
750	lck->servicepath = NULL;
751	lck->filename = NULL;
752	lck->dev = dev;
753	lck->ino = ino;
754	lck->num_share_modes = 0;
755	lck->share_modes = NULL;
756	lck->delete_token = NULL;
757	lck->delete_on_close = False;
758	lck->fresh = False;
759	lck->modified = False;
760
761	if (tdb_chainlock(tdb, key) != 0) {
762		DEBUG(3, ("Could not lock share entry\n"));
763		TALLOC_FREE(lck);
764		return NULL;
765	}
766
767	/* We must set the destructor immediately after the chainlock
768	   ensure the lock is cleaned up on any of the error return
769	   paths below. */
770
771	talloc_set_destructor(lck, share_mode_lock_destructor);
772
773	data = tdb_fetch(tdb, key);
774	lck->fresh = (data.dptr == NULL);
775
776	if (lck->fresh) {
777
778		if (fname == NULL || servicepath == NULL) {
779			TALLOC_FREE(lck);
780			return NULL;
781		}
782		lck->filename = talloc_strdup(lck, fname);
783		lck->servicepath = talloc_strdup(lck, servicepath);
784		if (lck->filename == NULL || lck->servicepath == NULL) {
785			DEBUG(0, ("talloc failed\n"));
786			TALLOC_FREE(lck);
787			return NULL;
788		}
789	} else {
790		if (!parse_share_modes(data, lck)) {
791			DEBUG(0, ("Could not parse share modes\n"));
792			TALLOC_FREE(lck);
793			SAFE_FREE(data.dptr);
794			return NULL;
795		}
796	}
797
798	SAFE_FREE(data.dptr);
799
800	return lck;
801}
802
803/*******************************************************************
804 Sets the service name and filename for rename.
805 At this point we emit "file renamed" messages to all
806 process id's that have this file open.
807 Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
808********************************************************************/
809
810BOOL rename_share_filename(struct share_mode_lock *lck,
811			const char *servicepath,
812			const char *newname)
813{
814	size_t sp_len;
815	size_t fn_len;
816	size_t msg_len;
817	char *frm = NULL;
818	int i;
819
820	if (!lck) {
821		return False;
822	}
823
824	DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
825		servicepath, newname));
826
827	/*
828	 * rename_internal_fsp() and rename_internals() add './' to
829	 * head of newname if newname does not contain a '/'.
830	 */
831	while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
832		newname += 2;
833	}
834
835	lck->servicepath = talloc_strdup(lck, servicepath);
836	lck->filename = talloc_strdup(lck, newname);
837	if (lck->filename == NULL || lck->servicepath == NULL) {
838		DEBUG(0, ("rename_share_filename: talloc failed\n"));
839		return False;
840	}
841	lck->modified = True;
842
843	sp_len = strlen(lck->servicepath);
844	fn_len = strlen(lck->filename);
845
846	msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1;
847
848	/* Set up the name changed message. */
849	frm = TALLOC_ARRAY(lck, char, msg_len);
850	if (!frm) {
851		return False;
852	}
853
854	SDEV_T_VAL(frm,0,lck->dev);
855	SINO_T_VAL(frm,8,lck->ino);
856
857	DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
858
859	safe_strcpy(&frm[16], lck->servicepath, sp_len);
860	safe_strcpy(&frm[16 + sp_len + 1], lck->filename, fn_len);
861
862	/* Send the messages. */
863	for (i=0; i<lck->num_share_modes; i++) {
864		struct share_mode_entry *se = &lck->share_modes[i];
865		if (!is_valid_share_mode_entry(se)) {
866			continue;
867		}
868		/* But not to ourselves... */
869		if (procid_is_me(&se->pid)) {
870			continue;
871		}
872
873		DEBUG(10,("rename_share_filename: sending rename message to pid %s "
874			"dev %x, inode  %.0f sharepath %s newname %s\n",
875			procid_str_static(&se->pid),
876			(unsigned int)lck->dev, (double)lck->ino,
877			lck->servicepath, lck->filename ));
878
879		message_send_pid(se->pid, MSG_SMB_FILE_RENAME,
880				frm, msg_len, True);
881	}
882
883	return True;
884}
885
886static int pull_delete_on_close_flag(TDB_DATA key, TDB_DATA dbuf,
887				     void *private_data)
888{
889	BOOL *result = (BOOL *)private_data;
890	struct locking_data *data;
891
892	if (dbuf.dsize < sizeof(struct locking_data)) {
893		smb_panic("PANIC: parse_share_modes: buffer too short.\n");
894	}
895
896	data = (struct locking_data *)dbuf.dptr;
897
898	*result = data->u.s.delete_on_close;
899	return 0;
900}
901
902BOOL get_delete_on_close_flag(SMB_DEV_T dev, SMB_INO_T inode)
903{
904	TDB_DATA key = locking_key(dev, inode);
905	BOOL result = False;
906
907	tdb_parse_record(tdb, key, pull_delete_on_close_flag,
908			 (void *)&result);
909	return result;
910}
911
912BOOL is_valid_share_mode_entry(const struct share_mode_entry *e)
913{
914	int num_props = 0;
915
916	num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
917	num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
918	num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
919
920	SMB_ASSERT(num_props <= 1);
921	return (num_props != 0);
922}
923
924BOOL is_deferred_open_entry(const struct share_mode_entry *e)
925{
926	return (e->op_type == DEFERRED_OPEN_ENTRY);
927}
928
929BOOL is_unused_share_mode_entry(const struct share_mode_entry *e)
930{
931	return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
932}
933
934/*******************************************************************
935 Fill a share mode entry.
936********************************************************************/
937
938static void fill_share_mode_entry(struct share_mode_entry *e,
939				  files_struct *fsp,
940				  uid_t uid, uint16 mid, uint16 op_type)
941{
942	ZERO_STRUCTP(e);
943	e->pid = procid_self();
944	e->share_access = fsp->share_access;
945	e->private_options = fsp->fh->private_options;
946	e->access_mask = fsp->access_mask;
947	e->op_mid = mid;
948	e->op_type = op_type;
949	e->time.tv_sec = fsp->open_time.tv_sec;
950	e->time.tv_usec = fsp->open_time.tv_usec;
951	e->dev = fsp->dev;
952	e->inode = fsp->inode;
953	e->share_file_id = fsp->fh->file_id;
954	e->uid = (uint32)uid;
955	e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
956}
957
958static void fill_deferred_open_entry(struct share_mode_entry *e,
959				     const struct timeval request_time,
960				     SMB_DEV_T dev, SMB_INO_T ino, uint16 mid)
961{
962	ZERO_STRUCTP(e);
963	e->pid = procid_self();
964	e->op_mid = mid;
965	e->op_type = DEFERRED_OPEN_ENTRY;
966	e->time.tv_sec = request_time.tv_sec;
967	e->time.tv_usec = request_time.tv_usec;
968	e->dev = dev;
969	e->inode = ino;
970	e->uid = (uint32)-1;
971	e->flags = 0;
972}
973
974static void add_share_mode_entry(struct share_mode_lock *lck,
975				 const struct share_mode_entry *entry)
976{
977	int i;
978
979	for (i=0; i<lck->num_share_modes; i++) {
980		struct share_mode_entry *e = &lck->share_modes[i];
981		if (is_unused_share_mode_entry(e)) {
982			*e = *entry;
983			break;
984		}
985	}
986
987	if (i == lck->num_share_modes) {
988		/* No unused entry found */
989		ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
990			     &lck->share_modes, &lck->num_share_modes);
991	}
992	lck->modified = True;
993}
994
995void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
996			uid_t uid, uint16 mid, uint16 op_type, BOOL initial_delete_on_close_allowed)
997{
998	struct share_mode_entry entry;
999	fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1000	if (initial_delete_on_close_allowed) {
1001		entry.flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1002	}
1003	add_share_mode_entry(lck, &entry);
1004}
1005
1006void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
1007		       struct timeval request_time,
1008		       SMB_DEV_T dev, SMB_INO_T ino)
1009{
1010	struct share_mode_entry entry;
1011	fill_deferred_open_entry(&entry, request_time, dev, ino, mid);
1012	add_share_mode_entry(lck, &entry);
1013}
1014
1015/*******************************************************************
1016 Check if two share mode entries are identical, ignoring oplock
1017 and mid info and desired_access. (Removed paranoia test - it's
1018 not automatically a logic error if they are identical. JRA.)
1019********************************************************************/
1020
1021static BOOL share_modes_identical(struct share_mode_entry *e1,
1022				  struct share_mode_entry *e2)
1023{
1024	/* We used to check for e1->share_access == e2->share_access here
1025	   as well as the other fields but 2 different DOS or FCB opens
1026	   sharing the same share mode entry may validly differ in
1027	   fsp->share_access field. */
1028
1029	return (procid_equal(&e1->pid, &e2->pid) &&
1030		e1->dev == e2->dev &&
1031		e1->inode == e2->inode &&
1032		e1->share_file_id == e2->share_file_id );
1033}
1034
1035static BOOL deferred_open_identical(struct share_mode_entry *e1,
1036				    struct share_mode_entry *e2)
1037{
1038	return (procid_equal(&e1->pid, &e2->pid) &&
1039		(e1->op_mid == e2->op_mid) &&
1040		(e1->dev == e2->dev) &&
1041		(e1->inode == e2->inode));
1042}
1043
1044static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1045						      struct share_mode_entry *entry)
1046{
1047	int i;
1048
1049	for (i=0; i<lck->num_share_modes; i++) {
1050		struct share_mode_entry *e = &lck->share_modes[i];
1051		if (is_valid_share_mode_entry(entry) &&
1052		    is_valid_share_mode_entry(e) &&
1053		    share_modes_identical(e, entry)) {
1054			return e;
1055		}
1056		if (is_deferred_open_entry(entry) &&
1057		    is_deferred_open_entry(e) &&
1058		    deferred_open_identical(e, entry)) {
1059			return e;
1060		}
1061	}
1062	return NULL;
1063}
1064
1065/*******************************************************************
1066 Del the share mode of a file for this process. Return the number of
1067 entries left.
1068********************************************************************/
1069
1070BOOL del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1071{
1072	struct share_mode_entry entry, *e;
1073
1074	/* Don't care about the pid owner being correct here - just a search. */
1075	fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1076
1077	e = find_share_mode_entry(lck, &entry);
1078	if (e == NULL) {
1079		return False;
1080	}
1081
1082	e->op_type = UNUSED_SHARE_MODE_ENTRY;
1083	lck->modified = True;
1084	return True;
1085}
1086
1087void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
1088{
1089	struct share_mode_entry entry, *e;
1090
1091	fill_deferred_open_entry(&entry, timeval_zero(),
1092				 lck->dev, lck->ino, mid);
1093
1094	e = find_share_mode_entry(lck, &entry);
1095	if (e == NULL) {
1096		return;
1097	}
1098
1099	e->op_type = UNUSED_SHARE_MODE_ENTRY;
1100	lck->modified = True;
1101}
1102
1103/*******************************************************************
1104 Remove an oplock mid and mode entry from a share mode.
1105********************************************************************/
1106
1107BOOL remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1108{
1109	struct share_mode_entry entry, *e;
1110
1111	/* Don't care about the pid owner being correct here - just a search. */
1112	fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1113
1114	e = find_share_mode_entry(lck, &entry);
1115	if (e == NULL) {
1116		return False;
1117	}
1118
1119	e->op_mid = 0;
1120	e->op_type = NO_OPLOCK;
1121	lck->modified = True;
1122	return True;
1123}
1124
1125/*******************************************************************
1126 Downgrade a oplock type from exclusive to level II.
1127********************************************************************/
1128
1129BOOL downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1130{
1131	struct share_mode_entry entry, *e;
1132
1133	/* Don't care about the pid owner being correct here - just a search. */
1134	fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1135
1136	e = find_share_mode_entry(lck, &entry);
1137	if (e == NULL) {
1138		return False;
1139	}
1140
1141	e->op_type = LEVEL_II_OPLOCK;
1142	lck->modified = True;
1143	return True;
1144}
1145
1146/****************************************************************************
1147 Deal with the internal needs of setting the delete on close flag. Note that
1148 as the tdb locking is recursive, it is safe to call this from within
1149 open_file_ntcreate. JRA.
1150****************************************************************************/
1151
1152NTSTATUS can_set_delete_on_close(files_struct *fsp, BOOL delete_on_close,
1153				 uint32 dosmode)
1154{
1155	if (!delete_on_close) {
1156		return NT_STATUS_OK;
1157	}
1158
1159	/*
1160	 * Only allow delete on close for writable files.
1161	 */
1162
1163	if ((dosmode & aRONLY) &&
1164	    !lp_delete_readonly(SNUM(fsp->conn))) {
1165		DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1166			  "flag set but file attribute is readonly.\n",
1167			  fsp->fsp_name ));
1168		return NT_STATUS_CANNOT_DELETE;
1169	}
1170
1171	/*
1172	 * Only allow delete on close for writable shares.
1173	 */
1174
1175	if (!CAN_WRITE(fsp->conn)) {
1176		DEBUG(10,("can_set_delete_on_close: file %s delete on "
1177			  "close flag set but write access denied on share.\n",
1178			  fsp->fsp_name ));
1179		return NT_STATUS_ACCESS_DENIED;
1180	}
1181
1182	/*
1183	 * Only allow delete on close for files/directories opened with delete
1184	 * intent.
1185	 */
1186
1187	if (!(fsp->access_mask & DELETE_ACCESS)) {
1188		DEBUG(10,("can_set_delete_on_close: file %s delete on "
1189			  "close flag set but delete access denied.\n",
1190			  fsp->fsp_name ));
1191		return NT_STATUS_ACCESS_DENIED;
1192	}
1193
1194	/* Don't allow delete on close for non-empty directories. */
1195	if (fsp->is_directory) {
1196		return can_delete_directory(fsp->conn, fsp->fsp_name);
1197	}
1198
1199	return NT_STATUS_OK;
1200}
1201
1202/****************************************************************************
1203 Do we have an open file handle that created this entry ?
1204****************************************************************************/
1205
1206BOOL can_set_initial_delete_on_close(const struct share_mode_lock *lck)
1207{
1208	int i;
1209
1210	for (i=0; i<lck->num_share_modes; i++) {
1211		if (lck->share_modes[i].flags & SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE) {
1212			return True;
1213		}
1214	}
1215	return False;
1216}
1217
1218/*************************************************************************
1219 Return a talloced copy of a UNIX_USER_TOKEN. NULL on fail.
1220 (Should this be in locking.c.... ?).
1221*************************************************************************/
1222
1223static UNIX_USER_TOKEN *copy_unix_token(TALLOC_CTX *ctx, UNIX_USER_TOKEN *tok)
1224{
1225	UNIX_USER_TOKEN *cpy;
1226
1227	if (tok == NULL) {
1228		return NULL;
1229	}
1230
1231	cpy = TALLOC_P(ctx, UNIX_USER_TOKEN);
1232	if (!cpy) {
1233		return NULL;
1234	}
1235
1236	cpy->uid = tok->uid;
1237	cpy->gid = tok->gid;
1238	cpy->ngroups = tok->ngroups;
1239	if (tok->ngroups) {
1240		/* Make this a talloc child of cpy. */
1241		cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1242		if (!cpy->groups) {
1243			return NULL;
1244		}
1245		memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1246	}
1247	return cpy;
1248}
1249
1250/****************************************************************************
1251 Replace the delete on close token.
1252****************************************************************************/
1253
1254void set_delete_on_close_token(struct share_mode_lock *lck, UNIX_USER_TOKEN *tok)
1255{
1256	/* Ensure there's no token. */
1257	if (lck->delete_token) {
1258		TALLOC_FREE(lck->delete_token); /* Also deletes groups... */
1259		lck->delete_token = NULL;
1260	}
1261
1262	/* Copy the new token (can be NULL). */
1263	lck->delete_token = copy_unix_token(lck, tok);
1264	lck->modified = True;
1265}
1266
1267/****************************************************************************
1268 Sets the delete on close flag over all share modes on this file.
1269 Modify the share mode entry for all files open
1270 on this device and inode to tell other smbds we have
1271 changed the delete on close flag. This will be noticed
1272 in the close code, the last closer will delete the file
1273 if flag is set.
1274 This makes a copy of any UNIX_USER_TOKEN into the
1275 lck entry. This function is used when the lock is already granted.
1276****************************************************************************/
1277
1278void set_delete_on_close_lck(struct share_mode_lock *lck, BOOL delete_on_close, UNIX_USER_TOKEN *tok)
1279{
1280	if (lck->delete_on_close != delete_on_close) {
1281		set_delete_on_close_token(lck, tok);
1282		lck->delete_on_close = delete_on_close;
1283		if (delete_on_close) {
1284			SMB_ASSERT(lck->delete_token != NULL);
1285		}
1286		lck->modified = True;
1287	}
1288}
1289
1290BOOL set_delete_on_close(files_struct *fsp, BOOL delete_on_close, UNIX_USER_TOKEN *tok)
1291{
1292	struct share_mode_lock *lck;
1293
1294	DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1295		  "fnum = %d, file %s\n",
1296		  delete_on_close ? "Adding" : "Removing", fsp->fnum,
1297		  fsp->fsp_name ));
1298
1299	if (fsp->is_stat) {
1300		return True;
1301	}
1302
1303	lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode, NULL, NULL);
1304	if (lck == NULL) {
1305		return False;
1306	}
1307
1308	set_delete_on_close_lck(lck, delete_on_close, tok);
1309
1310	if (fsp->is_directory) {
1311		send_stat_cache_delete_message(fsp->fsp_name);
1312	}
1313
1314	TALLOC_FREE(lck);
1315	return True;
1316}
1317
1318/****************************************************************************
1319 Sets the allow initial delete on close flag for this share mode.
1320****************************************************************************/
1321
1322BOOL set_allow_initial_delete_on_close(struct share_mode_lock *lck, files_struct *fsp, BOOL delete_on_close)
1323{
1324	struct share_mode_entry entry, *e;
1325
1326	/* Don't care about the pid owner being correct here - just a search. */
1327	fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1328
1329	e = find_share_mode_entry(lck, &entry);
1330	if (e == NULL) {
1331		return False;
1332	}
1333
1334	if (delete_on_close) {
1335		e->flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1336	} else {
1337		e->flags &= ~SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1338	}
1339	lck->modified = True;
1340	return True;
1341}
1342
1343struct forall_state {
1344	void (*fn)(const struct share_mode_entry *entry,
1345		   const char *sharepath,
1346		   const char *fname,
1347		   void *private_data);
1348	void *private_data;
1349};
1350
1351static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf,
1352                       void *_state)
1353{
1354	struct forall_state *state = (struct forall_state *)_state;
1355	struct locking_data *data;
1356	struct share_mode_entry *shares;
1357	const char *sharepath;
1358	const char *fname;
1359	int i;
1360
1361	/* Ensure this is a locking_key record. */
1362	if (kbuf.dsize != sizeof(struct locking_key))
1363		return 0;
1364
1365	data = (struct locking_data *)dbuf.dptr;
1366	shares = (struct share_mode_entry *)(dbuf.dptr + sizeof(*data));
1367	sharepath = dbuf.dptr + sizeof(*data) +
1368		data->u.s.num_share_mode_entries*sizeof(*shares) +
1369		data->u.s.delete_token_size;
1370	fname = dbuf.dptr + sizeof(*data) +
1371		data->u.s.num_share_mode_entries*sizeof(*shares) +
1372		data->u.s.delete_token_size +
1373		strlen(sharepath) + 1;
1374
1375	for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1376		state->fn(&shares[i], sharepath, fname,
1377			  state->private_data);
1378	}
1379	return 0;
1380}
1381
1382/*******************************************************************
1383 Call the specified function on each entry under management by the
1384 share mode system.
1385********************************************************************/
1386
1387int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1388				 const char *, void *),
1389		      void *private_data)
1390{
1391	struct forall_state state;
1392
1393	if (tdb == NULL)
1394		return 0;
1395
1396	state.fn = fn;
1397	state.private_data = private_data;
1398
1399	return tdb_traverse(tdb, traverse_fn, (void *)&state);
1400}
1401