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 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 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 (de->d_type == DT_DIR) { 53 int subfd; 54 55 /* always skip "." and ".." */ 56 if (name[0] == '.') { 57 if (name[1] == 0) 58 continue; 59 if ((name[1] == '.') && (name[2] == 0)) 60 continue; 61 } 62 63 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY); 64 if (subfd >= 0) { 65 size += calculate_dir_size(subfd); 66 } 67 } else { 68 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) { 69 size += stat_size(&s); 70 } 71 } 72 } 73 closedir(d); 74 return size; 75 } 76