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