Fix the only place we reply on the NULL handling for the source in safe_strcpy.
[kai/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 "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         strlcpy((char *)result.dptr + offset,
842                 lck->servicepath ? lck->servicepath : "",
843                 result.dsize - offset);
844         offset += sp_len + 1;
845         strlcpy((char *)result.dptr + offset,
846                 lck->base_name ? lck->base_name : "",
847                 result.dsize - offset);
848         offset += bn_len + 1;
849         strlcpy((char *)result.dptr + offset,
850                 lck->stream_name ? lck->stream_name : "",
851                 result.dsize - offset);
852
853         if (DEBUGLEVEL >= 10) {
854                 print_share_mode_table(data);
855         }
856
857         return result;
858 }
859
860 static int share_mode_lock_destructor(struct share_mode_lock *lck)
861 {
862         NTSTATUS status;
863         TDB_DATA data;
864
865         if (!lck->modified) {
866                 return 0;
867         }
868
869         data = unparse_share_modes(lck);
870
871         if (data.dptr == NULL) {
872                 if (!lck->fresh) {
873                         /* There has been an entry before, delete it */
874
875                         status = lck->record->delete_rec(lck->record);
876                         if (!NT_STATUS_IS_OK(status)) {
877                                 char *errmsg;
878
879                                 DEBUG(0, ("delete_rec returned %s\n",
880                                           nt_errstr(status)));
881
882                                 if (asprintf(&errmsg, "could not delete share "
883                                              "entry: %s\n",
884                                              nt_errstr(status)) == -1) {
885                                         smb_panic("could not delete share"
886                                                   "entry");
887                                 }
888                                 smb_panic(errmsg);
889                         }
890                 }
891                 goto done;
892         }
893
894         status = lck->record->store(lck->record, data, TDB_REPLACE);
895         if (!NT_STATUS_IS_OK(status)) {
896                 char *errmsg;
897
898                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
899
900                 if (asprintf(&errmsg, "could not store share mode entry: %s",
901                              nt_errstr(status)) == -1) {
902                         smb_panic("could not store share mode entry");
903                 }
904                 smb_panic(errmsg);
905         }
906
907  done:
908
909         return 0;
910 }
911
912 static bool fill_share_mode_lock(struct share_mode_lock *lck,
913                                  struct file_id id,
914                                  const char *servicepath,
915                                  const struct smb_filename *smb_fname,
916                                  TDB_DATA share_mode_data,
917                                  const struct timespec *old_write_time)
918 {
919         /* Ensure we set every field here as the destructor must be
920            valid even if parse_share_modes fails. */
921
922         lck->servicepath = NULL;
923         lck->base_name = NULL;
924         lck->stream_name = NULL;
925         lck->id = id;
926         lck->num_share_modes = 0;
927         lck->share_modes = NULL;
928         lck->delete_tokens = NULL;
929         ZERO_STRUCT(lck->old_write_time);
930         ZERO_STRUCT(lck->changed_write_time);
931         lck->fresh = False;
932         lck->modified = False;
933
934         lck->fresh = (share_mode_data.dptr == NULL);
935
936         if (lck->fresh) {
937                 bool has_stream;
938                 if (smb_fname == NULL || servicepath == NULL
939                     || old_write_time == NULL) {
940                         return False;
941                 }
942
943                 has_stream = smb_fname->stream_name != NULL;
944
945                 lck->base_name = talloc_strdup(lck, smb_fname->base_name);
946                 lck->stream_name = talloc_strdup(lck, smb_fname->stream_name);
947                 lck->servicepath = talloc_strdup(lck, servicepath);
948                 if (lck->base_name == NULL ||
949                     (has_stream && lck->stream_name == NULL) ||
950                     lck->servicepath == NULL) {
951                         DEBUG(0, ("talloc failed\n"));
952                         return False;
953                 }
954                 lck->old_write_time = *old_write_time;
955         } else {
956                 if (!parse_share_modes(share_mode_data, lck)) {
957                         DEBUG(0, ("Could not parse share modes\n"));
958                         return False;
959                 }
960         }
961
962         return True;
963 }
964
965 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
966                                             const struct file_id id,
967                                             const char *servicepath,
968                                             const struct smb_filename *smb_fname,
969                                             const struct timespec *old_write_time)
970 {
971         struct share_mode_lock *lck;
972         struct file_id tmp;
973         TDB_DATA key = locking_key(&id, &tmp);
974
975         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
976                 DEBUG(0, ("talloc failed\n"));
977                 return NULL;
978         }
979
980         if (!(lck->record = lock_db->fetch_locked(lock_db, lck, key))) {
981                 DEBUG(3, ("Could not lock share entry\n"));
982                 TALLOC_FREE(lck);
983                 return NULL;
984         }
985
986         if (!fill_share_mode_lock(lck, id, servicepath, smb_fname,
987                                   lck->record->value, old_write_time)) {
988                 DEBUG(3, ("fill_share_mode_lock failed\n"));
989                 TALLOC_FREE(lck);
990                 return NULL;
991         }
992
993         talloc_set_destructor(lck, share_mode_lock_destructor);
994
995         return lck;
996 }
997
998 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
999                                                   const struct file_id id)
1000 {
1001         struct share_mode_lock *lck;
1002         struct file_id tmp;
1003         TDB_DATA key = locking_key(&id, &tmp);
1004         TDB_DATA data;
1005
1006         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
1007                 DEBUG(0, ("talloc failed\n"));
1008                 return NULL;
1009         }
1010
1011         if (lock_db->fetch(lock_db, lck, key, &data) == -1) {
1012                 DEBUG(3, ("Could not fetch share entry\n"));
1013                 TALLOC_FREE(lck);
1014                 return NULL;
1015         }
1016
1017         if (!fill_share_mode_lock(lck, id, NULL, NULL, data, NULL)) {
1018                 DEBUG(10, ("fetch_share_mode_unlocked: no share_mode record "
1019                            "around (file not open)\n"));
1020                 TALLOC_FREE(lck);
1021                 return NULL;
1022         }
1023
1024         return lck;
1025 }
1026
1027 /*******************************************************************
1028  Sets the service name and filename for rename.
1029  At this point we emit "file renamed" messages to all
1030  process id's that have this file open.
1031  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
1032 ********************************************************************/
1033
1034 bool rename_share_filename(struct messaging_context *msg_ctx,
1035                         struct share_mode_lock *lck,
1036                         const char *servicepath,
1037                         uint32_t orig_name_hash,
1038                         uint32_t new_name_hash,
1039                         const struct smb_filename *smb_fname_dst)
1040 {
1041         size_t sp_len;
1042         size_t bn_len;
1043         size_t sn_len;
1044         size_t msg_len;
1045         char *frm = NULL;
1046         int i;
1047         bool strip_two_chars = false;
1048         bool has_stream = smb_fname_dst->stream_name != NULL;
1049
1050         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
1051                    servicepath, smb_fname_dst->base_name));
1052
1053         /*
1054          * rename_internal_fsp() and rename_internals() add './' to
1055          * head of newname if newname does not contain a '/'.
1056          */
1057         if (smb_fname_dst->base_name[0] &&
1058             smb_fname_dst->base_name[1] &&
1059             smb_fname_dst->base_name[0] == '.' &&
1060             smb_fname_dst->base_name[1] == '/') {
1061                 strip_two_chars = true;
1062         }
1063
1064         lck->servicepath = talloc_strdup(lck, servicepath);
1065         lck->base_name = talloc_strdup(lck, smb_fname_dst->base_name +
1066                                        (strip_two_chars ? 2 : 0));
1067         lck->stream_name = talloc_strdup(lck, smb_fname_dst->stream_name);
1068         if (lck->base_name == NULL ||
1069             (has_stream && lck->stream_name == NULL) ||
1070             lck->servicepath == NULL) {
1071                 DEBUG(0, ("rename_share_filename: talloc failed\n"));
1072                 return False;
1073         }
1074         lck->modified = True;
1075
1076         sp_len = strlen(lck->servicepath);
1077         bn_len = strlen(lck->base_name);
1078         sn_len = has_stream ? strlen(lck->stream_name) : 0;
1079
1080         msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + bn_len + 1 +
1081             sn_len + 1;
1082
1083         /* Set up the name changed message. */
1084         frm = TALLOC_ARRAY(lck, char, msg_len);
1085         if (!frm) {
1086                 return False;
1087         }
1088
1089         push_file_id_24(frm, &lck->id);
1090
1091         DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
1092
1093         strlcpy(&frm[24],
1094                 lck->servicepath ? lck->servicepath : "",
1095                 sp_len+1);
1096         strlcpy(&frm[24 + sp_len + 1],
1097                 lck->base_name ? lck->base_name : "",
1098                 bn_len+1);
1099         strlcpy(&frm[24 + sp_len + 1 + bn_len + 1],
1100                 lck->stream_name ? lck->stream_name : "",
1101                 sn_len+1);
1102
1103         /* Send the messages. */
1104         for (i=0; i<lck->num_share_modes; i++) {
1105                 struct share_mode_entry *se = &lck->share_modes[i];
1106                 if (!is_valid_share_mode_entry(se)) {
1107                         continue;
1108                 }
1109
1110                 /* If this is a hardlink to the inode
1111                    with a different name, skip this. */
1112                 if (se->name_hash != orig_name_hash) {
1113                         continue;
1114                 }
1115
1116                 se->name_hash = new_name_hash;
1117
1118                 /* But not to ourselves... */
1119                 if (procid_is_me(&se->pid)) {
1120                         continue;
1121                 }
1122
1123                 DEBUG(10,("rename_share_filename: sending rename message to "
1124                           "pid %s file_id %s sharepath %s base_name %s "
1125                           "stream_name %s\n",
1126                           procid_str_static(&se->pid),
1127                           file_id_string_tos(&lck->id),
1128                           lck->servicepath, lck->base_name,
1129                         has_stream ? lck->stream_name : ""));
1130
1131                 messaging_send_buf(msg_ctx, se->pid, MSG_SMB_FILE_RENAME,
1132                                    (uint8 *)frm, msg_len);
1133         }
1134
1135         return True;
1136 }
1137
1138 void get_file_infos(struct file_id id,
1139                     uint32_t name_hash,
1140                     bool *delete_on_close,
1141                     struct timespec *write_time)
1142 {
1143         struct share_mode_lock *lck;
1144
1145         if (delete_on_close) {
1146                 *delete_on_close = false;
1147         }
1148
1149         if (write_time) {
1150                 ZERO_STRUCTP(write_time);
1151         }
1152
1153         if (!(lck = fetch_share_mode_unlocked(talloc_tos(), id))) {
1154                 return;
1155         }
1156
1157         if (delete_on_close) {
1158                 *delete_on_close = is_delete_on_close_set(lck, name_hash);
1159         }
1160
1161         if (write_time) {
1162                 struct timespec wt;
1163
1164                 wt = lck->changed_write_time;
1165                 if (null_timespec(wt)) {
1166                         wt = lck->old_write_time;
1167                 }
1168
1169                 *write_time = wt;
1170         }
1171
1172         TALLOC_FREE(lck);
1173 }
1174
1175 bool is_valid_share_mode_entry(const struct share_mode_entry *e)
1176 {
1177         int num_props = 0;
1178
1179         if (e->op_type == UNUSED_SHARE_MODE_ENTRY) {
1180                 /* cope with dead entries from the process not
1181                    existing. These should not be considered valid,
1182                    otherwise we end up doing zero timeout sharing
1183                    violation */
1184                 return False;
1185         }
1186
1187         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
1188         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1189         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1190
1191         SMB_ASSERT(num_props <= 1);
1192         return (num_props != 0);
1193 }
1194
1195 bool is_deferred_open_entry(const struct share_mode_entry *e)
1196 {
1197         return (e->op_type == DEFERRED_OPEN_ENTRY);
1198 }
1199
1200 bool is_unused_share_mode_entry(const struct share_mode_entry *e)
1201 {
1202         return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
1203 }
1204
1205 /*******************************************************************
1206  Fill a share mode entry.
1207 ********************************************************************/
1208
1209 static void fill_share_mode_entry(struct share_mode_entry *e,
1210                                   files_struct *fsp,
1211                                   uid_t uid, uint64_t mid, uint16 op_type)
1212 {
1213         ZERO_STRUCTP(e);
1214         e->pid = sconn_server_id(fsp->conn->sconn);
1215         e->share_access = fsp->share_access;
1216         e->private_options = fsp->fh->private_options;
1217         e->access_mask = fsp->access_mask;
1218         e->op_mid = mid;
1219         e->op_type = op_type;
1220         e->time.tv_sec = fsp->open_time.tv_sec;
1221         e->time.tv_usec = fsp->open_time.tv_usec;
1222         e->id = fsp->file_id;
1223         e->share_file_id = fsp->fh->gen_id;
1224         e->uid = (uint32)uid;
1225         e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
1226         e->name_hash = fsp->name_hash;
1227 }
1228
1229 static void fill_deferred_open_entry(struct share_mode_entry *e,
1230                                      const struct timeval request_time,
1231                                      struct file_id id,
1232                                      struct server_id pid,
1233                                      uint64_t mid)
1234 {
1235         ZERO_STRUCTP(e);
1236         e->pid = pid;
1237         e->op_mid = mid;
1238         e->op_type = DEFERRED_OPEN_ENTRY;
1239         e->time.tv_sec = request_time.tv_sec;
1240         e->time.tv_usec = request_time.tv_usec;
1241         e->id = id;
1242         e->uid = (uint32)-1;
1243         e->flags = 0;
1244 }
1245
1246 static void add_share_mode_entry(struct share_mode_lock *lck,
1247                                  const struct share_mode_entry *entry)
1248 {
1249         int i;
1250
1251         for (i=0; i<lck->num_share_modes; i++) {
1252                 struct share_mode_entry *e = &lck->share_modes[i];
1253                 if (is_unused_share_mode_entry(e)) {
1254                         *e = *entry;
1255                         break;
1256                 }
1257         }
1258
1259         if (i == lck->num_share_modes) {
1260                 /* No unused entry found */
1261                 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
1262                              &lck->share_modes, &lck->num_share_modes);
1263         }
1264         lck->modified = True;
1265 }
1266
1267 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
1268                     uid_t uid, uint64_t mid, uint16 op_type)
1269 {
1270         struct share_mode_entry entry;
1271         fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1272         add_share_mode_entry(lck, &entry);
1273 }
1274
1275 void add_deferred_open(struct share_mode_lock *lck, uint64_t mid,
1276                        struct timeval request_time,
1277                        struct server_id pid, struct file_id id)
1278 {
1279         struct share_mode_entry entry;
1280         fill_deferred_open_entry(&entry, request_time, id, pid, mid);
1281         add_share_mode_entry(lck, &entry);
1282 }
1283
1284 /*******************************************************************
1285  Check if two share mode entries are identical, ignoring oplock 
1286  and mid info and desired_access. (Removed paranoia test - it's
1287  not automatically a logic error if they are identical. JRA.)
1288 ********************************************************************/
1289
1290 static bool share_modes_identical(struct share_mode_entry *e1,
1291                                   struct share_mode_entry *e2)
1292 {
1293         /* We used to check for e1->share_access == e2->share_access here
1294            as well as the other fields but 2 different DOS or FCB opens
1295            sharing the same share mode entry may validly differ in
1296            fsp->share_access field. */
1297
1298         return (procid_equal(&e1->pid, &e2->pid) &&
1299                 file_id_equal(&e1->id, &e2->id) &&
1300                 e1->share_file_id == e2->share_file_id );
1301 }
1302
1303 static bool deferred_open_identical(struct share_mode_entry *e1,
1304                                     struct share_mode_entry *e2)
1305 {
1306         return (procid_equal(&e1->pid, &e2->pid) &&
1307                 (e1->op_mid == e2->op_mid) &&
1308                 file_id_equal(&e1->id, &e2->id));
1309 }
1310
1311 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1312                                                       struct share_mode_entry *entry)
1313 {
1314         int i;
1315
1316         for (i=0; i<lck->num_share_modes; i++) {
1317                 struct share_mode_entry *e = &lck->share_modes[i];
1318                 if (is_valid_share_mode_entry(entry) &&
1319                     is_valid_share_mode_entry(e) &&
1320                     share_modes_identical(e, entry)) {
1321                         return e;
1322                 }
1323                 if (is_deferred_open_entry(entry) &&
1324                     is_deferred_open_entry(e) &&
1325                     deferred_open_identical(e, entry)) {
1326                         return e;
1327                 }
1328         }
1329         return NULL;
1330 }
1331
1332 /*******************************************************************
1333  Del the share mode of a file for this process. Return the number of
1334  entries left.
1335 ********************************************************************/
1336
1337 bool del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1338 {
1339         struct share_mode_entry entry, *e;
1340
1341         /* Don't care about the pid owner being correct here - just a search. */
1342         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1343
1344         e = find_share_mode_entry(lck, &entry);
1345         if (e == NULL) {
1346                 return False;
1347         }
1348
1349         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1350         lck->modified = True;
1351         return True;
1352 }
1353
1354 void del_deferred_open_entry(struct share_mode_lock *lck, uint64_t mid,
1355                              struct server_id pid)
1356 {
1357         struct share_mode_entry entry, *e;
1358
1359         fill_deferred_open_entry(&entry, timeval_zero(),
1360                                  lck->id, pid, mid);
1361
1362         e = find_share_mode_entry(lck, &entry);
1363         if (e == NULL) {
1364                 return;
1365         }
1366
1367         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1368         lck->modified = True;
1369 }
1370
1371 /*******************************************************************
1372  Remove an oplock mid and mode entry from a share mode.
1373 ********************************************************************/
1374
1375 bool remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1376 {
1377         struct share_mode_entry entry, *e;
1378
1379         /* Don't care about the pid owner being correct here - just a search. */
1380         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1381
1382         e = find_share_mode_entry(lck, &entry);
1383         if (e == NULL) {
1384                 return False;
1385         }
1386
1387         if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1388                 /*
1389                  * Going from exclusive or batch,
1390                  * we always go through FAKE_LEVEL_II
1391                  * first.
1392                  */
1393                 if (!EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1394                         smb_panic("remove_share_oplock: logic error");
1395                 }
1396                 e->op_type = FAKE_LEVEL_II_OPLOCK;
1397         } else {
1398                 e->op_type = NO_OPLOCK;
1399         }
1400         lck->modified = True;
1401         return True;
1402 }
1403
1404 /*******************************************************************
1405  Downgrade a oplock type from exclusive to level II.
1406 ********************************************************************/
1407
1408 bool downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1409 {
1410         struct share_mode_entry entry, *e;
1411
1412         /* Don't care about the pid owner being correct here - just a search. */
1413         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1414
1415         e = find_share_mode_entry(lck, &entry);
1416         if (e == NULL) {
1417                 return False;
1418         }
1419
1420         e->op_type = LEVEL_II_OPLOCK;
1421         lck->modified = True;
1422         return True;
1423 }
1424
1425 /****************************************************************************
1426  Check if setting delete on close is allowed on this fsp.
1427 ****************************************************************************/
1428
1429 NTSTATUS can_set_delete_on_close(files_struct *fsp, uint32 dosmode)
1430 {
1431         /*
1432          * Only allow delete on close for writable files.
1433          */
1434
1435         if ((dosmode & FILE_ATTRIBUTE_READONLY) &&
1436             !lp_delete_readonly(SNUM(fsp->conn))) {
1437                 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1438                           "flag set but file attribute is readonly.\n",
1439                           fsp_str_dbg(fsp)));
1440                 return NT_STATUS_CANNOT_DELETE;
1441         }
1442
1443         /*
1444          * Only allow delete on close for writable shares.
1445          */
1446
1447         if (!CAN_WRITE(fsp->conn)) {
1448                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1449                           "close flag set but write access denied on share.\n",
1450                           fsp_str_dbg(fsp)));
1451                 return NT_STATUS_ACCESS_DENIED;
1452         }
1453
1454         /*
1455          * Only allow delete on close for files/directories opened with delete
1456          * intent.
1457          */
1458
1459         if (!(fsp->access_mask & DELETE_ACCESS)) {
1460                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1461                           "close flag set but delete access denied.\n",
1462                           fsp_str_dbg(fsp)));
1463                 return NT_STATUS_ACCESS_DENIED;
1464         }
1465
1466         /* Don't allow delete on close for non-empty directories. */
1467         if (fsp->is_directory) {
1468                 SMB_ASSERT(!is_ntfs_stream_smb_fname(fsp->fsp_name));
1469                 return can_delete_directory(fsp->conn,
1470                                             fsp->fsp_name->base_name);
1471         }
1472
1473         return NT_STATUS_OK;
1474 }
1475
1476 /*************************************************************************
1477  Return a talloced copy of a struct security_unix_token. NULL on fail.
1478  (Should this be in locking.c.... ?).
1479 *************************************************************************/
1480
1481 static struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
1482 {
1483         struct security_unix_token *cpy;
1484
1485         cpy = TALLOC_P(ctx, struct security_unix_token);
1486         if (!cpy) {
1487                 return NULL;
1488         }
1489
1490         cpy->uid = tok->uid;
1491         cpy->gid = tok->gid;
1492         cpy->ngroups = tok->ngroups;
1493         if (tok->ngroups) {
1494                 /* Make this a talloc child of cpy. */
1495                 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1496                 if (!cpy->groups) {
1497                         return NULL;
1498                 }
1499                 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1500         }
1501         return cpy;
1502 }
1503
1504 /****************************************************************************
1505  Adds a delete on close token.
1506 ****************************************************************************/
1507
1508 static bool add_delete_on_close_token(struct share_mode_lock *lck,
1509                         uint32_t name_hash,
1510                         const struct security_unix_token *tok)
1511 {
1512         struct delete_token_list *dtl;
1513
1514         dtl = TALLOC_ZERO_P(lck, struct delete_token_list);
1515         if (dtl == NULL) {
1516                 return false;
1517         }
1518
1519         dtl->name_hash = name_hash;
1520         dtl->delete_token = copy_unix_token(lck, tok);
1521         if (dtl->delete_token == NULL) {
1522                 TALLOC_FREE(dtl);
1523                 return false;
1524         }
1525         DLIST_ADD(lck->delete_tokens, dtl);
1526         lck->modified = true;
1527         return true;
1528 }
1529
1530 /****************************************************************************
1531  Sets the delete on close flag over all share modes on this file.
1532  Modify the share mode entry for all files open
1533  on this device and inode to tell other smbds we have
1534  changed the delete on close flag. This will be noticed
1535  in the close code, the last closer will delete the file
1536  if flag is set.
1537  This makes a copy of any struct security_unix_token into the
1538  lck entry. This function is used when the lock is already granted.
1539 ****************************************************************************/
1540
1541 void set_delete_on_close_lck(files_struct *fsp,
1542                         struct share_mode_lock *lck,
1543                         bool delete_on_close,
1544                         const struct security_unix_token *tok)
1545 {
1546         struct delete_token_list *dtl;
1547         bool ret;
1548
1549         if (delete_on_close) {
1550                 SMB_ASSERT(tok != NULL);
1551         } else {
1552                 SMB_ASSERT(tok == NULL);
1553         }
1554
1555         for (dtl = lck->delete_tokens; dtl; dtl = dtl->next) {
1556                 if (dtl->name_hash == fsp->name_hash) {
1557                         lck->modified = true;
1558                         if (delete_on_close == false) {
1559                                 /* Delete this entry. */
1560                                 DLIST_REMOVE(lck->delete_tokens, dtl);
1561                                 TALLOC_FREE(dtl);
1562                                 return;
1563                         }
1564                         /* Replace this token with the
1565                            given tok. */
1566                         TALLOC_FREE(dtl->delete_token);
1567                         dtl->delete_token = copy_unix_token(dtl, tok);
1568                         SMB_ASSERT(dtl->delete_token != NULL);
1569                 }
1570         }
1571
1572         if (!delete_on_close) {
1573                 /* Nothing to delete - not found. */
1574                 return;
1575         }
1576
1577         ret = add_delete_on_close_token(lck, fsp->name_hash, tok);
1578         SMB_ASSERT(ret);
1579 }
1580
1581 bool set_delete_on_close(files_struct *fsp, bool delete_on_close, const struct security_unix_token *tok)
1582 {
1583         struct share_mode_lock *lck;
1584         
1585         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1586                   "fnum = %d, file %s\n",
1587                   delete_on_close ? "Adding" : "Removing", fsp->fnum,
1588                   fsp_str_dbg(fsp)));
1589
1590         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
1591                                   NULL);
1592         if (lck == NULL) {
1593                 return False;
1594         }
1595
1596         set_delete_on_close_lck(fsp, lck, delete_on_close,
1597                         delete_on_close ? tok : NULL);
1598
1599         if (fsp->is_directory) {
1600                 SMB_ASSERT(!is_ntfs_stream_smb_fname(fsp->fsp_name));
1601                 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1602                                                fsp->fsp_name->base_name);
1603         }
1604
1605         TALLOC_FREE(lck);
1606
1607         fsp->delete_on_close = delete_on_close;
1608
1609         return True;
1610 }
1611
1612 const struct security_unix_token *get_delete_on_close_token(struct share_mode_lock *lck, uint32_t name_hash)
1613 {
1614         struct delete_token_list *dtl;
1615
1616         DEBUG(10,("get_delete_on_close_token: name_hash = 0x%x\n",
1617                         (unsigned int)name_hash ));
1618
1619         for (dtl = lck->delete_tokens; dtl; dtl = dtl->next) {
1620                 DEBUG(10,("get_delete_on_close_token: dtl->name_hash = 0x%x\n",
1621                                 (unsigned int)dtl->name_hash ));
1622                 if (dtl->name_hash == name_hash) {
1623                         return dtl->delete_token;
1624                 }
1625         }
1626         return NULL;
1627 }
1628
1629 bool is_delete_on_close_set(struct share_mode_lock *lck, uint32_t name_hash)
1630 {
1631         return (get_delete_on_close_token(lck, name_hash) != NULL);
1632 }
1633
1634 bool set_sticky_write_time(struct file_id fileid, struct timespec write_time)
1635 {
1636         struct share_mode_lock *lck;
1637
1638         DEBUG(5,("set_sticky_write_time: %s id=%s\n",
1639                  timestring(talloc_tos(),
1640                             convert_timespec_to_time_t(write_time)),
1641                  file_id_string_tos(&fileid)));
1642
1643         lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1644         if (lck == NULL) {
1645                 return False;
1646         }
1647
1648         if (timespec_compare(&lck->changed_write_time, &write_time) != 0) {
1649                 lck->modified = True;
1650                 lck->changed_write_time = write_time;
1651         }
1652
1653         TALLOC_FREE(lck);
1654         return True;
1655 }
1656
1657 bool set_write_time(struct file_id fileid, struct timespec write_time)
1658 {
1659         struct share_mode_lock *lck;
1660
1661         DEBUG(5,("set_write_time: %s id=%s\n",
1662                  timestring(talloc_tos(),
1663                             convert_timespec_to_time_t(write_time)),
1664                  file_id_string_tos(&fileid)));
1665
1666         lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1667         if (lck == NULL) {
1668                 return False;
1669         }
1670
1671         if (timespec_compare(&lck->old_write_time, &write_time) != 0) {
1672                 lck->modified = True;
1673                 lck->old_write_time = write_time;
1674         }
1675
1676         TALLOC_FREE(lck);
1677         return True;
1678 }
1679
1680
1681 struct forall_state {
1682         void (*fn)(const struct share_mode_entry *entry,
1683                    const char *sharepath,
1684                    const char *fname,
1685                    void *private_data);
1686         void *private_data;
1687 };
1688
1689 static int traverse_fn(struct db_record *rec, void *_state)
1690 {
1691         struct forall_state *state = (struct forall_state *)_state;
1692         struct locking_data *data;
1693         struct share_mode_entry *shares;
1694         const char *sharepath;
1695         const char *fname;
1696         const char *del_tokens;
1697         uint32_t total_del_token_size = 0;
1698         int i;
1699
1700         /* Ensure this is a locking_key record. */
1701         if (rec->key.dsize != sizeof(struct file_id))
1702                 return 0;
1703
1704         data = (struct locking_data *)rec->value.dptr;
1705         shares = (struct share_mode_entry *)(rec->value.dptr + sizeof(*data));
1706         del_tokens = (const char *)rec->value.dptr + sizeof(*data) +
1707                 data->u.s.num_share_mode_entries*sizeof(*shares);
1708
1709         for (i = 0; i < data->u.s.num_delete_token_entries; i++) {
1710                 uint32_t del_token_size;
1711                 memcpy(&del_token_size, del_tokens, sizeof(uint32_t));
1712                 total_del_token_size += del_token_size;
1713                 del_tokens += del_token_size;
1714         }
1715
1716         sharepath = (const char *)rec->value.dptr + sizeof(*data) +
1717                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1718                 total_del_token_size;
1719         fname = (const char *)rec->value.dptr + sizeof(*data) +
1720                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1721                 total_del_token_size +
1722                 strlen(sharepath) + 1;
1723
1724         for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1725                 state->fn(&shares[i], sharepath, fname,
1726                           state->private_data);
1727         }
1728         return 0;
1729 }
1730
1731 /*******************************************************************
1732  Call the specified function on each entry under management by the
1733  share mode system.
1734 ********************************************************************/
1735
1736 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1737                                  const char *, void *),
1738                       void *private_data)
1739 {
1740         struct forall_state state;
1741
1742         if (lock_db == NULL)
1743                 return 0;
1744
1745         state.fn = fn;
1746         state.private_data = private_data;
1747
1748         return lock_db->traverse_read(lock_db, traverse_fn, (void *)&state);
1749 }