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