|
|
1.1 root 1: //
2: // nono
3: // Copyright (C) 2021 nono project
4: // Licensed under nono-license.txt
5: //
6:
7: //
8: // ディスクイメージ (生イメージ形式)
9: //
10:
11: #include "diskimage_raw.h"
12: #include <fcntl.h>
13: #include <sys/stat.h>
14:
15: // コンストラクタ
16: DiskImageRaw::DiskImageRaw(const std::string& pathname_)
1.1.1.2 root 17: : inherited(pathname_)
1.1 root 18: {
19: }
20:
21: // デストラクタ
22: DiskImageRaw::~DiskImageRaw()
23: {
24: }
25:
1.1.1.5 ! root 26: // このディスクイメージが書き込み可能かどうかを返す。
1.1 root 27: // Open() 前でも動作する。
1.1.1.5 ! root 28: int
! 29: DiskImageRaw::IsWriteable() const
1.1 root 30: {
1.1.1.5 ! root 31: int rv;
! 32:
1.1.1.4 root 33: // ファイルのパーミッション
34: int r = access(pathname.c_str(), W_OK);
35: if (r == 0) {
1.1.1.5 ! root 36: rv = 1;
1.1.1.4 root 37: } else if (errno == EACCES) {
1.1.1.5 ! root 38: rv = 0;
1.1.1.4 root 39: } else {
40: if (errno == ENOENT) {
41: warn("%s", pathname.c_str());
42: } else {
43: warn("%s: access failed", pathname.c_str());
44: }
1.1.1.5 ! root 45: rv = -1;
1.1 root 46: }
47:
1.1.1.5 ! root 48: return rv;
1.1 root 49: }
50:
51: // オープン
52: bool
53: DiskImageRaw::Open(bool read_only)
54: {
55: int openmode;
56:
57: assert(pathname.empty() == false);
58:
59: if (read_only) {
60: openmode = O_RDONLY;
61: } else {
62: openmode = O_RDWR;
63: }
64:
65: fd = open(pathname.c_str(), openmode);
66: if (fd < 0) {
67: warn("%s", pathname.c_str());
68: return false;
69: }
70:
1.1.1.5 ! root 71: // ファイルサイズを取得
! 72: struct stat st;
! 73: if (fstat(fd, &st) < 0) {
! 74: warn("%s: stat failed", pathname.c_str());
! 75: fd.Close();
! 76: return false;
1.1 root 77: }
1.1.1.5 ! root 78: filesize = st.st_size;
1.1 root 79:
80: return true;
81: }
82:
1.1.1.2 root 83: void
84: DiskImageRaw::Close()
85: {
86: fd.Close();
1.1.1.5 ! root 87: filesize = 0;
1.1.1.2 root 88: }
89:
1.1 root 90: bool
91: DiskImageRaw::Read(void *buf, off_t offset, size_t size)
92: {
93: if (__predict_false(fd < 0)) {
94: return false;
95: }
1.1.1.3 root 96: if (__predict_false(offset + size > GetSize())) {
1.1.1.2 root 97: return false;
98: }
99:
100: if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
101: return false;
102: }
1.1 root 103:
1.1.1.2 root 104: if (read(fd, buf, size) < 0) {
105: return false;
106: }
1.1 root 107: return true;
108: }
109:
110: bool
111: DiskImageRaw::Write(const void *buf, off_t offset, size_t size)
112: {
113: if (__predict_false(fd < 0)) {
114: return false;
115: }
1.1.1.3 root 116: if (__predict_false(offset + size > GetSize())) {
1.1.1.2 root 117: return false;
118: }
1.1 root 119:
1.1.1.2 root 120: if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
121: return false;
1.1 root 122: }
123:
1.1.1.2 root 124: if (write(fd, buf, size) < 0) {
125: return false;
126: }
127: return true;
1.1 root 128: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.