-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.java
606 lines (576 loc) · 24.4 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import java.io.*;
import java.nio.*;
import java.util.*;
import java.util.regex.*;
import java.text.*;
/**
* Main class of the ext2 file system reader.
*/
public class Main {
public static final String BOLD_FONT = "\u001b[1m";
public static final String LIGHT_GREY_COL = "\u001b[38;5;248m";
public static final String GREY_COL = "\u001b[38;5;245m";
public static final String BLUE_COL = "\u001b[38;5;110m";
public static final String RESET = "\u001b[0m";
private Volume vol = null;
private File cwd = null;
private File active = null;
/**
* Creates the main object.
*/
public static void main(String[] args) {
new Main();
}
/**
* The main object.
*/
public Main() {
//vol = new Volume("./ext2fs");
//cwd = new File(vol, "", new LinkedList<String>(), vol.get_root_inode());
Scanner scanner = new Scanner(System.in);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("\n");
}
});
while (true) {
if (vol != null) {
System.out.print(BOLD_FONT + BLUE_COL + cwd.get_path_string() + " $ " + RESET);
} else {
System.out.print(BOLD_FONT + BLUE_COL + "$ " + RESET);
}
String[] input = scanner.nextLine().trim().split("[ ]+");
String command = input[0];
String[] arguments = Arrays.copyOfRange(input, 1, input.length);
if (vol == null && command.indexOf("volume") < 0 && command.indexOf("vol") < 0) {
System.out.println("No volume selected. Do so using the volume <filename> command");
continue;
}
try {
switch (command) {
case "help":
case "h":
System.out.println("help");
System.out.println("h print this help text\n");
System.out.println("print-super-block");
System.out.println("psb print super block contents\n");
System.out.println("print-group-desc <group_id>");
System.out.println("pgd <group_id> print group description contents\n");
System.out.println("print-inode <inode_id>");
System.out.println("pi <inode_id> print group description contents\n");
System.out.println("print-dir-entries");
System.out.println("pde print directory entries\n");
System.out.println("vol-details");
System.out.println("df print volume details\n");
System.out.println("pwd print current path\n");
System.out.println("ls <filename> list contents of <filename>(directory)\n");
System.out.println("stat <filename> print details of <filename>(file)\n");
System.out.println("cd <filename> change directory to <filename>(directory)\n");
System.out.println("cat <filename> print file <filename>\n");
System.out.println("head -c <num_bytes> <filename> print first <num_bytes> of <filename>\n");
System.out.println("tail -c <num_bytes> <filename> print last <num_bytes> of <filename>");
break;
/**************** Code solely to comply with "API" *****************/
/**************** To be removed after demonstration ****************/
case "volume":
case "vol":
if (arguments.length >= 1) {
java.io.File f = new java.io.File(arguments[0]);
if (f.exists()) {
vol = new Volume(arguments[0]);
cwd = new File(vol, "", new LinkedList<String>(), vol.get_root_inode());
active = null;
} else {
System.out.println("volume: " + arguments[0] + ": File not found");
}
}
break;
case "select":
if (arguments.length >= 1) {
active = open(arguments[0], false);
}
break;
case "seek":
if (active == null) {
System.out.println("seek: No file selected. Do so using the select <filename> command");
break;
}
try {
if (arguments.length >= 1) {
if (Long.parseLong(arguments[0]) < 0) {
System.out.println("seek: Seek position smaller than 0");
break;
}
if (Long.parseLong(arguments[0]) > active.get_size()) {
System.out.println("seek: Seek position bigger than file size");
break;
}
active.position = Long.parseLong(arguments[0]);
}
} catch (NumberFormatException nfe) {
System.out.println("seek: argument is not numeric");
}
break;
case "read":
if (active == null) {
System.out.println("read: No file selected. Do so using the select <filename> command");
break;
}
try {
if (arguments.length >= 2) {
if (Long.parseLong(arguments[0]) < 0) {
System.out.println("read: Seek position smaller than 0");
break;
}
if (Long.parseLong(arguments[0]) > active.get_size()) {
System.out.println("read: Seek position bigger than file size");
break;
}
active.position = Long.parseLong(arguments[0]);
Helper.dumpHexBytes(active.read(Long.parseLong(arguments[1])));
}
else if (arguments.length == 1) {
Helper.dumpHexBytes(active.read(Long.parseLong(arguments[0])));
}
} catch (NumberFormatException nfe) {
System.out.println("read: argument is not numeric");
}
break;
case "position":
if (active == null) {
System.out.println("position: No file selected. Do so using the select <filename> command");
break;
}
System.out.println(active.position);
break;
case "size":
if (active == null) {
System.out.println("size: No file selected. Do so using the select <filename> command");
break;
}
System.out.println(active.get_size());
break;
case "dumpHexBytes":
case "dump-hex-bytes":
if (arguments.length >= 2) {
try {
long offset = Long.parseLong(arguments[0]);
for (int i = 0; i < (int)Math.ceil(Long.parseLong(arguments[1]) / (double)1024); i++) {
int read_len = (i == (int)Math.ceil(Long.parseLong(arguments[1]) / (double)1024)) ? (int)(Long.parseLong(arguments[1]) % 1024) : 1024;
byte[] bytes = new byte[read_len];
for (int j = 0; j < read_len; j++) {
bytes[j] = vol.bb.get((int)(offset + i * 1024 + j));
}
Helper.dumpHexBytes(bytes);
}
} catch (NumberFormatException nfe) {
System.out.println("dump-hex-bytes: argument is not numeric");
}
}
break;
/**************** End of code solely to comply with "API" *****************/
case "print-super-block":
case "psb":
vol.print_super_block();
break;
case "print-group-desc":
case "pgd":
if (arguments.length >= 1) {
vol.print_group_desc(Integer.parseInt(arguments[0]));
}
break;
case "print-inode":
case "pi":
if (arguments.length >= 1) {
vol.print_inode(Integer.parseInt(arguments[0]));
} else {
vol.print_inode(cwd.inode.id);
}
break;
case "print-dir-entries":
case "pde":
cmd_pde();
break;
case "df":
case "vol-details":
vol.print_vol_details();
break;
case "pwd":
System.out.println(cwd.get_path_string());
break;
case "ls":
cmd_ls(command, arguments);
break;
case "getFileInfo":
cmd_ls(command, new String[]{"-l"});
break;
case "stat":
if (arguments.length >= 1) {
cmd_stat(command, arguments);
} else {
System.out.println("stat: missing operand");
}
break;
case "cd":
if (arguments.length >= 1) {
cmd_cd(command, arguments);
}
break;
case "cat":
if (arguments.length >= 1) {
cmd_cat(command, arguments);
}
break;
case "head":
if (arguments.length >= 1) {
cmd_head(command, arguments);
}
break;
case "tail":
if (arguments.length >= 1) {
cmd_tail(command, arguments);
}
break;
case "quit":
case "exit":
System.exit(0);
break;
default:
System.out.println(command + ": command not found");
break;
}
} catch (FileSystemException e) {
e.print_err_msg(command);
}
}
}
/**
* Change directory (cd) command handler.
*
* @param command The command used
* @param arguments Arguments provided
*/
public void cmd_cd(String command, String[] arguments) throws FileSystemException {
String target_filename = arguments[0];
try {
cwd = open(target_filename, true);
} catch (FileSystemException e) {
e.name = target_filename;
throw e;
}
}
/**
* List directory (ls) command handler.
*
* @param command The command used
* @param arguments Arguments provided
*/
public void cmd_ls(String command, String[] arguments) throws FileSystemException { // TODO parse path
if (Arrays.asList(arguments).contains("-l")) {
TablePrinter table = new TablePrinter();
File file;
if (arguments.length < 2) {
file = cwd;
} else {
file = open(arguments[1], true);
}
for (String filename : file.read_dir()) {
List<String> file_path = new LinkedList<String>(file.path);
file_path.add(filename);
int[] file_stat = path_to_inode(file_path).stat();
String[] row = {
file_perm_string(file_stat[1]), // rwxrwxrwx
Integer.toString(file_stat[2]), // num hard links
Integer.toString(file_stat[3]), // uid
Integer.toString(file_stat[4]), // gid
Long.toString((long)file_stat[6] << 32 | file_stat[5]), // size
format_date(file_stat[10], "MMM d HH:mm"), // last modify time
"" // filename
};
if (path_to_inode(file_path).is_directory()) {
row[6] = BOLD_FONT + BLUE_COL + filename + RESET + " ";
} else {
row[6] = filename + " ";
}
table.add_row(row);
}
table.print_table();
} else {
File file;
if (arguments.length == 0) {
file = cwd;
} else {
file = open(arguments[0], true);
}
for (String filename : file.read_dir()) {
List<String> file_path = new LinkedList<String>(file.path);
file_path.add(filename);
if (path_to_inode(file_path).is_directory()) {
System.out.print(BOLD_FONT + BLUE_COL + filename + RESET + " ");
} else {
System.out.print(filename + " ");
}
}
System.out.print("\n");
}
}
/**
* Stat (stat) command handler.
*
* @param command The command used
* @param arguments Arguments provided
*/
public void cmd_stat(String command, String[] arguments) throws FileSystemException {
String target_filename = arguments[0];
try {
Inode target_inode = path_to_inode(realpath(target_filename));
int[] stat = target_inode.stat();
System.out.println(" File: " + target_filename);
TablePrinter table_printer = new TablePrinter();
long file_size = stat[6] << 32 | stat[5];
table_printer.add_row(new String[]{
" Size: " + file_size + " ",
"Blocks: " + stat[7] + " ",
"IO Block: 1024 ",
file_type_string(stat[1])
});
table_printer.add_row(new String[]{
LIGHT_GREY_COL + "Device: N/A " + RESET,
"Inode: " + stat[0] + " ",
"Links: " + stat[2],
""
});
table_printer.print_table();
if (stat[1] < 0) {
stat[1] &= 0xFFFF;
}
System.out.print("Access: (" + Integer.toOctalString(stat[1]).substring(1) + "/" + file_perm_string(stat[1]) + ") ");
System.out.print("Uid: " + stat[3] + " ");
System.out.print("Gid: " + stat[4] + " ");
System.out.print("\n");
System.out.println("Access: " + format_date(stat[8], "YYYY-MM-dd HH:mm:ss.SSS Z"));
System.out.println("Modify: " + format_date(stat[9], "YYYY-MM-dd HH:mm:ss.SSS Z"));
System.out.println("Change: " + format_date(stat[9], "YYYY-MM-dd HH:mm:ss.SSS Z"));
System.out.println(" Birth: " + format_date(stat[10], "YYYY-MM-dd HH:mm:ss.SSS Z"));
} catch (FileSystemException e) {
e.name = target_filename;
throw e;
}
}
/**
* Concatenate (cat) command handler.
*
* @param command The command used
* @param arguments Arguments provided
*/
public void cmd_cat(String command, String[] arguments) throws FileSystemException {
read_file(arguments[0], 0);
}
/**
* Head (head) command handler.
*
* @param command The command used
* @param arguments Arguments provided
*/
public void cmd_head(String command, String[] arguments) throws FileSystemException {
if (arguments[0].charAt(0) == '-') {
if (arguments[0].equals("-c")) {
if (arguments.length >= 3) {
read_file(arguments[2], 0, Integer.parseInt(arguments[1]));
}
}
}
}
/**
* Tail (tail) command handler.
*
* @param command The command used
* @param arguments Arguments provided
*/
public void cmd_tail(String command, String[] arguments) throws FileSystemException {
if (arguments[0].charAt(0) == '-') {
if (arguments[0].equals("-c")) {
if (arguments.length >= 3) {
read_file(arguments[2], Integer.parseInt(arguments[1]) * -1, Integer.parseInt(arguments[1]));
}
}
}
}
/**
* Print directory entries (pde / print-dir-entries) command handler.
*/
public void cmd_pde() {
TablePrinter table = new TablePrinter();
table.add_row(new String[]{"Inode", "Length", "Name length", "File type", "Filename"});
for (int direntry_offset : cwd.inode.iter_direntries()) {
int datablock_pt = cwd.inode.get_datablock_pt(direntry_offset / vol.BLOCK_LEN);
String[] row = new String[5];
row[0] = Integer.toString(vol.bb.getInt(datablock_pt + direntry_offset % vol.BLOCK_LEN));
row[1] = Integer.toString(vol.bb.getShort(datablock_pt + direntry_offset % vol.BLOCK_LEN + 4));
char[] filename = new char[vol.bb.get(datablock_pt + direntry_offset % vol.BLOCK_LEN + 6)];
row[2] = Integer.toString(filename.length);
row[3] = Integer.toString(vol.bb.get(datablock_pt + direntry_offset % vol.BLOCK_LEN + 7));
for (int i = 0; i < filename.length; i++) {
filename[i] = (char)vol.bb.get(datablock_pt + direntry_offset % vol.BLOCK_LEN + 8 + i);
}
row[4] = new String(filename);
table.add_row(row);
}
table.print_table();
}
/**
* Converts file mode from a number to a file type string.
*
* @param file_mode The file mode
* @return File type
*/
public String file_type_string(int file_mode) throws FileSystemException {
int[] file_types = {0xC000, 0xA000, 0x8000, 0x6000, 0x4000, 0x2000, 0x1000}; // TODO octal
String[] file_type_names = {
"socket",
"symbolic link",
"regular file",
"block device",
"directory",
"character deice",
"FIFO"
};
for (int i = 0; i < 7; i++) {
if ((file_mode & file_types[i]) == file_types[i]) {
return file_type_names[i];
}
}
return "unknown file type";
}
/**
* Returns a formatted date string.
*
* @param date_time Number of seconds since epoch
* @param format The desired format
* @return Formatted date string
*/
public String format_date(int date_time, String format) throws FileSystemException {
SimpleDateFormat simple_date_format = new SimpleDateFormat(format);
return simple_date_format.format(new Date((long)date_time * 1000));
}
/**
* Converts file mode from a number to a file permission string.
*
* @param file_mode The file mode
* @return File permission settings
*/
public String file_perm_string(int file_mode) throws FileSystemException {
String file_perm_string = "";
int[] file_types = {0xC000, 0xA000, 0x8000, 0x6000, 0x4000, 0x2000, 0x1000};
char[] file_type_symbols = {'s', 'l', '-', 'b', 'd', 'c', 'p'};
for (int i = 0; i < 7; i++) {
if ((file_mode & 0xF000) == file_types[i]) {
file_perm_string += file_type_symbols[i];
}
}
for (int i = 0; i < 3; i++) {
file_perm_string += ((file_mode >> ((2 - i) * 3 + 2) & 1) == 1) ? 'r' : '-';
file_perm_string += ((file_mode >> ((2 - i) * 3 + 1) & 1) == 1) ? 'w' : '-';
file_perm_string += ((file_mode >> ((2 - i) * 3) & 1) == 1) ? 'x' : '-';
}
return file_perm_string;
}
/**
* Prints (filename), starting from (offset) bytes.
*
* @param filename Filename to read
* @param offset Offset in bytes
*/
public void read_file(String filename, long offset) throws FileSystemException {
File target_file = open(filename, false);
read_file(filename, offset, target_file.get_size());
}
/**
* Prints (filename), starting from (offset) bytes, to (offset + length) bytes.
*
* @param filename Filename to read
* @param offset Offset in bytes
* @param length Length in bytes
*/
public void read_file(String filename, long offset, long length) throws FileSystemException {
File target_file = open(filename, false);
for (long i = 0; i < length; i += 10240) {
long temp_length = (i <= length - 10240) ? 10240 : length - i;
if (offset < 0) {
offset = target_file.get_size() - length + i;
}
System.out.print(new String(target_file.read(offset, temp_length)));
}
}
/**
* Gets file from path.
*
* @param path Path of the file to get
* @param directory If the file should be a directory or not
* @return The file object
*/
public File open(String path, boolean directory) throws FileSystemException {
try {
List<String> real_path = realpath(path);
Inode inode = path_to_inode(real_path);
if (directory != inode.is_directory()) {
throw new FileSystemException(directory ? 20 : 21);
}
File file = new File(vol, path, real_path, inode);
return file;
} catch (FileSystemException e) {
e.name = path;
throw e;
}
}
/**
* Gets inode from path.
*
* @param path_ll Path as a list
* @return The inode
*/
public Inode path_to_inode(List<String> path_ll) throws FileSystemException {
Inode ino = vol.get_root_inode();
for (String path_filename : path_ll) {
try {
ino = ino.lookup(path_filename);
} catch (FileSystemException e) {
e.name = path_filename;
throw e;
}
}
return ino;
}
/**
* Gets the clean absolute path.
*
* @param path_str Path as a string
* @return The path as a list
*/
public List<String> realpath(String path_str) {
String[] filenames = path_str.split("/");
List<String> path_ll = new LinkedList<String>();
if (path_str.charAt(0) != '/') {
for (String filename : cwd.path) {
path_ll.add(filename);
}
}
for (String filename : filenames) {
switch (filename) {
case ".":
case "":
break;
case "..":
if (path_ll.size() != 0) {
path_ll.remove(path_ll.size() - 1);
}
break;
default:
path_ll.add(filename);
break;
}
}
return path_ll;
}
}