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