r23222: share_mode_forall() is only for counting and status display stuff, so
[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 struct db_context *lock_db;
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 (lock_db)
380                 return True;
381
382         lock_db = db_open(NULL, lock_path("locking.tdb"),
383                           lp_open_files_db_hash_size(),
384                           TDB_DEFAULT
385                           |TDB_VOLATILE
386                           |(read_only?0x0:TDB_CLEAR_IF_FIRST),
387                           read_only?O_RDONLY:O_RDWR|O_CREAT, 0644);
388
389         if (!lock_db) {
390                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
391                 return False;
392         }
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         brl_shutdown(open_read_only);
409         if (lock_db) {
410                 TALLOC_FREE(lock_db);
411         }
412         return True;
413 }
414
415 /*******************************************************************
416  Form a static locking key for a dev/inode pair.
417 ******************************************************************/
418
419 static TDB_DATA locking_key(struct file_id id)
420 {
421         static struct file_id key;      
422         TDB_DATA kbuf;
423         key = id;
424         kbuf.dptr = (uint8 *)&key;
425         kbuf.dsize = sizeof(key);
426         return kbuf;
427 }
428
429 /*******************************************************************
430  Print out a share mode.
431 ********************************************************************/
432
433 char *share_mode_str(int num, struct share_mode_entry *e)
434 {
435         static pstring share_str;
436
437         slprintf(share_str, sizeof(share_str)-1, "share_mode_entry[%d]: %s "
438                  "pid = %s, share_access = 0x%x, private_options = 0x%x, "
439                  "access_mask = 0x%x, mid = 0x%x, type= 0x%x, gen_id = %lu, "
440                  "uid = %u, flags = %u, file_id %s",
441                  num,
442                  e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
443                  procid_str_static(&e->pid),
444                  e->share_access, e->private_options,
445                  e->access_mask, e->op_mid, e->op_type, e->share_file_id,
446                  (unsigned int)e->uid, (unsigned int)e->flags,
447                  file_id_static_string(&e->id));
448
449         return share_str;
450 }
451
452 /*******************************************************************
453  Print out a share mode table.
454 ********************************************************************/
455
456 static void print_share_mode_table(struct locking_data *data)
457 {
458         int num_share_modes = data->u.s.num_share_mode_entries;
459         struct share_mode_entry *shares =
460                 (struct share_mode_entry *)(data + 1);
461         int i;
462
463         for (i = 0; i < num_share_modes; i++) {
464                 struct share_mode_entry entry;
465
466                 memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
467                 DEBUG(10,("print_share_mode_table: %s\n",
468                           share_mode_str(i, &entry)));
469         }
470 }
471
472 /*******************************************************************
473  Get all share mode entries for a dev/inode pair.
474 ********************************************************************/
475
476 static BOOL parse_share_modes(TDB_DATA dbuf, struct share_mode_lock *lck)
477 {
478         struct locking_data *data;
479         int i;
480
481         if (dbuf.dsize < sizeof(struct locking_data)) {
482                 smb_panic("PANIC: parse_share_modes: buffer too short.\n");
483         }
484
485         data = (struct locking_data *)dbuf.dptr;
486
487         lck->delete_on_close = data->u.s.delete_on_close;
488         lck->num_share_modes = data->u.s.num_share_mode_entries;
489
490         DEBUG(10, ("parse_share_modes: delete_on_close: %d, "
491                    "num_share_modes: %d\n",
492                 lck->delete_on_close,
493                 lck->num_share_modes));
494
495         if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
496                 DEBUG(0, ("invalid number of share modes: %d\n",
497                           lck->num_share_modes));
498                 smb_panic("PANIC: invalid number of share modes");
499         }
500
501         lck->share_modes = NULL;
502         
503         if (lck->num_share_modes != 0) {
504
505                 if (dbuf.dsize < (sizeof(struct locking_data) +
506                                   (lck->num_share_modes *
507                                    sizeof(struct share_mode_entry)))) {
508                         smb_panic("PANIC: parse_share_modes: buffer too short.\n");
509                 }
510                                   
511                 lck->share_modes = (struct share_mode_entry *)
512                         TALLOC_MEMDUP(lck, dbuf.dptr+sizeof(*data),
513                                       lck->num_share_modes *
514                                       sizeof(struct share_mode_entry));
515
516                 if (lck->share_modes == NULL) {
517                         smb_panic("talloc failed\n");
518                 }
519         }
520
521         /* Get any delete token. */
522         if (data->u.s.delete_token_size) {
523                 uint8 *p = dbuf.dptr + sizeof(*data) +
524                                 (lck->num_share_modes *
525                                 sizeof(struct share_mode_entry));
526
527                 if ((data->u.s.delete_token_size < sizeof(uid_t) + sizeof(gid_t)) ||
528                                 ((data->u.s.delete_token_size - sizeof(uid_t)) % sizeof(gid_t)) != 0) {
529                         DEBUG(0, ("parse_share_modes: invalid token size %d\n",
530                                 data->u.s.delete_token_size));
531                         smb_panic("parse_share_modes: invalid token size\n");
532                 }
533
534                 lck->delete_token = TALLOC_P(lck, UNIX_USER_TOKEN);
535                 if (!lck->delete_token) {
536                         smb_panic("talloc failed\n");
537                 }
538
539                 /* Copy out the uid and gid. */
540                 memcpy(&lck->delete_token->uid, p, sizeof(uid_t));
541                 p += sizeof(uid_t);
542                 memcpy(&lck->delete_token->gid, p, sizeof(gid_t));
543                 p += sizeof(gid_t);
544
545                 /* Any supplementary groups ? */
546                 lck->delete_token->ngroups = (data->u.s.delete_token_size > (sizeof(uid_t) + sizeof(gid_t))) ?
547                                         ((data->u.s.delete_token_size -
548                                                 (sizeof(uid_t) + sizeof(gid_t)))/sizeof(gid_t)) : 0;
549
550                 if (lck->delete_token->ngroups) {
551                         /* Make this a talloc child of lck->delete_token. */
552                         lck->delete_token->groups = TALLOC_ARRAY(lck->delete_token, gid_t,
553                                                         lck->delete_token->ngroups);
554                         if (!lck->delete_token) {
555                                 smb_panic("talloc failed\n");
556                         }
557
558                         for (i = 0; i < lck->delete_token->ngroups; i++) {
559                                 memcpy(&lck->delete_token->groups[i], p, sizeof(gid_t));
560                                 p += sizeof(gid_t);
561                         }
562                 }
563
564         } else {
565                 lck->delete_token = NULL;
566         }
567
568         /* Save off the associated service path and filename. */
569         lck->servicepath = talloc_strdup(lck, (const char *)dbuf.dptr + sizeof(*data) +
570                                         (lck->num_share_modes *
571                                         sizeof(struct share_mode_entry)) +
572                                         data->u.s.delete_token_size );
573         if (lck->servicepath == NULL) {
574                 smb_panic("talloc_strdup failed\n");
575         }
576
577         lck->filename = talloc_strdup(lck, (const char *)dbuf.dptr + sizeof(*data) +
578                                         (lck->num_share_modes *
579                                         sizeof(struct share_mode_entry)) +
580                                         data->u.s.delete_token_size +
581                                         strlen(lck->servicepath) + 1 );
582         if (lck->filename == NULL) {
583                 smb_panic("talloc_strdup failed\n");
584         }
585
586         /*
587          * Ensure that each entry has a real process attached.
588          */
589
590         for (i = 0; i < lck->num_share_modes; i++) {
591                 struct share_mode_entry *entry_p = &lck->share_modes[i];
592                 DEBUG(10,("parse_share_modes: %s\n",
593                           share_mode_str(i, entry_p) ));
594                 if (!process_exists(entry_p->pid)) {
595                         DEBUG(10,("parse_share_modes: deleted %s\n",
596                                   share_mode_str(i, entry_p) ));
597                         entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
598                         lck->modified = True;
599                 }
600         }
601
602         return True;
603 }
604
605 static TDB_DATA unparse_share_modes(struct share_mode_lock *lck)
606 {
607         TDB_DATA result;
608         int num_valid = 0;
609         int i;
610         struct locking_data *data;
611         ssize_t offset;
612         ssize_t sp_len;
613         uint32 delete_token_size;
614
615         result.dptr = NULL;
616         result.dsize = 0;
617
618         for (i=0; i<lck->num_share_modes; i++) {
619                 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
620                         num_valid += 1;
621                 }
622         }
623
624         if (num_valid == 0) {
625                 return result;
626         }
627
628         sp_len = strlen(lck->servicepath);
629         delete_token_size = (lck->delete_token ?
630                         (sizeof(uid_t) + sizeof(gid_t) + (lck->delete_token->ngroups*sizeof(gid_t))) : 0);
631
632         result.dsize = sizeof(*data) +
633                 lck->num_share_modes * sizeof(struct share_mode_entry) +
634                 delete_token_size +
635                 sp_len + 1 +
636                 strlen(lck->filename) + 1;
637         result.dptr = TALLOC_ARRAY(lck, uint8, result.dsize);
638
639         if (result.dptr == NULL) {
640                 smb_panic("talloc failed\n");
641         }
642
643         data = (struct locking_data *)result.dptr;
644         ZERO_STRUCTP(data);
645         data->u.s.num_share_mode_entries = lck->num_share_modes;
646         data->u.s.delete_on_close = lck->delete_on_close;
647         data->u.s.delete_token_size = delete_token_size;
648         DEBUG(10, ("unparse_share_modes: del: %d, tok = %u, num: %d\n",
649                 data->u.s.delete_on_close,
650                 (unsigned int)data->u.s.delete_token_size,
651                 data->u.s.num_share_mode_entries));
652         memcpy(result.dptr + sizeof(*data), lck->share_modes,
653                sizeof(struct share_mode_entry)*lck->num_share_modes);
654         offset = sizeof(*data) +
655                 sizeof(struct share_mode_entry)*lck->num_share_modes;
656
657         /* Store any delete on close token. */
658         if (lck->delete_token) {
659                 uint8 *p = result.dptr + offset;
660
661                 memcpy(p, &lck->delete_token->uid, sizeof(uid_t));
662                 p += sizeof(uid_t);
663
664                 memcpy(p, &lck->delete_token->gid, sizeof(gid_t));
665                 p += sizeof(gid_t);
666
667                 for (i = 0; i < lck->delete_token->ngroups; i++) {
668                         memcpy(p, &lck->delete_token->groups[i], sizeof(gid_t));
669                         p += sizeof(gid_t);
670                 }
671                 offset = p - result.dptr;
672         }
673
674         safe_strcpy((char *)result.dptr + offset, lck->servicepath,
675                     result.dsize - offset - 1);
676         offset += sp_len + 1;
677         safe_strcpy((char *)result.dptr + offset, lck->filename,
678                     result.dsize - offset - 1);
679
680         if (DEBUGLEVEL >= 10) {
681                 print_share_mode_table(data);
682         }
683
684         return result;
685 }
686
687 static int share_mode_lock_destructor(struct share_mode_lock *lck)
688 {
689         NTSTATUS status;
690         TDB_DATA data;
691
692         if (!lck->modified) {
693                 return 0;
694         }
695
696         data = unparse_share_modes(lck);
697
698         if (data.dptr == NULL) {
699                 if (!lck->fresh) {
700                         /* There has been an entry before, delete it */
701
702                         status = lck->record->delete_rec(lck->record);
703                         if (!NT_STATUS_IS_OK(status)) {
704                                 DEBUG(0, ("delete_rec returned %s\n",
705                                           nt_errstr(status)));
706                                 smb_panic("Could not delete share entry\n");
707                         }
708                 }
709                 goto done;
710         }
711
712         status = lck->record->store(lck->record, data, TDB_REPLACE);
713         if (!NT_STATUS_IS_OK(status)) {
714                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
715                 smb_panic("Could not store share mode entry\n");
716         }
717
718  done:
719
720         return 0;
721 }
722
723 static BOOL fill_share_mode_lock(struct share_mode_lock *lck,
724                                  struct file_id id,
725                                  const char *servicepath,
726                                  const char *fname,
727                                  TDB_DATA share_mode_data)
728 {
729         /* Ensure we set every field here as the destructor must be
730            valid even if parse_share_modes fails. */
731
732         lck->servicepath = NULL;
733         lck->filename = NULL;
734         lck->id = id;
735         lck->num_share_modes = 0;
736         lck->share_modes = NULL;
737         lck->delete_token = NULL;
738         lck->delete_on_close = False;
739         lck->fresh = False;
740         lck->modified = False;
741
742         lck->fresh = (share_mode_data.dptr == NULL);
743
744         if (lck->fresh) {
745                 if (fname == NULL || servicepath == NULL) {
746                         return False;
747                 }
748                 lck->filename = talloc_strdup(lck, fname);
749                 lck->servicepath = talloc_strdup(lck, servicepath);
750                 if (lck->filename == NULL || lck->servicepath == NULL) {
751                         DEBUG(0, ("talloc failed\n"));
752                         return False;
753                 }
754         } else {
755                 if (!parse_share_modes(share_mode_data, lck)) {
756                         DEBUG(0, ("Could not parse share modes\n"));
757                         return False;
758                 }
759         }
760
761         return True;
762 }
763
764 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
765                                             struct file_id id,
766                                             const char *servicepath,
767                                             const char *fname)
768 {
769         struct share_mode_lock *lck;
770         TDB_DATA key;
771
772         key.dptr = (unsigned char *)&id;
773         key.dsize = sizeof(id);
774
775         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
776                 DEBUG(0, ("talloc failed\n"));
777                 return NULL;
778         }
779
780         if (!(lck->record = lock_db->fetch_locked(lock_db, lck, key))) {
781                 DEBUG(3, ("Could not lock share entry\n"));
782                 TALLOC_FREE(lck);
783                 return NULL;
784         }
785
786         if (!fill_share_mode_lock(lck, id, servicepath, fname,
787                                   lck->record->value)) {
788                 DEBUG(3, ("fill_share_mode_lock failed\n"));
789                 TALLOC_FREE(lck);
790                 return NULL;
791         }
792
793         talloc_set_destructor(lck, share_mode_lock_destructor);
794
795         return lck;
796 }
797
798 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
799                                                   struct file_id id,
800                                                   const char *servicepath,
801                                                   const char *fname)
802 {
803         struct share_mode_lock *lck;
804         TDB_DATA key = locking_key(id);
805         TDB_DATA data;
806
807         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
808                 DEBUG(0, ("talloc failed\n"));
809                 return NULL;
810         }
811
812         if (lock_db->fetch(lock_db, lck, key, &data) == -1) {
813                 DEBUG(3, ("Could not fetch share entry\n"));
814                 TALLOC_FREE(lck);
815                 return NULL;
816         }
817
818         if (!fill_share_mode_lock(lck, id, servicepath, fname, data)) {
819                 DEBUG(3, ("fill_share_mode_lock failed\n"));
820                 TALLOC_FREE(lck);
821                 return NULL;
822         }
823
824         TALLOC_FREE(data.dptr);
825
826         return lck;
827 }
828
829 /*******************************************************************
830  Sets the service name and filename for rename.
831  At this point we emit "file renamed" messages to all
832  process id's that have this file open.
833  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
834 ********************************************************************/
835
836 BOOL rename_share_filename(struct messaging_context *msg_ctx,
837                         struct share_mode_lock *lck,
838                         const char *servicepath,
839                         const char *newname)
840 {
841         size_t sp_len;
842         size_t fn_len;
843         size_t msg_len;
844         char *frm = NULL;
845         int i;
846
847         if (!lck) {
848                 return False;
849         }
850
851         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
852                 servicepath, newname));
853
854         /*
855          * rename_internal_fsp() and rename_internals() add './' to
856          * head of newname if newname does not contain a '/'.
857          */
858         while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
859                 newname += 2;
860         }
861
862         lck->servicepath = talloc_strdup(lck, servicepath);
863         lck->filename = talloc_strdup(lck, newname);
864         if (lck->filename == NULL || lck->servicepath == NULL) {
865                 DEBUG(0, ("rename_share_filename: talloc failed\n"));
866                 return False;
867         }
868         lck->modified = True;
869
870         sp_len = strlen(lck->servicepath);
871         fn_len = strlen(lck->filename);
872
873         msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1;
874
875         /* Set up the name changed message. */
876         frm = TALLOC_ARRAY(lck, char, msg_len);
877         if (!frm) {
878                 return False;
879         }
880
881         push_file_id_16(frm, &lck->id);
882
883         DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
884
885         safe_strcpy(&frm[16], lck->servicepath, sp_len);
886         safe_strcpy(&frm[16 + sp_len + 1], lck->filename, fn_len);
887
888         /* Send the messages. */
889         for (i=0; i<lck->num_share_modes; i++) {
890                 struct share_mode_entry *se = &lck->share_modes[i];
891                 if (!is_valid_share_mode_entry(se)) {
892                         continue;
893                 }
894                 /* But not to ourselves... */
895                 if (procid_is_me(&se->pid)) {
896                         continue;
897                 }
898
899                 DEBUG(10,("rename_share_filename: sending rename message to pid %s "
900                           "file_id %s sharepath %s newname %s\n",
901                           procid_str_static(&se->pid),
902                           file_id_static_string(&lck->id),
903                           lck->servicepath, lck->filename ));
904
905                 messaging_send_buf(msg_ctx, se->pid, MSG_SMB_FILE_RENAME,
906                                    (uint8 *)frm, msg_len);
907         }
908
909         return True;
910 }
911
912 BOOL get_delete_on_close_flag(struct file_id id)
913 {
914         BOOL result;
915         struct share_mode_lock *lck;
916   
917         if (!(lck = fetch_share_mode_unlocked(NULL, id, NULL, NULL))) {
918                 return False;
919         }
920         result = lck->delete_on_close;
921         TALLOC_FREE(lck);
922         return result;
923 }
924
925 BOOL is_valid_share_mode_entry(const struct share_mode_entry *e)
926 {
927         int num_props = 0;
928
929         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
930         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
931         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
932
933         SMB_ASSERT(num_props <= 1);
934         return (num_props != 0);
935 }
936
937 BOOL is_deferred_open_entry(const struct share_mode_entry *e)
938 {
939         return (e->op_type == DEFERRED_OPEN_ENTRY);
940 }
941
942 BOOL is_unused_share_mode_entry(const struct share_mode_entry *e)
943 {
944         return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
945 }
946
947 /*******************************************************************
948  Fill a share mode entry.
949 ********************************************************************/
950
951 static void fill_share_mode_entry(struct share_mode_entry *e,
952                                   files_struct *fsp,
953                                   uid_t uid, uint16 mid, uint16 op_type)
954 {
955         ZERO_STRUCTP(e);
956         e->pid = procid_self();
957         e->share_access = fsp->share_access;
958         e->private_options = fsp->fh->private_options;
959         e->access_mask = fsp->access_mask;
960         e->op_mid = mid;
961         e->op_type = op_type;
962         e->time.tv_sec = fsp->open_time.tv_sec;
963         e->time.tv_usec = fsp->open_time.tv_usec;
964         e->id = fsp->file_id;
965         e->share_file_id = fsp->fh->gen_id;
966         e->uid = (uint32)uid;
967         e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
968 }
969
970 static void fill_deferred_open_entry(struct share_mode_entry *e,
971                                      const struct timeval request_time,
972                                      struct file_id id, uint16 mid)
973 {
974         ZERO_STRUCTP(e);
975         e->pid = procid_self();
976         e->op_mid = mid;
977         e->op_type = DEFERRED_OPEN_ENTRY;
978         e->time.tv_sec = request_time.tv_sec;
979         e->time.tv_usec = request_time.tv_usec;
980         e->id = id;
981         e->uid = (uint32)-1;
982         e->flags = 0;
983 }
984
985 static void add_share_mode_entry(struct share_mode_lock *lck,
986                                  const struct share_mode_entry *entry)
987 {
988         int i;
989
990         for (i=0; i<lck->num_share_modes; i++) {
991                 struct share_mode_entry *e = &lck->share_modes[i];
992                 if (is_unused_share_mode_entry(e)) {
993                         *e = *entry;
994                         break;
995                 }
996         }
997
998         if (i == lck->num_share_modes) {
999                 /* No unused entry found */
1000                 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
1001                              &lck->share_modes, &lck->num_share_modes);
1002         }
1003         lck->modified = True;
1004 }
1005
1006 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
1007                         uid_t uid, uint16 mid, uint16 op_type, BOOL initial_delete_on_close_allowed)
1008 {
1009         struct share_mode_entry entry;
1010         fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1011         if (initial_delete_on_close_allowed) {
1012                 entry.flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1013         }
1014         add_share_mode_entry(lck, &entry);
1015 }
1016
1017 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
1018                        struct timeval request_time,
1019                        struct file_id id)
1020 {
1021         struct share_mode_entry entry;
1022         fill_deferred_open_entry(&entry, request_time, id, mid);
1023         add_share_mode_entry(lck, &entry);
1024 }
1025
1026 /*******************************************************************
1027  Check if two share mode entries are identical, ignoring oplock 
1028  and mid info and desired_access. (Removed paranoia test - it's
1029  not automatically a logic error if they are identical. JRA.)
1030 ********************************************************************/
1031
1032 static BOOL share_modes_identical(struct share_mode_entry *e1,
1033                                   struct share_mode_entry *e2)
1034 {
1035         /* We used to check for e1->share_access == e2->share_access here
1036            as well as the other fields but 2 different DOS or FCB opens
1037            sharing the same share mode entry may validly differ in
1038            fsp->share_access field. */
1039
1040         return (procid_equal(&e1->pid, &e2->pid) &&
1041                 file_id_equal(&e1->id, &e2->id) &&
1042                 e1->share_file_id == e2->share_file_id );
1043 }
1044
1045 static BOOL deferred_open_identical(struct share_mode_entry *e1,
1046                                     struct share_mode_entry *e2)
1047 {
1048         return (procid_equal(&e1->pid, &e2->pid) &&
1049                 (e1->op_mid == e2->op_mid) &&
1050                 file_id_equal(&e1->id, &e2->id));
1051 }
1052
1053 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1054                                                       struct share_mode_entry *entry)
1055 {
1056         int i;
1057
1058         for (i=0; i<lck->num_share_modes; i++) {
1059                 struct share_mode_entry *e = &lck->share_modes[i];
1060                 if (is_valid_share_mode_entry(entry) &&
1061                     is_valid_share_mode_entry(e) &&
1062                     share_modes_identical(e, entry)) {
1063                         return e;
1064                 }
1065                 if (is_deferred_open_entry(entry) &&
1066                     is_deferred_open_entry(e) &&
1067                     deferred_open_identical(e, entry)) {
1068                         return e;
1069                 }
1070         }
1071         return NULL;
1072 }
1073
1074 /*******************************************************************
1075  Del the share mode of a file for this process. Return the number of
1076  entries left.
1077 ********************************************************************/
1078
1079 BOOL del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1080 {
1081         struct share_mode_entry entry, *e;
1082
1083         /* Don't care about the pid owner being correct here - just a search. */
1084         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1085
1086         e = find_share_mode_entry(lck, &entry);
1087         if (e == NULL) {
1088                 return False;
1089         }
1090
1091         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1092         lck->modified = True;
1093         return True;
1094 }
1095
1096 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
1097 {
1098         struct share_mode_entry entry, *e;
1099
1100         fill_deferred_open_entry(&entry, timeval_zero(),
1101                                  lck->id, mid);
1102
1103         e = find_share_mode_entry(lck, &entry);
1104         if (e == NULL) {
1105                 return;
1106         }
1107
1108         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1109         lck->modified = True;
1110 }
1111
1112 /*******************************************************************
1113  Remove an oplock mid and mode entry from a share mode.
1114 ********************************************************************/
1115
1116 BOOL remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1117 {
1118         struct share_mode_entry entry, *e;
1119
1120         /* Don't care about the pid owner being correct here - just a search. */
1121         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1122
1123         e = find_share_mode_entry(lck, &entry);
1124         if (e == NULL) {
1125                 return False;
1126         }
1127
1128         e->op_mid = 0;
1129         e->op_type = NO_OPLOCK;
1130         lck->modified = True;
1131         return True;
1132 }
1133
1134 /*******************************************************************
1135  Downgrade a oplock type from exclusive to level II.
1136 ********************************************************************/
1137
1138 BOOL downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1139 {
1140         struct share_mode_entry entry, *e;
1141
1142         /* Don't care about the pid owner being correct here - just a search. */
1143         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1144
1145         e = find_share_mode_entry(lck, &entry);
1146         if (e == NULL) {
1147                 return False;
1148         }
1149
1150         e->op_type = LEVEL_II_OPLOCK;
1151         lck->modified = True;
1152         return True;
1153 }
1154
1155 /****************************************************************************
1156  Deal with the internal needs of setting the delete on close flag. Note that
1157  as the tdb locking is recursive, it is safe to call this from within 
1158  open_file_ntcreate. JRA.
1159 ****************************************************************************/
1160
1161 NTSTATUS can_set_delete_on_close(files_struct *fsp, BOOL delete_on_close,
1162                                  uint32 dosmode)
1163 {
1164         if (!delete_on_close) {
1165                 return NT_STATUS_OK;
1166         }
1167
1168         /*
1169          * Only allow delete on close for writable files.
1170          */
1171
1172         if ((dosmode & aRONLY) &&
1173             !lp_delete_readonly(SNUM(fsp->conn))) {
1174                 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1175                           "flag set but file attribute is readonly.\n",
1176                           fsp->fsp_name ));
1177                 return NT_STATUS_CANNOT_DELETE;
1178         }
1179
1180         /*
1181          * Only allow delete on close for writable shares.
1182          */
1183
1184         if (!CAN_WRITE(fsp->conn)) {
1185                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1186                           "close flag set but write access denied on share.\n",
1187                           fsp->fsp_name ));
1188                 return NT_STATUS_ACCESS_DENIED;
1189         }
1190
1191         /*
1192          * Only allow delete on close for files/directories opened with delete
1193          * intent.
1194          */
1195
1196         if (!(fsp->access_mask & DELETE_ACCESS)) {
1197                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1198                           "close flag set but delete access denied.\n",
1199                           fsp->fsp_name ));
1200                 return NT_STATUS_ACCESS_DENIED;
1201         }
1202
1203         /* Don't allow delete on close for non-empty directories. */
1204         if (fsp->is_directory) {
1205                 return can_delete_directory(fsp->conn, fsp->fsp_name);
1206         }
1207
1208         return NT_STATUS_OK;
1209 }
1210
1211 /****************************************************************************
1212  Do we have an open file handle that created this entry ?
1213 ****************************************************************************/
1214
1215 BOOL can_set_initial_delete_on_close(const struct share_mode_lock *lck)
1216 {
1217         int i;
1218
1219         for (i=0; i<lck->num_share_modes; i++) {
1220                 if (lck->share_modes[i].flags & SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE) {
1221                         return True;
1222                 }
1223         }
1224         return False;
1225 }
1226
1227 /*************************************************************************
1228  Return a talloced copy of a UNIX_USER_TOKEN. NULL on fail.
1229  (Should this be in locking.c.... ?).
1230 *************************************************************************/
1231
1232 static UNIX_USER_TOKEN *copy_unix_token(TALLOC_CTX *ctx, UNIX_USER_TOKEN *tok)
1233 {
1234         UNIX_USER_TOKEN *cpy;
1235
1236         if (tok == NULL) {
1237                 return NULL;
1238         }
1239
1240         cpy = TALLOC_P(ctx, UNIX_USER_TOKEN);
1241         if (!cpy) {
1242                 return NULL;
1243         }
1244
1245         cpy->uid = tok->uid;
1246         cpy->gid = tok->gid;
1247         cpy->ngroups = tok->ngroups;
1248         if (tok->ngroups) {
1249                 /* Make this a talloc child of cpy. */
1250                 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1251                 if (!cpy->groups) {
1252                         return NULL;
1253                 }
1254                 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1255         }
1256         return cpy;
1257 }
1258
1259 /****************************************************************************
1260  Replace the delete on close token.
1261 ****************************************************************************/
1262
1263 void set_delete_on_close_token(struct share_mode_lock *lck, UNIX_USER_TOKEN *tok)
1264 {
1265         /* Ensure there's no token. */
1266         if (lck->delete_token) {
1267                 TALLOC_FREE(lck->delete_token); /* Also deletes groups... */
1268                 lck->delete_token = NULL;
1269         }
1270
1271         /* Copy the new token (can be NULL). */
1272         lck->delete_token = copy_unix_token(lck, tok);
1273         lck->modified = True;
1274 }
1275
1276 /****************************************************************************
1277  Sets the delete on close flag over all share modes on this file.
1278  Modify the share mode entry for all files open
1279  on this device and inode to tell other smbds we have
1280  changed the delete on close flag. This will be noticed
1281  in the close code, the last closer will delete the file
1282  if flag is set.
1283  This makes a copy of any UNIX_USER_TOKEN into the
1284  lck entry. This function is used when the lock is already granted.
1285 ****************************************************************************/
1286
1287 void set_delete_on_close_lck(struct share_mode_lock *lck, BOOL delete_on_close, UNIX_USER_TOKEN *tok)
1288 {
1289         if (lck->delete_on_close != delete_on_close) {
1290                 set_delete_on_close_token(lck, tok);
1291                 lck->delete_on_close = delete_on_close;
1292                 if (delete_on_close) {
1293                         SMB_ASSERT(lck->delete_token != NULL);
1294                 }
1295                 lck->modified = True;
1296         }
1297 }
1298
1299 BOOL set_delete_on_close(files_struct *fsp, BOOL delete_on_close, UNIX_USER_TOKEN *tok)
1300 {
1301         struct share_mode_lock *lck;
1302         
1303         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1304                   "fnum = %d, file %s\n",
1305                   delete_on_close ? "Adding" : "Removing", fsp->fnum,
1306                   fsp->fsp_name ));
1307
1308         if (fsp->is_stat) {
1309                 return True;
1310         }
1311
1312         lck = get_share_mode_lock(NULL, fsp->file_id, NULL, NULL);
1313         if (lck == NULL) {
1314                 return False;
1315         }
1316
1317         set_delete_on_close_lck(lck, delete_on_close, tok);
1318
1319         if (fsp->is_directory) {
1320                 send_stat_cache_delete_message(fsp->fsp_name);
1321         }
1322
1323         TALLOC_FREE(lck);
1324         return True;
1325 }
1326
1327 /****************************************************************************
1328  Sets the allow initial delete on close flag for this share mode.
1329 ****************************************************************************/
1330
1331 BOOL set_allow_initial_delete_on_close(struct share_mode_lock *lck, files_struct *fsp, BOOL delete_on_close)
1332 {
1333         struct share_mode_entry entry, *e;
1334
1335         /* Don't care about the pid owner being correct here - just a search. */
1336         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1337
1338         e = find_share_mode_entry(lck, &entry);
1339         if (e == NULL) {
1340                 return False;
1341         }
1342
1343         if (delete_on_close) {
1344                 e->flags |= SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1345         } else {
1346                 e->flags &= ~SHARE_MODE_ALLOW_INITIAL_DELETE_ON_CLOSE;
1347         }
1348         lck->modified = True;
1349         return True;
1350 }
1351
1352 struct forall_state {
1353         void (*fn)(const struct share_mode_entry *entry,
1354                    const char *sharepath,
1355                    const char *fname,
1356                    void *private_data);
1357         void *private_data;
1358 };
1359
1360 static int traverse_fn(struct db_record *rec, void *_state)
1361 {
1362         struct forall_state *state = (struct forall_state *)_state;
1363         struct locking_data *data;
1364         struct share_mode_entry *shares;
1365         const char *sharepath;
1366         const char *fname;
1367         int i;
1368
1369         /* Ensure this is a locking_key record. */
1370         if (rec->key.dsize != sizeof(struct file_id))
1371                 return 0;
1372
1373         data = (struct locking_data *)rec->value.dptr;
1374         shares = (struct share_mode_entry *)(rec->value.dptr + sizeof(*data));
1375         sharepath = (const char *)rec->value.dptr + sizeof(*data) +
1376                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1377                 data->u.s.delete_token_size;
1378         fname = (const char *)rec->value.dptr + sizeof(*data) +
1379                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1380                 data->u.s.delete_token_size +
1381                 strlen(sharepath) + 1;
1382
1383         for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1384                 state->fn(&shares[i], sharepath, fname,
1385                           state->private_data);
1386         }
1387         return 0;
1388 }
1389
1390 /*******************************************************************
1391  Call the specified function on each entry under management by the
1392  share mode system.
1393 ********************************************************************/
1394
1395 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1396                                  const char *, void *),
1397                       void *private_data)
1398 {
1399         struct forall_state state;
1400
1401         if (lock_db == NULL)
1402                 return 0;
1403
1404         state.fn = fn;
1405         state.private_data = private_data;
1406
1407         return lock_db->traverse_read(lock_db, traverse_fn, (void *)&state);
1408 }