1 /*        $NetBSD: find.c,v 1.30 2016/06/13 00:04:40 pgoyette Exp $   */
2 
3 /*-
4  * Copyright (c) 1991, 1993, 1994
5  *        The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Cimarron D. Taylor of the University of California, Berkeley.
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "from: @(#)find.c          8.5 (Berkeley) 8/5/94";
39 #else
40 __RCSID("$NetBSD: find.c,v 1.30 2016/06/13 00:04:40 pgoyette Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 
47 #include <err.h>
48 #include <errno.h>
49 #include <fts.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <stdlib.h>
54 #include <stdbool.h>
55 #include <unistd.h>
56 
57 #include "find.h"
58 
59 static int ftscompare(const FTSENT **, const FTSENT **);
60 
61 /*
62  * find_formplan --
63  *        process the command line and create a "plan" corresponding to the
64  *        command arguments.
65  */
66 PLAN *
find_formplan(char ** argv)67 find_formplan(char **argv)
68 {
69           PLAN *plan, *tail, *new;
70 
71           /*
72            * for each argument in the command line, determine what kind of node
73            * it is, create the appropriate node type and add the new plan node
74            * to the end of the existing plan.  The resulting plan is a linked
75            * list of plan nodes.  For example, the string:
76            *
77            *        % find . -name foo -newer bar -print
78            *
79            * results in the plan:
80            *
81            *        [-name foo]--> [-newer bar]--> [-print]
82            *
83            * in this diagram, `[-name foo]' represents the plan node generated
84            * by c_name() with an argument of foo and `-->' represents the
85            * plan->next pointer.
86            */
87           for (plan = tail = NULL; *argv;) {
88                     if (!(new = find_create(&argv)))
89                               continue;
90                     if (plan == NULL)
91                               tail = plan = new;
92                     else {
93                               tail->next = new;
94                               tail = new;
95                     }
96           }
97 
98           /*
99            * if the user didn't specify one of -print, -ok, -fprint, -exec, or
100            * -exit, then -print is assumed so we bracket the current expression
101            * with parens, if necessary, and add a -print node on the end.
102            */
103           if (!isoutput) {
104                     if (plan == NULL) {
105                               new = c_print(NULL, 0, NULL);
106                               tail = plan = new;
107                     } else {
108                               new = c_openparen(NULL, 0, NULL);
109                               new->next = plan;
110                               plan = new;
111                               new = c_closeparen(NULL, 0, NULL);
112                               tail->next = new;
113                               tail = new;
114                               new = c_print(NULL, 0, NULL);
115                               tail->next = new;
116                               tail = new;
117                     }
118           }
119 
120           /*
121            * the command line has been completely processed into a search plan
122            * except for the (, ), !, and -o operators.  Rearrange the plan so
123            * that the portions of the plan which are affected by the operators
124            * are moved into operator nodes themselves.  For example:
125            *
126            *        [!]--> [-name foo]--> [-print]
127            *
128            * becomes
129            *
130            *        [! [-name foo] ]--> [-print]
131            *
132            * and
133            *
134            *        [(]--> [-depth]--> [-name foo]--> [)]--> [-print]
135            *
136            * becomes
137            *
138            *        [expr [-depth]-->[-name foo] ]--> [-print]
139            *
140            * operators are handled in order of precedence.
141            */
142 
143           plan = paren_squish(plan);              /* ()'s */
144           plan = not_squish(plan);                /* !'s */
145           plan = or_squish(plan);                           /* -o's */
146           return (plan);
147 }
148 
149 static int
ftscompare(const FTSENT ** e1,const FTSENT ** e2)150 ftscompare(const FTSENT **e1, const FTSENT **e2)
151 {
152 
153           return (strcoll((*e1)->fts_name, (*e2)->fts_name));
154 }
155 
156 static sigset_t ss;
157 static bool notty;
158 
159 static __inline void
sig_init(void)160 sig_init(void)
161 {
162           struct sigaction sa;
163           notty = !(isatty(STDIN_FILENO) || isatty(STDOUT_FILENO) ||
164               isatty(STDERR_FILENO));
165           if (notty)
166                     return;
167           sigemptyset(&ss);
168           sigaddset(&ss, SIGINFO); /* block SIGINFO */
169 
170           memset(&sa, 0, sizeof(sa));
171           sa.sa_flags = SA_RESTART;
172           sa.sa_handler = show_path;
173           (void)sigaction(SIGINFO, &sa, NULL);
174 
175 }
176 
177 static __inline void
sig_lock(sigset_t * s)178 sig_lock(sigset_t *s)
179 {
180           if (notty)
181                     return;
182           sigprocmask(SIG_BLOCK, &ss, s);
183 }
184 
185 static __inline void
sig_unlock(const sigset_t * s)186 sig_unlock(const sigset_t *s)
187 {
188           if (notty)
189                     return;
190           sigprocmask(SIG_SETMASK, s, NULL);
191 }
192 
193 FTS *tree;                              /* pointer to top of FTS hierarchy */
194 FTSENT *g_entry;              /* shared with SIGINFO handler */
195 
196 /*
197  * find_execute --
198  *        take a search plan and an array of search paths and executes the plan
199  *        over all FTSENT's returned for the given search paths.
200  */
201 int
find_execute(PLAN * plan,char ** paths)202 find_execute(PLAN *plan, char **paths)
203 {
204           PLAN *p;
205           int r, rval, cval;
206           sigset_t s;
207 
208           cval = 1;
209 
210           if (!(tree = fts_open(paths, ftsoptions, issort ? ftscompare : NULL)))
211                     err(1, "ftsopen");
212 
213           sig_init();
214           sig_lock(&s);
215           for (rval = 0; cval && (g_entry = fts_read(tree)) != NULL;) {
216                     switch (g_entry->fts_info) {
217                     case FTS_D:
218                               if (isdepth)
219                                         continue;
220                               break;
221                     case FTS_DP:
222                               if (!isdepth)
223                                         continue;
224                               break;
225                     case FTS_DNR:
226                     case FTS_ERR:
227                     case FTS_NS:
228                               sig_unlock(&s);
229                               (void)fflush(stdout);
230                               warnx("%s: %s",
231                                   g_entry->fts_path, strerror(g_entry->fts_errno));
232                               rval = 1;
233                               sig_lock(&s);
234                               continue;
235                     }
236 #define   BADCH     " \t\n\\'\""
237                     if (isxargs && strpbrk(g_entry->fts_path, BADCH)) {
238                               sig_unlock(&s);
239                               (void)fflush(stdout);
240                               warnx("%s: illegal path", g_entry->fts_path);
241                               rval = 1;
242                               sig_lock(&s);
243                               continue;
244                     }
245 
246                     /*
247                      * Call all the functions in the execution plan until one is
248                      * false or all have been executed.  This is where we do all
249                      * the work specified by the user on the command line.
250                      */
251                     sig_unlock(&s);
252                     for (p = plan; p && (p->eval)(p, g_entry); p = p->next)
253                               if (p->type == N_EXIT) {
254                                         rval = p->exit_val;
255                                         cval = 0;
256                               }
257                     sig_lock(&s);
258           }
259 
260           sig_unlock(&s);
261           if (g_entry == NULL && errno)
262                     err(1, "fts_read");
263           (void)fts_close(tree);
264 
265           /*
266            * Cleanup any plans with leftover state.
267            * Keep the last non-zero return value.
268            */
269           if ((r = find_traverse(plan, plan_cleanup, NULL)) != 0)
270                     rval = r;
271 
272           return (rval);
273 }
274 
275 /*
276  * find_traverse --
277  *        traverse the plan tree and execute func() on all plans.  This
278  *        does not evaluate each plan's eval() function; it is intended
279  *        for operations that must run on all plans, such as state
280  *        cleanup.
281  *
282  *        If any func() returns non-zero, then so will find_traverse().
283  */
284 int
find_traverse(PLAN * plan,int (* func)(PLAN *,void *),void * arg)285 find_traverse(PLAN *plan, int (*func)(PLAN *, void *), void *arg)
286 {
287           PLAN *p;
288           int r, rval;
289 
290           rval = 0;
291           for (p = plan; p; p = p->next) {
292                     if ((r = func(p, arg)) != 0)
293                               rval = r;
294                     if (p->type == N_EXPR || p->type == N_OR) {
295                               if (p->p_data[0])
296                                         if ((r = find_traverse(p->p_data[0],
297                                                       func, arg)) != 0)
298                                                   rval = r;
299                               if (p->p_data[1])
300                                         if ((r = find_traverse(p->p_data[1],
301                                                       func, arg)) != 0)
302                                                   rval = r;
303                     }
304           }
305           return rval;
306 }
307