r13293: Rather a big patch I'm afraid, but this should fix bug #3347
[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
562         result.dptr = NULL;
563         result.dsize = 0;
564
565         for (i=0; i<lck->num_share_modes; i++) {
566                 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
567                         num_valid += 1;
568                 }
569         }
570
571         if (num_valid == 0) {
572                 return result;
573         }
574
575         sp_len = strlen(lck->servicepath);
576
577         result.dsize = sizeof(*data) +
578                 lck->num_share_modes * sizeof(struct share_mode_entry) +
579                 (lck->delete_token ? (8 + (lck->delete_token->ngroups*4)) : 0) +
580                 sp_len + 1 +
581                 strlen(lck->filename) + 1;
582         result.dptr = talloc_size(lck, result.dsize);
583
584         if (result.dptr == NULL) {
585                 smb_panic("talloc failed\n");
586         }
587
588         data = (struct locking_data *)result.dptr;
589         ZERO_STRUCTP(data);
590         data->u.s.num_share_mode_entries = lck->num_share_modes;
591         data->u.s.delete_on_close = lck->delete_on_close;
592         data->u.s.initial_delete_on_close = lck->initial_delete_on_close;
593         DEBUG(10, ("unparse_share_modes: del: %d, initial del %d, num: %d\n",
594                    data->u.s.delete_on_close,
595                    data->u.s.initial_delete_on_close,
596                    data->u.s.num_share_mode_entries));
597         memcpy(result.dptr + sizeof(*data), lck->share_modes,
598                sizeof(struct share_mode_entry)*lck->num_share_modes);
599         offset = sizeof(*data) +
600                 sizeof(struct share_mode_entry)*lck->num_share_modes;
601
602         /* Store any delete on close token. */
603         if (lck->delete_token) {
604                 uint32 val;
605                 uint32 *p = (uint32 *)(result.dptr + offset);
606
607                 val = (uint32)lck->delete_token->uid;
608                 memcpy(p++, &val, 4);
609
610                 val = (uint32)lck->delete_token->uid;
611                 memcpy(p++, &val, 4);
612
613                 for (i = 0; i < lck->delete_token->ngroups; i++) {
614                         val = (uint32)lck->delete_token->groups[i];
615                         memcpy(p++, &val, 4);
616                 }
617                 offset = ((char *)p - result.dptr);
618         }
619
620         safe_strcpy(result.dptr + offset, lck->servicepath,
621                     result.dsize - offset - 1);
622         offset += sp_len + 1;
623         safe_strcpy(result.dptr + offset, lck->filename,
624                     result.dsize - offset - 1);
625
626         if (DEBUGLEVEL >= 10) {
627                 print_share_mode_table(data);
628         }
629
630         return result;
631 }
632
633 static int share_mode_lock_destructor(void *p)
634 {
635         struct share_mode_lock *lck =
636                 talloc_get_type_abort(p, struct share_mode_lock);
637         TDB_DATA key = locking_key(lck->dev, lck->ino);
638         TDB_DATA data;
639
640         if (!lck->modified) {
641                 goto done;
642         }
643
644         data = unparse_share_modes(lck);
645
646         if (data.dptr == NULL) {
647                 if (!lck->fresh) {
648                         /* There has been an entry before, delete it */
649                         if (tdb_delete(tdb, key) == -1) {
650                                 smb_panic("Could not delete share entry\n");
651                         }
652                 }
653                 goto done;
654         }
655
656         if (tdb_store(tdb, key, data, TDB_REPLACE) == -1) {
657                 smb_panic("Could not store share mode entry\n");
658         }
659
660  done:
661         tdb_chainunlock(tdb, key);
662
663         return 0;
664 }
665
666 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
667                                                 SMB_DEV_T dev, SMB_INO_T ino,
668                                                 const char *servicepath,
669                                                 const char *fname)
670 {
671         struct share_mode_lock *lck;
672         TDB_DATA key = locking_key(dev, ino);
673         TDB_DATA data;
674
675         lck = TALLOC_P(mem_ctx, struct share_mode_lock);
676         if (lck == NULL) {
677                 DEBUG(0, ("talloc failed\n"));
678                 return NULL;
679         }
680
681         /* Ensure we set every field here as the destructor must be
682            valid even if parse_share_modes fails. */
683
684         lck->servicepath = NULL;
685         lck->filename = NULL;
686         lck->dev = dev;
687         lck->ino = ino;
688         lck->num_share_modes = 0;
689         lck->share_modes = NULL;
690         lck->delete_token = NULL;
691         lck->delete_on_close = False;
692         lck->initial_delete_on_close = False;
693         lck->fresh = False;
694         lck->modified = False;
695
696         if (tdb_chainlock(tdb, key) != 0) {
697                 DEBUG(3, ("Could not lock share entry\n"));
698                 talloc_free(lck);
699                 return NULL;
700         }
701
702         /* We must set the destructor immediately after the chainlock
703            ensure the lock is cleaned up on any of the error return
704            paths below. */
705
706         talloc_set_destructor(lck, share_mode_lock_destructor);
707
708         data = tdb_fetch(tdb, key);
709         lck->fresh = (data.dptr == NULL);
710
711         if (lck->fresh) {
712
713                 if (fname == NULL || servicepath == NULL) {
714                         talloc_free(lck);
715                         return NULL;
716                 }
717                 lck->filename = talloc_strdup(lck, fname);
718                 lck->servicepath = talloc_strdup(lck, servicepath);
719                 if (lck->filename == NULL || lck->servicepath == NULL) {
720                         DEBUG(0, ("talloc failed\n"));
721                         talloc_free(lck);
722                         return NULL;
723                 }
724         } else {
725                 if (!parse_share_modes(data, lck)) {
726                         DEBUG(0, ("Could not parse share modes\n"));
727                         talloc_free(lck);
728                         SAFE_FREE(data.dptr);
729                         return NULL;
730                 }
731         }
732
733         SAFE_FREE(data.dptr);
734
735         return lck;
736 }
737
738 /*******************************************************************
739  Sets the service name and filename for rename.
740  At this point we emit "file renamed" messages to all
741  process id's that have this file open.
742  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
743 ********************************************************************/
744
745 BOOL rename_share_filename(struct share_mode_lock *lck,
746                         const char *servicepath,
747                         const char *newname)
748 {
749         size_t sp_len;
750         size_t fn_len;
751         size_t msg_len;
752         char *frm = NULL;
753         int i;
754
755         if (!lck) {
756                 return False;
757         }
758
759         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
760                 servicepath, newname));
761
762         /*
763          * rename_internal_fsp() and rename_internals() add './' to
764          * head of newname if newname does not contain a '/'.
765          */
766         while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
767                 newname += 2;
768         }
769
770         lck->servicepath = talloc_strdup(lck, servicepath);
771         lck->filename = talloc_strdup(lck, newname);
772         if (lck->filename == NULL || lck->servicepath == NULL) {
773                 DEBUG(0, ("rename_share_filename: talloc failed\n"));
774                 return False;
775         }
776         lck->modified = True;
777
778         sp_len = strlen(lck->servicepath);
779         fn_len = strlen(lck->filename);
780
781         msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1;
782
783         /* Set up the name changed message. */
784         frm = TALLOC(lck, msg_len);
785         if (!frm) {
786                 return False;
787         }
788
789         SDEV_T_VAL(frm,0,lck->dev);
790         SINO_T_VAL(frm,8,lck->ino);
791
792         DEBUG(10,("rename_share_filename: msg_len = %d\n", msg_len ));
793
794         safe_strcpy(&frm[16], lck->servicepath, sp_len);
795         safe_strcpy(&frm[16 + sp_len + 1], lck->filename, fn_len);
796
797         /* Send the messages. */
798         for (i=0; i<lck->num_share_modes; i++) {
799                 struct share_mode_entry *se = &lck->share_modes[i];
800                 if (!is_valid_share_mode_entry(se)) {
801                         continue;
802                 }
803                 /* But not to ourselves... */
804                 if (procid_is_me(&se->pid)) {
805                         continue;
806                 }
807
808                 DEBUG(10,("rename_share_filename: sending rename message to pid %u "
809                         "dev %x, inode  %.0f sharepath %s newname %s\n",
810                         (unsigned int)procid_to_pid(&se->pid),
811                         (unsigned int)lck->dev, (double)lck->ino,
812                         lck->servicepath, lck->filename ));
813
814                 become_root();
815                 message_send_pid(se->pid, MSG_SMB_FILE_RENAME,
816                                 frm, msg_len, True);
817                 unbecome_root();
818         }
819
820         return True;
821 }
822
823 BOOL get_delete_on_close_flag(SMB_DEV_T dev, SMB_INO_T inode)
824 {
825         BOOL result;
826         struct share_mode_lock *lck = get_share_mode_lock(NULL, dev, inode, NULL, NULL);
827         if (!lck) {
828                 return False;
829         }
830         result = lck->delete_on_close;
831         talloc_free(lck);
832         return result;
833 }
834
835 BOOL is_valid_share_mode_entry(const struct share_mode_entry *e)
836 {
837         int num_props = 0;
838
839         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
840         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
841         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
842
843         SMB_ASSERT(num_props <= 1);
844         return (num_props != 0);
845 }
846
847 BOOL is_deferred_open_entry(const struct share_mode_entry *e)
848 {
849         return (e->op_type == DEFERRED_OPEN_ENTRY);
850 }
851
852 BOOL is_unused_share_mode_entry(const struct share_mode_entry *e)
853 {
854         return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
855 }
856
857 /*******************************************************************
858  Fill a share mode entry.
859 ********************************************************************/
860
861 static void fill_share_mode_entry(struct share_mode_entry *e,
862                                   files_struct *fsp,
863                                   uint16 mid, uint16 op_type)
864 {
865         ZERO_STRUCTP(e);
866         e->pid = procid_self();
867         e->share_access = fsp->share_access;
868         e->private_options = fsp->fh->private_options;
869         e->access_mask = fsp->access_mask;
870         e->op_mid = mid;
871         e->op_type = op_type;
872         e->time.tv_sec = fsp->open_time.tv_sec;
873         e->time.tv_usec = fsp->open_time.tv_usec;
874         e->share_file_id = fsp->file_id;
875         e->dev = fsp->dev;
876         e->inode = fsp->inode;
877 }
878
879 static void fill_deferred_open_entry(struct share_mode_entry *e,
880                                      const struct timeval request_time,
881                                      SMB_DEV_T dev, SMB_INO_T ino, uint16 mid)
882 {
883         ZERO_STRUCTP(e);
884         e->pid = procid_self();
885         e->op_mid = mid;
886         e->op_type = DEFERRED_OPEN_ENTRY;
887         e->time.tv_sec = request_time.tv_sec;
888         e->time.tv_usec = request_time.tv_usec;
889         e->dev = dev;
890         e->inode = ino;
891 }
892
893 static void add_share_mode_entry(struct share_mode_lock *lck,
894                                  const struct share_mode_entry *entry)
895 {
896         int i;
897
898         for (i=0; i<lck->num_share_modes; i++) {
899                 struct share_mode_entry *e = &lck->share_modes[i];
900                 if (is_unused_share_mode_entry(e)) {
901                         *e = *entry;
902                         break;
903                 }
904         }
905
906         if (i == lck->num_share_modes) {
907                 /* No unused entry found */
908                 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
909                              &lck->share_modes, &lck->num_share_modes);
910         }
911         lck->modified = True;
912 }
913
914 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
915                     uint16 mid, uint16 op_type)
916 {
917         struct share_mode_entry entry;
918         fill_share_mode_entry(&entry, fsp, mid, op_type);
919         add_share_mode_entry(lck, &entry);
920 }
921
922 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
923                        struct timeval request_time,
924                        SMB_DEV_T dev, SMB_INO_T ino)
925 {
926         struct share_mode_entry entry;
927         fill_deferred_open_entry(&entry, request_time, dev, ino, mid);
928         add_share_mode_entry(lck, &entry);
929 }
930
931 /*******************************************************************
932  Check if two share mode entries are identical, ignoring oplock 
933  and mid info and desired_access.
934 ********************************************************************/
935
936 static BOOL share_modes_identical(struct share_mode_entry *e1,
937                                   struct share_mode_entry *e2)
938 {
939 #if 1 /* JRA PARANOIA TEST - REMOVE LATER */
940         if (procid_equal(&e1->pid, &e2->pid) &&
941             e1->share_file_id == e2->share_file_id &&
942             e1->dev == e2->dev &&
943             e1->inode == e2->inode &&
944             (e1->share_access) != (e2->share_access)) {
945                 DEBUG(0,("PANIC: share_modes_identical: share_mode "
946                          "mismatch (e1 = 0x%x, e2 = 0x%x). Logic error.\n",
947                          (unsigned int)e1->share_access,
948                          (unsigned int)e2->share_access ));
949                 smb_panic("PANIC: share_modes_identical logic error.\n");
950         }
951 #endif
952
953         return (procid_equal(&e1->pid, &e2->pid) &&
954                 (e1->share_access) == (e2->share_access) &&
955                 e1->dev == e2->dev &&
956                 e1->inode == e2->inode &&
957                 e1->share_file_id == e2->share_file_id );
958 }
959
960 static BOOL deferred_open_identical(struct share_mode_entry *e1,
961                                     struct share_mode_entry *e2)
962 {
963         return (procid_equal(&e1->pid, &e2->pid) &&
964                 (e1->op_mid == e2->op_mid) &&
965                 (e1->dev == e2->dev) &&
966                 (e1->inode == e2->inode));
967 }
968
969 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
970                                                       struct share_mode_entry *entry)
971 {
972         int i;
973
974         for (i=0; i<lck->num_share_modes; i++) {
975                 struct share_mode_entry *e = &lck->share_modes[i];
976                 if (is_valid_share_mode_entry(entry) &&
977                     is_valid_share_mode_entry(e) &&
978                     share_modes_identical(e, entry)) {
979                         return e;
980                 }
981                 if (is_deferred_open_entry(entry) &&
982                     is_deferred_open_entry(e) &&
983                     deferred_open_identical(e, entry)) {
984                         return e;
985                 }
986         }
987         return NULL;
988 }
989
990 /*******************************************************************
991  Del the share mode of a file for this process. Return the number of
992  entries left.
993 ********************************************************************/
994
995 BOOL del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
996 {
997         struct share_mode_entry entry, *e;
998
999         fill_share_mode_entry(&entry, fsp, 0, 0);
1000
1001         e = find_share_mode_entry(lck, &entry);
1002         if (e == NULL) {
1003                 return False;
1004         }
1005
1006         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1007         lck->modified = True;
1008         return True;
1009 }
1010
1011 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
1012 {
1013         struct share_mode_entry entry, *e;
1014
1015         fill_deferred_open_entry(&entry, timeval_zero(),
1016                                  lck->dev, lck->ino, mid);
1017
1018         e = find_share_mode_entry(lck, &entry);
1019         if (e == NULL) {
1020                 return;
1021         }
1022
1023         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1024         lck->modified = True;
1025 }
1026
1027 /*******************************************************************
1028  Remove an oplock mid and mode entry from a share mode.
1029 ********************************************************************/
1030
1031 BOOL remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1032 {
1033         struct share_mode_entry entry, *e;
1034
1035         fill_share_mode_entry(&entry, fsp, 0, 0);
1036
1037         e = find_share_mode_entry(lck, &entry);
1038         if (e == NULL) {
1039                 return False;
1040         }
1041
1042         e->op_mid = 0;
1043         e->op_type = NO_OPLOCK;
1044         lck->modified = True;
1045         return True;
1046 }
1047
1048 /*******************************************************************
1049  Downgrade a oplock type from exclusive to level II.
1050 ********************************************************************/
1051
1052 BOOL downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1053 {
1054         struct share_mode_entry entry, *e;
1055
1056         fill_share_mode_entry(&entry, fsp, 0, 0);
1057
1058         e = find_share_mode_entry(lck, &entry);
1059         if (e == NULL) {
1060                 return False;
1061         }
1062
1063         e->op_type = LEVEL_II_OPLOCK;
1064         lck->modified = True;
1065         return True;
1066 }
1067
1068 /****************************************************************************
1069  Deal with the internal needs of setting the delete on close flag. Note that
1070  as the tdb locking is recursive, it is safe to call this from within 
1071  open_file_shared. JRA.
1072 ****************************************************************************/
1073
1074 NTSTATUS can_set_delete_on_close(files_struct *fsp, BOOL delete_on_close,
1075                                  uint32 dosmode)
1076 {
1077         if (!delete_on_close) {
1078                 return NT_STATUS_OK;
1079         }
1080
1081         /*
1082          * Only allow delete on close for writable files.
1083          */
1084
1085         if ((dosmode & aRONLY) &&
1086             !lp_delete_readonly(SNUM(fsp->conn))) {
1087                 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1088                           "flag set but file attribute is readonly.\n",
1089                           fsp->fsp_name ));
1090                 return NT_STATUS_CANNOT_DELETE;
1091         }
1092
1093         /*
1094          * Only allow delete on close for writable shares.
1095          */
1096
1097         if (!CAN_WRITE(fsp->conn)) {
1098                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1099                           "close flag set but write access denied on share.\n",
1100                           fsp->fsp_name ));
1101                 return NT_STATUS_ACCESS_DENIED;
1102         }
1103
1104         /*
1105          * Only allow delete on close for files/directories opened with delete
1106          * intent.
1107          */
1108
1109         if (!(fsp->access_mask & DELETE_ACCESS)) {
1110                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1111                           "close flag set but delete access denied.\n",
1112                           fsp->fsp_name ));
1113                 return NT_STATUS_ACCESS_DENIED;
1114         }
1115
1116         return NT_STATUS_OK;
1117 }
1118
1119 /*************************************************************************
1120  Return a talloced copy of a UNIX_USER_TOKEN. NULL on fail.
1121  (Should this be in locking.c.... ?).
1122 *************************************************************************/
1123
1124 static UNIX_USER_TOKEN *copy_unix_token(TALLOC_CTX *ctx, UNIX_USER_TOKEN *tok)
1125 {
1126         UNIX_USER_TOKEN *cpy;
1127
1128         if (tok == NULL) {
1129                 return NULL;
1130         }
1131
1132         cpy = TALLOC_P(ctx, UNIX_USER_TOKEN);
1133         if (!cpy) {
1134                 return NULL;
1135         }
1136
1137         cpy->uid = tok->uid;
1138         cpy->gid = tok->gid;
1139         cpy->ngroups = tok->ngroups;
1140         if (tok->ngroups) {
1141                 /* Make this a talloc child of cpy. */
1142                 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1143                 if (!cpy->groups) {
1144                         return NULL;
1145                 }
1146                 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1147         }
1148         return cpy;
1149 }
1150
1151 /****************************************************************************
1152  Replace the delete on close token.
1153 ****************************************************************************/
1154
1155 void set_delete_on_close_token(struct share_mode_lock *lck, UNIX_USER_TOKEN *tok)
1156 {
1157         /* Ensure there's no token. */
1158         if (lck->delete_token) {
1159                 talloc_free(lck->delete_token); /* Also deletes groups... */
1160                 lck->delete_token = NULL;
1161         }
1162
1163         /* Copy the new token (can be NULL). */
1164         lck->delete_token = copy_unix_token(lck, tok);
1165         lck->modified = True;
1166 }
1167
1168 /****************************************************************************
1169  Sets the delete on close flag over all share modes on this file.
1170  Modify the share mode entry for all files open
1171  on this device and inode to tell other smbds we have
1172  changed the delete on close flag. This will be noticed
1173  in the close code, the last closer will delete the file
1174  if flag is set.
1175  Note that setting this to any value clears the initial_delete_on_close flag.
1176  If delete_on_close is True this makes a copy of any UNIX_USER_TOKEN into the
1177  lck entry.
1178 ****************************************************************************/
1179
1180 BOOL set_delete_on_close(files_struct *fsp, BOOL delete_on_close, UNIX_USER_TOKEN *tok)
1181 {
1182         struct share_mode_lock *lck;
1183         
1184         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1185                   "fnum = %d, file %s\n",
1186                   delete_on_close ? "Adding" : "Removing", fsp->fnum,
1187                   fsp->fsp_name ));
1188
1189         if (fsp->is_stat) {
1190                 return True;
1191         }
1192
1193         lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode, NULL, NULL);
1194         if (lck == NULL) {
1195                 return False;
1196         }
1197
1198         if (lck->delete_on_close != delete_on_close) {
1199                 set_delete_on_close_token(lck, tok);
1200                 lck->delete_on_close = delete_on_close;
1201                 if (delete_on_close) {
1202                         SMB_ASSERT(lck->delete_token != NULL);
1203                 }
1204                 lck->modified = True;
1205         }
1206
1207         if (lck->initial_delete_on_close) {
1208                 lck->initial_delete_on_close = False;
1209                 lck->modified = True;
1210         }
1211
1212         talloc_free(lck);
1213         return True;
1214 }
1215
1216 static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, 
1217                        void *state)
1218 {
1219         struct locking_data *data;
1220         struct share_mode_entry *shares;
1221         const char *sharepath;
1222         const char *fname;
1223         int i;
1224         void (*traverse_callback)(struct share_mode_entry *, const char *, const char *) = state;
1225
1226         /* Ensure this is a locking_key record. */
1227         if (kbuf.dsize != sizeof(struct locking_key))
1228                 return 0;
1229
1230         data = (struct locking_data *)dbuf.dptr;
1231         shares = (struct share_mode_entry *)(dbuf.dptr + sizeof(*data));
1232         sharepath = dbuf.dptr + sizeof(*data) +
1233                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1234                 data->u.s.delete_token_size;
1235         fname = dbuf.dptr + sizeof(*data) +
1236                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1237                 data->u.s.delete_token_size +
1238                 strlen(sharepath) + 1;
1239
1240         for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1241                 traverse_callback(&shares[i], sharepath, fname);
1242         }
1243         return 0;
1244 }
1245
1246 /*******************************************************************
1247  Call the specified function on each entry under management by the
1248  share mode system.
1249 ********************************************************************/
1250
1251 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *, const char *))
1252 {
1253         if (tdb == NULL)
1254                 return 0;
1255         return tdb_traverse(tdb, traverse_fn, fn);
1256 }