rspangler@google.com | 49fdf18 | 2009-10-10 00:57:34 +0000 | [diff] [blame^] | 1 | // Copyright (c) 2009 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef UPDATE_ENGINE_FILE_WRITER_H__ |
| 6 | #define UPDATE_ENGINE_FILE_WRITER_H__ |
| 7 | |
| 8 | #include <sys/types.h> |
| 9 | #include <sys/stat.h> |
| 10 | #include <fcntl.h> |
| 11 | #include <unistd.h> |
| 12 | #include "glog/logging.h" |
| 13 | |
| 14 | // FileWriter is a class that is used to (synchronously, for now) write to |
| 15 | // a file. This file is a thin wrapper around open/write/close system calls, |
| 16 | // but provides and interface that can be customized by subclasses that wish |
| 17 | // to filter the data. |
| 18 | |
| 19 | namespace chromeos_update_engine { |
| 20 | |
| 21 | class FileWriter { |
| 22 | public: |
| 23 | virtual ~FileWriter() {} |
| 24 | |
| 25 | // Wrapper around open. Returns 0 on success or -errno on error. |
| 26 | virtual int Open(const char* path, int flags, mode_t mode) = 0; |
| 27 | |
| 28 | // Wrapper around write. Returns bytes written on success or |
| 29 | // -errno on error. |
| 30 | virtual int Write(const void* bytes, size_t count) = 0; |
| 31 | |
| 32 | // Wrapper around close. Returns 0 on success or -errno on error. |
| 33 | virtual int Close() = 0; |
| 34 | }; |
| 35 | |
| 36 | // Direct file writer is probably the simplest FileWriter implementation. |
| 37 | // It calls the system calls directly. |
| 38 | |
| 39 | class DirectFileWriter : public FileWriter { |
| 40 | public: |
| 41 | DirectFileWriter() : fd_(-1) {} |
| 42 | virtual ~DirectFileWriter() {} |
| 43 | |
| 44 | virtual int Open(const char* path, int flags, mode_t mode) { |
| 45 | CHECK_EQ(-1, fd_); |
| 46 | fd_ = open(path, flags, mode); |
| 47 | if (fd_ < 0) |
| 48 | return -errno; |
| 49 | return 0; |
| 50 | } |
| 51 | |
| 52 | virtual int Write(const void* bytes, size_t count) { |
| 53 | CHECK_GE(fd_, 0); |
| 54 | ssize_t rc = write(fd_, bytes, count); |
| 55 | if (rc < 0) |
| 56 | return -errno; |
| 57 | return rc; |
| 58 | } |
| 59 | |
| 60 | virtual int Close() { |
| 61 | CHECK_GE(fd_, 0); |
| 62 | int rc = close(fd_); |
| 63 | |
| 64 | // This can be any negative number that's not -1. This way, this FileWriter |
| 65 | // won't be used again for another file. |
| 66 | fd_ = -2; |
| 67 | |
| 68 | if (rc < 0) |
| 69 | return -errno; |
| 70 | return rc; |
| 71 | } |
| 72 | |
| 73 | private: |
| 74 | int fd_; |
| 75 | }; |
| 76 | |
| 77 | } // namespace chromeos_update_engine |
| 78 | |
| 79 | #endif // UPDATE_ENGINE_FILE_WRITER_H__ |