blob: 5b5ab701b089dae1de774f280b7cc5398474f103 [file] [log] [blame]
Mike Lockwood126d2152012-10-24 12:28:57 -07001/*
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>
Elliott Hughes14df3562015-02-19 16:58:44 -080021#include <unistd.h>
Mike Lockwood126d2152012-10-24 12:28:57 -070022
23#include <diskusage/dirsize.h>
24
25int64_t stat_size(struct stat *s)
26{
Jeff Sharkey2f720f72016-04-10 20:51:40 -060027 return s->st_blocks * 512;
Mike Lockwood126d2152012-10-24 12:28:57 -070028}
29
30int64_t calculate_dir_size(int dfd)
31{
32 int64_t size = 0;
33 struct stat s;
34 DIR *d;
35 struct dirent *de;
36
37 d = fdopendir(dfd);
38 if (d == NULL) {
39 close(dfd);
40 return 0;
41 }
42
43 while ((de = readdir(d))) {
44 const char *name = de->d_name;
Mike Lockwood126d2152012-10-24 12:28:57 -070045 if (de->d_type == DT_DIR) {
46 int subfd;
47
48 /* always skip "." and ".." */
49 if (name[0] == '.') {
50 if (name[1] == 0)
51 continue;
52 if ((name[1] == '.') && (name[2] == 0))
53 continue;
54 }
55
Jeff Sharkey2f720f72016-04-10 20:51:40 -060056 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
57 size += stat_size(&s);
58 }
Mike Lockwood126d2152012-10-24 12:28:57 -070059 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
60 if (subfd >= 0) {
61 size += calculate_dir_size(subfd);
62 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -060063 } else {
64 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
65 size += stat_size(&s);
66 }
Mike Lockwood126d2152012-10-24 12:28:57 -070067 }
68 }
69 closedir(d);
70 return size;
71}