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