1 //
2 // Copyright (C) 2017 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 #ifndef UPDATE_ENGINE_PAYLOAD_CONSUMER_CACHED_FILE_DESCRIPTOR_H_
18 #define UPDATE_ENGINE_PAYLOAD_CONSUMER_CACHED_FILE_DESCRIPTOR_H_
19 
20 #include <errno.h>
21 #include <sys/types.h>
22 
23 #include <memory>
24 #include <vector>
25 
26 #include <brillo/secure_blob.h>
27 
28 #include "update_engine/payload_consumer/file_descriptor.h"
29 
30 namespace chromeos_update_engine {
31 
32 class CachedFileDescriptor : public FileDescriptor {
33  public:
CachedFileDescriptor(FileDescriptorPtr fd,size_t cache_size)34   CachedFileDescriptor(FileDescriptorPtr fd, size_t cache_size) : fd_(fd) {
35     cache_.resize(cache_size);
36   }
37   ~CachedFileDescriptor() override = default;
38 
Open(const char * path,int flags,mode_t mode)39   bool Open(const char* path, int flags, mode_t mode) override {
40     return fd_->Open(path, flags, mode);
41   }
Open(const char * path,int flags)42   bool Open(const char* path, int flags) override {
43     return fd_->Open(path, flags);
44   }
Read(void * buf,size_t count)45   ssize_t Read(void* buf, size_t count) override {
46     return fd_->Read(buf, count);
47   }
48   ssize_t Write(const void* buf, size_t count) override;
49   off64_t Seek(off64_t offset, int whence) override;
BlockDevSize()50   uint64_t BlockDevSize() override { return fd_->BlockDevSize(); }
BlkIoctl(int request,uint64_t start,uint64_t length,int * result)51   bool BlkIoctl(int request,
52                 uint64_t start,
53                 uint64_t length,
54                 int* result) override {
55     return fd_->BlkIoctl(request, start, length, result);
56   }
57   bool Flush() override;
58   bool Close() override;
IsSettingErrno()59   bool IsSettingErrno() override { return fd_->IsSettingErrno(); }
IsOpen()60   bool IsOpen() override { return fd_->IsOpen(); }
61 
62  private:
63   // Internal flush without the need to call |fd_->Flush()|.
64   bool FlushCache();
65 
66   FileDescriptorPtr fd_;
67   brillo::Blob cache_;
68   size_t bytes_cached_{0};
69   off64_t offset_{0};
70 
71   DISALLOW_COPY_AND_ASSIGN(CachedFileDescriptor);
72 };
73 
74 }  // namespace chromeos_update_engine
75 
76 #endif  // UPDATE_ENGINE_PAYLOAD_CONSUMER_CACHED_FILE_DESCRIPTOR_H_
77