Merge from vendor branch OPENSSL:
[dragonfly.git] / sys / vfs / isofs / cd9660 / cd9660_lookup.c
1 /*-
2  * Copyright (c) 1989, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley
6  * by Pace Willisson (pace@blitz.com).  The Rock Ridge Extension
7  * Support code is derived from software contributed to Berkeley
8  * by Atsushi Murai (amurai@spec.co.jp).
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)ufs_lookup.c  7.33 (Berkeley) 5/19/91
39  *
40  *      @(#)cd9660_lookup.c     8.2 (Berkeley) 1/23/94
41  * $FreeBSD: src/sys/isofs/cd9660/cd9660_lookup.c,v 1.23.2.2 2001/11/04 06:19:47 dillon Exp $
42  * $DragonFly: src/sys/vfs/isofs/cd9660/cd9660_lookup.c,v 1.12 2004/04/24 04:32:04 drhodus Exp $
43  */
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/proc.h>
48 #include <sys/namei.h>
49 #include <sys/buf.h>
50 #include <sys/vnode.h>
51 #include <sys/mount.h>
52
53 #include "iso.h"
54 #include "cd9660_node.h"
55 #include "iso_rrip.h"
56
57 /*
58  * Convert a component of a pathname into a pointer to a locked inode.
59  * This is a very central and rather complicated routine.
60  * If the file system is not maintained in a strict tree hierarchy,
61  * this can result in a deadlock situation (see comments in code below).
62  *
63  * The flag argument is LOOKUP, CREATE, RENAME, or DELETE depending on
64  * whether the name is to be looked up, created, renamed, or deleted.
65  * When CREATE, RENAME, or DELETE is specified, information usable in
66  * creating, renaming, or deleting a directory entry may be calculated.
67  * If flag has LOCKPARENT or'ed into it and the target of the pathname
68  * exists, lookup returns both the target and its parent directory locked.
69  * When creating or renaming and LOCKPARENT is specified, the target may
70  * not be ".".  When deleting and LOCKPARENT is specified, the target may
71  * be "."., but the caller must check to ensure it does an vrele and iput
72  * instead of two iputs.
73  *
74  * Overall outline of ufs_lookup:
75  *
76  *      search for name in directory, to found or notfound
77  * notfound:
78  *      if creating, return locked directory, leaving info on available slots
79  *      else return error
80  * found:
81  *      if at end of path and deleting, return information to allow delete
82  *      if at end of path and rewriting (RENAME and LOCKPARENT), lock target
83  *        inode and return info to allow rewrite
84  *      if not at end, add name to cache; if at end and neither creating
85  *        nor deleting, add name to cache
86  *
87  * NOTE: (LOOKUP | LOCKPARENT) currently returns the parent inode unlocked.
88  *
89  * cd9660_lookup(struct vnode *a_dvp, struct vnode **a_vpp,
90  *               struct componentname *a_cnp)
91  */
92 int
93 cd9660_lookup(struct vop_cachedlookup_args *ap)
94 {
95         struct vnode *vdp;      /* vnode for directory being searched */
96         globaldata_t gd = mycpu;
97         struct iso_node *dp;    /* inode for directory being searched */
98         struct iso_mnt *imp;    /* file system that directory is in */
99         struct buf *bp;                 /* a buffer of directory entries */
100         struct iso_directory_record *ep = 0;/* the current directory entry */
101         int entryoffsetinblock;         /* offset of ep in bp's buffer */
102         int saveoffset = 0;             /* offset of last directory entry in dir */
103         int numdirpasses;               /* strategy for directory search */
104         doff_t endsearch;               /* offset to end directory search */
105         struct vnode *pdp;              /* saved dp during symlink work */
106         struct vnode *tdp;              /* returned by cd9660_vget_internal */
107         u_long bmask;                   /* block offset mask */
108         int lockparent;                 /* 1 => lockparent flag is set */
109         int wantparent;                 /* 1 => wantparent or lockparent flag */
110         int error;
111         ino_t ino = 0;
112         int reclen;
113         u_short namelen;
114         int isoflags;
115         char altname[NAME_MAX];
116         int res;
117         int assoc, len;
118         char *name;
119         struct vnode **vpp = ap->a_vpp;
120         struct componentname *cnp = ap->a_cnp;
121         int flags = cnp->cn_flags;
122         int nameiop = cnp->cn_nameiop;
123         struct thread *td = cnp->cn_td;
124
125         bp = NULL;
126         *vpp = NULL;
127         vdp = ap->a_dvp;
128         dp = VTOI(vdp);
129         imp = dp->i_mnt;
130         lockparent = flags & CNP_LOCKPARENT;
131         wantparent = flags & (CNP_LOCKPARENT | CNP_WANTPARENT);
132         cnp->cn_flags &= ~CNP_PDIRUNLOCK;
133
134         /*
135          * We now have a segment name to search for, and a directory to search.
136          */
137
138         len = cnp->cn_namelen;
139         name = cnp->cn_nameptr;
140         /*
141          * A leading `=' means, we are looking for an associated file
142          */
143         if ((assoc = (imp->iso_ftype != ISO_FTYPE_RRIP && *name == ASSOCCHAR)))
144         {
145                 len--;
146                 name++;
147         }
148
149         /*
150          * If there is cached information on a previous search of
151          * this directory, pick up where we last left off.
152          * We cache only lookups as these are the most common
153          * and have the greatest payoff. Caching CREATE has little
154          * benefit as it usually must search the entire directory
155          * to determine that the entry does not exist. Caching the
156          * location of the last DELETE or RENAME has not reduced
157          * profiling time and hence has been removed in the interest
158          * of simplicity.
159          */
160         bmask = imp->im_bmask;
161         if (nameiop != NAMEI_LOOKUP || dp->i_diroff == 0 ||
162             dp->i_diroff > dp->i_size) {
163                 entryoffsetinblock = 0;
164                 dp->i_offset = 0;
165                 numdirpasses = 1;
166         } else {
167                 dp->i_offset = dp->i_diroff;
168                 if ((entryoffsetinblock = dp->i_offset & bmask) &&
169                     (error = cd9660_blkatoff(vdp, (off_t)dp->i_offset, NULL, &bp)))
170                                 return (error);
171                 numdirpasses = 2;
172                 gd->gd_nchstats->ncs_2passes++;
173         }
174         endsearch = dp->i_size;
175         
176 searchloop:
177         while (dp->i_offset < endsearch) {
178                 /*
179                  * If offset is on a block boundary,
180                  * read the next directory block.
181                  * Release previous if it exists.
182                  */
183                 if ((dp->i_offset & bmask) == 0) {
184                         if (bp != NULL)
185                                 brelse(bp);
186                         if ((error =
187                             cd9660_blkatoff(vdp, (off_t)dp->i_offset, NULL, &bp)) != 0)
188                                 return (error);
189                         entryoffsetinblock = 0;
190                 }
191                 /*
192                  * Get pointer to next entry.
193                  */
194                 ep = (struct iso_directory_record *)
195                         ((char *)bp->b_data + entryoffsetinblock);
196                 
197                 reclen = isonum_711(ep->length);
198                 if (reclen == 0) {
199                         /* skip to next block, if any */
200                         dp->i_offset =
201                             (dp->i_offset & ~bmask) + imp->logical_block_size;
202                         continue;
203                 }
204
205                 if (reclen < ISO_DIRECTORY_RECORD_SIZE)
206                         /* illegal entry, stop */
207                         break;
208
209                 if (entryoffsetinblock + reclen > imp->logical_block_size)
210                         /* entries are not allowed to cross boundaries */
211                         break;
212                 
213                 namelen = isonum_711(ep->name_len);
214                 isoflags = isonum_711(imp->iso_ftype == ISO_FTYPE_HIGH_SIERRA?
215                                       &ep->date[6]: ep->flags);
216
217                 if (reclen < ISO_DIRECTORY_RECORD_SIZE + namelen)
218                         /* illegal entry, stop */
219                         break;
220                 
221                 /*
222                  * Check for a name match.
223                  */
224                 switch (imp->iso_ftype) {
225                 default:
226                         if (!(isoflags & 4) == !assoc) {
227                                 if ((len == 1
228                                      && *name == '.')
229                                     || (flags & CNP_ISDOTDOT)) {
230                                         if (namelen == 1
231                                             && ep->name[0] == ((flags & CNP_ISDOTDOT) ? 1 : 0)) {
232                                                 /*
233                                                  * Save directory entry's inode number and
234                                                  * release directory buffer.
235                                                  */
236                                                 dp->i_ino = isodirino(ep, imp);
237                                                 goto found;
238                                         }
239                                         if (namelen != 1
240                                             || ep->name[0] != 0)
241                                                 goto notfound;
242                                 } else if (!(res = isofncmp(name, len, ep->name, namelen, imp->joliet_level))) {
243                                         if (isoflags & 2)
244                                                 ino = isodirino(ep, imp);
245                                         else
246                                                 ino = dbtob(bp->b_blkno)
247                                                         + entryoffsetinblock;
248                                         saveoffset = dp->i_offset;
249                                 } else if (ino)
250                                         goto foundino;
251 #ifdef  NOSORTBUG       /* On some CDs directory entries are not sorted correctly */
252                                 else if (res < 0)
253                                         goto notfound;
254                                 else if (res > 0 && numdirpasses == 2)
255                                         numdirpasses++;
256 #endif
257                         }
258                         break;
259                 case ISO_FTYPE_RRIP:
260                         if (isonum_711(ep->flags)&2)
261                                 ino = isodirino(ep, imp);
262                         else
263                                 ino = dbtob(bp->b_blkno) + entryoffsetinblock;
264                         dp->i_ino = ino;
265                         cd9660_rrip_getname(ep,altname,&namelen,&dp->i_ino,imp);
266                         if (namelen == cnp->cn_namelen
267                             && !bcmp(name,altname,namelen))
268                                 goto found;
269                         ino = 0;
270                         break;
271                 }
272                 dp->i_offset += reclen;
273                 entryoffsetinblock += reclen;
274         }
275         if (ino) {
276 foundino:
277                 dp->i_ino = ino;
278                 if (saveoffset != dp->i_offset) {
279                         if (lblkno(imp, dp->i_offset) !=
280                             lblkno(imp, saveoffset)) {
281                                 if (bp != NULL)
282                                         brelse(bp);
283                                 if ((error = cd9660_blkatoff(vdp,
284                                     (off_t)saveoffset, NULL, &bp)) != 0)
285                                         return (error);
286                         }
287                         entryoffsetinblock = saveoffset & bmask;
288                         ep = (struct iso_directory_record *)
289                                 ((char *)bp->b_data + entryoffsetinblock);
290                         dp->i_offset = saveoffset;
291                 }
292                 goto found;
293         }
294 notfound:
295         /*
296          * If we started in the middle of the directory and failed
297          * to find our target, we must check the beginning as well.
298          */
299         if (numdirpasses == 2) {
300                 numdirpasses--;
301                 dp->i_offset = 0;
302                 endsearch = dp->i_diroff;
303                 goto searchloop;
304         }
305         if (bp != NULL)
306                 brelse(bp);
307
308         /*
309          * Insert name into cache (as non-existent) if appropriate.
310          */
311         if (cnp->cn_flags & CNP_MAKEENTRY)
312                 cache_enter(vdp, NCPNULL, *vpp, cnp);
313         if (nameiop == NAMEI_CREATE || nameiop == NAMEI_RENAME)
314                 return (EROFS);
315         return (ENOENT);
316
317 found:
318         if (numdirpasses == 2)
319                 gd->gd_nchstats->ncs_pass2++;
320         
321         /*
322          * Found component in pathname.
323          * If the final component of path name, save information
324          * in the cache as to where the entry was found.
325          */
326         if ((flags & CNP_ISLASTCN) && nameiop == NAMEI_LOOKUP)
327                 dp->i_diroff = dp->i_offset;
328
329         /*
330          * Step through the translation in the name.  We do not `iput' the
331          * directory because we may need it again if a symbolic link
332          * is relative to the current directory.  Instead we save it
333          * unlocked as "pdp".  We must get the target inode before unlocking
334          * the directory to insure that the inode will not be removed
335          * before we get it.  We prevent deadlock by always fetching
336          * inodes from the root, moving down the directory tree. Thus
337          * when following backward pointers ".." we must unlock the
338          * parent directory before getting the requested directory.
339          * There is a potential race condition here if both the current
340          * and parent directories are removed before the `iget' for the
341          * inode associated with ".." returns.  We hope that this occurs
342          * infrequently since we cannot avoid this race condition without
343          * implementing a sophisticated deadlock detection algorithm.
344          * Note also that this simple deadlock detection scheme will not
345          * work if the file system has any hard links other than ".."
346          * that point backwards in the directory structure.
347          */
348         pdp = vdp;
349         /*
350          * If ino is different from dp->i_ino,
351          * it's a relocated directory.
352          */
353         if (flags & CNP_ISDOTDOT) {
354                 VOP_UNLOCK(pdp, NULL, 0, td);   /* race to get the inode */
355                 error = cd9660_vget_internal(vdp->v_mount, dp->i_ino, &tdp,
356                                              dp->i_ino != ino, ep);
357                 brelse(bp);
358                 if (error) {
359                         vn_lock(pdp, NULL, LK_EXCLUSIVE | LK_RETRY, td);
360                         return (error);
361                 }
362                 if (lockparent && (flags & CNP_ISLASTCN)) {
363                         if ((error = vn_lock(pdp, NULL, LK_EXCLUSIVE, td)) != 0) {
364                                 cnp->cn_flags |= CNP_PDIRUNLOCK;
365                                 vput(tdp);
366                                 return (error);
367                         }
368                 } else
369                         cnp->cn_flags |= CNP_PDIRUNLOCK;
370                 *vpp = tdp;
371         } else if (dp->i_number == dp->i_ino) {
372                 brelse(bp);
373                 vref(vdp);      /* we want ourself, ie "." */
374                 *vpp = vdp;
375         } else {
376                 error = cd9660_vget_internal(vdp->v_mount, dp->i_ino, &tdp,
377                                              dp->i_ino != ino, ep);
378                 brelse(bp);
379                 if (error)
380                         return (error);
381                 if (!lockparent || !(flags & CNP_ISLASTCN)) {
382                         cnp->cn_flags |= CNP_PDIRUNLOCK;
383                         VOP_UNLOCK(pdp, NULL, 0, td);
384                 }
385                 *vpp = tdp;
386         }
387
388         /*
389          * Insert name into cache if appropriate.
390          */
391         if (cnp->cn_flags & CNP_MAKEENTRY)
392                 cache_enter(vdp, NCPNULL, *vpp, cnp);
393         return (0);
394 }
395
396 /*
397  * Return buffer with the contents of block "offset" from the beginning of
398  * directory "ip".  If "res" is non-zero, fill it in with a pointer to the
399  * remaining space in the directory.
400  */
401 int
402 cd9660_blkatoff(struct vnode *vp, off_t offset, char **res, struct buf **bpp)
403 {
404         struct iso_node *ip;
405         struct iso_mnt *imp;
406         struct buf *bp;
407         daddr_t lbn;
408         int bsize, error;
409
410         ip = VTOI(vp);
411         imp = ip->i_mnt;
412         lbn = lblkno(imp, offset);
413         bsize = blksize(imp, ip, lbn);
414
415         if ((error = bread(vp, lbn, bsize, &bp)) != 0) {
416                 brelse(bp);
417                 *bpp = NULL;
418                 return (error);
419         }
420
421         /*
422          * We must BMAP the buffer because the directory code may use b_blkno
423          * to calculate the inode for certain types of directory entries.
424          * We could get away with not doing it before we VMIO-backed the
425          * directories because the buffers would get freed atomically with
426          * the invalidation of their data.  But with VMIO-backed buffers
427          * the buffers may be freed and then later reconstituted - and the
428          * reconstituted buffer will have no knowledge of b_blkno.
429          */
430         if (bp->b_blkno == bp->b_lblkno) {
431                 error = VOP_BMAP(vp, bp->b_lblkno, NULL, 
432                             &bp->b_blkno, NULL, NULL);
433                 if (error) {
434                         bp->b_error = error;
435                         bp->b_flags |= B_ERROR;
436                         brelse(bp);
437                         *bpp = NULL;
438                         return (error);
439                 }
440         }
441
442         if (res)
443                 *res = (char *)bp->b_data + blkoff(imp, offset);
444         *bpp = bp;
445         return (0);
446 }