Debian Codegraph @

src/uk/me/parabola/imgfmt/sys/ImgFS.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: 26-Nov-2006
16 */
17 package uk.me.parabola.imgfmt.sys;
18
19 import java.io.FileNotFoundException;
20 import java.io.IOException;
21 import java.nio.ByteBuffer;
22 import java.nio.ByteOrder;
23 import java.nio.channels.FileChannel;
24 import java.nio.file.OpenOption;
25 import java.nio.file.Paths;
26 import java.nio.file.StandardOpenOption;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 import uk.me.parabola.imgfmt.FileExistsException;
31 import uk.me.parabola.imgfmt.FileNotWritableException;
32 import uk.me.parabola.imgfmt.FileSystemParam;
33 import uk.me.parabola.imgfmt.fs.DirectoryEntry;
34 import uk.me.parabola.imgfmt.fs.FileSystem;
35 import uk.me.parabola.imgfmt.fs.ImgChannel;
36 import uk.me.parabola.log.Logger;
37
38 import static uk.me.parabola.imgfmt.fs.DirectoryEntry.ENTRY_SIZE;
39 import static uk.me.parabola.imgfmt.fs.DirectoryEntry.SLOTS_PER_ENTRY;
40
41 /**
42 * The img file is really a filesystem containing several files.
43 * It is made up of a header, a directory area and a data area which
44 * occur in the filesystem in that order.
45 *
46 * @author steve
47 */
48 public class ImgFS implements FileSystem {
49 private static final Logger log = Logger.getLogger(ImgFS.class);
50
51 // The directory is just like any other file, but with a name of 8+3 spaces
52 static final String DIRECTORY_FILE_NAME = " . ";
53 private static final OpenOption[] OPEN_CREATE_RW = {StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE};
54
55 // This is the read or write channel to the real file system.
56 private final FileChannel file;
57 private boolean readOnly = true;
58
59 // The header contains general information.
60 private ImgHeader header;
61 private FileSystemParam fsparam;
62
63 // There is only one directory that holds all filename and block allocation
64 // information.
65 private Directory directory;
66
67 // The filesystem is responsible for allocating blocks
68 private BlockManager fileBlockManager;
69
70 // The header entries are written in 512 blocks, regardless of the block size of the file itself.
71 private static final long ENTRY_BLOCK_SIZE = 512L;
72 private BlockManager headerBlockManager;
73
74 // Open files for write
75 private final List<FileNode> openNodes = new ArrayList<>();
76
77 // if non-zero, all bytes are XORed with this
78 private byte xorByte;
79
80 /**
81 * Private constructor, use the static {@link #createFs} and {@link #openFs}
82 * routines to make a filesystem.
83 *
84 * @param chan The open file.
85 */
86 private ImgFS(FileChannel chan) {
87 file = chan;
88 }
89
90 /**
91 * Create an IMG file from its external filesystem name and optionally some
92 * parameters.
93 *
94 * @param filename The name of the file to be created.
95 * @param params File system parameters. Can not be null.
96 * @throws FileNotWritableException If the file can not be written to.
97 */
98 public static FileSystem createFs(String filename, FileSystemParam params) throws FileNotWritableException {
99 params.setFilename(filename);
100 try {
101 FileChannel chan = FileChannel.open(Paths.get(filename), OPEN_CREATE_RW);
102 return createFs(chan, params);
103 } catch (IOException e) {
104 throw new FileNotWritableException("Could not create file", e);
105 }
106 }
107
108 private static FileSystem createFs(FileChannel chan, FileSystemParam params)
109 throws FileNotWritableException
110 {
111 assert params != null;
112
113 // Truncate the file, because extra bytes beyond the end make for a
114 // map that doesn't work on the GPS (although its likely to work in
115 // other software viewers).
116 try {
117 chan.truncate(0);
118 } catch (IOException e) {
119 throw new FileNotWritableException("Failed to truncate file", e);
120 }
121
122 ImgFS fs = new ImgFS(chan);
123 fs.createInitFS(chan, params);
124
125 return fs;
126 }
127
128 /**
129 * Open an existing IMG file system.
130 * @param name The file name to open.
131 * @return A File system that can be used lookup the internal files.
132 * @throws FileNotFoundException When the file doesn't exist or can't be
133 * read.
134 */
135 public static FileSystem openFs(String name) throws FileNotFoundException {
136 try {
137 FileChannel chan = FileChannel.open(Paths.get(name), StandardOpenOption.READ);
138 return openFs(name, chan);
139 } catch (IOException e) {
140 throw new FileNotFoundException("Failed to create or open file " + name);
141 }
142 }
143
144 private static FileSystem openFs(String name, FileChannel chan) throws FileNotFoundException {
145 ImgFS fs = new ImgFS(chan);
146
147 try {
148 fs.readInitFS(chan);
149 } catch (IOException e) {
150 throw new FileNotFoundException(name + ": " + e.getMessage());
151 }
152
153 return fs;
154 }
155
156 /**
157 * Create a new file, it must not already exist.
158 *
159 * @param name The file name.
160 * @return A directory entry for the new file.
161 */
162 public ImgChannel create(String name) throws FileExistsException {
163 Dirent dir = directory.create(name, fileBlockManager);
164
165 FileNode node = new FileNode(file, dir, "w");
166 openNodes.add(node);
167 return node;
168 }
169
170 /**
171 * Open a file. The returned file object can be used to read and write the
172 * underlying file.
173 *
174 * @param name The file name to open.
175 * @param mode Either "r" for read access, "w" for write access or "rw"
176 * for both read and write.
177 * @return A file descriptor.
178 * @throws FileNotFoundException When the file does not exist.
179 */
180 public ImgChannel open(String name, String mode) throws FileNotFoundException {
181 if (name == null || mode == null)
182 throw new IllegalArgumentException("null argument");
183
184 if (mode.indexOf('r') >= 0) {
185 Dirent ent = internalLookup(name);
186
187 FileNode fn = new FileNode(file, ent, "r");
188 if(xorByte != 0)
189 fn.setXorByte(xorByte);
190 return fn;
191 } else if (mode.indexOf('w') >= 0) {
192 Dirent ent;
193 try {
194 ent = internalLookup(name);
195 } catch (FileNotFoundException e) {
196 try {
197 ent = directory.create(name, fileBlockManager);
198 } catch (FileExistsException e1) {
199 // This shouldn't happen as we have just checked.
200 throw new FileNotFoundException("Attempt to duplicate a file name");
201 }
202 }
203 FileNode node = new FileNode(file, ent, "w");
204 openNodes.add(node);
205 return node;
206 } else {
207 throw new IllegalArgumentException("Invalid mode given");
208 }
209 }
210
211 /**
212 * Lookup the file and return a directory entry for it.
213 *
214 * @param name The filename to look up.
215 * @return A directory entry.
216 * @throws FileNotFoundException If an error occurs looking for the file,
217 * including it not existing.
218 */
219 public DirectoryEntry lookup(String name) throws FileNotFoundException {
220 return internalLookup(name);
221 }
222
223 /**
224 * List all the files in the directory.
225 *
226 * @return A List of directory entries.
227 */
228 public List<DirectoryEntry> list() {
229 return directory.getEntries();
230 }
231
232 /**
233 * Sync with the underlying file. All unwritten data is written out to
234 * the underlying file.
235 *
236 * @throws IOException If an error occurs during the write.
237 */
238 public void sync() throws IOException {
239 if (readOnly)
240 return;
241
242 assert fileBlockManager.getMaxBlockAllocated() == 0;
243
244 FileSystemParam param = fsparam;
245 int totalBlocks = calcBlockParam(param);
246
247 fileBlockManager.setBlockSize(param.getBlockSize());
248 headerBlockManager.setBlockSize(param.getBlockSize());
249 file.position((long)param.getReservedDirectoryBlocks() * param.getBlockSize());
250
251 fileBlockManager.setCurrentBlock(param.getReservedDirectoryBlocks());
252 for (FileNode n : openNodes) {
253 n.close();
254 }
255
256 header.createHeader(param);
257 header.setNumBlocks(totalBlocks);
258 header.sync();
259 directory.sync();
260 }
261
262 /**
263 * Calculate the block size and related parameters.
264 *
265 * We need to know the block size and the size of the directory before writing any of the files.
266 */
267 private int calcBlockParam(FileSystemParam param) {
268 int bestBlockSize = 0;
269 int reserved = 0;
270 int sizeInBlocks = 0;
271 long bestSize = Long.MAX_VALUE;
272
273 for (int blockSize = param.getBlockSize(); blockSize < (1 << 24); blockSize <<= 1) {
274 int headerSlotsRequired = 1; // for the top level directory entry
275 int fileBlocks = 0;
276
277 for (FileNode fn : openNodes) {
278 long len = fn.getSize();
279
280 // Blocks required for this file
281 int nBlocks = (int) ((len + blockSize - 1) / blockSize);
282 fileBlocks += nBlocks;
283
284 // Now we calculate how many directory blocks we need, you have
285 // to round up as files do not share directory blocks.
286 headerSlotsRequired += (nBlocks + SLOTS_PER_ENTRY - 1) / SLOTS_PER_ENTRY;
287 }
288
289 // Header blocks include the blocks before the directory.
290 int requiredSlots = param.getDirectoryStartEntry() + headerSlotsRequired;
291 int headerBlocks = (requiredSlots * ENTRY_SIZE + blockSize - 1) / blockSize;
292 int totalBlocks = headerBlocks + fileBlocks;
293 long size = (long) totalBlocks * blockSize;
294 log.infof("bs=%d, whole size=%d, hb=%d, fb=%d, blocks=%d", blockSize, size,
295 headerBlocks, fileBlocks, totalBlocks);
296
297 if (headerBlocks > SLOTS_PER_ENTRY)
298 continue;
299
300 if (totalBlocks > 0xfffe)
301 continue;
302
303 if (size > bestSize)
304 break;
305
306 bestBlockSize = blockSize;
307 reserved = headerBlocks;
308 sizeInBlocks = fileBlocks + headerBlocks;
309 bestSize = size;
310 }
311 log.infof("Best block size: %d sizeInBlocks=%d, reserved=%d", bestBlockSize, sizeInBlocks, reserved);
312
313 param.setBlockSize(bestBlockSize);
314 param.setReservedDirectoryBlocks(reserved);
315 return sizeInBlocks;
316 }
317
318 /**
319 * Close the filesystem. Any saved data is flushed out. It is better
320 * to explicitly sync the data out first, to be sure that it has worked.
321 */
322 public void close() {
323
324 try {
325 sync();
326 } catch (IOException e) {
327 log.debug("could not sync filesystem");
328 } finally {
329 try {
330 file.close();
331 } catch (IOException e) {
332 log.warn("Could not close file");
333 }
334 }
335 }
336
337 public FileSystemParam fsparam() {
338 return fsparam;
339 }
340
341 /**
342 * Set up and ImgFS that has just been created.
343 *
344 * @param chan The real underlying file to write to.
345 * @param params The file system parameters.
346 * @throws FileNotWritableException If the file cannot be written for any
347 * reason.
348 */
349 private void createInitFS(FileChannel chan, FileSystemParam params) throws FileNotWritableException {
350 readOnly = false;
351
352 this.fsparam = params;
353
354 // The block manager allocates blocks for files.
355 headerBlockManager = new BlockManager(params.getBlockSize(), 0);
356 headerBlockManager.setMaxBlock(params.getReservedDirectoryBlocks());
357
358 // This bit is tricky. We want to use a regular ImgChannel to write
359 // to the header and directory, but to create one normally would involve
360 // it already existing, so it is created by hand.
361 try {
362 directory = new Directory(headerBlockManager);
363
364 Dirent ent = directory.create(DIRECTORY_FILE_NAME, headerBlockManager);
365 ent.setSpecial(true);
366 ent.setInitialized(true);
367
368 FileNode f = new FileNode(chan, ent, "w");
369
370 directory.setFile(f);
371 header = new ImgHeader(f);
372 header.createHeader(params);
373 } catch (FileExistsException e) {
374 throw new FileNotWritableException("Could not create img file directory", e);
375 }
376
377 fileBlockManager = new BlockManager(params.getBlockSize(), params.getReservedDirectoryBlocks());
378
379 assert header != null;
380 }
381
382 /**
383 * Initialise a filesystem that is going to be read from. We need to read
384 * in the header including directory.
385 *
386 * @param chan The file channel to read from.
387 * @throws IOException If the file cannot be read.
388 */
389 private void readInitFS(FileChannel chan) throws IOException {
390 ByteBuffer headerBuf = ByteBuffer.allocate(512);
391 headerBuf.order(ByteOrder.LITTLE_ENDIAN);
392 chan.read(headerBuf);
393 xorByte = headerBuf.get(0);
394 if(xorByte != 0) {
395 byte[] headerBytes = headerBuf.array();
396 for(int i = 0; i < headerBytes.length; ++i)
397 headerBytes[i] ^= xorByte;
398 }
399
400 if (headerBuf.position() < 512)
401 throw new IOException("File too short or corrupted");
402
403 header = new ImgHeader(null);
404 header.setHeader(headerBuf);
405 fsparam = header.getParams();
406
407 BlockManager headerBlockManager = new BlockManager(fsparam.getBlockSize(), 0);
408 headerBlockManager.setMaxBlock(fsparam.getReservedDirectoryBlocks());
409
410 directory = new Directory(headerBlockManager);
411 directory.setStartPos(fsparam.getDirectoryStartEntry() * ENTRY_BLOCK_SIZE);
412
413 Dirent ent = directory.create(DIRECTORY_FILE_NAME, headerBlockManager);
414 FileNode f = new FileNode(chan, ent, "r");
415
416 header.setFile(f);
417 directory.setFile(f);
418 directory.readInit(xorByte);
419 }
420
421 /**
422 * Lookup the file and return a directory entry for it.
423 *
424 * @param name The filename to look up.
425 * @return A directory entry.
426 * @throws FileNotFoundException If an error occurs reading the directory.
427 */
428 private Dirent internalLookup(String name) throws FileNotFoundException {
429 if (name == null)
430 throw new IllegalArgumentException("null name argument");
431
432 Dirent ent = (Dirent) directory.lookup(name);
433 if (ent == null)
434 throw new FileNotFoundException(name + " not found");
435
436 return ent;
437 }
438 }