Autopsy  4.1
Graphical digital forensics platform for The Sleuth Kit and other tools.
StringsTextExtractor.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2011-2016 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.keywordsearch;
20 
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.logging.Level;
35 
39 class StringsTextExtractor extends FileTextExtractor {
40 
41  static final private Logger logger = Logger.getLogger(StringsTextExtractor.class.getName());
42 
46  enum ExtractOptions {
47  EXTRACT_UTF16,
48  EXTRACT_UTF8,
49  };
50 
51  private final List<SCRIPT> extractScripts = new ArrayList<>();
52  private Map<String, String> extractOptions = new HashMap<>();
53 
54  public StringsTextExtractor() {
55  //LATIN_2 is the default script
56  extractScripts.add(SCRIPT.LATIN_2);
57  }
58 
64  public void setScripts(List<SCRIPT> extractScripts) {
65  this.extractScripts.clear();
66  this.extractScripts.addAll(extractScripts);
67  }
68 
74  public List<SCRIPT> getScripts() {
75  return new ArrayList<>(extractScripts);
76  }
77 
84  public Map<String, String> getOptions() {
85  return extractOptions;
86  }
87 
93  public void setOptions(Map<String, String> options) {
94  this.extractOptions = options;
95  }
96 
97  @Override
98  public void logWarning(final String msg, Exception ex) {
99  logger.log(Level.WARNING, msg, ex); //NON-NLS }
100  }
101 
102  @Override
103  public boolean isDisabled() {
104  boolean extractUTF8 = Boolean.parseBoolean(extractOptions.get(ExtractOptions.EXTRACT_UTF8.toString()));
105  boolean extractUTF16 = Boolean.parseBoolean(extractOptions.get(ExtractOptions.EXTRACT_UTF16.toString()));
106 
107  return extractUTF8 == false && extractUTF16 == false;
108  }
109 
110  @Override
111  public InputStreamReader getReader(AbstractFile sourceFile) throws TextExtractorException {
112  InputStream stringStream = getInputStream(sourceFile);
113  return new InputStreamReader(stringStream, Server.DEFAULT_INDEXED_TEXT_CHARSET);
114  }
115 
116  InputStream getInputStream(AbstractFile sourceFile) {
117  //check which extract stream to use
118  if (extractScripts.size() == 1 && extractScripts.get(0).equals(SCRIPT.LATIN_1)) {
119  return new EnglishOnlyStream(sourceFile);//optimal for english, english only
120  } else {
121  boolean extractUTF8 = Boolean.parseBoolean(extractOptions.get(ExtractOptions.EXTRACT_UTF8.toString()));
122  boolean extractUTF16 = Boolean.parseBoolean(extractOptions.get(ExtractOptions.EXTRACT_UTF16.toString()));
123 
124  return new InternationalStream(sourceFile, extractScripts, extractUTF8, extractUTF16);
125  }
126  }
127 
128  @Override
129  public boolean isContentTypeSpecific() {
130  return false;
131  }
132 
133  @Override
134  public boolean isSupported(AbstractFile file, String detectedFormat) {
135  // strings can be run on anything.
136  return true;
137  }
138 
151  private static class EnglishOnlyStream extends InputStream {
152 
153  private static final Logger logger = Logger.getLogger(EnglishOnlyStream.class.getName());
154  private static final String NLS = Character.toString((char) 10); //new line
155  private static final int READ_BUF_SIZE = 256;
156  private static final int MIN_PRINTABLE_CHARS = 4; //num. of chars needed to qualify as a char string
157 
158  //args
159  private final AbstractFile content;
160 
161  //internal working data
162  private long contentOffset = 0; //offset in fscontent read into curReadBuf
163  private final byte[] curReadBuf = new byte[READ_BUF_SIZE];
164  private int bytesInReadBuf = 0;
165  private int readBufOffset = 0; //offset in read buf processed
166  private StringBuilder curString = new StringBuilder();
167  private int curStringLen = 0;
168  private StringBuilder tempString = new StringBuilder();
169  private int tempStringLen = 0;
170  private boolean isEOF = false;
171  private boolean stringAtTempBoundary = false; //if temp has part of string that didn't make it in previous read()
172  private boolean stringAtBufBoundary = false; //if read buffer has string being processed, continue as string from prev read() in next read()
173  private boolean inString = false; //if current temp has min chars required
174  private final byte[] oneCharBuf = new byte[1];
175 
185  private EnglishOnlyStream(AbstractFile content) {
186  this.content = content;
187  }
188 
189  @Override
190  public int read(byte[] b, int off, int len) throws IOException {
191  if (b == null) {
192  throw new NullPointerException();
193  } else if (off < 0 || len < 0 || len > b.length - off) {
194  throw new IndexOutOfBoundsException();
195  } else if (len == 0) {
196  return 0;
197  }
198  long fileSize = content.getSize();
199  if (fileSize == 0) {
200  return -1;
201  }
202  if (isEOF) {
203  return -1;
204  }
205  if (stringAtTempBoundary) {
206  //append entire temp string residual from previous read()
207  //because qualified string was broken down into 2 parts
208  appendResetTemp();
209  stringAtTempBoundary = false;
210  //there could be more to this string in fscontent/buffer
211  }
212  boolean singleConsecZero = false; //preserve the current sequence of chars if 1 consecutive zero char
213  int newCurLen = curStringLen + tempStringLen;
214  while (newCurLen < len) {
215  //need to extract more strings
216  if (readBufOffset > bytesInReadBuf - 1) {
217  //no more bytes to process into strings, read them
218  try {
219  bytesInReadBuf = 0;
220  bytesInReadBuf = content.read(curReadBuf, contentOffset, READ_BUF_SIZE);
221  } catch (TskException ex) {
222  if (curStringLen > 0 || tempStringLen >= MIN_PRINTABLE_CHARS) {
223  appendResetTemp();
224  //have some extracted string, return that, and fail next time
225  isEOF = true;
226  int copied = copyToReturn(b, off, len);
227  return copied;
228  } else {
229  return -1; //EOF
230  }
231  }
232  if (bytesInReadBuf < 1) {
233  if (curStringLen > 0 || tempStringLen >= MIN_PRINTABLE_CHARS) {
234  appendResetTemp();
235  //have some extracted string, return that, and fail next time
236  isEOF = true;
237  int copied = copyToReturn(b, off, len);
238  return copied;
239  } else {
240  return -1; //EOF
241  }
242  }
243  //increment content offset for next read
244  contentOffset += bytesInReadBuf;
245  //reset read buf position
246  readBufOffset = 0;
247  }
248  //get char from cur read buf
249  char c = (char) curReadBuf[readBufOffset++];
250  if (c == 0 && singleConsecZero == false) {
251  //preserve the current sequence if max consec. 1 zero char
252  singleConsecZero = true;
253  } else {
254  singleConsecZero = false;
255  }
257  tempString.append(c);
258  ++tempStringLen;
259  if (tempStringLen >= MIN_PRINTABLE_CHARS) {
260  inString = true;
261  }
262  //boundary case when temp has still chars - handled after the loop
263  } else if (!singleConsecZero) {
264  //break the string, clear temp
265  if (tempStringLen >= MIN_PRINTABLE_CHARS || stringAtBufBoundary) {
266  //append entire temp string with new line
267  tempString.append(NLS);
268  ++tempStringLen;
269  curString.append(tempString);
270  curStringLen += tempStringLen;
271  stringAtBufBoundary = false;
272  }
273  //reset temp
274  tempString = new StringBuilder();
275  tempStringLen = 0;
276  }
277  newCurLen = curStringLen + tempStringLen;
278  }
279  //check if still in string state, so that next chars in read buf bypass min chars check
280  //and qualify as string even if less < min chars required
281  if (inString) {
282  inString = false; //reset
283  stringAtBufBoundary = true; //will bypass the check
284  }
285  //check if temp still has chars to qualify as a string
286  //we might need to break up temp into 2 parts for next read() call
287  //consume as many as possible to fill entire user buffer
288  if (tempStringLen >= MIN_PRINTABLE_CHARS) {
289  if (newCurLen > len) {
290  int appendChars = len - curStringLen;
291  //save part for next user read(), need to break up temp string
292  //do not append new line
293  String toAppend = tempString.substring(0, appendChars);
294  String newTemp = tempString.substring(appendChars);
295  curString.append(toAppend);
296  curStringLen += appendChars;
297  tempString = new StringBuilder(newTemp);
298  tempStringLen = newTemp.length();
299  stringAtTempBoundary = true;
300  } else {
301  //append entire temp
302  curString.append(tempString);
303  curStringLen += tempStringLen;
304  //reset temp
305  tempString = new StringBuilder();
306  tempStringLen = 0;
307  }
308  } else {
309  //if temp has a few chars, not qualified as string for now,
310  //will be processed during next read() call
311  }
312  //copy current strings to user
313  final int copied = copyToReturn(b, off, len);
314  //there may be still chars in read buffer or tempString, for next read()
315  return copied;
316  }
317 
318  //append temp buffer to cur string buffer and reset temp, if enough chars
319  //does not append new line
320  private void appendResetTemp() {
321  if (tempStringLen >= MIN_PRINTABLE_CHARS) {
322  curString.append(tempString);
323  curStringLen += tempStringLen;
324  tempString = new StringBuilder();
325  tempStringLen = 0;
326  }
327  }
328 
329  //copy currently extracted string to user buffer
330  //and reset for next read() call
331  private int copyToReturn(byte[] b, int off, long len) {
332  final String curStringS = curString.toString();
333  //logger.log(Level.INFO, curStringS);
334  byte[] stringBytes = curStringS.getBytes(Server.DEFAULT_INDEXED_TEXT_CHARSET);
335  System.arraycopy(stringBytes, 0, b, off, Math.min(curStringLen, (int) len));
336  //logger.log(Level.INFO, curStringS);
337  //copied all string, reset
338  curString = new StringBuilder();
339  int ret = curStringLen;
340  curStringLen = 0;
341  return ret;
342  }
343 
344  @Override
345  public int read() throws IOException {
346  final int read = read(oneCharBuf, 0, 1);
347  if (read == 1) {
348  return oneCharBuf[0];
349  } else {
350  return -1;
351  }
352  }
353 
354  @Override
355  public int available() throws IOException {
356  //we don't know how many bytes in curReadBuf may end up as strings
357  return 0;
358  }
359 
360  @Override
361  public long skip(long n) throws IOException {
362  //use default implementation that reads into skip buffer
363  //but it could be more efficient
364  return super.skip(n);
365  }
366  }
367 
374  private static class InternationalStream extends InputStream {
375 
376  private static final Logger logger = Logger.getLogger(InternationalStream.class.getName());
377  private static final int FILE_BUF_SIZE = 1024 * 1024;
378  private final AbstractFile content;
379  private final byte[] oneCharBuf = new byte[1];
383  private final boolean nothingToDo;
384  private final byte[] fileReadBuff = new byte[FILE_BUF_SIZE];
385  private long fileReadOffset = 0L;
386  private byte[] convertBuff; //stores extracted string encoded as bytes, before returned to user
387  private int convertBuffOffset = 0; //offset to start returning data to user on next read()
388  private int bytesInConvertBuff = 0; //amount of data currently in the buffer
389  private boolean fileEOF = false; //if file has more bytes to read
391 
404  private InternationalStream(AbstractFile content, List<SCRIPT> scripts, boolean extractUTF8, boolean extractUTF16) {
405  this.content = content;
406  this.stringExtractor = new StringExtract();
407  this.stringExtractor.setEnabledScripts(scripts);
408  this.nothingToDo = extractUTF8 == false && extractUTF16 == false;
409  this.stringExtractor.setEnableUTF8(extractUTF8);
410  this.stringExtractor.setEnableUTF16(extractUTF16);
411  }
412 
413  @Override
414  public int read() throws IOException {
415  if (nothingToDo) {
416  return -1;
417  }
418  final int read = read(oneCharBuf, 0, 1);
419  if (read == 1) {
420  return oneCharBuf[0];
421  } else {
422  return -1;
423  }
424  }
425 
426  @Override
427  public int read(byte[] b, int off, int len) throws IOException {
428  if (b == null) {
429  throw new NullPointerException();
430  } else if (off < 0 || len < 0 || len > b.length - off) {
431  throw new IndexOutOfBoundsException();
432  } else if (len == 0) {
433  return 0;
434  }
435  if (nothingToDo) {
436  return -1;
437  }
438  long fileSize = content.getSize();
439  if (fileSize == 0) {
440  return -1;
441  }
442  //read and convert until user buffer full
443  //we have data if file can be read or when byteBuff has converted strings to return
444  int bytesToUser = 0; //returned to user so far
445  int offsetUser = off;
446  while (bytesToUser < len && offsetUser < len) {
447  //check if we have enough converted strings
448  int convertBuffRemain = bytesInConvertBuff - convertBuffOffset;
449  if ((convertBuff == null || convertBuffRemain == 0) && !fileEOF && fileReadOffset < fileSize) {
450  try {
451  //convert more strings, store in buffer
452  long toRead = 0;
453 
454  //fill up entire fileReadBuff fresh
455  toRead = Math.min(FILE_BUF_SIZE, fileSize - fileReadOffset);
456  //}
457  int read = content.read(fileReadBuff, fileReadOffset, toRead);
458  if (read == -1 || read == 0) {
459  fileEOF = true;
460  } else {
461  fileReadOffset += read;
462  if (fileReadOffset >= fileSize) {
463  fileEOF = true;
464  }
465  //put converted string in convertBuff
466  convert(read);
467  convertBuffRemain = bytesInConvertBuff - convertBuffOffset;
468  }
469  } catch (TskCoreException ex) {
470  //Exceptions.printStackTrace(ex);
471  fileEOF = true;
472  }
473  }
474  //nothing more to read, and no more bytes in convertBuff
475  if (convertBuff == null || convertBuffRemain == 0) {
476  if (fileEOF) {
477  return bytesToUser > 0 ? bytesToUser : -1;
478  } else {
479  //no strings extracted, try another read
480  continue;
481  }
482  }
483  //return part or all of convert buff to user
484  final int toCopy = Math.min(convertBuffRemain, len - offsetUser);
485  System.arraycopy(convertBuff, convertBuffOffset, b, offsetUser, toCopy);
486 
487  convertBuffOffset += toCopy;
488  offsetUser += toCopy;
489  bytesToUser += toCopy;
490  }
491  //if more string data in convertBuff, will be consumed on next read()
492  return bytesToUser;
493  }
494 
501  private void convert(int numBytes) {
502  lastExtractResult = stringExtractor.extract(fileReadBuff, numBytes, 0);
503  convertBuff = lastExtractResult.getText().getBytes(Server.DEFAULT_INDEXED_TEXT_CHARSET);
504  //reset tracking vars
505  if (lastExtractResult.getNumBytes() == 0) {
506  bytesInConvertBuff = 0;
507  } else {
508  bytesInConvertBuff = convertBuff.length;
509  }
510  convertBuffOffset = 0;
511  }
512  }
513 }
StringExtractResult extract(byte[] buff, int len, int offset)
InternationalStream(AbstractFile content, List< SCRIPT > scripts, boolean extractUTF8, boolean extractUTF16)
final void setEnabledScripts(List< SCRIPT > scripts)
static final Charset DEFAULT_INDEXED_TEXT_CHARSET
default Charset to index text as
Definition: Server.java:177
synchronized static Logger getLogger(String name)
Definition: Logger.java:161
final int read(byte[] buf, long offset, long len)

Copyright © 2012-2016 Basis Technology. Generated on: Mon Apr 24 2017
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.