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