Debian Codegraph @

src/uk/me/parabola/imgfmt/sys/FileNode.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: 03-Dec-2006
16 */
17 package uk.me.parabola.imgfmt.sys;
18
19 import java.io.Closeable;
20 import java.io.IOException;
21 import java.nio.ByteBuffer;
22 import java.nio.channels.AsynchronousCloseException;
23 import java.nio.channels.ClosedByInterruptException;
24 import java.nio.channels.ClosedChannelException;
25 import java.nio.channels.FileChannel;
26 import java.nio.channels.NonReadableChannelException;
27 import java.nio.channels.NonWritableChannelException;
28
29 import uk.me.parabola.imgfmt.Sized;
30 import uk.me.parabola.imgfmt.fs.ImgChannel;
31 import uk.me.parabola.log.Logger;
32
33 /**
34 * The internal representation of a file in the file system. In use it
35 * should only be referred to by the {@link ImgChannel} interface.
36 *
37 * @author Steve Ratcliffe
38 */
39 public class FileNode implements ImgChannel, FileLink {
40 private static final Logger log = Logger.getLogger(FileNode.class);
41
42 private boolean open;
43 private boolean writeable;
44 private boolean readable;
45
46 private final FileChannel file;
47 private final BlockManager blockManager;
48 private final Dirent dirent;
49
50 // The position in this file
51 private long position;
52
53 private byte xorByte;
54 private Closeable outerClose;
55
56 /**
57 * Creates a new file in the file system. You can treat this just like
58 * a regular file and write or read from it.
59 * Operations to two different files may not be interleaved although
60 * it may be possible to implement this.
61 *
62 * @param file The handle to the underlying file.
63 * @param dir The directory entry associated with this file.
64 * @param mode The mode "rw" for read and write etc.
65 */
66 public FileNode(FileChannel file, Dirent dir, String mode)
67 {
68 this.file = file;
69 this.dirent = dir;
70
71 if (mode.indexOf('r') >= 0)
72 readable = true;
73 if (mode.indexOf('w') >= 0)
74 writeable = true;
75 if (!(readable || writeable))
76 throw new IllegalArgumentException("File must be readable or writeable");
77
78 blockManager = dir.getBlockManager();
79 if (blockManager == null)
80 throw new IllegalArgumentException("no file system supplied");
81
82 open = true;
83 }
84
85 /**
86 * Closes this channel.
87 * <p/>
88 * <p> After a channel is closed, any further attempt to invoke I/O
89 * operations upon it will cause a {@link ClosedChannelException} to be
90 * thrown.
91 * <p/>
92 * <p> If this channel is already closed then invoking this method has no
93 * effect.
94 * <p/>
95 * <p> This method may be invoked at any time. If some other thread has
96 * already invoked it, however, then another invocation will block until
97 * the first invocation is complete, after which it will return without
98 * effect. </p>
99 *
100 * @throws IOException If an I/O error occurs
101 */
102 public void close() throws IOException {
103 if (!open)
104 return;
105
106 if (writeable && outerClose != null)
107 outerClose.close();
108
109 sync();
110
111 open = false;
112 readable = false;
113 writeable = false;
114 }
115
116 /**
117 * Tells whether or not this channel is open. </p>
118 *
119 * @return <tt>true</tt> if, and only if, this channel is open
120 */
121 public boolean isOpen() {
122 return open;
123 }
124
125 /**
126 * Reads a sequence of bytes from this channel into the given buffer.
127 *
128 * @param dst The buffer into which bytes are to be transferred
129 *
130 * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
131 * channel has reached end-of-stream
132 *
133 * @throws NonReadableChannelException If this channel was not opened for reading
134 * @throws ClosedChannelException If this channel is closed
135 * @throws AsynchronousCloseException If another thread closes this channel
136 * while the read operation is in progress
137 * @throws ClosedByInterruptException If another thread interrupts the
138 * current thread while the read operation is in progress, thereby closing
139 * the channel and setting the current thread's interrupt status
140 * @throws IOException If some other I/O error occurs
141 */
142 public int read(ByteBuffer dst) throws IOException {
143 if (!open)
144 throw new ClosedChannelException();
145 if (!readable)
146 throw new NonReadableChannelException();
147
148 int blockSize = blockManager.getBlockSize();
149
150 long size = dst.remaining();
151 long fileSize = dirent.getSize();
152 if (position >= fileSize)
153 return -1;
154 size = Math.min(size, fileSize - position);
155
156 int totalRead = 0;
157
158 while (size > 0) {
159 // Tet the logical block number, as we see it in our file.
160 int lblock = (int) (position / blockSize);
161
162 // Get the physical block number, the actual block number in
163 // the underlying file.
164 int pblock = dirent.getPhysicalBlock(lblock);
165 if (pblock == 0xffff) {
166 // We are at the end of the file.
167 log.debug("at eof");
168 break;
169 }
170
171 // Position the underlying file
172 int off = (int) (position - lblock*blockSize);
173 file.position((long) pblock * blockSize + off);
174
175 int n = (int) size;
176 if (n > blockSize)
177 n = blockSize;
178
179 if (off != 0)
180 n = Math.min(n, blockSize - off);
181
182 dst.limit(dst.position() + n);
183
184 int pos = dst.position();
185 int nr = file.read(dst);
186 if (nr == -1)
187 return -1;
188 if (nr == 0)
189 throw new IOException("Read nothing");
190
191 if(xorByte != 0) {
192 byte[] bufBytes = dst.array();
193 for(int i = pos + n - 1; i >= pos; --i)
194 bufBytes[i] ^= xorByte;
195 }
196
197 // Update the file positions
198 size -= nr;
199 position += nr;
200 totalRead += nr;
201 }
202
203 log.debug("read ret", totalRead);
204 return totalRead;
205 }
206
207 /**
208 * Writes a sequence of bytes to this channel from the given buffer.
209 * <p/>
210 * <p> An attempt is made to write up to <i>r</i> bytes to the channel,
211 * where <i>r</i> is the number of bytes remaining in the buffer, that is,
212 * <tt>dst.remaining()</tt>, at the moment this method is invoked.
213 * <p>The logical block has to be converted to a physical block in the
214 * underlying file.
215 *
216 * @param src The buffer from which bytes are to be retrieved
217 * @return The number of bytes written, possibly zero
218 * @throws NonWritableChannelException
219 * If this channel was not opened for writing
220 * @throws ClosedChannelException
221 * If this channel is closed
222 * @throws IOException If some other I/O error occurs
223 */
224 public int write(ByteBuffer src) throws IOException {
225 if (!open)
226 throw new ClosedChannelException();
227
228 int blockSize = blockManager.getBlockSize();
229
230 // Get the size of this write
231 int size = src.remaining();
232
233 // Loop over each block, this is to support the case (which we may
234 // not implement) of non-contiguous blocks.
235
236 int totalWritten = 0;
237 while (size > 0) {
238 // Get the logical block, ie the block as we see it in our file.
239 int lblock = (int) (position/blockSize);
240
241 // First need to allocate enough blocks for this write. First check
242 // if the block exists already
243 int pblock = dirent.getPhysicalBlock(lblock);
244 log.debug("lblock / pblock", lblock, '/', pblock);
245 if (pblock == 0xffff) {
246 log.debug("allocating new block");
247 pblock = blockManager.allocate();
248 dirent.addBlock(pblock);
249 }
250
251 // Position the underlying file, so that it is in the correct place.
252 int off = (int) (position - lblock*blockSize);
253 file.position((long) pblock * blockSize + off);
254
255 int n = size;
256 if (n > blockSize)
257 n = blockSize;
258
259 if (off != 0)
260 n = Math.min(n, blockSize - off);
261
262 src.limit(src.position() + n);
263
264 // Write to the underlying file.
265 int nw = file.write(src);
266 if (nw == 0)
267 throw new IOException("Wrote nothing");
268
269 // Update the file positions
270 size -= nw;
271 position += nw;
272 totalWritten += nw;
273
274 // Update file size.
275 if (position > dirent.getSize())
276 dirent.setSize((int) position);
277 }
278
279 return totalWritten;
280 }
281
282 public long position() {
283 return position;
284 }
285
286 public void position(long pos) {
287 int blockSize = blockManager.getBlockSize();
288
289 while (pos > position) {
290 long lblock = position / blockSize;
291 int pblock = dirent.getPhysicalBlock((int) lblock);
292
293 if (pblock == 0xffff) {
294 if (writeable) {
295 log.debug("setting position allocating new block", lblock);
296 pblock = blockManager.allocate();
297 dirent.addBlock(pblock);
298 }
299 }
300 position = (lblock+1) * blockSize;
301 }
302
303 this.position = pos;
304 }
305
306 public void link(Sized source, Closeable closeable) {
307 dirent.setSizeSource(source);
308 outerClose = closeable;
309 }
310
311 public long getSize() {
312 return dirent.getSize();
313 }
314
315 /**
316 * Write out any unsaved data to disk.
317 *
318 * @throws IOException If there is an error writing to disk.
319 */
320 private void sync() throws IOException {
321 if (!writeable)
322 return;
323
324 // Ensure that a complete block is written out.
325 int bs = blockManager.getBlockSize();
326 long rem = bs - (file.position() % bs);
327
328 ByteBuffer buf = ByteBuffer.allocate(blockManager.getBlockSize());
329
330 // Complete any partial block.
331 for (int i = 0; i < rem; i++)
332 buf.put((byte) 0);
333
334 buf.flip();
335 file.write(buf);
336 }
337
338 public void setXorByte(byte xorByte) {
339 this.xorByte = xorByte;
340 }
341
342 public String toString() {
343 return String.format("%s %d", dirent.getFullName(), getSize());
344 }
345 }