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