547741ecbc7e7250436b438406087d4d73960a7e
[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    rewritten 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 "lib/util/server_id.h"
41 #include "locking/proto.h"
42 #include "smbd/globals.h"
43 #include "dbwrap/dbwrap.h"
44 #include "dbwrap/dbwrap_open.h"
45 #include "../libcli/security/security.h"
46 #include "serverid.h"
47 #include "messages.h"
48 #include "util_tdb.h"
49 #include "../librpc/gen_ndr/ndr_open_files.h"
50 #include "librpc/gen_ndr/ndr_file_id.h"
51 #include "locking/leases_db.h"
52
53 #undef DBGC_CLASS
54 #define DBGC_CLASS DBGC_LOCKING
55
56 #define NO_LOCKING_COUNT (-1)
57
58 /****************************************************************************
59  Debugging aids :-).
60 ****************************************************************************/
61
62 const char *lock_type_name(enum brl_type lock_type)
63 {
64         switch (lock_type) {
65                 case READ_LOCK:
66                         return "READ";
67                 case WRITE_LOCK:
68                         return "WRITE";
69                 default:
70                         return "other";
71         }
72 }
73
74 const char *lock_flav_name(enum brl_flavour lock_flav)
75 {
76         return (lock_flav == WINDOWS_LOCK) ? "WINDOWS_LOCK" : "POSIX_LOCK";
77 }
78
79 /****************************************************************************
80  Utility function called to see if a file region is locked.
81  Called in the read/write codepath.
82 ****************************************************************************/
83
84 void init_strict_lock_struct(files_struct *fsp,
85                                 uint64_t smblctx,
86                                 br_off start,
87                                 br_off size,
88                                 enum brl_type lock_type,
89                                 struct lock_struct *plock)
90 {
91         SMB_ASSERT(lock_type == READ_LOCK || lock_type == WRITE_LOCK);
92
93         plock->context.smblctx = smblctx;
94         plock->context.tid = fsp->conn->cnum;
95         plock->context.pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
96         plock->start = start;
97         plock->size = size;
98         plock->fnum = fsp->fnum;
99         plock->lock_type = lock_type;
100         plock->lock_flav = lp_posix_cifsu_locktype(fsp);
101 }
102
103 bool strict_lock_check_default(files_struct *fsp, struct lock_struct *plock)
104 {
105         struct byte_range_lock *br_lck;
106         int strict_locking = lp_strict_locking(fsp->conn->params);
107         bool ret = False;
108
109         if (plock->size == 0) {
110                 return True;
111         }
112
113         if (!lp_locking(fsp->conn->params) || !strict_locking) {
114                 return True;
115         }
116
117         if (strict_locking == Auto) {
118                 uint32_t lease_type = fsp_lease_type(fsp);
119
120                 if ((lease_type & SMB2_LEASE_READ) &&
121                      (plock->lock_type == READ_LOCK))
122                 {
123                         DBG_DEBUG("optimisation - read lease on file %s\n",
124                                   fsp_str_dbg(fsp));
125                         return true;
126                 }
127
128                 if ((lease_type & SMB2_LEASE_WRITE) &&
129                      (plock->lock_type == WRITE_LOCK))
130                 {
131                         DBG_DEBUG("optimisation - write lease on file %s\n",
132                                   fsp_str_dbg(fsp));
133                         return true;
134                 }
135         }
136
137         br_lck = brl_get_locks_readonly(fsp);
138         if (!br_lck) {
139                 return true;
140         }
141         ret = brl_locktest(br_lck, plock);
142
143         if (!ret) {
144                 /*
145                  * We got a lock conflict. Retry with rw locks to enable
146                  * autocleanup. This is the slow path anyway.
147                  */
148                 br_lck = brl_get_locks(talloc_tos(), fsp);
149                 if (br_lck == NULL) {
150                         return true;
151                 }
152                 ret = brl_locktest(br_lck, plock);
153                 TALLOC_FREE(br_lck);
154         }
155
156         DEBUG(10, ("strict_lock_default: flavour = %s brl start=%ju "
157                    "len=%ju %s for fnum %ju file %s\n",
158                    lock_flav_name(plock->lock_flav),
159                    (uintmax_t)plock->start, (uintmax_t)plock->size,
160                    ret ? "unlocked" : "locked",
161                    (uintmax_t)plock->fnum, fsp_str_dbg(fsp)));
162
163         return ret;
164 }
165
166 /****************************************************************************
167  Find out if a lock could be granted - return who is blocking us if we can't.
168 ****************************************************************************/
169
170 NTSTATUS query_lock(files_struct *fsp,
171                         uint64_t *psmblctx,
172                         uint64_t *pcount,
173                         uint64_t *poffset,
174                         enum brl_type *plock_type,
175                         enum brl_flavour lock_flav)
176 {
177         struct byte_range_lock *br_lck = NULL;
178
179         if (!fsp->can_lock) {
180                 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
181         }
182
183         if (!lp_locking(fsp->conn->params)) {
184                 return NT_STATUS_OK;
185         }
186
187         br_lck = brl_get_locks_readonly(fsp);
188         if (!br_lck) {
189                 return NT_STATUS_NO_MEMORY;
190         }
191
192         return brl_lockquery(br_lck,
193                         psmblctx,
194                         messaging_server_id(fsp->conn->sconn->msg_ctx),
195                         poffset,
196                         pcount,
197                         plock_type,
198                         lock_flav);
199 }
200
201 static void increment_current_lock_count(files_struct *fsp,
202     enum brl_flavour lock_flav)
203 {
204         if (lock_flav == WINDOWS_LOCK &&
205             fsp->current_lock_count != NO_LOCKING_COUNT) {
206                 /* blocking ie. pending, locks also count here,
207                  * as this is an efficiency counter to avoid checking
208                  * the lock db. on close. JRA. */
209
210                 fsp->current_lock_count++;
211         } else {
212                 /* Notice that this has had a POSIX lock request.
213                  * We can't count locks after this so forget them.
214                  */
215                 fsp->current_lock_count = NO_LOCKING_COUNT;
216         }
217 }
218
219 static void decrement_current_lock_count(files_struct *fsp,
220     enum brl_flavour lock_flav)
221 {
222         if (lock_flav == WINDOWS_LOCK &&
223             fsp->current_lock_count != NO_LOCKING_COUNT) {
224                 SMB_ASSERT(fsp->current_lock_count > 0);
225                 fsp->current_lock_count--;
226         }
227 }
228
229 /****************************************************************************
230  Utility function called by locking requests.
231 ****************************************************************************/
232
233 struct do_lock_state {
234         struct files_struct *fsp;
235         TALLOC_CTX *req_mem_ctx;
236         const struct GUID *req_guid;
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
243         struct server_id blocker_pid;
244         uint64_t blocker_smblctx;
245         NTSTATUS status;
246 };
247
248 static void do_lock_fn(
249         struct db_record *rec,
250         bool *modified_dependent,
251         void *private_data)
252 {
253         struct do_lock_state *state = private_data;
254         struct byte_range_lock *br_lck = NULL;
255
256         br_lck = brl_get_locks_for_locking(talloc_tos(),
257                                            state->fsp,
258                                            state->req_mem_ctx,
259                                            state->req_guid);
260         if (br_lck == NULL) {
261                 state->status = NT_STATUS_NO_MEMORY;
262                 return;
263         }
264
265         state->status = brl_lock(
266                 br_lck,
267                 state->smblctx,
268                 messaging_server_id(state->fsp->conn->sconn->msg_ctx),
269                 state->offset,
270                 state->count,
271                 state->lock_type,
272                 state->lock_flav,
273                 &state->blocker_pid,
274                 &state->blocker_smblctx);
275
276         TALLOC_FREE(br_lck);
277 }
278
279 NTSTATUS do_lock(files_struct *fsp,
280                  TALLOC_CTX *req_mem_ctx,
281                  const struct GUID *req_guid,
282                  uint64_t smblctx,
283                  uint64_t count,
284                  uint64_t offset,
285                  enum brl_type lock_type,
286                  enum brl_flavour lock_flav,
287                  struct server_id *pblocker_pid,
288                  uint64_t *psmblctx)
289 {
290         struct do_lock_state state = {
291                 .fsp = fsp,
292                 .req_mem_ctx = req_mem_ctx,
293                 .req_guid = req_guid,
294                 .smblctx = smblctx,
295                 .count = count,
296                 .offset = offset,
297                 .lock_type = lock_type,
298                 .lock_flav = lock_flav,
299         };
300         NTSTATUS status;
301
302         /* silently return ok on print files as we don't do locking there */
303         if (fsp->print_file) {
304                 return NT_STATUS_OK;
305         }
306
307         if (!fsp->can_lock) {
308                 if (fsp->is_directory) {
309                         return NT_STATUS_INVALID_DEVICE_REQUEST;
310                 }
311                 return NT_STATUS_INVALID_HANDLE;
312         }
313
314         if (!lp_locking(fsp->conn->params)) {
315                 return NT_STATUS_OK;
316         }
317
318         /* NOTE! 0 byte long ranges ARE allowed and should be stored  */
319
320         DBG_DEBUG("lock flavour %s lock type %s start=%"PRIu64" len=%"PRIu64" "
321                   "requested for %s file %s\n",
322                   lock_flav_name(lock_flav),
323                   lock_type_name(lock_type),
324                   offset,
325                   count,
326                   fsp_fnum_dbg(fsp),
327                   fsp_str_dbg(fsp));
328
329         status = share_mode_do_locked(fsp->file_id, do_lock_fn, &state);
330         if (!NT_STATUS_IS_OK(status)) {
331                 DBG_DEBUG("share_mode_do_locked returned %s\n",
332                           nt_errstr(status));
333                 return status;
334         }
335
336         if (psmblctx != NULL) {
337                 *psmblctx = state.blocker_smblctx;
338         }
339         if (pblocker_pid != NULL) {
340                 *pblocker_pid = state.blocker_pid;
341         }
342
343         DBG_DEBUG("returning status=%s\n", nt_errstr(state.status));
344
345         increment_current_lock_count(fsp, lock_flav);
346
347         return state.status;
348 }
349
350 /****************************************************************************
351  Utility function called by unlocking requests.
352 ****************************************************************************/
353
354 NTSTATUS do_unlock(files_struct *fsp,
355                    uint64_t smblctx,
356                    uint64_t count,
357                    uint64_t offset,
358                    enum brl_flavour lock_flav)
359 {
360         bool ok = False;
361         struct byte_range_lock *br_lck = NULL;
362
363         if (!fsp->can_lock) {
364                 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
365         }
366
367         if (!lp_locking(fsp->conn->params)) {
368                 return NT_STATUS_OK;
369         }
370
371         DBG_DEBUG("unlock start=%"PRIu64" len=%"PRIu64" requested for %s file "
372                   "%s\n",
373                   offset,
374                   count,
375                   fsp_fnum_dbg(fsp),
376                   fsp_str_dbg(fsp));
377
378         br_lck = brl_get_locks(talloc_tos(), fsp);
379         if (!br_lck) {
380                 return NT_STATUS_NO_MEMORY;
381         }
382
383         ok = brl_unlock(br_lck,
384                         smblctx,
385                         messaging_server_id(fsp->conn->sconn->msg_ctx),
386                         offset,
387                         count,
388                         lock_flav);
389
390         TALLOC_FREE(br_lck);
391
392         if (!ok) {
393                 DEBUG(10,("do_unlock: returning ERRlock.\n" ));
394                 return NT_STATUS_RANGE_NOT_LOCKED;
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(files_struct *fsp,
406                         enum file_close_type close_type)
407 {
408         struct byte_range_lock *br_lck;
409
410         if (!lp_locking(fsp->conn->params)) {
411                 return;
412         }
413
414         /* If we have no outstanding locks or pending
415          * locks then we don't need to look in the lock db.
416          */
417
418         if (fsp->current_lock_count == 0) {
419                 return;
420         }
421
422         br_lck = brl_get_locks(talloc_tos(),fsp);
423
424         if (br_lck) {
425                 /*
426                  * Unlocks must trigger dbwrap_watch watchers,
427                  * normally in smbd_do_unlocking. Here it's done
428                  * implictly, we're closing the file and thus remove a
429                  * share mode. This will wake the waiters.
430                  */
431                 brl_close_fnum(br_lck);
432                 TALLOC_FREE(br_lck);
433         }
434 }
435
436 /*******************************************************************
437  Print out a share mode.
438 ********************************************************************/
439
440 char *share_mode_str(TALLOC_CTX *ctx, int num,
441                      const struct file_id *id,
442                      const struct share_mode_entry *e)
443 {
444         struct server_id_buf tmp;
445         struct file_id_buf ftmp;
446
447         return talloc_asprintf(ctx, "share_mode_entry[%d]: "
448                  "pid = %s, share_access = 0x%x, private_options = 0x%x, "
449                  "access_mask = 0x%x, mid = 0x%llx, type= 0x%x, gen_id = %llu, "
450                  "uid = %u, flags = %u, file_id %s, name_hash = 0x%x",
451                  num,
452                  server_id_str_buf(e->pid, &tmp),
453                  e->share_access, e->private_options,
454                  e->access_mask, (unsigned long long)e->op_mid,
455                  e->op_type, (unsigned long long)e->share_file_id,
456                  (unsigned int)e->uid, (unsigned int)e->flags,
457                  file_id_str_buf(*id, &ftmp),
458                  (unsigned int)e->name_hash);
459 }
460
461 /*******************************************************************
462  Fetch a share mode where we know one MUST exist. This call reference
463  counts it internally to allow for nested lock fetches.
464 ********************************************************************/
465
466 struct share_mode_lock *get_existing_share_mode_lock(TALLOC_CTX *mem_ctx,
467                                                      const struct file_id id)
468 {
469         return get_share_mode_lock(mem_ctx, id, NULL, NULL, NULL);
470 }
471
472 static bool rename_lease_fn(struct share_mode_lock *lck,
473                             struct share_mode_entry *e,
474                             void *private_data)
475 {
476         struct share_mode_data *d = lck->data;
477         NTSTATUS status;
478
479         status = leases_db_rename(&e->client_guid,
480                                   &e->lease_key,
481                                   &d->id,
482                                   d->servicepath,
483                                   d->base_name,
484                                   d->stream_name);
485
486         if (!NT_STATUS_IS_OK(status)) {
487                 /* Any error recovery possible here ? */
488                 DBG_WARNING("Failed to rename lease key for "
489                             "renamed file %s:%s. %s\n",
490                             d->base_name,
491                             d->stream_name,
492                             nt_errstr(status));
493         }
494
495         return false;
496 }
497
498 /*******************************************************************
499  Sets the service name and filename for rename.
500  At this point we emit "file renamed" messages to all
501  process id's that have this file open.
502  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
503 ********************************************************************/
504
505 bool rename_share_filename(struct messaging_context *msg_ctx,
506                         struct share_mode_lock *lck,
507                         struct file_id id,
508                         const char *servicepath,
509                         uint32_t orig_name_hash,
510                         uint32_t new_name_hash,
511                         const struct smb_filename *smb_fname_dst)
512 {
513         struct share_mode_data *d = lck->data;
514         struct file_rename_message msg = {
515                 .id = id,
516                 .servicepath = servicepath,
517                 .base_name = smb_fname_dst->base_name,
518                 .stream_name = smb_fname_dst->stream_name,
519         };
520         uint32_t i;
521         struct server_id self_pid = messaging_server_id(msg_ctx);
522         bool ok;
523
524         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
525                    servicepath, smb_fname_dst->base_name));
526
527         /*
528          * rename_internal_fsp() and rename_internals() add './' to
529          * head of newname if newname does not contain a '/'.
530          */
531
532         if (strncmp(msg.base_name, "./", 2) == 0) {
533                 msg.base_name += 2;
534         }
535
536         d->servicepath = talloc_strdup(d, msg.servicepath);
537         d->base_name = talloc_strdup(d, msg.base_name);
538         d->stream_name = talloc_strdup(d, msg.stream_name);
539         if ((d->servicepath == NULL) ||
540             (d->base_name == NULL) ||
541             ((msg.stream_name != NULL) && (d->stream_name == NULL))) {
542                 DBG_WARNING("talloc failed\n");
543                 return false;
544         }
545         d->modified = True;
546
547         /* Send the messages. */
548         for (i=0; i<d->num_share_modes; i++) {
549                 struct share_mode_entry *se = &d->share_modes[i];
550                 DATA_BLOB blob;
551                 enum ndr_err_code ndr_err;
552
553                 if (!is_valid_share_mode_entry(se)) {
554                         continue;
555                 }
556
557                 /* If this is a hardlink to the inode
558                    with a different name, skip this. */
559                 if (se->name_hash != orig_name_hash) {
560                         continue;
561                 }
562
563                 se->name_hash = new_name_hash;
564
565                 /* But not to ourselves... */
566                 if (serverid_equal(&se->pid, &self_pid)) {
567                         continue;
568                 }
569
570                 if (share_mode_stale_pid(d, i)) {
571                         continue;
572                 }
573
574                 msg.share_file_id = se->share_file_id;
575
576                 ndr_err = ndr_push_struct_blob(
577                         &blob,
578                         talloc_tos(),
579                         &msg,
580                         (ndr_push_flags_fn_t)ndr_push_file_rename_message);
581                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
582                         DBG_DEBUG("ndr_push_file_rename_message failed: %s\n",
583                                   ndr_errstr(ndr_err));
584                         return false;
585                 }
586                 if (DEBUGLEVEL >= 10) {
587                         struct server_id_buf tmp;
588                         DBG_DEBUG("sending rename message to %s\n",
589                                   server_id_str_buf(se->pid, &tmp));
590                         NDR_PRINT_DEBUG(file_rename_message, &msg);
591                 }
592
593                 messaging_send(msg_ctx, se->pid, MSG_SMB_FILE_RENAME, &blob);
594
595                 TALLOC_FREE(blob.data);
596         }
597
598         ok = share_mode_forall_leases(lck, rename_lease_fn, NULL);
599         if (!ok) {
600                 /*
601                  * Ignore error here. Not sure what to do..
602                  */
603                 DBG_WARNING("share_mode_forall_leases failed\n");
604         }
605
606         return True;
607 }
608
609 void get_file_infos(struct file_id id,
610                     uint32_t name_hash,
611                     bool *delete_on_close,
612                     struct timespec *write_time)
613 {
614         struct share_mode_lock *lck;
615
616         if (delete_on_close) {
617                 *delete_on_close = false;
618         }
619
620         if (write_time) {
621                 ZERO_STRUCTP(write_time);
622         }
623
624         if (!(lck = fetch_share_mode_unlocked(talloc_tos(), id))) {
625                 return;
626         }
627
628         if (delete_on_close) {
629                 *delete_on_close = is_delete_on_close_set(lck, name_hash);
630         }
631
632         if (write_time) {
633                 *write_time = get_share_mode_write_time(lck);
634         }
635
636         TALLOC_FREE(lck);
637 }
638
639 bool is_valid_share_mode_entry(const struct share_mode_entry *e)
640 {
641         int num_props = 0;
642
643         if (e->stale) {
644                 return false;
645         }
646
647         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
648         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
649         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
650         num_props += (e->op_type == LEASE_OPLOCK);
651
652         if ((num_props > 1) && serverid_exists(&e->pid)) {
653                 smb_panic("Invalid share mode entry");
654         }
655         return (num_props != 0);
656 }
657
658 NTSTATUS remove_lease_if_stale(const struct share_mode_data *d,
659                                const struct GUID *client_guid,
660                                const struct smb2_lease_key *lease_key)
661 {
662         uint32_t i;
663         NTSTATUS status;
664
665         for (i=0; i<d->num_share_modes; i++) {
666                 const struct share_mode_entry *e = &d->share_modes[i];
667                 bool same;
668
669                 if (e->stale) {
670                         continue;
671                 }
672                 if (e->op_type != LEASE_OPLOCK) {
673                         continue;
674                 }
675
676                 same = smb2_lease_equal(
677                         &e->client_guid,
678                         &e->lease_key,
679                         client_guid,
680                         lease_key);
681                 if (same) {
682                         return NT_STATUS_RESOURCE_IN_USE;
683                 }
684         }
685
686         status = leases_db_del(client_guid, lease_key, &d->id);
687         if (!NT_STATUS_IS_OK(status)) {
688                 DBG_DEBUG("leases_db_del failed: %s\n",
689                           nt_errstr(status));
690         }
691         return status;
692 }
693
694 /*
695  * See if we need to remove a lease being referred to by a
696  * share mode that is being marked stale or deleted.
697  */
698
699 static void remove_share_mode_lease(struct share_mode_data *d,
700                                     struct share_mode_entry *e)
701 {
702         uint16_t op_type;
703
704         op_type = e->op_type;
705         e->op_type = NO_OPLOCK;
706
707         d->modified = true;
708
709         if (op_type != LEASE_OPLOCK) {
710                 return;
711         }
712
713         remove_lease_if_stale(d, &e->client_guid, &e->lease_key);
714 }
715
716 bool share_entry_stale_pid(struct share_mode_entry *e)
717 {
718         struct server_id_buf buf;
719         bool exists;
720
721         if (e->stale) {
722                 return true;
723         }
724
725         exists = serverid_exists(&e->pid);
726         if (exists) {
727                 DBG_DEBUG("PID %s still exists\n",
728                           server_id_str_buf(e->pid, &buf));
729                 return false;
730         }
731
732         DBG_DEBUG("PID %s does not exist anymore\n",
733                   server_id_str_buf(e->pid, &buf));
734
735         e->stale = true;
736
737         return true;
738 }
739
740 /*
741  * In case d->share_modes[i] conflicts with something or otherwise is
742  * being used, we need to make sure the corresponding process still
743  * exists.
744  */
745 bool share_mode_stale_pid(struct share_mode_data *d, uint32_t idx)
746 {
747         struct share_mode_entry *e;
748         bool stale;
749
750         if (idx > d->num_share_modes) {
751                 DBG_WARNING("Asking for index %"PRIu32", "
752                             "only %"PRIu32" around\n",
753                             idx,
754                             d->num_share_modes);
755                 return false;
756         }
757         e = &d->share_modes[idx];
758
759         stale = share_entry_stale_pid(e);
760         if (!stale) {
761                 return false;
762         }
763         d->modified = true;
764
765         if (d->num_delete_tokens != 0) {
766                 uint32_t i;
767
768                 for (i=0; i<d->num_share_modes; i++) {
769                         bool valid = !d->share_modes[i].stale;
770                         if (valid) {
771                                 break;
772                         }
773                 }
774
775                 if (i == d->num_share_modes) {
776                         /*
777                          * No valid (non-stale) share mode found, all
778                          * who might have set the delete token are
779                          * gone.
780                          */
781                         TALLOC_FREE(d->delete_tokens);
782                         d->num_delete_tokens = 0;
783                 }
784         }
785
786         remove_share_mode_lease(d, e);
787
788         d->modified = true;
789         return true;
790 }
791
792 void remove_stale_share_mode_entries(struct share_mode_data *d)
793 {
794         uint32_t i;
795
796         i = 0;
797         while (i < d->num_share_modes) {
798                 if (d->share_modes[i].stale) {
799                         struct share_mode_entry *m = d->share_modes;
800                         m[i] = m[d->num_share_modes-1];
801                         d->num_share_modes -= 1;
802                         continue;
803                 }
804                 i += 1;
805         }
806 }
807
808 bool set_share_mode(struct share_mode_lock *lck,
809                     struct files_struct *fsp,
810                     uid_t uid,
811                     uint64_t mid,
812                     uint16_t op_type,
813                     uint32_t share_access,
814                     uint32_t access_mask)
815 {
816         struct share_mode_data *d = lck->data;
817         struct share_mode_entry *tmp, *e;
818
819         tmp = talloc_realloc(d, d->share_modes, struct share_mode_entry,
820                              d->num_share_modes+1);
821         if (tmp == NULL) {
822                 return false;
823         }
824         d->share_modes = tmp;
825         e = &d->share_modes[d->num_share_modes];
826         d->num_share_modes += 1;
827         d->modified = true;
828
829         ZERO_STRUCTP(e);
830         e->pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
831         e->share_access = share_access;
832         e->private_options = fsp->fh->private_options;
833         e->access_mask = access_mask;
834         e->op_mid = mid;
835         e->op_type = op_type;
836
837         if (op_type == LEASE_OPLOCK) {
838                 const struct GUID *client_guid = fsp_client_guid(fsp);
839                 e->client_guid = *client_guid;
840                 e->lease_key = fsp->lease->lease.lease_key;
841         }
842
843         e->time.tv_sec = fsp->open_time.tv_sec;
844         e->time.tv_usec = fsp->open_time.tv_usec;
845         e->share_file_id = fsp->fh->gen_id;
846         e->uid = (uint32_t)uid;
847         e->flags = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) ?
848                 SHARE_MODE_FLAG_POSIX_OPEN : 0;
849         e->name_hash = fsp->name_hash;
850
851         return true;
852 }
853
854 static struct share_mode_entry *find_share_mode_entry(
855         struct share_mode_lock *lck, files_struct *fsp)
856 {
857         struct share_mode_data *d = lck->data;
858         struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
859         uint32_t i;
860
861         for (i=0; i<d->num_share_modes; i++) {
862                 struct share_mode_entry *e = &d->share_modes[i];
863
864                 if (!is_valid_share_mode_entry(e)) {
865                         continue;
866                 }
867                 if (!serverid_equal(&pid, &e->pid)) {
868                         continue;
869                 }
870                 if (fsp->fh->gen_id != e->share_file_id) {
871                         continue;
872                 }
873                 return e;
874         }
875         return NULL;
876 }
877
878 /*******************************************************************
879  Del the share mode of a file for this process.
880 ********************************************************************/
881
882 bool del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
883 {
884         struct share_mode_entry *e;
885
886         e = find_share_mode_entry(lck, fsp);
887         if (e == NULL) {
888                 return False;
889         }
890         remove_share_mode_lease(lck->data, e);
891         *e = lck->data->share_modes[lck->data->num_share_modes-1];
892         lck->data->num_share_modes -= 1;
893         lck->data->modified = True;
894         return True;
895 }
896
897 bool mark_share_mode_disconnected(struct share_mode_lock *lck,
898                                   struct files_struct *fsp)
899 {
900         struct share_mode_entry *e;
901
902         if (lck->data->num_share_modes != 1) {
903                 return false;
904         }
905
906         if (fsp->op == NULL) {
907                 return false;
908         }
909         if (!fsp->op->global->durable) {
910                 return false;
911         }
912
913         e = find_share_mode_entry(lck, fsp);
914         if (e == NULL) {
915                 return false;
916         }
917
918         DEBUG(10, ("Marking share mode entry disconnected for durable handle\n"));
919
920         server_id_set_disconnected(&e->pid);
921
922         /*
923          * On reopen the caller needs to check that
924          * the client comes with the correct handle.
925          */
926         e->share_file_id = fsp->op->global->open_persistent_id;
927
928         lck->data->modified = true;
929         return true;
930 }
931
932 /*******************************************************************
933  Remove an oplock mid and mode entry from a share mode.
934 ********************************************************************/
935
936 bool remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
937 {
938         struct share_mode_data *d = lck->data;
939         struct share_mode_entry *e;
940
941         e = find_share_mode_entry(lck, fsp);
942         if (e == NULL) {
943                 return False;
944         }
945
946         remove_share_mode_lease(d, e);
947         d->modified = True;
948         return true;
949 }
950
951 /*******************************************************************
952  Downgrade a oplock type from exclusive to level II.
953 ********************************************************************/
954
955 bool downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
956 {
957         struct share_mode_entry *e;
958
959         e = find_share_mode_entry(lck, fsp);
960         if (e == NULL) {
961                 return False;
962         }
963
964         e->op_type = LEVEL_II_OPLOCK;
965         lck->data->flags |= SHARE_MODE_HAS_READ_LEASE;
966         lck->data->modified = True;
967         return True;
968 }
969
970 /****************************************************************************
971  Adds a delete on close token.
972 ****************************************************************************/
973
974 static bool add_delete_on_close_token(struct share_mode_data *d,
975                         uint32_t name_hash,
976                         const struct security_token *nt_tok,
977                         const struct security_unix_token *tok)
978 {
979         struct delete_token *tmp, *dtl;
980
981         tmp = talloc_realloc(d, d->delete_tokens, struct delete_token,
982                              d->num_delete_tokens+1);
983         if (tmp == NULL) {
984                 return false;
985         }
986         d->delete_tokens = tmp;
987         dtl = &d->delete_tokens[d->num_delete_tokens];
988
989         dtl->name_hash = name_hash;
990         dtl->delete_nt_token = dup_nt_token(d->delete_tokens, nt_tok);
991         if (dtl->delete_nt_token == NULL) {
992                 return false;
993         }
994         dtl->delete_token = copy_unix_token(d->delete_tokens, tok);
995         if (dtl->delete_token == NULL) {
996                 return false;
997         }
998         d->num_delete_tokens += 1;
999         d->modified = true;
1000         return true;
1001 }
1002
1003 void reset_delete_on_close_lck(files_struct *fsp,
1004                                struct share_mode_lock *lck)
1005 {
1006         struct share_mode_data *d = lck->data;
1007         uint32_t i;
1008
1009         for (i=0; i<d->num_delete_tokens; i++) {
1010                 struct delete_token *dt = &d->delete_tokens[i];
1011
1012                 if (dt->name_hash == fsp->name_hash) {
1013                         d->modified = true;
1014
1015                         /* Delete this entry. */
1016                         TALLOC_FREE(dt->delete_nt_token);
1017                         TALLOC_FREE(dt->delete_token);
1018                         *dt = d->delete_tokens[d->num_delete_tokens-1];
1019                         d->num_delete_tokens -= 1;
1020                 }
1021         }
1022 }
1023
1024 /****************************************************************************
1025  Sets the delete on close flag over all share modes on this file.
1026  Modify the share mode entry for all files open
1027  on this device and inode to tell other smbds we have
1028  changed the delete on close flag. This will be noticed
1029  in the close code, the last closer will delete the file
1030  if flag is set.
1031  This makes a copy of any struct security_unix_token into the
1032  lck entry. This function is used when the lock is already granted.
1033 ****************************************************************************/
1034
1035 void set_delete_on_close_lck(files_struct *fsp,
1036                         struct share_mode_lock *lck,
1037                         const struct security_token *nt_tok,
1038                         const struct security_unix_token *tok)
1039 {
1040         struct messaging_context *msg_ctx = fsp->conn->sconn->msg_ctx;
1041         struct share_mode_data *d = lck->data;
1042         uint32_t i;
1043         bool ret;
1044         DATA_BLOB fid_blob = {};
1045         enum ndr_err_code ndr_err;
1046
1047         SMB_ASSERT(nt_tok != NULL);
1048         SMB_ASSERT(tok != NULL);
1049
1050         for (i=0; i<d->num_delete_tokens; i++) {
1051                 struct delete_token *dt = &d->delete_tokens[i];
1052                 if (dt->name_hash == fsp->name_hash) {
1053                         d->modified = true;
1054
1055                         /* Replace this token with the given tok. */
1056                         TALLOC_FREE(dt->delete_nt_token);
1057                         dt->delete_nt_token = dup_nt_token(dt, nt_tok);
1058                         SMB_ASSERT(dt->delete_nt_token != NULL);
1059                         TALLOC_FREE(dt->delete_token);
1060                         dt->delete_token = copy_unix_token(dt, tok);
1061                         SMB_ASSERT(dt->delete_token != NULL);
1062
1063                         return;
1064                 }
1065         }
1066
1067         ret = add_delete_on_close_token(lck->data, fsp->name_hash, nt_tok, tok);
1068         SMB_ASSERT(ret);
1069
1070         ndr_err = ndr_push_struct_blob(&fid_blob, talloc_tos(), &fsp->file_id,
1071                                        (ndr_push_flags_fn_t)ndr_push_file_id);
1072         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1073                 DEBUG(10, ("ndr_push_file_id failed: %s\n",
1074                            ndr_errstr(ndr_err)));
1075         }
1076
1077         for (i=0; i<d->num_share_modes; i++) {
1078                 struct share_mode_entry *e = &d->share_modes[i];
1079                 NTSTATUS status;
1080
1081                 status = messaging_send(
1082                         msg_ctx, e->pid, MSG_SMB_NOTIFY_CANCEL_DELETED,
1083                         &fid_blob);
1084
1085                 if (!NT_STATUS_IS_OK(status)) {
1086                         struct server_id_buf tmp;
1087                         DEBUG(10, ("%s: messaging_send to %s returned %s\n",
1088                                    __func__, server_id_str_buf(e->pid, &tmp),
1089                                    nt_errstr(status)));
1090                 }
1091         }
1092
1093         TALLOC_FREE(fid_blob.data);
1094 }
1095
1096 bool set_delete_on_close(files_struct *fsp, bool delete_on_close,
1097                         const struct security_token *nt_tok,
1098                         const struct security_unix_token *tok)
1099 {
1100         struct share_mode_lock *lck;
1101
1102         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1103                   "%s, file %s\n",
1104                   delete_on_close ? "Adding" : "Removing", fsp_fnum_dbg(fsp),
1105                   fsp_str_dbg(fsp)));
1106
1107         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1108         if (lck == NULL) {
1109                 return False;
1110         }
1111
1112         if (delete_on_close) {
1113                 set_delete_on_close_lck(fsp, lck, nt_tok, tok);
1114         } else {
1115                 reset_delete_on_close_lck(fsp, lck);
1116         }
1117
1118         if (fsp->is_directory) {
1119                 SMB_ASSERT(!is_ntfs_stream_smb_fname(fsp->fsp_name));
1120                 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1121                                                fsp->fsp_name->base_name);
1122         }
1123
1124         TALLOC_FREE(lck);
1125
1126         fsp->delete_on_close = delete_on_close;
1127
1128         return True;
1129 }
1130
1131 static struct delete_token *find_delete_on_close_token(
1132         struct share_mode_data *d, uint32_t name_hash)
1133 {
1134         uint32_t i;
1135
1136         DBG_DEBUG("name_hash = 0x%"PRIx32"\n", name_hash);
1137
1138         for (i=0; i<d->num_delete_tokens; i++) {
1139                 struct delete_token *dt = &d->delete_tokens[i];
1140
1141                 DBG_DEBUG("dt->name_hash = 0x%"PRIx32"\n",
1142                           dt->name_hash);
1143                 if (dt->name_hash == name_hash) {
1144                         return dt;
1145                 }
1146         }
1147         return NULL;
1148 }
1149
1150 /****************************************************************************
1151  Return the NT token and UNIX token if there's a match. Return true if
1152  found, false if not.
1153 ****************************************************************************/
1154
1155 bool get_delete_on_close_token(struct share_mode_lock *lck,
1156                                         uint32_t name_hash,
1157                                         const struct security_token **pp_nt_tok,
1158                                         const struct security_unix_token **pp_tok)
1159 {
1160         struct delete_token *dt;
1161
1162         dt = find_delete_on_close_token(lck->data, name_hash);
1163         if (dt == NULL) {
1164                 return false;
1165         }
1166         *pp_nt_tok = dt->delete_nt_token;
1167         *pp_tok =  dt->delete_token;
1168         return true;
1169 }
1170
1171 bool is_delete_on_close_set(struct share_mode_lock *lck, uint32_t name_hash)
1172 {
1173         return find_delete_on_close_token(lck->data, name_hash) != NULL;
1174 }
1175
1176 bool set_sticky_write_time(struct file_id fileid, struct timespec write_time)
1177 {
1178         struct share_mode_lock *lck;
1179         struct file_id_buf ftmp;
1180
1181         DBG_INFO("%s id=%s\n",
1182                  timestring(talloc_tos(),
1183                             convert_timespec_to_time_t(write_time)),
1184                  file_id_str_buf(fileid, &ftmp));
1185
1186         lck = get_existing_share_mode_lock(talloc_tos(), fileid);
1187         if (lck == NULL) {
1188                 return False;
1189         }
1190
1191         if (timespec_compare(&lck->data->changed_write_time, &write_time) != 0) {
1192                 lck->data->modified = True;
1193                 lck->data->changed_write_time = write_time;
1194         }
1195
1196         TALLOC_FREE(lck);
1197         return True;
1198 }
1199
1200 bool set_write_time(struct file_id fileid, struct timespec write_time)
1201 {
1202         struct share_mode_lock *lck;
1203
1204         DEBUG(5,("set_write_time: %s id=%s\n",
1205                  timestring(talloc_tos(),
1206                             convert_timespec_to_time_t(write_time)),
1207                  file_id_string_tos(&fileid)));
1208
1209         lck = get_existing_share_mode_lock(talloc_tos(), fileid);
1210         if (lck == NULL) {
1211                 return False;
1212         }
1213
1214         if (timespec_compare(&lck->data->old_write_time, &write_time) != 0) {
1215                 lck->data->modified = True;
1216                 lck->data->old_write_time = write_time;
1217         }
1218
1219         TALLOC_FREE(lck);
1220         return True;
1221 }
1222
1223 struct timespec get_share_mode_write_time(struct share_mode_lock *lck)
1224 {
1225         struct share_mode_data *d = lck->data;
1226
1227         if (!null_timespec(d->changed_write_time)) {
1228                 return d->changed_write_time;
1229         }
1230         return d->old_write_time;
1231 }
1232
1233 bool file_has_open_streams(files_struct *fsp)
1234 {
1235         struct share_mode_lock *lock = NULL;
1236         struct share_mode_data *d = NULL;
1237         uint32_t i;
1238
1239         lock = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1240         if (lock == NULL) {
1241                 return false;
1242         }
1243         d = lock->data;
1244
1245         for (i = 0; i < d->num_share_modes; i++) {
1246                 struct share_mode_entry *e = &d->share_modes[i];
1247
1248                 if (share_mode_stale_pid(d, i)) {
1249                         continue;
1250                 }
1251
1252                 if (e->private_options &
1253                     NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN)
1254                 {
1255                         TALLOC_FREE(lock);
1256                         return true;
1257                 }
1258         }
1259
1260         TALLOC_FREE(lock);
1261         return false;
1262 }
1263
1264 /*
1265  * Walk share mode entries, looking at every lease only once
1266  */
1267
1268 bool share_mode_forall_leases(
1269         struct share_mode_lock *lck,
1270         bool (*fn)(struct share_mode_lock *lck,
1271                    struct share_mode_entry *e,
1272                    void *private_data),
1273         void *private_data)
1274 {
1275         struct share_mode_data *d = lck->data;
1276         uint32_t *leases = NULL;
1277         uint32_t num_leases = 0;
1278         uint32_t i;
1279
1280         leases = talloc_array(talloc_tos(), uint32_t, d->num_share_modes);
1281         if (leases == NULL) {
1282                 return false;
1283         }
1284
1285         for (i=0; i<d->num_share_modes; i++) {
1286                 struct share_mode_entry *e = &d->share_modes[i];
1287                 uint32_t j;
1288                 bool ok, stop;
1289
1290                 ok = is_valid_share_mode_entry(e);
1291                 if (!ok) {
1292                         continue;
1293                 }
1294
1295                 if (e->op_type != LEASE_OPLOCK) {
1296                         continue;
1297                 }
1298
1299                 /*
1300                  * See if we have already seen "e"'s lease. This is
1301                  * O(n^2). If we sort "leases", we can get this down
1302                  * to O(n).
1303                  */
1304
1305                 for (j=0; j<num_leases; j++) {
1306                         uint32_t idx = leases[j];
1307                         struct share_mode_entry *l = &d->share_modes[idx];
1308
1309                         if (smb2_lease_equal(&e->client_guid,
1310                                              &e->lease_key,
1311                                              &l->client_guid,
1312                                              &l->lease_key)) {
1313                                 break;
1314                         }
1315                 }
1316                 if (j < num_leases) {
1317                         /*
1318                          * Don't look at "e"'s lease, we've already
1319                          * seen it.
1320                          */
1321                         continue;
1322                 }
1323
1324                 stop = fn(lck, e, private_data);
1325                 if (stop) {
1326                         TALLOC_FREE(leases);
1327                         return true;
1328                 }
1329
1330                 leases[num_leases] = i;
1331                 num_leases += 1;
1332         }
1333
1334         TALLOC_FREE(leases);
1335         return true;
1336 }