ext2fs_lookup.c revision 1.71 1 /* $NetBSD: ext2fs_lookup.c,v 1.71 2012/11/05 17:24:12 dholland Exp $ */
2
3 /*
4 * Modified for NetBSD 1.2E
5 * May 1997, Manuel Bouyer
6 * Laboratoire d'informatique de Paris VI
7 */
8 /*
9 * modified for Lites 1.1
10 *
11 * Aug 1995, Godmar Back (gback (at) cs.utah.edu)
12 * University of Utah, Department of Computer Science
13 */
14 /*
15 * Copyright (c) 1989, 1993
16 * The Regents of the University of California. All rights reserved.
17 * (c) UNIX System Laboratories, Inc.
18 * All or some portions of this file are derived from material licensed
19 * to the University of California by American Telephone and Telegraph
20 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
21 * the permission of UNIX System Laboratories, Inc.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
34 *
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * SUCH DAMAGE.
46 *
47 * @(#)ufs_lookup.c 8.6 (Berkeley) 4/1/94
48 */
49
50 #include <sys/cdefs.h>
51 __KERNEL_RCSID(0, "$NetBSD: ext2fs_lookup.c,v 1.71 2012/11/05 17:24:12 dholland Exp $");
52
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/namei.h>
56 #include <sys/buf.h>
57 #include <sys/file.h>
58 #include <sys/mount.h>
59 #include <sys/vnode.h>
60 #include <sys/kmem.h>
61 #include <sys/malloc.h>
62 #include <sys/dirent.h>
63 #include <sys/kauth.h>
64 #include <sys/proc.h>
65
66 #include <ufs/ufs/inode.h>
67 #include <ufs/ufs/ufsmount.h>
68 #include <ufs/ufs/ufs_extern.h>
69
70 #include <ufs/ext2fs/ext2fs_extern.h>
71 #include <ufs/ext2fs/ext2fs_dir.h>
72 #include <ufs/ext2fs/ext2fs.h>
73
74 #include <miscfs/genfs/genfs.h>
75
76 extern int dirchk;
77
78 static void ext2fs_dirconv2ffs(struct ext2fs_direct *e2dir,
79 struct dirent *ffsdir);
80 static int ext2fs_dirbadentry(struct vnode *dp,
81 struct ext2fs_direct *de,
82 int entryoffsetinblock);
83
84 /*
85 * the problem that is tackled below is the fact that FFS
86 * includes the terminating zero on disk while EXT2FS doesn't
87 * this implies that we need to introduce some padding.
88 * For instance, a filename "sbin" has normally a reclen 12
89 * in EXT2, but 16 in FFS.
90 * This reminds me of that Pepsi commercial: 'Kid saved a lousy nine cents...'
91 * If it wasn't for that, the complete ufs code for directories would
92 * have worked w/o changes (except for the difference in DIRBLKSIZ)
93 */
94 static void
95 ext2fs_dirconv2ffs(struct ext2fs_direct *e2dir, struct dirent *ffsdir)
96 {
97 memset(ffsdir, 0, sizeof(struct dirent));
98 ffsdir->d_fileno = fs2h32(e2dir->e2d_ino);
99 ffsdir->d_namlen = e2dir->e2d_namlen;
100
101 ffsdir->d_type = DT_UNKNOWN; /* don't know more here */
102 #ifdef DIAGNOSTIC
103 #if MAXNAMLEN < E2FS_MAXNAMLEN
104 /*
105 * we should handle this more gracefully !
106 */
107 if (e2dir->e2d_namlen > MAXNAMLEN)
108 panic("ext2fs: e2dir->e2d_namlen");
109 #endif
110 #endif
111 strncpy(ffsdir->d_name, e2dir->e2d_name, ffsdir->d_namlen);
112
113 /* Godmar thinks: since e2dir->e2d_reclen can be big and means
114 nothing anyway, we compute our own reclen according to what
115 we think is right
116 */
117 ffsdir->d_reclen = _DIRENT_SIZE(ffsdir);
118 }
119
120 /*
121 * Vnode op for reading directories.
122 *
123 * Convert the on-disk entries to <sys/dirent.h> entries.
124 * the problem is that the conversion will blow up some entries by four bytes,
125 * so it can't be done in place. This is too bad. Right now the conversion is
126 * done entry by entry, the converted entry is sent via uiomove.
127 *
128 * XXX allocate a buffer, convert as many entries as possible, then send
129 * the whole buffer to uiomove
130 */
131 int
132 ext2fs_readdir(void *v)
133 {
134 struct vop_readdir_args /* {
135 struct vnode *a_vp;
136 struct uio *a_uio;
137 kauth_cred_t a_cred;
138 int **a_eofflag;
139 off_t **a_cookies;
140 int ncookies;
141 } */ *ap = v;
142 struct uio *uio = ap->a_uio;
143 int error;
144 size_t e2fs_count, readcnt;
145 struct vnode *vp = ap->a_vp;
146 struct m_ext2fs *fs = VTOI(vp)->i_e2fs;
147
148 struct ext2fs_direct *dp;
149 struct dirent *dstd;
150 struct uio auio;
151 struct iovec aiov;
152 void *dirbuf;
153 off_t off = uio->uio_offset;
154 off_t *cookies = NULL;
155 int nc = 0, ncookies = 0;
156 int e2d_reclen;
157
158 if (vp->v_type != VDIR)
159 return (ENOTDIR);
160
161 e2fs_count = uio->uio_resid;
162 /* Make sure we don't return partial entries. */
163 e2fs_count -= (uio->uio_offset + e2fs_count) & (fs->e2fs_bsize -1);
164 if (e2fs_count <= 0)
165 return (EINVAL);
166
167 auio = *uio;
168 auio.uio_iov = &aiov;
169 auio.uio_iovcnt = 1;
170 aiov.iov_len = e2fs_count;
171 auio.uio_resid = e2fs_count;
172 UIO_SETUP_SYSSPACE(&auio);
173 dirbuf = kmem_alloc(e2fs_count, KM_SLEEP);
174 dstd = kmem_zalloc(sizeof(struct dirent), KM_SLEEP);
175 if (ap->a_ncookies) {
176 nc = e2fs_count / _DIRENT_MINSIZE((struct dirent *)0);
177 ncookies = nc;
178 cookies = malloc(sizeof (off_t) * ncookies, M_TEMP, M_WAITOK);
179 *ap->a_cookies = cookies;
180 }
181 aiov.iov_base = dirbuf;
182
183 error = VOP_READ(ap->a_vp, &auio, 0, ap->a_cred);
184 if (error == 0) {
185 readcnt = e2fs_count - auio.uio_resid;
186 for (dp = (struct ext2fs_direct *)dirbuf;
187 (char *)dp < (char *)dirbuf + readcnt; ) {
188 e2d_reclen = fs2h16(dp->e2d_reclen);
189 if (e2d_reclen == 0) {
190 error = EIO;
191 break;
192 }
193 ext2fs_dirconv2ffs(dp, dstd);
194 if(dstd->d_reclen > uio->uio_resid) {
195 break;
196 }
197 error = uiomove(dstd, dstd->d_reclen, uio);
198 if (error != 0) {
199 break;
200 }
201 off = off + e2d_reclen;
202 if (cookies != NULL) {
203 *cookies++ = off;
204 if (--ncookies <= 0){
205 break; /* out of cookies */
206 }
207 }
208 /* advance dp */
209 dp = (struct ext2fs_direct *) ((char *)dp + e2d_reclen);
210 }
211 /* we need to correct uio_offset */
212 uio->uio_offset = off;
213 }
214 kmem_free(dirbuf, e2fs_count);
215 kmem_free(dstd, sizeof(*dstd));
216 *ap->a_eofflag = ext2fs_size(VTOI(ap->a_vp)) <= uio->uio_offset;
217 if (ap->a_ncookies) {
218 if (error) {
219 free(*ap->a_cookies, M_TEMP);
220 *ap->a_ncookies = 0;
221 *ap->a_cookies = NULL;
222 } else
223 *ap->a_ncookies = nc - ncookies;
224 }
225 return (error);
226 }
227
228 /*
229 * Convert a component of a pathname into a pointer to a locked inode.
230 * This is a very central and rather complicated routine.
231 * If the file system is not maintained in a strict tree hierarchy,
232 * this can result in a deadlock situation (see comments in code below).
233 *
234 * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
235 * on whether the name is to be looked up, created, renamed, or deleted.
236 * When CREATE, RENAME, or DELETE is specified, information usable in
237 * creating, renaming, or deleting a directory entry may be calculated.
238 * If flag has LOCKPARENT or'ed into it and the target of the pathname
239 * exists, lookup returns both the target and its parent directory locked.
240 * When creating or renaming and LOCKPARENT is specified, the target may
241 * not be ".". When deleting and LOCKPARENT is specified, the target may
242 * be "."., but the caller must check to ensure it does an vrele and vput
243 * instead of two vputs.
244 *
245 * Overall outline of ext2fs_lookup:
246 *
247 * check accessibility of directory
248 * look for name in cache, if found, then if at end of path
249 * and deleting or creating, drop it, else return name
250 * search for name in directory, to found or notfound
251 * notfound:
252 * if creating, return locked directory, leaving info on available slots
253 * else return error
254 * found:
255 * if at end of path and deleting, return information to allow delete
256 * if at end of path and rewriting (RENAME and LOCKPARENT), lock target
257 * inode and return info to allow rewrite
258 * if not at end, add name to cache; if at end and neither creating
259 * nor deleting, add name to cache
260 */
261 int
262 ext2fs_lookup(void *v)
263 {
264 struct vop_lookup_args /* {
265 struct vnode *a_dvp;
266 struct vnode **a_vpp;
267 struct componentname *a_cnp;
268 } */ *ap = v;
269 struct vnode *vdp = ap->a_dvp; /* vnode for directory being searched */
270 struct inode *dp = VTOI(vdp); /* inode for directory being searched */
271 struct buf *bp; /* a buffer of directory entries */
272 struct ext2fs_direct *ep; /* the current directory entry */
273 int entryoffsetinblock; /* offset of ep in bp's buffer */
274 enum {NONE, COMPACT, FOUND} slotstatus;
275 doff_t slotoffset; /* offset of area with free space */
276 int slotsize; /* size of area at slotoffset */
277 int slotfreespace; /* amount of space free in slot */
278 int slotneeded; /* size of the entry we're seeking */
279 int numdirpasses; /* strategy for directory search */
280 doff_t endsearch; /* offset to end directory search */
281 doff_t prevoff; /* prev entry dp->i_offset */
282 struct vnode *pdp; /* saved dp during symlink work */
283 struct vnode *tdp; /* returned by VFS_VGET */
284 doff_t enduseful; /* pointer past last used dir slot */
285 u_long bmask; /* block offset mask */
286 int namlen, error;
287 struct vnode **vpp = ap->a_vpp;
288 struct componentname *cnp = ap->a_cnp;
289 kauth_cred_t cred = cnp->cn_cred;
290 int flags;
291 int nameiop = cnp->cn_nameiop;
292 struct ufsmount *ump = dp->i_ump;
293 int dirblksiz = ump->um_dirblksiz;
294 ino_t foundino;
295 struct ufs_lookup_results *results;
296
297 flags = cnp->cn_flags;
298
299 bp = NULL;
300 slotoffset = -1;
301 *vpp = NULL;
302
303 /*
304 * Produce the auxiliary lookup results into i_crap. Increment
305 * its serial number so elsewhere we can tell if we're using
306 * stale results. This should not be done this way. XXX.
307 */
308 results = &dp->i_crap;
309 dp->i_crapcounter++;
310
311 /*
312 * Check accessiblity of directory.
313 */
314 if ((error = VOP_ACCESS(vdp, VEXEC, cred)) != 0)
315 return (error);
316
317 if ((flags & ISLASTCN) && (vdp->v_mount->mnt_flag & MNT_RDONLY) &&
318 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
319 return (EROFS);
320
321 /*
322 * We now have a segment name to search for, and a directory to search.
323 *
324 * Before tediously performing a linear scan of the directory,
325 * check the name cache to see if the directory/name pair
326 * we are looking for is known already.
327 */
328 if (cache_lookup(vdp, cnp, NULL, vpp)) {
329 return *vpp == NULLVP ? ENOENT : 0;
330 }
331
332 /*
333 * Suppress search for slots unless creating
334 * file and at end of pathname, in which case
335 * we watch for a place to put the new file in
336 * case it doesn't already exist.
337 */
338 slotstatus = FOUND;
339 slotfreespace = slotsize = slotneeded = 0;
340 if ((nameiop == CREATE || nameiop == RENAME) &&
341 (flags & ISLASTCN)) {
342 slotstatus = NONE;
343 slotneeded = EXT2FS_DIRSIZ(cnp->cn_namelen);
344 }
345
346 /*
347 * If there is cached information on a previous search of
348 * this directory, pick up where we last left off.
349 * We cache only lookups as these are the most common
350 * and have the greatest payoff. Caching CREATE has little
351 * benefit as it usually must search the entire directory
352 * to determine that the entry does not exist. Caching the
353 * location of the last DELETE or RENAME has not reduced
354 * profiling time and hence has been removed in the interest
355 * of simplicity.
356 */
357 bmask = vdp->v_mount->mnt_stat.f_iosize - 1;
358 if (nameiop != LOOKUP || results->ulr_diroff == 0 ||
359 results->ulr_diroff >= ext2fs_size(dp)) {
360 entryoffsetinblock = 0;
361 results->ulr_offset = 0;
362 numdirpasses = 1;
363 } else {
364 results->ulr_offset = results->ulr_diroff;
365 if ((entryoffsetinblock = results->ulr_offset & bmask) &&
366 (error = ext2fs_blkatoff(vdp, (off_t)results->ulr_offset, NULL, &bp)))
367 return (error);
368 numdirpasses = 2;
369 nchstats.ncs_2passes++;
370 }
371 prevoff = results->ulr_offset;
372 endsearch = roundup(ext2fs_size(dp), dirblksiz);
373 enduseful = 0;
374
375 searchloop:
376 while (results->ulr_offset < endsearch) {
377 if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD)
378 preempt();
379 /*
380 * If necessary, get the next directory block.
381 */
382 if ((results->ulr_offset & bmask) == 0) {
383 if (bp != NULL)
384 brelse(bp, 0);
385 error = ext2fs_blkatoff(vdp, (off_t)results->ulr_offset, NULL,
386 &bp);
387 if (error != 0)
388 return (error);
389 entryoffsetinblock = 0;
390 }
391 /*
392 * If still looking for a slot, and at a dirblksize
393 * boundary, have to start looking for free space again.
394 */
395 if (slotstatus == NONE &&
396 (entryoffsetinblock & (dirblksiz - 1)) == 0) {
397 slotoffset = -1;
398 slotfreespace = 0;
399 }
400 /*
401 * Get pointer to next entry.
402 * Full validation checks are slow, so we only check
403 * enough to insure forward progress through the
404 * directory. Complete checks can be run by patching
405 * "dirchk" to be true.
406 */
407 KASSERT(bp != NULL);
408 ep = (struct ext2fs_direct *)
409 ((char *)bp->b_data + entryoffsetinblock);
410 if (ep->e2d_reclen == 0 ||
411 (dirchk &&
412 ext2fs_dirbadentry(vdp, ep, entryoffsetinblock))) {
413 int i;
414
415 ufs_dirbad(dp, results->ulr_offset, "mangled entry");
416 i = dirblksiz - (entryoffsetinblock & (dirblksiz - 1));
417 results->ulr_offset += i;
418 entryoffsetinblock += i;
419 continue;
420 }
421
422 /*
423 * If an appropriate sized slot has not yet been found,
424 * check to see if one is available. Also accumulate space
425 * in the current block so that we can determine if
426 * compaction is viable.
427 */
428 if (slotstatus != FOUND) {
429 int size = fs2h16(ep->e2d_reclen);
430
431 if (ep->e2d_ino != 0)
432 size -= EXT2FS_DIRSIZ(ep->e2d_namlen);
433 if (size > 0) {
434 if (size >= slotneeded) {
435 slotstatus = FOUND;
436 slotoffset = results->ulr_offset;
437 slotsize = fs2h16(ep->e2d_reclen);
438 } else if (slotstatus == NONE) {
439 slotfreespace += size;
440 if (slotoffset == -1)
441 slotoffset = results->ulr_offset;
442 if (slotfreespace >= slotneeded) {
443 slotstatus = COMPACT;
444 slotsize = results->ulr_offset +
445 fs2h16(ep->e2d_reclen) -
446 slotoffset;
447 }
448 }
449 }
450 }
451
452 /*
453 * Check for a name match.
454 */
455 if (ep->e2d_ino) {
456 namlen = ep->e2d_namlen;
457 if (namlen == cnp->cn_namelen &&
458 !memcmp(cnp->cn_nameptr, ep->e2d_name,
459 (unsigned)namlen)) {
460 /*
461 * Save directory entry's inode number and
462 * reclen in ndp->ni_ufs area, and release
463 * directory buffer.
464 */
465 foundino = fs2h32(ep->e2d_ino);
466 results->ulr_reclen = fs2h16(ep->e2d_reclen);
467 goto found;
468 }
469 }
470 prevoff = results->ulr_offset;
471 results->ulr_offset += fs2h16(ep->e2d_reclen);
472 entryoffsetinblock += fs2h16(ep->e2d_reclen);
473 if (ep->e2d_ino)
474 enduseful = results->ulr_offset;
475 }
476 /* notfound: */
477 /*
478 * If we started in the middle of the directory and failed
479 * to find our target, we must check the beginning as well.
480 */
481 if (numdirpasses == 2) {
482 numdirpasses--;
483 results->ulr_offset = 0;
484 endsearch = results->ulr_diroff;
485 goto searchloop;
486 }
487 if (bp != NULL)
488 brelse(bp, 0);
489 /*
490 * If creating, and at end of pathname and current
491 * directory has not been removed, then can consider
492 * allowing file to be created.
493 */
494 if ((nameiop == CREATE || nameiop == RENAME) &&
495 (flags & ISLASTCN) && dp->i_e2fs_nlink != 0) {
496 /*
497 * Access for write is interpreted as allowing
498 * creation of files in the directory.
499 */
500 error = VOP_ACCESS(vdp, VWRITE, cred);
501 if (error)
502 return (error);
503 /*
504 * Return an indication of where the new directory
505 * entry should be put. If we didn't find a slot,
506 * then set results->ulr_count to 0 indicating
507 * that the new slot belongs at the end of the
508 * directory. If we found a slot, then the new entry
509 * can be put in the range from results->ulr_offset to
510 * results->ulr_offset + results->ulr_count.
511 */
512 if (slotstatus == NONE) {
513 results->ulr_offset = roundup(ext2fs_size(dp), dirblksiz);
514 results->ulr_count = 0;
515 enduseful = results->ulr_offset;
516 } else {
517 results->ulr_offset = slotoffset;
518 results->ulr_count = slotsize;
519 if (enduseful < slotoffset + slotsize)
520 enduseful = slotoffset + slotsize;
521 }
522 results->ulr_endoff = roundup(enduseful, dirblksiz);
523 #if 0
524 dp->i_flag |= IN_CHANGE | IN_UPDATE;
525 #endif
526 /*
527 * We return with the directory locked, so that
528 * the parameters we set up above will still be
529 * valid if we actually decide to do a direnter().
530 * We return ni_vp == NULL to indicate that the entry
531 * does not currently exist; we leave a pointer to
532 * the (locked) directory inode in ndp->ni_dvp.
533 *
534 * NB - if the directory is unlocked, then this
535 * information cannot be used.
536 */
537 return (EJUSTRETURN);
538 }
539 /*
540 * Insert name into cache (as non-existent) if appropriate.
541 */
542 if (nameiop != CREATE) {
543 cache_enter(vdp, *vpp, cnp);
544 }
545 return ENOENT;
546
547 found:
548 if (numdirpasses == 2)
549 nchstats.ncs_pass2++;
550 /*
551 * Check that directory length properly reflects presence
552 * of this entry.
553 */
554 if (results->ulr_offset + EXT2FS_DIRSIZ(ep->e2d_namlen) > ext2fs_size(dp)) {
555 ufs_dirbad(dp, results->ulr_offset, "i_size too small");
556 error = ext2fs_setsize(dp,
557 results->ulr_offset + EXT2FS_DIRSIZ(ep->e2d_namlen));
558 if (error) {
559 brelse(bp, 0);
560 return (error);
561 }
562 dp->i_flag |= IN_CHANGE | IN_UPDATE;
563 uvm_vnp_setsize(vdp, ext2fs_size(dp));
564 }
565 brelse(bp, 0);
566
567 /*
568 * Found component in pathname.
569 * If the final component of path name, save information
570 * in the cache as to where the entry was found.
571 */
572 if ((flags & ISLASTCN) && nameiop == LOOKUP)
573 results->ulr_diroff = results->ulr_offset &~ (dirblksiz - 1);
574
575 /*
576 * If deleting, and at end of pathname, return
577 * parameters which can be used to remove file.
578 * Lock the inode, being careful with ".".
579 */
580 if (nameiop == DELETE && (flags & ISLASTCN)) {
581 /*
582 * Return pointer to current entry in results->ulr_offset,
583 * and distance past previous entry (if there
584 * is a previous entry in this block) in results->ulr_count.
585 * Save directory inode pointer in ndp->ni_dvp for dirremove().
586 */
587 if ((results->ulr_offset & (dirblksiz - 1)) == 0)
588 results->ulr_count = 0;
589 else
590 results->ulr_count = results->ulr_offset - prevoff;
591 if (dp->i_number == foundino) {
592 vref(vdp);
593 tdp = vdp;
594 } else {
595 if (flags & ISDOTDOT)
596 VOP_UNLOCK(vdp); /* race to get the inode */
597 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
598 if (flags & ISDOTDOT)
599 vn_lock(vdp, LK_EXCLUSIVE | LK_RETRY);
600 if (error)
601 return (error);
602 }
603 /*
604 * Write access to directory required to delete files.
605 */
606 if ((error = VOP_ACCESS(vdp, VWRITE, cred)) != 0) {
607 if (dp->i_number == foundino)
608 vrele(tdp);
609 else
610 vput(tdp);
611 return (error);
612 }
613 /*
614 * If directory is "sticky", then user must own
615 * the directory, or the file in it, else she
616 * may not delete it (unless she's root). This
617 * implements append-only directories.
618 */
619 if (dp->i_e2fs_mode & ISVTX) {
620 error = kauth_authorize_vnode(cred, KAUTH_VNODE_DELETE,
621 tdp, vdp, genfs_can_sticky(cred, dp->i_uid,
622 VTOI(tdp)->i_uid));
623 if (error) {
624 if (dp->i_number == foundino)
625 vrele(tdp);
626 else
627 vput(tdp);
628 return (EPERM);
629 }
630 }
631 *vpp = tdp;
632 return (0);
633 }
634
635 /*
636 * If rewriting (RENAME), return the inode and the
637 * information required to rewrite the present directory
638 * Must get inode of directory entry to verify it's a
639 * regular file, or empty directory.
640 */
641 if (nameiop == RENAME && (flags & ISLASTCN)) {
642 error = VOP_ACCESS(vdp, VWRITE, cred);
643 if (error)
644 return (error);
645 /*
646 * Careful about locking second inode.
647 * This can only occur if the target is ".".
648 */
649 if (dp->i_number == foundino)
650 return (EISDIR);
651 if (flags & ISDOTDOT)
652 VOP_UNLOCK(vdp); /* race to get the inode */
653 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
654 if (flags & ISDOTDOT)
655 vn_lock(vdp, LK_EXCLUSIVE | LK_RETRY);
656 if (error)
657 return (error);
658 *vpp = tdp;
659 return (0);
660 }
661
662 /*
663 * Step through the translation in the name. We do not `vput' the
664 * directory because we may need it again if a symbolic link
665 * is relative to the current directory. Instead we save it
666 * unlocked as "pdp". We must get the target inode before unlocking
667 * the directory to insure that the inode will not be removed
668 * before we get it. We prevent deadlock by always fetching
669 * inodes from the root, moving down the directory tree. Thus
670 * when following backward pointers ".." we must unlock the
671 * parent directory before getting the requested directory.
672 * There is a potential race condition here if both the current
673 * and parent directories are removed before the VFS_VGET for the
674 * inode associated with ".." returns. We hope that this occurs
675 * infrequently since we cannot avoid this race condition without
676 * implementing a sophisticated deadlock detection algorithm.
677 * Note also that this simple deadlock detection scheme will not
678 * work if the file system has any hard links other than ".."
679 * that point backwards in the directory structure.
680 */
681 pdp = vdp;
682 if (flags & ISDOTDOT) {
683 VOP_UNLOCK(pdp); /* race to get the inode */
684 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
685 vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY);
686 if (error) {
687 return (error);
688 }
689 *vpp = tdp;
690 } else if (dp->i_number == foundino) {
691 vref(vdp); /* we want ourself, ie "." */
692 *vpp = vdp;
693 } else {
694 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
695 if (error)
696 return (error);
697 *vpp = tdp;
698 }
699
700 /*
701 * Insert name into cache if appropriate.
702 */
703 cache_enter(vdp, *vpp, cnp);
704 return 0;
705 }
706
707 /*
708 * Do consistency checking on a directory entry:
709 * record length must be multiple of 4
710 * entry must fit in rest of its dirblksize block
711 * record must be large enough to contain entry
712 * name is not longer than EXT2FS_MAXNAMLEN
713 * name must be as long as advertised, and null terminated
714 */
715 /*
716 * changed so that it confirms to ext2fs_check_dir_entry
717 */
718 static int
719 ext2fs_dirbadentry(struct vnode *dp, struct ext2fs_direct *de,
720 int entryoffsetinblock)
721 {
722 struct ufsmount *ump = VFSTOUFS(dp->v_mount);
723 int dirblksiz = ump->um_dirblksiz;
724
725 const char *error_msg = NULL;
726 int reclen = fs2h16(de->e2d_reclen);
727 int namlen = de->e2d_namlen;
728
729 if (reclen < EXT2FS_DIRSIZ(1)) /* e2d_namlen = 1 */
730 error_msg = "rec_len is smaller than minimal";
731 else if (reclen % 4 != 0)
732 error_msg = "rec_len % 4 != 0";
733 else if (namlen > EXT2FS_MAXNAMLEN)
734 error_msg = "namlen > EXT2FS_MAXNAMLEN";
735 else if (reclen < EXT2FS_DIRSIZ(namlen))
736 error_msg = "reclen is too small for name_len";
737 else if (entryoffsetinblock + reclen > dirblksiz)
738 error_msg = "directory entry across blocks";
739 else if (fs2h32(de->e2d_ino) >
740 VTOI(dp)->i_e2fs->e2fs.e2fs_icount)
741 error_msg = "inode out of bounds";
742
743 if (error_msg != NULL) {
744 printf( "bad directory entry: %s\n"
745 "offset=%d, inode=%lu, rec_len=%d, name_len=%d \n",
746 error_msg, entryoffsetinblock,
747 (unsigned long) fs2h32(de->e2d_ino),
748 reclen, namlen);
749 panic("ext2fs_dirbadentry");
750 }
751 return error_msg == NULL ? 0 : 1;
752 }
753
754 /*
755 * Write a directory entry after a call to namei, using the parameters
756 * that it left in nameidata. The argument ip is the inode which the new
757 * directory entry will refer to. Dvp is a pointer to the directory to
758 * be written, which was left locked by namei. Remaining parameters
759 * (ulr_offset, ulr_count) indicate how the space for the new
760 * entry is to be obtained.
761 */
762 int
763 ext2fs_direnter(struct inode *ip, struct vnode *dvp,
764 const struct ufs_lookup_results *ulr,
765 struct componentname *cnp)
766 {
767 struct ext2fs_direct *ep, *nep;
768 struct inode *dp;
769 struct buf *bp;
770 struct ext2fs_direct newdir;
771 struct iovec aiov;
772 struct uio auio;
773 u_int dsize;
774 int error, loc, newentrysize, spacefree;
775 char *dirbuf;
776 struct ufsmount *ump = VFSTOUFS(dvp->v_mount);
777 int dirblksiz = ump->um_dirblksiz;
778
779 dp = VTOI(dvp);
780
781 newdir.e2d_ino = h2fs32(ip->i_number);
782 newdir.e2d_namlen = cnp->cn_namelen;
783 if (ip->i_e2fs->e2fs.e2fs_rev > E2FS_REV0 &&
784 (ip->i_e2fs->e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) {
785 newdir.e2d_type = inot2ext2dt(IFTODT(ip->i_e2fs_mode));
786 } else {
787 newdir.e2d_type = 0;
788 }
789 memcpy(newdir.e2d_name, cnp->cn_nameptr, (unsigned)cnp->cn_namelen + 1);
790 newentrysize = EXT2FS_DIRSIZ(cnp->cn_namelen);
791 if (ulr->ulr_count == 0) {
792 /*
793 * If ulr_count is 0, then namei could find no
794 * space in the directory. Here, ulr_offset will
795 * be on a directory block boundary and we will write the
796 * new entry into a fresh block.
797 */
798 if (ulr->ulr_offset & (dirblksiz - 1))
799 panic("ext2fs_direnter: newblk");
800 auio.uio_offset = ulr->ulr_offset;
801 newdir.e2d_reclen = h2fs16(dirblksiz);
802 auio.uio_resid = newentrysize;
803 aiov.iov_len = newentrysize;
804 aiov.iov_base = (void *)&newdir;
805 auio.uio_iov = &aiov;
806 auio.uio_iovcnt = 1;
807 auio.uio_rw = UIO_WRITE;
808 UIO_SETUP_SYSSPACE(&auio);
809 error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
810 if (dirblksiz > dvp->v_mount->mnt_stat.f_bsize)
811 /* XXX should grow with balloc() */
812 panic("ext2fs_direnter: frag size");
813 else if (!error) {
814 error = ext2fs_setsize(dp,
815 roundup(ext2fs_size(dp), dirblksiz));
816 if (error)
817 return (error);
818 dp->i_flag |= IN_CHANGE;
819 uvm_vnp_setsize(dvp, ext2fs_size(dp));
820 }
821 return (error);
822 }
823
824 /*
825 * If ulr_count is non-zero, then namei found space
826 * for the new entry in the range ulr_offset to
827 * ulr_offset + ulr_count in the directory.
828 * To use this space, we may have to compact the entries located
829 * there, by copying them together towards the beginning of the
830 * block, leaving the free space in one usable chunk at the end.
831 */
832
833 /*
834 * Get the block containing the space for the new directory entry.
835 */
836 if ((error = ext2fs_blkatoff(dvp, (off_t)ulr->ulr_offset, &dirbuf, &bp)) != 0)
837 return (error);
838 /*
839 * Find space for the new entry. In the simple case, the entry at
840 * offset base will have the space. If it does not, then namei
841 * arranged that compacting the region ulr_offset to
842 * ulr_offset + ulr_count would yield the
843 * space.
844 */
845 ep = (struct ext2fs_direct *)dirbuf;
846 dsize = EXT2FS_DIRSIZ(ep->e2d_namlen);
847 spacefree = fs2h16(ep->e2d_reclen) - dsize;
848 for (loc = fs2h16(ep->e2d_reclen); loc < ulr->ulr_count; ) {
849 nep = (struct ext2fs_direct *)(dirbuf + loc);
850 if (ep->e2d_ino) {
851 /* trim the existing slot */
852 ep->e2d_reclen = h2fs16(dsize);
853 ep = (struct ext2fs_direct *)((char *)ep + dsize);
854 } else {
855 /* overwrite; nothing there; header is ours */
856 spacefree += dsize;
857 }
858 dsize = EXT2FS_DIRSIZ(nep->e2d_namlen);
859 spacefree += fs2h16(nep->e2d_reclen) - dsize;
860 loc += fs2h16(nep->e2d_reclen);
861 memcpy((void *)ep, (void *)nep, dsize);
862 }
863 /*
864 * Update the pointer fields in the previous entry (if any),
865 * copy in the new entry, and write out the block.
866 */
867 if (ep->e2d_ino == 0) {
868 #ifdef DIAGNOSTIC
869 if (spacefree + dsize < newentrysize)
870 panic("ext2fs_direnter: compact1");
871 #endif
872 newdir.e2d_reclen = h2fs16(spacefree + dsize);
873 } else {
874 #ifdef DIAGNOSTIC
875 if (spacefree < newentrysize) {
876 printf("ext2fs_direnter: compact2 %u %u",
877 (u_int)spacefree, (u_int)newentrysize);
878 panic("ext2fs_direnter: compact2");
879 }
880 #endif
881 newdir.e2d_reclen = h2fs16(spacefree);
882 ep->e2d_reclen = h2fs16(dsize);
883 ep = (struct ext2fs_direct *)((char *)ep + dsize);
884 }
885 memcpy((void *)ep, (void *)&newdir, (u_int)newentrysize);
886 error = VOP_BWRITE(bp->b_vp, bp);
887 dp->i_flag |= IN_CHANGE | IN_UPDATE;
888 if (!error && ulr->ulr_endoff && ulr->ulr_endoff < ext2fs_size(dp))
889 error = ext2fs_truncate(dvp, (off_t)ulr->ulr_endoff, IO_SYNC,
890 cnp->cn_cred);
891 return (error);
892 }
893
894 /*
895 * Remove a directory entry after a call to namei, using
896 * the auxiliary results it provided. The entry
897 * ulr_offset contains the offset into the directory of the
898 * entry to be eliminated. The ulr_count field contains the
899 * size of the previous record in the directory. If this
900 * is 0, the first entry is being deleted, so we need only
901 * zero the inode number to mark the entry as free. If the
902 * entry is not the first in the directory, we must reclaim
903 * the space of the now empty record by adding the record size
904 * to the size of the previous entry.
905 */
906 int
907 ext2fs_dirremove(struct vnode *dvp, const struct ufs_lookup_results *ulr,
908 struct componentname *cnp)
909 {
910 struct inode *dp;
911 struct ext2fs_direct *ep;
912 struct buf *bp;
913 int error;
914
915 dp = VTOI(dvp);
916
917 if (ulr->ulr_count == 0) {
918 /*
919 * First entry in block: set d_ino to zero.
920 */
921 error = ext2fs_blkatoff(dvp, (off_t)ulr->ulr_offset,
922 (void *)&ep, &bp);
923 if (error != 0)
924 return (error);
925 ep->e2d_ino = 0;
926 error = VOP_BWRITE(bp->b_vp, bp);
927 dp->i_flag |= IN_CHANGE | IN_UPDATE;
928 return (error);
929 }
930 /*
931 * Collapse new free space into previous entry.
932 */
933 error = ext2fs_blkatoff(dvp, (off_t)(ulr->ulr_offset - ulr->ulr_count),
934 (void *)&ep, &bp);
935 if (error != 0)
936 return (error);
937 ep->e2d_reclen = h2fs16(fs2h16(ep->e2d_reclen) + ulr->ulr_reclen);
938 error = VOP_BWRITE(bp->b_vp, bp);
939 dp->i_flag |= IN_CHANGE | IN_UPDATE;
940 return (error);
941 }
942
943 /*
944 * Rewrite an existing directory entry to point at the inode
945 * supplied. The parameters describing the directory entry are
946 * set up by a call to namei.
947 */
948 int
949 ext2fs_dirrewrite(struct inode *dp, const struct ufs_lookup_results *ulr,
950 struct inode *ip, struct componentname *cnp)
951 {
952 struct buf *bp;
953 struct ext2fs_direct *ep;
954 struct vnode *vdp = ITOV(dp);
955 int error;
956
957 error = ext2fs_blkatoff(vdp, (off_t)ulr->ulr_offset, (void *)&ep, &bp);
958 if (error != 0)
959 return (error);
960 ep->e2d_ino = h2fs32(ip->i_number);
961 if (ip->i_e2fs->e2fs.e2fs_rev > E2FS_REV0 &&
962 (ip->i_e2fs->e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) {
963 ep->e2d_type = inot2ext2dt(IFTODT(ip->i_e2fs_mode));
964 } else {
965 ep->e2d_type = 0;
966 }
967 error = VOP_BWRITE(bp->b_vp, bp);
968 dp->i_flag |= IN_CHANGE | IN_UPDATE;
969 return (error);
970 }
971
972 /*
973 * Check if a directory is empty or not.
974 * Inode supplied must be locked.
975 *
976 * Using a struct dirtemplate here is not precisely
977 * what we want, but better than using a struct ext2fs_direct.
978 *
979 * NB: does not handle corrupted directories.
980 */
981 int
982 ext2fs_dirempty(struct inode *ip, ino_t parentino, kauth_cred_t cred)
983 {
984 off_t off;
985 struct ext2fs_dirtemplate dbuf;
986 struct ext2fs_direct *dp = (struct ext2fs_direct *)&dbuf;
987 int error, namlen;
988 size_t count;
989
990 #define MINDIRSIZ (sizeof (struct ext2fs_dirtemplate) / 2)
991
992 for (off = 0; off < ext2fs_size(ip); off += fs2h16(dp->e2d_reclen)) {
993 error = vn_rdwr(UIO_READ, ITOV(ip), (void *)dp, MINDIRSIZ, off,
994 UIO_SYSSPACE, IO_NODELOCKED, cred, &count, NULL);
995 /*
996 * Since we read MINDIRSIZ, residual must
997 * be 0 unless we're at end of file.
998 */
999 if (error || count != 0)
1000 return (0);
1001 /* avoid infinite loops */
1002 if (dp->e2d_reclen == 0)
1003 return (0);
1004 /* skip empty entries */
1005 if (dp->e2d_ino == 0)
1006 continue;
1007 /* accept only "." and ".." */
1008 namlen = dp->e2d_namlen;
1009 if (namlen > 2)
1010 return (0);
1011 if (dp->e2d_name[0] != '.')
1012 return (0);
1013 /*
1014 * At this point namlen must be 1 or 2.
1015 * 1 implies ".", 2 implies ".." if second
1016 * char is also "."
1017 */
1018 if (namlen == 1)
1019 continue;
1020 if (dp->e2d_name[1] == '.' && fs2h32(dp->e2d_ino) == parentino)
1021 continue;
1022 return (0);
1023 }
1024 return (1);
1025 }
1026
1027 /*
1028 * Check if source directory is in the path of the target directory.
1029 * Target is supplied locked, source is unlocked.
1030 * The target is always vput before returning.
1031 */
1032 int
1033 ext2fs_checkpath(struct inode *source, struct inode *target,
1034 kauth_cred_t cred)
1035 {
1036 struct vnode *vp;
1037 int error, rootino, namlen;
1038 struct ext2fs_dirtemplate dirbuf;
1039 uint32_t ino;
1040
1041 vp = ITOV(target);
1042 if (target->i_number == source->i_number) {
1043 error = EEXIST;
1044 goto out;
1045 }
1046 rootino = ROOTINO;
1047 error = 0;
1048 if (target->i_number == rootino)
1049 goto out;
1050
1051 for (;;) {
1052 if (vp->v_type != VDIR) {
1053 error = ENOTDIR;
1054 break;
1055 }
1056 error = vn_rdwr(UIO_READ, vp, (void *)&dirbuf,
1057 sizeof (struct ext2fs_dirtemplate), (off_t)0,
1058 UIO_SYSSPACE, IO_NODELOCKED, cred, (size_t *)0,
1059 NULL);
1060 if (error != 0)
1061 break;
1062 namlen = dirbuf.dotdot_namlen;
1063 if (namlen != 2 ||
1064 dirbuf.dotdot_name[0] != '.' ||
1065 dirbuf.dotdot_name[1] != '.') {
1066 error = ENOTDIR;
1067 break;
1068 }
1069 ino = fs2h32(dirbuf.dotdot_ino);
1070 if (ino == source->i_number) {
1071 error = EINVAL;
1072 break;
1073 }
1074 if (ino == rootino)
1075 break;
1076 vput(vp);
1077 error = VFS_VGET(vp->v_mount, ino, &vp);
1078 if (error != 0) {
1079 vp = NULL;
1080 break;
1081 }
1082 }
1083
1084 out:
1085 if (error == ENOTDIR) {
1086 printf("checkpath: .. not a directory\n");
1087 panic("checkpath");
1088 }
1089 if (vp != NULL)
1090 vput(vp);
1091 return (error);
1092 }
1093