810a333d2221a0d441d08c9a158374e17844a4b3
[linux-2.6-microblaze.git] / fs / overlayfs / namei.c
1 /*
2  * Copyright (C) 2011 Novell Inc.
3  * Copyright (C) 2016 Red Hat, Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published by
7  * the Free Software Foundation.
8  */
9
10 #include <linux/fs.h>
11 #include <linux/cred.h>
12 #include <linux/ctype.h>
13 #include <linux/namei.h>
14 #include <linux/xattr.h>
15 #include <linux/ratelimit.h>
16 #include <linux/mount.h>
17 #include <linux/exportfs.h>
18 #include "overlayfs.h"
19
20 struct ovl_lookup_data {
21         struct qstr name;
22         bool is_dir;
23         bool opaque;
24         bool stop;
25         bool last;
26         char *redirect;
27 };
28
29 static int ovl_check_redirect(struct dentry *dentry, struct ovl_lookup_data *d,
30                               size_t prelen, const char *post)
31 {
32         int res;
33         char *s, *next, *buf = NULL;
34
35         res = vfs_getxattr(dentry, OVL_XATTR_REDIRECT, NULL, 0);
36         if (res < 0) {
37                 if (res == -ENODATA || res == -EOPNOTSUPP)
38                         return 0;
39                 goto fail;
40         }
41         buf = kzalloc(prelen + res + strlen(post) + 1, GFP_KERNEL);
42         if (!buf)
43                 return -ENOMEM;
44
45         if (res == 0)
46                 goto invalid;
47
48         res = vfs_getxattr(dentry, OVL_XATTR_REDIRECT, buf, res);
49         if (res < 0)
50                 goto fail;
51         if (res == 0)
52                 goto invalid;
53         if (buf[0] == '/') {
54                 for (s = buf; *s++ == '/'; s = next) {
55                         next = strchrnul(s, '/');
56                         if (s == next)
57                                 goto invalid;
58                 }
59                 /*
60                  * One of the ancestor path elements in an absolute path
61                  * lookup in ovl_lookup_layer() could have been opaque and
62                  * that will stop further lookup in lower layers (d->stop=true)
63                  * But we have found an absolute redirect in decendant path
64                  * element and that should force continue lookup in lower
65                  * layers (reset d->stop).
66                  */
67                 d->stop = false;
68         } else {
69                 if (strchr(buf, '/') != NULL)
70                         goto invalid;
71
72                 memmove(buf + prelen, buf, res);
73                 memcpy(buf, d->name.name, prelen);
74         }
75
76         strcat(buf, post);
77         kfree(d->redirect);
78         d->redirect = buf;
79         d->name.name = d->redirect;
80         d->name.len = strlen(d->redirect);
81
82         return 0;
83
84 err_free:
85         kfree(buf);
86         return 0;
87 fail:
88         pr_warn_ratelimited("overlayfs: failed to get redirect (%i)\n", res);
89         goto err_free;
90 invalid:
91         pr_warn_ratelimited("overlayfs: invalid redirect (%s)\n", buf);
92         goto err_free;
93 }
94
95 static int ovl_acceptable(void *ctx, struct dentry *dentry)
96 {
97         /*
98          * A non-dir origin may be disconnected, which is fine, because
99          * we only need it for its unique inode number.
100          */
101         if (!d_is_dir(dentry))
102                 return 1;
103
104         /* Don't decode a deleted empty directory */
105         if (d_unhashed(dentry))
106                 return 0;
107
108         /* Check if directory belongs to the layer we are decoding from */
109         return is_subdir(dentry, ((struct vfsmount *)ctx)->mnt_root);
110 }
111
112 /*
113  * Check validity of an overlay file handle buffer.
114  *
115  * Return 0 for a valid file handle.
116  * Return -ENODATA for "origin unknown".
117  * Return <0 for an invalid file handle.
118  */
119 int ovl_check_fh_len(struct ovl_fh *fh, int fh_len)
120 {
121         if (fh_len < sizeof(struct ovl_fh) || fh_len < fh->len)
122                 return -EINVAL;
123
124         if (fh->magic != OVL_FH_MAGIC)
125                 return -EINVAL;
126
127         /* Treat larger version and unknown flags as "origin unknown" */
128         if (fh->version > OVL_FH_VERSION || fh->flags & ~OVL_FH_FLAG_ALL)
129                 return -ENODATA;
130
131         /* Treat endianness mismatch as "origin unknown" */
132         if (!(fh->flags & OVL_FH_FLAG_ANY_ENDIAN) &&
133             (fh->flags & OVL_FH_FLAG_BIG_ENDIAN) != OVL_FH_FLAG_CPU_ENDIAN)
134                 return -ENODATA;
135
136         return 0;
137 }
138
139 static struct ovl_fh *ovl_get_fh(struct dentry *dentry, const char *name)
140 {
141         int res, err;
142         struct ovl_fh *fh = NULL;
143
144         res = vfs_getxattr(dentry, name, NULL, 0);
145         if (res < 0) {
146                 if (res == -ENODATA || res == -EOPNOTSUPP)
147                         return NULL;
148                 goto fail;
149         }
150         /* Zero size value means "copied up but origin unknown" */
151         if (res == 0)
152                 return NULL;
153
154         fh = kzalloc(res, GFP_KERNEL);
155         if (!fh)
156                 return ERR_PTR(-ENOMEM);
157
158         res = vfs_getxattr(dentry, name, fh, res);
159         if (res < 0)
160                 goto fail;
161
162         err = ovl_check_fh_len(fh, res);
163         if (err < 0) {
164                 if (err == -ENODATA)
165                         goto out;
166                 goto invalid;
167         }
168
169         return fh;
170
171 out:
172         kfree(fh);
173         return NULL;
174
175 fail:
176         pr_warn_ratelimited("overlayfs: failed to get origin (%i)\n", res);
177         goto out;
178 invalid:
179         pr_warn_ratelimited("overlayfs: invalid origin (%*phN)\n", res, fh);
180         goto out;
181 }
182
183 struct dentry *ovl_decode_real_fh(struct ovl_fh *fh, struct vfsmount *mnt,
184                                   bool connected)
185 {
186         struct dentry *real;
187         int bytes;
188
189         /*
190          * Make sure that the stored uuid matches the uuid of the lower
191          * layer where file handle will be decoded.
192          */
193         if (!uuid_equal(&fh->uuid, &mnt->mnt_sb->s_uuid))
194                 return NULL;
195
196         bytes = (fh->len - offsetof(struct ovl_fh, fid));
197         real = exportfs_decode_fh(mnt, (struct fid *)fh->fid,
198                                   bytes >> 2, (int)fh->type,
199                                   connected ? ovl_acceptable : NULL, mnt);
200         if (IS_ERR(real)) {
201                 /*
202                  * Treat stale file handle to lower file as "origin unknown".
203                  * upper file handle could become stale when upper file is
204                  * unlinked and this information is needed to handle stale
205                  * index entries correctly.
206                  */
207                 if (real == ERR_PTR(-ESTALE) &&
208                     !(fh->flags & OVL_FH_FLAG_PATH_UPPER))
209                         real = NULL;
210                 return real;
211         }
212
213         if (ovl_dentry_weird(real)) {
214                 dput(real);
215                 return NULL;
216         }
217
218         return real;
219 }
220
221 static bool ovl_is_opaquedir(struct dentry *dentry)
222 {
223         return ovl_check_dir_xattr(dentry, OVL_XATTR_OPAQUE);
224 }
225
226 static int ovl_lookup_single(struct dentry *base, struct ovl_lookup_data *d,
227                              const char *name, unsigned int namelen,
228                              size_t prelen, const char *post,
229                              struct dentry **ret)
230 {
231         struct dentry *this;
232         int err;
233
234         this = lookup_one_len_unlocked(name, base, namelen);
235         if (IS_ERR(this)) {
236                 err = PTR_ERR(this);
237                 this = NULL;
238                 if (err == -ENOENT || err == -ENAMETOOLONG)
239                         goto out;
240                 goto out_err;
241         }
242         if (!this->d_inode)
243                 goto put_and_out;
244
245         if (ovl_dentry_weird(this)) {
246                 /* Don't support traversing automounts and other weirdness */
247                 err = -EREMOTE;
248                 goto out_err;
249         }
250         if (ovl_is_whiteout(this)) {
251                 d->stop = d->opaque = true;
252                 goto put_and_out;
253         }
254         if (!d_can_lookup(this)) {
255                 d->stop = true;
256                 if (d->is_dir)
257                         goto put_and_out;
258                 goto out;
259         }
260         d->is_dir = true;
261         if (!d->last && ovl_is_opaquedir(this)) {
262                 d->stop = d->opaque = true;
263                 goto out;
264         }
265         err = ovl_check_redirect(this, d, prelen, post);
266         if (err)
267                 goto out_err;
268 out:
269         *ret = this;
270         return 0;
271
272 put_and_out:
273         dput(this);
274         this = NULL;
275         goto out;
276
277 out_err:
278         dput(this);
279         return err;
280 }
281
282 static int ovl_lookup_layer(struct dentry *base, struct ovl_lookup_data *d,
283                             struct dentry **ret)
284 {
285         /* Counting down from the end, since the prefix can change */
286         size_t rem = d->name.len - 1;
287         struct dentry *dentry = NULL;
288         int err;
289
290         if (d->name.name[0] != '/')
291                 return ovl_lookup_single(base, d, d->name.name, d->name.len,
292                                          0, "", ret);
293
294         while (!IS_ERR_OR_NULL(base) && d_can_lookup(base)) {
295                 const char *s = d->name.name + d->name.len - rem;
296                 const char *next = strchrnul(s, '/');
297                 size_t thislen = next - s;
298                 bool end = !next[0];
299
300                 /* Verify we did not go off the rails */
301                 if (WARN_ON(s[-1] != '/'))
302                         return -EIO;
303
304                 err = ovl_lookup_single(base, d, s, thislen,
305                                         d->name.len - rem, next, &base);
306                 dput(dentry);
307                 if (err)
308                         return err;
309                 dentry = base;
310                 if (end)
311                         break;
312
313                 rem -= thislen + 1;
314
315                 if (WARN_ON(rem >= d->name.len))
316                         return -EIO;
317         }
318         *ret = dentry;
319         return 0;
320 }
321
322
323 int ovl_check_origin_fh(struct ovl_fs *ofs, struct ovl_fh *fh, bool connected,
324                         struct dentry *upperdentry, struct ovl_path **stackp)
325 {
326         struct dentry *origin = NULL;
327         int i;
328
329         for (i = 0; i < ofs->numlower; i++) {
330                 origin = ovl_decode_real_fh(fh, ofs->lower_layers[i].mnt,
331                                             connected);
332                 if (origin)
333                         break;
334         }
335
336         if (!origin)
337                 return -ESTALE;
338         else if (IS_ERR(origin))
339                 return PTR_ERR(origin);
340
341         if (upperdentry && !ovl_is_whiteout(upperdentry) &&
342             ((d_inode(origin)->i_mode ^ d_inode(upperdentry)->i_mode) & S_IFMT))
343                 goto invalid;
344
345         if (!*stackp)
346                 *stackp = kmalloc(sizeof(struct ovl_path), GFP_KERNEL);
347         if (!*stackp) {
348                 dput(origin);
349                 return -ENOMEM;
350         }
351         **stackp = (struct ovl_path){
352                 .dentry = origin,
353                 .layer = &ofs->lower_layers[i]
354         };
355
356         return 0;
357
358 invalid:
359         pr_warn_ratelimited("overlayfs: invalid origin (%pd2, ftype=%x, origin ftype=%x).\n",
360                             upperdentry, d_inode(upperdentry)->i_mode & S_IFMT,
361                             d_inode(origin)->i_mode & S_IFMT);
362         dput(origin);
363         return -EIO;
364 }
365
366 static int ovl_check_origin(struct ovl_fs *ofs, struct dentry *upperdentry,
367                             struct ovl_path **stackp, unsigned int *ctrp)
368 {
369         struct ovl_fh *fh = ovl_get_fh(upperdentry, OVL_XATTR_ORIGIN);
370         int err;
371
372         if (IS_ERR_OR_NULL(fh))
373                 return PTR_ERR(fh);
374
375         err = ovl_check_origin_fh(ofs, fh, false, upperdentry, stackp);
376         kfree(fh);
377
378         if (err) {
379                 if (err == -ESTALE)
380                         return 0;
381                 return err;
382         }
383
384         if (WARN_ON(*ctrp))
385                 return -EIO;
386
387         *ctrp = 1;
388         return 0;
389 }
390
391 /*
392  * Verify that @fh matches the file handle stored in xattr @name.
393  * Return 0 on match, -ESTALE on mismatch, < 0 on error.
394  */
395 static int ovl_verify_fh(struct dentry *dentry, const char *name,
396                          const struct ovl_fh *fh)
397 {
398         struct ovl_fh *ofh = ovl_get_fh(dentry, name);
399         int err = 0;
400
401         if (!ofh)
402                 return -ENODATA;
403
404         if (IS_ERR(ofh))
405                 return PTR_ERR(ofh);
406
407         if (fh->len != ofh->len || memcmp(fh, ofh, fh->len))
408                 err = -ESTALE;
409
410         kfree(ofh);
411         return err;
412 }
413
414 /*
415  * Verify that @real dentry matches the file handle stored in xattr @name.
416  *
417  * If @set is true and there is no stored file handle, encode @real and store
418  * file handle in xattr @name.
419  *
420  * Return 0 on match, -ESTALE on mismatch, -ENODATA on no xattr, < 0 on error.
421  */
422 int ovl_verify_set_fh(struct dentry *dentry, const char *name,
423                       struct dentry *real, bool is_upper, bool set)
424 {
425         struct inode *inode;
426         struct ovl_fh *fh;
427         int err;
428
429         fh = ovl_encode_real_fh(real, is_upper);
430         err = PTR_ERR(fh);
431         if (IS_ERR(fh))
432                 goto fail;
433
434         err = ovl_verify_fh(dentry, name, fh);
435         if (set && err == -ENODATA)
436                 err = ovl_do_setxattr(dentry, name, fh, fh->len, 0);
437         if (err)
438                 goto fail;
439
440 out:
441         kfree(fh);
442         return err;
443
444 fail:
445         inode = d_inode(real);
446         pr_warn_ratelimited("overlayfs: failed to verify %s (%pd2, ino=%lu, err=%i)\n",
447                             is_upper ? "upper" : "origin", real,
448                             inode ? inode->i_ino : 0, err);
449         goto out;
450 }
451
452 /* Get upper dentry from index */
453 struct dentry *ovl_index_upper(struct ovl_fs *ofs, struct dentry *index)
454 {
455         struct ovl_fh *fh;
456         struct dentry *upper;
457
458         if (!d_is_dir(index))
459                 return dget(index);
460
461         fh = ovl_get_fh(index, OVL_XATTR_UPPER);
462         if (IS_ERR_OR_NULL(fh))
463                 return ERR_CAST(fh);
464
465         upper = ovl_decode_real_fh(fh, ofs->upper_mnt, true);
466         kfree(fh);
467
468         if (IS_ERR_OR_NULL(upper))
469                 return upper ?: ERR_PTR(-ESTALE);
470
471         if (!d_is_dir(upper)) {
472                 pr_warn_ratelimited("overlayfs: invalid index upper (%pd2, upper=%pd2).\n",
473                                     index, upper);
474                 dput(upper);
475                 return ERR_PTR(-EIO);
476         }
477
478         return upper;
479 }
480
481 /* Is this a leftover from create/whiteout of directory index entry? */
482 static bool ovl_is_temp_index(struct dentry *index)
483 {
484         return index->d_name.name[0] == '#';
485 }
486
487 /*
488  * Verify that an index entry name matches the origin file handle stored in
489  * OVL_XATTR_ORIGIN and that origin file handle can be decoded to lower path.
490  * Return 0 on match, -ESTALE on mismatch or stale origin, < 0 on error.
491  */
492 int ovl_verify_index(struct ovl_fs *ofs, struct dentry *index)
493 {
494         struct ovl_fh *fh = NULL;
495         size_t len;
496         struct ovl_path origin = { };
497         struct ovl_path *stack = &origin;
498         struct dentry *upper = NULL;
499         int err;
500
501         if (!d_inode(index))
502                 return 0;
503
504         /* Cleanup leftover from index create/cleanup attempt */
505         err = -ESTALE;
506         if (ovl_is_temp_index(index))
507                 goto fail;
508
509         err = -EINVAL;
510         if (index->d_name.len < sizeof(struct ovl_fh)*2)
511                 goto fail;
512
513         err = -ENOMEM;
514         len = index->d_name.len / 2;
515         fh = kzalloc(len, GFP_KERNEL);
516         if (!fh)
517                 goto fail;
518
519         err = -EINVAL;
520         if (hex2bin((u8 *)fh, index->d_name.name, len))
521                 goto fail;
522
523         err = ovl_check_fh_len(fh, len);
524         if (err)
525                 goto fail;
526
527         /*
528          * Whiteout index entries are used as an indication that an exported
529          * overlay file handle should be treated as stale (i.e. after unlink
530          * of the overlay inode). These entries contain no origin xattr.
531          */
532         if (ovl_is_whiteout(index))
533                 goto out;
534
535         /*
536          * Verifying directory index entries are not stale is expensive, so
537          * only verify stale dir index if NFS export is enabled.
538          */
539         if (d_is_dir(index) && !ofs->config.nfs_export)
540                 goto out;
541
542         /*
543          * Directory index entries should have 'upper' xattr pointing to the
544          * real upper dir. Non-dir index entries are hardlinks to the upper
545          * real inode. For non-dir index, we can read the copy up origin xattr
546          * directly from the index dentry, but for dir index we first need to
547          * decode the upper directory.
548          */
549         upper = ovl_index_upper(ofs, index);
550         if (IS_ERR_OR_NULL(upper)) {
551                 err = PTR_ERR(upper);
552                 /*
553                  * Directory index entries with no 'upper' xattr need to be
554                  * removed. When dir index entry has a stale 'upper' xattr,
555                  * we assume that upper dir was removed and we treat the dir
556                  * index as orphan entry that needs to be whited out.
557                  */
558                 if (err == -ESTALE)
559                         goto orphan;
560                 else if (!err)
561                         err = -ESTALE;
562                 goto fail;
563         }
564
565         err = ovl_verify_fh(upper, OVL_XATTR_ORIGIN, fh);
566         dput(upper);
567         if (err)
568                 goto fail;
569
570         /* Check if non-dir index is orphan and don't warn before cleaning it */
571         if (!d_is_dir(index) && d_inode(index)->i_nlink == 1) {
572                 err = ovl_check_origin_fh(ofs, fh, false, index, &stack);
573                 if (err)
574                         goto fail;
575
576                 if (ovl_get_nlink(origin.dentry, index, 0) == 0)
577                         goto orphan;
578         }
579
580 out:
581         dput(origin.dentry);
582         kfree(fh);
583         return err;
584
585 fail:
586         pr_warn_ratelimited("overlayfs: failed to verify index (%pd2, ftype=%x, err=%i)\n",
587                             index, d_inode(index)->i_mode & S_IFMT, err);
588         goto out;
589
590 orphan:
591         pr_warn_ratelimited("overlayfs: orphan index entry (%pd2, ftype=%x, nlink=%u)\n",
592                             index, d_inode(index)->i_mode & S_IFMT,
593                             d_inode(index)->i_nlink);
594         err = -ENOENT;
595         goto out;
596 }
597
598 static int ovl_get_index_name_fh(struct ovl_fh *fh, struct qstr *name)
599 {
600         char *n, *s;
601
602         n = kzalloc(fh->len * 2, GFP_KERNEL);
603         if (!n)
604                 return -ENOMEM;
605
606         s  = bin2hex(n, fh, fh->len);
607         *name = (struct qstr) QSTR_INIT(n, s - n);
608
609         return 0;
610
611 }
612
613 /*
614  * Lookup in indexdir for the index entry of a lower real inode or a copy up
615  * origin inode. The index entry name is the hex representation of the lower
616  * inode file handle.
617  *
618  * If the index dentry in negative, then either no lower aliases have been
619  * copied up yet, or aliases have been copied up in older kernels and are
620  * not indexed.
621  *
622  * If the index dentry for a copy up origin inode is positive, but points
623  * to an inode different than the upper inode, then either the upper inode
624  * has been copied up and not indexed or it was indexed, but since then
625  * index dir was cleared. Either way, that index cannot be used to indentify
626  * the overlay inode.
627  */
628 int ovl_get_index_name(struct dentry *origin, struct qstr *name)
629 {
630         struct ovl_fh *fh;
631         int err;
632
633         fh = ovl_encode_real_fh(origin, false);
634         if (IS_ERR(fh))
635                 return PTR_ERR(fh);
636
637         err = ovl_get_index_name_fh(fh, name);
638
639         kfree(fh);
640         return err;
641 }
642
643 /* Lookup index by file handle for NFS export */
644 struct dentry *ovl_get_index_fh(struct ovl_fs *ofs, struct ovl_fh *fh)
645 {
646         struct dentry *index;
647         struct qstr name;
648         int err;
649
650         err = ovl_get_index_name_fh(fh, &name);
651         if (err)
652                 return ERR_PTR(err);
653
654         index = lookup_one_len_unlocked(name.name, ofs->indexdir, name.len);
655         kfree(name.name);
656         if (IS_ERR(index)) {
657                 if (PTR_ERR(index) == -ENOENT)
658                         index = NULL;
659                 return index;
660         }
661
662         if (d_is_negative(index))
663                 err = 0;
664         else if (ovl_is_whiteout(index))
665                 err = -ESTALE;
666         else if (ovl_dentry_weird(index))
667                 err = -EIO;
668         else
669                 return index;
670
671         dput(index);
672         return ERR_PTR(err);
673 }
674
675 struct dentry *ovl_lookup_index(struct ovl_fs *ofs, struct dentry *upper,
676                                 struct dentry *origin, bool verify)
677 {
678         struct dentry *index;
679         struct inode *inode;
680         struct qstr name;
681         bool is_dir = d_is_dir(origin);
682         int err;
683
684         err = ovl_get_index_name(origin, &name);
685         if (err)
686                 return ERR_PTR(err);
687
688         index = lookup_one_len_unlocked(name.name, ofs->indexdir, name.len);
689         if (IS_ERR(index)) {
690                 err = PTR_ERR(index);
691                 if (err == -ENOENT) {
692                         index = NULL;
693                         goto out;
694                 }
695                 pr_warn_ratelimited("overlayfs: failed inode index lookup (ino=%lu, key=%*s, err=%i);\n"
696                                     "overlayfs: mount with '-o index=off' to disable inodes index.\n",
697                                     d_inode(origin)->i_ino, name.len, name.name,
698                                     err);
699                 goto out;
700         }
701
702         inode = d_inode(index);
703         if (d_is_negative(index)) {
704                 goto out_dput;
705         } else if (ovl_is_whiteout(index) && !verify) {
706                 /*
707                  * When index lookup is called with !verify for decoding an
708                  * overlay file handle, a whiteout index implies that decode
709                  * should treat file handle as stale and no need to print a
710                  * warning about it.
711                  */
712                 dput(index);
713                 index = ERR_PTR(-ESTALE);
714                 goto out;
715         } else if (ovl_dentry_weird(index) || ovl_is_whiteout(index) ||
716                    ((inode->i_mode ^ d_inode(origin)->i_mode) & S_IFMT)) {
717                 /*
718                  * Index should always be of the same file type as origin
719                  * except for the case of a whiteout index. A whiteout
720                  * index should only exist if all lower aliases have been
721                  * unlinked, which means that finding a lower origin on lookup
722                  * whose index is a whiteout should be treated as an error.
723                  */
724                 pr_warn_ratelimited("overlayfs: bad index found (index=%pd2, ftype=%x, origin ftype=%x).\n",
725                                     index, d_inode(index)->i_mode & S_IFMT,
726                                     d_inode(origin)->i_mode & S_IFMT);
727                 goto fail;
728         } else if (is_dir && verify) {
729                 if (!upper) {
730                         pr_warn_ratelimited("overlayfs: suspected uncovered redirected dir found (origin=%pd2, index=%pd2).\n",
731                                             origin, index);
732                         goto fail;
733                 }
734
735                 /* Verify that dir index 'upper' xattr points to upper dir */
736                 err = ovl_verify_upper(index, upper, false);
737                 if (err) {
738                         if (err == -ESTALE) {
739                                 pr_warn_ratelimited("overlayfs: suspected multiply redirected dir found (upper=%pd2, origin=%pd2, index=%pd2).\n",
740                                                     upper, origin, index);
741                         }
742                         goto fail;
743                 }
744         } else if (upper && d_inode(upper) != inode) {
745                 goto out_dput;
746         }
747 out:
748         kfree(name.name);
749         return index;
750
751 out_dput:
752         dput(index);
753         index = NULL;
754         goto out;
755
756 fail:
757         dput(index);
758         index = ERR_PTR(-EIO);
759         goto out;
760 }
761
762 /*
763  * Returns next layer in stack starting from top.
764  * Returns -1 if this is the last layer.
765  */
766 int ovl_path_next(int idx, struct dentry *dentry, struct path *path)
767 {
768         struct ovl_entry *oe = dentry->d_fsdata;
769
770         BUG_ON(idx < 0);
771         if (idx == 0) {
772                 ovl_path_upper(dentry, path);
773                 if (path->dentry)
774                         return oe->numlower ? 1 : -1;
775                 idx++;
776         }
777         BUG_ON(idx > oe->numlower);
778         path->dentry = oe->lowerstack[idx - 1].dentry;
779         path->mnt = oe->lowerstack[idx - 1].layer->mnt;
780
781         return (idx < oe->numlower) ? idx + 1 : -1;
782 }
783
784 /* Fix missing 'origin' xattr */
785 static int ovl_fix_origin(struct dentry *dentry, struct dentry *lower,
786                           struct dentry *upper)
787 {
788         int err;
789
790         if (ovl_check_origin_xattr(upper))
791                 return 0;
792
793         err = ovl_want_write(dentry);
794         if (err)
795                 return err;
796
797         err = ovl_set_origin(dentry, lower, upper);
798         if (!err)
799                 err = ovl_set_impure(dentry->d_parent, upper->d_parent);
800
801         ovl_drop_write(dentry);
802         return err;
803 }
804
805 struct dentry *ovl_lookup(struct inode *dir, struct dentry *dentry,
806                           unsigned int flags)
807 {
808         struct ovl_entry *oe;
809         const struct cred *old_cred;
810         struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
811         struct ovl_entry *poe = dentry->d_parent->d_fsdata;
812         struct ovl_entry *roe = dentry->d_sb->s_root->d_fsdata;
813         struct ovl_path *stack = NULL;
814         struct dentry *upperdir, *upperdentry = NULL;
815         struct dentry *origin = NULL;
816         struct dentry *index = NULL;
817         unsigned int ctr = 0;
818         struct inode *inode = NULL;
819         bool upperopaque = false;
820         char *upperredirect = NULL;
821         struct dentry *this;
822         unsigned int i;
823         int err;
824         struct ovl_lookup_data d = {
825                 .name = dentry->d_name,
826                 .is_dir = false,
827                 .opaque = false,
828                 .stop = false,
829                 .last = ofs->config.redirect_follow ? false : !poe->numlower,
830                 .redirect = NULL,
831         };
832
833         if (dentry->d_name.len > ofs->namelen)
834                 return ERR_PTR(-ENAMETOOLONG);
835
836         old_cred = ovl_override_creds(dentry->d_sb);
837         upperdir = ovl_dentry_upper(dentry->d_parent);
838         if (upperdir) {
839                 err = ovl_lookup_layer(upperdir, &d, &upperdentry);
840                 if (err)
841                         goto out;
842
843                 if (upperdentry && unlikely(ovl_dentry_remote(upperdentry))) {
844                         dput(upperdentry);
845                         err = -EREMOTE;
846                         goto out;
847                 }
848                 if (upperdentry && !d.is_dir) {
849                         BUG_ON(!d.stop || d.redirect);
850                         /*
851                          * Lookup copy up origin by decoding origin file handle.
852                          * We may get a disconnected dentry, which is fine,
853                          * because we only need to hold the origin inode in
854                          * cache and use its inode number.  We may even get a
855                          * connected dentry, that is not under any of the lower
856                          * layers root.  That is also fine for using it's inode
857                          * number - it's the same as if we held a reference
858                          * to a dentry in lower layer that was moved under us.
859                          */
860                         err = ovl_check_origin(ofs, upperdentry, &stack, &ctr);
861                         if (err)
862                                 goto out_put_upper;
863                 }
864
865                 if (d.redirect) {
866                         err = -ENOMEM;
867                         upperredirect = kstrdup(d.redirect, GFP_KERNEL);
868                         if (!upperredirect)
869                                 goto out_put_upper;
870                         if (d.redirect[0] == '/')
871                                 poe = roe;
872                 }
873                 upperopaque = d.opaque;
874         }
875
876         if (!d.stop && poe->numlower) {
877                 err = -ENOMEM;
878                 stack = kcalloc(ofs->numlower, sizeof(struct ovl_path),
879                                 GFP_KERNEL);
880                 if (!stack)
881                         goto out_put_upper;
882         }
883
884         for (i = 0; !d.stop && i < poe->numlower; i++) {
885                 struct ovl_path lower = poe->lowerstack[i];
886
887                 if (!ofs->config.redirect_follow)
888                         d.last = i == poe->numlower - 1;
889                 else
890                         d.last = lower.layer->idx == roe->numlower;
891
892                 err = ovl_lookup_layer(lower.dentry, &d, &this);
893                 if (err)
894                         goto out_put;
895
896                 if (!this)
897                         continue;
898
899                 /*
900                  * If no origin fh is stored in upper of a merge dir, store fh
901                  * of lower dir and set upper parent "impure".
902                  */
903                 if (upperdentry && !ctr && !ofs->noxattr) {
904                         err = ovl_fix_origin(dentry, this, upperdentry);
905                         if (err) {
906                                 dput(this);
907                                 goto out_put;
908                         }
909                 }
910
911                 /*
912                  * When "verify_lower" feature is enabled, do not merge with a
913                  * lower dir that does not match a stored origin xattr. In any
914                  * case, only verified origin is used for index lookup.
915                  */
916                 if (upperdentry && !ctr && ovl_verify_lower(dentry->d_sb)) {
917                         err = ovl_verify_origin(upperdentry, this, false);
918                         if (err) {
919                                 dput(this);
920                                 break;
921                         }
922
923                         /* Bless lower dir as verified origin */
924                         origin = this;
925                 }
926
927                 stack[ctr].dentry = this;
928                 stack[ctr].layer = lower.layer;
929                 ctr++;
930
931                 /*
932                  * Following redirects can have security consequences: it's like
933                  * a symlink into the lower layer without the permission checks.
934                  * This is only a problem if the upper layer is untrusted (e.g
935                  * comes from an USB drive).  This can allow a non-readable file
936                  * or directory to become readable.
937                  *
938                  * Only following redirects when redirects are enabled disables
939                  * this attack vector when not necessary.
940                  */
941                 err = -EPERM;
942                 if (d.redirect && !ofs->config.redirect_follow) {
943                         pr_warn_ratelimited("overlayfs: refusing to follow redirect for (%pd2)\n",
944                                             dentry);
945                         goto out_put;
946                 }
947
948                 if (d.stop)
949                         break;
950
951                 if (d.redirect && d.redirect[0] == '/' && poe != roe) {
952                         poe = roe;
953                         /* Find the current layer on the root dentry */
954                         i = lower.layer->idx - 1;
955                 }
956         }
957
958         /*
959          * Lookup index by lower inode and verify it matches upper inode.
960          * We only trust dir index if we verified that lower dir matches
961          * origin, otherwise dir index entries may be inconsistent and we
962          * ignore them. Always lookup index of non-dir and non-upper.
963          */
964         if (ctr && (!upperdentry || !d.is_dir))
965                 origin = stack[0].dentry;
966
967         if (origin && ovl_indexdir(dentry->d_sb) &&
968             (!d.is_dir || ovl_index_all(dentry->d_sb))) {
969                 index = ovl_lookup_index(ofs, upperdentry, origin, true);
970                 if (IS_ERR(index)) {
971                         err = PTR_ERR(index);
972                         index = NULL;
973                         goto out_put;
974                 }
975         }
976
977         oe = ovl_alloc_entry(ctr);
978         err = -ENOMEM;
979         if (!oe)
980                 goto out_put;
981
982         memcpy(oe->lowerstack, stack, sizeof(struct ovl_path) * ctr);
983         dentry->d_fsdata = oe;
984
985         if (upperopaque)
986                 ovl_dentry_set_opaque(dentry);
987
988         if (upperdentry)
989                 ovl_dentry_set_upper_alias(dentry);
990         else if (index)
991                 upperdentry = dget(index);
992
993         if (upperdentry || ctr) {
994                 if (ctr)
995                         origin = stack[0].dentry;
996                 inode = ovl_get_inode(dentry->d_sb, upperdentry, origin, index,
997                                       ctr);
998                 err = PTR_ERR(inode);
999                 if (IS_ERR(inode))
1000                         goto out_free_oe;
1001
1002                 OVL_I(inode)->redirect = upperredirect;
1003                 if (index)
1004                         ovl_set_flag(OVL_INDEX, inode);
1005         }
1006
1007         revert_creds(old_cred);
1008         dput(index);
1009         kfree(stack);
1010         kfree(d.redirect);
1011         return d_splice_alias(inode, dentry);
1012
1013 out_free_oe:
1014         dentry->d_fsdata = NULL;
1015         kfree(oe);
1016 out_put:
1017         dput(index);
1018         for (i = 0; i < ctr; i++)
1019                 dput(stack[i].dentry);
1020         kfree(stack);
1021 out_put_upper:
1022         dput(upperdentry);
1023         kfree(upperredirect);
1024 out:
1025         kfree(d.redirect);
1026         revert_creds(old_cred);
1027         return ERR_PTR(err);
1028 }
1029
1030 bool ovl_lower_positive(struct dentry *dentry)
1031 {
1032         struct ovl_entry *poe = dentry->d_parent->d_fsdata;
1033         const struct qstr *name = &dentry->d_name;
1034         const struct cred *old_cred;
1035         unsigned int i;
1036         bool positive = false;
1037         bool done = false;
1038
1039         /*
1040          * If dentry is negative, then lower is positive iff this is a
1041          * whiteout.
1042          */
1043         if (!dentry->d_inode)
1044                 return ovl_dentry_is_opaque(dentry);
1045
1046         /* Negative upper -> positive lower */
1047         if (!ovl_dentry_upper(dentry))
1048                 return true;
1049
1050         old_cred = ovl_override_creds(dentry->d_sb);
1051         /* Positive upper -> have to look up lower to see whether it exists */
1052         for (i = 0; !done && !positive && i < poe->numlower; i++) {
1053                 struct dentry *this;
1054                 struct dentry *lowerdir = poe->lowerstack[i].dentry;
1055
1056                 this = lookup_one_len_unlocked(name->name, lowerdir,
1057                                                name->len);
1058                 if (IS_ERR(this)) {
1059                         switch (PTR_ERR(this)) {
1060                         case -ENOENT:
1061                         case -ENAMETOOLONG:
1062                                 break;
1063
1064                         default:
1065                                 /*
1066                                  * Assume something is there, we just couldn't
1067                                  * access it.
1068                                  */
1069                                 positive = true;
1070                                 break;
1071                         }
1072                 } else {
1073                         if (this->d_inode) {
1074                                 positive = !ovl_is_whiteout(this);
1075                                 done = true;
1076                         }
1077                         dput(this);
1078                 }
1079         }
1080         revert_creds(old_cred);
1081
1082         return positive;
1083 }