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