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