Imported Upstream version 4.5.14
[platform/upstream/findutils.git] / lib / dircallback.c
1 /* listfile.c -- run a function in a specific directory
2    Copyright (C) 2007, 2008, 2009, 2010, 2011 Free Software Foundation,
3    Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /* This file was written by James Youngman, based on gnulib'c at-func.c.
20  */
21
22 /* config.h must be included first. */
23 #include <config.h>
24
25 /* system headers. */
26 #include <errno.h>
27 #include <locale.h>
28 #include <stdarg.h>
29 #include <sys/stat.h>
30
31 /* gnulib headers. */
32 #include "fcntl--.h"
33 #include "openat.h"
34 #include "save-cwd.h"
35
36 /* find headers. */
37 #include "dircallback.h"
38
39 int
40 run_in_dir (const struct saved_cwd *there,
41             int (*callback)(void*), void *usercontext)
42 {
43   int err = -1;
44   int saved_errno = 0;
45   struct saved_cwd here;
46   if (0 == save_cwd (&here))
47     {
48       if (0 == restore_cwd (there))
49         {
50           err = callback(usercontext);
51           saved_errno = (err < 0 ? errno : 0);
52         }
53       else
54         {
55           openat_restore_fail (errno);
56         }
57
58       if (restore_cwd (&here) != 0)
59         openat_restore_fail (errno);
60
61       free_cwd (&here);
62     }
63   else
64     {
65       openat_save_fail (errno);
66     }
67   if (saved_errno)
68     errno = saved_errno;
69   return err;
70 }
71
72
73 int
74 run_in_dirfd (int dir_fd, int (*callback)(void*), void *usercontext)
75 {
76   if (dir_fd == AT_FDCWD)
77     {
78       return (*callback)(usercontext);
79     }
80   else
81     {
82       struct saved_cwd saved_cwd;
83       int saved_errno;
84       int err;
85
86       if (save_cwd (&saved_cwd) != 0)
87         openat_save_fail (errno);
88
89       if (fchdir (dir_fd) != 0)
90         {
91           saved_errno = errno;
92           free_cwd (&saved_cwd);
93           errno = saved_errno;
94           return -1;
95         }
96
97       err = (*callback)(usercontext);
98       saved_errno = (err < 0 ? errno : 0);
99
100       if (restore_cwd (&saved_cwd) != 0)
101         openat_restore_fail (errno);
102
103       free_cwd (&saved_cwd);
104
105       if (saved_errno)
106         errno = saved_errno;
107       return err;
108     }
109 }