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