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