Autopsy  4.14.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
Ingester.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2011-2018 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.BufferedReader;
22 import java.io.Reader;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.logging.Level;
28 import org.apache.commons.lang3.math.NumberUtils;
29 import org.apache.solr.client.solrj.SolrServerException;
30 import org.apache.solr.common.SolrInputDocument;
31 import org.openide.util.NbBundle;
38 import org.sleuthkit.datamodel.AbstractFile;
39 import org.sleuthkit.datamodel.BlackboardArtifact;
40 import org.sleuthkit.datamodel.Content;
41 import org.sleuthkit.datamodel.DerivedFile;
42 import org.sleuthkit.datamodel.Directory;
43 import org.sleuthkit.datamodel.File;
44 import org.sleuthkit.datamodel.LayoutFile;
45 import org.sleuthkit.datamodel.LocalDirectory;
46 import org.sleuthkit.datamodel.LocalFile;
47 import org.sleuthkit.datamodel.Report;
48 import org.sleuthkit.datamodel.SlackFile;
49 import org.sleuthkit.datamodel.SleuthkitItemVisitor;
50 import org.sleuthkit.datamodel.SleuthkitVisitableItem;
51 import org.sleuthkit.datamodel.TskCoreException;
52 
56 //JMTODO: Should this class really be a singleton?
57 class Ingester {
58 
59  private static final Logger logger = Logger.getLogger(Ingester.class.getName());
60  private volatile boolean uncommitedIngests = false;
61  private final Server solrServer = KeywordSearch.getServer();
62  private static final SolrFieldsVisitor SOLR_FIELDS_VISITOR = new SolrFieldsVisitor();
63  private static Ingester instance;
64  private final LanguageSpecificContentIndexingHelper languageSpecificContentIndexingHelper
65  = new LanguageSpecificContentIndexingHelper();
66 
67  private Ingester() {
68  }
69 
70  public static synchronized Ingester getDefault() {
71  if (instance == null) {
72  instance = new Ingester();
73  }
74  return instance;
75  }
76 
77  //JMTODO: this is probably useless
78  @Override
79  @SuppressWarnings("FinalizeDeclaration")
80  protected void finalize() throws Throwable {
81  super.finalize();
82 
83  // Warn if files might have been left uncommited.
84  if (uncommitedIngests) {
85  logger.warning("Ingester was used to add files that it never committed."); //NON-NLS
86  }
87  }
88 
99  void indexMetaDataOnly(AbstractFile file) throws IngesterException {
100  indexChunk("", "", file.getName().toLowerCase(), new HashMap<>(getContentFields(file)));
101  }
102 
113  void indexMetaDataOnly(BlackboardArtifact artifact, String sourceName) throws IngesterException {
114  indexChunk("", "", sourceName, new HashMap<>(getContentFields(artifact)));
115  }
116 
125  private Map<String, String> getContentFields(SleuthkitVisitableItem item) {
126  return item.accept(SOLR_FIELDS_VISITOR);
127  }
128 
146  // TODO (JIRA-3118): Cancelled text indexing does not propagate cancellation to clients
147  < T extends SleuthkitVisitableItem> boolean indexText(Reader sourceReader, long sourceID, String sourceName, T source, IngestJobContext context) throws Ingester.IngesterException {
148  int numChunks = 0; //unknown until chunking is done
149 
150  Map<String, String> contentFields = Collections.unmodifiableMap(getContentFields(source));
151  //Get a reader for the content of the given source
152  try (BufferedReader reader = new BufferedReader(sourceReader)) {
153  Chunker chunker = new Chunker(reader);
154  while (chunker.hasNext()) {
155  if (context != null && context.fileIngestIsCancelled()) {
156  logger.log(Level.INFO, "File ingest cancelled. Cancelling keyword search indexing of {0}", sourceName);
157  return false;
158  }
159 
160  Chunk chunk = chunker.next();
161  Map<String, Object> fields = new HashMap<>(contentFields);
162  String chunkId = Server.getChunkIdString(sourceID, numChunks + 1);
163  fields.put(Server.Schema.ID.toString(), chunkId);
164  fields.put(Server.Schema.CHUNK_SIZE.toString(), String.valueOf(chunk.getBaseChunkLength()));
165  Optional<Language> language = languageSpecificContentIndexingHelper.detectLanguageIfNeeded(chunk);
166  language.ifPresent(lang -> languageSpecificContentIndexingHelper.updateLanguageSpecificFields(fields, chunk, lang));
167  try {
168  //add the chunk text to Solr index
169  indexChunk(chunk.toString(), chunk.geLowerCasedChunk(), sourceName, fields);
170  // add mini chunk when there's a language specific field
171  if (chunker.hasNext() && language.isPresent()) {
172  languageSpecificContentIndexingHelper.indexMiniChunk(chunk, sourceName, new HashMap<>(contentFields), chunkId, language.get());
173  }
174  numChunks++;
175  } catch (Ingester.IngesterException ingEx) {
176  logger.log(Level.WARNING, "Ingester had a problem with extracted string from file '" //NON-NLS
177  + sourceName + "' (id: " + sourceID + ").", ingEx);//NON-NLS
178 
179  throw ingEx; //need to rethrow to signal error and move on
180  }
181  }
182  if (chunker.hasException()) {
183  logger.log(Level.WARNING, "Error chunking content from " + sourceID + ": " + sourceName, chunker.getException());
184  return false;
185  }
186  } catch (Exception ex) {
187  logger.log(Level.WARNING, "Unexpected error, can't read content stream from " + sourceID + ": " + sourceName, ex);//NON-NLS
188  return false;
189  } finally {
190  if (context != null && context.fileIngestIsCancelled()) {
191  return false;
192  } else {
193  Map<String, Object> fields = new HashMap<>(contentFields);
194  //after all chunks, index just the meta data, including the numChunks, of the parent file
195  fields.put(Server.Schema.NUM_CHUNKS.toString(), Integer.toString(numChunks));
196  //reset id field to base document id
197  fields.put(Server.Schema.ID.toString(), Long.toString(sourceID));
198  //"parent" docs don't have chunk_size
199  fields.remove(Server.Schema.CHUNK_SIZE.toString());
200  indexChunk(null, null, sourceName, fields);
201  }
202  }
203  return true;
204  }
205 
220  private void indexChunk(String chunk, String lowerCasedChunk, String sourceName, Map<String, Object> fields) throws IngesterException {
221  if (fields.get(Server.Schema.IMAGE_ID.toString()) == null) {
222  //JMTODO: actually if the we couldn't get the image id it is set to -1,
223  // but does this really mean we don't want to index it?
224 
225  //skip the file, image id unknown
226  String msg = NbBundle.getMessage(Ingester.class,
227  "Ingester.ingest.exception.unknownImgId.msg", sourceName); //JMTODO: does this need to ne internationalized?
228  logger.log(Level.SEVERE, msg);
229  throw new IngesterException(msg);
230  }
231 
232  //Make a SolrInputDocument out of the field map
233  SolrInputDocument updateDoc = new SolrInputDocument();
234  for (String key : fields.keySet()) {
235  updateDoc.addField(key, fields.get(key));
236  }
237 
238  try {
239  //TODO: consider timeout thread, or vary socket timeout based on size of indexed content
240 
241  //add the content to the SolrInputDocument
242  //JMTODO: can we just add it to the field map before passing that in?
243  updateDoc.addField(Server.Schema.CONTENT.toString(), chunk);
244 
245  // We also add the content (if present) in lowercase form to facilitate case
246  // insensitive substring/regular expression search.
247  double indexSchemaVersion = NumberUtils.toDouble(solrServer.getIndexInfo().getSchemaVersion());
248  if (indexSchemaVersion >= 2.1) {
249  updateDoc.addField(Server.Schema.CONTENT_STR.toString(), ((chunk == null) ? "" : lowerCasedChunk));
250  }
251 
252  TimingMetric metric = HealthMonitor.getTimingMetric("Solr: Index chunk");
253 
254  solrServer.addDocument(updateDoc);
255  HealthMonitor.submitTimingMetric(metric);
256  uncommitedIngests = true;
257 
258  } catch (KeywordSearchModuleException | NoOpenCoreException ex) {
259  //JMTODO: does this need to be internationalized?
260  throw new IngesterException(
261  NbBundle.getMessage(Ingester.class, "Ingester.ingest.exception.err.msg", sourceName), ex);
262  }
263  }
264 
269  void commit() {
270  try {
271  solrServer.commit();
272  uncommitedIngests = false;
273  } catch (NoOpenCoreException | SolrServerException ex) {
274  logger.log(Level.WARNING, "Error commiting index", ex); //NON-NLS
275 
276  }
277  }
278 
282  static private class SolrFieldsVisitor extends SleuthkitItemVisitor.Default<Map<String, String>> {
283 
284  @Override
285  protected Map<String, String> defaultVisit(SleuthkitVisitableItem svi) {
286  return new HashMap<>();
287  }
288 
289  @Override
290  public Map<String, String> visit(File f) {
291  return getCommonAndMACTimeFields(f);
292  }
293 
294  @Override
295  public Map<String, String> visit(DerivedFile df) {
296  return getCommonAndMACTimeFields(df);
297  }
298 
299  @Override
300  public Map<String, String> visit(Directory d) {
301  return getCommonAndMACTimeFields(d);
302  }
303 
304  @Override
305  public Map<String, String> visit(LocalDirectory ld) {
306  return getCommonAndMACTimeFields(ld);
307  }
308 
309  @Override
310  public Map<String, String> visit(LayoutFile lf) {
311  // layout files do not have times
312  return getCommonFields(lf);
313  }
314 
315  @Override
316  public Map<String, String> visit(LocalFile lf) {
317  return getCommonAndMACTimeFields(lf);
318  }
319 
320  @Override
321  public Map<String, String> visit(SlackFile f) {
322  return getCommonAndMACTimeFields(f);
323  }
324 
334  private Map<String, String> getCommonAndMACTimeFields(AbstractFile file) {
335  Map<String, String> params = getCommonFields(file);
336  params.put(Server.Schema.CTIME.toString(), ContentUtils.getStringTimeISO8601(file.getCtime(), file));
337  params.put(Server.Schema.ATIME.toString(), ContentUtils.getStringTimeISO8601(file.getAtime(), file));
338  params.put(Server.Schema.MTIME.toString(), ContentUtils.getStringTimeISO8601(file.getMtime(), file));
339  params.put(Server.Schema.CRTIME.toString(), ContentUtils.getStringTimeISO8601(file.getCrtime(), file));
340  return params;
341  }
342 
351  private Map<String, String> getCommonFields(AbstractFile file) {
352  Map<String, String> params = new HashMap<>();
353  params.put(Server.Schema.ID.toString(), Long.toString(file.getId()));
354  try {
355  params.put(Server.Schema.IMAGE_ID.toString(), Long.toString(file.getDataSource().getId()));
356  } catch (TskCoreException ex) {
357  logger.log(Level.SEVERE, "Could not get data source id to properly index the file " + file.getId(), ex); //NON-NLS
358  params.put(Server.Schema.IMAGE_ID.toString(), Long.toString(-1));
359  }
360  params.put(Server.Schema.FILE_NAME.toString(), file.getName().toLowerCase());
361  return params;
362  }
363 
371  @Override
372  public Map<String, String> visit(BlackboardArtifact artifact) {
373  Map<String, String> params = new HashMap<>();
374  params.put(Server.Schema.ID.toString(), Long.toString(artifact.getArtifactID()));
375  try {
376  params.put(Server.Schema.IMAGE_ID.toString(), Long.toString(artifact.getDataSource().getId()));
377  } catch (TskCoreException ex) {
378  logger.log(Level.SEVERE, "Could not get data source id to properly index the artifact " + artifact.getArtifactID(), ex); //NON-NLS
379  params.put(Server.Schema.IMAGE_ID.toString(), Long.toString(-1));
380  }
381  return params;
382  }
383 
391  @Override
392  public Map<String, String> visit(Report report) {
393  Map<String, String> params = new HashMap<>();
394  params.put(Server.Schema.ID.toString(), Long.toString(report.getId()));
395  try {
396  Content dataSource = report.getDataSource();
397  if (null == dataSource) {
398  params.put(Server.Schema.IMAGE_ID.toString(), Long.toString(-1));
399  } else {
400  params.put(Server.Schema.IMAGE_ID.toString(), Long.toString(dataSource.getId()));
401  }
402  } catch (TskCoreException ex) {
403  logger.log(Level.SEVERE, "Could not get data source id to properly index the report, using default value. Id: " + report.getId(), ex); //NON-NLS
404  params.put(Server.Schema.IMAGE_ID.toString(), Long.toString(-1));
405  }
406  return params;
407  }
408  }
409 
414  static class IngesterException extends Exception {
415 
416  private static final long serialVersionUID = 1L;
417 
418  IngesterException(String message, Throwable ex) {
419  super(message, ex);
420  }
421 
422  IngesterException(String message) {
423  super(message);
424  }
425  }
426 }
Map< String, String > visit(LocalDirectory ld)
Definition: Ingester.java:305
Map< String, String > getCommonAndMACTimeFields(AbstractFile file)
Definition: Ingester.java:334
static String getStringTimeISO8601(long epochSeconds, TimeZone tzone)
Map< String, String > getCommonFields(AbstractFile file)
Definition: Ingester.java:351
Map< String, String > visit(BlackboardArtifact artifact)
Definition: Ingester.java:372
Map< String, String > defaultVisit(SleuthkitVisitableItem svi)
Definition: Ingester.java:285

Copyright © 2012-2020 Basis Technology. Generated on: Wed Apr 8 2020
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.