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