1 /*
2  * Copyright (C) 2023 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 <limits.h>
18 #include <string.h>
19 #include <sys/inotify.h>
20 #include <unistd.h>
21 #include <string>
22 #include <vector>
23 
24 #include <android-base/logging.h>
25 
26 #include "inotify.h"
27 
28 namespace cuttlefish {
29 
GetCreatedFileListFromInotifyFd(int fd)30 std::vector<std::string> GetCreatedFileListFromInotifyFd(int fd) {
31   return GetFileListFromInotifyFd(fd, IN_CREATE);
32 }
33 
34 #define INOTIFY_MAX_EVENT_SIZE (sizeof(struct inotify_event) + NAME_MAX + 1)
35 
GetFileListFromInotifyFd(int fd,uint32_t mask)36 std::vector<std::string> GetFileListFromInotifyFd(int fd, uint32_t mask) {
37   char event_readout[INOTIFY_MAX_EVENT_SIZE];
38   int bytes_parsed = 0;
39   std::vector<std::string> result;
40   // Each successful read can contain one or more of inotify_event events
41   // Note: read() on inotify returns 'whole' events, will never partially
42   // populate the buffer.
43   int event_read_out_length = read(fd, event_readout, INOTIFY_MAX_EVENT_SIZE);
44 
45   if (event_read_out_length == -1) {
46     LOG(ERROR) << __FUNCTION__
47                << ": Couldn't read out inotify event due to error: '"
48                << strerror(errno) << "' (" << errno << ")";
49     return std::vector<std::string>();
50   }
51 
52   while (bytes_parsed < event_read_out_length) {
53     struct inotify_event* event =
54         reinterpret_cast<inotify_event*>(event_readout + bytes_parsed);
55     bytes_parsed += sizeof(struct inotify_event) + event->len;
56 
57     // No file name was present
58     if (event->len == 0) {
59       LOG(ERROR) << __FUNCTION__ << ": inotify event didn't contain filename";
60       continue;
61     }
62     if (!(event->mask & mask)) {
63       LOG(ERROR) << __FUNCTION__
64                  << ": inotify event didn't pertain to the event";
65       continue;
66     }
67     result.push_back(std::string(event->name));
68   }
69 
70   return result;
71 }
72 
73 }  // namespace cuttlefish
74