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