-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.cpp
1629 lines (1403 loc) · 52.1 KB
/
Utils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Utils.h"
#include "Process.h"
#include "sehandle.h"
#include <android-base/chrono_utils.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <cutils/fs.h>
#include <logwrap/logwrap.h>
#include <private/android_filesystem_config.h>
#include <private/android_projectid_config.h>
#include <dirent.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <unistd.h>
#include <filesystem>
#include <list>
#include <mutex>
#include <regex>
#include <thread>
#ifndef UMOUNT_NOFOLLOW
#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
#endif
using namespace std::chrono_literals;
using android::base::EndsWith;
using android::base::ReadFileToString;
using android::base::StartsWith;
using android::base::StringPrintf;
using android::base::unique_fd;
namespace android {
namespace vold {
security_context_t sBlkidContext = nullptr;
security_context_t sBlkidUntrustedContext = nullptr;
security_context_t sFsckContext = nullptr;
security_context_t sFsckUntrustedContext = nullptr;
bool sSleepOnUnmount = true;
static const char* kBlkidPath = "/system/bin/blkid";
static const char* kKeyPath = "/data/misc/vold";
static const char* kProcDevices = "/proc/devices";
static const char* kProcFilesystems = "/proc/filesystems";
static const char* kAndroidDir = "/Android/";
static const char* kAppDataDir = "/Android/data/";
static const char* kAppMediaDir = "/Android/media/";
static const char* kAppObbDir = "/Android/obb/";
static const char* kMediaProviderCtx = "u:r:mediaprovider:";
static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
// Lock used to protect process-level SELinux changes from racing with each
// other between multiple threads.
static std::mutex kSecurityLock;
std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
}
status_t CreateDeviceNode(const std::string& path, dev_t dev) {
std::lock_guard<std::mutex> lock(kSecurityLock);
const char* cpath = path.c_str();
status_t res = 0;
char* secontext = nullptr;
if (sehandle) {
if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
setfscreatecon(secontext);
}
}
mode_t mode = 0660 | S_IFBLK;
if (mknod(cpath, mode, dev) < 0) {
if (errno != EEXIST) {
PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
<< " at " << path;
res = -errno;
}
}
if (secontext) {
setfscreatecon(nullptr);
freecon(secontext);
}
return res;
}
status_t DestroyDeviceNode(const std::string& path) {
const char* cpath = path.c_str();
if (TEMP_FAILURE_RETRY(unlink(cpath))) {
return -errno;
} else {
return OK;
}
}
// Sets a default ACL on the directory.
int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
std::vector<gid_t> additionalGids) {
if (IsSdcardfsUsed()) {
// sdcardfs magically takes care of this
return OK;
}
size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
auto buf = std::make_unique<uint8_t[]>(size);
posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
acl_header->a_version = POSIX_ACL_XATTR_VERSION;
posix_acl_xattr_entry* entry =
reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
int tag_index = 0;
entry[tag_index].e_tag = ACL_USER_OBJ;
// The existing mode_t mask has the ACL in the lower 9 bits:
// the lowest 3 for "other", the next 3 the group, the next 3 for the owner
// Use the mode_t masks to get these bits out, and shift them to get the
// correct value per entity.
//
// Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
entry[tag_index].e_id = uid;
tag_index++;
entry[tag_index].e_tag = ACL_GROUP_OBJ;
entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
entry[tag_index].e_id = gid;
tag_index++;
if (additionalGids.size() > 0) {
for (gid_t additional_gid : additionalGids) {
entry[tag_index].e_tag = ACL_GROUP;
entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
entry[tag_index].e_id = additional_gid;
tag_index++;
}
entry[tag_index].e_tag = ACL_MASK;
entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
entry[tag_index].e_id = 0;
tag_index++;
}
entry[tag_index].e_tag = ACL_OTHER;
entry[tag_index].e_perm = mode & S_IRWXO;
entry[tag_index].e_id = 0;
int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
if (ret != 0) {
PLOG(ERROR) << "Failed to set default ACL on " << path;
}
return ret;
}
int SetQuotaInherit(const std::string& path) {
unsigned long flags;
android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
if (fd == -1) {
PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
return -1;
}
int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
if (ret == -1) {
PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
return ret;
}
flags |= FS_PROJINHERIT_FL;
ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
if (ret == -1) {
PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
return ret;
}
return 0;
}
int SetQuotaProjectId(const std::string& path, long projectId) {
struct fsxattr fsx;
android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
if (fd == -1) {
PLOG(ERROR) << "Failed to open " << path << " to set project id.";
return -1;
}
int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
if (ret == -1) {
PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
return ret;
}
fsx.fsx_projid = projectId;
return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
}
int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
long projectId) {
int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
if (ret != 0) {
return ret;
}
if (!IsSdcardfsUsed()) {
ret = SetQuotaProjectId(path, projectId);
}
return ret;
}
static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
namespace fs = std::filesystem;
// Setup the directory itself correctly
int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
if (ret != OK) {
return ret;
}
// Fixup all of its file entries
for (const auto& itEntry : fs::directory_iterator(path)) {
ret = lchown(itEntry.path().c_str(), uid, gid);
if (ret != 0) {
return ret;
}
ret = chmod(itEntry.path().c_str(), mode);
if (ret != 0) {
return ret;
}
if (!IsSdcardfsUsed()) {
ret = SetQuotaProjectId(itEntry.path(), projectId);
if (ret != 0) {
return ret;
}
}
}
return OK;
}
int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
bool fixupExisting) {
long projectId;
size_t pos;
int ret = 0;
bool sdcardfsSupport = IsSdcardfsUsed();
// Make sure the Android/ directories exist and are setup correctly
ret = PrepareAndroidDirs(root);
if (ret != 0) {
LOG(ERROR) << "Failed to prepare Android/ directories.";
return ret;
}
// Now create the application-specific subdir(s)
// path is something like /data/media/0/Android/data/com.foo/files
// First, chop off the volume root, eg /data/media/0
std::string pathFromRoot = path.substr(root.length());
uid_t uid = appUid;
gid_t gid = AID_MEDIA_RW;
std::vector<gid_t> additionalGids;
std::string appDir;
// Check that the next part matches one of the allowed Android/ dirs
if (StartsWith(pathFromRoot, kAppDataDir)) {
appDir = kAppDataDir;
if (!sdcardfsSupport) {
gid = AID_EXT_DATA_RW;
// Also add the app's own UID as a group; since apps belong to a group
// that matches their UID, this ensures that they will always have access to
// the files created in these dirs, even if they are created by other processes
additionalGids.push_back(uid);
}
} else if (StartsWith(pathFromRoot, kAppMediaDir)) {
appDir = kAppMediaDir;
if (!sdcardfsSupport) {
gid = AID_MEDIA_RW;
}
} else if (StartsWith(pathFromRoot, kAppObbDir)) {
appDir = kAppObbDir;
if (!sdcardfsSupport) {
gid = AID_EXT_OBB_RW;
// See comments for kAppDataDir above
additionalGids.push_back(uid);
}
} else {
LOG(ERROR) << "Invalid application directory: " << path;
return -EINVAL;
}
// mode = 770, plus sticky bit on directory to inherit GID when apps
// create subdirs
mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
// the project ID for application-specific directories is directly
// derived from their uid
// Chop off the generic application-specific part, eg /Android/data/
// this leaves us with something like com.foo/files/
std::string leftToCreate = pathFromRoot.substr(appDir.length());
if (!EndsWith(leftToCreate, "/")) {
leftToCreate += "/";
}
std::string pathToCreate = root + appDir;
int depth = 0;
// Derive initial project ID
if (appDir == kAppDataDir || appDir == kAppMediaDir) {
projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
} else if (appDir == kAppObbDir) {
projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
}
while ((pos = leftToCreate.find('/')) != std::string::npos) {
std::string component = leftToCreate.substr(0, pos + 1);
leftToCreate = leftToCreate.erase(0, pos + 1);
pathToCreate = pathToCreate + component;
if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
// All dirs use the "app" project ID, except for the cache dirs in
// Android/data, eg Android/data/com.foo/cache
// Note that this "sticks" - eg subdirs of this dir need the same
// project ID.
projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
}
if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
// Fixup all files in this existing directory with the correct UID/GID
// and project ID.
ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
} else {
ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
}
if (ret != 0) {
return ret;
}
if (depth == 0) {
// Set the default ACL on the top-level application-specific directories,
// to ensure that even if applications run with a umask of 0077,
// new directories within these directories will allow the GID
// specified here to write; this is necessary for apps like
// installers and MTP, that require access here.
//
// See man (5) acl for more details.
ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
if (ret != 0) {
return ret;
}
if (!sdcardfsSupport) {
// Set project ID inheritance, so that future subdirectories inherit the
// same project ID
ret = SetQuotaInherit(pathToCreate);
if (ret != 0) {
return ret;
}
}
}
depth++;
}
return OK;
}
status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
std::lock_guard<std::mutex> lock(kSecurityLock);
const char* cpath = path.c_str();
char* secontext = nullptr;
if (sehandle) {
if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
setfscreatecon(secontext);
}
}
int res = fs_prepare_dir(cpath, mode, uid, gid);
if (secontext) {
setfscreatecon(nullptr);
freecon(secontext);
}
if (res == 0) {
return OK;
} else {
return -errno;
}
}
status_t ForceUnmount(const std::string& path) {
const char* cpath = path.c_str();
if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
return OK;
}
// Apps might still be handling eject request, so wait before
// we start sending signals
if (sSleepOnUnmount) sleep(5);
KillProcessesWithOpenFiles(path, SIGINT);
if (sSleepOnUnmount) sleep(5);
if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
return OK;
}
KillProcessesWithOpenFiles(path, SIGTERM);
if (sSleepOnUnmount) sleep(5);
if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
return OK;
}
KillProcessesWithOpenFiles(path, SIGKILL);
if (sSleepOnUnmount) sleep(5);
if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
return OK;
}
PLOG(INFO) << "ForceUnmount failed";
return -errno;
}
status_t KillProcessesWithMountPrefix(const std::string& path) {
if (KillProcessesWithMounts(path, SIGINT) == 0) {
return OK;
}
if (sSleepOnUnmount) sleep(5);
if (KillProcessesWithMounts(path, SIGTERM) == 0) {
return OK;
}
if (sSleepOnUnmount) sleep(5);
if (KillProcessesWithMounts(path, SIGKILL) == 0) {
return OK;
}
if (sSleepOnUnmount) sleep(5);
// Send SIGKILL a second time to determine if we've
// actually killed everyone mount
if (KillProcessesWithMounts(path, SIGKILL) == 0) {
return OK;
}
PLOG(ERROR) << "Failed to kill processes using " << path;
return -EBUSY;
}
status_t KillProcessesUsingPath(const std::string& path) {
if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
return OK;
}
if (sSleepOnUnmount) sleep(5);
if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
return OK;
}
if (sSleepOnUnmount) sleep(5);
if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
return OK;
}
if (sSleepOnUnmount) sleep(5);
// Send SIGKILL a second time to determine if we've
// actually killed everyone with open files
if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
return OK;
}
PLOG(ERROR) << "Failed to kill processes using " << path;
return -EBUSY;
}
status_t BindMount(const std::string& source, const std::string& target) {
if (UnmountTree(target) < 0) {
return -errno;
}
if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
return -errno;
}
return OK;
}
status_t Symlink(const std::string& target, const std::string& linkpath) {
if (Unlink(linkpath) < 0) {
return -errno;
}
if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
return -errno;
}
return OK;
}
status_t Unlink(const std::string& linkpath) {
if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
PLOG(ERROR) << "Failed to unlink " << linkpath;
return -errno;
}
return OK;
}
status_t CreateDir(const std::string& dir, mode_t mode) {
struct stat sb;
if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
if (S_ISDIR(sb.st_mode)) {
return OK;
} else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
PLOG(ERROR) << "Failed to unlink " << dir;
return -errno;
}
} else if (errno != ENOENT) {
PLOG(ERROR) << "Failed to stat " << dir;
return -errno;
}
if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
PLOG(ERROR) << "Failed to mkdir " << dir;
return -errno;
}
return OK;
}
bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
auto qual = key + "=\"";
size_t start = 0;
while (true) {
start = raw.find(qual, start);
if (start == std::string::npos) return false;
if (start == 0 || raw[start - 1] == ' ') {
break;
}
start += 1;
}
start += qual.length();
auto end = raw.find("\"", start);
if (end == std::string::npos) return false;
*value = raw.substr(start, end - start);
return true;
}
static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
std::string* fsLabel, bool untrusted) {
fsType->clear();
fsUuid->clear();
fsLabel->clear();
std::vector<std::string> cmd;
cmd.push_back(kBlkidPath);
cmd.push_back("-c");
cmd.push_back("/dev/null");
cmd.push_back("-s");
cmd.push_back("TYPE");
cmd.push_back("-s");
cmd.push_back("UUID");
cmd.push_back("-s");
cmd.push_back("LABEL");
cmd.push_back(path);
std::vector<std::string> output;
status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
if (res != OK) {
LOG(WARNING) << "blkid failed to identify " << path;
return res;
}
for (const auto& line : output) {
// Extract values from blkid output, if defined
FindValue(line, "TYPE", fsType);
FindValue(line, "UUID", fsUuid);
FindValue(line, "LABEL", fsLabel);
}
return OK;
}
status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
std::string* fsLabel) {
return readMetadata(path, fsType, fsUuid, fsLabel, false);
}
status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
std::string* fsLabel) {
return readMetadata(path, fsType, fsUuid, fsLabel, true);
}
static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
std::vector<const char*> argv;
argv.reserve(args.size() + 1);
for (const auto& arg : args) {
if (argv.empty()) {
LOG(DEBUG) << arg;
} else {
LOG(DEBUG) << " " << arg;
}
argv.emplace_back(arg.data());
}
argv.emplace_back(nullptr);
return argv;
}
static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
android::base::unique_fd ufd) {
std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
if (!fp) {
PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
return -errno;
}
if (output) output->clear();
char line[1024];
while (fgets(line, sizeof(line), fp.get()) != nullptr) {
LOG(DEBUG) << line;
if (output) output->emplace_back(line);
}
return OK;
}
status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
security_context_t context) {
auto argv = ConvertToArgv(args);
android::base::unique_fd pipe_read, pipe_write;
if (!android::base::Pipe(&pipe_read, &pipe_write)) {
PLOG(ERROR) << "Pipe in ForkExecvp";
return -errno;
}
pid_t pid = fork();
if (pid == 0) {
if (context) {
if (setexeccon(context)) {
LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
abort();
}
}
pipe_read.reset();
if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
PLOG(ERROR) << "dup2 in ForkExecvp";
_exit(EXIT_FAILURE);
}
pipe_write.reset();
execvp(argv[0], const_cast<char**>(argv.data()));
PLOG(ERROR) << "exec in ForkExecvp";
_exit(EXIT_FAILURE);
}
if (pid == -1) {
PLOG(ERROR) << "fork in ForkExecvp";
return -errno;
}
pipe_write.reset();
auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
if (st != 0) return st;
int status;
if (waitpid(pid, &status, 0) == -1) {
PLOG(ERROR) << "waitpid in ForkExecvp";
return -errno;
}
if (!WIFEXITED(status)) {
LOG(ERROR) << "Process did not exit normally, status: " << status;
return -ECHILD;
}
if (WEXITSTATUS(status)) {
LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
return WEXITSTATUS(status);
}
return OK;
}
pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
auto argv = ConvertToArgv(args);
pid_t pid = fork();
if (pid == 0) {
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
execvp(argv[0], const_cast<char**>(argv.data()));
PLOG(ERROR) << "exec in ForkExecvpAsync";
_exit(EXIT_FAILURE);
}
if (pid == -1) {
PLOG(ERROR) << "fork in ForkExecvpAsync";
return -1;
}
return pid;
}
status_t ReadRandomBytes(size_t bytes, std::string& out) {
out.resize(bytes);
return ReadRandomBytes(bytes, &out[0]);
}
status_t ReadRandomBytes(size_t bytes, char* buf) {
int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
if (fd == -1) {
return -errno;
}
ssize_t n;
while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
bytes -= n;
buf += n;
}
close(fd);
if (bytes == 0) {
return OK;
} else {
return -EIO;
}
}
status_t GenerateRandomUuid(std::string& out) {
status_t res = ReadRandomBytes(16, out);
if (res == OK) {
out[6] &= 0x0f; /* clear version */
out[6] |= 0x40; /* set to version 4 */
out[8] &= 0x3f; /* clear variant */
out[8] |= 0x80; /* set to IETF variant */
}
return res;
}
status_t HexToStr(const std::string& hex, std::string& str) {
str.clear();
bool even = true;
char cur = 0;
for (size_t i = 0; i < hex.size(); i++) {
int val = 0;
switch (hex[i]) {
// clang-format off
case ' ': case '-': case ':': continue;
case 'f': case 'F': val = 15; break;
case 'e': case 'E': val = 14; break;
case 'd': case 'D': val = 13; break;
case 'c': case 'C': val = 12; break;
case 'b': case 'B': val = 11; break;
case 'a': case 'A': val = 10; break;
case '9': val = 9; break;
case '8': val = 8; break;
case '7': val = 7; break;
case '6': val = 6; break;
case '5': val = 5; break;
case '4': val = 4; break;
case '3': val = 3; break;
case '2': val = 2; break;
case '1': val = 1; break;
case '0': val = 0; break;
default: return -EINVAL;
// clang-format on
}
if (even) {
cur = val << 4;
} else {
cur += val;
str.push_back(cur);
cur = 0;
}
even = !even;
}
return even ? OK : -EINVAL;
}
static const char* kLookup = "0123456789abcdef";
status_t StrToHex(const std::string& str, std::string& hex) {
hex.clear();
for (size_t i = 0; i < str.size(); i++) {
hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
hex.push_back(kLookup[str[i] & 0x0F]);
}
return OK;
}
status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
hex.clear();
for (size_t i = 0; i < str.size(); i++) {
hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
hex.push_back(kLookup[str.data()[i] & 0x0F]);
}
return OK;
}
status_t NormalizeHex(const std::string& in, std::string& out) {
std::string tmp;
if (HexToStr(in, tmp)) {
return -EINVAL;
}
return StrToHex(tmp, out);
}
status_t GetBlockDevSize(int fd, uint64_t* size) {
if (ioctl(fd, BLKGETSIZE64, size)) {
return -errno;
}
return OK;
}
status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
status_t res = OK;
if (fd < 0) {
return -errno;
}
res = GetBlockDevSize(fd, size);
close(fd);
return res;
}
status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
uint64_t size;
status_t res = GetBlockDevSize(path, &size);
if (res != OK) {
return res;
}
*nr_sec = size / 512;
return OK;
}
uint64_t GetFreeBytes(const std::string& path) {
struct statvfs sb;
if (statvfs(path.c_str(), &sb) == 0) {
return (uint64_t)sb.f_bavail * sb.f_frsize;
} else {
return -1;
}
}
// TODO: borrowed from frameworks/native/libs/diskusage/ which should
// eventually be migrated into system/
static int64_t stat_size(struct stat* s) {
int64_t blksize = s->st_blksize;
// count actual blocks used instead of nominal file size
int64_t size = s->st_blocks * 512;
if (blksize) {
/* round up to filesystem block size */
size = (size + blksize - 1) & (~(blksize - 1));
}
return size;
}
// TODO: borrowed from frameworks/native/libs/diskusage/ which should
// eventually be migrated into system/
int64_t calculate_dir_size(int dfd) {
int64_t size = 0;
struct stat s;
DIR* d;
struct dirent* de;
d = fdopendir(dfd);
if (d == NULL) {
close(dfd);
return 0;
}
while ((de = readdir(d))) {
const char* name = de->d_name;
if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
size += stat_size(&s);
}
if (de->d_type == DT_DIR) {
int subfd;
/* always skip "." and ".." */
if (name[0] == '.') {
if (name[1] == 0) continue;
if ((name[1] == '.') && (name[2] == 0)) continue;
}
subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (subfd >= 0) {
size += calculate_dir_size(subfd);
}
}
}
closedir(d);
return size;
}
uint64_t GetTreeBytes(const std::string& path) {
int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (dirfd < 0) {
PLOG(WARNING) << "Failed to open " << path;
return -1;
} else {
return calculate_dir_size(dirfd);
}
}
// TODO: Use a better way to determine if it's media provider app.
bool IsFuseDaemon(const pid_t pid) {
auto path = StringPrintf("/proc/%d/mounts", pid);
char* tmp;
if (lgetfilecon(path.c_str(), &tmp) < 0) {
return false;
}
bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
|| android::base::StartsWith(tmp, kMediaProviderCtx);
freecon(tmp);
return result;
}
bool IsFilesystemSupported(const std::string& fsType) {
std::string supported;
if (!ReadFileToString(kProcFilesystems, &supported)) {
PLOG(ERROR) << "Failed to read supported filesystems";
return false;
}
/* fuse filesystems */
supported.append("fuse\tntfs\n");
return supported.find(fsType + "\n") != std::string::npos;
}
bool IsSdcardfsUsed() {
return IsFilesystemSupported("sdcardfs") &&
base::GetBoolProperty(kExternalStorageSdcardfs, true);
}
status_t WipeBlockDevice(const std::string& path) {
status_t res = -1;
const char* c_path = path.c_str();
uint64_t range[2] = {0, 0};
int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
if (fd == -1) {
PLOG(ERROR) << "Failed to open " << path;
goto done;
}
if (GetBlockDevSize(fd, &range[1]) != OK) {
PLOG(ERROR) << "Failed to determine size of " << path;
goto done;