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