1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "Log.h"
18 
19 #include "incidentd_util.h"
20 #include "proto_util.h"
21 #include "PrivacyFilter.h"
22 #include "WorkDirectory.h"
23 
24 #include <google/protobuf/io/zero_copy_stream_impl.h>
25 #include <private/android_filesystem_config.h>
26 
27 #include <iomanip>
28 #include <map>
29 #include <sstream>
30 #include <thread>
31 #include <vector>
32 
33 #include <sys/stat.h>
34 #include <time.h>
35 #include <unistd.h>
36 #include <inttypes.h>
37 
38 namespace android {
39 namespace os {
40 namespace incidentd {
41 
42 using std::thread;
43 using google::protobuf::MessageLite;
44 using google::protobuf::RepeatedPtrField;
45 using google::protobuf::io::FileInputStream;
46 using google::protobuf::io::FileOutputStream;
47 
48 /**
49  * Turn off to skip removing files for debugging.
50  */
51 static const bool DO_UNLINK = true;
52 
53 /**
54  * File extension for envelope files.
55  */
56 static const string EXTENSION_ENVELOPE(".envelope");
57 
58 /**
59  * File extension for data files.
60  */
61 static const string EXTENSION_DATA(".data");
62 
63 /**
64  * Send these reports to dropbox.
65  */
66 const ComponentName DROPBOX_SENTINEL("android", "DROPBOX");
67 
68 /** metadata field id in IncidentProto */
69 const int FIELD_ID_INCIDENT_METADATA = 2;
70 
71 // Args for exec gzip
72 static const char* GZIP[] = {"/system/bin/gzip", NULL};
73 
74 /**
75  * Read a protobuf from disk into the message.
76  */
read_proto(MessageLite * msg,const string & filename)77 static status_t read_proto(MessageLite* msg, const string& filename) {
78     int fd = open(filename.c_str(), O_RDONLY | O_CLOEXEC);
79     if (fd < 0) {
80         return -errno;
81     }
82 
83     FileInputStream stream(fd);
84     stream.SetCloseOnDelete(fd);
85 
86     if (!msg->ParseFromZeroCopyStream(&stream)) {
87         return BAD_VALUE;
88     }
89 
90     return stream.GetErrno();
91 }
92 
93 /**
94  * Write a protobuf to disk.
95  */
write_proto(const MessageLite & msg,const string & filename)96 static status_t write_proto(const MessageLite& msg, const string& filename) {
97     int fd = open(filename.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0660);
98     if (fd < 0) {
99         return -errno;
100     }
101 
102     FileOutputStream stream(fd);
103     stream.SetCloseOnDelete(fd);
104 
105     if (!msg.SerializeToZeroCopyStream(&stream)) {
106         ALOGW("write_proto: error writing to %s", filename.c_str());
107         return BAD_VALUE;
108     }
109 
110     return stream.GetErrno();
111 }
112 
strip_extension(const string & filename)113 static string strip_extension(const string& filename) {
114     return filename.substr(0, filename.find('.'));
115 }
116 
ends_with(const string & str,const string & ending)117 static bool ends_with(const string& str, const string& ending) {
118     if (str.length() >= ending.length()) {
119         return str.compare(str.length()-ending.length(), ending.length(), ending) == 0;
120     } else {
121         return false;
122     }
123 }
124 
125 // Returns true if it was a valid timestamp.
parse_timestamp_ns(const string & id,int64_t * result)126 static bool parse_timestamp_ns(const string& id, int64_t* result) {
127     char* endptr;
128     *result = strtoll(id.c_str(), &endptr, 10);
129     return id.length() != 0 && *endptr == '\0';
130 }
131 
has_section(const ReportFileProto_Report & report,int section)132 static bool has_section(const ReportFileProto_Report& report, int section) {
133     const size_t sectionCount = report.section_size();
134     for (int i = 0; i < sectionCount; i++) {
135         if (report.section(i) == section) {
136             return true;
137         }
138     }
139     return false;
140 }
141 
create_directory(const char * directory)142 status_t create_directory(const char* directory) {
143     struct stat st;
144     status_t err = NO_ERROR;
145     char* dir = strdup(directory);
146 
147     // Skip first slash
148     char* d = dir + 1;
149 
150     // Create directories, assigning them to the system user
151     bool last = false;
152     while (!last) {
153         d = strchr(d, '/');
154         if (d != NULL) {
155             *d = '\0';
156         } else {
157             last = true;
158         }
159         if (stat(dir, &st) == 0) {
160             if (!S_ISDIR(st.st_mode)) {
161                 err = ALREADY_EXISTS;
162                 goto done;
163             }
164         } else {
165             ALOGE("No such directory %s, something wrong.", dir);
166             err = -1;
167             goto done;
168         }
169         if (!last) {
170             *d++ = '/';
171         }
172     }
173 
174     // Ensure that the final directory is owned by the system with 0770. If it isn't
175     // we won't write into it.
176     if (stat(directory, &st) != 0) {
177         ALOGE("No incident reports today. Can't stat: %s", directory);
178         err = -errno;
179         goto done;
180     }
181     if ((st.st_mode & 0777) != 0770) {
182         ALOGE("No incident reports today. Mode is %0o on report directory %s", st.st_mode,
183               directory);
184         err = BAD_VALUE;
185         goto done;
186     }
187     if (st.st_uid != AID_INCIDENTD || st.st_gid != AID_INCIDENTD) {
188         ALOGE("No incident reports today. Owner is %d and group is %d on report directory %s",
189               st.st_uid, st.st_gid, directory);
190         err = BAD_VALUE;
191         goto done;
192     }
193 
194 done:
195     free(dir);
196     return err;
197 }
198 
log_envelope(const ReportFileProto & envelope)199 void log_envelope(const ReportFileProto& envelope) {
200     ALOGD("Envelope: {");
201     for (int i=0; i<envelope.report_size(); i++) {
202         ALOGD("  report {");
203         ALOGD("    pkg=%s", envelope.report(i).pkg().c_str());
204         ALOGD("    cls=%s", envelope.report(i).cls().c_str());
205         ALOGD("    share_approved=%d", envelope.report(i).share_approved());
206         ALOGD("    privacy_policy=%d", envelope.report(i).privacy_policy());
207         ALOGD("    all_sections=%d", envelope.report(i).all_sections());
208         for (int j=0; j<envelope.report(i).section_size(); j++) {
209             ALOGD("    section[%d]=%d", j, envelope.report(i).section(j));
210         }
211         ALOGD("  }");
212     }
213     ALOGD("  data_file=%s", envelope.data_file().c_str());
214     ALOGD("  privacy_policy=%d", envelope.privacy_policy());
215     ALOGD("  data_file_size=%" PRIi64, (int64_t)envelope.data_file_size());
216     ALOGD("  completed=%d", envelope.completed());
217     ALOGD("}");
218 }
219 
220 // ================================================================================
221 struct WorkDirectoryEntry {
222     WorkDirectoryEntry();
223     explicit WorkDirectoryEntry(const WorkDirectoryEntry& that);
224     ~WorkDirectoryEntry();
225 
226     string envelope;
227     string data;
228     int64_t timestampNs;
229     off_t size;
230 };
231 
WorkDirectoryEntry()232 WorkDirectoryEntry::WorkDirectoryEntry()
233         :envelope(),
234          data(),
235          size(0) {
236 }
237 
WorkDirectoryEntry(const WorkDirectoryEntry & that)238 WorkDirectoryEntry::WorkDirectoryEntry(const WorkDirectoryEntry& that)
239         :envelope(that.envelope),
240          data(that.data),
241          size(that.size) {
242 }
243 
~WorkDirectoryEntry()244 WorkDirectoryEntry::~WorkDirectoryEntry() {
245 }
246 
247 // ================================================================================
ReportFile(const sp<WorkDirectory> & workDirectory,int64_t timestampNs,const string & envelopeFileName,const string & dataFileName)248 ReportFile::ReportFile(const sp<WorkDirectory>& workDirectory, int64_t timestampNs,
249             const string& envelopeFileName, const string& dataFileName)
250         :mWorkDirectory(workDirectory),
251          mTimestampNs(timestampNs),
252          mEnvelopeFileName(envelopeFileName),
253          mDataFileName(dataFileName),
254          mEnvelope(),
255          mDataFd(-1),
256          mError(NO_ERROR) {
257     // might get overwritten when we read but that's ok
258     mEnvelope.set_data_file(mDataFileName);
259 }
260 
~ReportFile()261 ReportFile::~ReportFile() {
262     if (mDataFd >= 0) {
263         close(mDataFd);
264     }
265 }
266 
getTimestampNs() const267 int64_t ReportFile::getTimestampNs() const {
268     return mTimestampNs;
269 }
270 
addReport(const IncidentReportArgs & args)271 void ReportFile::addReport(const IncidentReportArgs& args) {
272     // There is only one report per component.  Merge into an existing one if necessary.
273     ReportFileProto_Report* report;
274     const int reportCount = mEnvelope.report_size();
275     int i = 0;
276     for (; i < reportCount; i++) {
277         report = mEnvelope.mutable_report(i);
278         if (report->pkg() == args.receiverPkg() && report->cls() == args.receiverCls()) {
279             if (args.getPrivacyPolicy() < report->privacy_policy()) {
280                 // Lower privacy policy (less restrictive) wins.
281                 report->set_privacy_policy(args.getPrivacyPolicy());
282             }
283             report->set_all_sections(report->all_sections() | args.all());
284             for (int section: args.sections()) {
285                 if (!has_section(*report, section)) {
286                     report->add_section(section);
287                 }
288             }
289             break;
290         }
291     }
292     if (i >= reportCount) {
293         report = mEnvelope.add_report();
294         report->set_pkg(args.receiverPkg());
295         report->set_cls(args.receiverCls());
296         report->set_privacy_policy(args.getPrivacyPolicy());
297         report->set_all_sections(args.all());
298         report->set_gzip(args.gzip());
299         for (int section: args.sections()) {
300             report->add_section(section);
301         }
302     }
303 
304     for (const vector<uint8_t>& header: args.headers()) {
305         report->add_header(header.data(), header.size());
306     }
307 }
308 
removeReport(const string & pkg,const string & cls)309 void ReportFile::removeReport(const string& pkg, const string& cls) {
310     RepeatedPtrField<ReportFileProto_Report>* reports = mEnvelope.mutable_report();
311     const int reportCount = reports->size();
312     for (int i = 0; i < reportCount; i++) {
313         const ReportFileProto_Report& r = reports->Get(i);
314         if (r.pkg() == pkg && r.cls() == cls) {
315             reports->DeleteSubrange(i, 1);
316             return;
317         }
318     }
319 }
320 
removeReports(const string & pkg)321 void ReportFile::removeReports(const string& pkg) {
322     RepeatedPtrField<ReportFileProto_Report>* reports = mEnvelope.mutable_report();
323     const int reportCount = reports->size();
324     for (int i = reportCount-1; i >= 0; i--) {
325         const ReportFileProto_Report& r = reports->Get(i);
326         if (r.pkg() == pkg) {
327             reports->DeleteSubrange(i, 1);
328         }
329     }
330 }
331 
setMetadata(const IncidentMetadata & metadata)332 void ReportFile::setMetadata(const IncidentMetadata& metadata) {
333     *mEnvelope.mutable_metadata() = metadata;
334 }
335 
markCompleted()336 void ReportFile::markCompleted() {
337     mEnvelope.set_completed(true);
338 }
339 
markApproved(const string & pkg,const string & cls)340 status_t ReportFile::markApproved(const string& pkg, const string& cls) {
341     size_t const reportCount = mEnvelope.report_size();
342     for (int reportIndex = 0; reportIndex < reportCount; reportIndex++) {
343         ReportFileProto_Report* report = mEnvelope.mutable_report(reportIndex);
344         if (report->pkg() == pkg && report->cls() == cls) {
345             report->set_share_approved(true);
346             return NO_ERROR;
347         }
348     }
349     return NAME_NOT_FOUND;
350 }
351 
setMaxPersistedPrivacyPolicy(int persistedPrivacyPolicy)352 void ReportFile::setMaxPersistedPrivacyPolicy(int persistedPrivacyPolicy) {
353     mEnvelope.set_privacy_policy(persistedPrivacyPolicy);
354 }
355 
saveEnvelope()356 status_t ReportFile::saveEnvelope() {
357     return save_envelope_impl(true);
358 }
359 
trySaveEnvelope()360 status_t ReportFile::trySaveEnvelope() {
361     return save_envelope_impl(false);
362 }
363 
loadEnvelope()364 status_t ReportFile::loadEnvelope() {
365     return load_envelope_impl(true);
366 }
367 
tryLoadEnvelope()368 status_t ReportFile::tryLoadEnvelope() {
369     return load_envelope_impl(false);
370 }
371 
getEnvelope()372 const ReportFileProto& ReportFile::getEnvelope() {
373     return mEnvelope;
374 }
375 
startWritingDataFile()376 status_t ReportFile::startWritingDataFile() {
377     if (mDataFd >= 0) {
378         ALOGW("ReportFile::startWritingDataFile called with the file already open: %s",
379                 mDataFileName.c_str());
380         return ALREADY_EXISTS;
381     }
382     mDataFd = open(mDataFileName.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0660);
383     if (mDataFd < 0) {
384         return -errno;
385     }
386     return NO_ERROR;
387 }
388 
closeDataFile()389 void ReportFile::closeDataFile() {
390     if (mDataFd >= 0) {
391         mEnvelope.set_data_file_size(lseek(mDataFd, 0, SEEK_END));
392         close(mDataFd);
393         mDataFd = -1;
394     }
395 }
396 
startFilteringData(int writeFd,const IncidentReportArgs & args)397 status_t ReportFile::startFilteringData(int writeFd, const IncidentReportArgs& args) {
398     // Open data file.
399     int dataFd = open(mDataFileName.c_str(), O_RDONLY | O_CLOEXEC);
400     if (dataFd < 0) {
401         ALOGW("Error opening incident report '%s' %s", getDataFileName().c_str(), strerror(-errno));
402         close(writeFd);
403         return -errno;
404     }
405 
406     // Check that the size on disk is what we thought we wrote.
407     struct stat st;
408     if (fstat(dataFd, &st) != 0) {
409         ALOGW("Error running fstat incident report '%s' %s", getDataFileName().c_str(),
410               strerror(-errno));
411         close(writeFd);
412         return -errno;
413     }
414     if (st.st_size != mEnvelope.data_file_size()) {
415         ALOGW("File size mismatch. Envelope says %" PRIi64 " bytes but data file is %" PRIi64
416               " bytes: %s",
417               (int64_t)mEnvelope.data_file_size(), st.st_size, mDataFileName.c_str());
418         ALOGW("Removing incident report");
419         mWorkDirectory->remove(this);
420         close(writeFd);
421         return BAD_VALUE;
422     }
423 
424     pid_t zipPid = 0;
425     if (args.gzip()) {
426         Fpipe zipPipe;
427         if (!zipPipe.init()) {
428             ALOGE("[ReportFile] Failed to setup pipe for gzip");
429             close(writeFd);
430             return -errno;
431         }
432         int status = 0;
433         zipPid = fork_execute_cmd((char* const*)GZIP, zipPipe.readFd().release(), writeFd, &status);
434         close(writeFd);
435         if (zipPid < 0 || status != 0) {
436             ALOGE("[ReportFile] Failed to fork and exec gzip");
437             return status;
438         }
439         writeFd = zipPipe.writeFd().release();
440     }
441 
442     status_t err;
443 
444     for (const auto& report : mEnvelope.report()) {
445         for (const auto& header : report.header()) {
446            write_header_section(writeFd,
447                reinterpret_cast<const uint8_t*>(header.c_str()), header.size());
448         }
449     }
450 
451     if (mEnvelope.has_metadata()) {
452         write_section(writeFd, FIELD_ID_INCIDENT_METADATA, mEnvelope.metadata());
453     }
454 
455     err = filter_and_write_report(writeFd, dataFd, mEnvelope.privacy_policy(), args);
456     if (err != NO_ERROR) {
457         ALOGW("Error writing incident report '%s' to dropbox: %s", getDataFileName().c_str(),
458                 strerror(-err));
459     }
460 
461     close(writeFd);
462     if (zipPid > 0) {
463         status_t err = wait_child(zipPid, /* timeout_ms= */ 10 * 1000);
464         if (err != 0) {
465             ALOGE("[ReportFile] abnormal child process: %s", strerror(-err));
466         }
467         return err;
468     }
469     return NO_ERROR;
470 }
471 
getDataFileName() const472 string ReportFile::getDataFileName() const {
473     return mDataFileName;
474 }
475 
getEnvelopeFileName() const476 string ReportFile::getEnvelopeFileName() const {
477     return mEnvelopeFileName;
478 }
479 
getDataFileFd()480 int ReportFile::getDataFileFd() {
481     return mDataFd;
482 }
483 
setWriteError(status_t err)484 void ReportFile::setWriteError(status_t err) {
485     mError = err;
486 }
487 
getWriteError()488 status_t ReportFile::getWriteError() {
489     return mError;
490 }
491 
getId()492 string ReportFile::getId() {
493     return to_string(mTimestampNs);
494 }
495 
save_envelope_impl(bool cleanup)496 status_t ReportFile::save_envelope_impl(bool cleanup) {
497     status_t err;
498     err = write_proto(mEnvelope, mEnvelopeFileName);
499     if (err != NO_ERROR) {
500         // If there was an error writing the envelope, then delete the whole thing.
501         if (cleanup) {
502             mWorkDirectory->remove(this);
503         }
504         return err;
505     }
506     return NO_ERROR;
507 }
508 
load_envelope_impl(bool cleanup)509 status_t ReportFile::load_envelope_impl(bool cleanup) {
510     status_t err;
511     err = read_proto(&mEnvelope, mEnvelopeFileName);
512     if (err != NO_ERROR) {
513         // If there was an error reading the envelope, then delete the whole thing.
514         if (cleanup) {
515             mWorkDirectory->remove(this);
516         }
517         return err;
518     }
519     return NO_ERROR;
520 }
521 
522 
523 
524 // ================================================================================
525 //
526 
WorkDirectory()527 WorkDirectory::WorkDirectory()
528         :mDirectory("/data/misc/incidents"),
529          mMaxFileCount(100),
530          mMaxDiskUsageBytes(100 * 1024 * 1024) {  // Incident reports can take up to 100MB on disk.
531                                                  // TODO: Should be a flag.
532     create_directory(mDirectory.c_str());
533 }
534 
WorkDirectory(const string & dir,int maxFileCount,long maxDiskUsageBytes)535 WorkDirectory::WorkDirectory(const string& dir, int maxFileCount, long maxDiskUsageBytes)
536         :mDirectory(dir),
537          mMaxFileCount(maxFileCount),
538          mMaxDiskUsageBytes(maxDiskUsageBytes) {
539     create_directory(mDirectory.c_str());
540 }
541 
createReportFile()542 sp<ReportFile> WorkDirectory::createReportFile() {
543     unique_lock<mutex> lock(mLock);
544     status_t err;
545 
546     clean_directory_locked();
547 
548     int64_t timestampNs = make_timestamp_ns_locked();
549     string envelopeFileName = make_filename(timestampNs, EXTENSION_ENVELOPE);
550     string dataFileName = make_filename(timestampNs, EXTENSION_DATA);
551 
552     sp<ReportFile> result = new ReportFile(this, timestampNs, envelopeFileName, dataFileName);
553 
554     err = result->trySaveEnvelope();
555     if (err != NO_ERROR) {
556         ALOGW("Can't save envelope file %s: %s", strerror(-errno), envelopeFileName.c_str());
557         return nullptr;
558     }
559 
560     return result;
561 }
562 
getReports(vector<sp<ReportFile>> * result,int64_t after)563 status_t WorkDirectory::getReports(vector<sp<ReportFile>>* result, int64_t after) {
564     unique_lock<mutex> lock(mLock);
565 
566     const bool DBG = true;
567 
568     if (DBG) {
569         ALOGD("WorkDirectory::getReports");
570     }
571 
572     map<string,WorkDirectoryEntry> files;
573     get_directory_contents_locked(&files, after);
574     for (map<string,WorkDirectoryEntry>::iterator it = files.begin();
575             it != files.end(); it++) {
576         sp<ReportFile> reportFile = new ReportFile(this, it->second.timestampNs,
577                 it->second.envelope, it->second.data);
578         if (DBG) {
579             ALOGD("  %s", reportFile->getId().c_str());
580         }
581         result->push_back(reportFile);
582     }
583     return NO_ERROR;
584 }
585 
getReport(const string & pkg,const string & cls,const string & id,IncidentReportArgs * args)586 sp<ReportFile> WorkDirectory::getReport(const string& pkg, const string& cls, const string& id,
587             IncidentReportArgs* args) {
588     unique_lock<mutex> lock(mLock);
589 
590     status_t err;
591     int64_t timestampNs;
592     if (!parse_timestamp_ns(id, &timestampNs)) {
593         return nullptr;
594     }
595 
596     // Make the ReportFile object, and then see if it's valid and for pkg and cls.
597     sp<ReportFile> result = new ReportFile(this, timestampNs,
598             make_filename(timestampNs, EXTENSION_ENVELOPE),
599             make_filename(timestampNs, EXTENSION_DATA));
600 
601     err = result->tryLoadEnvelope();
602     if (err != NO_ERROR) {
603         ALOGW("Can't open envelope file for report %s/%s %s", pkg.c_str(), cls.c_str(), id.c_str());
604         return nullptr;
605     }
606 
607     const ReportFileProto& envelope = result->getEnvelope();
608     const size_t reportCount = envelope.report_size();
609     for (int i = 0; i < reportCount; i++) {
610         const ReportFileProto_Report& report = envelope.report(i);
611         if (report.pkg() == pkg && report.cls() == cls) {
612             if (args != nullptr) {
613                 get_args_from_report(args, report);
614             }
615             return result;
616         }
617 
618     }
619 
620     return nullptr;
621 }
622 
hasMore(int64_t after)623 bool WorkDirectory::hasMore(int64_t after) {
624     unique_lock<mutex> lock(mLock);
625 
626     map<string,WorkDirectoryEntry> files;
627     get_directory_contents_locked(&files, after);
628     return files.size() > 0;
629 }
630 
commit(const sp<ReportFile> & report,const string & pkg,const string & cls)631 void WorkDirectory::commit(const sp<ReportFile>& report, const string& pkg, const string& cls) {
632     status_t err;
633     ALOGI("Committing report %s for %s/%s", report->getId().c_str(), pkg.c_str(), cls.c_str());
634 
635     unique_lock<mutex> lock(mLock);
636 
637     // Load the envelope here inside the lock.
638     err = report->loadEnvelope();
639 
640     report->removeReport(pkg, cls);
641 
642     delete_files_for_report_if_necessary(report);
643 }
644 
commitAll(const string & pkg)645 void WorkDirectory::commitAll(const string& pkg) {
646     status_t err;
647     ALOGI("All reports for %s", pkg.c_str());
648 
649     unique_lock<mutex> lock(mLock);
650 
651     map<string,WorkDirectoryEntry> files;
652     get_directory_contents_locked(&files, 0);
653 
654     for (map<string,WorkDirectoryEntry>::iterator it = files.begin();
655             it != files.end(); it++) {
656         sp<ReportFile> reportFile = new ReportFile(this, it->second.timestampNs,
657                 it->second.envelope, it->second.data);
658 
659         err = reportFile->loadEnvelope();
660         if (err != NO_ERROR) {
661             continue;
662         }
663 
664         reportFile->removeReports(pkg);
665 
666         delete_files_for_report_if_necessary(reportFile);
667     }
668 }
669 
remove(const sp<ReportFile> & report)670 void WorkDirectory::remove(const sp<ReportFile>& report) {
671     unique_lock<mutex> lock(mLock);
672     // Set this to false to leave files around for debugging.
673     if (DO_UNLINK) {
674         unlink(report->getDataFileName().c_str());
675         unlink(report->getEnvelopeFileName().c_str());
676     }
677 }
678 
make_timestamp_ns_locked()679 int64_t WorkDirectory::make_timestamp_ns_locked() {
680     // Guarantee that we don't have duplicate timestamps.
681     // This is a little bit lame, but since reports are created on the
682     // same thread and are kinda slow we'll seldomly actually hit the
683     // condition.  The bigger risk is the clock getting reset and causing
684     // a collision.  In that case, we'll just make incident reporting a
685     // little bit slower.  Nobody will notice if we just loop until we
686     // have a unique file name.
687     int64_t timestampNs = 0;
688     do {
689         struct timespec spec;
690         if (timestampNs > 0) {
691             spec.tv_sec = 0;
692             spec.tv_nsec = 1;
693             nanosleep(&spec, nullptr);
694         }
695         clock_gettime(CLOCK_REALTIME, &spec);
696         timestampNs = int64_t(spec.tv_sec) * 1000 + spec.tv_nsec;
697     } while (file_exists_locked(timestampNs));
698     return (timestampNs >= 0)? timestampNs : -timestampNs;
699 }
700 
701 /**
702  * It is required to hold the lock here so in case someone else adds it
703  * our result is still correct for the caller.
704  */
file_exists_locked(int64_t timestampNs)705 bool WorkDirectory::file_exists_locked(int64_t timestampNs) {
706     const string filename = make_filename(timestampNs, EXTENSION_ENVELOPE);
707     struct stat st;
708     return stat(filename.c_str(), &st) == 0;
709 }
710 
make_filename(int64_t timestampNs,const string & extension)711 string WorkDirectory::make_filename(int64_t timestampNs, const string& extension) {
712     // Zero pad the timestamp so it can also be alpha sorted.
713     stringstream result;
714     result << mDirectory << '/' << setfill('0') << setw(20) << timestampNs << extension;
715     return result.str();
716 }
717 
get_directory_contents_locked(map<string,WorkDirectoryEntry> * files,int64_t after)718 off_t WorkDirectory::get_directory_contents_locked(map<string,WorkDirectoryEntry>* files,
719         int64_t after) {
720     DIR* dir;
721     struct dirent* entry;
722 
723     if ((dir = opendir(mDirectory.c_str())) == NULL) {
724         ALOGE("Couldn't open incident directory: %s", mDirectory.c_str());
725         return -1;
726     }
727 
728     string dirbase(mDirectory);
729     if (mDirectory[dirbase.size() - 1] != '/') dirbase += "/";
730 
731     off_t totalSize = 0;
732 
733     // Enumerate, count and add up size
734     while ((entry = readdir(dir)) != NULL) {
735         if (entry->d_name[0] == '.') {
736             continue;
737         }
738         string entryname = entry->d_name;  // local to this dir
739         string filename = dirbase + entryname;  // fully qualified
740 
741         bool isEnvelope = ends_with(entryname, EXTENSION_ENVELOPE);
742         bool isData = ends_with(entryname, EXTENSION_DATA);
743 
744         // If the file isn't one of our files, just ignore it.  Otherwise,
745         // sum up the sizes.
746         if (isEnvelope || isData) {
747             string timestamp = strip_extension(entryname);
748 
749             int64_t timestampNs;
750             if (!parse_timestamp_ns(timestamp, &timestampNs)) {
751                 continue;
752             }
753 
754             if (after == 0 || timestampNs > after) {
755                 struct stat st;
756                 if (stat(filename.c_str(), &st) != 0) {
757                     ALOGE("Unable to stat file %s", filename.c_str());
758                     continue;
759                 }
760                 if (!S_ISREG(st.st_mode)) {
761                     continue;
762                 }
763 
764                 WorkDirectoryEntry& entry = (*files)[timestamp];
765                 if (isEnvelope) {
766                     entry.envelope = filename;
767                 } else if (isData) {
768                     entry.data = filename;
769                 }
770                 entry.timestampNs = timestampNs;
771                 entry.size += st.st_size;
772                 totalSize += st.st_size;
773             }
774         }
775     }
776 
777     closedir(dir);
778 
779     // Now check if there are any data files that don't have envelope files.
780     // If there are, then just go ahead and delete them now.  Don't wait for
781     // a cleaning.
782 
783     if (DO_UNLINK) {
784         map<string,WorkDirectoryEntry>::iterator it = files->begin();
785         while (it != files->end()) {
786             if (it->second.envelope.length() == 0) {
787                 unlink(it->second.data.c_str());
788                 it = files->erase(it);
789             } else {
790                 it++;
791             }
792         }
793     }
794 
795     return totalSize;
796 }
797 
clean_directory_locked()798 void WorkDirectory::clean_directory_locked() {
799     DIR* dir;
800     struct dirent* entry;
801     struct stat st;
802 
803     // Map of filename without extension to the entries about it.  Conveniently,
804     // this also keeps the list sorted by filename, which is a timestamp.
805     map<string,WorkDirectoryEntry> files;
806     off_t totalSize = get_directory_contents_locked(&files, 0);
807     if (totalSize < 0) {
808         return;
809     }
810     int totalCount = files.size();
811 
812     // Count or size is less than max, then we're done.
813     if (totalSize < mMaxDiskUsageBytes && totalCount < mMaxFileCount) {
814         return;
815     }
816 
817     // Remove files until we're under our limits.
818     if (DO_UNLINK) {
819         for (map<string, WorkDirectoryEntry>::const_iterator it = files.begin();
820                 it != files.end() && (totalSize >= mMaxDiskUsageBytes
821                     || totalCount >= mMaxFileCount);
822                 it++) {
823             unlink(it->second.envelope.c_str());
824             unlink(it->second.data.c_str());
825             totalSize -= it->second.size;
826             totalCount--;
827         }
828     }
829 }
830 
delete_files_for_report_if_necessary(const sp<ReportFile> & report)831 void WorkDirectory::delete_files_for_report_if_necessary(const sp<ReportFile>& report) {
832     if (report->getEnvelope().report_size() == 0) {
833         ALOGI("Report %s is finished. Deleting from storage.", report->getId().c_str());
834         if (DO_UNLINK) {
835             unlink(report->getDataFileName().c_str());
836             unlink(report->getEnvelopeFileName().c_str());
837         }
838     }
839 }
840 
841 // ================================================================================
get_args_from_report(IncidentReportArgs * out,const ReportFileProto_Report & report)842 void get_args_from_report(IncidentReportArgs* out, const ReportFileProto_Report& report) {
843     out->setPrivacyPolicy(report.privacy_policy());
844     out->setAll(report.all_sections());
845     out->setReceiverPkg(report.pkg());
846     out->setReceiverCls(report.cls());
847     out->setGzip(report.gzip());
848 
849     const int sectionCount = report.section_size();
850     for (int i = 0; i < sectionCount; i++) {
851         out->addSection(report.section(i));
852     }
853 
854     const int headerCount = report.header_size();
855     for (int i = 0; i < headerCount; i++) {
856         const string& header  = report.header(i);
857         vector<uint8_t> vec(header.begin(), header.end());
858         out->addHeader(vec);
859     }
860 }
861 
862 
863 }  // namespace incidentd
864 }  // namespace os
865 }  // namespace android
866 
867