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