1 /*
2 *
3 * Copyright (C) 2008, The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #include <dirent.h>
19 #include <fcntl.h>
20 #include <sys/stat.h>
21
22 #include <diskusage/dirsize.h>
23
stat_size(struct stat * s)24 int64_t stat_size(struct stat *s)
25 {
26 int64_t blksize = s->st_blksize;
27 int64_t size = s->st_size;
28
29 if (blksize) {
30 /* round up to filesystem block size */
31 size = (size + blksize - 1) & (~(blksize - 1));
32 }
33
34 return size;
35 }
36
calculate_dir_size(int dfd)37 int64_t calculate_dir_size(int dfd)
38 {
39 int64_t size = 0;
40 struct stat s;
41 DIR *d;
42 struct dirent *de;
43
44 d = fdopendir(dfd);
45 if (d == NULL) {
46 close(dfd);
47 return 0;
48 }
49
50 while ((de = readdir(d))) {
51 const char *name = de->d_name;
52 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
53 size += stat_size(&s);
54 }
55 if (de->d_type == DT_DIR) {
56 int subfd;
57
58 /* always skip "." and ".." */
59 if (name[0] == '.') {
60 if (name[1] == 0)
61 continue;
62 if ((name[1] == '.') && (name[2] == 0))
63 continue;
64 }
65
66 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
67 if (subfd >= 0) {
68 size += calculate_dir_size(subfd);
69 }
70 }
71 }
72 closedir(d);
73 return size;
74 }
75