smbd: Make readlink_talloc() public
[samba.git] / source3 / smbd / files.c
1 /*
2    Unix SMB/CIFS implementation.
3    Files[] structure handling
4    Copyright (C) Andrew Tridgell 1998
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "smbd/smbd.h"
22 #include "smbd/globals.h"
23 #include "smbd/smbXsrv_open.h"
24 #include "libcli/security/security.h"
25 #include "util_tdb.h"
26 #include "lib/util/bitmap.h"
27 #include "lib/util/strv.h"
28
29 #define FILE_HANDLE_OFFSET 0x1000
30
31 static NTSTATUS fsp_attach_smb_fname(struct files_struct *fsp,
32                                      struct smb_filename **_smb_fname);
33
34 /**
35  * create new fsp to be used for file_new or a durable handle reconnect
36  */
37 NTSTATUS fsp_new(struct connection_struct *conn, TALLOC_CTX *mem_ctx,
38                  files_struct **result)
39 {
40         NTSTATUS status = NT_STATUS_NO_MEMORY;
41         files_struct *fsp = NULL;
42         struct smbd_server_connection *sconn = conn->sconn;
43
44         fsp = talloc_zero(mem_ctx, struct files_struct);
45         if (fsp == NULL) {
46                 goto fail;
47         }
48
49         /*
50          * This can't be a child of fsp because the file_handle can be ref'd
51          * when doing a dos/fcb open, which will then share the file_handle
52          * across multiple fsps.
53          */
54         fsp->fh = fd_handle_create(mem_ctx);
55         if (fsp->fh == NULL) {
56                 goto fail;
57         }
58
59         fsp->fsp_flags.use_ofd_locks = !lp_smbd_force_process_locks(SNUM(conn));
60 #ifndef HAVE_OFD_LOCKS
61         fsp->fsp_flags.use_ofd_locks = false;
62 #endif
63
64         fh_set_refcount(fsp->fh, 1);
65         fsp_set_fd(fsp, -1);
66
67         fsp->fnum = FNUM_FIELD_INVALID;
68         fsp->conn = conn;
69         fsp->close_write_time = make_omit_timespec();
70
71         DLIST_ADD(sconn->files, fsp);
72         sconn->num_files += 1;
73
74         conn->num_files_open++;
75
76         DBG_INFO("allocated files structure (%u used)\n",
77                 (unsigned int)sconn->num_files);
78
79         *result = fsp;
80         return NT_STATUS_OK;
81
82 fail:
83         if (fsp != NULL) {
84                 TALLOC_FREE(fsp->fh);
85         }
86         TALLOC_FREE(fsp);
87
88         return status;
89 }
90
91 void fsp_set_gen_id(files_struct *fsp)
92 {
93         static uint64_t gen_id = 1;
94
95         /*
96          * A billion of 64-bit increments per second gives us
97          * more than 500 years of runtime without wrap.
98          */
99         gen_id++;
100         fh_set_gen_id(fsp->fh, gen_id);
101 }
102
103 /****************************************************************************
104  Find first available file slot.
105 ****************************************************************************/
106
107 NTSTATUS fsp_bind_smb(struct files_struct *fsp, struct smb_request *req)
108 {
109         struct smbXsrv_open *op = NULL;
110         NTTIME now;
111         NTSTATUS status;
112
113         if (req == NULL) {
114                 DBG_DEBUG("INTERNAL_OPEN_ONLY, skipping smbXsrv_open\n");
115                 return NT_STATUS_OK;
116         }
117
118         now = timeval_to_nttime(&fsp->open_time);
119
120         status = smbXsrv_open_create(req->xconn,
121                                      fsp->conn->session_info,
122                                      now,
123                                      &op);
124         if (!NT_STATUS_IS_OK(status)) {
125                 return status;
126         }
127         fsp->op = op;
128         op->compat = fsp;
129         fsp->fnum = op->local_id;
130
131         fsp->mid = req->mid;
132         req->chain_fsp = fsp;
133
134         DBG_DEBUG("fsp [%s] mid [%" PRIu64"]\n",
135                 fsp_str_dbg(fsp), fsp->mid);
136
137         return NT_STATUS_OK;
138 }
139
140 NTSTATUS file_new(struct smb_request *req, connection_struct *conn,
141                   files_struct **result)
142 {
143         struct smbd_server_connection *sconn = conn->sconn;
144         files_struct *fsp;
145         NTSTATUS status;
146
147         status = fsp_new(conn, conn, &fsp);
148         if (!NT_STATUS_IS_OK(status)) {
149                 return status;
150         }
151
152         GetTimeOfDay(&fsp->open_time);
153
154         status = fsp_bind_smb(fsp, req);
155         if (!NT_STATUS_IS_OK(status)) {
156                 file_free(NULL, fsp);
157                 return status;
158         }
159
160         fsp_set_gen_id(fsp);
161
162         /*
163          * Create an smb_filename with "" for the base_name.  There are very
164          * few NULL checks, so make sure it's initialized with something. to
165          * be safe until an audit can be done.
166          */
167         fsp->fsp_name = synthetic_smb_fname(fsp,
168                                             "",
169                                             NULL,
170                                             NULL,
171                                             0,
172                                             0);
173         if (fsp->fsp_name == NULL) {
174                 file_free(NULL, fsp);
175                 return NT_STATUS_NO_MEMORY;
176         }
177
178         DBG_INFO("new file %s\n", fsp_fnum_dbg(fsp));
179
180         /* A new fsp invalidates the positive and
181           negative fsp_fi_cache as the new fsp is pushed
182           at the start of the list and we search from
183           a cache hit to the *end* of the list. */
184
185         ZERO_STRUCT(sconn->fsp_fi_cache);
186
187         *result = fsp;
188         return NT_STATUS_OK;
189 }
190
191 NTSTATUS create_internal_fsp(connection_struct *conn,
192                              const struct smb_filename *smb_fname,
193                              struct files_struct **_fsp)
194 {
195         struct files_struct *fsp = NULL;
196         NTSTATUS status;
197
198         status = file_new(NULL, conn, &fsp);
199         if (!NT_STATUS_IS_OK(status)) {
200                 return status;
201         }
202
203         status = fsp_set_smb_fname(fsp, smb_fname);
204         if (!NT_STATUS_IS_OK(status)) {
205                 file_free(NULL, fsp);
206                 return status;
207         }
208
209         *_fsp = fsp;
210         return NT_STATUS_OK;
211 }
212
213 /*
214  * Create an internal fsp for an *existing* directory.
215  *
216  * This should only be used by callers in the VFS that need to control the
217  * opening of the directory. Otherwise use open_internal_dirfsp_at().
218  */
219 NTSTATUS create_internal_dirfsp(connection_struct *conn,
220                                 const struct smb_filename *smb_dname,
221                                 struct files_struct **_fsp)
222 {
223         struct files_struct *fsp = NULL;
224         NTSTATUS status;
225
226         status = create_internal_fsp(conn, smb_dname, &fsp);
227         if (!NT_STATUS_IS_OK(status)) {
228                 return status;
229         }
230
231         fsp->access_mask = FILE_LIST_DIRECTORY;
232         fsp->fsp_flags.is_directory = true;
233         fsp->fsp_flags.is_dirfsp = true;
234
235         *_fsp = fsp;
236         return NT_STATUS_OK;
237 }
238
239 /*
240  * Open an internal fsp for an *existing* directory.
241  */
242 NTSTATUS open_internal_dirfsp(connection_struct *conn,
243                               const struct smb_filename *smb_dname,
244                               int _open_flags,
245                               struct files_struct **_fsp)
246 {
247         struct vfs_open_how how = { .flags = _open_flags, };
248         struct files_struct *fsp = NULL;
249         NTSTATUS status;
250
251         status = create_internal_dirfsp(conn, smb_dname, &fsp);
252         if (!NT_STATUS_IS_OK(status)) {
253                 return status;
254         }
255
256 #ifdef O_DIRECTORY
257         how.flags |= O_DIRECTORY;
258 #endif
259         status = fd_openat(conn->cwd_fsp, fsp->fsp_name, fsp, &how);
260         if (!NT_STATUS_IS_OK(status)) {
261                 DBG_INFO("Could not open fd for %s (%s)\n",
262                          smb_fname_str_dbg(smb_dname),
263                          nt_errstr(status));
264                 file_free(NULL, fsp);
265                 return status;
266         }
267
268         status = vfs_stat_fsp(fsp);
269         if (!NT_STATUS_IS_OK(status)) {
270                 file_free(NULL, fsp);
271                 return status;
272         }
273
274         if (!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
275                 DBG_ERR("%s is not a directory!\n",
276                         smb_fname_str_dbg(smb_dname));
277                 file_free(NULL, fsp);
278                 return NT_STATUS_NOT_A_DIRECTORY;
279         }
280
281         fsp->file_id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
282
283         *_fsp = fsp;
284         return NT_STATUS_OK;
285 }
286
287 /*
288  * Convert a pathref dirfsp into a real fsp. No need to do any cwd
289  * tricks, we just open ".".
290  */
291 NTSTATUS openat_internal_dir_from_pathref(
292         struct files_struct *dirfsp,
293         int _open_flags,
294         struct files_struct **_fsp)
295 {
296         struct connection_struct *conn = dirfsp->conn;
297         struct smb_filename *smb_dname = dirfsp->fsp_name;
298         struct files_struct *fsp = NULL;
299         char dot[] = ".";
300         struct smb_filename smb_dot = {
301                 .base_name = dot,
302                 .flags = smb_dname->flags,
303                 .twrp = smb_dname->twrp,
304         };
305         struct vfs_open_how how = { .flags = _open_flags, };
306         NTSTATUS status;
307
308         status = create_internal_dirfsp(conn, smb_dname, &fsp);
309         if (!NT_STATUS_IS_OK(status)) {
310                 return status;
311         }
312
313         /*
314          * Pointless for opening ".", but you never know...
315          */
316         how.flags |= O_NOFOLLOW;
317
318         status = fd_openat(dirfsp, &smb_dot, fsp, &how);
319         if (!NT_STATUS_IS_OK(status)) {
320                 DBG_INFO("fd_openat(\"%s\", \".\") failed: %s\n",
321                          fsp_str_dbg(dirfsp),
322                          nt_errstr(status));
323                 file_free(NULL, fsp);
324                 return status;
325         }
326
327         fsp->fsp_name->st = smb_dname->st;
328         fsp->file_id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
329         *_fsp = fsp;
330         return NT_STATUS_OK;
331 }
332
333 /*
334  * The "link" in the name doesn't imply link in the filesystem
335  * sense. It's a object that "links" together an fsp and an smb_fname
336  * and the link allocated as talloc child of an fsp.
337  *
338  * The link is created for fsps that openat_pathref_fsp() returns in
339  * smb_fname->fsp. When this fsp is freed by file_free() by some caller
340  * somewhere, the destructor fsp_smb_fname_link_destructor() on the link object
341  * will use the link to reset the reference in smb_fname->fsp that is about to
342  * go away.
343  *
344  * This prevents smb_fname_internal_fsp_destructor() from seeing dangling fsp
345  * pointers.
346  */
347
348 struct fsp_smb_fname_link {
349         struct fsp_smb_fname_link **smb_fname_link;
350         struct files_struct **smb_fname_fsp;
351 };
352
353 static int fsp_smb_fname_link_destructor(struct fsp_smb_fname_link *link)
354 {
355         if (link->smb_fname_link == NULL) {
356                 return 0;
357         }
358
359         *link->smb_fname_link = NULL;
360         *link->smb_fname_fsp = NULL;
361         return 0;
362 }
363
364 static NTSTATUS fsp_smb_fname_link(struct files_struct *fsp,
365                                    struct fsp_smb_fname_link **smb_fname_link,
366                                    struct files_struct **smb_fname_fsp)
367 {
368         struct fsp_smb_fname_link *link = NULL;
369
370         SMB_ASSERT(*smb_fname_link == NULL);
371         SMB_ASSERT(*smb_fname_fsp == NULL);
372
373         link = talloc_zero(fsp, struct fsp_smb_fname_link);
374         if (link == NULL) {
375                 return NT_STATUS_NO_MEMORY;
376         }
377
378         link->smb_fname_link = smb_fname_link;
379         link->smb_fname_fsp = smb_fname_fsp;
380         *smb_fname_link = link;
381         *smb_fname_fsp = fsp;
382
383         talloc_set_destructor(link, fsp_smb_fname_link_destructor);
384         return NT_STATUS_OK;
385 }
386
387 /*
388  * Free a link, carefully avoiding to trigger the link destructor
389  */
390 static void destroy_fsp_smb_fname_link(struct fsp_smb_fname_link **_link)
391 {
392         struct fsp_smb_fname_link *link = *_link;
393
394         if (link == NULL) {
395                 return;
396         }
397         talloc_set_destructor(link, NULL);
398         TALLOC_FREE(link);
399         *_link = NULL;
400 }
401
402 /*
403  * Talloc destructor set on an smb_fname set by openat_pathref_fsp() used to
404  * close the embedded smb_fname->fsp.
405  */
406 static int smb_fname_fsp_destructor(struct smb_filename *smb_fname)
407 {
408         struct files_struct *fsp = smb_fname->fsp;
409         NTSTATUS status;
410         int saved_errno = errno;
411
412         destroy_fsp_smb_fname_link(&smb_fname->fsp_link);
413
414         if (fsp == NULL) {
415                 errno = saved_errno;
416                 return 0;
417         }
418
419         if (fsp_is_alternate_stream(fsp)) {
420                 struct files_struct *tmp_base_fsp = fsp->base_fsp;
421
422                 fsp_set_base_fsp(fsp, NULL);
423
424                 status = fd_close(tmp_base_fsp);
425                 if (!NT_STATUS_IS_OK(status)) {
426                         DBG_ERR("Closing fd for fsp [%s] failed: %s. "
427                                 "Please check your filesystem!!!\n",
428                                 fsp_str_dbg(fsp), nt_errstr(status));
429                 }
430                 file_free(NULL, tmp_base_fsp);
431         }
432
433         status = fd_close(fsp);
434         if (!NT_STATUS_IS_OK(status)) {
435                 DBG_ERR("Closing fd for fsp [%s] failed: %s. "
436                         "Please check your filesystem!!!\n",
437                         fsp_str_dbg(fsp), nt_errstr(status));
438         }
439         file_free(NULL, fsp);
440         smb_fname->fsp = NULL;
441
442         errno = saved_errno;
443         return 0;
444 }
445
446 static NTSTATUS openat_pathref_fullname(
447         struct connection_struct *conn,
448         const struct files_struct *dirfsp,
449         struct files_struct *basefsp,
450         struct smb_filename **full_fname,
451         struct smb_filename *smb_fname,
452         const struct vfs_open_how *how)
453 {
454         struct files_struct *fsp = NULL;
455         bool have_dirfsp = (dirfsp != NULL);
456         bool have_basefsp = (basefsp != NULL);
457         NTSTATUS status;
458
459         DBG_DEBUG("smb_fname [%s]\n", smb_fname_str_dbg(smb_fname));
460
461         SMB_ASSERT(smb_fname->fsp == NULL);
462         SMB_ASSERT(have_dirfsp != have_basefsp);
463
464         status = fsp_new(conn, conn, &fsp);
465         if (!NT_STATUS_IS_OK(status)) {
466                 return status;
467         }
468
469         GetTimeOfDay(&fsp->open_time);
470         fsp_set_gen_id(fsp);
471         ZERO_STRUCT(conn->sconn->fsp_fi_cache);
472
473         fsp->fsp_flags.is_pathref = true;
474
475         status = fsp_attach_smb_fname(fsp, full_fname);
476         if (!NT_STATUS_IS_OK(status)) {
477                 goto fail;
478         }
479         fsp_set_base_fsp(fsp, basefsp);
480
481         status = fd_openat(dirfsp, smb_fname, fsp, how);
482         if (!NT_STATUS_IS_OK(status)) {
483
484                 smb_fname->st = fsp->fsp_name->st;
485
486                 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) ||
487                     NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_PATH_NOT_FOUND) ||
488                     NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK))
489                 {
490                         /*
491                          * streams_xattr return NT_STATUS_NOT_FOUND for
492                          * opens of not yet existing streams.
493                          *
494                          * ELOOP maps to NT_STATUS_OBJECT_PATH_NOT_FOUND
495                          * and this will result from a open request from
496                          * a POSIX client on a symlink.
497                          *
498                          * NT_STATUS_OBJECT_NAME_NOT_FOUND is the simple
499                          * ENOENT case.
500                          *
501                          * NT_STATUS_STOPPED_ON_SYMLINK is returned when trying
502                          * to open a symlink, our callers are not interested in
503                          * this.
504                          */
505                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
506                 }
507                 goto fail;
508         }
509
510         /*
511          * fd_openat() has done an FSTAT on the handle
512          * so update the smb_fname stat info with "truth".
513          * from the handle.
514          */
515         smb_fname->st = fsp->fsp_name->st;
516
517         fsp->fsp_flags.is_directory = S_ISDIR(fsp->fsp_name->st.st_ex_mode);
518
519         fsp->file_id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
520
521         status = fsp_smb_fname_link(fsp,
522                                     &smb_fname->fsp_link,
523                                     &smb_fname->fsp);
524         if (!NT_STATUS_IS_OK(status)) {
525                 goto fail;
526         }
527
528         DBG_DEBUG("fsp [%s]: OK\n", fsp_str_dbg(fsp));
529
530         talloc_set_destructor(smb_fname, smb_fname_fsp_destructor);
531         return NT_STATUS_OK;
532
533 fail:
534         DBG_DEBUG("Opening pathref for [%s] failed: %s\n",
535                   smb_fname_str_dbg(smb_fname),
536                   nt_errstr(status));
537
538         fsp_set_base_fsp(fsp, NULL);
539         fd_close(fsp);
540         file_free(NULL, fsp);
541         return status;
542 }
543
544 /*
545  * Open an internal O_PATH based fsp for smb_fname. If O_PATH is not
546  * available, open O_RDONLY as root. Both is done in fd_open() ->
547  * non_widelink_open(), triggered by setting fsp->fsp_flags.is_pathref to
548  * true.
549  */
550 NTSTATUS openat_pathref_fsp(const struct files_struct *dirfsp,
551                             struct smb_filename *smb_fname)
552 {
553         connection_struct *conn = dirfsp->conn;
554         struct smb_filename *full_fname = NULL;
555         struct smb_filename *base_fname = NULL;
556         struct vfs_open_how how = { .flags = O_RDONLY|O_NONBLOCK, };
557         NTSTATUS status;
558
559         DBG_DEBUG("smb_fname [%s]\n", smb_fname_str_dbg(smb_fname));
560
561         if (smb_fname->fsp != NULL) {
562                 /* We already have one for this name. */
563                 DBG_DEBUG("smb_fname [%s] already has a pathref fsp.\n",
564                         smb_fname_str_dbg(smb_fname));
565                 return NT_STATUS_OK;
566         }
567
568         if (is_named_stream(smb_fname) &&
569             ((conn->fs_capabilities & FILE_NAMED_STREAMS) == 0)) {
570                 DBG_DEBUG("stream open [%s] on non-stream share\n",
571                           smb_fname_str_dbg(smb_fname));
572                 return NT_STATUS_OBJECT_NAME_INVALID;
573         }
574
575         if (!is_named_stream(smb_fname)) {
576                 /*
577                  * openat_pathref_fullname() will make "full_fname" a
578                  * talloc child of the smb_fname->fsp. Don't use
579                  * talloc_tos() to allocate it to avoid making the
580                  * talloc stackframe pool long-lived.
581                  */
582                 full_fname = full_path_from_dirfsp_atname(
583                         conn,
584                         dirfsp,
585                         smb_fname);
586                 if (full_fname == NULL) {
587                         status = NT_STATUS_NO_MEMORY;
588                         goto fail;
589                 }
590                 status = openat_pathref_fullname(
591                         conn, dirfsp, NULL, &full_fname, smb_fname, &how);
592                 TALLOC_FREE(full_fname);
593                 return status;
594         }
595
596         /*
597          * stream open
598          */
599         base_fname = cp_smb_filename_nostream(conn, smb_fname);
600         if (base_fname == NULL) {
601                 return NT_STATUS_NO_MEMORY;
602         }
603
604         full_fname = full_path_from_dirfsp_atname(
605                 conn,   /* no talloc_tos(), see comment above */
606                 dirfsp,
607                 base_fname);
608         if (full_fname == NULL) {
609                 status = NT_STATUS_NO_MEMORY;
610                 goto fail;
611         }
612
613         status = openat_pathref_fullname(
614                 conn, dirfsp, NULL, &full_fname, base_fname, &how);
615         TALLOC_FREE(full_fname);
616         if (!NT_STATUS_IS_OK(status)) {
617                 DBG_DEBUG("openat_pathref_nostream failed: %s\n",
618                           nt_errstr(status));
619                 goto fail;
620         }
621
622         status = open_stream_pathref_fsp(&base_fname->fsp, smb_fname);
623         if (!NT_STATUS_IS_OK(status)) {
624                 DBG_DEBUG("open_stream_pathref_fsp failed: %s\n",
625                           nt_errstr(status));
626                 goto fail;
627         }
628
629         smb_fname_fsp_unlink(base_fname);
630 fail:
631         TALLOC_FREE(base_fname);
632         return status;
633 }
634
635 /*
636  * Open a stream given an already opened base_fsp. Avoid
637  * non_widelink_open: This is only valid for the case where we have a
638  * valid non-cwd_fsp dirfsp that we can pass to SMB_VFS_OPENAT()
639  */
640 NTSTATUS open_stream_pathref_fsp(
641         struct files_struct **_base_fsp,
642         struct smb_filename *smb_fname)
643 {
644         struct files_struct *base_fsp = *_base_fsp;
645         connection_struct *conn = base_fsp->conn;
646         struct smb_filename *base_fname = base_fsp->fsp_name;
647         struct smb_filename *full_fname = NULL;
648         struct vfs_open_how how = { .flags = O_RDONLY|O_NONBLOCK, };
649         NTSTATUS status;
650
651         SMB_ASSERT(smb_fname->fsp == NULL);
652         SMB_ASSERT(is_named_stream(smb_fname));
653
654         full_fname = synthetic_smb_fname(
655                 conn, /* no talloc_tos(), this will be long-lived */
656                 base_fname->base_name,
657                 smb_fname->stream_name,
658                 &smb_fname->st,
659                 smb_fname->twrp,
660                 smb_fname->flags);
661         if (full_fname == NULL) {
662                 return NT_STATUS_NO_MEMORY;
663         }
664
665         status = openat_pathref_fullname(
666                 conn, NULL, base_fsp, &full_fname, smb_fname, &how);
667         TALLOC_FREE(full_fname);
668         return status;
669 }
670
671 static char *path_to_strv(TALLOC_CTX *mem_ctx, const char *path)
672 {
673         char *result = talloc_strdup(mem_ctx, path);
674
675         if (result == NULL) {
676                 return NULL;
677         }
678         string_replace(result, '/', '\0');
679         return result;
680 }
681
682 NTSTATUS readlink_talloc(
683         TALLOC_CTX *mem_ctx,
684         struct files_struct *dirfsp,
685         struct smb_filename *smb_relname,
686         char **_substitute)
687 {
688         char buf[4096];
689         ssize_t ret;
690         char *substitute;
691         NTSTATUS status;
692
693         if (_substitute == NULL) {
694                 return NT_STATUS_OK;
695         }
696
697         if (smb_relname == NULL) {
698                 /*
699                  * We have a Linux O_PATH handle in dirfsp and want to
700                  * read its value, essentially a freadlink
701                  */
702                 smb_relname = synthetic_smb_fname(
703                         talloc_tos(), "", NULL, NULL, 0, 0);
704                 if (smb_relname == NULL) {
705                         DBG_DEBUG("synthetic_smb_fname() failed\n");
706                         return NT_STATUS_NO_MEMORY;
707                 }
708         }
709
710         ret = SMB_VFS_READLINKAT(
711                 dirfsp->conn, dirfsp, smb_relname, buf, sizeof(buf));
712         if (ret < 0) {
713                 status = map_nt_error_from_unix(errno);
714                 DBG_DEBUG("SMB_VFS_READLINKAT() failed: %s\n",
715                           strerror(errno));
716                 return status;
717         }
718
719         if ((size_t)ret == sizeof(buf)) {
720                 /*
721                  * Do we need symlink targets >4k?
722                  */
723                 DBG_DEBUG("Got full %zu bytes from readlink, too long\n",
724                           sizeof(buf));
725                 return NT_STATUS_BUFFER_OVERFLOW;
726         }
727
728         substitute = talloc_strndup(mem_ctx, buf, ret);
729         if (substitute == NULL) {
730                 DBG_DEBUG("talloc_strndup() failed\n");
731                 return NT_STATUS_NO_MEMORY;
732         }
733
734         *_substitute = substitute;
735         return NT_STATUS_OK;
736 }
737
738 NTSTATUS openat_pathref_dirfsp_nosymlink(
739         TALLOC_CTX *mem_ctx,
740         struct connection_struct *conn,
741         const char *path_in,
742         NTTIME twrp,
743         struct smb_filename **_smb_fname,
744         size_t *unparsed,
745         char **substitute)
746 {
747         struct files_struct *dirfsp = conn->cwd_fsp;
748         struct smb_filename full_fname = {
749                 .base_name = NULL,
750                 .twrp = twrp,
751         };
752         struct smb_filename rel_fname = {
753                 .base_name = NULL,
754                 .twrp = twrp,
755         };
756         struct smb_filename *result = NULL;
757         struct files_struct *fsp = NULL;
758         char *path = NULL, *next = NULL;
759         int fd;
760         NTSTATUS status;
761         struct vfs_open_how how = {
762                 .flags = O_NOFOLLOW|O_DIRECTORY,
763                 .mode = 0,
764         };
765
766         DBG_DEBUG("path_in=%s\n", path_in);
767
768         status = fsp_new(conn, conn, &fsp);
769         if (!NT_STATUS_IS_OK(status)) {
770                 DBG_DEBUG("fsp_new() failed: %s\n", nt_errstr(status));
771                 goto fail;
772         }
773         fsp->fsp_name = &full_fname;
774
775 #ifdef O_PATH
776         /*
777          * Add O_PATH manually, doing this by setting
778          * fsp->fsp_flags.is_pathref will make us become_root() in the
779          * non-O_PATH case, which would cause a security problem.
780          */
781         how.flags |= O_PATH;
782 #else
783 #ifdef O_SEARCH
784         /*
785          * O_SEARCH just checks for the "x" bit. We are traversing
786          * directories, so we don't need the implicit O_RDONLY ("r"
787          * permissions) but only the "x"-permissions requested by
788          * O_SEARCH. We need either O_PATH or O_SEARCH to correctly
789          * function, without either we will incorrectly require also
790          * the "r" bit when traversing the directory hierarchy.
791          */
792         how.flags |= O_SEARCH;
793 #endif
794 #endif
795
796         full_fname.base_name = talloc_strdup(talloc_tos(), "");
797         if (full_fname.base_name == NULL) {
798                 DBG_DEBUG("talloc_strdup() failed\n");
799                 goto nomem;
800         }
801
802         /*
803          * First split the path into individual components.
804          */
805         path = path_to_strv(talloc_tos(), path_in);
806         if (path == NULL) {
807                 DBG_DEBUG("path_to_strv() failed\n");
808                 goto nomem;
809         }
810
811         /*
812          * First we loop over all components
813          * in order to verify, there's no '.' or '..'
814          */
815         rel_fname.base_name = path;
816         while (rel_fname.base_name != NULL) {
817
818                 next = strv_next(path, rel_fname.base_name);
819
820                 if (ISDOT(rel_fname.base_name) ||
821                     ISDOTDOT(rel_fname.base_name)) {
822                         DBG_DEBUG("%s contains a dot\n", path_in);
823                         status = NT_STATUS_OBJECT_NAME_INVALID;
824                         goto fail;
825                 }
826
827                 /* Check veto files. */
828                 if (IS_VETO_PATH(conn, rel_fname.base_name)) {
829                         DBG_DEBUG("%s contains veto files path component %s\n",
830                                   path_in, rel_fname.base_name);
831                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
832                         goto fail;
833                 }
834
835                 rel_fname.base_name = next;
836         }
837
838         if (conn->open_how_resolve & VFS_OPEN_HOW_RESOLVE_NO_SYMLINKS) {
839
840                 /*
841                  * Try a direct openat2 with RESOLVE_NO_SYMLINKS to
842                  * avoid the openat/close loop further down.
843                  */
844
845                 rel_fname.base_name = discard_const_p(char, path_in);
846                 how.resolve = VFS_OPEN_HOW_RESOLVE_NO_SYMLINKS;
847
848                 fd = SMB_VFS_OPENAT(conn, dirfsp, &rel_fname, fsp, &how);
849                 if (fd >= 0) {
850                         fsp_set_fd(fsp, fd);
851                         TALLOC_FREE(full_fname.base_name);
852                         full_fname = rel_fname;
853                         goto done;
854                 }
855
856                 status = map_nt_error_from_unix(errno);
857                 DBG_DEBUG("SMB_VFS_OPENAT(%s, %s, RESOLVE_NO_SYMLINKS) "
858                           "returned %d %s => %s\n",
859                           smb_fname_str_dbg(dirfsp->fsp_name), path_in,
860                           errno, strerror(errno), nt_errstr(status));
861                 SMB_ASSERT(fd == -1);
862                 switch (errno) {
863                 case ENOSYS:
864                         /*
865                          * We got ENOSYS, so fallback to the old code
866                          * if the kernel doesn't support openat2() yet.
867                          */
868                         break;
869
870                 case ELOOP:
871                 case ENOTDIR:
872                         /*
873                          * For ELOOP we also fallback in order to
874                          * return the correct information with
875                          * NT_STATUS_STOPPED_ON_SYMLINK.
876                          *
877                          * O_NOFOLLOW|O_DIRECTORY results in
878                          * ENOTDIR instead of ELOOP for the final
879                          * component.
880                          */
881                         break;
882
883                 case ENOENT:
884                         /*
885                          * If we got ENOENT, the filesystem could
886                          * be case sensitive. For now we only do
887                          * the get_real_filename_at() dance in
888                          * the fallback loop below.
889                          */
890                         break;
891
892                 default:
893                         goto fail;
894                 }
895
896                 /*
897                  * Just fallback to the openat loop
898                  */
899                 how.resolve = 0;
900         }
901
902         /*
903          * Now we loop over all components
904          * opening each one and using it
905          * as dirfd for the next one.
906          *
907          * It means we can detect symlinks
908          * within the path.
909          */
910         rel_fname.base_name = path;
911 next:
912         next = strv_next(path, rel_fname.base_name);
913
914         fd = SMB_VFS_OPENAT(
915                 conn,
916                 dirfsp,
917                 &rel_fname,
918                 fsp,
919                 &how);
920
921         if ((fd == -1) && (errno == ENOENT)) {
922                 const char *orig_base_name = rel_fname.base_name;
923
924                 status = get_real_filename_at(
925                         dirfsp,
926                         rel_fname.base_name,
927                         talloc_tos(),
928                         &rel_fname.base_name);
929
930                 if (!NT_STATUS_IS_OK(status)) {
931                         DBG_DEBUG("get_real_filename_at failed: %s\n",
932                                   nt_errstr(status));
933                         goto fail;
934                 }
935
936                 /* Name might have been demangled - check veto files. */
937                 if (IS_VETO_PATH(conn, rel_fname.base_name)) {
938                         DBG_DEBUG("%s contains veto files path component "
939                                   "%s => %s\n",
940                                   path_in,
941                                   orig_base_name,
942                                   rel_fname.base_name);
943                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
944                         goto fail;
945                 }
946
947                 fd = SMB_VFS_OPENAT(
948                         conn,
949                         dirfsp,
950                         &rel_fname,
951                         fsp,
952                         &how);
953         }
954
955         /*
956          * O_NOFOLLOW|O_DIRECTORY results in
957          * ENOTDIR instead of ELOOP.
958          *
959          * But we should be prepared to handle ELOOP too.
960          */
961         if ((fd == -1) && (errno == ENOTDIR || errno == ELOOP)) {
962                 NTSTATUS orig_status = map_nt_error_from_unix(errno);
963
964                 status = readlink_talloc(
965                         mem_ctx, dirfsp, &rel_fname, substitute);
966
967                 if (NT_STATUS_IS_OK(status)) {
968                         /*
969                          * readlink_talloc() found a symlink
970                          */
971                         status = NT_STATUS_STOPPED_ON_SYMLINK;
972
973                         if (unparsed != NULL) {
974                                 if (next == NULL) {
975                                         *unparsed = 0;
976                                 } else {
977                                         size_t parsed = next - path;
978                                         size_t len = talloc_get_size(path);
979                                         *unparsed = len - parsed;
980                                 }
981                         }
982                         /*
983                          * If we're on an MSDFS share, see if this is
984                          * an MSDFS link.
985                          */
986                         if (lp_host_msdfs() &&
987                             lp_msdfs_root(SNUM(conn)) &&
988                             (substitute != NULL) &&
989                             strnequal(*substitute, "msdfs:", 6) &&
990                             is_msdfs_link(dirfsp, &rel_fname))
991                         {
992                                 status = NT_STATUS_PATH_NOT_COVERED;
993                         }
994                 } else {
995
996                         DBG_DEBUG("readlink_talloc failed: %s\n",
997                                   nt_errstr(status));
998                         /*
999                          * Restore the error status from SMB_VFS_OPENAT()
1000                          */
1001                         status = orig_status;
1002                 }
1003                 goto fail;
1004         }
1005
1006         if (fd == -1) {
1007                 status = map_nt_error_from_unix(errno);
1008                 DBG_DEBUG("SMB_VFS_OPENAT() failed: %s\n",
1009                           strerror(errno));
1010                 goto fail;
1011         }
1012         fsp_set_fd(fsp, fd);
1013
1014         fsp->fsp_flags.is_directory = true; /* See O_DIRECTORY above */
1015
1016         full_fname.base_name = talloc_asprintf_append_buffer(
1017                         full_fname.base_name,
1018                         "%s%s",
1019                         full_fname.base_name[0] == '\0' ? "" : "/",
1020                         rel_fname.base_name);
1021
1022         if (full_fname.base_name == NULL) {
1023                 DBG_DEBUG("talloc_asprintf_append_buffer() failed\n");
1024                 goto nomem;
1025         }
1026
1027         if (next != NULL) {
1028                 struct files_struct *tmp = NULL;
1029
1030                 if (dirfsp != conn->cwd_fsp) {
1031                         fd_close(dirfsp);
1032                 }
1033
1034                 tmp = dirfsp;
1035                 dirfsp = fsp;
1036
1037                 if (tmp == conn->cwd_fsp) {
1038                         status = fsp_new(conn, conn, &fsp);
1039                         if (!NT_STATUS_IS_OK(status)) {
1040                                 DBG_DEBUG("fsp_new() failed: %s\n",
1041                                           nt_errstr(status));
1042                                 goto fail;
1043                         }
1044                         fsp->fsp_name = &full_fname;
1045                 } else {
1046                         fsp = tmp;
1047                 }
1048
1049                 rel_fname.base_name = next;
1050
1051                 goto next;
1052         }
1053
1054         if (dirfsp != conn->cwd_fsp) {
1055                 dirfsp->fsp_name = NULL;
1056                 SMB_ASSERT(fsp_get_pathref_fd(dirfsp) != -1);
1057                 fd_close(dirfsp);
1058                 file_free(NULL, dirfsp);
1059                 dirfsp = NULL;
1060         }
1061
1062 done:
1063         fsp->fsp_flags.is_pathref = true;
1064         fsp->fsp_name = NULL;
1065
1066         status = fsp_set_smb_fname(fsp, &full_fname);
1067         if (!NT_STATUS_IS_OK(status)) {
1068                 DBG_DEBUG("fsp_set_smb_fname() failed: %s\n",
1069                           nt_errstr(status));
1070                 goto fail;
1071         }
1072
1073         status = vfs_stat_fsp(fsp);
1074         if (!NT_STATUS_IS_OK(status)) {
1075                 DBG_DEBUG("vfs_stat_fsp(%s) failed: %s\n",
1076                           fsp_str_dbg(fsp),
1077                           nt_errstr(status));
1078                 goto fail;
1079         }
1080         /*
1081          * We must correctly set fsp->file_id as code inside
1082          * open.c will use this to check if delete_on_close
1083          * has been set on the dirfsp.
1084          */
1085         fsp->file_id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
1086
1087         result = cp_smb_filename(mem_ctx, fsp->fsp_name);
1088         if (result == NULL) {
1089                 DBG_DEBUG("cp_smb_filename() failed\n");
1090                 goto nomem;
1091         }
1092
1093         status = fsp_smb_fname_link(fsp,
1094                                         &result->fsp_link,
1095                                         &result->fsp);
1096         if (!NT_STATUS_IS_OK(status)) {
1097                 goto fail;
1098         }
1099         talloc_set_destructor(result, smb_fname_fsp_destructor);
1100
1101         *_smb_fname = result;
1102
1103         DBG_DEBUG("returning %s\n", smb_fname_str_dbg(result));
1104
1105         return NT_STATUS_OK;
1106
1107 nomem:
1108         status = NT_STATUS_NO_MEMORY;
1109 fail:
1110         if (fsp != NULL) {
1111                 if (fsp_get_pathref_fd(fsp) != -1) {
1112                         fd_close(fsp);
1113                 }
1114                 file_free(NULL, fsp);
1115                 fsp = NULL;
1116         }
1117
1118         if ((dirfsp != NULL) && (dirfsp != conn->cwd_fsp)) {
1119                 dirfsp->fsp_name = NULL;
1120                 SMB_ASSERT(fsp_get_pathref_fd(dirfsp) != -1);
1121                 fd_close(dirfsp);
1122                 file_free(NULL, dirfsp);
1123                 dirfsp = NULL;
1124         }
1125
1126         TALLOC_FREE(path);
1127         return status;
1128 }
1129
1130 void smb_fname_fsp_unlink(struct smb_filename *smb_fname)
1131 {
1132         talloc_set_destructor(smb_fname, NULL);
1133         smb_fname->fsp = NULL;
1134         destroy_fsp_smb_fname_link(&smb_fname->fsp_link);
1135 }
1136
1137 /*
1138  * Move any existing embedded fsp refs from the src name to the
1139  * destination. It's safe to call this on src smb_fname's that have no embedded
1140  * pathref fsp.
1141  */
1142 NTSTATUS move_smb_fname_fsp_link(struct smb_filename *smb_fname_dst,
1143                                  struct smb_filename *smb_fname_src)
1144 {
1145         NTSTATUS status;
1146
1147         /*
1148          * The target should always not be linked yet!
1149          */
1150         SMB_ASSERT(smb_fname_dst->fsp == NULL);
1151         SMB_ASSERT(smb_fname_dst->fsp_link == NULL);
1152
1153         if (smb_fname_src->fsp == NULL) {
1154                 return NT_STATUS_OK;
1155         }
1156
1157         status = fsp_smb_fname_link(smb_fname_src->fsp,
1158                                     &smb_fname_dst->fsp_link,
1159                                     &smb_fname_dst->fsp);
1160         if (!NT_STATUS_IS_OK(status)) {
1161                 return status;
1162         }
1163
1164         talloc_set_destructor(smb_fname_dst, smb_fname_fsp_destructor);
1165
1166         smb_fname_fsp_unlink(smb_fname_src);
1167
1168         return NT_STATUS_OK;
1169 }
1170
1171 /**
1172  * Create an smb_fname and open smb_fname->fsp pathref
1173  **/
1174 NTSTATUS synthetic_pathref(TALLOC_CTX *mem_ctx,
1175                            struct files_struct *dirfsp,
1176                            const char *base_name,
1177                            const char *stream_name,
1178                            const SMB_STRUCT_STAT *psbuf,
1179                            NTTIME twrp,
1180                            uint32_t flags,
1181                            struct smb_filename **_smb_fname)
1182 {
1183         struct smb_filename *smb_fname = NULL;
1184         NTSTATUS status;
1185
1186         smb_fname = synthetic_smb_fname(mem_ctx,
1187                                         base_name,
1188                                         stream_name,
1189                                         psbuf,
1190                                         twrp,
1191                                         flags);
1192         if (smb_fname == NULL) {
1193                 return NT_STATUS_NO_MEMORY;
1194         }
1195
1196         status = openat_pathref_fsp(dirfsp, smb_fname);
1197         if (!NT_STATUS_IS_OK(status)) {
1198                 DBG_ERR("opening [%s] failed\n",
1199                         smb_fname_str_dbg(smb_fname));
1200                 TALLOC_FREE(smb_fname);
1201                 return status;
1202         }
1203
1204         *_smb_fname = smb_fname;
1205         return NT_STATUS_OK;
1206 }
1207
1208 static int atname_destructor(struct smb_filename *smb_fname)
1209 {
1210         destroy_fsp_smb_fname_link(&smb_fname->fsp_link);
1211         return 0;
1212 }
1213
1214 /**
1215  * Turn a path into a parent pathref and atname
1216  *
1217  * This returns the parent pathref in _parent and the name relative to it. If
1218  * smb_fname was a pathref (ie smb_fname->fsp != NULL), then _atname will be a
1219  * pathref as well, ie _atname->fsp will point at the same fsp as
1220  * smb_fname->fsp.
1221  **/
1222 NTSTATUS parent_pathref(TALLOC_CTX *mem_ctx,
1223                         struct files_struct *dirfsp,
1224                         const struct smb_filename *smb_fname,
1225                         struct smb_filename **_parent,
1226                         struct smb_filename **_atname)
1227 {
1228         struct smb_filename *parent = NULL;
1229         struct smb_filename *atname = NULL;
1230         NTSTATUS status;
1231
1232         status = SMB_VFS_PARENT_PATHNAME(dirfsp->conn,
1233                                          mem_ctx,
1234                                          smb_fname,
1235                                          &parent,
1236                                          &atname);
1237         if (!NT_STATUS_IS_OK(status)) {
1238                 return status;
1239         }
1240
1241         /*
1242          * We know that the parent name must
1243          * exist, and the name has been canonicalized
1244          * even if this was a POSIX pathname.
1245          * Ensure that we follow symlinks for
1246          * the parent. See the torture test
1247          * POSIX-SYMLINK-PARENT for details.
1248          */
1249         parent->flags &= ~SMB_FILENAME_POSIX_PATH;
1250
1251         status = openat_pathref_fsp(dirfsp, parent);
1252         if (!NT_STATUS_IS_OK(status)) {
1253                 TALLOC_FREE(parent);
1254                 return status;
1255         }
1256
1257         if (smb_fname->fsp != NULL) {
1258                 status = fsp_smb_fname_link(smb_fname->fsp,
1259                                             &atname->fsp_link,
1260                                             &atname->fsp);
1261                 if (!NT_STATUS_IS_OK(status)) {
1262                         TALLOC_FREE(parent);
1263                         return status;
1264                 }
1265                 talloc_set_destructor(atname, atname_destructor);
1266         }
1267         *_parent = parent;
1268         *_atname = atname;
1269         return NT_STATUS_OK;
1270 }
1271
1272 static bool close_file_in_loop(struct files_struct *fsp,
1273                                enum file_close_type close_type)
1274 {
1275         if (fsp_is_alternate_stream(fsp)) {
1276                 /*
1277                  * This is a stream, it can't be a base
1278                  */
1279                 SMB_ASSERT(fsp->stream_fsp == NULL);
1280                 SMB_ASSERT(fsp->base_fsp->stream_fsp == fsp);
1281
1282                 /*
1283                  * Remove the base<->stream link so that
1284                  * close_file_free() does not close fsp->base_fsp as
1285                  * well. This would destroy walking the linked list of
1286                  * fsps.
1287                  */
1288                 fsp->base_fsp->stream_fsp = NULL;
1289                 fsp->base_fsp = NULL;
1290
1291                 close_file_free(NULL, &fsp, close_type);
1292                 return NULL;
1293         }
1294
1295         if (fsp->stream_fsp != NULL) {
1296                 /*
1297                  * This is the base of a stream.
1298                  */
1299                 SMB_ASSERT(fsp->stream_fsp->base_fsp == fsp);
1300
1301                 /*
1302                  * Remove the base<->stream link. This will make fsp
1303                  * look like a normal fsp for the next round.
1304                  */
1305                 fsp->stream_fsp->base_fsp = NULL;
1306                 fsp->stream_fsp = NULL;
1307
1308                 /*
1309                  * Have us called back a second time. In the second
1310                  * round, "fsp" now looks like a normal fsp.
1311                  */
1312                 return false;
1313         }
1314
1315         close_file_free(NULL, &fsp, close_type);
1316         return true;
1317 }
1318
1319 /****************************************************************************
1320  Close all open files for a connection.
1321 ****************************************************************************/
1322
1323 struct file_close_conn_state {
1324         struct connection_struct *conn;
1325         enum file_close_type close_type;
1326         bool fsp_left_behind;
1327 };
1328
1329 static struct files_struct *file_close_conn_fn(
1330         struct files_struct *fsp,
1331         void *private_data)
1332 {
1333         struct file_close_conn_state *state = private_data;
1334         bool did_close;
1335
1336         if (fsp->conn != state->conn) {
1337                 return NULL;
1338         }
1339
1340         if (fsp->op != NULL && fsp->op->global->durable) {
1341                 /*
1342                  * A tree disconnect closes a durable handle
1343                  */
1344                 fsp->op->global->durable = false;
1345         }
1346
1347         did_close = close_file_in_loop(fsp, state->close_type);
1348         if (!did_close) {
1349                 state->fsp_left_behind = true;
1350         }
1351
1352         return NULL;
1353 }
1354
1355 void file_close_conn(connection_struct *conn, enum file_close_type close_type)
1356 {
1357         struct file_close_conn_state state = { .conn = conn,
1358                                                .close_type = close_type };
1359
1360         files_forall(conn->sconn, file_close_conn_fn, &state);
1361
1362         if (state.fsp_left_behind) {
1363                 state.fsp_left_behind = false;
1364                 files_forall(conn->sconn, file_close_conn_fn, &state);
1365                 SMB_ASSERT(!state.fsp_left_behind);
1366         }
1367 }
1368
1369 /****************************************************************************
1370  Initialise file structures.
1371 ****************************************************************************/
1372
1373 static int files_max_open_fds;
1374
1375 bool file_init_global(void)
1376 {
1377         int request_max = lp_max_open_files();
1378         int real_lim;
1379         int real_max;
1380
1381         if (files_max_open_fds != 0) {
1382                 return true;
1383         }
1384
1385         /*
1386          * Set the max_open files to be the requested
1387          * max plus a fudgefactor to allow for the extra
1388          * fd's we need such as log files etc...
1389          */
1390         real_lim = set_maxfiles(request_max + MAX_OPEN_FUDGEFACTOR);
1391
1392         real_max = real_lim - MAX_OPEN_FUDGEFACTOR;
1393
1394         if (real_max + FILE_HANDLE_OFFSET + MAX_OPEN_PIPES > 65536) {
1395                 real_max = 65536 - FILE_HANDLE_OFFSET - MAX_OPEN_PIPES;
1396         }
1397
1398         if (real_max != request_max) {
1399                 DEBUG(1, ("file_init_global: Information only: requested %d "
1400                           "open files, %d are available.\n",
1401                           request_max, real_max));
1402         }
1403
1404         SMB_ASSERT(real_max > 100);
1405
1406         files_max_open_fds = real_max;
1407         return true;
1408 }
1409
1410 bool file_init(struct smbd_server_connection *sconn)
1411 {
1412         bool ok;
1413
1414         ok = file_init_global();
1415         if (!ok) {
1416                 return false;
1417         }
1418
1419         sconn->real_max_open_files = files_max_open_fds;
1420
1421         return true;
1422 }
1423
1424 /****************************************************************************
1425  Close files open by a specified vuid.
1426 ****************************************************************************/
1427
1428 struct file_close_user_state {
1429         uint64_t vuid;
1430         bool fsp_left_behind;
1431 };
1432
1433 static struct files_struct *file_close_user_fn(
1434         struct files_struct *fsp,
1435         void *private_data)
1436 {
1437         struct file_close_user_state *state = private_data;
1438         bool did_close;
1439
1440         if (fsp->vuid != state->vuid) {
1441                 return NULL;
1442         }
1443
1444         did_close = close_file_in_loop(fsp, SHUTDOWN_CLOSE);
1445         if (!did_close) {
1446                 state->fsp_left_behind = true;
1447         }
1448
1449         return NULL;
1450 }
1451
1452 void file_close_user(struct smbd_server_connection *sconn, uint64_t vuid)
1453 {
1454         struct file_close_user_state state = { .vuid = vuid };
1455
1456         files_forall(sconn, file_close_user_fn, &state);
1457
1458         if (state.fsp_left_behind) {
1459                 state.fsp_left_behind = false;
1460                 files_forall(sconn, file_close_user_fn, &state);
1461                 SMB_ASSERT(!state.fsp_left_behind);
1462         }
1463 }
1464
1465 /*
1466  * Walk the files table until "fn" returns non-NULL
1467  */
1468
1469 struct files_struct *files_forall(
1470         struct smbd_server_connection *sconn,
1471         struct files_struct *(*fn)(struct files_struct *fsp,
1472                                    void *private_data),
1473         void *private_data)
1474 {
1475         struct files_struct *fsp, *next;
1476
1477         for (fsp = sconn->files; fsp; fsp = next) {
1478                 struct files_struct *ret;
1479                 next = fsp->next;
1480                 ret = fn(fsp, private_data);
1481                 if (ret != NULL) {
1482                         return ret;
1483                 }
1484         }
1485         return NULL;
1486 }
1487
1488 /****************************************************************************
1489  Find a fsp given a file descriptor.
1490 ****************************************************************************/
1491
1492 files_struct *file_find_fd(struct smbd_server_connection *sconn, int fd)
1493 {
1494         int count=0;
1495         files_struct *fsp;
1496
1497         for (fsp=sconn->files; fsp; fsp=fsp->next,count++) {
1498                 if (fsp_get_pathref_fd(fsp) == fd) {
1499                         if (count > 10) {
1500                                 DLIST_PROMOTE(sconn->files, fsp);
1501                         }
1502                         return fsp;
1503                 }
1504         }
1505
1506         return NULL;
1507 }
1508
1509 /****************************************************************************
1510  Find a fsp given a device, inode and file_id.
1511 ****************************************************************************/
1512
1513 files_struct *file_find_dif(struct smbd_server_connection *sconn,
1514                             struct file_id id, unsigned long gen_id)
1515 {
1516         int count=0;
1517         files_struct *fsp;
1518
1519         if (gen_id == 0) {
1520                 return NULL;
1521         }
1522
1523         for (fsp = sconn->files; fsp; fsp = fsp->next,count++) {
1524                 /*
1525                  * We can have a fsp->fh->fd == -1 here as it could be a stat
1526                  * open.
1527                  */
1528                 if (!file_id_equal(&fsp->file_id, &id)) {
1529                         continue;
1530                 }
1531                 if (!fsp->fsp_flags.is_fsa) {
1532                         continue;
1533                 }
1534                 if (fh_get_gen_id(fsp->fh) != gen_id) {
1535                         continue;
1536                 }
1537                 if (count > 10) {
1538                         DLIST_PROMOTE(sconn->files, fsp);
1539                 }
1540                 /* Paranoia check. */
1541                 if ((fsp_get_pathref_fd(fsp) == -1) &&
1542                     (fsp->oplock_type != NO_OPLOCK &&
1543                      fsp->oplock_type != LEASE_OPLOCK))
1544                 {
1545                         struct file_id_buf idbuf;
1546
1547                         DBG_ERR("file %s file_id = "
1548                                 "%s, gen = %u oplock_type = %u is a "
1549                                 "stat open with oplock type !\n",
1550                                 fsp_str_dbg(fsp),
1551                                 file_id_str_buf(fsp->file_id, &idbuf),
1552                                 (unsigned int)fh_get_gen_id(fsp->fh),
1553                                 (unsigned int)fsp->oplock_type);
1554                         smb_panic("file_find_dif");
1555                 }
1556                 return fsp;
1557         }
1558
1559         return NULL;
1560 }
1561
1562 /****************************************************************************
1563  Find the first fsp given a device and inode.
1564  We use a singleton cache here to speed up searching from getfilepathinfo
1565  calls.
1566 ****************************************************************************/
1567
1568 files_struct *file_find_di_first(struct smbd_server_connection *sconn,
1569                                  struct file_id id,
1570                                  bool need_fsa)
1571 {
1572         files_struct *fsp;
1573
1574         if (file_id_equal(&sconn->fsp_fi_cache.id, &id)) {
1575                 /* Positive or negative cache hit. */
1576                 return sconn->fsp_fi_cache.fsp;
1577         }
1578
1579         sconn->fsp_fi_cache.id = id;
1580
1581         for (fsp=sconn->files;fsp;fsp=fsp->next) {
1582                 if (need_fsa && !fsp->fsp_flags.is_fsa) {
1583                         continue;
1584                 }
1585                 if (file_id_equal(&fsp->file_id, &id)) {
1586                         /* Setup positive cache. */
1587                         sconn->fsp_fi_cache.fsp = fsp;
1588                         return fsp;
1589                 }
1590         }
1591
1592         /* Setup negative cache. */
1593         sconn->fsp_fi_cache.fsp = NULL;
1594         return NULL;
1595 }
1596
1597 /****************************************************************************
1598  Find the next fsp having the same device and inode.
1599 ****************************************************************************/
1600
1601 files_struct *file_find_di_next(files_struct *start_fsp,
1602                                 bool need_fsa)
1603 {
1604         files_struct *fsp;
1605
1606         for (fsp = start_fsp->next;fsp;fsp=fsp->next) {
1607                 if (need_fsa && !fsp->fsp_flags.is_fsa) {
1608                         continue;
1609                 }
1610                 if (file_id_equal(&fsp->file_id, &start_fsp->file_id)) {
1611                         return fsp;
1612                 }
1613         }
1614
1615         return NULL;
1616 }
1617
1618 struct files_struct *file_find_one_fsp_from_lease_key(
1619         struct smbd_server_connection *sconn,
1620         const struct smb2_lease_key *lease_key)
1621 {
1622         struct files_struct *fsp;
1623
1624         for (fsp = sconn->files; fsp; fsp=fsp->next) {
1625                 if ((fsp->lease != NULL) &&
1626                     (fsp->lease->lease.lease_key.data[0] ==
1627                      lease_key->data[0]) &&
1628                     (fsp->lease->lease.lease_key.data[1] ==
1629                      lease_key->data[1])) {
1630                         return fsp;
1631                 }
1632         }
1633         return NULL;
1634 }
1635
1636 /****************************************************************************
1637  Find any fsp open with a pathname below that of an already open path.
1638 ****************************************************************************/
1639
1640 bool file_find_subpath(files_struct *dir_fsp)
1641 {
1642         files_struct *fsp;
1643         size_t dlen;
1644         char *d_fullname = NULL;
1645
1646         d_fullname = talloc_asprintf(talloc_tos(), "%s/%s",
1647                                      dir_fsp->conn->connectpath,
1648                                      dir_fsp->fsp_name->base_name);
1649
1650         if (!d_fullname) {
1651                 return false;
1652         }
1653
1654         dlen = strlen(d_fullname);
1655
1656         for (fsp=dir_fsp->conn->sconn->files; fsp; fsp=fsp->next) {
1657                 char *d1_fullname;
1658
1659                 if (fsp == dir_fsp) {
1660                         continue;
1661                 }
1662
1663                 d1_fullname = talloc_asprintf(talloc_tos(),
1664                                         "%s/%s",
1665                                         fsp->conn->connectpath,
1666                                         fsp->fsp_name->base_name);
1667
1668                 /*
1669                  * If the open file has a path that is a longer
1670                  * component, then it's a subpath.
1671                  */
1672                 if (strnequal(d_fullname, d1_fullname, dlen) &&
1673                                 (d1_fullname[dlen] == '/')) {
1674                         TALLOC_FREE(d1_fullname);
1675                         TALLOC_FREE(d_fullname);
1676                         return true;
1677                 }
1678                 TALLOC_FREE(d1_fullname);
1679         }
1680
1681         TALLOC_FREE(d_fullname);
1682         return false;
1683 }
1684
1685 /****************************************************************************
1686  Free up a fsp.
1687 ****************************************************************************/
1688
1689 static void fsp_free(files_struct *fsp)
1690 {
1691         struct smbd_server_connection *sconn = fsp->conn->sconn;
1692
1693         if (fsp == sconn->fsp_fi_cache.fsp) {
1694                 ZERO_STRUCT(sconn->fsp_fi_cache);
1695         }
1696
1697         DLIST_REMOVE(sconn->files, fsp);
1698         SMB_ASSERT(sconn->num_files > 0);
1699         sconn->num_files--;
1700
1701         TALLOC_FREE(fsp->fake_file_handle);
1702
1703         if (fh_get_refcount(fsp->fh) == 1) {
1704                 TALLOC_FREE(fsp->fh);
1705         } else {
1706                 size_t new_refcount = fh_get_refcount(fsp->fh) - 1;
1707                 fh_set_refcount(fsp->fh, new_refcount);
1708         }
1709
1710         if (fsp->lease != NULL) {
1711                 if (fsp->lease->ref_count == 1) {
1712                         TALLOC_FREE(fsp->lease);
1713                 } else {
1714                         fsp->lease->ref_count--;
1715                 }
1716         }
1717
1718         fsp->conn->num_files_open--;
1719
1720         if (fsp->fsp_name != NULL &&
1721             fsp->fsp_name->fsp_link != NULL)
1722         {
1723                 /*
1724                  * Free fsp_link of fsp->fsp_name. To do this in the correct
1725                  * talloc destructor order we have to do it here. The
1726                  * talloc_free() of the link should set the fsp pointer to NULL.
1727                  */
1728                 TALLOC_FREE(fsp->fsp_name->fsp_link);
1729                 SMB_ASSERT(fsp->fsp_name->fsp == NULL);
1730         }
1731
1732         /* this is paranoia, just in case someone tries to reuse the
1733            information */
1734         ZERO_STRUCTP(fsp);
1735
1736         /* fsp->fsp_name is a talloc child and is free'd automatically. */
1737         TALLOC_FREE(fsp);
1738 }
1739
1740 /*
1741  * Rundown of all smb-related sub-structures of an fsp
1742  */
1743 void fsp_unbind_smb(struct smb_request *req, files_struct *fsp)
1744 {
1745         if (fsp == fsp->conn->cwd_fsp) {
1746                 return;
1747         }
1748
1749         if (fsp->notify) {
1750                 size_t len = fsp_fullbasepath(fsp, NULL, 0);
1751                 char fullpath[len+1];
1752
1753                 fsp_fullbasepath(fsp, fullpath, sizeof(fullpath));
1754
1755                 /*
1756                  * Avoid /. at the end of the path name. notify can't
1757                  * deal with it.
1758                  */
1759                 if (len > 1 && fullpath[len-1] == '.' &&
1760                     fullpath[len-2] == '/') {
1761                         fullpath[len-2] = '\0';
1762                 }
1763
1764                 notify_remove(fsp->conn->sconn->notify_ctx, fsp, fullpath);
1765                 TALLOC_FREE(fsp->notify);
1766         }
1767
1768         /* Ensure this event will never fire. */
1769         TALLOC_FREE(fsp->update_write_time_event);
1770
1771         if (fsp->op != NULL) {
1772                 fsp->op->compat = NULL;
1773         }
1774         TALLOC_FREE(fsp->op);
1775
1776         if ((req != NULL) && (fsp == req->chain_fsp)) {
1777                 req->chain_fsp = NULL;
1778         }
1779
1780         /*
1781          * Clear all possible chained fsp
1782          * pointers in the SMB2 request queue.
1783          */
1784         remove_smb2_chained_fsp(fsp);
1785 }
1786
1787 void file_free(struct smb_request *req, files_struct *fsp)
1788 {
1789         struct smbd_server_connection *sconn = fsp->conn->sconn;
1790         uint64_t fnum = fsp->fnum;
1791
1792         fsp_unbind_smb(req, fsp);
1793
1794         /* Drop all remaining extensions. */
1795         vfs_remove_all_fsp_extensions(fsp);
1796
1797         fsp_free(fsp);
1798
1799         DBG_INFO("freed files structure %"PRIu64" (%zu used)\n",
1800                  fnum,
1801                  sconn->num_files);
1802 }
1803
1804 /****************************************************************************
1805  Get an fsp from a packet given a 16 bit fnum.
1806 ****************************************************************************/
1807
1808 files_struct *file_fsp(struct smb_request *req, uint16_t fid)
1809 {
1810         struct smbXsrv_open *op;
1811         NTSTATUS status;
1812         NTTIME now = 0;
1813         files_struct *fsp;
1814
1815         if (req == NULL) {
1816                 /*
1817                  * We should never get here. req==NULL could in theory
1818                  * only happen from internal opens with a non-zero
1819                  * root_dir_fid. Internal opens just don't do that, at
1820                  * least they are not supposed to do so. And if they
1821                  * start to do so, they better fake up a smb_request
1822                  * from which we get the right smbd_server_conn. While
1823                  * this should never happen, let's return NULL here.
1824                  */
1825                 return NULL;
1826         }
1827
1828         if (req->chain_fsp != NULL) {
1829                 if (req->chain_fsp->fsp_flags.closing) {
1830                         return NULL;
1831                 }
1832                 return req->chain_fsp;
1833         }
1834
1835         if (req->xconn == NULL) {
1836                 return NULL;
1837         }
1838
1839         now = timeval_to_nttime(&req->request_time);
1840
1841         status = smb1srv_open_lookup(req->xconn,
1842                                      fid, now, &op);
1843         if (!NT_STATUS_IS_OK(status)) {
1844                 return NULL;
1845         }
1846
1847         fsp = op->compat;
1848         if (fsp == NULL) {
1849                 return NULL;
1850         }
1851
1852         if (fsp->fsp_flags.closing) {
1853                 return NULL;
1854         }
1855
1856         req->chain_fsp = fsp;
1857         fsp->fsp_name->st.cached_dos_attributes = FILE_ATTRIBUTES_INVALID;
1858         return fsp;
1859 }
1860
1861 struct files_struct *file_fsp_get(struct smbd_smb2_request *smb2req,
1862                                   uint64_t persistent_id,
1863                                   uint64_t volatile_id)
1864 {
1865         struct smbXsrv_open *op;
1866         NTSTATUS status;
1867         NTTIME now = 0;
1868         struct files_struct *fsp;
1869
1870         now = timeval_to_nttime(&smb2req->request_time);
1871
1872         status = smb2srv_open_lookup(smb2req->xconn,
1873                                      persistent_id, volatile_id,
1874                                      now, &op);
1875         if (!NT_STATUS_IS_OK(status)) {
1876                 return NULL;
1877         }
1878
1879         fsp = op->compat;
1880         if (fsp == NULL) {
1881                 return NULL;
1882         }
1883
1884         if (smb2req->tcon == NULL) {
1885                 return NULL;
1886         }
1887
1888         if (smb2req->tcon->compat != fsp->conn) {
1889                 return NULL;
1890         }
1891
1892         if (smb2req->session == NULL) {
1893                 return NULL;
1894         }
1895
1896         if (smb2req->session->global->session_wire_id != fsp->vuid) {
1897                 return NULL;
1898         }
1899
1900         if (fsp->fsp_flags.closing) {
1901                 return NULL;
1902         }
1903
1904         fsp->fsp_name->st.cached_dos_attributes = FILE_ATTRIBUTES_INVALID;
1905
1906         return fsp;
1907 }
1908
1909 struct files_struct *file_fsp_smb2(struct smbd_smb2_request *smb2req,
1910                                    uint64_t persistent_id,
1911                                    uint64_t volatile_id)
1912 {
1913         struct files_struct *fsp;
1914
1915         if (smb2req->compat_chain_fsp != NULL) {
1916                 if (smb2req->compat_chain_fsp->fsp_flags.closing) {
1917                         return NULL;
1918                 }
1919                 smb2req->compat_chain_fsp->fsp_name->st.cached_dos_attributes =
1920                         FILE_ATTRIBUTES_INVALID;
1921                 return smb2req->compat_chain_fsp;
1922         }
1923
1924         fsp = file_fsp_get(smb2req, persistent_id, volatile_id);
1925         if (fsp == NULL) {
1926                 return NULL;
1927         }
1928
1929         smb2req->compat_chain_fsp = fsp;
1930         return fsp;
1931 }
1932
1933 /****************************************************************************
1934  Duplicate the file handle part for a DOS or FCB open.
1935 ****************************************************************************/
1936
1937 NTSTATUS dup_file_fsp(
1938         files_struct *from,
1939         uint32_t access_mask,
1940         files_struct *to)
1941 {
1942         size_t new_refcount;
1943
1944         /* this can never happen for print files */
1945         SMB_ASSERT(from->print_file == NULL);
1946
1947         TALLOC_FREE(to->fh);
1948
1949         to->fh = from->fh;
1950         new_refcount = fh_get_refcount(to->fh) + 1;
1951         fh_set_refcount(to->fh, new_refcount);
1952
1953         to->file_id = from->file_id;
1954         to->initial_allocation_size = from->initial_allocation_size;
1955         to->file_pid = from->file_pid;
1956         to->vuid = from->vuid;
1957         to->open_time = from->open_time;
1958         to->access_mask = access_mask;
1959         to->oplock_type = from->oplock_type;
1960         to->fsp_flags.can_lock = from->fsp_flags.can_lock;
1961         to->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1962         to->fsp_flags.can_write =
1963                 CAN_WRITE(from->conn) &&
1964                 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1965         to->fsp_flags.modified = from->fsp_flags.modified;
1966         to->fsp_flags.is_directory = from->fsp_flags.is_directory;
1967         to->fsp_flags.aio_write_behind = from->fsp_flags.aio_write_behind;
1968         to->fsp_flags.is_fsa = from->fsp_flags.is_fsa;
1969         to->fsp_flags.is_pathref = from->fsp_flags.is_pathref;
1970         to->fsp_flags.have_proc_fds = from->fsp_flags.have_proc_fds;
1971         to->fsp_flags.is_dirfsp = from->fsp_flags.is_dirfsp;
1972
1973         return fsp_set_smb_fname(to, from->fsp_name);
1974 }
1975
1976 /**
1977  * Return a jenkins hash of a pathname on a connection.
1978  */
1979
1980 NTSTATUS file_name_hash(connection_struct *conn,
1981                         const char *name, uint32_t *p_name_hash)
1982 {
1983         char tmpbuf[PATH_MAX];
1984         char *fullpath, *to_free;
1985         ssize_t len;
1986         TDB_DATA key;
1987
1988         /* Set the hash of the full pathname. */
1989
1990         if (name[0] == '/') {
1991                 strlcpy(tmpbuf, name, sizeof(tmpbuf));
1992                 fullpath = tmpbuf;
1993                 len = strlen(fullpath);
1994                 to_free = NULL;
1995         } else {
1996                 len = full_path_tos(conn->connectpath,
1997                                     name,
1998                                     tmpbuf,
1999                                     sizeof(tmpbuf),
2000                                     &fullpath,
2001                                     &to_free);
2002         }
2003         if (len == -1) {
2004                 return NT_STATUS_NO_MEMORY;
2005         }
2006         key = (TDB_DATA) { .dptr = (uint8_t *)fullpath, .dsize = len+1 };
2007         *p_name_hash = tdb_jenkins_hash(&key);
2008
2009         DEBUG(10,("file_name_hash: %s hash 0x%x\n",
2010                   fullpath,
2011                 (unsigned int)*p_name_hash ));
2012
2013         TALLOC_FREE(to_free);
2014         return NT_STATUS_OK;
2015 }
2016
2017 static NTSTATUS fsp_attach_smb_fname(struct files_struct *fsp,
2018                                      struct smb_filename **_smb_fname)
2019 {
2020         struct smb_filename *smb_fname_new = talloc_move(fsp, _smb_fname);
2021         const char *name_str = NULL;
2022         uint32_t name_hash = 0;
2023         NTSTATUS status;
2024
2025         name_str = smb_fname_str_dbg(smb_fname_new);
2026         if (name_str == NULL) {
2027                 return NT_STATUS_NO_MEMORY;
2028         }
2029
2030         status = file_name_hash(fsp->conn,
2031                                 name_str,
2032                                 &name_hash);
2033         if (!NT_STATUS_IS_OK(status)) {
2034                 return status;
2035         }
2036
2037         status = fsp_smb_fname_link(fsp,
2038                                     &smb_fname_new->fsp_link,
2039                                     &smb_fname_new->fsp);
2040         if (!NT_STATUS_IS_OK(status)) {
2041                 return status;
2042         }
2043
2044         fsp->name_hash = name_hash;
2045         fsp->fsp_name = smb_fname_new;
2046         fsp->fsp_name->st.cached_dos_attributes = FILE_ATTRIBUTES_INVALID;
2047         *_smb_fname = NULL;
2048         return NT_STATUS_OK;
2049 }
2050
2051 /**
2052  * The only way that the fsp->fsp_name field should ever be set.
2053  */
2054 NTSTATUS fsp_set_smb_fname(struct files_struct *fsp,
2055                            const struct smb_filename *smb_fname_in)
2056 {
2057         struct smb_filename *smb_fname_old = fsp->fsp_name;
2058         struct smb_filename *smb_fname_new = NULL;
2059         NTSTATUS status;
2060
2061         smb_fname_new = cp_smb_filename(fsp, smb_fname_in);
2062         if (smb_fname_new == NULL) {
2063                 return NT_STATUS_NO_MEMORY;
2064         }
2065
2066         status = fsp_attach_smb_fname(fsp, &smb_fname_new);
2067         if (!NT_STATUS_IS_OK(status)) {
2068                 TALLOC_FREE(smb_fname_new);
2069                 return status;
2070         }
2071
2072         if (smb_fname_old != NULL) {
2073                 smb_fname_fsp_unlink(smb_fname_old);
2074                 TALLOC_FREE(smb_fname_old);
2075         }
2076
2077         return NT_STATUS_OK;
2078 }
2079
2080 size_t fsp_fullbasepath(struct files_struct *fsp, char *buf, size_t buflen)
2081 {
2082         int len = 0;
2083         char tmp_buf[1] = {'\0'};
2084
2085         /*
2086          * Don't pass NULL buffer to snprintf (to satisfy static checker)
2087          * Some callers will call this function with NULL for buf and
2088          * 0 for buflen in order to get length of fullbasepath (without
2089          * needing to allocate or write to buf)
2090          */
2091         if (buf == NULL) {
2092                 buf = tmp_buf;
2093                 SMB_ASSERT(buflen==0);
2094         }
2095
2096         len = snprintf(buf, buflen, "%s/%s", fsp->conn->connectpath,
2097                        fsp->fsp_name->base_name);
2098         SMB_ASSERT(len>0);
2099
2100         return len;
2101 }
2102
2103 void fsp_set_base_fsp(struct files_struct *fsp, struct files_struct *base_fsp)
2104 {
2105         SMB_ASSERT(fsp->stream_fsp == NULL);
2106         if (base_fsp != NULL) {
2107                 SMB_ASSERT(base_fsp->base_fsp == NULL);
2108                 SMB_ASSERT(base_fsp->stream_fsp == NULL);
2109         }
2110
2111         if (fsp->base_fsp != NULL) {
2112                 SMB_ASSERT(fsp->base_fsp->stream_fsp == fsp);
2113                 fsp->base_fsp->stream_fsp = NULL;
2114         }
2115
2116         fsp->base_fsp = base_fsp;
2117         if (fsp->base_fsp != NULL) {
2118                 fsp->base_fsp->stream_fsp = fsp;
2119         }
2120 }
2121
2122 bool fsp_is_alternate_stream(const struct files_struct *fsp)
2123 {
2124         return (fsp->base_fsp != NULL);
2125 }
2126
2127 struct files_struct *metadata_fsp(struct files_struct *fsp)
2128 {
2129         if (fsp_is_alternate_stream(fsp)) {
2130                 return fsp->base_fsp;
2131         }
2132         return fsp;
2133 }