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