ext2fs_lookup.c revision 1.68 1 /* $NetBSD: ext2fs_lookup.c,v 1.68 2012/03/13 18:41:03 elad 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.68 2012/03/13 18:41:03 elad 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 ((error = cache_lookup(vdp, vpp, cnp)) >= 0)
329 return (error);
330
331 /*
332 * Suppress search for slots unless creating
333 * file and at end of pathname, in which case
334 * we watch for a place to put the new file in
335 * case it doesn't already exist.
336 */
337 slotstatus = FOUND;
338 slotfreespace = slotsize = slotneeded = 0;
339 if ((nameiop == CREATE || nameiop == RENAME) &&
340 (flags & ISLASTCN)) {
341 slotstatus = NONE;
342 slotneeded = EXT2FS_DIRSIZ(cnp->cn_namelen);
343 }
344
345 /*
346 * If there is cached information on a previous search of
347 * this directory, pick up where we last left off.
348 * We cache only lookups as these are the most common
349 * and have the greatest payoff. Caching CREATE has little
350 * benefit as it usually must search the entire directory
351 * to determine that the entry does not exist. Caching the
352 * location of the last DELETE or RENAME has not reduced
353 * profiling time and hence has been removed in the interest
354 * of simplicity.
355 */
356 bmask = vdp->v_mount->mnt_stat.f_iosize - 1;
357 if (nameiop != LOOKUP || results->ulr_diroff == 0 ||
358 results->ulr_diroff >= ext2fs_size(dp)) {
359 entryoffsetinblock = 0;
360 results->ulr_offset = 0;
361 numdirpasses = 1;
362 } else {
363 results->ulr_offset = results->ulr_diroff;
364 if ((entryoffsetinblock = results->ulr_offset & bmask) &&
365 (error = ext2fs_blkatoff(vdp, (off_t)results->ulr_offset, NULL, &bp)))
366 return (error);
367 numdirpasses = 2;
368 nchstats.ncs_2passes++;
369 }
370 prevoff = results->ulr_offset;
371 endsearch = roundup(ext2fs_size(dp), dirblksiz);
372 enduseful = 0;
373
374 searchloop:
375 while (results->ulr_offset < endsearch) {
376 if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD)
377 preempt();
378 /*
379 * If necessary, get the next directory block.
380 */
381 if ((results->ulr_offset & bmask) == 0) {
382 if (bp != NULL)
383 brelse(bp, 0);
384 error = ext2fs_blkatoff(vdp, (off_t)results->ulr_offset, NULL,
385 &bp);
386 if (error != 0)
387 return (error);
388 entryoffsetinblock = 0;
389 }
390 /*
391 * If still looking for a slot, and at a dirblksize
392 * boundary, have to start looking for free space again.
393 */
394 if (slotstatus == NONE &&
395 (entryoffsetinblock & (dirblksiz - 1)) == 0) {
396 slotoffset = -1;
397 slotfreespace = 0;
398 }
399 /*
400 * Get pointer to next entry.
401 * Full validation checks are slow, so we only check
402 * enough to insure forward progress through the
403 * directory. Complete checks can be run by patching
404 * "dirchk" to be true.
405 */
406 KASSERT(bp != NULL);
407 ep = (struct ext2fs_direct *)
408 ((char *)bp->b_data + entryoffsetinblock);
409 if (ep->e2d_reclen == 0 ||
410 (dirchk &&
411 ext2fs_dirbadentry(vdp, ep, entryoffsetinblock))) {
412 int i;
413
414 ufs_dirbad(dp, results->ulr_offset, "mangled entry");
415 i = dirblksiz - (entryoffsetinblock & (dirblksiz - 1));
416 results->ulr_offset += i;
417 entryoffsetinblock += i;
418 continue;
419 }
420
421 /*
422 * If an appropriate sized slot has not yet been found,
423 * check to see if one is available. Also accumulate space
424 * in the current block so that we can determine if
425 * compaction is viable.
426 */
427 if (slotstatus != FOUND) {
428 int size = fs2h16(ep->e2d_reclen);
429
430 if (ep->e2d_ino != 0)
431 size -= EXT2FS_DIRSIZ(ep->e2d_namlen);
432 if (size > 0) {
433 if (size >= slotneeded) {
434 slotstatus = FOUND;
435 slotoffset = results->ulr_offset;
436 slotsize = fs2h16(ep->e2d_reclen);
437 } else if (slotstatus == NONE) {
438 slotfreespace += size;
439 if (slotoffset == -1)
440 slotoffset = results->ulr_offset;
441 if (slotfreespace >= slotneeded) {
442 slotstatus = COMPACT;
443 slotsize = results->ulr_offset +
444 fs2h16(ep->e2d_reclen) -
445 slotoffset;
446 }
447 }
448 }
449 }
450
451 /*
452 * Check for a name match.
453 */
454 if (ep->e2d_ino) {
455 namlen = ep->e2d_namlen;
456 if (namlen == cnp->cn_namelen &&
457 !memcmp(cnp->cn_nameptr, ep->e2d_name,
458 (unsigned)namlen)) {
459 /*
460 * Save directory entry's inode number and
461 * reclen in ndp->ni_ufs area, and release
462 * directory buffer.
463 */
464 foundino = fs2h32(ep->e2d_ino);
465 results->ulr_reclen = fs2h16(ep->e2d_reclen);
466 goto found;
467 }
468 }
469 prevoff = results->ulr_offset;
470 results->ulr_offset += fs2h16(ep->e2d_reclen);
471 entryoffsetinblock += fs2h16(ep->e2d_reclen);
472 if (ep->e2d_ino)
473 enduseful = results->ulr_offset;
474 }
475 /* notfound: */
476 /*
477 * If we started in the middle of the directory and failed
478 * to find our target, we must check the beginning as well.
479 */
480 if (numdirpasses == 2) {
481 numdirpasses--;
482 results->ulr_offset = 0;
483 endsearch = results->ulr_diroff;
484 goto searchloop;
485 }
486 if (bp != NULL)
487 brelse(bp, 0);
488 /*
489 * If creating, and at end of pathname and current
490 * directory has not been removed, then can consider
491 * allowing file to be created.
492 */
493 if ((nameiop == CREATE || nameiop == RENAME) &&
494 (flags & ISLASTCN) && dp->i_e2fs_nlink != 0) {
495 /*
496 * Access for write is interpreted as allowing
497 * creation of files in the directory.
498 */
499 error = VOP_ACCESS(vdp, VWRITE, cred);
500 if (error)
501 return (error);
502 /*
503 * Return an indication of where the new directory
504 * entry should be put. If we didn't find a slot,
505 * then set results->ulr_count to 0 indicating
506 * that the new slot belongs at the end of the
507 * directory. If we found a slot, then the new entry
508 * can be put in the range from results->ulr_offset to
509 * results->ulr_offset + results->ulr_count.
510 */
511 if (slotstatus == NONE) {
512 results->ulr_offset = roundup(ext2fs_size(dp), dirblksiz);
513 results->ulr_count = 0;
514 enduseful = results->ulr_offset;
515 } else {
516 results->ulr_offset = slotoffset;
517 results->ulr_count = slotsize;
518 if (enduseful < slotoffset + slotsize)
519 enduseful = slotoffset + slotsize;
520 }
521 results->ulr_endoff = roundup(enduseful, dirblksiz);
522 #if 0
523 dp->i_flag |= IN_CHANGE | IN_UPDATE;
524 #endif
525 /*
526 * We return with the directory locked, so that
527 * the parameters we set up above will still be
528 * valid if we actually decide to do a direnter().
529 * We return ni_vp == NULL to indicate that the entry
530 * does not currently exist; we leave a pointer to
531 * the (locked) directory inode in ndp->ni_dvp.
532 *
533 * NB - if the directory is unlocked, then this
534 * information cannot be used.
535 */
536 return (EJUSTRETURN);
537 }
538 /*
539 * Insert name into cache (as non-existent) if appropriate.
540 */
541 if ((cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
542 cache_enter(vdp, *vpp, cnp);
543 return (ENOENT);
544
545 found:
546 if (numdirpasses == 2)
547 nchstats.ncs_pass2++;
548 /*
549 * Check that directory length properly reflects presence
550 * of this entry.
551 */
552 if (results->ulr_offset + EXT2FS_DIRSIZ(ep->e2d_namlen) > ext2fs_size(dp)) {
553 ufs_dirbad(dp, results->ulr_offset, "i_size too small");
554 error = ext2fs_setsize(dp,
555 results->ulr_offset + EXT2FS_DIRSIZ(ep->e2d_namlen));
556 if (error) {
557 brelse(bp, 0);
558 return (error);
559 }
560 dp->i_flag |= IN_CHANGE | IN_UPDATE;
561 uvm_vnp_setsize(vdp, ext2fs_size(dp));
562 }
563 brelse(bp, 0);
564
565 /*
566 * Found component in pathname.
567 * If the final component of path name, save information
568 * in the cache as to where the entry was found.
569 */
570 if ((flags & ISLASTCN) && nameiop == LOOKUP)
571 results->ulr_diroff = results->ulr_offset &~ (dirblksiz - 1);
572
573 /*
574 * If deleting, and at end of pathname, return
575 * parameters which can be used to remove file.
576 * Lock the inode, being careful with ".".
577 */
578 if (nameiop == DELETE && (flags & ISLASTCN)) {
579 /*
580 * Return pointer to current entry in results->ulr_offset,
581 * and distance past previous entry (if there
582 * is a previous entry in this block) in results->ulr_count.
583 * Save directory inode pointer in ndp->ni_dvp for dirremove().
584 */
585 if ((results->ulr_offset & (dirblksiz - 1)) == 0)
586 results->ulr_count = 0;
587 else
588 results->ulr_count = results->ulr_offset - prevoff;
589 if (flags & ISDOTDOT)
590 VOP_UNLOCK(vdp); /* race to get the inode */
591 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
592 if (flags & ISDOTDOT)
593 vn_lock(vdp, LK_EXCLUSIVE | LK_RETRY);
594 if (error)
595 return (error);
596 /*
597 * Write access to directory required to delete files.
598 */
599 if ((error = VOP_ACCESS(vdp, VWRITE, cred)) != 0) {
600 vput(tdp);
601 return (error);
602 }
603 /*
604 * If directory is "sticky", then user must own
605 * the directory, or the file in it, else she
606 * may not delete it (unless she's root). This
607 * implements append-only directories.
608 */
609 if (dp->i_e2fs_mode & ISVTX) {
610 error = kauth_authorize_vnode(cred, KAUTH_VNODE_DELETE,
611 tdp, vdp, genfs_can_sticky(cred, dp->i_uid,
612 VTOI(tdp)->i_uid));
613 if (error) {
614 vput(tdp);
615 return (EPERM);
616 }
617 }
618 if (dp->i_number == foundino) {
619 vref(vdp);
620 *vpp = vdp;
621 return (0);
622 }
623 *vpp = tdp;
624 return (0);
625 }
626
627 /*
628 * If rewriting (RENAME), return the inode and the
629 * information required to rewrite the present directory
630 * Must get inode of directory entry to verify it's a
631 * regular file, or empty directory.
632 */
633 if (nameiop == RENAME && (flags & ISLASTCN)) {
634 error = VOP_ACCESS(vdp, VWRITE, cred);
635 if (error)
636 return (error);
637 /*
638 * Careful about locking second inode.
639 * This can only occur if the target is ".".
640 */
641 if (dp->i_number == foundino)
642 return (EISDIR);
643 if (flags & ISDOTDOT)
644 VOP_UNLOCK(vdp); /* race to get the inode */
645 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
646 if (flags & ISDOTDOT)
647 vn_lock(vdp, LK_EXCLUSIVE | LK_RETRY);
648 if (error)
649 return (error);
650 *vpp = tdp;
651 return (0);
652 }
653
654 /*
655 * Step through the translation in the name. We do not `vput' the
656 * directory because we may need it again if a symbolic link
657 * is relative to the current directory. Instead we save it
658 * unlocked as "pdp". We must get the target inode before unlocking
659 * the directory to insure that the inode will not be removed
660 * before we get it. We prevent deadlock by always fetching
661 * inodes from the root, moving down the directory tree. Thus
662 * when following backward pointers ".." we must unlock the
663 * parent directory before getting the requested directory.
664 * There is a potential race condition here if both the current
665 * and parent directories are removed before the VFS_VGET for the
666 * inode associated with ".." returns. We hope that this occurs
667 * infrequently since we cannot avoid this race condition without
668 * implementing a sophisticated deadlock detection algorithm.
669 * Note also that this simple deadlock detection scheme will not
670 * work if the file system has any hard links other than ".."
671 * that point backwards in the directory structure.
672 */
673 pdp = vdp;
674 if (flags & ISDOTDOT) {
675 VOP_UNLOCK(pdp); /* race to get the inode */
676 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
677 vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY);
678 if (error) {
679 return (error);
680 }
681 *vpp = tdp;
682 } else if (dp->i_number == foundino) {
683 vref(vdp); /* we want ourself, ie "." */
684 *vpp = vdp;
685 } else {
686 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
687 if (error)
688 return (error);
689 *vpp = tdp;
690 }
691
692 /*
693 * Insert name into cache if appropriate.
694 */
695 if (cnp->cn_flags & MAKEENTRY)
696 cache_enter(vdp, *vpp, cnp);
697 return (0);
698 }
699
700 /*
701 * Do consistency checking on a directory entry:
702 * record length must be multiple of 4
703 * entry must fit in rest of its dirblksize block
704 * record must be large enough to contain entry
705 * name is not longer than EXT2FS_MAXNAMLEN
706 * name must be as long as advertised, and null terminated
707 */
708 /*
709 * changed so that it confirms to ext2fs_check_dir_entry
710 */
711 static int
712 ext2fs_dirbadentry(struct vnode *dp, struct ext2fs_direct *de,
713 int entryoffsetinblock)
714 {
715 struct ufsmount *ump = VFSTOUFS(dp->v_mount);
716 int dirblksiz = ump->um_dirblksiz;
717
718 const char *error_msg = NULL;
719 int reclen = fs2h16(de->e2d_reclen);
720 int namlen = de->e2d_namlen;
721
722 if (reclen < EXT2FS_DIRSIZ(1)) /* e2d_namlen = 1 */
723 error_msg = "rec_len is smaller than minimal";
724 else if (reclen % 4 != 0)
725 error_msg = "rec_len % 4 != 0";
726 else if (namlen > EXT2FS_MAXNAMLEN)
727 error_msg = "namlen > EXT2FS_MAXNAMLEN";
728 else if (reclen < EXT2FS_DIRSIZ(namlen))
729 error_msg = "reclen is too small for name_len";
730 else if (entryoffsetinblock + reclen > dirblksiz)
731 error_msg = "directory entry across blocks";
732 else if (fs2h32(de->e2d_ino) >
733 VTOI(dp)->i_e2fs->e2fs.e2fs_icount)
734 error_msg = "inode out of bounds";
735
736 if (error_msg != NULL) {
737 printf( "bad directory entry: %s\n"
738 "offset=%d, inode=%lu, rec_len=%d, name_len=%d \n",
739 error_msg, entryoffsetinblock,
740 (unsigned long) fs2h32(de->e2d_ino),
741 reclen, namlen);
742 panic("ext2fs_dirbadentry");
743 }
744 return error_msg == NULL ? 0 : 1;
745 }
746
747 /*
748 * Write a directory entry after a call to namei, using the parameters
749 * that it left in nameidata. The argument ip is the inode which the new
750 * directory entry will refer to. Dvp is a pointer to the directory to
751 * be written, which was left locked by namei. Remaining parameters
752 * (ulr_offset, ulr_count) indicate how the space for the new
753 * entry is to be obtained.
754 */
755 int
756 ext2fs_direnter(struct inode *ip, struct vnode *dvp,
757 const struct ufs_lookup_results *ulr,
758 struct componentname *cnp)
759 {
760 struct ext2fs_direct *ep, *nep;
761 struct inode *dp;
762 struct buf *bp;
763 struct ext2fs_direct newdir;
764 struct iovec aiov;
765 struct uio auio;
766 u_int dsize;
767 int error, loc, newentrysize, spacefree;
768 char *dirbuf;
769 struct ufsmount *ump = VFSTOUFS(dvp->v_mount);
770 int dirblksiz = ump->um_dirblksiz;
771
772 dp = VTOI(dvp);
773
774 newdir.e2d_ino = h2fs32(ip->i_number);
775 newdir.e2d_namlen = cnp->cn_namelen;
776 if (ip->i_e2fs->e2fs.e2fs_rev > E2FS_REV0 &&
777 (ip->i_e2fs->e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) {
778 newdir.e2d_type = inot2ext2dt(IFTODT(ip->i_e2fs_mode));
779 } else {
780 newdir.e2d_type = 0;
781 }
782 memcpy(newdir.e2d_name, cnp->cn_nameptr, (unsigned)cnp->cn_namelen + 1);
783 newentrysize = EXT2FS_DIRSIZ(cnp->cn_namelen);
784 if (ulr->ulr_count == 0) {
785 /*
786 * If ulr_count is 0, then namei could find no
787 * space in the directory. Here, ulr_offset will
788 * be on a directory block boundary and we will write the
789 * new entry into a fresh block.
790 */
791 if (ulr->ulr_offset & (dirblksiz - 1))
792 panic("ext2fs_direnter: newblk");
793 auio.uio_offset = ulr->ulr_offset;
794 newdir.e2d_reclen = h2fs16(dirblksiz);
795 auio.uio_resid = newentrysize;
796 aiov.iov_len = newentrysize;
797 aiov.iov_base = (void *)&newdir;
798 auio.uio_iov = &aiov;
799 auio.uio_iovcnt = 1;
800 auio.uio_rw = UIO_WRITE;
801 UIO_SETUP_SYSSPACE(&auio);
802 error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
803 if (dirblksiz > dvp->v_mount->mnt_stat.f_bsize)
804 /* XXX should grow with balloc() */
805 panic("ext2fs_direnter: frag size");
806 else if (!error) {
807 error = ext2fs_setsize(dp,
808 roundup(ext2fs_size(dp), dirblksiz));
809 if (error)
810 return (error);
811 dp->i_flag |= IN_CHANGE;
812 uvm_vnp_setsize(dvp, ext2fs_size(dp));
813 }
814 return (error);
815 }
816
817 /*
818 * If ulr_count is non-zero, then namei found space
819 * for the new entry in the range ulr_offset to
820 * ulr_offset + ulr_count in the directory.
821 * To use this space, we may have to compact the entries located
822 * there, by copying them together towards the beginning of the
823 * block, leaving the free space in one usable chunk at the end.
824 */
825
826 /*
827 * Get the block containing the space for the new directory entry.
828 */
829 if ((error = ext2fs_blkatoff(dvp, (off_t)ulr->ulr_offset, &dirbuf, &bp)) != 0)
830 return (error);
831 /*
832 * Find space for the new entry. In the simple case, the entry at
833 * offset base will have the space. If it does not, then namei
834 * arranged that compacting the region ulr_offset to
835 * ulr_offset + ulr_count would yield the
836 * space.
837 */
838 ep = (struct ext2fs_direct *)dirbuf;
839 dsize = EXT2FS_DIRSIZ(ep->e2d_namlen);
840 spacefree = fs2h16(ep->e2d_reclen) - dsize;
841 for (loc = fs2h16(ep->e2d_reclen); loc < ulr->ulr_count; ) {
842 nep = (struct ext2fs_direct *)(dirbuf + loc);
843 if (ep->e2d_ino) {
844 /* trim the existing slot */
845 ep->e2d_reclen = h2fs16(dsize);
846 ep = (struct ext2fs_direct *)((char *)ep + dsize);
847 } else {
848 /* overwrite; nothing there; header is ours */
849 spacefree += dsize;
850 }
851 dsize = EXT2FS_DIRSIZ(nep->e2d_namlen);
852 spacefree += fs2h16(nep->e2d_reclen) - dsize;
853 loc += fs2h16(nep->e2d_reclen);
854 memcpy((void *)ep, (void *)nep, dsize);
855 }
856 /*
857 * Update the pointer fields in the previous entry (if any),
858 * copy in the new entry, and write out the block.
859 */
860 if (ep->e2d_ino == 0) {
861 #ifdef DIAGNOSTIC
862 if (spacefree + dsize < newentrysize)
863 panic("ext2fs_direnter: compact1");
864 #endif
865 newdir.e2d_reclen = h2fs16(spacefree + dsize);
866 } else {
867 #ifdef DIAGNOSTIC
868 if (spacefree < newentrysize) {
869 printf("ext2fs_direnter: compact2 %u %u",
870 (u_int)spacefree, (u_int)newentrysize);
871 panic("ext2fs_direnter: compact2");
872 }
873 #endif
874 newdir.e2d_reclen = h2fs16(spacefree);
875 ep->e2d_reclen = h2fs16(dsize);
876 ep = (struct ext2fs_direct *)((char *)ep + dsize);
877 }
878 memcpy((void *)ep, (void *)&newdir, (u_int)newentrysize);
879 error = VOP_BWRITE(bp->b_vp, bp);
880 dp->i_flag |= IN_CHANGE | IN_UPDATE;
881 if (!error && ulr->ulr_endoff && ulr->ulr_endoff < ext2fs_size(dp))
882 error = ext2fs_truncate(dvp, (off_t)ulr->ulr_endoff, IO_SYNC,
883 cnp->cn_cred);
884 return (error);
885 }
886
887 /*
888 * Remove a directory entry after a call to namei, using
889 * the auxiliary results it provided. The entry
890 * ulr_offset contains the offset into the directory of the
891 * entry to be eliminated. The ulr_count field contains the
892 * size of the previous record in the directory. If this
893 * is 0, the first entry is being deleted, so we need only
894 * zero the inode number to mark the entry as free. If the
895 * entry is not the first in the directory, we must reclaim
896 * the space of the now empty record by adding the record size
897 * to the size of the previous entry.
898 */
899 int
900 ext2fs_dirremove(struct vnode *dvp, const struct ufs_lookup_results *ulr,
901 struct componentname *cnp)
902 {
903 struct inode *dp;
904 struct ext2fs_direct *ep;
905 struct buf *bp;
906 int error;
907
908 dp = VTOI(dvp);
909
910 if (ulr->ulr_count == 0) {
911 /*
912 * First entry in block: set d_ino to zero.
913 */
914 error = ext2fs_blkatoff(dvp, (off_t)ulr->ulr_offset,
915 (void *)&ep, &bp);
916 if (error != 0)
917 return (error);
918 ep->e2d_ino = 0;
919 error = VOP_BWRITE(bp->b_vp, bp);
920 dp->i_flag |= IN_CHANGE | IN_UPDATE;
921 return (error);
922 }
923 /*
924 * Collapse new free space into previous entry.
925 */
926 error = ext2fs_blkatoff(dvp, (off_t)(ulr->ulr_offset - ulr->ulr_count),
927 (void *)&ep, &bp);
928 if (error != 0)
929 return (error);
930 ep->e2d_reclen = h2fs16(fs2h16(ep->e2d_reclen) + ulr->ulr_reclen);
931 error = VOP_BWRITE(bp->b_vp, bp);
932 dp->i_flag |= IN_CHANGE | IN_UPDATE;
933 return (error);
934 }
935
936 /*
937 * Rewrite an existing directory entry to point at the inode
938 * supplied. The parameters describing the directory entry are
939 * set up by a call to namei.
940 */
941 int
942 ext2fs_dirrewrite(struct inode *dp, const struct ufs_lookup_results *ulr,
943 struct inode *ip, struct componentname *cnp)
944 {
945 struct buf *bp;
946 struct ext2fs_direct *ep;
947 struct vnode *vdp = ITOV(dp);
948 int error;
949
950 error = ext2fs_blkatoff(vdp, (off_t)ulr->ulr_offset, (void *)&ep, &bp);
951 if (error != 0)
952 return (error);
953 ep->e2d_ino = h2fs32(ip->i_number);
954 if (ip->i_e2fs->e2fs.e2fs_rev > E2FS_REV0 &&
955 (ip->i_e2fs->e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) {
956 ep->e2d_type = inot2ext2dt(IFTODT(ip->i_e2fs_mode));
957 } else {
958 ep->e2d_type = 0;
959 }
960 error = VOP_BWRITE(bp->b_vp, bp);
961 dp->i_flag |= IN_CHANGE | IN_UPDATE;
962 return (error);
963 }
964
965 /*
966 * Check if a directory is empty or not.
967 * Inode supplied must be locked.
968 *
969 * Using a struct dirtemplate here is not precisely
970 * what we want, but better than using a struct ext2fs_direct.
971 *
972 * NB: does not handle corrupted directories.
973 */
974 int
975 ext2fs_dirempty(struct inode *ip, ino_t parentino, kauth_cred_t cred)
976 {
977 off_t off;
978 struct ext2fs_dirtemplate dbuf;
979 struct ext2fs_direct *dp = (struct ext2fs_direct *)&dbuf;
980 int error, namlen;
981 size_t count;
982
983 #define MINDIRSIZ (sizeof (struct ext2fs_dirtemplate) / 2)
984
985 for (off = 0; off < ext2fs_size(ip); off += fs2h16(dp->e2d_reclen)) {
986 error = vn_rdwr(UIO_READ, ITOV(ip), (void *)dp, MINDIRSIZ, off,
987 UIO_SYSSPACE, IO_NODELOCKED, cred, &count, NULL);
988 /*
989 * Since we read MINDIRSIZ, residual must
990 * be 0 unless we're at end of file.
991 */
992 if (error || count != 0)
993 return (0);
994 /* avoid infinite loops */
995 if (dp->e2d_reclen == 0)
996 return (0);
997 /* skip empty entries */
998 if (dp->e2d_ino == 0)
999 continue;
1000 /* accept only "." and ".." */
1001 namlen = dp->e2d_namlen;
1002 if (namlen > 2)
1003 return (0);
1004 if (dp->e2d_name[0] != '.')
1005 return (0);
1006 /*
1007 * At this point namlen must be 1 or 2.
1008 * 1 implies ".", 2 implies ".." if second
1009 * char is also "."
1010 */
1011 if (namlen == 1)
1012 continue;
1013 if (dp->e2d_name[1] == '.' && fs2h32(dp->e2d_ino) == parentino)
1014 continue;
1015 return (0);
1016 }
1017 return (1);
1018 }
1019
1020 /*
1021 * Check if source directory is in the path of the target directory.
1022 * Target is supplied locked, source is unlocked.
1023 * The target is always vput before returning.
1024 */
1025 int
1026 ext2fs_checkpath(struct inode *source, struct inode *target,
1027 kauth_cred_t cred)
1028 {
1029 struct vnode *vp;
1030 int error, rootino, namlen;
1031 struct ext2fs_dirtemplate dirbuf;
1032 uint32_t ino;
1033
1034 vp = ITOV(target);
1035 if (target->i_number == source->i_number) {
1036 error = EEXIST;
1037 goto out;
1038 }
1039 rootino = ROOTINO;
1040 error = 0;
1041 if (target->i_number == rootino)
1042 goto out;
1043
1044 for (;;) {
1045 if (vp->v_type != VDIR) {
1046 error = ENOTDIR;
1047 break;
1048 }
1049 error = vn_rdwr(UIO_READ, vp, (void *)&dirbuf,
1050 sizeof (struct ext2fs_dirtemplate), (off_t)0,
1051 UIO_SYSSPACE, IO_NODELOCKED, cred, (size_t *)0,
1052 NULL);
1053 if (error != 0)
1054 break;
1055 namlen = dirbuf.dotdot_namlen;
1056 if (namlen != 2 ||
1057 dirbuf.dotdot_name[0] != '.' ||
1058 dirbuf.dotdot_name[1] != '.') {
1059 error = ENOTDIR;
1060 break;
1061 }
1062 ino = fs2h32(dirbuf.dotdot_ino);
1063 if (ino == source->i_number) {
1064 error = EINVAL;
1065 break;
1066 }
1067 if (ino == rootino)
1068 break;
1069 vput(vp);
1070 error = VFS_VGET(vp->v_mount, ino, &vp);
1071 if (error != 0) {
1072 vp = NULL;
1073 break;
1074 }
1075 }
1076
1077 out:
1078 if (error == ENOTDIR) {
1079 printf("checkpath: .. not a directory\n");
1080 panic("checkpath");
1081 }
1082 if (vp != NULL)
1083 vput(vp);
1084 return (error);
1085 }
1086