bfdf8092fd4cdf7d38ae287514e59c506988e420
[samba.git] / source3 / locking / locking.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Locking functions
4    Copyright (C) Andrew Tridgell 1992-2000
5    Copyright (C) Jeremy Allison 1992-2006
6    Copyright (C) Volker Lendecke 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21    Revision History:
22
23    12 aug 96: Erik.Devriendt@te6.siemens.be
24    added support for shared memory implementation of share mode locking
25
26    May 1997. Jeremy Allison (jallison@whistle.com). Modified share mode
27    locking to deal with multiple share modes per open file.
28
29    September 1997. Jeremy Allison (jallison@whistle.com). Added oplock
30    support.
31
32    rewrtten completely to use new tdb code. Tridge, Dec '99
33
34    Added POSIX locking support. Jeremy Allison (jeremy@valinux.com), Apr. 2000.
35    Added Unix Extensions POSIX locking support. Jeremy Allison Mar 2006.
36 */
37
38 #include "includes.h"
39 #include "system/filesys.h"
40 #include "librpc/gen_ndr/messaging.h"
41 #include "smbd/globals.h"
42 #include "dbwrap.h"
43 #include "../libcli/security/security.h"
44 #include "serverid.h"
45
46 #undef DBGC_CLASS
47 #define DBGC_CLASS DBGC_LOCKING
48
49 #define NO_LOCKING_COUNT (-1)
50
51 /* the locking database handle */
52 static struct db_context *lock_db;
53
54 /****************************************************************************
55  Debugging aids :-).
56 ****************************************************************************/
57
58 const char *lock_type_name(enum brl_type lock_type)
59 {
60         switch (lock_type) {
61                 case READ_LOCK:
62                         return "READ";
63                 case WRITE_LOCK:
64                         return "WRITE";
65                 case PENDING_READ_LOCK:
66                         return "PENDING_READ";
67                 case PENDING_WRITE_LOCK:
68                         return "PENDING_WRITE";
69                 default:
70                         return "other";
71         }
72 }
73
74 const char *lock_flav_name(enum brl_flavour lock_flav)
75 {
76         return (lock_flav == WINDOWS_LOCK) ? "WINDOWS_LOCK" : "POSIX_LOCK";
77 }
78
79 /****************************************************************************
80  Utility function called to see if a file region is locked.
81  Called in the read/write codepath.
82 ****************************************************************************/
83
84 void init_strict_lock_struct(files_struct *fsp,
85                                 uint64_t smblctx,
86                                 br_off start,
87                                 br_off size,
88                                 enum brl_type lock_type,
89                                 struct lock_struct *plock)
90 {
91         SMB_ASSERT(lock_type == READ_LOCK || lock_type == WRITE_LOCK);
92
93         plock->context.smblctx = smblctx;
94         plock->context.tid = fsp->conn->cnum;
95         plock->context.pid = sconn_server_id(fsp->conn->sconn);
96         plock->start = start;
97         plock->size = size;
98         plock->fnum = fsp->fnum;
99         plock->lock_type = lock_type;
100         plock->lock_flav = lp_posix_cifsu_locktype(fsp);
101 }
102
103 bool strict_lock_default(files_struct *fsp, struct lock_struct *plock)
104 {
105         int strict_locking = lp_strict_locking(fsp->conn->params);
106         bool ret = False;
107
108         if (plock->size == 0) {
109                 return True;
110         }
111
112         if (!lp_locking(fsp->conn->params) || !strict_locking) {
113                 return True;
114         }
115
116         if (strict_locking == Auto) {
117                 if  (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && (plock->lock_type == READ_LOCK || plock->lock_type == WRITE_LOCK)) {
118                         DEBUG(10,("is_locked: optimisation - exclusive oplock on file %s\n", fsp_str_dbg(fsp)));
119                         ret = True;
120                 } else if ((fsp->oplock_type == LEVEL_II_OPLOCK) &&
121                            (plock->lock_type == READ_LOCK)) {
122                         DEBUG(10,("is_locked: optimisation - level II oplock on file %s\n", fsp_str_dbg(fsp)));
123                         ret = True;
124                 } else {
125                         struct byte_range_lock *br_lck;
126
127                         br_lck = brl_get_locks_readonly(fsp);
128                         if (!br_lck) {
129                                 return True;
130                         }
131                         ret = brl_locktest(br_lck,
132                                         plock->context.smblctx,
133                                         plock->context.pid,
134                                         plock->start,
135                                         plock->size,
136                                         plock->lock_type,
137                                         plock->lock_flav);
138                 }
139         } else {
140                 struct byte_range_lock *br_lck;
141
142                 br_lck = brl_get_locks_readonly(fsp);
143                 if (!br_lck) {
144                         return True;
145                 }
146                 ret = brl_locktest(br_lck,
147                                 plock->context.smblctx,
148                                 plock->context.pid,
149                                 plock->start,
150                                 plock->size,
151                                 plock->lock_type,
152                                 plock->lock_flav);
153         }
154
155         DEBUG(10,("strict_lock_default: flavour = %s brl start=%.0f "
156                         "len=%.0f %s for fnum %d file %s\n",
157                         lock_flav_name(plock->lock_flav),
158                         (double)plock->start, (double)plock->size,
159                         ret ? "unlocked" : "locked",
160                         plock->fnum, fsp_str_dbg(fsp)));
161
162         return ret;
163 }
164
165 void strict_unlock_default(files_struct *fsp, struct lock_struct *plock)
166 {
167 }
168
169 /****************************************************************************
170  Find out if a lock could be granted - return who is blocking us if we can't.
171 ****************************************************************************/
172
173 NTSTATUS query_lock(files_struct *fsp,
174                         uint64_t *psmblctx,
175                         uint64_t *pcount,
176                         uint64_t *poffset,
177                         enum brl_type *plock_type,
178                         enum brl_flavour lock_flav)
179 {
180         struct byte_range_lock *br_lck = NULL;
181
182         if (!fsp->can_lock) {
183                 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
184         }
185
186         if (!lp_locking(fsp->conn->params)) {
187                 return NT_STATUS_OK;
188         }
189
190         br_lck = brl_get_locks_readonly(fsp);
191         if (!br_lck) {
192                 return NT_STATUS_NO_MEMORY;
193         }
194
195         return brl_lockquery(br_lck,
196                         psmblctx,
197                         sconn_server_id(fsp->conn->sconn),
198                         poffset,
199                         pcount,
200                         plock_type,
201                         lock_flav);
202 }
203
204 static void increment_current_lock_count(files_struct *fsp,
205     enum brl_flavour lock_flav)
206 {
207         if (lock_flav == WINDOWS_LOCK &&
208             fsp->current_lock_count != NO_LOCKING_COUNT) {
209                 /* blocking ie. pending, locks also count here,
210                  * as this is an efficiency counter to avoid checking
211                  * the lock db. on close. JRA. */
212
213                 fsp->current_lock_count++;
214         } else {
215                 /* Notice that this has had a POSIX lock request.
216                  * We can't count locks after this so forget them.
217                  */
218                 fsp->current_lock_count = NO_LOCKING_COUNT;
219         }
220 }
221
222 static void decrement_current_lock_count(files_struct *fsp,
223     enum brl_flavour lock_flav)
224 {
225         if (lock_flav == WINDOWS_LOCK &&
226             fsp->current_lock_count != NO_LOCKING_COUNT) {
227                 SMB_ASSERT(fsp->current_lock_count > 0);
228                 fsp->current_lock_count--;
229         }
230 }
231
232 /****************************************************************************
233  Utility function called by locking requests.
234 ****************************************************************************/
235
236 struct byte_range_lock *do_lock(struct messaging_context *msg_ctx,
237                         files_struct *fsp,
238                         uint64_t smblctx,
239                         uint64_t count,
240                         uint64_t offset,
241                         enum brl_type lock_type,
242                         enum brl_flavour lock_flav,
243                         bool blocking_lock,
244                         NTSTATUS *perr,
245                         uint64_t *psmblctx,
246                         struct blocking_lock_record *blr)
247 {
248         struct byte_range_lock *br_lck = NULL;
249
250         /* silently return ok on print files as we don't do locking there */
251         if (fsp->print_file) {
252                 *perr = NT_STATUS_OK;
253                 return NULL;
254         }
255
256         if (!fsp->can_lock) {
257                 *perr = fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
258                 return NULL;
259         }
260
261         if (!lp_locking(fsp->conn->params)) {
262                 *perr = NT_STATUS_OK;
263                 return NULL;
264         }
265
266         /* NOTE! 0 byte long ranges ARE allowed and should be stored  */
267
268         DEBUG(10,("do_lock: lock flavour %s lock type %s start=%.0f len=%.0f "
269                 "blocking_lock=%s requested for fnum %d file %s\n",
270                 lock_flav_name(lock_flav), lock_type_name(lock_type),
271                 (double)offset, (double)count, blocking_lock ? "true" :
272                 "false", fsp->fnum, fsp_str_dbg(fsp)));
273
274         br_lck = brl_get_locks(talloc_tos(), fsp);
275         if (!br_lck) {
276                 *perr = NT_STATUS_NO_MEMORY;
277                 return NULL;
278         }
279
280         *perr = brl_lock(msg_ctx,
281                         br_lck,
282                         smblctx,
283                         sconn_server_id(fsp->conn->sconn),
284                         offset,
285                         count,
286                         lock_type,
287                         lock_flav,
288                         blocking_lock,
289                         psmblctx,
290                         blr);
291
292         DEBUG(10, ("do_lock: returning status=%s\n", nt_errstr(*perr)));
293
294         increment_current_lock_count(fsp, lock_flav);
295         return br_lck;
296 }
297
298 /****************************************************************************
299  Utility function called by unlocking requests.
300 ****************************************************************************/
301
302 NTSTATUS do_unlock(struct messaging_context *msg_ctx,
303                         files_struct *fsp,
304                         uint64_t smblctx,
305                         uint64_t count,
306                         uint64_t offset,
307                         enum brl_flavour lock_flav)
308 {
309         bool ok = False;
310         struct byte_range_lock *br_lck = NULL;
311         
312         if (!fsp->can_lock) {
313                 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
314         }
315         
316         if (!lp_locking(fsp->conn->params)) {
317                 return NT_STATUS_OK;
318         }
319         
320         DEBUG(10,("do_unlock: unlock start=%.0f len=%.0f requested for fnum %d file %s\n",
321                   (double)offset, (double)count, fsp->fnum,
322                   fsp_str_dbg(fsp)));
323
324         br_lck = brl_get_locks(talloc_tos(), fsp);
325         if (!br_lck) {
326                 return NT_STATUS_NO_MEMORY;
327         }
328
329         ok = brl_unlock(msg_ctx,
330                         br_lck,
331                         smblctx,
332                         sconn_server_id(fsp->conn->sconn),
333                         offset,
334                         count,
335                         lock_flav);
336    
337         TALLOC_FREE(br_lck);
338
339         if (!ok) {
340                 DEBUG(10,("do_unlock: returning ERRlock.\n" ));
341                 return NT_STATUS_RANGE_NOT_LOCKED;
342         }
343
344         decrement_current_lock_count(fsp, lock_flav);
345         return NT_STATUS_OK;
346 }
347
348 /****************************************************************************
349  Cancel any pending blocked locks.
350 ****************************************************************************/
351
352 NTSTATUS do_lock_cancel(files_struct *fsp,
353                         uint64 smblctx,
354                         uint64_t count,
355                         uint64_t offset,
356                         enum brl_flavour lock_flav,
357                         struct blocking_lock_record *blr)
358 {
359         bool ok = False;
360         struct byte_range_lock *br_lck = NULL;
361
362         if (!fsp->can_lock) {
363                 return fsp->is_directory ?
364                         NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
365         }
366         
367         if (!lp_locking(fsp->conn->params)) {
368                 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
369         }
370
371         DEBUG(10,("do_lock_cancel: cancel start=%.0f len=%.0f requested for fnum %d file %s\n",
372                   (double)offset, (double)count, fsp->fnum,
373                   fsp_str_dbg(fsp)));
374
375         br_lck = brl_get_locks(talloc_tos(), fsp);
376         if (!br_lck) {
377                 return NT_STATUS_NO_MEMORY;
378         }
379
380         ok = brl_lock_cancel(br_lck,
381                         smblctx,
382                         sconn_server_id(fsp->conn->sconn),
383                         offset,
384                         count,
385                         lock_flav,
386                         blr);
387
388         TALLOC_FREE(br_lck);
389
390         if (!ok) {
391                 DEBUG(10,("do_lock_cancel: returning ERRcancelviolation.\n" ));
392                 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
393         }
394
395         decrement_current_lock_count(fsp, lock_flav);
396         return NT_STATUS_OK;
397 }
398
399 /****************************************************************************
400  Remove any locks on this fd. Called from file_close().
401 ****************************************************************************/
402
403 void locking_close_file(struct messaging_context *msg_ctx,
404                         files_struct *fsp,
405                         enum file_close_type close_type)
406 {
407         struct byte_range_lock *br_lck;
408
409         if (!lp_locking(fsp->conn->params)) {
410                 return;
411         }
412
413         /* If we have not outstanding locks or pending
414          * locks then we don't need to look in the lock db.
415          */
416
417         if (fsp->current_lock_count == 0) {
418                 return;
419         }
420
421         br_lck = brl_get_locks(talloc_tos(),fsp);
422
423         if (br_lck) {
424                 cancel_pending_lock_requests_by_fid(fsp, br_lck, close_type);
425                 brl_close_fnum(msg_ctx, br_lck);
426                 TALLOC_FREE(br_lck);
427         }
428 }
429
430 /****************************************************************************
431  Initialise the locking functions.
432 ****************************************************************************/
433
434 static bool locking_init_internal(bool read_only)
435 {
436         brl_init(read_only);
437
438         if (lock_db)
439                 return True;
440
441         lock_db = db_open(NULL, lock_path("locking.tdb"),
442                           lp_open_files_db_hash_size(),
443                           TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH,
444                           read_only?O_RDONLY:O_RDWR|O_CREAT, 0644);
445
446         if (!lock_db) {
447                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
448                 return False;
449         }
450
451         if (!posix_locking_init(read_only))
452                 return False;
453
454         return True;
455 }
456
457 bool locking_init(void)
458 {
459         return locking_init_internal(false);
460 }
461
462 bool locking_init_readonly(void)
463 {
464         return locking_init_internal(true);
465 }
466
467 /*******************************************************************
468  Deinitialize the share_mode management.
469 ******************************************************************/
470
471 bool locking_end(void)
472 {
473         brl_shutdown();
474         TALLOC_FREE(lock_db);
475         return true;
476 }
477
478 /*******************************************************************
479  Form a static locking key for a dev/inode pair.
480 ******************************************************************/
481
482 static TDB_DATA locking_key(const struct file_id *id, struct file_id *tmp)
483 {
484         *tmp = *id;
485         return make_tdb_data((const uint8_t *)tmp, sizeof(*tmp));
486 }
487
488 /*******************************************************************
489  Print out a share mode.
490 ********************************************************************/
491
492 char *share_mode_str(TALLOC_CTX *ctx, int num, const struct share_mode_entry *e)
493 {
494         return talloc_asprintf(ctx, "share_mode_entry[%d]: %s "
495                  "pid = %s, share_access = 0x%x, private_options = 0x%x, "
496                  "access_mask = 0x%x, mid = 0x%llx, type= 0x%x, gen_id = %lu, "
497                  "uid = %u, flags = %u, file_id %s, name_hash = 0x%x",
498                  num,
499                  e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
500                  procid_str_static(&e->pid),
501                  e->share_access, e->private_options,
502                  e->access_mask, (unsigned long long)e->op_mid,
503                  e->op_type, e->share_file_id,
504                  (unsigned int)e->uid, (unsigned int)e->flags,
505                  file_id_string_tos(&e->id),
506                  (unsigned int)e->name_hash);
507 }
508
509 /*******************************************************************
510  Print out a share mode table.
511 ********************************************************************/
512
513 static void print_share_mode_table(struct locking_data *data)
514 {
515         int num_share_modes = data->u.s.num_share_mode_entries;
516         struct share_mode_entry *shares =
517                 (struct share_mode_entry *)(data + 1);
518         int i;
519
520         for (i = 0; i < num_share_modes; i++) {
521                 struct share_mode_entry entry;
522                 char *str;
523
524                 /*
525                  * We need to memcpy the entry here due to alignment
526                  * restrictions that are not met when directly accessing
527                  * shares[i]
528                  */
529
530                 memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
531                 str = share_mode_str(talloc_tos(), i, &entry);
532
533                 DEBUG(10,("print_share_mode_table: %s\n", str ? str : ""));
534                 TALLOC_FREE(str);
535         }
536 }
537
538 static int parse_delete_tokens_list(struct share_mode_lock *lck,
539                 struct locking_data *pdata,
540                 const TDB_DATA dbuf)
541 {
542         uint8_t *p = dbuf.dptr + sizeof(struct locking_data) +
543                         (lck->num_share_modes *
544                         sizeof(struct share_mode_entry));
545         uint8_t *end_ptr = dbuf.dptr + (dbuf.dsize - 2);
546         int delete_tokens_size = 0;
547         int i;
548
549         lck->delete_tokens = NULL;
550
551         for (i = 0; i < pdata->u.s.num_delete_token_entries; i++) {
552                 uint32_t token_len;
553                 struct delete_token_list *pdtl;
554
555                 if (end_ptr - p < (sizeof(uint32_t) + sizeof(uint32_t) +
556                                         sizeof(uid_t) + sizeof(gid_t))) {
557                         DEBUG(0,("parse_delete_tokens_list: "
558                                 "corrupt token list (%u)",
559                                 (unsigned int)(end_ptr - p)));
560                         smb_panic("corrupt token list");
561                         return -1;
562                 }
563
564                 memcpy(&token_len, p, sizeof(token_len));
565                 delete_tokens_size += token_len;
566
567                 if (p + token_len > end_ptr || token_len < sizeof(token_len) +
568                                                 sizeof(pdtl->name_hash) +
569                                                 sizeof(uid_t) +
570                                                 sizeof(gid_t)) {
571                         DEBUG(0,("parse_delete_tokens_list: "
572                                 "invalid token length (%u)\n",
573                                 (unsigned int)token_len ));
574                         smb_panic("invalid token length");
575                         return -1;
576                 }
577
578                 p += sizeof(token_len);
579
580                 pdtl = TALLOC_ZERO_P(lck, struct delete_token_list);
581                 if (pdtl == NULL) {
582                         DEBUG(0,("parse_delete_tokens_list: talloc failed"));
583                         return -1;
584                 }
585                 /* Copy out the name_hash. */
586                 memcpy(&pdtl->name_hash, p, sizeof(pdtl->name_hash));
587                 p += sizeof(pdtl->name_hash);
588
589                 pdtl->delete_token = TALLOC_ZERO_P(pdtl, struct security_unix_token);
590                 if (pdtl->delete_token == NULL) {
591                         DEBUG(0,("parse_delete_tokens_list: talloc failed"));
592                         return -1;
593                 }
594
595                 /* Copy out the uid and gid. */
596                 memcpy(&pdtl->delete_token->uid, p, sizeof(uid_t));
597                 p += sizeof(uid_t);
598                 memcpy(&pdtl->delete_token->gid, p, sizeof(gid_t));
599                 p += sizeof(gid_t);
600
601                 token_len -= (sizeof(token_len) + sizeof(pdtl->name_hash) +
602                                 sizeof(uid_t) + sizeof(gid_t));
603
604                 /* Any supplementary groups ? */
605                 if (token_len) {
606                         int j;
607
608                         if (token_len % sizeof(gid_t) != 0) {
609                                 DEBUG(0,("parse_delete_tokens_list: "
610                                         "corrupt group list (%u)",
611                                         (unsigned int)(token_len % sizeof(gid_t)) ));
612                                 smb_panic("corrupt group list");
613                                 return -1;
614                         }
615
616                         pdtl->delete_token->ngroups = token_len / sizeof(gid_t);
617                         pdtl->delete_token->groups = TALLOC_ARRAY(pdtl->delete_token, gid_t,
618                                                 pdtl->delete_token->ngroups);
619                         if (pdtl->delete_token->groups == NULL) {
620                                 DEBUG(0,("parse_delete_tokens_list: talloc failed"));
621                                 return -1;
622                         }
623
624                         for (j = 0; j < pdtl->delete_token->ngroups; j++) {
625                                 memcpy(&pdtl->delete_token->groups[j], p, sizeof(gid_t));
626                                 p += sizeof(gid_t);
627                         }
628                 }
629                 /* Add to the list. */
630                 DLIST_ADD(lck->delete_tokens, pdtl);
631         }
632
633         return delete_tokens_size;
634 }
635
636 /*******************************************************************
637  Get all share mode entries for a dev/inode pair.
638 ********************************************************************/
639
640 static bool parse_share_modes(const TDB_DATA dbuf, struct share_mode_lock *lck)
641 {
642         struct locking_data data;
643         int delete_tokens_size;
644         int i;
645
646         if (dbuf.dsize < sizeof(struct locking_data)) {
647                 smb_panic("parse_share_modes: buffer too short");
648         }
649
650         memcpy(&data, dbuf.dptr, sizeof(data));
651
652         lck->old_write_time = data.u.s.old_write_time;
653         lck->changed_write_time = data.u.s.changed_write_time;
654         lck->num_share_modes = data.u.s.num_share_mode_entries;
655
656         DEBUG(10, ("parse_share_modes: owrt: %s, "
657                    "cwrt: %s, ntok: %u, num_share_modes: %d\n",
658                    timestring(talloc_tos(),
659                               convert_timespec_to_time_t(lck->old_write_time)),
660                    timestring(talloc_tos(),
661                               convert_timespec_to_time_t(
662                                       lck->changed_write_time)),
663                    (unsigned int)data.u.s.num_delete_token_entries,
664                    lck->num_share_modes));
665
666         if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
667                 DEBUG(0, ("invalid number of share modes: %d\n",
668                           lck->num_share_modes));
669                 smb_panic("parse_share_modes: invalid number of share modes");
670         }
671
672         lck->share_modes = NULL;
673         
674         if (lck->num_share_modes != 0) {
675
676                 if (dbuf.dsize < (sizeof(struct locking_data) +
677                                   (lck->num_share_modes *
678                                    sizeof(struct share_mode_entry)))) {
679                         smb_panic("parse_share_modes: buffer too short");
680                 }
681                                   
682                 lck->share_modes = (struct share_mode_entry *)
683                         TALLOC_MEMDUP(lck,
684                                       dbuf.dptr+sizeof(struct locking_data),
685                                       lck->num_share_modes *
686                                       sizeof(struct share_mode_entry));
687
688                 if (lck->share_modes == NULL) {
689                         smb_panic("parse_share_modes: talloc failed");
690                 }
691         }
692
693         /* Get any delete tokens. */
694         delete_tokens_size = parse_delete_tokens_list(lck, &data, dbuf);
695         if (delete_tokens_size < 0) {
696                 smb_panic("parse_share_modes: parse_delete_tokens_list failed");
697         }
698
699         /* Save off the associated service path and filename. */
700         lck->servicepath = (const char *)dbuf.dptr + sizeof(struct locking_data) +
701                 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
702                 delete_tokens_size;
703
704         lck->base_name = (const char *)dbuf.dptr + sizeof(struct locking_data) +
705                 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
706                 delete_tokens_size +
707                 strlen(lck->servicepath) + 1;
708
709         lck->stream_name = (const char *)dbuf.dptr + sizeof(struct locking_data) +
710                 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
711                 delete_tokens_size +
712                 strlen(lck->servicepath) + 1 +
713                 strlen(lck->base_name) + 1;
714
715         /*
716          * Ensure that each entry has a real process attached.
717          */
718
719         for (i = 0; i < lck->num_share_modes; i++) {
720                 struct share_mode_entry *entry_p = &lck->share_modes[i];
721                 char *str = NULL;
722                 if (DEBUGLEVEL >= 10) {
723                         str = share_mode_str(NULL, i, entry_p);
724                 }
725                 DEBUG(10,("parse_share_modes: %s\n",
726                         str ? str : ""));
727                 if (!serverid_exists(&entry_p->pid)) {
728                         DEBUG(10,("parse_share_modes: deleted %s\n",
729                                 str ? str : ""));
730                         entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
731                         lck->modified = True;
732                 }
733                 TALLOC_FREE(str);
734         }
735
736         return True;
737 }
738
739 static TDB_DATA unparse_share_modes(const struct share_mode_lock *lck)
740 {
741         TDB_DATA result;
742         int num_valid = 0;
743         int i;
744         struct locking_data *data;
745         ssize_t offset;
746         ssize_t sp_len, bn_len, sn_len;
747         uint32_t delete_tokens_size = 0;
748         struct delete_token_list *pdtl = NULL;
749         uint32_t num_delete_token_entries = 0;
750
751         result.dptr = NULL;
752         result.dsize = 0;
753
754         for (i=0; i<lck->num_share_modes; i++) {
755                 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
756                         num_valid += 1;
757                 }
758         }
759
760         if (num_valid == 0) {
761                 return result;
762         }
763
764         sp_len = strlen(lck->servicepath);
765         bn_len = strlen(lck->base_name);
766         sn_len = lck->stream_name != NULL ? strlen(lck->stream_name) : 0;
767
768         for (pdtl = lck->delete_tokens; pdtl; pdtl = pdtl->next) {
769                 num_delete_token_entries++;
770                 delete_tokens_size += (sizeof(uint32_t) +
771                                 sizeof(uint32_t) +
772                                 sizeof(uid_t) +
773                                 sizeof(gid_t) +
774                                 pdtl->delete_token->ngroups*sizeof(gid_t));
775         }
776
777         result.dsize = sizeof(*data) +
778                 lck->num_share_modes * sizeof(struct share_mode_entry) +
779                 delete_tokens_size +
780                 sp_len + 1 +
781                 bn_len + 1 +
782                 sn_len + 1;
783         result.dptr = TALLOC_ARRAY(lck, uint8, result.dsize);
784
785         if (result.dptr == NULL) {
786                 smb_panic("talloc failed");
787         }
788
789         data = (struct locking_data *)result.dptr;
790         ZERO_STRUCTP(data);
791         data->u.s.num_share_mode_entries = lck->num_share_modes;
792         data->u.s.old_write_time = lck->old_write_time;
793         data->u.s.changed_write_time = lck->changed_write_time;
794         data->u.s.num_delete_token_entries = num_delete_token_entries;
795
796         DEBUG(10,("unparse_share_modes: owrt: %s cwrt: %s, ntok: %u, "
797                   "num: %d\n",
798                   timestring(talloc_tos(),
799                              convert_timespec_to_time_t(lck->old_write_time)),
800                   timestring(talloc_tos(),
801                              convert_timespec_to_time_t(
802                                      lck->changed_write_time)),
803                   (unsigned int)data->u.s.num_delete_token_entries,
804                   data->u.s.num_share_mode_entries));
805
806         memcpy(result.dptr + sizeof(*data), lck->share_modes,
807                sizeof(struct share_mode_entry)*lck->num_share_modes);
808         offset = sizeof(*data) +
809                 sizeof(struct share_mode_entry)*lck->num_share_modes;
810
811         /* Store any delete on close tokens. */
812         for (pdtl = lck->delete_tokens; pdtl; pdtl = pdtl->next) {
813                 struct security_unix_token *pdt = pdtl->delete_token;
814                 uint32_t token_size = sizeof(uint32_t) +
815                                         sizeof(uint32_t) +
816                                         sizeof(uid_t) +
817                                         sizeof(gid_t) +
818                                         (pdt->ngroups * sizeof(gid_t));
819                 uint8_t *p = result.dptr + offset;
820
821                 memcpy(p, &token_size, sizeof(uint32_t));
822                 p += sizeof(uint32_t);
823
824                 memcpy(p, &pdtl->name_hash, sizeof(uint32_t));
825                 p += sizeof(uint32_t);
826
827                 memcpy(p, &pdt->uid, sizeof(uid_t));
828                 p += sizeof(uid_t);
829
830                 memcpy(p, &pdt->gid, sizeof(gid_t));
831                 p += sizeof(gid_t);
832
833                 for (i = 0; i < pdt->ngroups; i++) {
834                         memcpy(p, &pdt->groups[i], sizeof(gid_t));
835                         p += sizeof(gid_t);
836                 }
837                 offset += token_size;
838         }
839
840         safe_strcpy((char *)result.dptr + offset, lck->servicepath,
841                     result.dsize - offset - 1);
842         offset += sp_len + 1;
843         safe_strcpy((char *)result.dptr + offset, lck->base_name,
844                     result.dsize - offset - 1);
845         offset += bn_len + 1;
846         safe_strcpy((char *)result.dptr + offset, lck->stream_name,
847                     result.dsize - offset - 1);
848
849         if (DEBUGLEVEL >= 10) {
850                 print_share_mode_table(data);
851         }
852
853         return result;
854 }
855
856 static int share_mode_lock_destructor(struct share_mode_lock *lck)
857 {
858         NTSTATUS status;
859         TDB_DATA data;
860
861         if (!lck->modified) {
862                 return 0;
863         }
864
865         data = unparse_share_modes(lck);
866
867         if (data.dptr == NULL) {
868                 if (!lck->fresh) {
869                         /* There has been an entry before, delete it */
870
871                         status = lck->record->delete_rec(lck->record);
872                         if (!NT_STATUS_IS_OK(status)) {
873                                 char *errmsg;
874
875                                 DEBUG(0, ("delete_rec returned %s\n",
876                                           nt_errstr(status)));
877
878                                 if (asprintf(&errmsg, "could not delete share "
879                                              "entry: %s\n",
880                                              nt_errstr(status)) == -1) {
881                                         smb_panic("could not delete share"
882                                                   "entry");
883                                 }
884                                 smb_panic(errmsg);
885                         }
886                 }
887                 goto done;
888         }
889
890         status = lck->record->store(lck->record, data, TDB_REPLACE);
891         if (!NT_STATUS_IS_OK(status)) {
892                 char *errmsg;
893
894                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
895
896                 if (asprintf(&errmsg, "could not store share mode entry: %s",
897                              nt_errstr(status)) == -1) {
898                         smb_panic("could not store share mode entry");
899                 }
900                 smb_panic(errmsg);
901         }
902
903  done:
904
905         return 0;
906 }
907
908 static bool fill_share_mode_lock(struct share_mode_lock *lck,
909                                  struct file_id id,
910                                  const char *servicepath,
911                                  const struct smb_filename *smb_fname,
912                                  TDB_DATA share_mode_data,
913                                  const struct timespec *old_write_time)
914 {
915         /* Ensure we set every field here as the destructor must be
916            valid even if parse_share_modes fails. */
917
918         lck->servicepath = NULL;
919         lck->base_name = NULL;
920         lck->stream_name = NULL;
921         lck->id = id;
922         lck->num_share_modes = 0;
923         lck->share_modes = NULL;
924         lck->delete_tokens = NULL;
925         ZERO_STRUCT(lck->old_write_time);
926         ZERO_STRUCT(lck->changed_write_time);
927         lck->fresh = False;
928         lck->modified = False;
929
930         lck->fresh = (share_mode_data.dptr == NULL);
931
932         if (lck->fresh) {
933                 bool has_stream;
934                 if (smb_fname == NULL || servicepath == NULL
935                     || old_write_time == NULL) {
936                         return False;
937                 }
938
939                 has_stream = smb_fname->stream_name != NULL;
940
941                 lck->base_name = talloc_strdup(lck, smb_fname->base_name);
942                 lck->stream_name = talloc_strdup(lck, smb_fname->stream_name);
943                 lck->servicepath = talloc_strdup(lck, servicepath);
944                 if (lck->base_name == NULL ||
945                     (has_stream && lck->stream_name == NULL) ||
946                     lck->servicepath == NULL) {
947                         DEBUG(0, ("talloc failed\n"));
948                         return False;
949                 }
950                 lck->old_write_time = *old_write_time;
951         } else {
952                 if (!parse_share_modes(share_mode_data, lck)) {
953                         DEBUG(0, ("Could not parse share modes\n"));
954                         return False;
955                 }
956         }
957
958         return True;
959 }
960
961 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
962                                             const struct file_id id,
963                                             const char *servicepath,
964                                             const struct smb_filename *smb_fname,
965                                             const struct timespec *old_write_time)
966 {
967         struct share_mode_lock *lck;
968         struct file_id tmp;
969         TDB_DATA key = locking_key(&id, &tmp);
970
971         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
972                 DEBUG(0, ("talloc failed\n"));
973                 return NULL;
974         }
975
976         if (!(lck->record = lock_db->fetch_locked(lock_db, lck, key))) {
977                 DEBUG(3, ("Could not lock share entry\n"));
978                 TALLOC_FREE(lck);
979                 return NULL;
980         }
981
982         if (!fill_share_mode_lock(lck, id, servicepath, smb_fname,
983                                   lck->record->value, old_write_time)) {
984                 DEBUG(3, ("fill_share_mode_lock failed\n"));
985                 TALLOC_FREE(lck);
986                 return NULL;
987         }
988
989         talloc_set_destructor(lck, share_mode_lock_destructor);
990
991         return lck;
992 }
993
994 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
995                                                   const struct file_id id)
996 {
997         struct share_mode_lock *lck;
998         struct file_id tmp;
999         TDB_DATA key = locking_key(&id, &tmp);
1000         TDB_DATA data;
1001
1002         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
1003                 DEBUG(0, ("talloc failed\n"));
1004                 return NULL;
1005         }
1006
1007         if (lock_db->fetch(lock_db, lck, key, &data) == -1) {
1008                 DEBUG(3, ("Could not fetch share entry\n"));
1009                 TALLOC_FREE(lck);
1010                 return NULL;
1011         }
1012
1013         if (!fill_share_mode_lock(lck, id, NULL, NULL, data, NULL)) {
1014                 DEBUG(10, ("fetch_share_mode_unlocked: no share_mode record "
1015                            "around (file not open)\n"));
1016                 TALLOC_FREE(lck);
1017                 return NULL;
1018         }
1019
1020         return lck;
1021 }
1022
1023 /*******************************************************************
1024  Sets the service name and filename for rename.
1025  At this point we emit "file renamed" messages to all
1026  process id's that have this file open.
1027  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
1028 ********************************************************************/
1029
1030 bool rename_share_filename(struct messaging_context *msg_ctx,
1031                         struct share_mode_lock *lck,
1032                         const char *servicepath,
1033                         uint32_t orig_name_hash,
1034                         uint32_t new_name_hash,
1035                         const struct smb_filename *smb_fname_dst)
1036 {
1037         size_t sp_len;
1038         size_t bn_len;
1039         size_t sn_len;
1040         size_t msg_len;
1041         char *frm = NULL;
1042         int i;
1043         bool strip_two_chars = false;
1044         bool has_stream = smb_fname_dst->stream_name != NULL;
1045
1046         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
1047                    servicepath, smb_fname_dst->base_name));
1048
1049         /*
1050          * rename_internal_fsp() and rename_internals() add './' to
1051          * head of newname if newname does not contain a '/'.
1052          */
1053         if (smb_fname_dst->base_name[0] &&
1054             smb_fname_dst->base_name[1] &&
1055             smb_fname_dst->base_name[0] == '.' &&
1056             smb_fname_dst->base_name[1] == '/') {
1057                 strip_two_chars = true;
1058         }
1059
1060         lck->servicepath = talloc_strdup(lck, servicepath);
1061         lck->base_name = talloc_strdup(lck, smb_fname_dst->base_name +
1062                                        (strip_two_chars ? 2 : 0));
1063         lck->stream_name = talloc_strdup(lck, smb_fname_dst->stream_name);
1064         if (lck->base_name == NULL ||
1065             (has_stream && lck->stream_name == NULL) ||
1066             lck->servicepath == NULL) {
1067                 DEBUG(0, ("rename_share_filename: talloc failed\n"));
1068                 return False;
1069         }
1070         lck->modified = True;
1071
1072         sp_len = strlen(lck->servicepath);
1073         bn_len = strlen(lck->base_name);
1074         sn_len = has_stream ? strlen(lck->stream_name) : 0;
1075
1076         msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + bn_len + 1 +
1077             sn_len + 1;
1078
1079         /* Set up the name changed message. */
1080         frm = TALLOC_ARRAY(lck, char, msg_len);
1081         if (!frm) {
1082                 return False;
1083         }
1084
1085         push_file_id_24(frm, &lck->id);
1086
1087         DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
1088
1089         safe_strcpy(&frm[24], lck->servicepath, sp_len);
1090         safe_strcpy(&frm[24 + sp_len + 1], lck->base_name, bn_len);
1091         safe_strcpy(&frm[24 + sp_len + 1 + bn_len + 1], lck->stream_name,
1092                     sn_len);
1093
1094         /* Send the messages. */
1095         for (i=0; i<lck->num_share_modes; i++) {
1096                 struct share_mode_entry *se = &lck->share_modes[i];
1097                 if (!is_valid_share_mode_entry(se)) {
1098                         continue;
1099                 }
1100
1101                 /* If this is a hardlink to the inode
1102                    with a different name, skip this. */
1103                 if (se->name_hash != orig_name_hash) {
1104                         continue;
1105                 }
1106
1107                 se->name_hash = new_name_hash;
1108
1109                 /* But not to ourselves... */
1110                 if (procid_is_me(&se->pid)) {
1111                         continue;
1112                 }
1113
1114                 DEBUG(10,("rename_share_filename: sending rename message to "
1115                           "pid %s file_id %s sharepath %s base_name %s "
1116                           "stream_name %s\n",
1117                           procid_str_static(&se->pid),
1118                           file_id_string_tos(&lck->id),
1119                           lck->servicepath, lck->base_name,
1120                         has_stream ? lck->stream_name : ""));
1121
1122                 messaging_send_buf(msg_ctx, se->pid, MSG_SMB_FILE_RENAME,
1123                                    (uint8 *)frm, msg_len);
1124         }
1125
1126         return True;
1127 }
1128
1129 void get_file_infos(struct file_id id,
1130                     uint32_t name_hash,
1131                     bool *delete_on_close,
1132                     struct timespec *write_time)
1133 {
1134         struct share_mode_lock *lck;
1135
1136         if (delete_on_close) {
1137                 *delete_on_close = false;
1138         }
1139
1140         if (write_time) {
1141                 ZERO_STRUCTP(write_time);
1142         }
1143
1144         if (!(lck = fetch_share_mode_unlocked(talloc_tos(), id))) {
1145                 return;
1146         }
1147
1148         if (delete_on_close) {
1149                 *delete_on_close = is_delete_on_close_set(lck, name_hash);
1150         }
1151
1152         if (write_time) {
1153                 struct timespec wt;
1154
1155                 wt = lck->changed_write_time;
1156                 if (null_timespec(wt)) {
1157                         wt = lck->old_write_time;
1158                 }
1159
1160                 *write_time = wt;
1161         }
1162
1163         TALLOC_FREE(lck);
1164 }
1165
1166 bool is_valid_share_mode_entry(const struct share_mode_entry *e)
1167 {
1168         int num_props = 0;
1169
1170         if (e->op_type == UNUSED_SHARE_MODE_ENTRY) {
1171                 /* cope with dead entries from the process not
1172                    existing. These should not be considered valid,
1173                    otherwise we end up doing zero timeout sharing
1174                    violation */
1175                 return False;
1176         }
1177
1178         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
1179         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1180         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1181
1182         SMB_ASSERT(num_props <= 1);
1183         return (num_props != 0);
1184 }
1185
1186 bool is_deferred_open_entry(const struct share_mode_entry *e)
1187 {
1188         return (e->op_type == DEFERRED_OPEN_ENTRY);
1189 }
1190
1191 bool is_unused_share_mode_entry(const struct share_mode_entry *e)
1192 {
1193         return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
1194 }
1195
1196 /*******************************************************************
1197  Fill a share mode entry.
1198 ********************************************************************/
1199
1200 static void fill_share_mode_entry(struct share_mode_entry *e,
1201                                   files_struct *fsp,
1202                                   uid_t uid, uint64_t mid, uint16 op_type)
1203 {
1204         ZERO_STRUCTP(e);
1205         e->pid = sconn_server_id(fsp->conn->sconn);
1206         e->share_access = fsp->share_access;
1207         e->private_options = fsp->fh->private_options;
1208         e->access_mask = fsp->access_mask;
1209         e->op_mid = mid;
1210         e->op_type = op_type;
1211         e->time.tv_sec = fsp->open_time.tv_sec;
1212         e->time.tv_usec = fsp->open_time.tv_usec;
1213         e->id = fsp->file_id;
1214         e->share_file_id = fsp->fh->gen_id;
1215         e->uid = (uint32)uid;
1216         e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
1217         e->name_hash = fsp->name_hash;
1218 }
1219
1220 static void fill_deferred_open_entry(struct share_mode_entry *e,
1221                                      const struct timeval request_time,
1222                                      struct file_id id,
1223                                      struct server_id pid,
1224                                      uint64_t mid)
1225 {
1226         ZERO_STRUCTP(e);
1227         e->pid = pid;
1228         e->op_mid = mid;
1229         e->op_type = DEFERRED_OPEN_ENTRY;
1230         e->time.tv_sec = request_time.tv_sec;
1231         e->time.tv_usec = request_time.tv_usec;
1232         e->id = id;
1233         e->uid = (uint32)-1;
1234         e->flags = 0;
1235 }
1236
1237 static void add_share_mode_entry(struct share_mode_lock *lck,
1238                                  const struct share_mode_entry *entry)
1239 {
1240         int i;
1241
1242         for (i=0; i<lck->num_share_modes; i++) {
1243                 struct share_mode_entry *e = &lck->share_modes[i];
1244                 if (is_unused_share_mode_entry(e)) {
1245                         *e = *entry;
1246                         break;
1247                 }
1248         }
1249
1250         if (i == lck->num_share_modes) {
1251                 /* No unused entry found */
1252                 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
1253                              &lck->share_modes, &lck->num_share_modes);
1254         }
1255         lck->modified = True;
1256 }
1257
1258 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
1259                     uid_t uid, uint64_t mid, uint16 op_type)
1260 {
1261         struct share_mode_entry entry;
1262         fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1263         add_share_mode_entry(lck, &entry);
1264 }
1265
1266 void add_deferred_open(struct share_mode_lock *lck, uint64_t mid,
1267                        struct timeval request_time,
1268                        struct server_id pid, struct file_id id)
1269 {
1270         struct share_mode_entry entry;
1271         fill_deferred_open_entry(&entry, request_time, id, pid, mid);
1272         add_share_mode_entry(lck, &entry);
1273 }
1274
1275 /*******************************************************************
1276  Check if two share mode entries are identical, ignoring oplock 
1277  and mid info and desired_access. (Removed paranoia test - it's
1278  not automatically a logic error if they are identical. JRA.)
1279 ********************************************************************/
1280
1281 static bool share_modes_identical(struct share_mode_entry *e1,
1282                                   struct share_mode_entry *e2)
1283 {
1284         /* We used to check for e1->share_access == e2->share_access here
1285            as well as the other fields but 2 different DOS or FCB opens
1286            sharing the same share mode entry may validly differ in
1287            fsp->share_access field. */
1288
1289         return (procid_equal(&e1->pid, &e2->pid) &&
1290                 file_id_equal(&e1->id, &e2->id) &&
1291                 e1->share_file_id == e2->share_file_id );
1292 }
1293
1294 static bool deferred_open_identical(struct share_mode_entry *e1,
1295                                     struct share_mode_entry *e2)
1296 {
1297         return (procid_equal(&e1->pid, &e2->pid) &&
1298                 (e1->op_mid == e2->op_mid) &&
1299                 file_id_equal(&e1->id, &e2->id));
1300 }
1301
1302 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1303                                                       struct share_mode_entry *entry)
1304 {
1305         int i;
1306
1307         for (i=0; i<lck->num_share_modes; i++) {
1308                 struct share_mode_entry *e = &lck->share_modes[i];
1309                 if (is_valid_share_mode_entry(entry) &&
1310                     is_valid_share_mode_entry(e) &&
1311                     share_modes_identical(e, entry)) {
1312                         return e;
1313                 }
1314                 if (is_deferred_open_entry(entry) &&
1315                     is_deferred_open_entry(e) &&
1316                     deferred_open_identical(e, entry)) {
1317                         return e;
1318                 }
1319         }
1320         return NULL;
1321 }
1322
1323 /*******************************************************************
1324  Del the share mode of a file for this process. Return the number of
1325  entries left.
1326 ********************************************************************/
1327
1328 bool del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1329 {
1330         struct share_mode_entry entry, *e;
1331
1332         /* Don't care about the pid owner being correct here - just a search. */
1333         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1334
1335         e = find_share_mode_entry(lck, &entry);
1336         if (e == NULL) {
1337                 return False;
1338         }
1339
1340         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1341         lck->modified = True;
1342         return True;
1343 }
1344
1345 void del_deferred_open_entry(struct share_mode_lock *lck, uint64_t mid,
1346                              struct server_id pid)
1347 {
1348         struct share_mode_entry entry, *e;
1349
1350         fill_deferred_open_entry(&entry, timeval_zero(),
1351                                  lck->id, pid, mid);
1352
1353         e = find_share_mode_entry(lck, &entry);
1354         if (e == NULL) {
1355                 return;
1356         }
1357
1358         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1359         lck->modified = True;
1360 }
1361
1362 /*******************************************************************
1363  Remove an oplock mid and mode entry from a share mode.
1364 ********************************************************************/
1365
1366 bool remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1367 {
1368         struct share_mode_entry entry, *e;
1369
1370         /* Don't care about the pid owner being correct here - just a search. */
1371         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1372
1373         e = find_share_mode_entry(lck, &entry);
1374         if (e == NULL) {
1375                 return False;
1376         }
1377
1378         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1379                 /*
1380                  * Going from exclusive or batch,
1381                  * we always go through FAKE_LEVEL_II
1382                  * first.
1383                  */
1384                 e->op_type = FAKE_LEVEL_II_OPLOCK;
1385         } else {
1386                 e->op_type = NO_OPLOCK;
1387         }
1388         lck->modified = True;
1389         return True;
1390 }
1391
1392 /*******************************************************************
1393  Downgrade a oplock type from exclusive to level II.
1394 ********************************************************************/
1395
1396 bool downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1397 {
1398         struct share_mode_entry entry, *e;
1399
1400         /* Don't care about the pid owner being correct here - just a search. */
1401         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1402
1403         e = find_share_mode_entry(lck, &entry);
1404         if (e == NULL) {
1405                 return False;
1406         }
1407
1408         e->op_type = LEVEL_II_OPLOCK;
1409         lck->modified = True;
1410         return True;
1411 }
1412
1413 /****************************************************************************
1414  Check if setting delete on close is allowed on this fsp.
1415 ****************************************************************************/
1416
1417 NTSTATUS can_set_delete_on_close(files_struct *fsp, uint32 dosmode)
1418 {
1419         /*
1420          * Only allow delete on close for writable files.
1421          */
1422
1423         if ((dosmode & aRONLY) &&
1424             !lp_delete_readonly(SNUM(fsp->conn))) {
1425                 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1426                           "flag set but file attribute is readonly.\n",
1427                           fsp_str_dbg(fsp)));
1428                 return NT_STATUS_CANNOT_DELETE;
1429         }
1430
1431         /*
1432          * Only allow delete on close for writable shares.
1433          */
1434
1435         if (!CAN_WRITE(fsp->conn)) {
1436                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1437                           "close flag set but write access denied on share.\n",
1438                           fsp_str_dbg(fsp)));
1439                 return NT_STATUS_ACCESS_DENIED;
1440         }
1441
1442         /*
1443          * Only allow delete on close for files/directories opened with delete
1444          * intent.
1445          */
1446
1447         if (!(fsp->access_mask & DELETE_ACCESS)) {
1448                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1449                           "close flag set but delete access denied.\n",
1450                           fsp_str_dbg(fsp)));
1451                 return NT_STATUS_ACCESS_DENIED;
1452         }
1453
1454         /* Don't allow delete on close for non-empty directories. */
1455         if (fsp->is_directory) {
1456                 SMB_ASSERT(!is_ntfs_stream_smb_fname(fsp->fsp_name));
1457                 return can_delete_directory(fsp->conn,
1458                                             fsp->fsp_name->base_name);
1459         }
1460
1461         return NT_STATUS_OK;
1462 }
1463
1464 /*************************************************************************
1465  Return a talloced copy of a struct security_unix_token. NULL on fail.
1466  (Should this be in locking.c.... ?).
1467 *************************************************************************/
1468
1469 static struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
1470 {
1471         struct security_unix_token *cpy;
1472
1473         cpy = TALLOC_P(ctx, struct security_unix_token);
1474         if (!cpy) {
1475                 return NULL;
1476         }
1477
1478         cpy->uid = tok->uid;
1479         cpy->gid = tok->gid;
1480         cpy->ngroups = tok->ngroups;
1481         if (tok->ngroups) {
1482                 /* Make this a talloc child of cpy. */
1483                 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1484                 if (!cpy->groups) {
1485                         return NULL;
1486                 }
1487                 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1488         }
1489         return cpy;
1490 }
1491
1492 /****************************************************************************
1493  Adds a delete on close token.
1494 ****************************************************************************/
1495
1496 static bool add_delete_on_close_token(struct share_mode_lock *lck,
1497                         uint32_t name_hash,
1498                         const struct security_unix_token *tok)
1499 {
1500         struct delete_token_list *dtl;
1501
1502         dtl = TALLOC_ZERO_P(lck, struct delete_token_list);
1503         if (dtl == NULL) {
1504                 return false;
1505         }
1506
1507         dtl->name_hash = name_hash;
1508         dtl->delete_token = copy_unix_token(lck, tok);
1509         if (dtl->delete_token == NULL) {
1510                 TALLOC_FREE(dtl);
1511                 return false;
1512         }
1513         DLIST_ADD(lck->delete_tokens, dtl);
1514         lck->modified = true;
1515         return true;
1516 }
1517
1518 /****************************************************************************
1519  Sets the delete on close flag over all share modes on this file.
1520  Modify the share mode entry for all files open
1521  on this device and inode to tell other smbds we have
1522  changed the delete on close flag. This will be noticed
1523  in the close code, the last closer will delete the file
1524  if flag is set.
1525  This makes a copy of any struct security_unix_token into the
1526  lck entry. This function is used when the lock is already granted.
1527 ****************************************************************************/
1528
1529 void set_delete_on_close_lck(files_struct *fsp,
1530                         struct share_mode_lock *lck,
1531                         bool delete_on_close,
1532                         const struct security_unix_token *tok)
1533 {
1534         struct delete_token_list *dtl;
1535         bool ret;
1536
1537         if (delete_on_close) {
1538                 SMB_ASSERT(tok != NULL);
1539         } else {
1540                 SMB_ASSERT(tok == NULL);
1541         }
1542
1543         for (dtl = lck->delete_tokens; dtl; dtl = dtl->next) {
1544                 if (dtl->name_hash == fsp->name_hash) {
1545                         lck->modified = true;
1546                         if (delete_on_close == false) {
1547                                 /* Delete this entry. */
1548                                 DLIST_REMOVE(lck->delete_tokens, dtl);
1549                                 TALLOC_FREE(dtl);
1550                                 return;
1551                         }
1552                         /* Replace this token with the
1553                            given tok. */
1554                         TALLOC_FREE(dtl->delete_token);
1555                         dtl->delete_token = copy_unix_token(dtl, tok);
1556                         SMB_ASSERT(dtl->delete_token != NULL);
1557                 }
1558         }
1559
1560         if (!delete_on_close) {
1561                 /* Nothing to delete - not found. */
1562                 return;
1563         }
1564
1565         ret = add_delete_on_close_token(lck, fsp->name_hash, tok);
1566         SMB_ASSERT(ret);
1567 }
1568
1569 bool set_delete_on_close(files_struct *fsp, bool delete_on_close, const struct security_unix_token *tok)
1570 {
1571         struct share_mode_lock *lck;
1572         
1573         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1574                   "fnum = %d, file %s\n",
1575                   delete_on_close ? "Adding" : "Removing", fsp->fnum,
1576                   fsp_str_dbg(fsp)));
1577
1578         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
1579                                   NULL);
1580         if (lck == NULL) {
1581                 return False;
1582         }
1583
1584         set_delete_on_close_lck(fsp, lck, delete_on_close,
1585                         delete_on_close ? tok : NULL);
1586
1587         if (fsp->is_directory) {
1588                 SMB_ASSERT(!is_ntfs_stream_smb_fname(fsp->fsp_name));
1589                 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1590                                                fsp->fsp_name->base_name);
1591         }
1592
1593         TALLOC_FREE(lck);
1594
1595         fsp->delete_on_close = delete_on_close;
1596
1597         return True;
1598 }
1599
1600 const struct security_unix_token *get_delete_on_close_token(struct share_mode_lock *lck, uint32_t name_hash)
1601 {
1602         struct delete_token_list *dtl;
1603
1604         DEBUG(10,("get_delete_on_close_token: name_hash = 0x%x\n",
1605                         (unsigned int)name_hash ));
1606
1607         for (dtl = lck->delete_tokens; dtl; dtl = dtl->next) {
1608                 DEBUG(10,("get_delete_on_close_token: dtl->name_hash = 0x%x\n",
1609                                 (unsigned int)dtl->name_hash ));
1610                 if (dtl->name_hash == name_hash) {
1611                         return dtl->delete_token;
1612                 }
1613         }
1614         return NULL;
1615 }
1616
1617 bool is_delete_on_close_set(struct share_mode_lock *lck, uint32_t name_hash)
1618 {
1619         return (get_delete_on_close_token(lck, name_hash) != NULL);
1620 }
1621
1622 bool set_sticky_write_time(struct file_id fileid, struct timespec write_time)
1623 {
1624         struct share_mode_lock *lck;
1625
1626         DEBUG(5,("set_sticky_write_time: %s id=%s\n",
1627                  timestring(talloc_tos(),
1628                             convert_timespec_to_time_t(write_time)),
1629                  file_id_string_tos(&fileid)));
1630
1631         lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1632         if (lck == NULL) {
1633                 return False;
1634         }
1635
1636         if (timespec_compare(&lck->changed_write_time, &write_time) != 0) {
1637                 lck->modified = True;
1638                 lck->changed_write_time = write_time;
1639         }
1640
1641         TALLOC_FREE(lck);
1642         return True;
1643 }
1644
1645 bool set_write_time(struct file_id fileid, struct timespec write_time)
1646 {
1647         struct share_mode_lock *lck;
1648
1649         DEBUG(5,("set_write_time: %s id=%s\n",
1650                  timestring(talloc_tos(),
1651                             convert_timespec_to_time_t(write_time)),
1652                  file_id_string_tos(&fileid)));
1653
1654         lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1655         if (lck == NULL) {
1656                 return False;
1657         }
1658
1659         if (timespec_compare(&lck->old_write_time, &write_time) != 0) {
1660                 lck->modified = True;
1661                 lck->old_write_time = write_time;
1662         }
1663
1664         TALLOC_FREE(lck);
1665         return True;
1666 }
1667
1668
1669 struct forall_state {
1670         void (*fn)(const struct share_mode_entry *entry,
1671                    const char *sharepath,
1672                    const char *fname,
1673                    void *private_data);
1674         void *private_data;
1675 };
1676
1677 static int traverse_fn(struct db_record *rec, void *_state)
1678 {
1679         struct forall_state *state = (struct forall_state *)_state;
1680         struct locking_data *data;
1681         struct share_mode_entry *shares;
1682         const char *sharepath;
1683         const char *fname;
1684         const char *del_tokens;
1685         uint32_t total_del_token_size = 0;
1686         int i;
1687
1688         /* Ensure this is a locking_key record. */
1689         if (rec->key.dsize != sizeof(struct file_id))
1690                 return 0;
1691
1692         data = (struct locking_data *)rec->value.dptr;
1693         shares = (struct share_mode_entry *)(rec->value.dptr + sizeof(*data));
1694         del_tokens = (const char *)rec->value.dptr + sizeof(*data) +
1695                 data->u.s.num_share_mode_entries*sizeof(*shares);
1696
1697         for (i = 0; i < data->u.s.num_delete_token_entries; i++) {
1698                 uint32_t del_token_size;
1699                 memcpy(&del_token_size, del_tokens, sizeof(uint32_t));
1700                 total_del_token_size += del_token_size;
1701                 del_tokens += del_token_size;
1702         }
1703
1704         sharepath = (const char *)rec->value.dptr + sizeof(*data) +
1705                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1706                 total_del_token_size;
1707         fname = (const char *)rec->value.dptr + sizeof(*data) +
1708                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1709                 total_del_token_size +
1710                 strlen(sharepath) + 1;
1711
1712         for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1713                 state->fn(&shares[i], sharepath, fname,
1714                           state->private_data);
1715         }
1716         return 0;
1717 }
1718
1719 /*******************************************************************
1720  Call the specified function on each entry under management by the
1721  share mode system.
1722 ********************************************************************/
1723
1724 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1725                                  const char *, void *),
1726                       void *private_data)
1727 {
1728         struct forall_state state;
1729
1730         if (lock_db == NULL)
1731                 return 0;
1732
1733         state.fn = fn;
1734         state.private_data = private_data;
1735
1736         return lock_db->traverse_read(lock_db, traverse_fn, (void *)&state);
1737 }