smb: client: report correct st_size for SMB and NFS symlinks
[platform/kernel/linux-rpi.git] / fs / smb / server / vfs.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4  *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
5  */
6
7 #include <linux/kernel.h>
8 #include <linux/fs.h>
9 #include <linux/filelock.h>
10 #include <linux/uaccess.h>
11 #include <linux/backing-dev.h>
12 #include <linux/writeback.h>
13 #include <linux/xattr.h>
14 #include <linux/falloc.h>
15 #include <linux/fsnotify.h>
16 #include <linux/dcache.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
19 #include <linux/sched/xacct.h>
20 #include <linux/crc32c.h>
21 #include <linux/namei.h>
22
23 #include "glob.h"
24 #include "oplock.h"
25 #include "connection.h"
26 #include "vfs.h"
27 #include "vfs_cache.h"
28 #include "smbacl.h"
29 #include "ndr.h"
30 #include "auth.h"
31 #include "misc.h"
32
33 #include "smb_common.h"
34 #include "mgmt/share_config.h"
35 #include "mgmt/tree_connect.h"
36 #include "mgmt/user_session.h"
37 #include "mgmt/user_config.h"
38
39 static void ksmbd_vfs_inherit_owner(struct ksmbd_work *work,
40                                     struct inode *parent_inode,
41                                     struct inode *inode)
42 {
43         if (!test_share_config_flag(work->tcon->share_conf,
44                                     KSMBD_SHARE_FLAG_INHERIT_OWNER))
45                 return;
46
47         i_uid_write(inode, i_uid_read(parent_inode));
48 }
49
50 /**
51  * ksmbd_vfs_lock_parent() - lock parent dentry if it is stable
52  */
53 int ksmbd_vfs_lock_parent(struct dentry *parent, struct dentry *child)
54 {
55         inode_lock_nested(d_inode(parent), I_MUTEX_PARENT);
56         if (child->d_parent != parent) {
57                 inode_unlock(d_inode(parent));
58                 return -ENOENT;
59         }
60
61         return 0;
62 }
63
64 static int ksmbd_vfs_path_lookup_locked(struct ksmbd_share_config *share_conf,
65                                         char *pathname, unsigned int flags,
66                                         struct path *parent_path,
67                                         struct path *path)
68 {
69         struct qstr last;
70         struct filename *filename;
71         struct path *root_share_path = &share_conf->vfs_path;
72         int err, type;
73         struct dentry *d;
74
75         if (pathname[0] == '\0') {
76                 pathname = share_conf->path;
77                 root_share_path = NULL;
78         } else {
79                 flags |= LOOKUP_BENEATH;
80         }
81
82         filename = getname_kernel(pathname);
83         if (IS_ERR(filename))
84                 return PTR_ERR(filename);
85
86         err = vfs_path_parent_lookup(filename, flags,
87                                      parent_path, &last, &type,
88                                      root_share_path);
89         if (err) {
90                 putname(filename);
91                 return err;
92         }
93
94         if (unlikely(type != LAST_NORM)) {
95                 path_put(parent_path);
96                 putname(filename);
97                 return -ENOENT;
98         }
99
100         inode_lock_nested(parent_path->dentry->d_inode, I_MUTEX_PARENT);
101         d = lookup_one_qstr_excl(&last, parent_path->dentry, 0);
102         if (IS_ERR(d))
103                 goto err_out;
104
105         if (d_is_negative(d)) {
106                 dput(d);
107                 goto err_out;
108         }
109
110         path->dentry = d;
111         path->mnt = mntget(parent_path->mnt);
112
113         if (test_share_config_flag(share_conf, KSMBD_SHARE_FLAG_CROSSMNT)) {
114                 err = follow_down(path, 0);
115                 if (err < 0) {
116                         path_put(path);
117                         goto err_out;
118                 }
119         }
120
121         putname(filename);
122         return 0;
123
124 err_out:
125         inode_unlock(d_inode(parent_path->dentry));
126         path_put(parent_path);
127         putname(filename);
128         return -ENOENT;
129 }
130
131 void ksmbd_vfs_query_maximal_access(struct mnt_idmap *idmap,
132                                    struct dentry *dentry, __le32 *daccess)
133 {
134         *daccess = cpu_to_le32(FILE_READ_ATTRIBUTES | READ_CONTROL);
135
136         if (!inode_permission(idmap, d_inode(dentry), MAY_OPEN | MAY_WRITE))
137                 *daccess |= cpu_to_le32(WRITE_DAC | WRITE_OWNER | SYNCHRONIZE |
138                                 FILE_WRITE_DATA | FILE_APPEND_DATA |
139                                 FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES |
140                                 FILE_DELETE_CHILD);
141
142         if (!inode_permission(idmap, d_inode(dentry), MAY_OPEN | MAY_READ))
143                 *daccess |= FILE_READ_DATA_LE | FILE_READ_EA_LE;
144
145         if (!inode_permission(idmap, d_inode(dentry), MAY_OPEN | MAY_EXEC))
146                 *daccess |= FILE_EXECUTE_LE;
147
148         if (!inode_permission(idmap, d_inode(dentry->d_parent), MAY_EXEC | MAY_WRITE))
149                 *daccess |= FILE_DELETE_LE;
150 }
151
152 /**
153  * ksmbd_vfs_create() - vfs helper for smb create file
154  * @work:       work
155  * @name:       file name that is relative to share
156  * @mode:       file create mode
157  *
158  * Return:      0 on success, otherwise error
159  */
160 int ksmbd_vfs_create(struct ksmbd_work *work, const char *name, umode_t mode)
161 {
162         struct path path;
163         struct dentry *dentry;
164         int err;
165
166         dentry = ksmbd_vfs_kern_path_create(work, name,
167                                             LOOKUP_NO_SYMLINKS, &path);
168         if (IS_ERR(dentry)) {
169                 err = PTR_ERR(dentry);
170                 if (err != -ENOENT)
171                         pr_err("path create failed for %s, err %d\n",
172                                name, err);
173                 return err;
174         }
175
176         mode |= S_IFREG;
177         err = vfs_create(mnt_idmap(path.mnt), d_inode(path.dentry),
178                          dentry, mode, true);
179         if (!err) {
180                 ksmbd_vfs_inherit_owner(work, d_inode(path.dentry),
181                                         d_inode(dentry));
182         } else {
183                 pr_err("File(%s): creation failed (err:%d)\n", name, err);
184         }
185
186         done_path_create(&path, dentry);
187         return err;
188 }
189
190 /**
191  * ksmbd_vfs_mkdir() - vfs helper for smb create directory
192  * @work:       work
193  * @name:       directory name that is relative to share
194  * @mode:       directory create mode
195  *
196  * Return:      0 on success, otherwise error
197  */
198 int ksmbd_vfs_mkdir(struct ksmbd_work *work, const char *name, umode_t mode)
199 {
200         struct mnt_idmap *idmap;
201         struct path path;
202         struct dentry *dentry;
203         int err;
204
205         dentry = ksmbd_vfs_kern_path_create(work, name,
206                                             LOOKUP_NO_SYMLINKS | LOOKUP_DIRECTORY,
207                                             &path);
208         if (IS_ERR(dentry)) {
209                 err = PTR_ERR(dentry);
210                 if (err != -EEXIST)
211                         ksmbd_debug(VFS, "path create failed for %s, err %d\n",
212                                     name, err);
213                 return err;
214         }
215
216         idmap = mnt_idmap(path.mnt);
217         mode |= S_IFDIR;
218         err = vfs_mkdir(idmap, d_inode(path.dentry), dentry, mode);
219         if (!err && d_unhashed(dentry)) {
220                 struct dentry *d;
221
222                 d = lookup_one(idmap, dentry->d_name.name, dentry->d_parent,
223                                dentry->d_name.len);
224                 if (IS_ERR(d)) {
225                         err = PTR_ERR(d);
226                         goto out_err;
227                 }
228                 if (unlikely(d_is_negative(d))) {
229                         dput(d);
230                         err = -ENOENT;
231                         goto out_err;
232                 }
233
234                 ksmbd_vfs_inherit_owner(work, d_inode(path.dentry), d_inode(d));
235                 dput(d);
236         }
237
238 out_err:
239         done_path_create(&path, dentry);
240         if (err)
241                 pr_err("mkdir(%s): creation failed (err:%d)\n", name, err);
242         return err;
243 }
244
245 static ssize_t ksmbd_vfs_getcasexattr(struct mnt_idmap *idmap,
246                                       struct dentry *dentry, char *attr_name,
247                                       int attr_name_len, char **attr_value)
248 {
249         char *name, *xattr_list = NULL;
250         ssize_t value_len = -ENOENT, xattr_list_len;
251
252         xattr_list_len = ksmbd_vfs_listxattr(dentry, &xattr_list);
253         if (xattr_list_len <= 0)
254                 goto out;
255
256         for (name = xattr_list; name - xattr_list < xattr_list_len;
257                         name += strlen(name) + 1) {
258                 ksmbd_debug(VFS, "%s, len %zd\n", name, strlen(name));
259                 if (strncasecmp(attr_name, name, attr_name_len))
260                         continue;
261
262                 value_len = ksmbd_vfs_getxattr(idmap,
263                                                dentry,
264                                                name,
265                                                attr_value);
266                 if (value_len < 0)
267                         pr_err("failed to get xattr in file\n");
268                 break;
269         }
270
271 out:
272         kvfree(xattr_list);
273         return value_len;
274 }
275
276 static int ksmbd_vfs_stream_read(struct ksmbd_file *fp, char *buf, loff_t *pos,
277                                  size_t count)
278 {
279         ssize_t v_len;
280         char *stream_buf = NULL;
281
282         ksmbd_debug(VFS, "read stream data pos : %llu, count : %zd\n",
283                     *pos, count);
284
285         v_len = ksmbd_vfs_getcasexattr(file_mnt_idmap(fp->filp),
286                                        fp->filp->f_path.dentry,
287                                        fp->stream.name,
288                                        fp->stream.size,
289                                        &stream_buf);
290         if ((int)v_len <= 0)
291                 return (int)v_len;
292
293         if (v_len <= *pos) {
294                 count = -EINVAL;
295                 goto free_buf;
296         }
297
298         if (v_len - *pos < count)
299                 count = v_len - *pos;
300
301         memcpy(buf, &stream_buf[*pos], count);
302
303 free_buf:
304         kvfree(stream_buf);
305         return count;
306 }
307
308 /**
309  * check_lock_range() - vfs helper for smb byte range file locking
310  * @filp:       the file to apply the lock to
311  * @start:      lock start byte offset
312  * @end:        lock end byte offset
313  * @type:       byte range type read/write
314  *
315  * Return:      0 on success, otherwise error
316  */
317 static int check_lock_range(struct file *filp, loff_t start, loff_t end,
318                             unsigned char type)
319 {
320         struct file_lock *flock;
321         struct file_lock_context *ctx = locks_inode_context(file_inode(filp));
322         int error = 0;
323
324         if (!ctx || list_empty_careful(&ctx->flc_posix))
325                 return 0;
326
327         spin_lock(&ctx->flc_lock);
328         list_for_each_entry(flock, &ctx->flc_posix, fl_list) {
329                 /* check conflict locks */
330                 if (flock->fl_end >= start && end >= flock->fl_start) {
331                         if (flock->fl_type == F_RDLCK) {
332                                 if (type == WRITE) {
333                                         pr_err("not allow write by shared lock\n");
334                                         error = 1;
335                                         goto out;
336                                 }
337                         } else if (flock->fl_type == F_WRLCK) {
338                                 /* check owner in lock */
339                                 if (flock->fl_file != filp) {
340                                         error = 1;
341                                         pr_err("not allow rw access by exclusive lock from other opens\n");
342                                         goto out;
343                                 }
344                         }
345                 }
346         }
347 out:
348         spin_unlock(&ctx->flc_lock);
349         return error;
350 }
351
352 /**
353  * ksmbd_vfs_read() - vfs helper for smb file read
354  * @work:       smb work
355  * @fid:        file id of open file
356  * @count:      read byte count
357  * @pos:        file pos
358  * @rbuf:       read data buffer
359  *
360  * Return:      number of read bytes on success, otherwise error
361  */
362 int ksmbd_vfs_read(struct ksmbd_work *work, struct ksmbd_file *fp, size_t count,
363                    loff_t *pos, char *rbuf)
364 {
365         struct file *filp = fp->filp;
366         ssize_t nbytes = 0;
367         struct inode *inode = file_inode(filp);
368
369         if (S_ISDIR(inode->i_mode))
370                 return -EISDIR;
371
372         if (unlikely(count == 0))
373                 return 0;
374
375         if (work->conn->connection_type) {
376                 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_EXECUTE_LE))) {
377                         pr_err("no right to read(%pD)\n", fp->filp);
378                         return -EACCES;
379                 }
380         }
381
382         if (ksmbd_stream_fd(fp))
383                 return ksmbd_vfs_stream_read(fp, rbuf, pos, count);
384
385         if (!work->tcon->posix_extensions) {
386                 int ret;
387
388                 ret = check_lock_range(filp, *pos, *pos + count - 1, READ);
389                 if (ret) {
390                         pr_err("unable to read due to lock\n");
391                         return -EAGAIN;
392                 }
393         }
394
395         nbytes = kernel_read(filp, rbuf, count, pos);
396         if (nbytes < 0) {
397                 pr_err("smb read failed, err = %zd\n", nbytes);
398                 return nbytes;
399         }
400
401         filp->f_pos = *pos;
402         return nbytes;
403 }
404
405 static int ksmbd_vfs_stream_write(struct ksmbd_file *fp, char *buf, loff_t *pos,
406                                   size_t count)
407 {
408         char *stream_buf = NULL, *wbuf;
409         struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
410         size_t size;
411         ssize_t v_len;
412         int err = 0;
413
414         ksmbd_debug(VFS, "write stream data pos : %llu, count : %zd\n",
415                     *pos, count);
416
417         size = *pos + count;
418         if (size > XATTR_SIZE_MAX) {
419                 size = XATTR_SIZE_MAX;
420                 count = (*pos + count) - XATTR_SIZE_MAX;
421         }
422
423         v_len = ksmbd_vfs_getcasexattr(idmap,
424                                        fp->filp->f_path.dentry,
425                                        fp->stream.name,
426                                        fp->stream.size,
427                                        &stream_buf);
428         if (v_len < 0) {
429                 pr_err("not found stream in xattr : %zd\n", v_len);
430                 err = v_len;
431                 goto out;
432         }
433
434         if (v_len < size) {
435                 wbuf = kvzalloc(size, GFP_KERNEL);
436                 if (!wbuf) {
437                         err = -ENOMEM;
438                         goto out;
439                 }
440
441                 if (v_len > 0)
442                         memcpy(wbuf, stream_buf, v_len);
443                 kvfree(stream_buf);
444                 stream_buf = wbuf;
445         }
446
447         memcpy(&stream_buf[*pos], buf, count);
448
449         err = ksmbd_vfs_setxattr(idmap,
450                                  &fp->filp->f_path,
451                                  fp->stream.name,
452                                  (void *)stream_buf,
453                                  size,
454                                  0);
455         if (err < 0)
456                 goto out;
457
458         fp->filp->f_pos = *pos;
459         err = 0;
460 out:
461         kvfree(stream_buf);
462         return err;
463 }
464
465 /**
466  * ksmbd_vfs_write() - vfs helper for smb file write
467  * @work:       work
468  * @fid:        file id of open file
469  * @buf:        buf containing data for writing
470  * @count:      read byte count
471  * @pos:        file pos
472  * @sync:       fsync after write
473  * @written:    number of bytes written
474  *
475  * Return:      0 on success, otherwise error
476  */
477 int ksmbd_vfs_write(struct ksmbd_work *work, struct ksmbd_file *fp,
478                     char *buf, size_t count, loff_t *pos, bool sync,
479                     ssize_t *written)
480 {
481         struct file *filp;
482         loff_t  offset = *pos;
483         int err = 0;
484
485         if (work->conn->connection_type) {
486                 if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
487                         pr_err("no right to write(%pD)\n", fp->filp);
488                         err = -EACCES;
489                         goto out;
490                 }
491         }
492
493         filp = fp->filp;
494
495         if (ksmbd_stream_fd(fp)) {
496                 err = ksmbd_vfs_stream_write(fp, buf, pos, count);
497                 if (!err)
498                         *written = count;
499                 goto out;
500         }
501
502         if (!work->tcon->posix_extensions) {
503                 err = check_lock_range(filp, *pos, *pos + count - 1, WRITE);
504                 if (err) {
505                         pr_err("unable to write due to lock\n");
506                         err = -EAGAIN;
507                         goto out;
508                 }
509         }
510
511         /* Do we need to break any of a levelII oplock? */
512         smb_break_all_levII_oplock(work, fp, 1);
513
514         err = kernel_write(filp, buf, count, pos);
515         if (err < 0) {
516                 ksmbd_debug(VFS, "smb write failed, err = %d\n", err);
517                 goto out;
518         }
519
520         filp->f_pos = *pos;
521         *written = err;
522         err = 0;
523         if (sync) {
524                 err = vfs_fsync_range(filp, offset, offset + *written, 0);
525                 if (err < 0)
526                         pr_err("fsync failed for filename = %pD, err = %d\n",
527                                fp->filp, err);
528         }
529
530 out:
531         return err;
532 }
533
534 /**
535  * ksmbd_vfs_getattr() - vfs helper for smb getattr
536  * @work:       work
537  * @fid:        file id of open file
538  * @attrs:      inode attributes
539  *
540  * Return:      0 on success, otherwise error
541  */
542 int ksmbd_vfs_getattr(const struct path *path, struct kstat *stat)
543 {
544         int err;
545
546         err = vfs_getattr(path, stat, STATX_BTIME, AT_STATX_SYNC_AS_STAT);
547         if (err)
548                 pr_err("getattr failed, err %d\n", err);
549         return err;
550 }
551
552 /**
553  * ksmbd_vfs_fsync() - vfs helper for smb fsync
554  * @work:       work
555  * @fid:        file id of open file
556  *
557  * Return:      0 on success, otherwise error
558  */
559 int ksmbd_vfs_fsync(struct ksmbd_work *work, u64 fid, u64 p_id)
560 {
561         struct ksmbd_file *fp;
562         int err;
563
564         fp = ksmbd_lookup_fd_slow(work, fid, p_id);
565         if (!fp) {
566                 pr_err("failed to get filp for fid %llu\n", fid);
567                 return -ENOENT;
568         }
569         err = vfs_fsync(fp->filp, 0);
570         if (err < 0)
571                 pr_err("smb fsync failed, err = %d\n", err);
572         ksmbd_fd_put(work, fp);
573         return err;
574 }
575
576 /**
577  * ksmbd_vfs_remove_file() - vfs helper for smb rmdir or unlink
578  * @name:       directory or file name that is relative to share
579  *
580  * Return:      0 on success, otherwise error
581  */
582 int ksmbd_vfs_remove_file(struct ksmbd_work *work, const struct path *path)
583 {
584         struct mnt_idmap *idmap;
585         struct dentry *parent = path->dentry->d_parent;
586         int err;
587
588         if (ksmbd_override_fsids(work))
589                 return -ENOMEM;
590
591         if (!d_inode(path->dentry)->i_nlink) {
592                 err = -ENOENT;
593                 goto out_err;
594         }
595
596         err = mnt_want_write(path->mnt);
597         if (err)
598                 goto out_err;
599
600         idmap = mnt_idmap(path->mnt);
601         if (S_ISDIR(d_inode(path->dentry)->i_mode)) {
602                 err = vfs_rmdir(idmap, d_inode(parent), path->dentry);
603                 if (err && err != -ENOTEMPTY)
604                         ksmbd_debug(VFS, "rmdir failed, err %d\n", err);
605         } else {
606                 err = vfs_unlink(idmap, d_inode(parent), path->dentry, NULL);
607                 if (err)
608                         ksmbd_debug(VFS, "unlink failed, err %d\n", err);
609         }
610         mnt_drop_write(path->mnt);
611
612 out_err:
613         ksmbd_revert_fsids(work);
614         return err;
615 }
616
617 /**
618  * ksmbd_vfs_link() - vfs helper for creating smb hardlink
619  * @oldname:    source file name
620  * @newname:    hardlink name that is relative to share
621  *
622  * Return:      0 on success, otherwise error
623  */
624 int ksmbd_vfs_link(struct ksmbd_work *work, const char *oldname,
625                    const char *newname)
626 {
627         struct path oldpath, newpath;
628         struct dentry *dentry;
629         int err;
630
631         if (ksmbd_override_fsids(work))
632                 return -ENOMEM;
633
634         err = kern_path(oldname, LOOKUP_NO_SYMLINKS, &oldpath);
635         if (err) {
636                 pr_err("cannot get linux path for %s, err = %d\n",
637                        oldname, err);
638                 goto out1;
639         }
640
641         dentry = ksmbd_vfs_kern_path_create(work, newname,
642                                             LOOKUP_NO_SYMLINKS | LOOKUP_REVAL,
643                                             &newpath);
644         if (IS_ERR(dentry)) {
645                 err = PTR_ERR(dentry);
646                 pr_err("path create err for %s, err %d\n", newname, err);
647                 goto out2;
648         }
649
650         err = -EXDEV;
651         if (oldpath.mnt != newpath.mnt) {
652                 pr_err("vfs_link failed err %d\n", err);
653                 goto out3;
654         }
655
656         err = vfs_link(oldpath.dentry, mnt_idmap(newpath.mnt),
657                        d_inode(newpath.dentry),
658                        dentry, NULL);
659         if (err)
660                 ksmbd_debug(VFS, "vfs_link failed err %d\n", err);
661
662 out3:
663         done_path_create(&newpath, dentry);
664 out2:
665         path_put(&oldpath);
666 out1:
667         ksmbd_revert_fsids(work);
668         return err;
669 }
670
671 int ksmbd_vfs_rename(struct ksmbd_work *work, const struct path *old_path,
672                      char *newname, int flags)
673 {
674         struct dentry *old_parent, *new_dentry, *trap;
675         struct dentry *old_child = old_path->dentry;
676         struct path new_path;
677         struct qstr new_last;
678         struct renamedata rd;
679         struct filename *to;
680         struct ksmbd_share_config *share_conf = work->tcon->share_conf;
681         struct ksmbd_file *parent_fp;
682         int new_type;
683         int err, lookup_flags = LOOKUP_NO_SYMLINKS;
684
685         if (ksmbd_override_fsids(work))
686                 return -ENOMEM;
687
688         to = getname_kernel(newname);
689         if (IS_ERR(to)) {
690                 err = PTR_ERR(to);
691                 goto revert_fsids;
692         }
693
694 retry:
695         err = vfs_path_parent_lookup(to, lookup_flags | LOOKUP_BENEATH,
696                                      &new_path, &new_last, &new_type,
697                                      &share_conf->vfs_path);
698         if (err)
699                 goto out1;
700
701         if (old_path->mnt != new_path.mnt) {
702                 err = -EXDEV;
703                 goto out2;
704         }
705
706         err = mnt_want_write(old_path->mnt);
707         if (err)
708                 goto out2;
709
710         trap = lock_rename_child(old_child, new_path.dentry);
711
712         old_parent = dget(old_child->d_parent);
713         if (d_unhashed(old_child)) {
714                 err = -EINVAL;
715                 goto out3;
716         }
717
718         parent_fp = ksmbd_lookup_fd_inode(d_inode(old_child->d_parent));
719         if (parent_fp) {
720                 if (parent_fp->daccess & FILE_DELETE_LE) {
721                         pr_err("parent dir is opened with delete access\n");
722                         err = -ESHARE;
723                         ksmbd_fd_put(work, parent_fp);
724                         goto out3;
725                 }
726                 ksmbd_fd_put(work, parent_fp);
727         }
728
729         new_dentry = lookup_one_qstr_excl(&new_last, new_path.dentry,
730                                           lookup_flags | LOOKUP_RENAME_TARGET);
731         if (IS_ERR(new_dentry)) {
732                 err = PTR_ERR(new_dentry);
733                 goto out3;
734         }
735
736         if (d_is_symlink(new_dentry)) {
737                 err = -EACCES;
738                 goto out4;
739         }
740
741         if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry)) {
742                 err = -EEXIST;
743                 goto out4;
744         }
745
746         if (old_child == trap) {
747                 err = -EINVAL;
748                 goto out4;
749         }
750
751         if (new_dentry == trap) {
752                 err = -ENOTEMPTY;
753                 goto out4;
754         }
755
756         rd.old_mnt_idmap        = mnt_idmap(old_path->mnt),
757         rd.old_dir              = d_inode(old_parent),
758         rd.old_dentry           = old_child,
759         rd.new_mnt_idmap        = mnt_idmap(new_path.mnt),
760         rd.new_dir              = new_path.dentry->d_inode,
761         rd.new_dentry           = new_dentry,
762         rd.flags                = flags,
763         rd.delegated_inode      = NULL,
764         err = vfs_rename(&rd);
765         if (err)
766                 ksmbd_debug(VFS, "vfs_rename failed err %d\n", err);
767
768 out4:
769         dput(new_dentry);
770 out3:
771         dput(old_parent);
772         unlock_rename(old_parent, new_path.dentry);
773         mnt_drop_write(old_path->mnt);
774 out2:
775         path_put(&new_path);
776
777         if (retry_estale(err, lookup_flags)) {
778                 lookup_flags |= LOOKUP_REVAL;
779                 goto retry;
780         }
781 out1:
782         putname(to);
783 revert_fsids:
784         ksmbd_revert_fsids(work);
785         return err;
786 }
787
788 /**
789  * ksmbd_vfs_truncate() - vfs helper for smb file truncate
790  * @work:       work
791  * @fid:        file id of old file
792  * @size:       truncate to given size
793  *
794  * Return:      0 on success, otherwise error
795  */
796 int ksmbd_vfs_truncate(struct ksmbd_work *work,
797                        struct ksmbd_file *fp, loff_t size)
798 {
799         int err = 0;
800         struct file *filp;
801
802         filp = fp->filp;
803
804         /* Do we need to break any of a levelII oplock? */
805         smb_break_all_levII_oplock(work, fp, 1);
806
807         if (!work->tcon->posix_extensions) {
808                 struct inode *inode = file_inode(filp);
809
810                 if (size < inode->i_size) {
811                         err = check_lock_range(filp, size,
812                                                inode->i_size - 1, WRITE);
813                 } else {
814                         err = check_lock_range(filp, inode->i_size,
815                                                size - 1, WRITE);
816                 }
817
818                 if (err) {
819                         pr_err("failed due to lock\n");
820                         return -EAGAIN;
821                 }
822         }
823
824         err = vfs_truncate(&filp->f_path, size);
825         if (err)
826                 pr_err("truncate failed, err %d\n", err);
827         return err;
828 }
829
830 /**
831  * ksmbd_vfs_listxattr() - vfs helper for smb list extended attributes
832  * @dentry:     dentry of file for listing xattrs
833  * @list:       destination buffer
834  * @size:       destination buffer length
835  *
836  * Return:      xattr list length on success, otherwise error
837  */
838 ssize_t ksmbd_vfs_listxattr(struct dentry *dentry, char **list)
839 {
840         ssize_t size;
841         char *vlist = NULL;
842
843         size = vfs_listxattr(dentry, NULL, 0);
844         if (size <= 0)
845                 return size;
846
847         vlist = kvzalloc(size, GFP_KERNEL);
848         if (!vlist)
849                 return -ENOMEM;
850
851         *list = vlist;
852         size = vfs_listxattr(dentry, vlist, size);
853         if (size < 0) {
854                 ksmbd_debug(VFS, "listxattr failed\n");
855                 kvfree(vlist);
856                 *list = NULL;
857         }
858
859         return size;
860 }
861
862 static ssize_t ksmbd_vfs_xattr_len(struct mnt_idmap *idmap,
863                                    struct dentry *dentry, char *xattr_name)
864 {
865         return vfs_getxattr(idmap, dentry, xattr_name, NULL, 0);
866 }
867
868 /**
869  * ksmbd_vfs_getxattr() - vfs helper for smb get extended attributes value
870  * @idmap:      idmap
871  * @dentry:     dentry of file for getting xattrs
872  * @xattr_name: name of xattr name to query
873  * @xattr_buf:  destination buffer xattr value
874  *
875  * Return:      read xattr value length on success, otherwise error
876  */
877 ssize_t ksmbd_vfs_getxattr(struct mnt_idmap *idmap,
878                            struct dentry *dentry,
879                            char *xattr_name, char **xattr_buf)
880 {
881         ssize_t xattr_len;
882         char *buf;
883
884         *xattr_buf = NULL;
885         xattr_len = ksmbd_vfs_xattr_len(idmap, dentry, xattr_name);
886         if (xattr_len < 0)
887                 return xattr_len;
888
889         buf = kmalloc(xattr_len + 1, GFP_KERNEL);
890         if (!buf)
891                 return -ENOMEM;
892
893         xattr_len = vfs_getxattr(idmap, dentry, xattr_name,
894                                  (void *)buf, xattr_len);
895         if (xattr_len > 0)
896                 *xattr_buf = buf;
897         else
898                 kfree(buf);
899         return xattr_len;
900 }
901
902 /**
903  * ksmbd_vfs_setxattr() - vfs helper for smb set extended attributes value
904  * @idmap:      idmap of the relevant mount
905  * @dentry:     dentry to set XATTR at
906  * @attr_name:  xattr name for setxattr
907  * @attr_value: xattr value to set
908  * @attr_size:  size of xattr value
909  * @flags:      destination buffer length
910  *
911  * Return:      0 on success, otherwise error
912  */
913 int ksmbd_vfs_setxattr(struct mnt_idmap *idmap,
914                        const struct path *path, const char *attr_name,
915                        void *attr_value, size_t attr_size, int flags)
916 {
917         int err;
918
919         err = mnt_want_write(path->mnt);
920         if (err)
921                 return err;
922
923         err = vfs_setxattr(idmap,
924                            path->dentry,
925                            attr_name,
926                            attr_value,
927                            attr_size,
928                            flags);
929         if (err)
930                 ksmbd_debug(VFS, "setxattr failed, err %d\n", err);
931         mnt_drop_write(path->mnt);
932         return err;
933 }
934
935 /**
936  * ksmbd_vfs_set_fadvise() - convert smb IO caching options to linux options
937  * @filp:       file pointer for IO
938  * @options:    smb IO options
939  */
940 void ksmbd_vfs_set_fadvise(struct file *filp, __le32 option)
941 {
942         struct address_space *mapping;
943
944         mapping = filp->f_mapping;
945
946         if (!option || !mapping)
947                 return;
948
949         if (option & FILE_WRITE_THROUGH_LE) {
950                 filp->f_flags |= O_SYNC;
951         } else if (option & FILE_SEQUENTIAL_ONLY_LE) {
952                 filp->f_ra.ra_pages = inode_to_bdi(mapping->host)->ra_pages * 2;
953                 spin_lock(&filp->f_lock);
954                 filp->f_mode &= ~FMODE_RANDOM;
955                 spin_unlock(&filp->f_lock);
956         } else if (option & FILE_RANDOM_ACCESS_LE) {
957                 spin_lock(&filp->f_lock);
958                 filp->f_mode |= FMODE_RANDOM;
959                 spin_unlock(&filp->f_lock);
960         }
961 }
962
963 int ksmbd_vfs_zero_data(struct ksmbd_work *work, struct ksmbd_file *fp,
964                         loff_t off, loff_t len)
965 {
966         smb_break_all_levII_oplock(work, fp, 1);
967         if (fp->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)
968                 return vfs_fallocate(fp->filp,
969                                      FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
970                                      off, len);
971
972         return vfs_fallocate(fp->filp,
973                              FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE,
974                              off, len);
975 }
976
977 int ksmbd_vfs_fqar_lseek(struct ksmbd_file *fp, loff_t start, loff_t length,
978                          struct file_allocated_range_buffer *ranges,
979                          unsigned int in_count, unsigned int *out_count)
980 {
981         struct file *f = fp->filp;
982         struct inode *inode = file_inode(fp->filp);
983         loff_t maxbytes = (u64)inode->i_sb->s_maxbytes, end;
984         loff_t extent_start, extent_end;
985         int ret = 0;
986
987         if (start > maxbytes)
988                 return -EFBIG;
989
990         if (!in_count)
991                 return 0;
992
993         /*
994          * Shrink request scope to what the fs can actually handle.
995          */
996         if (length > maxbytes || (maxbytes - length) < start)
997                 length = maxbytes - start;
998
999         if (start + length > inode->i_size)
1000                 length = inode->i_size - start;
1001
1002         *out_count = 0;
1003         end = start + length;
1004         while (start < end && *out_count < in_count) {
1005                 extent_start = vfs_llseek(f, start, SEEK_DATA);
1006                 if (extent_start < 0) {
1007                         if (extent_start != -ENXIO)
1008                                 ret = (int)extent_start;
1009                         break;
1010                 }
1011
1012                 if (extent_start >= end)
1013                         break;
1014
1015                 extent_end = vfs_llseek(f, extent_start, SEEK_HOLE);
1016                 if (extent_end < 0) {
1017                         if (extent_end != -ENXIO)
1018                                 ret = (int)extent_end;
1019                         break;
1020                 } else if (extent_start >= extent_end) {
1021                         break;
1022                 }
1023
1024                 ranges[*out_count].file_offset = cpu_to_le64(extent_start);
1025                 ranges[(*out_count)++].length =
1026                         cpu_to_le64(min(extent_end, end) - extent_start);
1027
1028                 start = extent_end;
1029         }
1030
1031         return ret;
1032 }
1033
1034 int ksmbd_vfs_remove_xattr(struct mnt_idmap *idmap,
1035                            const struct path *path, char *attr_name)
1036 {
1037         int err;
1038
1039         err = mnt_want_write(path->mnt);
1040         if (err)
1041                 return err;
1042
1043         err = vfs_removexattr(idmap, path->dentry, attr_name);
1044         mnt_drop_write(path->mnt);
1045
1046         return err;
1047 }
1048
1049 int ksmbd_vfs_unlink(struct file *filp)
1050 {
1051         int err = 0;
1052         struct dentry *dir, *dentry = filp->f_path.dentry;
1053         struct mnt_idmap *idmap = file_mnt_idmap(filp);
1054
1055         err = mnt_want_write(filp->f_path.mnt);
1056         if (err)
1057                 return err;
1058
1059         dir = dget_parent(dentry);
1060         err = ksmbd_vfs_lock_parent(dir, dentry);
1061         if (err)
1062                 goto out;
1063         dget(dentry);
1064
1065         if (S_ISDIR(d_inode(dentry)->i_mode))
1066                 err = vfs_rmdir(idmap, d_inode(dir), dentry);
1067         else
1068                 err = vfs_unlink(idmap, d_inode(dir), dentry, NULL);
1069
1070         dput(dentry);
1071         inode_unlock(d_inode(dir));
1072         if (err)
1073                 ksmbd_debug(VFS, "failed to delete, err %d\n", err);
1074 out:
1075         dput(dir);
1076         mnt_drop_write(filp->f_path.mnt);
1077
1078         return err;
1079 }
1080
1081 static bool __dir_empty(struct dir_context *ctx, const char *name, int namlen,
1082                        loff_t offset, u64 ino, unsigned int d_type)
1083 {
1084         struct ksmbd_readdir_data *buf;
1085
1086         buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
1087         buf->dirent_count++;
1088
1089         return buf->dirent_count <= 2;
1090 }
1091
1092 /**
1093  * ksmbd_vfs_empty_dir() - check for empty directory
1094  * @fp: ksmbd file pointer
1095  *
1096  * Return:      true if directory empty, otherwise false
1097  */
1098 int ksmbd_vfs_empty_dir(struct ksmbd_file *fp)
1099 {
1100         int err;
1101         struct ksmbd_readdir_data readdir_data;
1102
1103         memset(&readdir_data, 0, sizeof(struct ksmbd_readdir_data));
1104
1105         set_ctx_actor(&readdir_data.ctx, __dir_empty);
1106         readdir_data.dirent_count = 0;
1107
1108         err = iterate_dir(fp->filp, &readdir_data.ctx);
1109         if (readdir_data.dirent_count > 2)
1110                 err = -ENOTEMPTY;
1111         else
1112                 err = 0;
1113         return err;
1114 }
1115
1116 static bool __caseless_lookup(struct dir_context *ctx, const char *name,
1117                              int namlen, loff_t offset, u64 ino,
1118                              unsigned int d_type)
1119 {
1120         struct ksmbd_readdir_data *buf;
1121         int cmp = -EINVAL;
1122
1123         buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
1124
1125         if (buf->used != namlen)
1126                 return true;
1127         if (IS_ENABLED(CONFIG_UNICODE) && buf->um) {
1128                 const struct qstr q_buf = {.name = buf->private,
1129                                            .len = buf->used};
1130                 const struct qstr q_name = {.name = name,
1131                                             .len = namlen};
1132
1133                 cmp = utf8_strncasecmp(buf->um, &q_buf, &q_name);
1134         }
1135         if (cmp < 0)
1136                 cmp = strncasecmp((char *)buf->private, name, namlen);
1137         if (!cmp) {
1138                 memcpy((char *)buf->private, name, namlen);
1139                 buf->dirent_count = 1;
1140                 return false;
1141         }
1142         return true;
1143 }
1144
1145 /**
1146  * ksmbd_vfs_lookup_in_dir() - lookup a file in a directory
1147  * @dir:        path info
1148  * @name:       filename to lookup
1149  * @namelen:    filename length
1150  *
1151  * Return:      0 on success, otherwise error
1152  */
1153 static int ksmbd_vfs_lookup_in_dir(const struct path *dir, char *name,
1154                                    size_t namelen, struct unicode_map *um)
1155 {
1156         int ret;
1157         struct file *dfilp;
1158         int flags = O_RDONLY | O_LARGEFILE;
1159         struct ksmbd_readdir_data readdir_data = {
1160                 .ctx.actor      = __caseless_lookup,
1161                 .private        = name,
1162                 .used           = namelen,
1163                 .dirent_count   = 0,
1164                 .um             = um,
1165         };
1166
1167         dfilp = dentry_open(dir, flags, current_cred());
1168         if (IS_ERR(dfilp))
1169                 return PTR_ERR(dfilp);
1170
1171         ret = iterate_dir(dfilp, &readdir_data.ctx);
1172         if (readdir_data.dirent_count > 0)
1173                 ret = 0;
1174         fput(dfilp);
1175         return ret;
1176 }
1177
1178 /**
1179  * ksmbd_vfs_kern_path_locked() - lookup a file and get path info
1180  * @name:       file path that is relative to share
1181  * @flags:      lookup flags
1182  * @path:       if lookup succeed, return path info
1183  * @caseless:   caseless filename lookup
1184  *
1185  * Return:      0 on success, otherwise error
1186  */
1187 int ksmbd_vfs_kern_path_locked(struct ksmbd_work *work, char *name,
1188                                unsigned int flags, struct path *parent_path,
1189                                struct path *path, bool caseless)
1190 {
1191         struct ksmbd_share_config *share_conf = work->tcon->share_conf;
1192         int err;
1193
1194         err = ksmbd_vfs_path_lookup_locked(share_conf, name, flags, parent_path,
1195                                            path);
1196         if (!err)
1197                 return 0;
1198
1199         if (caseless) {
1200                 char *filepath;
1201                 size_t path_len, remain_len;
1202
1203                 filepath = kstrdup(name, GFP_KERNEL);
1204                 if (!filepath)
1205                         return -ENOMEM;
1206
1207                 path_len = strlen(filepath);
1208                 remain_len = path_len;
1209
1210                 *parent_path = share_conf->vfs_path;
1211                 path_get(parent_path);
1212
1213                 while (d_can_lookup(parent_path->dentry)) {
1214                         char *filename = filepath + path_len - remain_len;
1215                         char *next = strchrnul(filename, '/');
1216                         size_t filename_len = next - filename;
1217                         bool is_last = !next[0];
1218
1219                         if (filename_len == 0)
1220                                 break;
1221
1222                         err = ksmbd_vfs_lookup_in_dir(parent_path, filename,
1223                                                       filename_len,
1224                                                       work->conn->um);
1225                         if (err)
1226                                 goto out2;
1227
1228                         next[0] = '\0';
1229
1230                         err = vfs_path_lookup(share_conf->vfs_path.dentry,
1231                                               share_conf->vfs_path.mnt,
1232                                               filepath,
1233                                               flags,
1234                                               path);
1235                         if (err)
1236                                 goto out2;
1237                         else if (is_last)
1238                                 goto out1;
1239                         path_put(parent_path);
1240                         *parent_path = *path;
1241
1242                         next[0] = '/';
1243                         remain_len -= filename_len + 1;
1244                 }
1245
1246                 err = -EINVAL;
1247 out2:
1248                 path_put(parent_path);
1249 out1:
1250                 kfree(filepath);
1251         }
1252
1253         if (!err) {
1254                 err = ksmbd_vfs_lock_parent(parent_path->dentry, path->dentry);
1255                 if (err) {
1256                         path_put(path);
1257                         path_put(parent_path);
1258                 }
1259         }
1260         return err;
1261 }
1262
1263 struct dentry *ksmbd_vfs_kern_path_create(struct ksmbd_work *work,
1264                                           const char *name,
1265                                           unsigned int flags,
1266                                           struct path *path)
1267 {
1268         char *abs_name;
1269         struct dentry *dent;
1270
1271         abs_name = convert_to_unix_name(work->tcon->share_conf, name);
1272         if (!abs_name)
1273                 return ERR_PTR(-ENOMEM);
1274
1275         dent = kern_path_create(AT_FDCWD, abs_name, path, flags);
1276         kfree(abs_name);
1277         return dent;
1278 }
1279
1280 int ksmbd_vfs_remove_acl_xattrs(struct mnt_idmap *idmap,
1281                                 const struct path *path)
1282 {
1283         char *name, *xattr_list = NULL;
1284         ssize_t xattr_list_len;
1285         int err = 0;
1286
1287         xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
1288         if (xattr_list_len < 0) {
1289                 goto out;
1290         } else if (!xattr_list_len) {
1291                 ksmbd_debug(SMB, "empty xattr in the file\n");
1292                 goto out;
1293         }
1294
1295         err = mnt_want_write(path->mnt);
1296         if (err)
1297                 goto out;
1298
1299         for (name = xattr_list; name - xattr_list < xattr_list_len;
1300              name += strlen(name) + 1) {
1301                 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
1302
1303                 if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS,
1304                              sizeof(XATTR_NAME_POSIX_ACL_ACCESS) - 1) ||
1305                     !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT,
1306                              sizeof(XATTR_NAME_POSIX_ACL_DEFAULT) - 1)) {
1307                         err = vfs_remove_acl(idmap, path->dentry, name);
1308                         if (err)
1309                                 ksmbd_debug(SMB,
1310                                             "remove acl xattr failed : %s\n", name);
1311                 }
1312         }
1313         mnt_drop_write(path->mnt);
1314
1315 out:
1316         kvfree(xattr_list);
1317         return err;
1318 }
1319
1320 int ksmbd_vfs_remove_sd_xattrs(struct mnt_idmap *idmap, const struct path *path)
1321 {
1322         char *name, *xattr_list = NULL;
1323         ssize_t xattr_list_len;
1324         int err = 0;
1325
1326         xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
1327         if (xattr_list_len < 0) {
1328                 goto out;
1329         } else if (!xattr_list_len) {
1330                 ksmbd_debug(SMB, "empty xattr in the file\n");
1331                 goto out;
1332         }
1333
1334         for (name = xattr_list; name - xattr_list < xattr_list_len;
1335                         name += strlen(name) + 1) {
1336                 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
1337
1338                 if (!strncmp(name, XATTR_NAME_SD, XATTR_NAME_SD_LEN)) {
1339                         err = ksmbd_vfs_remove_xattr(idmap, path, name);
1340                         if (err)
1341                                 ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
1342                 }
1343         }
1344 out:
1345         kvfree(xattr_list);
1346         return err;
1347 }
1348
1349 static struct xattr_smb_acl *ksmbd_vfs_make_xattr_posix_acl(struct mnt_idmap *idmap,
1350                                                             struct inode *inode,
1351                                                             int acl_type)
1352 {
1353         struct xattr_smb_acl *smb_acl = NULL;
1354         struct posix_acl *posix_acls;
1355         struct posix_acl_entry *pa_entry;
1356         struct xattr_acl_entry *xa_entry;
1357         int i;
1358
1359         if (!IS_ENABLED(CONFIG_FS_POSIX_ACL))
1360                 return NULL;
1361
1362         posix_acls = get_inode_acl(inode, acl_type);
1363         if (IS_ERR_OR_NULL(posix_acls))
1364                 return NULL;
1365
1366         smb_acl = kzalloc(sizeof(struct xattr_smb_acl) +
1367                           sizeof(struct xattr_acl_entry) * posix_acls->a_count,
1368                           GFP_KERNEL);
1369         if (!smb_acl)
1370                 goto out;
1371
1372         smb_acl->count = posix_acls->a_count;
1373         pa_entry = posix_acls->a_entries;
1374         xa_entry = smb_acl->entries;
1375         for (i = 0; i < posix_acls->a_count; i++, pa_entry++, xa_entry++) {
1376                 switch (pa_entry->e_tag) {
1377                 case ACL_USER:
1378                         xa_entry->type = SMB_ACL_USER;
1379                         xa_entry->uid = posix_acl_uid_translate(idmap, pa_entry);
1380                         break;
1381                 case ACL_USER_OBJ:
1382                         xa_entry->type = SMB_ACL_USER_OBJ;
1383                         break;
1384                 case ACL_GROUP:
1385                         xa_entry->type = SMB_ACL_GROUP;
1386                         xa_entry->gid = posix_acl_gid_translate(idmap, pa_entry);
1387                         break;
1388                 case ACL_GROUP_OBJ:
1389                         xa_entry->type = SMB_ACL_GROUP_OBJ;
1390                         break;
1391                 case ACL_OTHER:
1392                         xa_entry->type = SMB_ACL_OTHER;
1393                         break;
1394                 case ACL_MASK:
1395                         xa_entry->type = SMB_ACL_MASK;
1396                         break;
1397                 default:
1398                         pr_err("unknown type : 0x%x\n", pa_entry->e_tag);
1399                         goto out;
1400                 }
1401
1402                 if (pa_entry->e_perm & ACL_READ)
1403                         xa_entry->perm |= SMB_ACL_READ;
1404                 if (pa_entry->e_perm & ACL_WRITE)
1405                         xa_entry->perm |= SMB_ACL_WRITE;
1406                 if (pa_entry->e_perm & ACL_EXECUTE)
1407                         xa_entry->perm |= SMB_ACL_EXECUTE;
1408         }
1409 out:
1410         posix_acl_release(posix_acls);
1411         return smb_acl;
1412 }
1413
1414 int ksmbd_vfs_set_sd_xattr(struct ksmbd_conn *conn,
1415                            struct mnt_idmap *idmap,
1416                            const struct path *path,
1417                            struct smb_ntsd *pntsd, int len)
1418 {
1419         int rc;
1420         struct ndr sd_ndr = {0}, acl_ndr = {0};
1421         struct xattr_ntacl acl = {0};
1422         struct xattr_smb_acl *smb_acl, *def_smb_acl = NULL;
1423         struct dentry *dentry = path->dentry;
1424         struct inode *inode = d_inode(dentry);
1425
1426         acl.version = 4;
1427         acl.hash_type = XATTR_SD_HASH_TYPE_SHA256;
1428         acl.current_time = ksmbd_UnixTimeToNT(current_time(inode));
1429
1430         memcpy(acl.desc, "posix_acl", 9);
1431         acl.desc_len = 10;
1432
1433         pntsd->osidoffset =
1434                 cpu_to_le32(le32_to_cpu(pntsd->osidoffset) + NDR_NTSD_OFFSETOF);
1435         pntsd->gsidoffset =
1436                 cpu_to_le32(le32_to_cpu(pntsd->gsidoffset) + NDR_NTSD_OFFSETOF);
1437         pntsd->dacloffset =
1438                 cpu_to_le32(le32_to_cpu(pntsd->dacloffset) + NDR_NTSD_OFFSETOF);
1439
1440         acl.sd_buf = (char *)pntsd;
1441         acl.sd_size = len;
1442
1443         rc = ksmbd_gen_sd_hash(conn, acl.sd_buf, acl.sd_size, acl.hash);
1444         if (rc) {
1445                 pr_err("failed to generate hash for ndr acl\n");
1446                 return rc;
1447         }
1448
1449         smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1450                                                  ACL_TYPE_ACCESS);
1451         if (S_ISDIR(inode->i_mode))
1452                 def_smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1453                                                              ACL_TYPE_DEFAULT);
1454
1455         rc = ndr_encode_posix_acl(&acl_ndr, idmap, inode,
1456                                   smb_acl, def_smb_acl);
1457         if (rc) {
1458                 pr_err("failed to encode ndr to posix acl\n");
1459                 goto out;
1460         }
1461
1462         rc = ksmbd_gen_sd_hash(conn, acl_ndr.data, acl_ndr.offset,
1463                                acl.posix_acl_hash);
1464         if (rc) {
1465                 pr_err("failed to generate hash for ndr acl\n");
1466                 goto out;
1467         }
1468
1469         rc = ndr_encode_v4_ntacl(&sd_ndr, &acl);
1470         if (rc) {
1471                 pr_err("failed to encode ndr to posix acl\n");
1472                 goto out;
1473         }
1474
1475         rc = ksmbd_vfs_setxattr(idmap, path,
1476                                 XATTR_NAME_SD, sd_ndr.data,
1477                                 sd_ndr.offset, 0);
1478         if (rc < 0)
1479                 pr_err("Failed to store XATTR ntacl :%d\n", rc);
1480
1481         kfree(sd_ndr.data);
1482 out:
1483         kfree(acl_ndr.data);
1484         kfree(smb_acl);
1485         kfree(def_smb_acl);
1486         return rc;
1487 }
1488
1489 int ksmbd_vfs_get_sd_xattr(struct ksmbd_conn *conn,
1490                            struct mnt_idmap *idmap,
1491                            struct dentry *dentry,
1492                            struct smb_ntsd **pntsd)
1493 {
1494         int rc;
1495         struct ndr n;
1496         struct inode *inode = d_inode(dentry);
1497         struct ndr acl_ndr = {0};
1498         struct xattr_ntacl acl;
1499         struct xattr_smb_acl *smb_acl = NULL, *def_smb_acl = NULL;
1500         __u8 cmp_hash[XATTR_SD_HASH_SIZE] = {0};
1501
1502         rc = ksmbd_vfs_getxattr(idmap, dentry, XATTR_NAME_SD, &n.data);
1503         if (rc <= 0)
1504                 return rc;
1505
1506         n.length = rc;
1507         rc = ndr_decode_v4_ntacl(&n, &acl);
1508         if (rc)
1509                 goto free_n_data;
1510
1511         smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1512                                                  ACL_TYPE_ACCESS);
1513         if (S_ISDIR(inode->i_mode))
1514                 def_smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1515                                                              ACL_TYPE_DEFAULT);
1516
1517         rc = ndr_encode_posix_acl(&acl_ndr, idmap, inode, smb_acl,
1518                                   def_smb_acl);
1519         if (rc) {
1520                 pr_err("failed to encode ndr to posix acl\n");
1521                 goto out_free;
1522         }
1523
1524         rc = ksmbd_gen_sd_hash(conn, acl_ndr.data, acl_ndr.offset, cmp_hash);
1525         if (rc) {
1526                 pr_err("failed to generate hash for ndr acl\n");
1527                 goto out_free;
1528         }
1529
1530         if (memcmp(cmp_hash, acl.posix_acl_hash, XATTR_SD_HASH_SIZE)) {
1531                 pr_err("hash value diff\n");
1532                 rc = -EINVAL;
1533                 goto out_free;
1534         }
1535
1536         *pntsd = acl.sd_buf;
1537         if (acl.sd_size < sizeof(struct smb_ntsd)) {
1538                 pr_err("sd size is invalid\n");
1539                 goto out_free;
1540         }
1541
1542         (*pntsd)->osidoffset = cpu_to_le32(le32_to_cpu((*pntsd)->osidoffset) -
1543                                            NDR_NTSD_OFFSETOF);
1544         (*pntsd)->gsidoffset = cpu_to_le32(le32_to_cpu((*pntsd)->gsidoffset) -
1545                                            NDR_NTSD_OFFSETOF);
1546         (*pntsd)->dacloffset = cpu_to_le32(le32_to_cpu((*pntsd)->dacloffset) -
1547                                            NDR_NTSD_OFFSETOF);
1548
1549         rc = acl.sd_size;
1550 out_free:
1551         kfree(acl_ndr.data);
1552         kfree(smb_acl);
1553         kfree(def_smb_acl);
1554         if (rc < 0) {
1555                 kfree(acl.sd_buf);
1556                 *pntsd = NULL;
1557         }
1558
1559 free_n_data:
1560         kfree(n.data);
1561         return rc;
1562 }
1563
1564 int ksmbd_vfs_set_dos_attrib_xattr(struct mnt_idmap *idmap,
1565                                    const struct path *path,
1566                                    struct xattr_dos_attrib *da)
1567 {
1568         struct ndr n;
1569         int err;
1570
1571         err = ndr_encode_dos_attr(&n, da);
1572         if (err)
1573                 return err;
1574
1575         err = ksmbd_vfs_setxattr(idmap, path, XATTR_NAME_DOS_ATTRIBUTE,
1576                                  (void *)n.data, n.offset, 0);
1577         if (err)
1578                 ksmbd_debug(SMB, "failed to store dos attribute in xattr\n");
1579         kfree(n.data);
1580
1581         return err;
1582 }
1583
1584 int ksmbd_vfs_get_dos_attrib_xattr(struct mnt_idmap *idmap,
1585                                    struct dentry *dentry,
1586                                    struct xattr_dos_attrib *da)
1587 {
1588         struct ndr n;
1589         int err;
1590
1591         err = ksmbd_vfs_getxattr(idmap, dentry, XATTR_NAME_DOS_ATTRIBUTE,
1592                                  (char **)&n.data);
1593         if (err > 0) {
1594                 n.length = err;
1595                 if (ndr_decode_dos_attr(&n, da))
1596                         err = -EINVAL;
1597                 kfree(n.data);
1598         } else {
1599                 ksmbd_debug(SMB, "failed to load dos attribute in xattr\n");
1600         }
1601
1602         return err;
1603 }
1604
1605 /**
1606  * ksmbd_vfs_init_kstat() - convert unix stat information to smb stat format
1607  * @p:          destination buffer
1608  * @ksmbd_kstat:      ksmbd kstat wrapper
1609  */
1610 void *ksmbd_vfs_init_kstat(char **p, struct ksmbd_kstat *ksmbd_kstat)
1611 {
1612         struct file_directory_info *info = (struct file_directory_info *)(*p);
1613         struct kstat *kstat = ksmbd_kstat->kstat;
1614         u64 time;
1615
1616         info->FileIndex = 0;
1617         info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
1618         time = ksmbd_UnixTimeToNT(kstat->atime);
1619         info->LastAccessTime = cpu_to_le64(time);
1620         time = ksmbd_UnixTimeToNT(kstat->mtime);
1621         info->LastWriteTime = cpu_to_le64(time);
1622         time = ksmbd_UnixTimeToNT(kstat->ctime);
1623         info->ChangeTime = cpu_to_le64(time);
1624
1625         if (ksmbd_kstat->file_attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
1626                 info->EndOfFile = 0;
1627                 info->AllocationSize = 0;
1628         } else {
1629                 info->EndOfFile = cpu_to_le64(kstat->size);
1630                 info->AllocationSize = cpu_to_le64(kstat->blocks << 9);
1631         }
1632         info->ExtFileAttributes = ksmbd_kstat->file_attributes;
1633
1634         return info;
1635 }
1636
1637 int ksmbd_vfs_fill_dentry_attrs(struct ksmbd_work *work,
1638                                 struct mnt_idmap *idmap,
1639                                 struct dentry *dentry,
1640                                 struct ksmbd_kstat *ksmbd_kstat)
1641 {
1642         u64 time;
1643         int rc;
1644
1645         generic_fillattr(idmap, STATX_BASIC_STATS, d_inode(dentry),
1646                          ksmbd_kstat->kstat);
1647
1648         time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
1649         ksmbd_kstat->create_time = time;
1650
1651         /*
1652          * set default value for the case that store dos attributes is not yes
1653          * or that acl is disable in server's filesystem and the config is yes.
1654          */
1655         if (S_ISDIR(ksmbd_kstat->kstat->mode))
1656                 ksmbd_kstat->file_attributes = FILE_ATTRIBUTE_DIRECTORY_LE;
1657         else
1658                 ksmbd_kstat->file_attributes = FILE_ATTRIBUTE_ARCHIVE_LE;
1659
1660         if (test_share_config_flag(work->tcon->share_conf,
1661                                    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
1662                 struct xattr_dos_attrib da;
1663
1664                 rc = ksmbd_vfs_get_dos_attrib_xattr(idmap, dentry, &da);
1665                 if (rc > 0) {
1666                         ksmbd_kstat->file_attributes = cpu_to_le32(da.attr);
1667                         ksmbd_kstat->create_time = da.create_time;
1668                 } else {
1669                         ksmbd_debug(VFS, "fail to load dos attribute.\n");
1670                 }
1671         }
1672
1673         return 0;
1674 }
1675
1676 ssize_t ksmbd_vfs_casexattr_len(struct mnt_idmap *idmap,
1677                                 struct dentry *dentry, char *attr_name,
1678                                 int attr_name_len)
1679 {
1680         char *name, *xattr_list = NULL;
1681         ssize_t value_len = -ENOENT, xattr_list_len;
1682
1683         xattr_list_len = ksmbd_vfs_listxattr(dentry, &xattr_list);
1684         if (xattr_list_len <= 0)
1685                 goto out;
1686
1687         for (name = xattr_list; name - xattr_list < xattr_list_len;
1688                         name += strlen(name) + 1) {
1689                 ksmbd_debug(VFS, "%s, len %zd\n", name, strlen(name));
1690                 if (strncasecmp(attr_name, name, attr_name_len))
1691                         continue;
1692
1693                 value_len = ksmbd_vfs_xattr_len(idmap, dentry, name);
1694                 break;
1695         }
1696
1697 out:
1698         kvfree(xattr_list);
1699         return value_len;
1700 }
1701
1702 int ksmbd_vfs_xattr_stream_name(char *stream_name, char **xattr_stream_name,
1703                                 size_t *xattr_stream_name_size, int s_type)
1704 {
1705         char *type, *buf;
1706
1707         if (s_type == DIR_STREAM)
1708                 type = ":$INDEX_ALLOCATION";
1709         else
1710                 type = ":$DATA";
1711
1712         buf = kasprintf(GFP_KERNEL, "%s%s%s",
1713                         XATTR_NAME_STREAM, stream_name, type);
1714         if (!buf)
1715                 return -ENOMEM;
1716
1717         *xattr_stream_name = buf;
1718         *xattr_stream_name_size = strlen(buf) + 1;
1719
1720         return 0;
1721 }
1722
1723 int ksmbd_vfs_copy_file_ranges(struct ksmbd_work *work,
1724                                struct ksmbd_file *src_fp,
1725                                struct ksmbd_file *dst_fp,
1726                                struct srv_copychunk *chunks,
1727                                unsigned int chunk_count,
1728                                unsigned int *chunk_count_written,
1729                                unsigned int *chunk_size_written,
1730                                loff_t *total_size_written)
1731 {
1732         unsigned int i;
1733         loff_t src_off, dst_off, src_file_size;
1734         size_t len;
1735         int ret;
1736
1737         *chunk_count_written = 0;
1738         *chunk_size_written = 0;
1739         *total_size_written = 0;
1740
1741         if (!(src_fp->daccess & (FILE_READ_DATA_LE | FILE_EXECUTE_LE))) {
1742                 pr_err("no right to read(%pD)\n", src_fp->filp);
1743                 return -EACCES;
1744         }
1745         if (!(dst_fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE))) {
1746                 pr_err("no right to write(%pD)\n", dst_fp->filp);
1747                 return -EACCES;
1748         }
1749
1750         if (ksmbd_stream_fd(src_fp) || ksmbd_stream_fd(dst_fp))
1751                 return -EBADF;
1752
1753         smb_break_all_levII_oplock(work, dst_fp, 1);
1754
1755         if (!work->tcon->posix_extensions) {
1756                 for (i = 0; i < chunk_count; i++) {
1757                         src_off = le64_to_cpu(chunks[i].SourceOffset);
1758                         dst_off = le64_to_cpu(chunks[i].TargetOffset);
1759                         len = le32_to_cpu(chunks[i].Length);
1760
1761                         if (check_lock_range(src_fp->filp, src_off,
1762                                              src_off + len - 1, READ))
1763                                 return -EAGAIN;
1764                         if (check_lock_range(dst_fp->filp, dst_off,
1765                                              dst_off + len - 1, WRITE))
1766                                 return -EAGAIN;
1767                 }
1768         }
1769
1770         src_file_size = i_size_read(file_inode(src_fp->filp));
1771
1772         for (i = 0; i < chunk_count; i++) {
1773                 src_off = le64_to_cpu(chunks[i].SourceOffset);
1774                 dst_off = le64_to_cpu(chunks[i].TargetOffset);
1775                 len = le32_to_cpu(chunks[i].Length);
1776
1777                 if (src_off + len > src_file_size)
1778                         return -E2BIG;
1779
1780                 ret = vfs_copy_file_range(src_fp->filp, src_off,
1781                                           dst_fp->filp, dst_off, len, 0);
1782                 if (ret == -EOPNOTSUPP || ret == -EXDEV)
1783                         ret = vfs_copy_file_range(src_fp->filp, src_off,
1784                                                   dst_fp->filp, dst_off, len,
1785                                                   COPY_FILE_SPLICE);
1786                 if (ret < 0)
1787                         return ret;
1788
1789                 *chunk_count_written += 1;
1790                 *total_size_written += ret;
1791         }
1792         return 0;
1793 }
1794
1795 void ksmbd_vfs_posix_lock_wait(struct file_lock *flock)
1796 {
1797         wait_event(flock->fl_wait, !flock->fl_blocker);
1798 }
1799
1800 int ksmbd_vfs_posix_lock_wait_timeout(struct file_lock *flock, long timeout)
1801 {
1802         return wait_event_interruptible_timeout(flock->fl_wait,
1803                                                 !flock->fl_blocker,
1804                                                 timeout);
1805 }
1806
1807 void ksmbd_vfs_posix_lock_unblock(struct file_lock *flock)
1808 {
1809         locks_delete_block(flock);
1810 }
1811
1812 int ksmbd_vfs_set_init_posix_acl(struct mnt_idmap *idmap,
1813                                  struct path *path)
1814 {
1815         struct posix_acl_state acl_state;
1816         struct posix_acl *acls;
1817         struct dentry *dentry = path->dentry;
1818         struct inode *inode = d_inode(dentry);
1819         int rc;
1820
1821         if (!IS_ENABLED(CONFIG_FS_POSIX_ACL))
1822                 return -EOPNOTSUPP;
1823
1824         ksmbd_debug(SMB, "Set posix acls\n");
1825         rc = init_acl_state(&acl_state, 1);
1826         if (rc)
1827                 return rc;
1828
1829         /* Set default owner group */
1830         acl_state.owner.allow = (inode->i_mode & 0700) >> 6;
1831         acl_state.group.allow = (inode->i_mode & 0070) >> 3;
1832         acl_state.other.allow = inode->i_mode & 0007;
1833         acl_state.users->aces[acl_state.users->n].uid = inode->i_uid;
1834         acl_state.users->aces[acl_state.users->n++].perms.allow =
1835                 acl_state.owner.allow;
1836         acl_state.groups->aces[acl_state.groups->n].gid = inode->i_gid;
1837         acl_state.groups->aces[acl_state.groups->n++].perms.allow =
1838                 acl_state.group.allow;
1839         acl_state.mask.allow = 0x07;
1840
1841         acls = posix_acl_alloc(6, GFP_KERNEL);
1842         if (!acls) {
1843                 free_acl_state(&acl_state);
1844                 return -ENOMEM;
1845         }
1846         posix_state_to_acl(&acl_state, acls->a_entries);
1847
1848         rc = mnt_want_write(path->mnt);
1849         if (rc)
1850                 goto out_err;
1851
1852         rc = set_posix_acl(idmap, dentry, ACL_TYPE_ACCESS, acls);
1853         if (rc < 0)
1854                 ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_ACCESS) failed, rc : %d\n",
1855                             rc);
1856         else if (S_ISDIR(inode->i_mode)) {
1857                 posix_state_to_acl(&acl_state, acls->a_entries);
1858                 rc = set_posix_acl(idmap, dentry, ACL_TYPE_DEFAULT, acls);
1859                 if (rc < 0)
1860                         ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_DEFAULT) failed, rc : %d\n",
1861                                     rc);
1862         }
1863         mnt_drop_write(path->mnt);
1864
1865 out_err:
1866         free_acl_state(&acl_state);
1867         posix_acl_release(acls);
1868         return rc;
1869 }
1870
1871 int ksmbd_vfs_inherit_posix_acl(struct mnt_idmap *idmap,
1872                                 struct path *path, struct inode *parent_inode)
1873 {
1874         struct posix_acl *acls;
1875         struct posix_acl_entry *pace;
1876         struct dentry *dentry = path->dentry;
1877         struct inode *inode = d_inode(dentry);
1878         int rc, i;
1879
1880         if (!IS_ENABLED(CONFIG_FS_POSIX_ACL))
1881                 return -EOPNOTSUPP;
1882
1883         acls = get_inode_acl(parent_inode, ACL_TYPE_DEFAULT);
1884         if (IS_ERR_OR_NULL(acls))
1885                 return -ENOENT;
1886         pace = acls->a_entries;
1887
1888         for (i = 0; i < acls->a_count; i++, pace++) {
1889                 if (pace->e_tag == ACL_MASK) {
1890                         pace->e_perm = 0x07;
1891                         break;
1892                 }
1893         }
1894
1895         rc = mnt_want_write(path->mnt);
1896         if (rc)
1897                 goto out_err;
1898
1899         rc = set_posix_acl(idmap, dentry, ACL_TYPE_ACCESS, acls);
1900         if (rc < 0)
1901                 ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_ACCESS) failed, rc : %d\n",
1902                             rc);
1903         if (S_ISDIR(inode->i_mode)) {
1904                 rc = set_posix_acl(idmap, dentry, ACL_TYPE_DEFAULT,
1905                                    acls);
1906                 if (rc < 0)
1907                         ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_DEFAULT) failed, rc : %d\n",
1908                                     rc);
1909         }
1910         mnt_drop_write(path->mnt);
1911
1912 out_err:
1913         posix_acl_release(acls);
1914         return rc;
1915 }