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