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