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