19 package org.sleuthkit.datamodel;
21 import com.google.common.annotations.Beta;
22 import com.google.common.cache.Cache;
23 import com.google.common.cache.CacheBuilder;
24 import com.google.common.collect.ImmutableSet;
25 import com.google.common.eventbus.EventBus;
26 import com.mchange.v2.c3p0.ComboPooledDataSource;
27 import com.mchange.v2.c3p0.DataSources;
28 import com.mchange.v2.c3p0.PooledDataSource;
29 import com.zaxxer.sparsebits.SparseBitSet;
30 import java.beans.PropertyVetoException;
31 import java.io.BufferedInputStream;
32 import java.io.BufferedOutputStream;
34 import java.io.FileInputStream;
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.OutputStream;
39 import java.io.UnsupportedEncodingException;
40 import java.net.InetAddress;
41 import java.net.URLEncoder;
42 import java.nio.charset.StandardCharsets;
43 import java.nio.file.Paths;
44 import java.sql.Connection;
45 import java.sql.DriverManager;
46 import java.sql.PreparedStatement;
47 import java.sql.ResultSet;
48 import java.sql.SQLException;
49 import java.sql.Statement;
50 import java.text.SimpleDateFormat;
51 import java.util.ArrayList;
52 import java.util.Arrays;
53 import java.util.Collection;
54 import java.util.Collections;
55 import java.util.concurrent.atomic.AtomicBoolean;
56 import java.util.concurrent.atomic.AtomicInteger;
57 import java.util.Date;
58 import java.util.EnumMap;
59 import java.util.HashMap;
60 import java.util.HashSet;
61 import java.util.LinkedHashMap;
62 import java.util.List;
64 import java.util.MissingResourceException;
65 import java.util.Objects;
66 import java.util.Properties;
67 import java.util.ResourceBundle;
69 import java.util.UUID;
70 import java.util.concurrent.TimeUnit;
71 import java.util.concurrent.locks.ReentrantReadWriteLock;
72 import java.util.logging.Level;
73 import java.util.logging.Logger;
74 import java.util.stream.Collectors;
75 import org.apache.commons.lang3.StringUtils;
76 import org.postgresql.util.PSQLState;
95 import org.sqlite.SQLiteConfig;
96 import org.sqlite.SQLiteDataSource;
97 import org.sqlite.SQLiteJDBCLoader;
105 private static final int MAX_DB_NAME_LEN_BEFORE_TIMESTAMP = 47;
110 private static final long BASE_ARTIFACT_ID = Long.MIN_VALUE;
111 private static final Logger logger = Logger.getLogger(
SleuthkitCase.class.getName());
112 private static final ResourceBundle bundle = ResourceBundle.getBundle(
"org.sleuthkit.datamodel.Bundle");
113 private static final int IS_REACHABLE_TIMEOUT_MS = 1000;
114 private static final String SQL_ERROR_CONNECTION_GROUP =
"08";
116 private static final String SQL_CONNECTION_REJECTED =
"08004";
117 private static final String UNABLE_TO_VERIFY_SSL =
"08006";
119 private static final String SQL_ERROR_AUTHENTICATION_GROUP =
"28";
120 private static final String SQL_ERROR_PRIVILEGE_GROUP =
"42";
121 private static final String SQL_ERROR_RESOURCE_GROUP =
"53";
122 private static final String SQL_ERROR_LIMIT_GROUP =
"54";
123 private static final String SQL_ERROR_INTERNAL_GROUP =
"xx";
125 private static final Set<String> CORE_TABLE_NAMES = ImmutableSet.of(
127 "tsk_event_descriptions",
140 "tsk_files_derived_method",
143 "blackboard_artifact_tags",
144 "blackboard_artifacts",
145 "blackboard_attributes",
146 "blackboard_artifact_types",
147 "blackboard_attribute_types",
149 "file_encoding_types",
150 "file_collection_status_types",
151 "ingest_module_types",
152 "ingest_job_status_types",
155 "ingest_job_modules",
158 "account_relationships",
162 private static final Set<String> CORE_INDEX_NAMES = ImmutableSet.of(
166 "artifact_artifact_objID",
171 "relationships_account1",
172 "relationships_account2",
173 "relationships_relationship_source_obj_id",
174 "relationships_date_time",
175 "relationships_relationship_type",
176 "relationships_data_source_obj_id",
179 "events_data_source_obj_id",
180 "events_file_obj_id",
181 "events_artifact_id");
183 private static final String TSK_VERSION_KEY =
"TSK_VER";
184 private static final String SCHEMA_MAJOR_VERSION_KEY =
"SCHEMA_MAJOR_VERSION";
185 private static final String SCHEMA_MINOR_VERSION_KEY =
"SCHEMA_MINOR_VERSION";
186 private static final String CREATION_SCHEMA_MAJOR_VERSION_KEY =
"CREATION_SCHEMA_MAJOR_VERSION";
187 private static final String CREATION_SCHEMA_MINOR_VERSION_KEY =
"CREATION_SCHEMA_MINOR_VERSION";
189 private final ConnectionPool connections;
190 private final Object carvedFileDirsLock =
new Object();
191 private final static int MAX_CARVED_FILES_PER_FOLDER = 2000;
192 private final Map<Long, CarvedFileDirInfo> rootIdsToCarvedFileDirs =
new HashMap<>();
193 private final Map<Long, FileSystem> fileSystemIdMap =
new HashMap<>();
194 private final List<ErrorObserver> sleuthkitCaseErrorObservers =
new ArrayList<>();
195 private final String databaseName;
196 private final String dbPath;
197 private final DbType dbType;
198 private final String caseDirPath;
200 private final String caseHandleIdentifier;
201 private String dbBackupPath;
202 private AtomicBoolean timelineEventsDisabled =
new AtomicBoolean(
false);
207 private final Object rootDirectoryMapLock =
new Object();
208 private final Map<RootDirectoryKey, Long> rootDirectoryMap =
new HashMap<>();
209 private final Cache<Long, Boolean> isRootDirectoryCache
210 = CacheBuilder.newBuilder().maximumSize(200000).expireAfterAccess(5, TimeUnit.MINUTES).build();
218 private final Map<Long, SparseBitSet> hasChildrenBitSetMap =
new HashMap<>();
220 private long nextArtifactId;
225 private final ReentrantReadWriteLock rwLock =
new ReentrantReadWriteLock(
true);
240 private final Map<String, Set<Long>> deviceIdToDatasourceObjIdMap =
new HashMap<>();
242 private final EventBus eventBus =
new EventBus(
"SleuthkitCase-EventBus");
245 eventBus.register(listener);
249 eventBus.unregister(listener);
252 void fireTSKEvent(Object event) {
253 eventBus.post(event);
257 private final Map<Long, Content> frequentlyUsedContentMap =
new HashMap<>();
259 private Examiner cachedCurrentExaminer = null;
262 Properties p =
new Properties(System.getProperties());
263 p.put(
"com.mchange.v2.log.MLog",
"com.mchange.v2.log.FallbackMLog");
264 p.put(
"com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL",
"SEVERE");
265 System.setProperties(p);
284 if (info.getHost() == null || info.getHost().isEmpty()) {
285 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingHostname"));
286 }
else if (info.getPort() == null || info.getPort().isEmpty()) {
287 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingPort"));
288 }
else if (info.getUserName() == null || info.getUserName().isEmpty()) {
289 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingUsername"));
290 }
else if (info.getPassword() == null || info.getPassword().isEmpty()) {
291 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingPassword"));
295 Class.forName(
"org.postgresql.Driver");
296 String connectionURL =
"jdbc:postgresql://" + info.getHost() +
":" + info.getPort() +
"/postgres";
297 if (info.isSslEnabled()) {
298 if (info.isSslVerify()) {
299 if (info.getCustomSslValidationClassName().isBlank()) {
300 connectionURL += CaseDatabaseFactory.SSL_VERIFY_DEFAULT_URL;
303 connectionURL += CaseDatabaseFactory.getCustomPostrgesSslVerificationUrl(info.getCustomSslValidationClassName());
306 connectionURL += CaseDatabaseFactory.SSL_NONVERIFY_URL;
309 Connection conn = DriverManager.getConnection(connectionURL, info.getUserName(), info.getPassword());
313 }
catch (SQLException ex) {
315 String sqlState = ex.getSQLState().toLowerCase();
316 if (sqlState.startsWith(SQL_ERROR_CONNECTION_GROUP)) {
317 if (SQL_CONNECTION_REJECTED.equals(ex.getSQLState())) {
318 if (info.isSslEnabled()) {
319 result =
"Server rejected the SSL connection attempt. Check SSL configuration.";
321 result =
"Server rejected the connection attempt. Check server configuration.";
323 }
else if (UNABLE_TO_VERIFY_SSL.equals(ex.getSQLState())) {
324 result =
"Unable to verify SSL certificates. Check SSL configuration.";
327 if (InetAddress.getByName(info.getHost()).isReachable(IS_REACHABLE_TIMEOUT_MS)) {
329 result = bundle.getString(
"DatabaseConnectionCheck.Port");
331 result = bundle.getString(
"DatabaseConnectionCheck.HostnameOrPort");
333 }
catch (IOException | MissingResourceException any) {
335 result = bundle.getString(
"DatabaseConnectionCheck.Everything");
338 }
else if (sqlState.startsWith(SQL_ERROR_AUTHENTICATION_GROUP)) {
339 result = bundle.getString(
"DatabaseConnectionCheck.Authentication");
340 }
else if (sqlState.startsWith(SQL_ERROR_PRIVILEGE_GROUP)) {
341 result = bundle.getString(
"DatabaseConnectionCheck.Access");
342 }
else if (sqlState.startsWith(SQL_ERROR_RESOURCE_GROUP)) {
343 result = bundle.getString(
"DatabaseConnectionCheck.ServerDiskSpace");
344 }
else if (sqlState.startsWith(SQL_ERROR_LIMIT_GROUP)) {
345 result = bundle.getString(
"DatabaseConnectionCheck.ServerRestart");
346 }
else if (sqlState.startsWith(SQL_ERROR_INTERNAL_GROUP)) {
347 result = bundle.getString(
"DatabaseConnectionCheck.InternalServerIssue");
349 result = bundle.getString(
"DatabaseConnectionCheck.Connection");
352 }
catch (ClassNotFoundException ex) {
353 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.Installation"));
370 Class.forName(
"org.sqlite.JDBC");
371 this.dbPath = dbPath;
372 this.dbType = dbType;
374 this.caseDirPath = dbFile.getParentFile().getAbsolutePath();
375 this.databaseName = dbFile.
getName();
376 this.connections =
new SQLiteConnections(dbPath);
377 this.caseHandle = caseHandle;
378 this.caseHandleIdentifier = caseHandle.getCaseDbIdentifier();
379 this.contentProvider = contentProvider;
381 logSQLiteJDBCDriverInfo();
395 private SleuthkitCase(CaseDbConnectionInfo info, String dbName, SleuthkitJNI.CaseDbHandle caseHandle, String caseDirPath, ContentStreamProvider contentProvider)
throws Exception {
397 this.databaseName = dbName;
398 this.dbType = info.getDbType();
399 this.caseDirPath = caseDirPath;
400 this.connections =
new PostgreSQLConnections(info, dbName);
401 this.caseHandle = caseHandle;
402 this.caseHandleIdentifier = caseHandle.getCaseDbIdentifier();
403 this.contentProvider = contentProvider;
407 private void init() throws Exception {
408 blackboard =
new Blackboard(
this);
409 updateDatabaseSchema(null);
410 try (CaseDbConnection connection = connections.getConnection()) {
411 blackboard.initBlackboardArtifactTypes(connection);
412 blackboard.initBlackboardAttributeTypes(connection);
413 initNextArtifactId(connection);
414 initIngestModuleTypes(connection);
415 initIngestStatusTypes(connection);
416 initReviewStatuses(connection);
417 initEncodingTypes(connection);
418 initCollectedStatusTypes(connection);
419 populateHasChildrenMap(connection);
420 updateExaminers(connection);
421 initDBSchemaCreationVersion(connection);
424 fileManager =
new FileManager(
this);
425 communicationsMgr =
new CommunicationsManager(
this);
426 timelineMgr =
new TimelineManager(
this);
427 dbAccessManager =
new CaseDbAccessManager(
this);
428 taggingMgr =
new TaggingManager(
this);
429 scoringManager =
new ScoringManager(
this);
430 osAccountRealmManager =
new OsAccountRealmManager(
this);
431 osAccountManager =
new OsAccountManager(
this);
432 hostManager =
new HostManager(
this);
433 personManager =
new PersonManager(
this);
434 hostAddressManager =
new HostAddressManager(
this);
444 ContentStreamProvider getContentProvider() {
445 return this.contentProvider;
453 static Set<String> getCoreTableNames() {
454 return Collections.unmodifiableSet(CORE_TABLE_NAMES);
462 static Set<String> getCoreIndexNames() {
463 return Collections.unmodifiableSet(CORE_INDEX_NAMES);
474 boolean getHasChildren(Content content) {
475 long objId = content.getId();
476 long mapIndex = objId / Integer.MAX_VALUE;
477 int mapValue = (int) (objId % Integer.MAX_VALUE);
479 synchronized (hasChildrenBitSetMap) {
480 if (hasChildrenBitSetMap.containsKey(mapIndex)) {
481 return hasChildrenBitSetMap.get(mapIndex).get(mapValue);
492 private void setHasChildren(Long objId) {
493 long mapIndex = objId / Integer.MAX_VALUE;
494 int mapValue = (int) (objId % Integer.MAX_VALUE);
496 synchronized (hasChildrenBitSetMap) {
497 if (hasChildrenBitSetMap.containsKey(mapIndex)) {
498 hasChildrenBitSetMap.get(mapIndex).set(mapValue);
500 SparseBitSet bitSet =
new SparseBitSet();
501 bitSet.set(mapValue);
502 hasChildrenBitSetMap.put(mapIndex, bitSet);
515 return communicationsMgr;
555 return dbAccessManager;
575 return scoringManager;
586 return osAccountRealmManager;
597 return osAccountManager;
619 return personManager;
630 return hostAddressManager;
642 private void initNextArtifactId(CaseDbConnection connection)
throws SQLException {
644 try (Statement statement = connection.createStatement()) {
645 ResultSet resultSet = connection.executeQuery(statement,
"SELECT MAX(artifact_id) AS max_artifact_id FROM blackboard_artifacts");
647 nextArtifactId = resultSet.getLong(
"max_artifact_id") + 1;
648 if (nextArtifactId == 1) {
649 nextArtifactId = BASE_ARTIFACT_ID;
663 private void initIngestModuleTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
664 Statement statement = null;
665 ResultSet resultSet = null;
668 statement = connection.createStatement();
669 for (IngestModuleType type : IngestModuleType.values()) {
671 String query =
"INSERT INTO ingest_module_types (type_id, type_name) VALUES (" + type.ordinal() +
", '" + type.toString() +
"')";
673 query +=
" ON CONFLICT ON CONSTRAINT ingest_module_types_pkey DO NOTHING";
675 statement.execute(query);
676 }
catch (SQLException ex) {
677 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM ingest_module_types WHERE type_id = " + type.ordinal() +
";");
679 if (resultSet.getLong(
"count") == 0) {
687 closeResultSet(resultSet);
688 closeStatement(statement);
700 private void initIngestStatusTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
701 Statement statement = null;
702 ResultSet resultSet = null;
705 statement = connection.createStatement();
706 for (IngestJobStatusType type : IngestJobStatusType.values()) {
708 String query =
"INSERT INTO ingest_job_status_types (type_id, type_name) VALUES (" + type.ordinal() +
", '" + type.toString() +
"')";
710 query +=
" ON CONFLICT ON CONSTRAINT ingest_job_status_types_pkey DO NOTHING";
712 statement.execute(query);
713 }
catch (SQLException ex) {
714 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM ingest_job_status_types WHERE type_id = " + type.ordinal() +
";");
716 if (resultSet.getLong(
"count") == 0) {
724 closeResultSet(resultSet);
725 closeStatement(statement);
736 private void initReviewStatuses(CaseDbConnection connection)
throws SQLException, TskCoreException {
737 Statement statement = null;
738 ResultSet resultSet = null;
741 statement = connection.createStatement();
742 for (BlackboardArtifact.ReviewStatus status : BlackboardArtifact.ReviewStatus.values()) {
744 String query =
"INSERT INTO review_statuses (review_status_id, review_status_name, display_name) "
745 +
"VALUES (" + status.getID() +
",'" + status.getName() +
"','" + status.getDisplayName() +
"')";
747 query +=
" ON CONFLICT ON CONSTRAINT review_statuses_pkey DO NOTHING";
749 statement.execute(query);
750 }
catch (SQLException ex) {
751 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM review_statuses WHERE review_status_id = " + status.getID());
753 if (resultSet.getLong(
"count") == 0) {
761 closeResultSet(resultSet);
762 closeStatement(statement);
774 private void initEncodingTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
775 Statement statement = null;
776 ResultSet resultSet = null;
779 statement = connection.createStatement();
780 for (TskData.EncodingType type : TskData.EncodingType.values()) {
782 String query =
"INSERT INTO file_encoding_types (encoding_type, name) VALUES (" + type.getType() +
" , '" + type.name() +
"')";
784 query +=
" ON CONFLICT ON CONSTRAINT file_encoding_types_pkey DO NOTHING";
786 statement.execute(query);
787 }
catch (SQLException ex) {
788 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM file_encoding_types WHERE encoding_type = " + type.getType());
790 if (resultSet.getLong(
"count") == 0) {
798 closeResultSet(resultSet);
799 closeStatement(statement);
811 private void initCollectedStatusTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
812 Statement statement = null;
813 ResultSet resultSet = null;
816 statement = connection.createStatement();
817 for (TskData.CollectedStatus type : TskData.CollectedStatus.values()) {
819 String query =
"INSERT INTO file_collection_status_types (collection_status_type, name) VALUES (" + type.getType() +
" , '" + type.name() +
"')";
821 query +=
" ON CONFLICT ON CONSTRAINT file_collection_status_types_pkey DO NOTHING";
823 statement.execute(query);
824 }
catch (SQLException ex) {
825 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM file_collection_status_types WHERE collection_status_type = " + type.getType());
827 if (resultSet.getLong(
"count") == 0) {
835 closeResultSet(resultSet);
836 closeStatement(statement);
849 private void updateExaminers(CaseDbConnection connection)
throws SQLException, TskCoreException {
851 String loginName = System.getProperty(
"user.name");
852 if (loginName.isEmpty()) {
853 logger.log(Level.SEVERE,
"Cannot determine logged in user name");
859 PreparedStatement statement;
862 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_EXAMINER_POSTGRESQL);
865 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_EXAMINER_SQLITE);
868 throw new TskCoreException(
"Unknown DB Type: " +
getDatabaseType().name());
870 statement.clearParameters();
871 statement.setString(1, loginName);
872 connection.executeUpdate(statement);
873 }
catch (SQLException ex) {
874 throw new TskCoreException(
"Error inserting row in tsk_examiners. login name: " + loginName, ex);
887 private void populateHasChildrenMap(CaseDbConnection connection)
throws TskCoreException {
888 long timestamp = System.currentTimeMillis();
890 Statement statement = null;
891 ResultSet resultSet = null;
894 statement = connection.createStatement();
895 resultSet = statement.executeQuery(
"select distinct par_obj_id from tsk_objects");
897 synchronized (hasChildrenBitSetMap) {
898 while (resultSet.next()) {
899 setHasChildren(resultSet.getLong(
"par_obj_id"));
902 long delay = System.currentTimeMillis() - timestamp;
903 logger.log(Level.INFO,
"Time to initialize parent node cache: {0} ms", delay);
904 }
catch (SQLException ex) {
905 throw new TskCoreException(
"Error populating parent node cache", ex);
907 closeResultSet(resultSet);
908 closeStatement(statement);
919 void addDataSourceToHasChildrenMap() throws TskCoreException {
921 CaseDbConnection connection = connections.getConnection();
923 populateHasChildrenMap(connection);
925 closeConnection(connection);
938 private void updateDatabaseSchema(String dbPath)
throws Exception {
939 CaseDbConnection connection = null;
940 ResultSet resultSet = null;
941 Statement statement = null;
944 connection = connections.getConnection();
945 connection.beginTransaction();
947 boolean hasMinorVersion =
false;
948 ResultSet columns = connection.getConnection().getMetaData().getColumns(null, null,
"tsk_db_info",
"schema%");
949 while (columns.next()) {
950 if (columns.getString(
"COLUMN_NAME").equals(
"schema_minor_ver")) {
951 hasMinorVersion =
true;
956 int dbSchemaMajorVersion;
957 int dbSchemaMinorVersion = 0;
959 statement = connection.createStatement();
960 resultSet = connection.executeQuery(statement,
"SELECT schema_ver"
961 + (hasMinorVersion ?
", schema_minor_ver" :
"")
962 +
" FROM tsk_db_info");
963 if (resultSet.next()) {
964 dbSchemaMajorVersion = resultSet.getInt(
"schema_ver");
965 if (hasMinorVersion) {
967 dbSchemaMinorVersion = resultSet.getInt(
"schema_minor_ver");
970 throw new TskCoreException();
972 CaseDbSchemaVersionNumber dbSchemaVersion =
new CaseDbSchemaVersionNumber(dbSchemaMajorVersion, dbSchemaMinorVersion);
979 if (
false == CURRENT_DB_SCHEMA_VERSION.
isCompatible(dbSchemaVersion)) {
981 throw new TskUnsupportedSchemaVersionException(
982 "Unsupported DB schema version " + dbSchemaVersion +
", the highest supported schema version is " + CURRENT_DB_SCHEMA_VERSION.
getMajor() +
".X");
983 }
else if (dbSchemaVersion.compareTo(CURRENT_DB_SCHEMA_VERSION) < 0) {
986 if (null != dbPath) {
989 String backupFilePath = dbPath +
".schemaVer" + dbSchemaVersion.toString() +
".backup";
991 dbBackupPath = backupFilePath;
998 dbSchemaVersion = updateFromSchema2toSchema3(dbSchemaVersion, connection);
999 dbSchemaVersion = updateFromSchema3toSchema4(dbSchemaVersion, connection);
1000 dbSchemaVersion = updateFromSchema4toSchema5(dbSchemaVersion, connection);
1001 dbSchemaVersion = updateFromSchema5toSchema6(dbSchemaVersion, connection);
1002 dbSchemaVersion = updateFromSchema6toSchema7(dbSchemaVersion, connection);
1003 dbSchemaVersion = updateFromSchema7toSchema7dot1(dbSchemaVersion, connection);
1004 dbSchemaVersion = updateFromSchema7dot1toSchema7dot2(dbSchemaVersion, connection);
1005 dbSchemaVersion = updateFromSchema7dot2toSchema8dot0(dbSchemaVersion, connection);
1006 dbSchemaVersion = updateFromSchema8dot0toSchema8dot1(dbSchemaVersion, connection);
1007 dbSchemaVersion = updateFromSchema8dot1toSchema8dot2(dbSchemaVersion, connection);
1008 dbSchemaVersion = updateFromSchema8dot2toSchema8dot3(dbSchemaVersion, connection);
1009 dbSchemaVersion = updateFromSchema8dot3toSchema8dot4(dbSchemaVersion, connection);
1010 dbSchemaVersion = updateFromSchema8dot4toSchema8dot5(dbSchemaVersion, connection);
1011 dbSchemaVersion = updateFromSchema8dot5toSchema8dot6(dbSchemaVersion, connection);
1012 dbSchemaVersion = updateFromSchema8dot6toSchema9dot0(dbSchemaVersion, connection);
1013 dbSchemaVersion = updateFromSchema9dot0toSchema9dot1(dbSchemaVersion, connection);
1014 dbSchemaVersion = updateFromSchema9dot1toSchema9dot2(dbSchemaVersion, connection);
1015 dbSchemaVersion = updateFromSchema9dot2toSchema9dot3(dbSchemaVersion, connection);
1016 dbSchemaVersion = updateFromSchema9dot3toSchema9dot4(dbSchemaVersion, connection);
1020 statement = connection.createStatement();
1021 connection.executeUpdate(statement,
"UPDATE tsk_db_info SET schema_ver = " + dbSchemaVersion.getMajor() +
", schema_minor_ver = " + dbSchemaVersion.getMinor());
1022 connection.executeUpdate(statement,
"UPDATE tsk_db_info_extended SET value = " + dbSchemaVersion.getMajor() +
" WHERE name = '" + SCHEMA_MAJOR_VERSION_KEY +
"'");
1023 connection.executeUpdate(statement,
"UPDATE tsk_db_info_extended SET value = " + dbSchemaVersion.getMinor() +
" WHERE name = '" + SCHEMA_MINOR_VERSION_KEY +
"'");
1028 connection.commitTransaction();
1029 }
catch (Exception ex) {
1030 rollbackTransaction(connection);
1033 closeResultSet(resultSet);
1034 closeStatement(statement);
1035 closeConnection(connection);
1047 private void initDBSchemaCreationVersion(CaseDbConnection connection)
throws SQLException {
1049 Statement statement = null;
1050 ResultSet resultSet = null;
1051 String createdSchemaMajorVersion =
"0";
1052 String createdSchemaMinorVersion =
"0";
1055 statement = connection.createStatement();
1056 resultSet = connection.executeQuery(statement,
"SELECT name, value FROM tsk_db_info_extended");
1057 while (resultSet.next()) {
1058 String name = resultSet.getString(
"name");
1059 if (name.equals(CREATION_SCHEMA_MAJOR_VERSION_KEY) || name.equals(
"CREATED_SCHEMA_MAJOR_VERSION")) {
1060 createdSchemaMajorVersion = resultSet.getString(
"value");
1061 }
else if (name.equals(CREATION_SCHEMA_MINOR_VERSION_KEY) || name.equals(
"CREATED_SCHEMA_MINOR_VERSION")) {
1062 createdSchemaMinorVersion = resultSet.getString(
"value");
1067 closeResultSet(resultSet);
1068 closeStatement(statement);
1072 caseDBSchemaCreationVersion =
new CaseDbSchemaVersionNumber(Integer.parseInt(createdSchemaMajorVersion), Integer.parseInt(createdSchemaMinorVersion));
1085 if (dbPath.isEmpty()) {
1086 throw new IOException(
"Copying case database files is not supported for this type of case database");
1088 InputStream in = null;
1089 OutputStream out = null;
1092 InputStream inFile =
new FileInputStream(dbPath);
1093 in =
new BufferedInputStream(inFile);
1094 OutputStream outFile =
new FileOutputStream(newDBPath);
1095 out =
new BufferedOutputStream(outFile);
1096 int bytesRead = in.read();
1097 while (bytesRead != -1) {
1098 out.write(bytesRead);
1099 bytesRead = in.read();
1110 }
catch (IOException e) {
1111 logger.log(Level.WARNING,
"Could not close streams after db copy", e);
1120 private void logSQLiteJDBCDriverInfo() {
1122 SleuthkitCase.logger.info(String.format(
"sqlite-jdbc version %s loaded in %s mode",
1123 SQLiteJDBCLoader.getVersion(), SQLiteJDBCLoader.isNativeMode()
1124 ?
"native" :
"pure-java"));
1125 }
catch (Exception ex) {
1126 SleuthkitCase.logger.log(Level.SEVERE,
"Error querying case database mode", ex);
1143 @SuppressWarnings(
"deprecation")
1144 private CaseDbSchemaVersionNumber updateFromSchema2toSchema3(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection) throws SQLException, TskCoreException {
1145 if (schemaVersion.getMajor() != 2) {
1146 return schemaVersion;
1148 Statement statement = null;
1149 Statement statement2 = null;
1150 Statement updateStatement = null;
1151 ResultSet resultSet = null;
1154 statement = connection.createStatement();
1155 statement2 = connection.createStatement();
1158 statement.execute(
"CREATE TABLE tag_names (tag_name_id INTEGER PRIMARY KEY, display_name TEXT UNIQUE, description TEXT NOT NULL, color TEXT NOT NULL)");
1159 statement.execute(
"CREATE TABLE content_tags (tag_id INTEGER PRIMARY KEY, obj_id INTEGER NOT NULL, tag_name_id INTEGER NOT NULL, comment TEXT NOT NULL, begin_byte_offset INTEGER NOT NULL, end_byte_offset INTEGER NOT NULL)");
1160 statement.execute(
"CREATE TABLE blackboard_artifact_tags (tag_id INTEGER PRIMARY KEY, artifact_id INTEGER NOT NULL, tag_name_id INTEGER NOT NULL, comment TEXT NOT NULL)");
1163 statement.execute(
"CREATE TABLE reports (report_id INTEGER PRIMARY KEY, path TEXT NOT NULL, crtime INTEGER NOT NULL, src_module_name TEXT NOT NULL, report_name TEXT NOT NULL)");
1166 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN size INTEGER;");
1167 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN md5 TEXT;");
1168 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN display_name TEXT;");
1171 statement.execute(
"ALTER TABLE tsk_fs_info ADD COLUMN display_name TEXT;");
1174 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN meta_seq INTEGER;");
1179 statement.execute(
"ALTER TABLE blackboard_attributes ADD COLUMN artifact_type_id INTEGER NULL NOT NULL DEFAULT -1;");
1180 statement.execute(
"CREATE INDEX attribute_artifactTypeId ON blackboard_attributes(artifact_type_id);");
1181 statement.execute(
"CREATE INDEX attribute_valueText ON blackboard_attributes(value_text);");
1182 statement.execute(
"CREATE INDEX attribute_valueInt32 ON blackboard_attributes(value_int32);");
1183 statement.execute(
"CREATE INDEX attribute_valueInt64 ON blackboard_attributes(value_int64);");
1184 statement.execute(
"CREATE INDEX attribute_valueDouble ON blackboard_attributes(value_double);");
1185 resultSet = statement.executeQuery(
"SELECT attrs.artifact_id AS artifact_id, "
1186 +
"arts.artifact_type_id AS artifact_type_id "
1187 +
"FROM blackboard_attributes AS attrs "
1188 +
"INNER JOIN blackboard_artifacts AS arts "
1189 +
"WHERE attrs.artifact_id = arts.artifact_id;");
1190 updateStatement = connection.createStatement();
1191 while (resultSet.next()) {
1192 long artifactId = resultSet.getLong(
"artifact_id");
1193 int artifactTypeId = resultSet.getInt(
"artifact_type_id");
1194 updateStatement.executeUpdate(
1195 "UPDATE blackboard_attributes "
1196 +
"SET artifact_type_id = " + artifactTypeId
1197 +
" WHERE blackboard_attributes.artifact_id = " + artifactId +
";");
1202 Map<String, Long> tagNames =
new HashMap<>();
1203 long tagNameCounter = 1;
1207 resultSet = statement.executeQuery(
"SELECT * FROM \n"
1208 +
"(SELECT blackboard_artifacts.obj_id AS objId, blackboard_attributes.artifact_id AS artifactId, blackboard_attributes.value_text AS name\n"
1209 +
"FROM blackboard_artifacts INNER JOIN blackboard_attributes \n"
1210 +
"ON blackboard_artifacts.artifact_id = blackboard_attributes.artifact_id \n"
1211 +
"WHERE blackboard_artifacts.artifact_type_id = "
1212 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID()
1213 +
" AND blackboard_attributes.attribute_type_id = " + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TAG_NAME.getTypeID()
1214 +
") AS tagNames \n"
1216 +
"(SELECT tsk_files.obj_id as objId2, tsk_files.size AS fileSize \n"
1217 +
"FROM blackboard_artifacts INNER JOIN tsk_files \n"
1218 +
"ON blackboard_artifacts.obj_id = tsk_files.obj_id) AS fileData \n"
1219 +
"ON tagNames.objId = fileData.objId2 \n"
1221 +
"(SELECT value_text AS comment, artifact_id AS tagArtifactId FROM blackboard_attributes WHERE attribute_type_id = "
1222 + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT.getTypeID() +
") AS tagComments \n"
1223 +
"ON tagNames.artifactId = tagComments.tagArtifactId");
1225 while (resultSet.next()) {
1226 long objId = resultSet.getLong(
"objId");
1227 long fileSize = resultSet.getLong(
"fileSize");
1228 String tagName = resultSet.getString(
"name");
1229 String tagComment = resultSet.getString(
"comment");
1230 if (tagComment == null) {
1234 if (tagName != null && !tagName.isEmpty()) {
1237 if (tagNames.containsKey(tagName)) {
1238 tagNameIndex = tagNames.get(tagName);
1240 statement2.execute(
"INSERT INTO tag_names (display_name, description, color) "
1241 +
"VALUES(\"" + tagName +
"\", \"\", \"None\")");
1242 tagNames.put(tagName, tagNameCounter);
1243 tagNameIndex = tagNameCounter;
1247 statement2.execute(
"INSERT INTO content_tags (obj_id, tag_name_id, comment, begin_byte_offset, end_byte_offset) "
1248 +
"VALUES(" + objId +
", " + tagNameIndex +
", \"" + tagComment +
"\", 0, " + fileSize +
")");
1255 resultSet = statement.executeQuery(
"SELECT * FROM \n"
1256 +
"(SELECT blackboard_artifacts.obj_id AS objId, blackboard_attributes.artifact_id AS artifactId, "
1257 +
"blackboard_attributes.value_text AS name\n"
1258 +
"FROM blackboard_artifacts INNER JOIN blackboard_attributes \n"
1259 +
"ON blackboard_artifacts.artifact_id = blackboard_attributes.artifact_id \n"
1260 +
"WHERE blackboard_artifacts.artifact_type_id = "
1261 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID()
1262 +
" AND blackboard_attributes.attribute_type_id = " + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TAG_NAME.getTypeID()
1263 +
") AS tagNames \n"
1265 +
"(SELECT value_int64 AS taggedArtifactId, artifact_id AS associatedArtifactId FROM blackboard_attributes WHERE attribute_type_id = "
1266 + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TAGGED_ARTIFACT.getTypeID() +
") AS tagArtifacts \n"
1267 +
"ON tagNames.artifactId = tagArtifacts.associatedArtifactId \n"
1269 +
"(SELECT value_text AS comment, artifact_id AS commentArtifactId FROM blackboard_attributes WHERE attribute_type_id = "
1270 + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT.getTypeID() +
") AS tagComments \n"
1271 +
"ON tagNames.artifactId = tagComments.commentArtifactId");
1273 while (resultSet.next()) {
1274 long artifactId = resultSet.getLong(
"taggedArtifactId");
1275 String tagName = resultSet.getString(
"name");
1276 String tagComment = resultSet.getString(
"comment");
1277 if (tagComment == null) {
1280 if (tagName != null && !tagName.isEmpty()) {
1283 if (tagNames.containsKey(tagName)) {
1284 tagNameIndex = tagNames.get(tagName);
1286 statement2.execute(
"INSERT INTO tag_names (display_name, description, color) "
1287 +
"VALUES(\"" + tagName +
"\", \"\", \"None\")");
1288 tagNames.put(tagName, tagNameCounter);
1289 tagNameIndex = tagNameCounter;
1293 statement2.execute(
"INSERT INTO blackboard_artifact_tags (artifact_id, tag_name_id, comment) "
1294 +
"VALUES(" + artifactId +
", " + tagNameIndex +
", \"" + tagComment +
"\")");
1300 "DELETE FROM blackboard_attributes WHERE artifact_id IN "
1301 +
"(SELECT artifact_id FROM blackboard_artifacts WHERE artifact_type_id = "
1302 + ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID()
1303 +
" OR artifact_type_id = " + ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID() +
");");
1305 "DELETE FROM blackboard_artifacts WHERE artifact_type_id = "
1306 + ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID()
1307 +
" OR artifact_type_id = " + ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID() +
";");
1309 return new CaseDbSchemaVersionNumber(3, 0);
1311 closeStatement(updateStatement);
1312 closeResultSet(resultSet);
1313 closeStatement(statement);
1314 closeStatement(statement2);
1332 private CaseDbSchemaVersionNumber updateFromSchema3toSchema4(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1333 if (schemaVersion.getMajor() != 3) {
1334 return schemaVersion;
1337 Statement statement = null;
1338 ResultSet resultSet = null;
1339 Statement queryStatement = null;
1340 ResultSet queryResultSet = null;
1341 Statement updateStatement = null;
1346 statement = connection.createStatement();
1347 updateStatement = connection.createStatement();
1348 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN mime_type TEXT;");
1349 resultSet = statement.executeQuery(
"SELECT files.obj_id AS obj_id, attrs.value_text AS value_text "
1350 +
"FROM tsk_files AS files, blackboard_attributes AS attrs, blackboard_artifacts AS arts "
1351 +
"WHERE files.obj_id = arts.obj_id AND "
1352 +
"arts.artifact_id = attrs.artifact_id AND "
1353 +
"arts.artifact_type_id = 1 AND "
1354 +
"attrs.attribute_type_id = 62");
1355 while (resultSet.next()) {
1356 updateStatement.executeUpdate(
1358 +
"SET mime_type = '" + resultSet.getString(
"value_text") +
"' "
1359 +
"WHERE tsk_files.obj_id = " + resultSet.getInt(
"obj_id") +
";");
1364 statement.execute(
"ALTER TABLE blackboard_attribute_types ADD COLUMN value_type INTEGER NOT NULL DEFAULT -1;");
1365 resultSet = statement.executeQuery(
"SELECT * FROM blackboard_attribute_types AS types");
1366 while (resultSet.next()) {
1367 int attributeTypeId = resultSet.getInt(
"attribute_type_id");
1368 String attributeLabel = resultSet.getString(
"type_name");
1369 if (attributeTypeId < Blackboard.MIN_USER_DEFINED_TYPE_ID) {
1370 updateStatement.executeUpdate(
1371 "UPDATE blackboard_attribute_types "
1372 +
"SET value_type = " + ATTRIBUTE_TYPE.fromLabel(attributeLabel).getValueType().getType() +
" "
1373 +
"WHERE blackboard_attribute_types.attribute_type_id = " + attributeTypeId +
";");
1379 queryStatement = connection.createStatement();
1380 statement.execute(
"CREATE TABLE data_source_info (obj_id INTEGER PRIMARY KEY, device_id TEXT NOT NULL, time_zone TEXT NOT NULL, FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id));");
1381 resultSet = statement.executeQuery(
"SELECT * FROM tsk_objects WHERE par_obj_id IS NULL");
1382 while (resultSet.next()) {
1383 long objectId = resultSet.getLong(
"obj_id");
1384 String timeZone =
"";
1385 queryResultSet = queryStatement.executeQuery(
"SELECT tzone FROM tsk_image_info WHERE obj_id = " + objectId);
1386 if (queryResultSet.next()) {
1387 timeZone = queryResultSet.getString(
"tzone");
1389 queryResultSet.close();
1390 updateStatement.executeUpdate(
"INSERT INTO data_source_info (obj_id, device_id, time_zone) "
1391 +
"VALUES(" + objectId +
", '" + UUID.randomUUID().toString() +
"' , '" + timeZone +
"');");
1405 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN data_source_obj_id BIGINT NOT NULL DEFAULT -1;");
1406 resultSet = statement.executeQuery(
"SELECT tsk_files.obj_id AS obj_id, par_obj_id FROM tsk_files, tsk_objects WHERE tsk_files.obj_id = tsk_objects.obj_id");
1407 while (resultSet.next()) {
1408 long fileId = resultSet.getLong(
"obj_id");
1409 long dataSourceId = getDataSourceObjectId(connection, fileId);
1410 updateStatement.executeUpdate(
"UPDATE tsk_files SET data_source_obj_id = " + dataSourceId +
" WHERE obj_id = " + fileId +
";");
1413 statement.execute(
"CREATE TABLE ingest_module_types (type_id INTEGER PRIMARY KEY, type_name TEXT NOT NULL)");
1414 statement.execute(
"CREATE TABLE ingest_job_status_types (type_id INTEGER PRIMARY KEY, type_name TEXT NOT NULL)");
1415 if (this.dbType.equals(DbType.SQLITE)) {
1416 statement.execute(
"CREATE TABLE ingest_modules (ingest_module_id INTEGER PRIMARY KEY, display_name TEXT NOT NULL, unique_name TEXT UNIQUE NOT NULL, type_id INTEGER NOT NULL, version TEXT NOT NULL, FOREIGN KEY(type_id) REFERENCES ingest_module_types(type_id));");
1417 statement.execute(
"CREATE TABLE ingest_jobs (ingest_job_id INTEGER PRIMARY KEY, obj_id BIGINT NOT NULL, host_name TEXT NOT NULL, start_date_time BIGINT NOT NULL, end_date_time BIGINT NOT NULL, status_id INTEGER NOT NULL, settings_dir TEXT, FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id), FOREIGN KEY(status_id) REFERENCES ingest_job_status_types(type_id));");
1419 statement.execute(
"CREATE TABLE ingest_modules (ingest_module_id BIGSERIAL PRIMARY KEY, display_name TEXT NOT NULL, unique_name TEXT UNIQUE NOT NULL, type_id INTEGER NOT NULL, version TEXT NOT NULL, FOREIGN KEY(type_id) REFERENCES ingest_module_types(type_id));");
1420 statement.execute(
"CREATE TABLE ingest_jobs (ingest_job_id BIGSERIAL PRIMARY KEY, obj_id BIGINT NOT NULL, host_name TEXT NOT NULL, start_date_time BIGINT NOT NULL, end_date_time BIGINT NOT NULL, status_id INTEGER NOT NULL, settings_dir TEXT, FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id), FOREIGN KEY(status_id) REFERENCES ingest_job_status_types(type_id));");
1423 statement.execute(
"CREATE TABLE ingest_job_modules (ingest_job_id INTEGER, ingest_module_id INTEGER, pipeline_position INTEGER, PRIMARY KEY(ingest_job_id, ingest_module_id), FOREIGN KEY(ingest_job_id) REFERENCES ingest_jobs(ingest_job_id), FOREIGN KEY(ingest_module_id) REFERENCES ingest_modules(ingest_module_id));");
1424 initIngestModuleTypes(connection);
1425 initIngestStatusTypes(connection);
1427 return new CaseDbSchemaVersionNumber(4, 0);
1430 closeResultSet(queryResultSet);
1431 closeStatement(queryStatement);
1432 closeStatement(updateStatement);
1433 closeResultSet(resultSet);
1434 closeStatement(statement);
1452 private CaseDbSchemaVersionNumber updateFromSchema4toSchema5(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1453 if (schemaVersion.getMajor() != 4) {
1454 return schemaVersion;
1457 Statement statement = null;
1461 statement = connection.createStatement();
1462 statement.execute(
"CREATE TABLE review_statuses (review_status_id INTEGER PRIMARY KEY, review_status_name TEXT NOT NULL, display_name TEXT NOT NULL)");
1472 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN review_status_id INTEGER NOT NULL DEFAULT " + BlackboardArtifact.ReviewStatus.UNDECIDED.getID());
1475 statement.execute(
"CREATE TABLE file_encoding_types (encoding_type INTEGER PRIMARY KEY, name TEXT NOT NULL);");
1476 initEncodingTypes(connection);
1483 initReviewStatuses(connection);
1488 statement.execute(
"ALTER TABLE tsk_files_path ADD COLUMN encoding_type INTEGER NOT NULL DEFAULT 0;");
1490 return new CaseDbSchemaVersionNumber(5, 0);
1493 closeStatement(statement);
1511 private CaseDbSchemaVersionNumber updateFromSchema5toSchema6(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1512 if (schemaVersion.getMajor() != 5) {
1513 return schemaVersion;
1520 Statement statement = null;
1521 ResultSet resultSet = null;
1527 statement = connection.createStatement();
1528 statement.execute(
"CREATE TABLE IF NOT EXISTS review_statuses (review_status_id INTEGER PRIMARY KEY, review_status_name TEXT NOT NULL, display_name TEXT NOT NULL)");
1530 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) AS count FROM review_statuses");
1532 if (resultSet.getLong(
"count") == 0) {
1541 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN review_status_id INTEGER NOT NULL DEFAULT " + BlackboardArtifact.ReviewStatus.UNDECIDED.getID());
1544 return new CaseDbSchemaVersionNumber(6, 0);
1547 closeResultSet(resultSet);
1548 closeStatement(statement);
1566 private CaseDbSchemaVersionNumber updateFromSchema6toSchema7(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1567 if (schemaVersion.getMajor() != 6) {
1568 return schemaVersion;
1574 Statement statement = null;
1575 Statement updstatement = null;
1576 ResultSet resultSet = null;
1579 statement = connection.createStatement();
1580 updstatement = connection.createStatement();
1581 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN extension TEXT");
1583 resultSet = connection.executeQuery(statement,
"SELECT obj_id,name FROM tsk_files");
1584 while (resultSet.next()) {
1585 long objID = resultSet.getLong(
"obj_id");
1586 String name = resultSet.getString(
"name");
1587 updstatement.executeUpdate(
"UPDATE tsk_files SET extension = '" +
escapeSingleQuotes(extractExtension(name)) +
"' "
1588 +
"WHERE obj_id = " + objID);
1591 statement.execute(
"CREATE INDEX file_extension ON tsk_files ( extension )");
1594 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN artifact_obj_id INTEGER NOT NULL DEFAULT -1");
1596 return new CaseDbSchemaVersionNumber(7, 0);
1599 closeResultSet(resultSet);
1600 closeStatement(statement);
1601 closeStatement(updstatement);
1619 private CaseDbSchemaVersionNumber updateFromSchema7toSchema7dot1(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1620 if (schemaVersion.getMajor() != 7) {
1621 return schemaVersion;
1624 if (schemaVersion.getMinor() != 0) {
1625 return schemaVersion;
1631 Statement statement = null;
1632 ResultSet resultSet = null;
1635 statement = connection.createStatement();
1638 if (schemaVersion.getMinor() == 0) {
1640 statement.execute(
"ALTER TABLE tsk_db_info ADD COLUMN schema_minor_ver INTEGER DEFAULT 1");
1642 return new CaseDbSchemaVersionNumber(7, 1);
1645 closeResultSet(resultSet);
1646 closeStatement(statement);
1664 private CaseDbSchemaVersionNumber updateFromSchema7dot1toSchema7dot2(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1665 if (schemaVersion.getMajor() != 7) {
1666 return schemaVersion;
1669 if (schemaVersion.getMinor() != 1) {
1670 return schemaVersion;
1673 Statement statement = null;
1674 Statement updstatement = null;
1675 ResultSet resultSet = null;
1679 statement = connection.createStatement();
1680 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN data_source_obj_id INTEGER NOT NULL DEFAULT -1");
1683 updstatement = connection.createStatement();
1684 resultSet = connection.executeQuery(statement,
"SELECT artifact_id, obj_id FROM blackboard_artifacts");
1685 while (resultSet.next()) {
1686 long artifact_id = resultSet.getLong(
"artifact_id");
1687 long obj_id = resultSet.getLong(
"obj_id");
1688 long data_source_obj_id = getDataSourceObjectId(connection, obj_id);
1689 updstatement.executeUpdate(
"UPDATE blackboard_artifacts SET data_source_obj_id = " + data_source_obj_id +
" "
1690 +
"WHERE artifact_id = " + artifact_id);
1692 closeResultSet(resultSet);
1693 closeStatement(statement);
1694 closeStatement(updstatement);
1699 statement = connection.createStatement();
1700 statement.execute(
"ALTER TABLE tag_names ADD COLUMN knownStatus INTEGER NOT NULL DEFAULT " + TskData.FileKnown.UNKNOWN.getFileKnownValue());
1703 if (this.dbType.equals(DbType.SQLITE)) {
1704 statement.execute(
"CREATE TABLE account_types (account_type_id INTEGER PRIMARY KEY, type_name TEXT UNIQUE NOT NULL, display_name TEXT NOT NULL)");
1705 statement.execute(
"CREATE TABLE accounts (account_id INTEGER PRIMARY KEY, account_type_id INTEGER NOT NULL, account_unique_identifier TEXT NOT NULL, UNIQUE(account_type_id, account_unique_identifier) , FOREIGN KEY(account_type_id) REFERENCES account_types(account_type_id))");
1706 statement.execute(
"CREATE TABLE account_relationships (relationship_id INTEGER PRIMARY KEY, account1_id INTEGER NOT NULL, account2_id INTEGER NOT NULL, relationship_source_obj_id INTEGER NOT NULL, date_time INTEGER, relationship_type INTEGER NOT NULL, data_source_obj_id INTEGER NOT NULL, UNIQUE(account1_id, account2_id, relationship_source_obj_id), FOREIGN KEY(account1_id) REFERENCES accounts(account_id), FOREIGN KEY(account2_id) REFERENCES accounts(account_id), FOREIGN KEY(relationship_source_obj_id) REFERENCES tsk_objects(obj_id), FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id))");
1708 statement.execute(
"CREATE TABLE account_types (account_type_id BIGSERIAL PRIMARY KEY, type_name TEXT UNIQUE NOT NULL, display_name TEXT NOT NULL)");
1709 statement.execute(
"CREATE TABLE accounts (account_id BIGSERIAL PRIMARY KEY, account_type_id INTEGER NOT NULL, account_unique_identifier TEXT NOT NULL, UNIQUE(account_type_id, account_unique_identifier) , FOREIGN KEY(account_type_id) REFERENCES account_types(account_type_id))");
1710 statement.execute(
"CREATE TABLE account_relationships (relationship_id BIGSERIAL PRIMARY KEY, account1_id INTEGER NOT NULL, account2_id INTEGER NOT NULL, relationship_source_obj_id INTEGER NOT NULL, date_time BIGINT, relationship_type INTEGER NOT NULL, data_source_obj_id INTEGER NOT NULL, UNIQUE(account1_id, account2_id, relationship_source_obj_id), FOREIGN KEY(account1_id) REFERENCES accounts(account_id), FOREIGN KEY(account2_id) REFERENCES accounts(account_id), FOREIGN KEY(relationship_source_obj_id) REFERENCES tsk_objects(obj_id), FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id))");
1714 statement.execute(
"CREATE INDEX artifact_artifact_objID ON blackboard_artifacts(artifact_obj_id)");
1715 statement.execute(
"CREATE INDEX relationships_account1 ON account_relationships(account1_id)");
1716 statement.execute(
"CREATE INDEX relationships_account2 ON account_relationships(account2_id)");
1717 statement.execute(
"CREATE INDEX relationships_relationship_source_obj_id ON account_relationships(relationship_source_obj_id)");
1718 statement.execute(
"CREATE INDEX relationships_date_time ON account_relationships(date_time)");
1719 statement.execute(
"CREATE INDEX relationships_relationship_type ON account_relationships(relationship_type)");
1720 statement.execute(
"CREATE INDEX relationships_data_source_obj_id ON account_relationships(data_source_obj_id)");
1722 return new CaseDbSchemaVersionNumber(7, 2);
1724 closeResultSet(resultSet);
1725 closeStatement(statement);
1726 closeStatement(updstatement);
1744 private CaseDbSchemaVersionNumber updateFromSchema7dot2toSchema8dot0(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1745 if (schemaVersion.getMajor() != 7) {
1746 return schemaVersion;
1749 if (schemaVersion.getMinor() != 2) {
1750 return schemaVersion;
1753 Statement updateSchemaStatement = connection.createStatement();
1754 Statement getExistingReportsStatement = connection.createStatement();
1755 ResultSet resultSet = null;
1756 ResultSet existingReports = null;
1764 updateSchemaStatement.execute(
"ALTER TABLE reports RENAME TO old_reports");
1767 updateSchemaStatement.execute(
"CREATE TABLE reports (obj_id BIGSERIAL PRIMARY KEY, path TEXT NOT NULL, crtime INTEGER NOT NULL, src_module_name TEXT NOT NULL, report_name TEXT NOT NULL, FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id))");
1770 existingReports = getExistingReportsStatement.executeQuery(
"SELECT * FROM old_reports");
1771 while (existingReports.next()) {
1772 String path = existingReports.getString(2);
1773 long crtime = existingReports.getInt(3);
1774 String sourceModule = existingReports.getString(4);
1775 String reportName = existingReports.getString(5);
1777 PreparedStatement insertObjectStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_OBJECT, Statement.RETURN_GENERATED_KEYS);
1778 insertObjectStatement.clearParameters();
1779 insertObjectStatement.setNull(1, java.sql.Types.BIGINT);
1780 insertObjectStatement.setLong(2, TskData.ObjectType.REPORT.getObjectType());
1781 connection.executeUpdate(insertObjectStatement);
1782 resultSet = insertObjectStatement.getGeneratedKeys();
1783 if (!resultSet.next()) {
1784 throw new TskCoreException(String.format(
"Failed to INSERT report %s (%s) in tsk_objects table", reportName, path));
1786 long objectId = resultSet.getLong(1);
1789 PreparedStatement insertReportStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_REPORT);
1790 insertReportStatement.clearParameters();
1791 insertReportStatement.setLong(1, objectId);
1792 insertReportStatement.setString(2, path);
1793 insertReportStatement.setLong(3, crtime);
1794 insertReportStatement.setString(4, sourceModule);
1795 insertReportStatement.setString(5, reportName);
1796 connection.executeUpdate(insertReportStatement);
1800 updateSchemaStatement.execute(
"DROP TABLE old_reports");
1802 return new CaseDbSchemaVersionNumber(8, 0);
1804 closeResultSet(resultSet);
1805 closeResultSet(existingReports);
1806 closeStatement(updateSchemaStatement);
1807 closeStatement(getExistingReportsStatement);
1825 private CaseDbSchemaVersionNumber updateFromSchema8dot0toSchema8dot1(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1826 if (schemaVersion.getMajor() != 8) {
1827 return schemaVersion;
1830 if (schemaVersion.getMinor() != 0) {
1831 return schemaVersion;
1836 try (Statement statement = connection.createStatement();) {
1838 if (this.dbType.equals(DbType.SQLITE)) {
1839 statement.execute(
"CREATE TABLE tsk_examiners (examiner_id INTEGER PRIMARY KEY, login_name TEXT NOT NULL, display_name TEXT, UNIQUE(login_name) )");
1840 statement.execute(
"ALTER TABLE content_tags ADD COLUMN examiner_id INTEGER REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1841 statement.execute(
"ALTER TABLE blackboard_artifact_tags ADD COLUMN examiner_id INTEGER REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1843 statement.execute(
"CREATE TABLE tsk_examiners (examiner_id BIGSERIAL PRIMARY KEY, login_name TEXT NOT NULL, display_name TEXT, UNIQUE(login_name))");
1844 statement.execute(
"ALTER TABLE content_tags ADD COLUMN examiner_id BIGINT REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1845 statement.execute(
"ALTER TABLE blackboard_artifact_tags ADD COLUMN examiner_id BIGINT REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1848 return new CaseDbSchemaVersionNumber(8, 1);
1867 private CaseDbSchemaVersionNumber updateFromSchema8dot1toSchema8dot2(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1868 if (schemaVersion.getMajor() != 8) {
1869 return schemaVersion;
1872 if (schemaVersion.getMinor() != 1) {
1873 return schemaVersion;
1878 try (Statement statement = connection.createStatement();) {
1879 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN sha1 TEXT DEFAULT NULL");
1880 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN sha256 TEXT DEFAULT NULL");
1882 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_details TEXT");
1890 statement.execute(
"CREATE TABLE tsk_db_info_extended (name TEXT PRIMARY KEY, value TEXT NOT NULL)");
1891 ResultSet result = statement.executeQuery(
"SELECT tsk_ver FROM tsk_db_info");
1893 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + TSK_VERSION_KEY +
"', '" + result.getLong(
"tsk_ver") +
"')");
1894 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + SCHEMA_MAJOR_VERSION_KEY +
"', '8')");
1895 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + SCHEMA_MINOR_VERSION_KEY +
"', '2')");
1896 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + CREATION_SCHEMA_MAJOR_VERSION_KEY +
"', '0')");
1897 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + CREATION_SCHEMA_MINOR_VERSION_KEY +
"', '0')");
1899 String primaryKeyType;
1902 primaryKeyType =
"BIGSERIAL";
1905 primaryKeyType =
"INTEGER";
1908 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
1912 statement.execute(
"CREATE TABLE tsk_event_types ("
1913 +
" event_type_id " + primaryKeyType +
" PRIMARY KEY, "
1914 +
" display_name TEXT UNIQUE NOT NULL, "
1915 +
" super_type_id INTEGER REFERENCES tsk_event_types(event_type_id) )");
1916 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1917 +
" values( 0, 'Event Types', null)");
1918 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1919 +
" values(1, 'File System', 0)");
1920 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1921 +
" values(2, 'Web Activity', 0)");
1922 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1923 +
" values(3, 'Misc Types', 0)");
1924 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1925 +
" values(4, 'Modified', 1)");
1926 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1927 +
" values(5, 'Accessed', 1)");
1928 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1929 +
" values(6, 'Created', 1)");
1930 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
1931 +
" values(7, 'Changed', 1)");
1934 statement.execute(
"CREATE TABLE tsk_event_descriptions ("
1935 +
" event_description_id " + primaryKeyType +
" PRIMARY KEY, "
1936 +
" full_description TEXT NOT NULL, "
1937 +
" med_description TEXT, "
1938 +
" short_description TEXT,"
1939 +
" data_source_obj_id BIGINT NOT NULL, "
1940 +
" file_obj_id BIGINT NOT NULL, "
1941 +
" artifact_id BIGINT, "
1942 +
" hash_hit INTEGER NOT NULL, "
1943 +
" tagged INTEGER NOT NULL, "
1944 +
" FOREIGN KEY(data_source_obj_id) REFERENCES data_source_info(obj_id), "
1945 +
" FOREIGN KEY(file_obj_id) REFERENCES tsk_files(obj_id), "
1946 +
" FOREIGN KEY(artifact_id) REFERENCES blackboard_artifacts(artifact_id))"
1949 statement.execute(
"CREATE TABLE tsk_events ( "
1950 +
" event_id " + primaryKeyType +
" PRIMARY KEY, "
1951 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
1952 +
" event_description_id BIGINT NOT NULL REFERENCES tsk_event_descriptions(event_description_id) ,"
1953 +
" time INTEGER NOT NULL) "
1957 statement.execute(
"CREATE INDEX events_time ON tsk_events(time)");
1958 statement.execute(
"CREATE INDEX events_type ON tsk_events(event_type_id)");
1959 statement.execute(
"CREATE INDEX events_data_source_obj_id ON tsk_event_descriptions(data_source_obj_id) ");
1960 statement.execute(
"CREATE INDEX events_file_obj_id ON tsk_event_descriptions(file_obj_id) ");
1961 statement.execute(
"CREATE INDEX events_artifact_id ON tsk_event_descriptions(artifact_id) ");
1962 statement.execute(
"CREATE INDEX events_sub_type_time ON tsk_events(event_type_id, time) ");
1963 return new CaseDbSchemaVersionNumber(8, 2);
1983 private CaseDbSchemaVersionNumber updateFromSchema8dot2toSchema8dot3(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1984 if (schemaVersion.getMajor() != 8) {
1985 return schemaVersion;
1988 if (schemaVersion.getMinor() != 2) {
1989 return schemaVersion;
1994 ResultSet resultSet = null;
1996 try (Statement statement = connection.createStatement();) {
2001 String primaryKeyType;
2004 primaryKeyType =
"BIGSERIAL";
2007 primaryKeyType =
"INTEGER";
2010 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
2014 statement.execute(
"CREATE TABLE IF NOT EXISTS tsk_event_types ("
2015 +
" event_type_id " + primaryKeyType +
" PRIMARY KEY, "
2016 +
" display_name TEXT UNIQUE NOT NULL, "
2017 +
" super_type_id INTEGER REFERENCES tsk_event_types(event_type_id) )");
2019 resultSet = statement.executeQuery(
"SELECT * from tsk_event_types");
2023 if (!resultSet.next()) {
2025 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2026 +
" values( 0, 'Event Types', null)");
2027 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2028 +
" values(1, 'File System', 0)");
2029 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2030 +
" values(2, 'Web Activity', 0)");
2031 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2032 +
" values(3, 'Misc Types', 0)");
2033 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2034 +
" values(4, 'Modified', 1)");
2035 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2036 +
" values(5, 'Accessed', 1)");
2037 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2038 +
" values(6, 'Created', 1)");
2039 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2040 +
" values(7, 'Changed', 1)");
2045 statement.execute(
"DROP TABLE IF EXISTS tsk_events");
2049 statement.execute(
"DROP TABLE IF EXISTS tsk_event_descriptions");
2052 statement.execute(
"CREATE TABLE tsk_event_descriptions ("
2053 +
" event_description_id " + primaryKeyType +
" PRIMARY KEY, "
2054 +
" full_description TEXT NOT NULL, "
2055 +
" med_description TEXT, "
2056 +
" short_description TEXT,"
2057 +
" data_source_obj_id BIGINT NOT NULL, "
2058 +
" file_obj_id BIGINT NOT NULL, "
2059 +
" artifact_id BIGINT, "
2060 +
" hash_hit INTEGER NOT NULL, "
2061 +
" tagged INTEGER NOT NULL, "
2062 +
" UNIQUE(full_description, file_obj_id, artifact_id), "
2063 +
" FOREIGN KEY(data_source_obj_id) REFERENCES data_source_info(obj_id), "
2064 +
" FOREIGN KEY(file_obj_id) REFERENCES tsk_files(obj_id), "
2065 +
" FOREIGN KEY(artifact_id) REFERENCES blackboard_artifacts(artifact_id))"
2069 statement.execute(
"CREATE TABLE tsk_events ( "
2070 +
" event_id " + primaryKeyType +
" PRIMARY KEY, "
2071 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
2072 +
" event_description_id BIGINT NOT NULL REFERENCES tsk_event_descriptions(event_description_id) ,"
2073 +
" time INTEGER NOT NULL, "
2074 +
" UNIQUE (event_type_id, event_description_id, time))"
2078 statement.execute(
"UPDATE tsk_db_info_extended SET name = 'CREATION_SCHEMA_MAJOR_VERSION' WHERE name = 'CREATED_SCHEMA_MAJOR_VERSION'");
2079 statement.execute(
"UPDATE tsk_db_info_extended SET name = 'CREATION_SCHEMA_MINOR_VERSION' WHERE name = 'CREATED_SCHEMA_MINOR_VERSION'");
2081 return new CaseDbSchemaVersionNumber(8, 3);
2083 closeResultSet(resultSet);
2109 private CaseDbSchemaVersionNumber updateFromSchema8dot3toSchema8dot4(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2110 if (schemaVersion.getMajor() != 8) {
2111 return schemaVersion;
2114 if (schemaVersion.getMinor() != 3) {
2115 return schemaVersion;
2118 Statement statement = connection.createStatement();
2119 ResultSet results = null;
2126 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
2132 results = statement.executeQuery(
"SELECT column_name FROM information_schema.columns "
2133 +
"WHERE table_name='tsk_event_descriptions' and column_name='file_obj_id'");
2134 if (results.next()) {
2136 statement.execute(
"ALTER TABLE tsk_event_descriptions "
2137 +
"RENAME COLUMN file_obj_id TO content_obj_id");
2141 statement.execute(
"CREATE TABLE temp_tsk_events ( "
2142 +
" event_id BIGSERIAL PRIMARY KEY, "
2143 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
2144 +
" event_description_id BIGINT NOT NULL REFERENCES tsk_event_descriptions(event_description_id),"
2145 +
" time BIGINT NOT NULL, "
2146 +
" UNIQUE (event_type_id, event_description_id, time))"
2150 statement.execute(
"INSERT INTO temp_tsk_events(event_id, event_type_id, "
2151 +
"event_description_id, time) SELECT * FROM tsk_events");
2154 statement.execute(
"DROP TABLE tsk_events");
2157 statement.execute(
"ALTER TABLE temp_tsk_events RENAME TO tsk_events");
2160 statement.execute(
"CREATE INDEX events_data_source_obj_id ON tsk_event_descriptions(data_source_obj_id) ");
2161 statement.execute(
"CREATE INDEX events_content_obj_id ON tsk_event_descriptions(content_obj_id) ");
2162 statement.execute(
"CREATE INDEX events_artifact_id ON tsk_event_descriptions(artifact_id) ");
2163 statement.execute(
"CREATE INDEX events_sub_type_time ON tsk_events(event_type_id, time) ");
2164 statement.execute(
"CREATE INDEX events_time ON tsk_events(time) ");
2168 boolean hasMisnamedColumn =
false;
2169 results = statement.executeQuery(
"pragma table_info('tsk_event_descriptions')");
2170 while (results.next()) {
2171 if (results.getString(
"name") != null && results.getString(
"name").equals(
"file_obj_id")) {
2172 hasMisnamedColumn =
true;
2177 if (hasMisnamedColumn) {
2179 statement.execute(
"CREATE TABLE temp_tsk_event_descriptions ("
2180 +
" event_description_id INTEGER PRIMARY KEY, "
2181 +
" full_description TEXT NOT NULL, "
2182 +
" med_description TEXT, "
2183 +
" short_description TEXT,"
2184 +
" data_source_obj_id BIGINT NOT NULL, "
2185 +
" content_obj_id BIGINT NOT NULL, "
2186 +
" artifact_id BIGINT, "
2187 +
" hash_hit INTEGER NOT NULL, "
2188 +
" tagged INTEGER NOT NULL, "
2189 +
" UNIQUE(full_description, content_obj_id, artifact_id), "
2190 +
" FOREIGN KEY(data_source_obj_id) REFERENCES data_source_info(obj_id), "
2191 +
" FOREIGN KEY(content_obj_id) REFERENCES tsk_files(obj_id), "
2192 +
" FOREIGN KEY(artifact_id) REFERENCES blackboard_artifacts(artifact_id))"
2195 statement.execute(
"CREATE TABLE temp_tsk_events ( "
2196 +
" event_id INTEGER PRIMARY KEY, "
2197 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
2198 +
" event_description_id BIGINT NOT NULL REFERENCES temp_tsk_event_descriptions(event_description_id),"
2199 +
" time INTEGER NOT NULL, "
2200 +
" UNIQUE (event_type_id, event_description_id, time))"
2204 statement.execute(
"INSERT INTO temp_tsk_event_descriptions(event_description_id, full_description, "
2205 +
"med_description, short_description, data_source_obj_id, content_obj_id, artifact_id, "
2206 +
"hash_hit, tagged) SELECT * FROM tsk_event_descriptions");
2208 statement.execute(
"INSERT INTO temp_tsk_events(event_id, event_type_id, "
2209 +
"event_description_id, time) SELECT * FROM tsk_events");
2212 statement.execute(
"DROP TABLE tsk_events");
2213 statement.execute(
"DROP TABLE tsk_event_descriptions");
2216 statement.execute(
"ALTER TABLE temp_tsk_event_descriptions RENAME TO tsk_event_descriptions");
2217 statement.execute(
"ALTER TABLE temp_tsk_events RENAME TO tsk_events");
2220 statement.execute(
"CREATE INDEX events_data_source_obj_id ON tsk_event_descriptions(data_source_obj_id) ");
2221 statement.execute(
"CREATE INDEX events_content_obj_id ON tsk_event_descriptions(content_obj_id) ");
2222 statement.execute(
"CREATE INDEX events_artifact_id ON tsk_event_descriptions(artifact_id) ");
2223 statement.execute(
"CREATE INDEX events_sub_type_time ON tsk_events(event_type_id, time) ");
2224 statement.execute(
"CREATE INDEX events_time ON tsk_events(time) ");
2228 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
2232 if (this.dbType.equals(DbType.SQLITE)) {
2233 statement.execute(
"CREATE TABLE tsk_pool_info (obj_id INTEGER PRIMARY KEY, pool_type INTEGER NOT NULL, FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE)");
2235 statement.execute(
"CREATE TABLE tsk_pool_info (obj_id BIGSERIAL PRIMARY KEY, pool_type INTEGER NOT NULL, FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE)");
2239 insertAccountTypeIfNotExists(statement,
"IMO",
"IMO");
2240 insertAccountTypeIfNotExists(statement,
"LINE",
"LINE");
2241 insertAccountTypeIfNotExists(statement,
"SKYPE",
"Skype");
2242 insertAccountTypeIfNotExists(statement,
"TANGO",
"Tango");
2243 insertAccountTypeIfNotExists(statement,
"TEXTNOW",
"TextNow");
2244 insertAccountTypeIfNotExists(statement,
"THREEMA",
"ThreeMa");
2245 insertAccountTypeIfNotExists(statement,
"VIBER",
"Viber");
2246 insertAccountTypeIfNotExists(statement,
"XENDER",
"Xender");
2247 insertAccountTypeIfNotExists(statement,
"ZAPYA",
"Zapya");
2248 insertAccountTypeIfNotExists(statement,
"SHAREIT",
"ShareIt");
2250 return new CaseDbSchemaVersionNumber(8, 4);
2252 closeResultSet(results);
2253 closeStatement(statement);
2258 private CaseDbSchemaVersionNumber updateFromSchema8dot4toSchema8dot5(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2259 if (schemaVersion.getMajor() != 8) {
2260 return schemaVersion;
2263 if (schemaVersion.getMinor() != 4) {
2264 return schemaVersion;
2267 Statement statement = connection.createStatement();
2272 statement.execute(
"CREATE TABLE tsk_tag_sets (tag_set_id BIGSERIAL PRIMARY KEY, name TEXT UNIQUE)");
2273 statement.execute(
"ALTER TABLE tag_names ADD COLUMN tag_set_id BIGINT REFERENCES tsk_tag_sets(tag_set_id)");
2276 statement.execute(
"CREATE TABLE tsk_tag_sets (tag_set_id INTEGER PRIMARY KEY, name TEXT UNIQUE)");
2277 statement.execute(
"ALTER TABLE tag_names ADD COLUMN tag_set_id INTEGER REFERENCES tsk_tag_sets(tag_set_id)");
2281 statement.execute(
"ALTER TABLE tag_names ADD COLUMN rank INTEGER");
2289 String insertStmt =
"INSERT INTO tsk_tag_sets (name) VALUES ('Project VIC')";
2291 statement.execute(insertStmt, Statement.RETURN_GENERATED_KEYS);
2293 statement.execute(insertStmt);
2295 try (ResultSet resultSet = statement.getGeneratedKeys()) {
2296 if (resultSet != null && resultSet.next()) {
2297 int tagSetId = resultSet.getInt(1);
2299 String updateQuery =
"UPDATE tag_names SET tag_set_id = %d, color = '%s', rank = %d, display_name = '%s' WHERE display_name = '%s'";
2300 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Red", 1,
"Child Exploitation (Illegal)",
"CAT-1: Child Exploitation (Illegal)"));
2301 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Lime", 2,
"Child Exploitation (Non-Illegal/Age Difficult)",
"CAT-2: Child Exploitation (Non-Illegal/Age Difficult)"));
2302 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Yellow", 3,
"CGI/Animation (Child Exploitive)",
"CAT-3: CGI/Animation (Child Exploitive)"));
2303 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Purple", 4,
"Exemplar/Comparison (Internal Use Only)",
"CAT-4: Exemplar/Comparison (Internal Use Only)"));
2304 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Fuchsia", 5,
"Non-pertinent",
"CAT-5: Non-pertinent"));
2306 String
deleteContentTag =
"DELETE FROM content_tags WHERE tag_name_id IN (SELECT tag_name_id from tag_names WHERE display_name LIKE 'CAT-0: Uncategorized')";
2307 String deleteArtifactTag =
"DELETE FROM blackboard_artifact_tags WHERE tag_name_id IN (SELECT tag_name_id from tag_names WHERE display_name LIKE 'CAT-0: Uncategorized')";
2308 String deleteCat0 =
"DELETE FROM tag_names WHERE display_name = 'CAT-0: Uncategorized'";
2309 statement.executeUpdate(deleteContentTag);
2310 statement.executeUpdate(deleteArtifactTag);
2311 statement.executeUpdate(deleteCat0);
2314 throw new TskCoreException(
"Failed to retrieve the default tag_set_id from DB");
2324 statement.execute(
"ALTER TABLE tsk_fs_info ADD COLUMN data_source_obj_id BIGINT NOT NULL DEFAULT -1;");
2327 statement.execute(
"ALTER TABLE tsk_fs_info ADD COLUMN data_source_obj_id INTEGER NOT NULL DEFAULT -1;");
2330 Statement updateStatement = connection.createStatement();
2331 try (ResultSet resultSet = statement.executeQuery(
"SELECT obj_id FROM tsk_fs_info")) {
2332 while (resultSet.next()) {
2333 long fsId = resultSet.getLong(
"obj_id");
2334 long dataSourceId = getDataSourceObjectId(connection, fsId);
2335 updateStatement.executeUpdate(
"UPDATE tsk_fs_info SET data_source_obj_id = " + dataSourceId +
" WHERE obj_id = " + fsId +
";");
2338 closeStatement(updateStatement);
2341 return new CaseDbSchemaVersionNumber(8, 5);
2344 closeStatement(statement);
2349 private CaseDbSchemaVersionNumber updateFromSchema8dot5toSchema8dot6(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2350 if (schemaVersion.getMajor() != 8) {
2351 return schemaVersion;
2354 if (schemaVersion.getMinor() != 5) {
2355 return schemaVersion;
2358 Statement statement = connection.createStatement();
2361 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN sha256 TEXT");
2363 return new CaseDbSchemaVersionNumber(8, 6);
2366 closeStatement(statement);
2371 @SuppressWarnings(
"deprecation")
2372 private CaseDbSchemaVersionNumber updateFromSchema8dot6toSchema9dot0(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection) throws SQLException, TskCoreException {
2373 if (schemaVersion.getMajor() != 8) {
2374 return schemaVersion;
2377 if (schemaVersion.getMinor() != 6) {
2378 return schemaVersion;
2381 Statement statement = connection.createStatement();
2384 String dateDataType =
"BIGINT";
2385 String bigIntDataType =
"BIGINT";
2386 String blobDataType =
"BYTEA";
2387 String primaryKeyType =
"BIGSERIAL";
2389 if (this.dbType.equals(DbType.SQLITE)) {
2390 dateDataType =
"INTEGER";
2391 bigIntDataType =
"INTEGER";
2392 blobDataType =
"BLOB";
2393 primaryKeyType =
"INTEGER";
2395 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN added_date_time " + dateDataType);
2396 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_tool_settings TEXT");
2397 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_tool_name TEXT");
2398 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_tool_version TEXT");
2403 statement.execute(
"ALTER TABLE blackboard_artifact_types ADD COLUMN category_type INTEGER DEFAULT 0");
2404 String analysisTypeObjIdList
2405 = BlackboardArtifact.ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID() +
", "
2406 + BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID() +
", "
2407 + BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT.getTypeID() +
", "
2408 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID() +
", "
2409 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID() +
", "
2410 + BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED.getTypeID() +
", "
2411 + BlackboardArtifact.ARTIFACT_TYPE.TSK_EXT_MISMATCH_DETECTED.getTypeID() +
", "
2412 + BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID() +
", "
2413 + BlackboardArtifact.ARTIFACT_TYPE.TSK_FACE_DETECTED.getTypeID() +
", "
2414 + BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_SUSPECTED.getTypeID() +
", "
2415 + BlackboardArtifact.ARTIFACT_TYPE.TSK_OBJECT_DETECTED.getTypeID() +
", "
2416 + BlackboardArtifact.ARTIFACT_TYPE.TSK_VERIFICATION_FAILED.getTypeID() +
", "
2417 + BlackboardArtifact.ARTIFACT_TYPE.TSK_DATA_SOURCE_USAGE.getTypeID() +
", "
2418 + BlackboardArtifact.ARTIFACT_TYPE.TSK_USER_CONTENT_SUSPECTED.getTypeID() +
", "
2419 + BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_ACCOUNT_TYPE.getTypeID() +
", "
2420 + BlackboardArtifact.ARTIFACT_TYPE.TSK_YARA_HIT.getTypeID() +
", "
2421 + BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_CATEGORIZATION.getTypeID();
2422 statement.execute(
"UPDATE blackboard_artifact_types SET category_type = " + BlackboardArtifact.Category.ANALYSIS_RESULT.getID()
2423 +
" WHERE artifact_type_id IN (" + analysisTypeObjIdList +
")");
2426 statement.execute(
"CREATE TABLE tsk_file_attributes (id " + primaryKeyType +
" PRIMARY KEY, "
2427 +
"obj_id " + bigIntDataType +
" NOT NULL, "
2428 +
"attribute_type_id " + bigIntDataType +
" NOT NULL, "
2429 +
"value_type INTEGER NOT NULL, value_byte " + blobDataType +
", "
2430 +
"value_text TEXT, value_int32 INTEGER, value_int64 " + bigIntDataType +
", value_double NUMERIC(20, 10), "
2431 +
"FOREIGN KEY(obj_id) REFERENCES tsk_files(obj_id) ON DELETE CASCADE, "
2432 +
"FOREIGN KEY(attribute_type_id) REFERENCES blackboard_attribute_types(attribute_type_id))");
2435 statement.execute(
"CREATE TABLE tsk_analysis_results (artifact_obj_id " + bigIntDataType +
" PRIMARY KEY, "
2436 +
"conclusion TEXT, "
2437 +
"significance INTEGER NOT NULL, "
2445 +
"configuration TEXT, justification TEXT, "
2446 +
"ignore_score INTEGER DEFAULT 0 "
2449 statement.execute(
"CREATE TABLE tsk_aggregate_score( obj_id " + bigIntDataType +
" PRIMARY KEY, "
2450 +
"data_source_obj_id " + bigIntDataType +
", "
2451 +
"significance INTEGER NOT NULL, "
2454 +
"UNIQUE (obj_id),"
2455 +
"FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE, "
2456 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE "
2460 statement.execute(
"CREATE TABLE tsk_persons (id " + primaryKeyType +
" PRIMARY KEY, "
2461 +
"name TEXT NOT NULL, "
2462 +
"UNIQUE(name)) ");
2465 statement.execute(
"CREATE TABLE tsk_hosts (id " + primaryKeyType +
" PRIMARY KEY, "
2466 +
"name TEXT NOT NULL, "
2467 +
"db_status INTEGER DEFAULT 0, "
2468 +
"person_id INTEGER, "
2469 +
"merged_into " + bigIntDataType +
", "
2470 +
"FOREIGN KEY(person_id) REFERENCES tsk_persons(id) ON DELETE SET NULL, "
2471 +
"FOREIGN KEY(merged_into) REFERENCES tsk_hosts(id), "
2472 +
"UNIQUE(name)) ");
2475 statement.execute(
"CREATE TABLE tsk_os_account_realms (id " + primaryKeyType +
" PRIMARY KEY, "
2476 +
"realm_name TEXT DEFAULT NULL, "
2477 +
"realm_addr TEXT DEFAULT NULL, "
2478 +
"realm_signature TEXT NOT NULL, "
2479 +
"scope_host_id " + bigIntDataType +
" DEFAULT NULL, "
2480 +
"scope_confidence INTEGER, "
2481 +
"db_status INTEGER DEFAULT 0, "
2482 +
"merged_into " + bigIntDataType +
" DEFAULT NULL, "
2483 +
"UNIQUE(realm_signature), "
2484 +
"FOREIGN KEY(scope_host_id) REFERENCES tsk_hosts(id),"
2485 +
"FOREIGN KEY(merged_into) REFERENCES tsk_os_account_realms(id) )");
2490 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN host_id INTEGER REFERENCES tsk_hosts(id)");
2491 Statement updateStatement = connection.createStatement();
2492 try (ResultSet resultSet = statement.executeQuery(
"SELECT obj_id, device_id FROM data_source_info")) {
2493 Map<String, Long> hostMap =
new HashMap<>();
2495 while (resultSet.next()) {
2496 long objId = resultSet.getLong(
"obj_id");
2497 String deviceId = resultSet.getString(
"device_id");
2499 if (!hostMap.containsKey(deviceId)) {
2500 String hostName =
"Host " + hostIndex;
2501 updateStatement.execute(
"INSERT INTO tsk_hosts (name, db_status) VALUES ('" + hostName +
"', 0)");
2502 hostMap.put(deviceId, hostIndex);
2505 updateStatement.execute(
"UPDATE data_source_info SET host_id = " + hostMap.get(deviceId) +
" WHERE obj_id = " + objId);
2508 closeStatement(updateStatement);
2511 statement.execute(
"CREATE TABLE tsk_os_accounts (os_account_obj_id " + bigIntDataType +
" PRIMARY KEY, "
2512 +
"login_name TEXT DEFAULT NULL, "
2513 +
"full_name TEXT DEFAULT NULL, "
2514 +
"realm_id " + bigIntDataType +
" NOT NULL, "
2515 +
"addr TEXT DEFAULT NULL, "
2516 +
"signature TEXT NOT NULL, "
2517 +
"status INTEGER, "
2519 +
"created_date " + bigIntDataType +
" DEFAULT NULL, "
2520 +
"db_status INTEGER DEFAULT 0, "
2521 +
"merged_into " + bigIntDataType +
" DEFAULT NULL, "
2522 +
"UNIQUE(signature, realm_id), "
2523 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE, "
2524 +
"FOREIGN KEY(realm_id) REFERENCES tsk_os_account_realms(id),"
2525 +
"FOREIGN KEY(merged_into) REFERENCES tsk_os_accounts(os_account_obj_id) )");
2527 statement.execute(
"CREATE TABLE tsk_os_account_attributes (id " + primaryKeyType +
" PRIMARY KEY, "
2528 +
"os_account_obj_id " + bigIntDataType +
" NOT NULL, "
2529 +
"host_id " + bigIntDataType +
", "
2530 +
"source_obj_id " + bigIntDataType +
", "
2531 +
"attribute_type_id " + bigIntDataType +
" NOT NULL, "
2532 +
"value_type INTEGER NOT NULL, "
2533 +
"value_byte " + bigIntDataType +
", "
2534 +
"value_text TEXT, "
2535 +
"value_int32 INTEGER, value_int64 " + bigIntDataType +
", "
2536 +
"value_double NUMERIC(20, 10), "
2537 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id), "
2538 +
"FOREIGN KEY(host_id) REFERENCES tsk_hosts(id), "
2539 +
"FOREIGN KEY(source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE SET NULL, "
2540 +
"FOREIGN KEY(attribute_type_id) REFERENCES blackboard_attribute_types(attribute_type_id))");
2542 statement.execute(
"CREATE TABLE tsk_os_account_instances (id " + primaryKeyType +
" PRIMARY KEY, "
2543 +
"os_account_obj_id " + bigIntDataType +
" NOT NULL, "
2544 +
"data_source_obj_id " + bigIntDataType +
" NOT NULL, "
2545 +
"instance_type INTEGER NOT NULL, "
2546 +
"UNIQUE(os_account_obj_id, data_source_obj_id), "
2547 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id), "
2548 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE )");
2550 statement.execute(
"CREATE TABLE tsk_data_artifacts ( "
2551 +
"artifact_obj_id " + bigIntDataType +
" PRIMARY KEY, "
2552 +
"os_account_obj_id " + bigIntDataType +
", "
2553 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id)) ");
2556 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN owner_uid TEXT DEFAULT NULL");
2557 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN os_account_obj_id " + bigIntDataType +
" DEFAULT NULL REFERENCES tsk_os_accounts(os_account_obj_id) ");
2560 statement.execute(
"CREATE TABLE tsk_host_addresses (id " + primaryKeyType +
" PRIMARY KEY, "
2561 +
"address_type INTEGER NOT NULL, "
2562 +
"address TEXT NOT NULL, "
2563 +
"UNIQUE(address_type, address)) ");
2565 statement.execute(
"CREATE TABLE tsk_host_address_map (id " + primaryKeyType +
" PRIMARY KEY, "
2566 +
"host_id " + bigIntDataType +
" NOT NULL, "
2567 +
"addr_obj_id " + bigIntDataType +
" NOT NULL, "
2568 +
"source_obj_id " + bigIntDataType +
", "
2569 +
"time " + bigIntDataType +
", "
2570 +
"UNIQUE(host_id, addr_obj_id, time), "
2571 +
"FOREIGN KEY(host_id) REFERENCES tsk_hosts(id) ON DELETE CASCADE, "
2572 +
"FOREIGN KEY(addr_obj_id) REFERENCES tsk_host_addresses(id), "
2573 +
"FOREIGN KEY(source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE SET NULL )");
2576 statement.execute(
"CREATE TABLE tsk_host_address_dns_ip_map (id " + primaryKeyType +
" PRIMARY KEY, "
2577 +
"dns_address_id " + bigIntDataType +
" NOT NULL, "
2578 +
"ip_address_id " + bigIntDataType +
" NOT NULL, "
2579 +
"source_obj_id " + bigIntDataType +
", "
2580 +
"time " + bigIntDataType +
", "
2581 +
"UNIQUE(dns_address_id, ip_address_id, time), "
2582 +
"FOREIGN KEY(dns_address_id) REFERENCES tsk_host_addresses(id) ON DELETE CASCADE, "
2583 +
"FOREIGN KEY(ip_address_id) REFERENCES tsk_host_addresses(id) ON DELETE CASCADE,"
2584 +
"FOREIGN KEY(source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE SET NULL )");
2587 statement.execute(
"CREATE TABLE tsk_host_address_usage (id " + primaryKeyType +
" PRIMARY KEY, "
2588 +
"addr_obj_id " + bigIntDataType +
" NOT NULL, "
2589 +
"obj_id " + bigIntDataType +
" NOT NULL, "
2590 +
"data_source_obj_id " + bigIntDataType +
" NOT NULL, "
2591 +
"UNIQUE(addr_obj_id, obj_id), "
2592 +
"FOREIGN KEY(addr_obj_id) REFERENCES tsk_host_addresses(id) ON DELETE CASCADE, "
2593 +
"FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE )");
2595 return new CaseDbSchemaVersionNumber(9, 0);
2598 closeStatement(statement);
2603 private CaseDbSchemaVersionNumber updateFromSchema9dot0toSchema9dot1(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2604 if (schemaVersion.getMajor() != 9) {
2605 return schemaVersion;
2608 if (schemaVersion.getMinor() != 0) {
2609 return schemaVersion;
2612 Statement statement = connection.createStatement();
2613 ResultSet results = null;
2621 results = statement.executeQuery(
"SELECT column_name FROM information_schema.columns "
2622 +
"WHERE table_name='tsk_analysis_results' and column_name='method_category'");
2623 if (results.next()) {
2625 statement.execute(
"ALTER TABLE tsk_analysis_results "
2626 +
"DROP COLUMN method_category");
2627 statement.execute(
"ALTER TABLE tsk_aggregate_score "
2628 +
"DROP COLUMN method_category");
2634 boolean hasMisnamedColumn =
false;
2635 results = statement.executeQuery(
"pragma table_info('tsk_analysis_results')");
2636 while (results.next()) {
2637 if (results.getString(
"name") != null && results.getString(
"name").equals(
"method_category")) {
2638 hasMisnamedColumn =
true;
2643 if (hasMisnamedColumn) {
2646 statement.execute(
"CREATE TABLE temp_tsk_analysis_results (artifact_obj_id INTEGER PRIMARY KEY, "
2647 +
"conclusion TEXT, "
2648 +
"significance INTEGER NOT NULL, "
2649 +
"configuration TEXT, justification TEXT, "
2650 +
"ignore_score INTEGER DEFAULT 0 "
2652 statement.execute(
"CREATE TABLE temp_tsk_aggregate_score( obj_id INTEGER PRIMARY KEY, "
2653 +
"data_source_obj_id INTEGER, "
2654 +
"significance INTEGER NOT NULL, "
2655 +
"UNIQUE (obj_id),"
2656 +
"FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE, "
2657 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE "
2661 statement.execute(
"INSERT INTO temp_tsk_analysis_results(artifact_obj_id, "
2662 +
"conclusion, justification, significance, configuration, ignore_score) "
2663 +
"SELECT artifact_obj_id, conclusion, justification, significance, configuration, ignore_score FROM tsk_analysis_results");
2664 statement.execute(
"INSERT INTO temp_tsk_aggregate_score(obj_id, "
2665 +
"data_source_obj_id, significance) "
2666 +
"SELECT obj_id, data_source_obj_id, significance FROM tsk_aggregate_score");
2669 statement.execute(
"DROP TABLE tsk_analysis_results");
2670 statement.execute(
"DROP TABLE tsk_aggregate_score");
2673 statement.execute(
"ALTER TABLE temp_tsk_analysis_results RENAME TO tsk_analysis_results");
2674 statement.execute(
"ALTER TABLE temp_tsk_aggregate_score RENAME TO tsk_aggregate_score");
2679 throw new TskCoreException(
"Unsupported database type: " +
getDatabaseType().toString());
2683 statement.execute(
"CREATE INDEX tsk_file_attributes_obj_id ON tsk_file_attributes(obj_id)");
2685 statement.execute(
"ALTER TABLE tsk_analysis_results ADD COLUMN priority INTEGER NOT NULL DEFAULT " + Score.Priority.NORMAL.getId());
2686 statement.execute(
"ALTER TABLE tsk_aggregate_score ADD COLUMN priority INTEGER NOT NULL DEFAULT " + Score.Priority.NORMAL.getId());
2688 statement.execute(
"UPDATE blackboard_artifact_types SET category_type = 1 WHERE artifact_type_id = 16");
2690 return new CaseDbSchemaVersionNumber(9, 1);
2692 closeResultSet(results);
2693 closeStatement(statement);
2711 private CaseDbSchemaVersionNumber updateFromSchema9dot1toSchema9dot2(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2712 if (schemaVersion.getMajor() != 9) {
2713 return schemaVersion;
2716 if (schemaVersion.getMinor() != 1) {
2717 return schemaVersion;
2720 Statement updateSchemaStatement = connection.createStatement();
2721 ResultSet results = null;
2725 String bigIntDataType =
"BIGINT";
2726 String primaryKeyType =
"BIGSERIAL";
2728 if (this.dbType.equals(DbType.SQLITE)) {
2729 bigIntDataType =
"INTEGER";
2730 primaryKeyType =
"INTEGER";
2736 updateSchemaStatement.execute(
"ALTER TABLE tsk_os_account_instances RENAME TO old_tsk_os_account_instances");
2739 updateSchemaStatement.execute(
"CREATE TABLE tsk_os_account_instances (id " + primaryKeyType +
" PRIMARY KEY, "
2740 +
"os_account_obj_id " + bigIntDataType +
" NOT NULL, "
2741 +
"data_source_obj_id " + bigIntDataType +
" NOT NULL, "
2742 +
"instance_type INTEGER NOT NULL, "
2743 +
"UNIQUE(os_account_obj_id, data_source_obj_id, instance_type), "
2744 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id) ON DELETE CASCADE, "
2745 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE ) ");
2748 updateSchemaStatement.execute(
"INSERT INTO tsk_os_account_instances(os_account_obj_id, "
2749 +
"data_source_obj_id, instance_type) SELECT os_account_obj_id, data_source_obj_id, instance_type FROM old_tsk_os_account_instances ORDER BY id ASC");
2752 updateSchemaStatement.execute(
"DROP TABLE old_tsk_os_account_instances");
2754 return new CaseDbSchemaVersionNumber(9, 2);
2756 closeResultSet(results);
2757 closeStatement(updateSchemaStatement);
2762 private CaseDbSchemaVersionNumber updateFromSchema9dot2toSchema9dot3(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2763 if (schemaVersion.getMajor() != 9) {
2764 return schemaVersion;
2767 if (schemaVersion.getMinor() != 2) {
2768 return schemaVersion;
2771 Statement statement = connection.createStatement();
2775 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN sha1 TEXT");
2778 return new CaseDbSchemaVersionNumber(9, 3);
2781 closeStatement(statement);
2786 private CaseDbSchemaVersionNumber updateFromSchema9dot3toSchema9dot4(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2787 if (schemaVersion.getMajor() != 9) {
2788 return schemaVersion;
2791 if (schemaVersion.getMinor() != 3) {
2792 return schemaVersion;
2795 Statement statement = connection.createStatement();
2799 statement.execute(
"CREATE TABLE file_collection_status_types (collection_status_type INTEGER PRIMARY KEY, name TEXT NOT NULL);");
2800 initCollectedStatusTypes(connection);
2803 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN collected INTEGER NOT NULL DEFAULT " +
2804 TskData.CollectedStatus.UNKNOWN.getType() +
";");
2806 return new CaseDbSchemaVersionNumber(9, 4);
2809 closeStatement(statement);
2825 private void insertAccountTypeIfNotExists(Statement statement, String type_name, String display_name)
throws TskCoreException, SQLException {
2827 String insertSQL = String.format(
"INTO account_types(type_name, display_name) VALUES ('%s', '%s')", type_name, display_name);
2830 insertSQL =
"INSERT " + insertSQL +
" ON CONFLICT DO NOTHING";
2833 insertSQL =
"INSERT OR IGNORE " + insertSQL;
2836 throw new TskCoreException(
"Unknown DB Type: " +
getDatabaseType().name());
2838 statement.execute(insertSQL);
2848 static String extractExtension(
final String fileName) {
2850 int i = fileName.lastIndexOf(
".");
2852 if ((i > 0) && ((i + 1) < fileName.length())) {
2853 ext = fileName.substring(i + 1);
2864 return ext.toLowerCase();
2888 return CURRENT_DB_SCHEMA_VERSION;
2898 return caseDBSchemaCreationVersion;
2917 return dbBackupPath;
2944 return databaseName;
2964 rwLock.writeLock().lock();
2975 rwLock.writeLock().unlock();
2986 rwLock.readLock().lock();
2997 rwLock.readLock().unlock();
3032 }
catch (Exception ex) {
3033 throw new TskCoreException(
"Failed to open case database at " + dbPath, ex);
3049 return openCase(databaseName, info, caseDir, null);
3080 return new SleuthkitCase(info, databaseName, caseHandle, caseDir, contentProvider);
3081 }
catch (PropertyVetoException exp) {
3083 throw new TskCoreException(exp.getMessage(), exp);
3087 }
catch (Exception exp) {
3089 throw new TskCoreException(exp.getMessage(), exp);
3119 CaseDatabaseFactory factory =
new CaseDatabaseFactory(dbPath);
3120 factory.createCaseDatabase();
3124 }
catch (Exception ex) {
3125 throw new TskCoreException(
"Failed to create case database at " + dbPath, ex);
3145 return newCase(caseName, info, caseDirPath, null);
3167 String databaseName = createCaseDataBaseName(caseName);
3181 CaseDatabaseFactory factory =
new CaseDatabaseFactory(databaseName, info);
3182 factory.createCaseDatabase();
3185 return new SleuthkitCase(info, databaseName, caseHandle, caseDirPath, contentProvider);
3186 }
catch (PropertyVetoException exp) {
3188 throw new TskCoreException(exp.getMessage(), exp);
3189 }
catch (Exception exp) {
3191 throw new TskCoreException(exp.getMessage(), exp);
3204 private static String createCaseDataBaseName(String candidateDbName) {
3206 if (!candidateDbName.isEmpty()) {
3210 dbName = candidateDbName.replaceAll(
"[^\\p{ASCII}]",
"_");
3215 dbName = dbName.replaceAll(
"[\\p{Cntrl}]",
"_");
3220 dbName = dbName.replaceAll(
"[ /?:'\"\\\\]",
"_");
3225 dbName = dbName.toLowerCase();
3231 if ((dbName.length() > 0 && !(Character.isLetter(dbName.codePointAt(0))) && !(dbName.codePointAt(0) ==
'_'))) {
3232 dbName =
"_" + dbName;
3239 if (dbName.length() > MAX_DB_NAME_LEN_BEFORE_TIMESTAMP) {
3240 dbName = dbName.substring(0, MAX_DB_NAME_LEN_BEFORE_TIMESTAMP);
3252 SimpleDateFormat dateFormat =
new SimpleDateFormat(
"yyyyMMdd_HHmmss");
3253 Date date =
new Date();
3254 dbName = dbName +
"_" + dateFormat.format(date);
3266 timelineEventsDisabled.set(
true);
3279 if (cachedCurrentExaminer != null) {
3280 return cachedCurrentExaminer;
3282 String loginName = System.getProperty(
"user.name");
3283 if (loginName == null || loginName.isEmpty()) {
3284 throw new TskCoreException(
"Failed to determine logged in user name.");
3287 ResultSet resultSet = null;
3288 CaseDbConnection connection = null;
3291 connection = connections.getConnection();
3292 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_EXAMINER_BY_LOGIN_NAME);
3293 statement.clearParameters();
3294 statement.setString(1, loginName);
3295 resultSet = connection.executeQuery(statement);
3296 if (resultSet.next()) {
3297 cachedCurrentExaminer =
new Examiner(resultSet.getLong(
"examiner_id"), resultSet.getString(
"login_name"), resultSet.getString(
"display_name"));
3298 return cachedCurrentExaminer;
3300 throw new TskCoreException(
"Error getting examaminer for name = " + loginName);
3303 }
catch (SQLException ex) {
3304 throw new TskCoreException(
"Error getting examaminer for name = " + loginName, ex);
3306 closeResultSet(resultSet);
3307 closeConnection(connection);
3322 Examiner getExaminerById(
long id)
throws TskCoreException {
3324 CaseDbConnection connection = null;
3325 ResultSet resultSet = null;
3328 connection = connections.getConnection();
3329 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_EXAMINER_BY_ID);
3330 statement.clearParameters();
3331 statement.setLong(1,
id);
3332 resultSet = connection.executeQuery(statement);
3333 if (resultSet.next()) {
3334 return new Examiner(resultSet.getLong(
"examiner_id"), resultSet.getString(
"login_name"), resultSet.getString(
"full_name"));
3336 throw new TskCoreException(
"Error getting examaminer for id = " +
id);
3338 }
catch (SQLException ex) {
3339 throw new TskCoreException(
"Error getting examaminer for id = " +
id, ex);
3341 closeResultSet(resultSet);
3342 closeConnection(connection);
3365 return this.caseHandle.initAddImageProcess(timeZone, addUnallocSpace, noFatFsOrphans, imageCopyPath,
this);
3377 CaseDbConnection connection = null;
3379 ResultSet rs = null;
3382 connection = connections.getConnection();
3383 s = connection.createStatement();
3384 rs = connection.executeQuery(s,
"SELECT obj_id, type FROM tsk_objects "
3385 +
"WHERE par_obj_id IS NULL");
3386 Collection<ObjectInfo> infos =
new ArrayList<ObjectInfo>();
3388 infos.add(
new ObjectInfo(rs.getLong(
"obj_id"),
ObjectType.
valueOf(rs.getShort(
"type"))));
3391 List<Content> rootObjs =
new ArrayList<Content>();
3392 for (ObjectInfo i : infos) {
3393 if (null != i.type) {
3404 throw new TskCoreException(
"Parentless object has wrong type to be a root (ABSTRACTFILE, but not VIRTUAL_DIRECTORY: " + i.type);
3416 throw new TskCoreException(
"Parentless object has wrong type to be a root: " + i.type);
3421 }
catch (SQLException ex) {
3422 throw new TskCoreException(
"Error getting root objects", ex);
3426 closeConnection(connection);
3442 List<Long> getDataSourceObjIds(String deviceId)
throws TskCoreException {
3445 synchronized (deviceIdToDatasourceObjIdMap) {
3446 if (deviceIdToDatasourceObjIdMap.containsKey(deviceId)) {
3447 return new ArrayList<Long>(deviceIdToDatasourceObjIdMap.get(deviceId));
3450 CaseDbConnection connection = null;
3452 ResultSet rs = null;
3455 connection = connections.getConnection();
3456 s = connection.createStatement();
3457 rs = connection.executeQuery(s,
"SELECT obj_id FROM data_source_info WHERE device_id = '" + deviceId +
"'");
3458 List<Long> dataSourceObjIds =
new ArrayList<Long>();
3460 dataSourceObjIds.add(rs.getLong(
"obj_id"));
3463 long ds_obj_id = rs.getLong(
"obj_id");
3464 if (deviceIdToDatasourceObjIdMap.containsKey(deviceId)) {
3465 deviceIdToDatasourceObjIdMap.get(deviceId).add(ds_obj_id);
3467 deviceIdToDatasourceObjIdMap.put(deviceId,
new HashSet<Long>(Arrays.asList(ds_obj_id)));
3470 return dataSourceObjIds;
3471 }
catch (SQLException ex) {
3472 throw new TskCoreException(
"Error getting data sources", ex);
3476 closeConnection(connection);
3499 CaseDbConnection connection = null;
3500 Statement statement = null;
3501 ResultSet resultSet = null;
3502 Statement statement2 = null;
3503 ResultSet resultSet2 = null;
3506 connection = connections.getConnection();
3507 statement = connection.createStatement();
3508 statement2 = connection.createStatement();
3509 resultSet = connection.executeQuery(statement,
3510 "SELECT ds.obj_id, ds.device_id, ds.time_zone, img.type, img.ssize, img.size, img.md5, img.sha1, img.sha256, img.display_name "
3511 +
"FROM data_source_info AS ds "
3512 +
"LEFT JOIN tsk_image_info AS img "
3513 +
"ON ds.obj_id = img.obj_id");
3515 List<DataSource> dataSourceList =
new ArrayList<DataSource>();
3518 while (resultSet.next()) {
3520 Long objectId = resultSet.getLong(
"obj_id");
3521 String deviceId = resultSet.getString(
"device_id");
3522 String timezone = resultSet.getString(
"time_zone");
3523 String type = resultSet.getString(
"type");
3531 resultSet2 = connection.executeQuery(statement2,
"SELECT name FROM tsk_files WHERE tsk_files.obj_id = " + objectId);
3532 String dsName = (resultSet2.next()) ? resultSet2.getString(
"name") :
"";
3540 String parentPath =
"/";
3541 dataSource =
new LocalFilesDataSource(
this, objectId, objectId, deviceId, dsName, dirType, metaType, dirFlag, metaFlags, timezone, null, null, null,
FileKnown.
UNKNOWN, parentPath);
3546 Long ssize = resultSet.getLong(
"ssize");
3547 Long size = resultSet.getLong(
"size");
3548 String md5 = resultSet.getString(
"md5");
3549 String sha1 = resultSet.getString(
"sha1");
3550 String sha256 = resultSet.getString(
"sha256");
3551 String name = resultSet.getString(
"display_name");
3553 List<String> imagePaths = imagePathsMap.get(objectId);
3555 if (imagePaths.size() > 0) {
3556 String path = imagePaths.get(0);
3557 name = (
new java.io.File(path)).getName();
3563 dataSource =
new Image(
this, objectId, Long.valueOf(type), deviceId, ssize, name,
3564 imagePaths.toArray(
new String[imagePaths.size()]), timezone, md5, sha1, sha256, size);
3567 dataSourceList.add(dataSource);
3570 return dataSourceList;
3572 }
catch (SQLException ex) {
3573 throw new TskCoreException(
"Error getting data sources", ex);
3575 closeResultSet(resultSet);
3576 closeStatement(statement);
3577 closeResultSet(resultSet2);
3578 closeStatement(statement2);
3579 closeConnection(connection);
3605 CaseDbConnection connection = null;
3606 Statement statement = null;
3607 ResultSet resultSet = null;
3608 Statement statement2 = null;
3609 ResultSet resultSet2 = null;
3612 connection = connections.getConnection();
3613 statement = connection.createStatement();
3614 statement2 = connection.createStatement();
3615 resultSet = connection.executeQuery(statement,
3616 "SELECT ds.device_id, ds.time_zone, img.type, img.ssize, img.size, img.md5, img.sha1, img.sha256, img.display_name "
3617 +
"FROM data_source_info AS ds "
3618 +
"LEFT JOIN tsk_image_info AS img "
3619 +
"ON ds.obj_id = img.obj_id "
3620 +
"WHERE ds.obj_id = " + objectId);
3621 if (resultSet.next()) {
3622 String deviceId = resultSet.getString(
"device_id");
3623 String timezone = resultSet.getString(
"time_zone");
3624 String type = resultSet.getString(
"type");
3632 resultSet2 = connection.executeQuery(statement2,
"SELECT name FROM tsk_files WHERE tsk_files.obj_id = " + objectId);
3633 String dsName = (resultSet2.next()) ? resultSet2.getString(
"name") :
"";
3640 String parentPath =
"/";
3641 dataSource =
new LocalFilesDataSource(
this, objectId, objectId, deviceId, dsName, dirType, metaType, dirFlag, metaFlags, timezone, null, null, null,
FileKnown.
UNKNOWN, parentPath);
3646 Long ssize = resultSet.getLong(
"ssize");
3647 Long size = resultSet.getLong(
"size");
3648 String md5 = resultSet.getString(
"md5");
3649 String sha1 = resultSet.getString(
"sha1");
3650 String sha256 = resultSet.getString(
"sha256");
3651 String name = resultSet.getString(
"display_name");
3653 List<String> imagePaths = getImagePathsById(objectId, connection);
3655 if (imagePaths.size() > 0) {
3656 String path = imagePaths.get(0);
3657 name = (
new java.io.File(path)).getName();
3663 dataSource =
new Image(
this, objectId, Long.valueOf(type), deviceId, ssize, name,
3664 imagePaths.toArray(
new String[imagePaths.size()]), timezone, md5, sha1, sha256, size);
3667 throw new TskDataException(String.format(
"There is no data source with obj_id = %d", objectId));
3669 }
catch (SQLException ex) {
3670 throw new TskCoreException(String.format(
"Error getting data source with obj_id = %d", objectId), ex);
3672 closeResultSet(resultSet);
3673 closeStatement(statement);
3674 closeResultSet(resultSet2);
3675 closeStatement(statement2);
3676 closeConnection(connection);
3697 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
3698 artifacts.addAll(blackboard.getArtifactsByType(blackboard.
getArtifactType(artifactTypeID)));
3713 CaseDbConnection connection = null;
3714 ResultSet rs = null;
3717 connection = connections.getConnection();
3720 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_FROM_SOURCE);
3721 statement.clearParameters();
3722 statement.setLong(1, objId);
3723 rs = connection.executeQuery(statement);
3726 count = rs.getLong(
"count");
3729 }
catch (SQLException ex) {
3730 throw new TskCoreException(
"Error getting number of blackboard artifacts by content", ex);
3733 closeConnection(connection);
3749 CaseDbConnection connection = null;
3750 ResultSet rs = null;
3753 connection = connections.getConnection();
3756 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_OF_TYPE);
3757 statement.clearParameters();
3758 statement.setInt(1, artifactTypeID);
3759 rs = connection.executeQuery(statement);
3762 count = rs.getLong(
"count");
3765 }
catch (SQLException ex) {
3766 throw new TskCoreException(
"Error getting number of blackboard artifacts by type", ex);
3769 closeConnection(connection);
3786 CaseDbConnection connection = null;
3787 ResultSet rs = null;
3790 connection = connections.getConnection();
3793 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_OF_TYPE_BY_DATA_SOURCE);
3794 statement.clearParameters();
3795 statement.setInt(2, artifactTypeID);
3796 statement.setLong(1, dataSourceID);
3797 rs = connection.executeQuery(statement);
3800 count = rs.getLong(
"count");
3803 }
catch (SQLException ex) {
3804 throw new TskCoreException(String.format(
"Error getting number of blackboard artifacts by type (%d) and data source (%d)", artifactTypeID, dataSourceID), ex);
3807 closeConnection(connection);
3831 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
3832 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
3833 +
"arts.obj_id AS obj_id, arts.artifact_obj_id AS artifact_obj_id, arts.data_source_obj_id AS data_source_obj_id, arts.artifact_type_id AS artifact_type_id, "
3834 +
"types.type_name AS type_name, types.display_name AS display_name, "
3835 +
" arts.review_status_id AS review_status_id "
3836 +
"FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
3837 +
"WHERE arts.artifact_id = attrs.artifact_id "
3838 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
3839 +
" AND attrs.value_text = '" + value +
"'"
3840 +
" AND types.artifact_type_id=arts.artifact_type_id"
3843 List<Long> analysisArtifactObjIds =
new ArrayList<>();
3844 List<Long> dataArtifactObjIds =
new ArrayList<>();
3845 while (resultSet.next()) {
3848 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
3850 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
3854 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
3855 if (!analysisArtifactObjIds.isEmpty()) {
3859 if (!dataArtifactObjIds.isEmpty()) {
3863 }
catch (SQLException ex) {
3864 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
3890 String valSubStr =
"%" + subString;
3891 if (startsWith ==
false) {
3896 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
3897 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
3898 +
" arts.obj_id AS obj_id, arts.artifact_obj_id AS artifact_obj_id, arts.data_source_obj_id AS data_source_obj_id, arts.artifact_type_id AS artifact_type_id, "
3899 +
" types.type_name AS type_name, types.display_name AS display_name, "
3900 +
" arts.review_status_id AS review_status_id "
3901 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
3902 +
" WHERE arts.artifact_id = attrs.artifact_id "
3903 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
3904 +
" AND LOWER(attrs.value_text) LIKE LOWER('" + valSubStr +
"')"
3905 +
" AND types.artifact_type_id=arts.artifact_type_id "
3907 List<Long> analysisArtifactObjIds =
new ArrayList<>();
3908 List<Long> dataArtifactObjIds =
new ArrayList<>();
3909 while (resultSet.next()) {
3912 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
3914 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
3918 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
3919 if (!analysisArtifactObjIds.isEmpty()) {
3923 if (!dataArtifactObjIds.isEmpty()) {
3927 }
catch (SQLException ex) {
3928 throw new TskCoreException(
"Error getting blackboard artifacts by attribute. " + ex.getMessage(), ex);
3952 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
3953 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
3954 +
" arts.obj_id AS obj_id, arts.artifact_obj_id AS artifact_obj_id, arts.data_source_obj_id AS data_source_obj_id, arts.artifact_type_id AS artifact_type_id, "
3955 +
" types.type_name AS type_name, types.display_name AS display_name, "
3956 +
" arts.review_status_id AS review_status_id "
3957 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
3958 +
"WHERE arts.artifact_id = attrs.artifact_id "
3959 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
3960 +
" AND attrs.value_int32 = " + value
3961 +
" AND types.artifact_type_id=arts.artifact_type_id "
3963 List<Long> analysisArtifactObjIds =
new ArrayList<>();
3964 List<Long> dataArtifactObjIds =
new ArrayList<>();
3965 while (resultSet.next()) {
3968 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
3970 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
3974 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
3975 if (!analysisArtifactObjIds.isEmpty()) {
3979 if (!dataArtifactObjIds.isEmpty()) {
3983 }
catch (SQLException ex) {
3984 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
4009 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4010 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4011 +
" arts.obj_id AS obj_id, arts.artifact_obj_id AS artifact_obj_id, arts.data_source_obj_id AS data_source_obj_id, arts.artifact_type_id AS artifact_type_id, "
4012 +
" types.type_name AS type_name, types.display_name AS display_name, "
4013 +
" arts.review_status_id AS review_status_id "
4014 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4015 +
" WHERE arts.artifact_id = attrs.artifact_id "
4016 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4017 +
" AND attrs.value_int64 = " + value
4018 +
" AND types.artifact_type_id=arts.artifact_type_id "
4020 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4021 List<Long> dataArtifactObjIds =
new ArrayList<>();
4022 while (resultSet.next()) {
4025 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4027 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4031 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4032 if (!analysisArtifactObjIds.isEmpty()) {
4036 if (!dataArtifactObjIds.isEmpty()) {
4040 }
catch (SQLException ex) {
4041 throw new TskCoreException(
"Error getting blackboard artifacts by attribute. " + ex.getMessage(), ex);
4066 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4067 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4068 +
" arts.obj_id AS obj_id, arts.artifact_obj_id AS artifact_obj_id, arts.data_source_obj_id AS data_source_obj_id, arts.artifact_type_id AS artifact_type_id, "
4069 +
" types.type_name AS type_name, types.display_name AS display_name, "
4070 +
" arts.review_status_id AS review_status_id "
4071 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4072 +
" WHERE arts.artifact_id = attrs.artifact_id "
4073 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4074 +
" AND attrs.value_double = " + value
4075 +
" AND types.artifact_type_id=arts.artifact_type_id "
4077 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4078 List<Long> dataArtifactObjIds =
new ArrayList<>();
4079 while (resultSet.next()) {
4082 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4084 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4088 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4089 if (!analysisArtifactObjIds.isEmpty()) {
4093 if (!dataArtifactObjIds.isEmpty()) {
4097 }
catch (SQLException ex) {
4098 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
4124 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4125 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4126 +
" arts.obj_id AS obj_id, arts.artifact_obj_id AS artifact_obj_id, arts.data_source_obj_id AS data_source_obj_id, arts.artifact_type_id AS artifact_type_id, "
4127 +
" types.type_name AS type_name, types.display_name AS display_name, "
4128 +
" arts.review_status_id AS review_status_id "
4129 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4130 +
" WHERE arts.artifact_id = attrs.artifact_id "
4131 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4132 +
" AND attrs.value_byte = " + value
4133 +
" AND types.artifact_type_id=arts.artifact_type_id "
4135 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4136 List<Long> dataArtifactObjIds =
new ArrayList<>();
4137 while (resultSet.next()) {
4140 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4142 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4146 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4147 if (!analysisArtifactObjIds.isEmpty()) {
4151 if (!dataArtifactObjIds.isEmpty()) {
4155 }
catch (SQLException ex) {
4156 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
4170 CaseDbConnection connection = null;
4172 ResultSet rs = null;
4175 connection = connections.getConnection();
4176 s = connection.createStatement();
4177 rs = connection.executeQuery(s,
"SELECT artifact_type_id, type_name, display_name, category_type FROM blackboard_artifact_types");
4181 rs.getString(
"type_name"), rs.getString(
"display_name"),
4184 return artifactTypes;
4185 }
catch (SQLException ex) {
4186 throw new TskCoreException(
"Error getting artifact types", ex);
4190 closeConnection(connection);
4204 String typeIdList =
"";
4211 String query =
"SELECT DISTINCT artifact_type_id FROM blackboard_artifacts "
4212 +
"WHERE artifact_type_id IN (" + typeIdList +
")";
4213 CaseDbConnection connection = null;
4215 ResultSet rs = null;
4218 connection = connections.getConnection();
4219 s = connection.createStatement();
4220 rs = connection.executeQuery(s, query);
4226 }
catch (SQLException ex) {
4227 throw new TskCoreException(
"Error getting artifact types in use", ex);
4231 closeConnection(connection);
4247 CaseDbConnection connection = null;
4249 ResultSet rs = null;
4252 connection = connections.getConnection();
4253 s = connection.createStatement();
4254 rs = connection.executeQuery(s,
4255 "SELECT DISTINCT arts.artifact_type_id AS artifact_type_id, "
4256 +
"types.type_name AS type_name, "
4257 +
"types.display_name AS display_name, "
4258 +
"types.category_type AS category_type "
4259 +
"FROM blackboard_artifact_types AS types "
4260 +
"INNER JOIN blackboard_artifacts AS arts "
4261 +
"ON arts.artifact_type_id = types.artifact_type_id");
4265 rs.getString(
"type_name"), rs.getString(
"display_name"),
4268 return uniqueArtifactTypes;
4269 }
catch (SQLException ex) {
4270 throw new TskCoreException(
"Error getting attribute types", ex);
4274 closeConnection(connection);
4287 CaseDbConnection connection = null;
4289 ResultSet rs = null;
4292 connection = connections.getConnection();
4293 s = connection.createStatement();
4294 rs = connection.executeQuery(s,
"SELECT attribute_type_id, type_name, display_name, value_type FROM blackboard_attribute_types");
4300 return attribute_types;
4301 }
catch (SQLException ex) {
4302 throw new TskCoreException(
"Error getting attribute types", ex);
4306 closeConnection(connection);
4323 CaseDbConnection connection = null;
4325 ResultSet rs = null;
4328 connection = connections.getConnection();
4329 s = connection.createStatement();
4330 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM blackboard_attribute_types");
4333 count = rs.getInt(
"count");
4336 }
catch (SQLException ex) {
4337 throw new TskCoreException(
"Error getting number of blackboard artifacts by type", ex);
4341 closeConnection(connection);
4358 private long getArtifactsCountHelper(
int artifactTypeID,
long obj_id)
throws TskCoreException {
4359 CaseDbConnection connection = null;
4360 ResultSet rs = null;
4363 connection = connections.getConnection();
4366 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_BY_SOURCE_AND_TYPE);
4367 statement.clearParameters();
4368 statement.setLong(1, obj_id);
4369 statement.setInt(2, artifactTypeID);
4370 rs = connection.executeQuery(statement);
4373 count = rs.getLong(
"count");
4376 }
catch (SQLException ex) {
4377 throw new TskCoreException(
"Error getting blackboard artifact count", ex);
4380 closeConnection(connection);
4398 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4399 artifacts.addAll(blackboard.getArtifactsBySourceId(
getArtifactType(artifactTypeName), obj_id));
4416 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4417 artifacts.addAll(blackboard.getArtifactsBySourceId(blackboard.
getArtifactType(artifactTypeID), obj_id));
4450 int artifactTypeID = this.
getArtifactType(artifactTypeName).getTypeID();
4451 if (artifactTypeID == -1) {
4454 return getArtifactsCountHelper(artifactTypeID, obj_id);
4470 return getArtifactsCountHelper(artifactTypeID, obj_id);
4486 return getArtifactsCountHelper(artifactType.getTypeID(), obj_id);
4501 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4502 artifacts.addAll(blackboard.getArtifactsByType(
getArtifactType(artifactTypeName)));
4518 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4519 artifacts.addAll(blackboard.getArtifactsByType(blackboard.
getArtifactType(artifactType.getTypeID())));
4541 String dataArtifactJoin =
"tsk_data_artifacts AS datarts ON datarts.artifact_obj_id = arts.artifact_obj_id";
4542 String analysisResultJoin =
"tsk_analysis_results AS anresult ON anresult.artifact_obj_id = arts.artifact_obj_id";
4543 String dataArtifactColumns =
", datarts.os_account_obj_id AS os_account_obj_id";
4544 String analysResultColumns =
", anresult.conclusion AS conclusion, anresult.significance AS significance, anresult.priority AS priority, anresult.configuration AS configuration, anresult.justification AS justification ";
4546 String formatQuery =
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4547 +
"arts.obj_id AS obj_id, arts.artifact_obj_id as artifact_obj_id, arts.data_source_obj_id AS data_source_obj_id, arts.artifact_type_id AS artifact_type_id, "
4548 +
"types.type_name AS type_name, types.display_name AS display_name,"
4549 +
"arts.review_status_id AS review_status_id %s "
4550 +
"FROM blackboard_artifacts AS arts "
4551 +
"JOIN blackboard_attributes AS attrs ON arts.artifact_id = attrs.artifact_id "
4552 +
"JOIN blackboard_artifact_types AS types ON types.artifact_type_id = arts.artifact_type_id "
4554 +
"WHERE arts.artifact_id = attrs.artifact_id "
4555 +
"AND attrs.attribute_type_id = %d "
4556 +
" AND arts.artifact_type_id = %d "
4557 +
" AND attrs.value_text = '%s' "
4558 +
" AND types.artifact_type_id=arts.artifact_type_id "
4559 +
" AND arts.review_status_id != %d";
4561 String query = String.format(formatQuery,
4564 attrType.getTypeID(),
4565 artifactType.getTypeID(),
4570 try (CaseDbConnection connection = connections.getConnection(); Statement s = connection.createStatement(); ResultSet rs = connection.executeQuery(s, query)) {
4571 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4574 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
4576 osAccountObjId = null;
4579 artifacts.add(
new DataArtifact(
this, rs.getLong(
"artifact_id"), rs.getLong(
"obj_id"),
4580 rs.getLong(
"artifact_obj_id"),
4581 rs.getObject(
"data_source_obj_id") != null ? rs.getLong(
"data_source_obj_id") : null,
4582 rs.getInt(
"artifact_type_id"), rs.getString(
"type_name"), rs.getString(
"display_name"),
4585 artifacts.add(
new AnalysisResult(
this, rs.getLong(
"artifact_id"), rs.getLong(
"obj_id"),
4586 rs.getLong(
"artifact_obj_id"),
4587 rs.getObject(
"data_source_obj_id") != null ? rs.getLong(
"data_source_obj_id") : null,
4588 rs.getInt(
"artifact_type_id"), rs.getString(
"type_name"), rs.getString(
"display_name"),
4591 rs.getString(
"conclusion"), rs.getString(
"configuration"), rs.getString(
"justification")));
4595 }
catch (SQLException ex) {
4596 throw new TskCoreException(
"Error getting blackboard artifacts by artifact type and attribute. " + ex.getMessage(), ex);
4614 List<DataArtifact> dataArtifacts = blackboard.
getDataArtifactsWhere(
"artifacts.artifact_id = " + artifactID);
4615 if (!dataArtifacts.isEmpty()) {
4616 return dataArtifacts.get(0);
4619 List<AnalysisResult> analysisResults = blackboard.
getAnalysisResultsWhere(
"artifacts.artifact_id = " + artifactID);
4620 if (!analysisResults.isEmpty()) {
4621 return analysisResults.get(0);
4624 throw new TskCoreException(
"No blackboard artifact with id " + artifactID);
4637 try (CaseDbConnection connection = connections.getConnection();) {
4638 addBlackBoardAttribute(attr, artifactTypeId, connection);
4639 }
catch (SQLException ex) {
4640 throw new TskCoreException(
"Error adding blackboard attribute " + attr.toString(), ex);
4656 CaseDbConnection connection = null;
4659 connection = connections.getConnection();
4660 connection.beginTransaction();
4662 addBlackBoardAttribute(attr, artifactTypeId, connection);
4664 connection.commitTransaction();
4665 }
catch (SQLException ex) {
4666 rollbackTransaction(connection);
4667 throw new TskCoreException(
"Error adding blackboard attributes", ex);
4669 closeConnection(connection);
4674 void addBlackBoardAttribute(
BlackboardAttribute attr,
int artifactTypeId, CaseDbConnection connection)
throws SQLException, TskCoreException {
4675 PreparedStatement statement;
4676 switch (attr.getAttributeType().getValueType()) {
4679 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_STRING_ATTRIBUTE);
4680 statement.clearParameters();
4681 statement.setString(7, attr.getValueString());
4684 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_BYTE_ATTRIBUTE);
4685 statement.clearParameters();
4686 statement.setBytes(7, attr.getValueBytes());
4689 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_INT_ATTRIBUTE);
4690 statement.clearParameters();
4691 statement.setInt(7, attr.getValueInt());
4694 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LONG_ATTRIBUTE);
4695 statement.clearParameters();
4696 statement.setLong(7, attr.getValueLong());
4699 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_DOUBLE_ATTRIBUTE);
4700 statement.clearParameters();
4701 statement.setDouble(7, attr.getValueDouble());
4704 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LONG_ATTRIBUTE);
4705 statement.clearParameters();
4706 statement.setLong(7, attr.getValueLong());
4709 throw new TskCoreException(
"Unrecognized artifact attribute value type");
4711 statement.setLong(1, attr.getArtifactID());
4712 statement.setInt(2, artifactTypeId);
4713 statement.setString(3, attr.getSourcesCSV());
4714 statement.setString(4,
"");
4715 statement.setInt(5, attr.getAttributeType().getTypeID());
4716 statement.setLong(6, attr.getAttributeType().getValueType().getType());
4717 connection.executeUpdate(statement);
4720 void addFileAttribute(Attribute attr, CaseDbConnection connection)
throws SQLException, TskCoreException {
4721 PreparedStatement statement;
4722 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE_ATTRIBUTE, Statement.RETURN_GENERATED_KEYS);
4723 statement.clearParameters();
4725 statement.setLong(1, attr.getAttributeParentId());
4726 statement.setInt(2, attr.getAttributeType().getTypeID());
4727 statement.setLong(3, attr.getAttributeType().getValueType().getType());
4729 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE) {
4730 statement.setBytes(4, attr.getValueBytes());
4732 statement.setBytes(4, null);
4735 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.STRING
4736 || attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.JSON) {
4737 statement.setString(5, attr.getValueString());
4739 statement.setString(5, null);
4741 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.INTEGER) {
4742 statement.setInt(6, attr.getValueInt());
4744 statement.setNull(6, java.sql.Types.INTEGER);
4747 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME
4748 || attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.LONG) {
4749 statement.setLong(7, attr.getValueLong());
4751 statement.setNull(7, java.sql.Types.BIGINT);
4754 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DOUBLE) {
4755 statement.setDouble(8, attr.getValueDouble());
4757 statement.setNull(8, java.sql.Types.DOUBLE);
4760 connection.executeUpdate(statement);
4761 try (ResultSet resultSet = statement.getGeneratedKeys()) {
4762 if (!resultSet.next()) {
4763 throw new TskCoreException(String.format(
"Failed to insert file attribute "
4764 +
"with id=%d. The expected key was not generated", attr.getId()));
4767 attr.setId(resultSet.getLong(1));
4781 String addSourceToArtifactAttribute(BlackboardAttribute attr, String source)
throws TskCoreException {
4789 if (null == source || source.isEmpty()) {
4790 throw new TskCoreException(
"Attempt to add null or empty source module name to artifact attribute");
4792 CaseDbConnection connection = null;
4794 Statement queryStmt = null;
4795 Statement updateStmt = null;
4796 ResultSet result = null;
4797 String newSources =
"";
4799 connection = connections.getConnection();
4800 connection.beginTransaction();
4801 String valueClause =
"";
4802 BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE valueType = attr.getAttributeType().getValueType();
4803 if (BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE != valueType) {
4804 switch (valueType) {
4810 valueClause =
" value_int32 = " + attr.getValueInt();
4814 valueClause =
" value_int64 = " + attr.getValueLong();
4817 valueClause =
" value_double = " + attr.getValueDouble();
4820 throw new TskCoreException(String.format(
"Unrecognized value type for attribute %s", attr.getDisplayString()));
4822 String query =
"SELECT source FROM blackboard_attributes WHERE"
4823 +
" artifact_id = " + attr.getArtifactID()
4824 +
" AND attribute_type_id = " + attr.getAttributeType().getTypeID()
4825 +
" AND value_type = " + attr.getAttributeType().getValueType().getType()
4826 +
" AND " + valueClause +
";";
4827 queryStmt = connection.createStatement();
4828 updateStmt = connection.createStatement();
4829 result = connection.executeQuery(queryStmt, query);
4836 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ATTR_BY_VALUE_BYTE);
4837 statement.clearParameters();
4838 statement.setLong(1, attr.getArtifactID());
4839 statement.setLong(2, attr.getAttributeType().getTypeID());
4840 statement.setBytes(3, attr.getValueBytes());
4841 result = connection.executeQuery(statement);
4843 while (result.next()) {
4844 String oldSources = result.getString(
"source");
4845 if (null != oldSources && !oldSources.isEmpty()) {
4846 Set<String> uniqueSources =
new HashSet<String>(Arrays.asList(oldSources.split(
",")));
4847 if (!uniqueSources.contains(source)) {
4848 newSources = oldSources +
"," + source;
4850 newSources = oldSources;
4853 newSources = source;
4855 if (BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE != valueType) {
4856 String update =
"UPDATE blackboard_attributes SET source = '" + newSources +
"' WHERE"
4857 +
" artifact_id = " + attr.getArtifactID()
4858 +
" AND attribute_type_id = " + attr.getAttributeType().getTypeID()
4859 +
" AND value_type = " + attr.getAttributeType().getValueType().getType()
4860 +
" AND " + valueClause +
";";
4861 connection.executeUpdate(updateStmt, update);
4868 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ATTR_BY_VALUE_BYTE);
4869 statement.clearParameters();
4870 statement.setString(1, newSources);
4871 statement.setLong(2, attr.getArtifactID());
4872 statement.setLong(3, attr.getAttributeType().getTypeID());
4873 statement.setBytes(4, attr.getValueBytes());
4874 connection.executeUpdate(statement);
4877 connection.commitTransaction();
4879 }
catch (SQLException ex) {
4880 rollbackTransaction(connection);
4881 throw new TskCoreException(String.format(
"Error adding source module to attribute %s", attr.getDisplayString()), ex);
4883 closeResultSet(result);
4884 closeStatement(updateStmt);
4885 closeStatement(queryStmt);
4886 closeConnection(connection);
4910 throw new TskCoreException(
"Error adding artifact type: " + attrTypeString, ex);
4986 }
catch (BlackboardException ex) {
4987 throw new TskCoreException(
"Error getting or adding artifact type with name: " + artifactTypeName, ex);
5021 CaseDbConnection connection = null;
5023 ResultSet rs = null;
5026 connection = connections.getConnection();
5027 s = connection.createStatement();
5028 rs = connection.executeQuery(s,
"SELECT blackboard_attributes.artifact_id AS artifact_id, "
5029 +
"blackboard_attributes.source AS source, blackboard_attributes.context AS context, "
5030 +
"blackboard_attributes.attribute_type_id AS attribute_type_id, "
5031 +
"blackboard_attributes.value_type AS value_type, blackboard_attributes.value_byte AS value_byte, "
5032 +
"blackboard_attributes.value_text AS value_text, blackboard_attributes.value_int32 AS value_int32, "
5033 +
"blackboard_attributes.value_int64 AS value_int64, blackboard_attributes.value_double AS value_double "
5034 +
"FROM blackboard_attributes " + whereClause);
5035 ArrayList<BlackboardAttribute> matches =
new ArrayList<>();
5041 rs.getLong(
"artifact_id"),
5043 rs.getString(
"source"),
5044 rs.getString(
"context"),
5045 rs.getInt(
"value_int32"),
5046 rs.getLong(
"value_int64"),
5047 rs.getDouble(
"value_double"),
5048 rs.getString(
"value_text"),
5049 rs.getBytes(
"value_byte"), this
5054 }
catch (SQLException ex) {
5055 throw new TskCoreException(
"Error getting attributes using this where clause: " + whereClause, ex);
5059 closeConnection(connection);
5076 String query =
"SELECT blackboard_artifacts.artifact_id AS artifact_id, "
5077 +
"blackboard_artifacts.obj_id AS obj_id, blackboard_artifacts.artifact_obj_id AS artifact_obj_id, blackboard_artifacts.data_source_obj_id AS data_source_obj_id, blackboard_artifacts.artifact_type_id AS artifact_type_id, "
5078 +
"blackboard_artifacts.review_status_id AS review_status_id "
5079 +
"FROM blackboard_artifacts " + whereClause;
5081 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) {
5083 List<Long> analysisArtifactObjIds =
new ArrayList<>();
5084 List<Long> dataArtifactObjIds =
new ArrayList<>();
5085 while (resultSet.next()) {
5088 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
5090 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
5094 ArrayList<BlackboardArtifact> matches =
new ArrayList<>();
5095 if (!analysisArtifactObjIds.isEmpty()) {
5099 if (!dataArtifactObjIds.isEmpty()) {
5104 }
catch (SQLException ex) {
5105 throw new TskCoreException(
"Error getting attributes using this where clause: " + whereClause, ex);
5129 throw new TskCoreException(
"Unknown artifact type for id: " + artifactTypeID);
5132 Category category = type.getCategory();
5133 if (category == null) {
5134 throw new TskCoreException(String.format(
"No category for %s (id: %d)",
5135 type.getDisplayName() == null ?
"<null>" : type.getDisplayName(),
5140 if (content == null) {
5141 throw new TskCoreException(
"No content found for object id: " + obj_id);
5145 case ANALYSIS_RESULT:
5147 .getAnalysisResult();
5151 throw new TskCoreException(
"Unknown category type: " + category.
getName());
5168 @SuppressWarnings(
"deprecation")
5189 @SuppressWarnings(
"deprecation")
5192 try (CaseDbConnection connection = connections.getConnection()) {
5193 return newBlackboardArtifact(artifactTypeID, obj_id, type.getTypeName(), type.getDisplayName(), data_source_obj_id, connection);
5198 private BlackboardArtifact
newBlackboardArtifact(
int artifact_type_id,
long obj_id, String artifactTypeName, String artifactDisplayName)
throws TskCoreException {
5199 try (CaseDbConnection connection = connections.getConnection()) {
5200 long data_source_obj_id = getDataSourceObjectId(connection, obj_id);
5201 return this.
newBlackboardArtifact(artifact_type_id, obj_id, artifactTypeName, artifactDisplayName, data_source_obj_id, connection);
5205 PreparedStatement createInsertArtifactStatement(
int artifact_type_id,
long obj_id,
long artifact_obj_id,
long data_source_obj_id, CaseDbConnection connection)
throws TskCoreException, SQLException {
5207 PreparedStatement statement;
5209 statement = connection.getPreparedStatement(PREPARED_STATEMENT.POSTGRESQL_INSERT_ARTIFACT, Statement.RETURN_GENERATED_KEYS);
5210 statement.clearParameters();
5211 statement.setLong(1, obj_id);
5212 statement.setLong(2, artifact_obj_id);
5213 statement.setLong(3, data_source_obj_id);
5214 statement.setInt(4, artifact_type_id);
5216 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_ARTIFACT, Statement.RETURN_GENERATED_KEYS);
5217 statement.clearParameters();
5218 this.nextArtifactId++;
5219 statement.setLong(1, this.nextArtifactId);
5220 statement.setLong(2, obj_id);
5221 statement.setLong(3, artifact_obj_id);
5222 statement.setLong(4, data_source_obj_id);
5223 statement.setInt(5, artifact_type_id);
5246 private BlackboardArtifact
newBlackboardArtifact(
int artifact_type_id,
long obj_id, String artifactTypeName, String artifactDisplayName,
long data_source_obj_id, CaseDbConnection connection)
throws TskCoreException {
5249 if (type.getCategory() == BlackboardArtifact.Category.ANALYSIS_RESULT) {
5250 return blackboard.
newAnalysisResult(type, obj_id, data_source_obj_id, Score.SCORE_UNKNOWN, null, null, null, Collections.emptyList()).getAnalysisResult();
5252 return blackboard.
newDataArtifact(type, obj_id, data_source_obj_id, Collections.emptyList(), null);
5254 }
catch (BlackboardException ex) {
5255 throw new TskCoreException(
"Error creating a blackboard artifact", ex);
5277 AnalysisResult newAnalysisResult(BlackboardArtifact.Type artifactType,
long objId, Long dataSourceObjId, Score score, String conclusion, String configuration, String justification, CaseDbConnection connection)
throws TskCoreException {
5279 if (artifactType.getCategory() != BlackboardArtifact.Category.ANALYSIS_RESULT) {
5280 throw new TskCoreException(String.format(
"Artifact type (name = %s) is not of the AnalysisResult category. ", artifactType.getTypeName()));
5287 long artifactObjId = addObject(objId, TskData.ObjectType.ARTIFACT.getObjectType(), connection);
5290 PreparedStatement insertArtifactstatement;
5291 ResultSet resultSet = null;
5293 insertArtifactstatement = createInsertArtifactStatement(artifactType.getTypeID(), objId, artifactObjId, dataSourceObjId, connection);
5294 connection.executeUpdate(insertArtifactstatement);
5295 resultSet = insertArtifactstatement.getGeneratedKeys();
5297 artifactID = resultSet.getLong(1);
5300 if (score.getSignificance() != Score.Significance.UNKNOWN
5301 || !StringUtils.isBlank(conclusion)
5302 || !StringUtils.isBlank(configuration)
5303 || !StringUtils.isBlank(justification)) {
5305 PreparedStatement analysisResultsStatement;
5307 analysisResultsStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_ANALYSIS_RESULT);
5308 analysisResultsStatement.clearParameters();
5310 analysisResultsStatement.setLong(1, artifactObjId);
5311 analysisResultsStatement.setString(2, (conclusion != null) ? conclusion :
"");
5312 analysisResultsStatement.setInt(3, score.getSignificance().getId());
5313 analysisResultsStatement.setInt(4, score.getPriority().getId());
5314 analysisResultsStatement.setString(5, (configuration != null) ? configuration :
"");
5315 analysisResultsStatement.setString(6, (justification != null) ? justification :
"");
5317 connection.executeUpdate(analysisResultsStatement);
5320 return new AnalysisResult(
this, artifactID, objId, artifactObjId, dataSourceObjId, artifactType.getTypeID(),
5321 artifactType.getTypeName(), artifactType.getDisplayName(),
5322 BlackboardArtifact.ReviewStatus.UNDECIDED,
true,
5323 score, (conclusion != null) ? conclusion :
"",
5324 (configuration != null) ? configuration :
"", (justification != null) ? justification :
"");
5327 closeResultSet(resultSet);
5330 }
catch (SQLException ex) {
5331 throw new TskCoreException(
"Error creating a analysis result", ex);
5349 boolean getContentHasChildren(Content content)
throws TskCoreException {
5350 CaseDbConnection connection = null;
5351 ResultSet rs = null;
5354 connection = connections.getConnection();
5357 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CHILD_OBJECTS_BY_PARENT);
5358 statement.clearParameters();
5359 statement.setLong(1, content.getId());
5360 rs = connection.executeQuery(statement);
5361 boolean hasChildren =
false;
5363 hasChildren = rs.getInt(
"count") > 0;
5366 }
catch (SQLException e) {
5367 throw new TskCoreException(
"Error checking for children of parent " + content, e);
5370 closeConnection(connection);
5387 int getContentChildrenCount(Content content)
throws TskCoreException {
5389 if (!this.getHasChildren(content)) {
5393 CaseDbConnection connection = null;
5394 ResultSet rs = null;
5397 connection = connections.getConnection();
5400 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CHILD_OBJECTS_BY_PARENT);
5401 statement.clearParameters();
5402 statement.setLong(1, content.getId());
5403 rs = connection.executeQuery(statement);
5404 int countChildren = -1;
5406 countChildren = rs.getInt(
"count");
5408 return countChildren;
5409 }
catch (SQLException e) {
5410 throw new TskCoreException(
"Error checking for children of parent " + content, e);
5413 closeConnection(connection);
5429 List<Content> getAbstractFileChildren(Content parent, TSK_DB_FILES_TYPE_ENUM type)
throws TskCoreException {
5430 CaseDbConnection connection = null;
5431 ResultSet rs = null;
5434 connection = connections.getConnection();
5436 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_PARENT_AND_TYPE);
5437 statement.clearParameters();
5438 long parentId = parent.getId();
5439 statement.setLong(1, parentId);
5440 statement.setShort(2, type.getFileType());
5441 rs = connection.executeQuery(statement);
5442 return fileChildren(rs, connection, parentId);
5443 }
catch (SQLException ex) {
5444 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5447 closeConnection(connection);
5461 List<Content> getAbstractFileChildren(Content parent)
throws TskCoreException {
5462 CaseDbConnection connection = null;
5463 ResultSet rs = null;
5466 connection = connections.getConnection();
5468 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_PARENT);
5469 statement.clearParameters();
5470 long parentId = parent.getId();
5471 statement.setLong(1, parentId);
5472 rs = connection.executeQuery(statement);
5473 return fileChildren(rs, connection, parentId);
5474 }
catch (SQLException ex) {
5475 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5478 closeConnection(connection);
5494 List<Long> getAbstractFileChildrenIds(Content parent, TSK_DB_FILES_TYPE_ENUM type)
throws TskCoreException {
5495 CaseDbConnection connection = null;
5496 ResultSet rs = null;
5499 connection = connections.getConnection();
5501 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_IDS_BY_PARENT_AND_TYPE);
5502 statement.clearParameters();
5503 statement.setLong(1, parent.getId());
5504 statement.setShort(2, type.getFileType());
5505 rs = connection.executeQuery(statement);
5506 List<Long> children =
new ArrayList<Long>();
5508 children.add(rs.getLong(
"obj_id"));
5511 }
catch (SQLException ex) {
5512 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5515 closeConnection(connection);
5529 List<Long> getAbstractFileChildrenIds(Content parent)
throws TskCoreException {
5530 CaseDbConnection connection = null;
5531 ResultSet rs = null;
5534 connection = connections.getConnection();
5536 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_IDS_BY_PARENT);
5537 statement.clearParameters();
5538 statement.setLong(1, parent.getId());
5539 rs = connection.executeQuery(statement);
5540 List<Long> children =
new ArrayList<Long>();
5542 children.add(rs.getLong(
"obj_id"));
5545 }
catch (SQLException ex) {
5546 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5549 closeConnection(connection);
5564 List<Long> getBlackboardArtifactChildrenIds(Content parent)
throws TskCoreException {
5565 CaseDbConnection connection = null;
5566 ResultSet rs = null;
5569 connection = connections.getConnection();
5571 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_OBJECTIDS_BY_PARENT);
5572 statement.clearParameters();
5573 statement.setLong(1, parent.getId());
5574 rs = connection.executeQuery(statement);
5575 List<Long> children =
new ArrayList<Long>();
5577 children.add(rs.getLong(
"obj_id"));
5580 }
catch (SQLException ex) {
5581 throw new TskCoreException(
"Error getting children for BlackboardArtifact", ex);
5584 closeConnection(connection);
5598 List<Content> getBlackboardArtifactChildren(Content parent)
throws TskCoreException {
5599 long parentId = parent.getId();
5600 List<Content> lc =
new ArrayList<>();
5602 lc.addAll(blackboard.getDataArtifactsBySource(parentId));
5614 Collection<ObjectInfo> getChildrenInfo(Content c)
throws TskCoreException {
5615 CaseDbConnection connection = null;
5617 ResultSet rs = null;
5620 connection = connections.getConnection();
5621 s = connection.createStatement();
5622 rs = connection.executeQuery(s,
"SELECT tsk_objects.obj_id AS obj_id, tsk_objects.type AS type "
5623 +
"FROM tsk_objects LEFT JOIN tsk_files "
5624 +
"ON tsk_objects.obj_id = tsk_files.obj_id "
5625 +
"WHERE tsk_objects.par_obj_id = " + c.getId()
5626 +
" ORDER BY tsk_objects.obj_id");
5627 Collection<ObjectInfo> infos =
new ArrayList<ObjectInfo>();
5629 infos.add(
new ObjectInfo(rs.getLong(
"obj_id"), ObjectType.valueOf(rs.getShort(
"type"))));
5632 }
catch (SQLException ex) {
5633 throw new TskCoreException(
"Error getting Children Info for Content", ex);
5637 closeConnection(connection);
5652 ObjectInfo getParentInfo(Content c)
throws TskCoreException {
5653 return getParentInfo(c.getId());
5666 ObjectInfo getParentInfo(
long contentId)
throws TskCoreException {
5668 CaseDbConnection connection = null;
5670 ResultSet rs = null;
5672 connection = connections.getConnection();
5673 s = connection.createStatement();
5674 rs = connection.executeQuery(s,
"SELECT parent.obj_id AS obj_id, parent.type AS type "
5675 +
"FROM tsk_objects AS parent INNER JOIN tsk_objects AS child "
5676 +
"ON child.par_obj_id = parent.obj_id "
5677 +
"WHERE child.obj_id = " + contentId);
5679 return new ObjectInfo(rs.getLong(
"obj_id"), ObjectType.valueOf(rs.getShort(
"type")));
5683 }
catch (SQLException ex) {
5684 throw new TskCoreException(
"Error getting Parent Info for Content: " + contentId, ex);
5688 closeConnection(connection);
5703 Directory getParentDirectory(FsContent fsc)
throws TskCoreException {
5708 ObjectInfo parentInfo = getParentInfo(fsc);
5709 if (parentInfo == null) {
5712 Directory parent = null;
5713 if (parentInfo.type == ObjectType.ABSTRACTFILE) {
5714 parent = getDirectoryById(parentInfo.id, fsc.getFileSystem());
5716 throw new TskCoreException(
"Parent of FsContent (id: " + fsc.getId() +
") has wrong type to be directory: " + parentInfo.type);
5735 Content content = frequentlyUsedContentMap.get(
id);
5736 if (null != content) {
5743 CaseDbConnection connection = null;
5745 ResultSet rs = null;
5748 connection = connections.getConnection();
5749 s = connection.createStatement();
5750 rs = connection.executeQuery(s,
"SELECT * FROM tsk_objects WHERE obj_id = " +
id +
" LIMIT 1");
5754 parentId = rs.getLong(
"par_obj_id");
5756 }
catch (SQLException ex) {
5757 throw new TskCoreException(
"Error getting Content by ID.", ex);
5761 closeConnection(connection);
5769 frequentlyUsedContentMap.put(
id, content);
5772 content = getVolumeSystemById(
id, parentId);
5775 content = getVolumeById(
id, parentId);
5776 frequentlyUsedContentMap.put(
id, content);
5779 content = getPoolById(
id, parentId);
5782 content = getFileSystemById(
id, parentId);
5783 frequentlyUsedContentMap.put(
id, content);
5794 frequentlyUsedContentMap.put(
id, content);
5823 String getFilePath(
long id) {
5825 String filePath = null;
5826 CaseDbConnection connection = null;
5827 ResultSet rs = null;
5830 connection = connections.getConnection();
5832 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_LOCAL_PATH_FOR_FILE);
5833 statement.clearParameters();
5834 statement.setLong(1,
id);
5835 rs = connection.executeQuery(statement);
5837 filePath = rs.getString(
"path");
5839 }
catch (SQLException | TskCoreException ex) {
5840 logger.log(Level.SEVERE,
"Error getting file path for file " +
id, ex);
5843 closeConnection(connection);
5856 TskData.EncodingType getEncodingType(
long id) {
5858 TskData.EncodingType type = TskData.EncodingType.NONE;
5859 CaseDbConnection connection = null;
5860 ResultSet rs = null;
5863 connection = connections.getConnection();
5864 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ENCODING_FOR_FILE);
5865 statement.clearParameters();
5866 statement.setLong(1,
id);
5867 rs = connection.executeQuery(statement);
5869 type = TskData.EncodingType.valueOf(rs.getInt(1));
5871 }
catch (SQLException | TskCoreException ex) {
5872 logger.log(Level.SEVERE,
"Error getting encoding type for file " +
id, ex);
5875 closeConnection(connection);
5889 String getFileParentPath(
long objectId, CaseDbConnection connection) {
5890 String parentPath = null;
5892 ResultSet rs = null;
5894 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_PATH_FOR_FILE);
5895 statement.clearParameters();
5896 statement.setLong(1, objectId);
5897 rs = connection.executeQuery(statement);
5899 parentPath = rs.getString(
"parent_path");
5901 }
catch (SQLException ex) {
5902 logger.log(Level.SEVERE,
"Error getting file parent_path for file " + objectId, ex);
5918 String getFileName(
long objectId, CaseDbConnection connection) {
5919 String fileName = null;
5921 ResultSet rs = null;
5923 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_NAME);
5924 statement.clearParameters();
5925 statement.setLong(1, objectId);
5926 rs = connection.executeQuery(statement);
5928 fileName = rs.getString(
"name");
5930 }
catch (SQLException ex) {
5931 logger.log(Level.SEVERE,
"Error getting file parent_path for file " + objectId, ex);
5949 DerivedFile.DerivedMethod getDerivedMethod(
long id)
throws TskCoreException {
5951 DerivedFile.DerivedMethod method = null;
5952 CaseDbConnection connection = null;
5953 ResultSet rs1 = null;
5954 ResultSet rs2 = null;
5957 connection = connections.getConnection();
5959 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_DERIVED_FILE);
5960 statement.clearParameters();
5961 statement.setLong(1,
id);
5962 rs1 = connection.executeQuery(statement);
5964 int method_id = rs1.getInt(
"derived_id");
5965 String rederive = rs1.getString(
"rederive");
5966 method =
new DerivedFile.DerivedMethod(method_id, rederive);
5967 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_DERIVATION_METHOD);
5968 statement.clearParameters();
5969 statement.setInt(1, method_id);
5970 rs2 = connection.executeQuery(statement);
5972 method.setToolName(rs2.getString(
"tool_name"));
5973 method.setToolVersion(rs2.getString(
"tool_version"));
5974 method.setOther(rs2.getString(
"other"));
5977 }
catch (SQLException e) {
5978 logger.log(Level.SEVERE,
"Error getting derived method for file: " +
id, e);
5980 closeResultSet(rs2);
5981 closeResultSet(rs1);
5982 closeConnection(connection);
5999 CaseDbConnection connection = connections.getConnection();
6003 closeConnection(connection);
6021 ResultSet rs = null;
6023 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_BY_ID);
6024 statement.clearParameters();
6025 statement.setLong(1, objectId);
6026 rs = connection.executeQuery(statement);
6027 List<AbstractFile> files = resultSetToAbstractFiles(rs, connection);
6028 if (files.size() > 0) {
6029 return files.get(0);
6033 }
catch (SQLException ex) {
6034 throw new TskCoreException(
"Error getting file by id, id = " + objectId, ex);
6054 CaseDbConnection connection = null;
6055 ResultSet rs = null;
6058 connection = connections.getConnection();
6061 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TYPE_BY_ARTIFACT_OBJ_ID);
6062 statement.clearParameters();
6063 statement.setLong(1,
id);
6065 rs = connection.executeQuery(statement);
6067 throw new TskCoreException(
"Error getting artifacttype for artifact with artifact_obj_id = " +
id);
6072 switch (artifactType.getCategory()) {
6073 case ANALYSIS_RESULT:
6078 throw new TskCoreException(String.format(
"Unknown artifact category for artifact with artifact_obj_id = %d, and artifact type = %s",
id, artifactType.getTypeName()));
6081 }
catch (SQLException ex) {
6082 throw new TskCoreException(
"Error getting artifacts by artifact_obj_id, artifact_obj_id = " +
id, ex);
6085 closeConnection(connection);
6105 String query =
"SELECT artifact_type_id, artifact_obj_id FROM blackboard_artifacts WHERE artifact_id = " + id;
6108 try (CaseDbConnection connection = connections.getConnection();
6109 Statement statement = connection.createStatement();
6110 ResultSet resultSet = statement.executeQuery(query);) {
6111 if (resultSet != null && resultSet.next()) {
6113 long artifactObjId = resultSet.getLong(
"artifact_obj_id");
6114 switch (artifactType.getCategory()) {
6115 case ANALYSIS_RESULT:
6122 }
catch (SQLException ex) {
6123 throw new TskCoreException(
"Error getting artifacts by artifact id, artifact id = " +
id, ex);
6141 private long getFileSystemId(
long fileId, CaseDbConnection connection) {
6143 ResultSet rs = null;
6146 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_SYSTEM_BY_OBJECT);
6147 statement.clearParameters();
6148 statement.setLong(1, fileId);
6149 rs = connection.executeQuery(statement);
6151 ret = rs.getLong(
"fs_obj_id");
6156 }
catch (SQLException e) {
6157 logger.log(Level.SEVERE,
"Error checking file system id of a file, id = " + fileId, e);
6177 String query = String.format(
"SELECT COUNT(*) AS count FROM tsk_files WHERE obj_id = %d AND data_source_obj_id = %d", fileId, dataSource.getId());
6178 CaseDbConnection connection = null;
6179 Statement statement = null;
6180 ResultSet resultSet = null;
6183 connection = connections.getConnection();
6184 statement = connection.createStatement();
6185 resultSet = connection.executeQuery(statement, query);
6187 return (resultSet.getLong(
"count") > 0L);
6188 }
catch (SQLException ex) {
6189 throw new TskCoreException(String.format(
"Error executing query %s", query), ex);
6191 closeResultSet(resultSet);
6192 closeStatement(statement);
6193 closeConnection(connection);
6207 private static boolean containsLikeWildcard(String str) {
6211 return str.contains(
"%") || str.contains(
"_");
6226 public List<AbstractFile>
findFiles(
Content dataSource, String fileName)
throws TskCoreException {
6228 if (!containsLikeWildcard(fileName)) {
6232 List<AbstractFile> files =
new ArrayList<>();
6233 CaseDbConnection connection = null;
6234 ResultSet resultSet = null;
6237 connection = connections.getConnection();
6239 PreparedStatement statement;
6240 if (ext.isEmpty()) {
6241 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_DATA_SOURCE_AND_NAME);
6242 statement.clearParameters();
6243 statement.setString(1, fileName.toLowerCase());
6244 statement.setLong(2, dataSource.getId());
6246 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_EXTENSION_AND_DATA_SOURCE_AND_NAME);
6247 statement.clearParameters();
6248 statement.setString(1, ext);
6249 statement.setString(2, fileName.toLowerCase());
6250 statement.setLong(3, dataSource.getId());
6253 resultSet = connection.executeQuery(statement);
6254 files.addAll(resultSetToAbstractFiles(resultSet, connection));
6255 }
catch (SQLException e) {
6256 throw new TskCoreException(bundle.getString(
"SleuthkitCase.findFiles.exception.msg3.text"), e);
6258 closeResultSet(resultSet);
6259 closeConnection(connection);
6278 public List<AbstractFile>
findFiles(
Content dataSource, String fileName, String dirSubString)
throws TskCoreException {
6280 if (!containsLikeWildcard(fileName)) {
6284 List<AbstractFile> files =
new ArrayList<>();
6285 CaseDbConnection connection = null;
6286 ResultSet resultSet = null;
6289 connection = connections.getConnection();
6290 PreparedStatement statement;
6291 if (ext.isEmpty()) {
6292 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_DATA_SOURCE_AND_PARENT_PATH_AND_NAME);
6293 statement.clearParameters();
6294 statement.setString(1, fileName.toLowerCase());
6295 statement.setString(2,
"%" + dirSubString.toLowerCase() +
"%");
6296 statement.setLong(3, dataSource.getId());
6298 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_EXTENSION_AND_DATA_SOURCE_AND_PARENT_PATH_AND_NAME);
6299 statement.clearParameters();
6300 statement.setString(1, ext);
6301 statement.setString(2, fileName.toLowerCase());
6302 statement.setString(3,
"%" + dirSubString.toLowerCase() +
"%");
6303 statement.setLong(4, dataSource.getId());
6306 resultSet = connection.executeQuery(statement);
6307 files.addAll(resultSetToAbstractFiles(resultSet, connection));
6308 }
catch (SQLException e) {
6309 throw new TskCoreException(bundle.getString(
"SleuthkitCase.findFiles3.exception.msg3.text"), e);
6311 closeResultSet(resultSet);
6312 closeConnection(connection);
6337 if (null != localTrans) {
6340 }
catch (TskCoreException ex2) {
6341 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
6359 long addObject(
long parentId,
int objectType, CaseDbConnection connection)
throws SQLException {
6360 ResultSet resultSet = null;
6364 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_OBJECT, Statement.RETURN_GENERATED_KEYS);
6365 statement.clearParameters();
6366 if (parentId != 0) {
6367 statement.setLong(1, parentId);
6369 statement.setNull(1, java.sql.Types.BIGINT);
6371 statement.setInt(2, objectType);
6372 connection.executeUpdate(statement);
6373 resultSet = statement.getGeneratedKeys();
6375 if (resultSet.next()) {
6376 if (parentId != 0) {
6377 setHasChildren(parentId);
6379 return resultSet.getLong(1);
6381 throw new SQLException(
"Error inserting object with parent " + parentId +
" into tsk_objects");
6384 closeResultSet(resultSet);
6407 if (transaction == null) {
6408 throw new TskCoreException(
"Passed null CaseDbTransaction");
6411 ResultSet resultSet = null;
6414 CaseDbConnection connection = transaction.getConnection();
6419 if (isRootDirectory((AbstractFile) parent, transaction)) {
6420 if (parent.
getName().isEmpty()) {
6423 parentPath =
"/" + parent.
getName() +
"/";
6426 parentPath = ((AbstractFile) parent).getParentPath() + parent.
getName() +
"/";
6440 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
6441 statement.clearParameters();
6442 statement.setLong(1, newObjId);
6445 Long fileSystemObjectId = null;
6446 if (0 != parentId) {
6447 fileSystemObjectId = this.getFileSystemId(parentId, connection);
6448 if (fileSystemObjectId != -1) {
6449 statement.setLong(2, fileSystemObjectId);
6451 statement.setNull(2, java.sql.Types.BIGINT);
6452 fileSystemObjectId = null;
6455 statement.setNull(2, java.sql.Types.BIGINT);
6459 statement.setString(3, directoryName);
6463 statement.setShort(5, (
short) 1);
6467 statement.setShort(6, dirType.
getValue());
6469 statement.setShort(7, metaType.
getValue());
6473 statement.setShort(8, dirFlag.
getValue());
6476 statement.setShort(9, metaFlags);
6479 statement.setLong(10, 0);
6482 statement.setNull(11, java.sql.Types.BIGINT);
6483 statement.setNull(12, java.sql.Types.BIGINT);
6484 statement.setNull(13, java.sql.Types.BIGINT);
6485 statement.setNull(14, java.sql.Types.BIGINT);
6487 statement.setNull(15, java.sql.Types.VARCHAR);
6488 statement.setNull(16, java.sql.Types.VARCHAR);
6489 statement.setNull(17, java.sql.Types.VARCHAR);
6492 statement.setNull(19, java.sql.Types.VARCHAR);
6495 statement.setString(20, parentPath);
6498 long dataSourceObjectId;
6499 if (0 == parentId) {
6500 dataSourceObjectId = newObjId;
6502 dataSourceObjectId = getDataSourceObjectId(connection, parentId);
6504 statement.setLong(21, dataSourceObjectId);
6507 statement.setString(22, null);
6509 statement.setString(23,
OsAccount.NO_OWNER_ID);
6510 statement.setNull(24, java.sql.Types.BIGINT);
6513 connection.executeUpdate(statement);
6515 return new VirtualDirectory(
this, newObjId, dataSourceObjectId, fileSystemObjectId, directoryName, dirType,
6518 }
catch (SQLException e) {
6519 throw new TskCoreException(
"Error creating virtual directory '" + directoryName +
"'", e);
6521 closeResultSet(resultSet);
6543 }
catch (TskCoreException ex) {
6546 }
catch (TskCoreException ex2) {
6547 logger.log(Level.SEVERE, String.format(
"Failed to rollback transaction after exception: %s", ex.getMessage()), ex2);
6571 if (transaction == null) {
6572 throw new TskCoreException(
"Passed null CaseDbTransaction");
6575 ResultSet resultSet = null;
6578 CaseDbConnection connection = transaction.getConnection();
6581 if ((parent == null) || isRootDirectory(parent, transaction)) {
6594 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
6595 statement.clearParameters();
6596 statement.setLong(1, newObjId);
6599 statement.setNull(2, java.sql.Types.BIGINT);
6602 statement.setString(3, directoryName);
6606 statement.setShort(5, (
short) 1);
6610 statement.setShort(6, dirType.
getValue());
6612 statement.setShort(7, metaType.
getValue());
6616 statement.setShort(8, dirFlag.
getValue());
6619 statement.setShort(9, metaFlags);
6622 statement.setLong(10, 0);
6625 statement.setNull(11, java.sql.Types.BIGINT);
6626 statement.setNull(12, java.sql.Types.BIGINT);
6627 statement.setNull(13, java.sql.Types.BIGINT);
6628 statement.setNull(14, java.sql.Types.BIGINT);
6630 statement.setNull(15, java.sql.Types.VARCHAR);
6631 statement.setNull(16, java.sql.Types.VARCHAR);
6632 statement.setNull(17, java.sql.Types.VARCHAR);
6635 statement.setNull(19, java.sql.Types.VARCHAR);
6638 statement.setString(20, parentPath);
6641 long dataSourceObjectId = getDataSourceObjectId(connection, parentId);
6642 statement.setLong(21, dataSourceObjectId);
6645 statement.setString(22, null);
6647 statement.setString(23,
OsAccount.NO_OWNER_ID);
6648 statement.setNull(24, java.sql.Types.BIGINT);
6651 connection.executeUpdate(statement);
6653 return new LocalDirectory(
this, newObjId, dataSourceObjectId, directoryName, dirType,
6656 }
catch (SQLException e) {
6657 throw new TskCoreException(
"Error creating local directory '" + directoryName +
"'", e);
6659 closeResultSet(resultSet);
6708 Statement statement = null;
6710 CaseDbConnection connection = transaction.getConnection();
6723 statement = connection.createStatement();
6724 statement.executeUpdate(
"INSERT INTO data_source_info (obj_id, device_id, time_zone, host_id) "
6725 +
"VALUES(" + newObjId +
", '" + deviceId +
"', '" + timeZone +
"', " + host.getHostId() +
");");
6734 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
6735 preparedStatement.clearParameters();
6736 preparedStatement.setLong(1, newObjId);
6737 preparedStatement.setNull(2, java.sql.Types.BIGINT);
6738 preparedStatement.setString(3, rootDirectoryName);
6740 preparedStatement.setShort(5, (
short) 1);
6744 preparedStatement.setShort(7, metaType.
getValue());
6746 preparedStatement.setShort(8, dirFlag.
getValue());
6749 preparedStatement.setShort(9, metaFlags);
6750 preparedStatement.setLong(10, 0);
6751 preparedStatement.setNull(11, java.sql.Types.BIGINT);
6752 preparedStatement.setNull(12, java.sql.Types.BIGINT);
6753 preparedStatement.setNull(13, java.sql.Types.BIGINT);
6754 preparedStatement.setNull(14, java.sql.Types.BIGINT);
6755 preparedStatement.setNull(15, java.sql.Types.VARCHAR);
6756 preparedStatement.setNull(16, java.sql.Types.VARCHAR);
6757 preparedStatement.setNull(17, java.sql.Types.VARCHAR);
6759 preparedStatement.setNull(19, java.sql.Types.VARCHAR);
6760 String parentPath =
"/";
6761 preparedStatement.setString(20, parentPath);
6762 preparedStatement.setLong(21, newObjId);
6763 preparedStatement.setString(22, null);
6764 preparedStatement.setString(23,
OsAccount.NO_OWNER_ID);
6765 preparedStatement.setNull(24, java.sql.Types.BIGINT);
6769 connection.executeUpdate(preparedStatement);
6771 return new LocalFilesDataSource(
this, newObjId, newObjId, deviceId, rootDirectoryName, dirType, metaType, dirFlag, metaFlags, timeZone, null, null, null,
FileKnown.
UNKNOWN, parentPath);
6773 }
catch (SQLException ex) {
6774 throw new TskCoreException(String.format(
"Error creating local files data source with device id %s and directory name %s", deviceId, rootDirectoryName), ex);
6776 closeStatement(statement);
6800 String timezone, String md5, String sha1, String sha256,
6803 return addImage(type, sectorSize, size, displayName, imagePaths, timezone, md5, sha1, sha256, deviceId, null, transaction);
6827 String timezone, String md5, String sha1, String sha256,
6828 String deviceId,
Host host,
6830 Statement statement = null;
6833 CaseDbConnection connection = transaction.getConnection();
6838 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_IMAGE_INFO);
6839 preparedStatement.clearParameters();
6840 preparedStatement.setLong(1, newObjId);
6841 preparedStatement.setShort(2, (
short) type.getValue());
6842 preparedStatement.setLong(3, sectorSize);
6843 preparedStatement.setString(4, timezone);
6845 long savedSize = size < 0 ? 0 : size;
6846 preparedStatement.setLong(5, savedSize);
6847 preparedStatement.setString(6, md5);
6848 preparedStatement.setString(7, sha1);
6849 preparedStatement.setString(8, sha256);
6850 preparedStatement.setString(9, displayName);
6851 connection.executeUpdate(preparedStatement);
6854 for (
int i = 0; i < imagePaths.size(); i++) {
6855 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_IMAGE_NAME);
6856 preparedStatement.clearParameters();
6857 preparedStatement.setLong(1, newObjId);
6858 preparedStatement.setString(2, imagePaths.get(i));
6859 preparedStatement.setLong(3, i);
6860 connection.executeUpdate(preparedStatement);
6864 String name = displayName;
6865 if (name == null || name.isEmpty()) {
6866 if (imagePaths.size() > 0) {
6867 String path = imagePaths.get(0);
6868 name = (
new java.io.File(path)).getName();
6876 if (name.isEmpty()) {
6884 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_DATA_SOURCE_INFO);
6885 statement = connection.createStatement();
6886 preparedStatement.setLong(1, newObjId);
6887 preparedStatement.setString(2, deviceId);
6888 preparedStatement.setString(3, timezone);
6889 preparedStatement.setLong(4,
new Date().getTime());
6890 preparedStatement.setLong(5, host.getHostId());
6891 connection.executeUpdate(preparedStatement);
6894 return new Image(
this, newObjId, type.getValue(), deviceId, sectorSize, name,
6895 imagePaths.toArray(
new String[imagePaths.size()]), timezone, md5, sha1, sha256, savedSize);
6896 }
catch (SQLException ex) {
6897 if (!imagePaths.isEmpty()) {
6898 throw new TskCoreException(String.format(
"Error adding image with path %s to database", imagePaths.get(0)), ex);
6900 throw new TskCoreException(String.format(
"Error adding image with display name %s to database", displayName), ex);
6903 closeStatement(statement);
6924 CaseDbConnection connection = transaction.getConnection();
6925 long newObjId = addObject(parentObjId,
TskData.
ObjectType.
VS.getObjectType(), connection);
6929 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_VS_INFO);
6930 preparedStatement.clearParameters();
6931 preparedStatement.setLong(1, newObjId);
6932 preparedStatement.setShort(2, (
short) type.getVsType());
6933 preparedStatement.setLong(3, imgOffset);
6934 preparedStatement.setLong(4, blockSize);
6935 connection.executeUpdate(preparedStatement);
6938 return new VolumeSystem(
this, newObjId,
"", type.getVsType(), imgOffset, blockSize);
6939 }
catch (SQLException ex) {
6940 throw new TskCoreException(String.format(
"Error creating volume system with parent ID %d and image offset %d",
6941 parentObjId, imgOffset), ex);
6960 public Volume addVolume(
long parentObjId,
long addr,
long start,
long length, String desc,
6964 CaseDbConnection connection = transaction.getConnection();
6969 PreparedStatement preparedStatement;
6971 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_VS_PART_POSTGRESQL);
6973 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_VS_PART_SQLITE);
6975 preparedStatement.clearParameters();
6976 preparedStatement.setLong(1, newObjId);
6977 preparedStatement.setLong(2, addr);
6978 preparedStatement.setLong(3, start);
6979 preparedStatement.setLong(4, length);
6980 preparedStatement.setString(5, desc);
6981 preparedStatement.setShort(6, (
short) flags);
6982 connection.executeUpdate(preparedStatement);
6985 return new Volume(
this, newObjId, addr, start, length, flags, desc);
6986 }
catch (SQLException ex) {
6987 throw new TskCoreException(String.format(
"Error creating volume with address %d and parent ID %d", addr, parentObjId), ex);
7005 CaseDbConnection connection = transaction.getConnection();
7010 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_POOL_INFO);
7011 preparedStatement.clearParameters();
7012 preparedStatement.setLong(1, newObjId);
7013 preparedStatement.setShort(2, type.getValue());
7014 connection.executeUpdate(preparedStatement);
7017 return new Pool(
this, newObjId, type.getName(), type.getValue());
7018 }
catch (SQLException ex) {
7019 throw new TskCoreException(String.format(
"Error creating pool with type %d and parent ID %d", type.getValue(), parentObjId), ex);
7042 long rootInum,
long firstInum,
long lastInum, String displayName,
7046 CaseDbConnection connection = transaction.getConnection();
7047 long newObjId = addObject(parentObjId,
TskData.
ObjectType.
FS.getObjectType(), connection);
7050 long dataSourceId = getDataSourceObjectId(connection, newObjId);
7054 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FS_INFO);
7055 preparedStatement.clearParameters();
7056 preparedStatement.setLong(1, newObjId);
7057 preparedStatement.setLong(2, dataSourceId);
7058 preparedStatement.setLong(3, imgOffset);
7059 preparedStatement.setInt(4, type.getValue());
7060 preparedStatement.setLong(5, blockSize);
7061 preparedStatement.setLong(6, blockCount);
7062 preparedStatement.setLong(7, rootInum);
7063 preparedStatement.setLong(8, firstInum);
7064 preparedStatement.setLong(9, lastInum);
7065 preparedStatement.setString(10, displayName);
7066 connection.executeUpdate(preparedStatement);
7069 return new FileSystem(
this, newObjId, displayName, imgOffset, type, blockSize, blockCount, rootInum,
7070 firstInum, lastInum);
7071 }
catch (SQLException ex) {
7072 throw new TskCoreException(String.format(
"Error creating file system with image offset %d and parent ID %d",
7073 imgOffset, parentObjId), ex);
7104 long metaAddr,
int metaSeq,
7107 long ctime,
long crtime,
long atime,
long mtime,
7108 boolean isFile,
Content parent)
throws TskCoreException {
7114 metaAddr, metaSeq, attrType, attrId, dirFlag, metaFlags, size,
7115 ctime, crtime, atime, mtime, null, null, null, isFile, parent,
7117 Collections.emptyList(), transaction);
7121 return fileSystemFile;
7123 if (null != transaction) {
7126 }
catch (TskCoreException ex2) {
7127 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
7172 long metaAddr,
int metaSeq,
7175 long ctime,
long crtime,
long atime,
long mtime,
7176 String md5Hash, String sha256Hash, String mimeType,
7177 boolean isFile,
Content parent, String ownerUid,
7178 OsAccount osAccount, List<Attribute> fileAttributes,
7185 dirFlag, metaFlags, size,
7186 ctime, crtime, atime, mtime,
7187 md5Hash, sha256Hash, null,
7189 isFile, parent, ownerUid,
7190 osAccount, fileAttributes,
7235 long metaAddr,
int metaSeq,
7238 long ctime,
long crtime,
long atime,
long mtime,
7239 String md5Hash, String sha256Hash, String sha1Hash,
7240 String mimeType,
boolean isFile,
7241 Content parent, String ownerUid,
7242 OsAccount osAccount, List<Attribute> fileAttributes,
7248 dirFlag, metaFlags, size,
7249 ctime, crtime, atime, mtime,
7250 md5Hash, sha256Hash, sha1Hash,
7252 isFile, parent, ownerUid,
7299 long metaAddr,
int metaSeq,
7302 long ctime,
long crtime,
long atime,
long mtime,
7303 String md5Hash, String sha256Hash, String sha1Hash,
7304 String mimeType,
boolean isFile,
7305 Content parent, String ownerUid,
7307 List<Attribute> fileAttributes,
7311 Statement queryStatement = null;
7312 String parentPath =
"/";
7314 CaseDbConnection connection = transaction.getConnection();
7321 AbstractFile parentFile = (AbstractFile) parent;
7322 if (isRootDirectory(parentFile, transaction)) {
7325 parentPath = parentFile.
getParentPath() + parent.getName() +
"/";
7331 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE_SYSTEM_FILE);
7332 statement.clearParameters();
7333 statement.setLong(1, objectId);
7334 statement.setLong(2, fsObjId);
7335 statement.setLong(3, dataSourceObjId);
7336 statement.setShort(4, (
short) attrType.getValue());
7337 statement.setInt(5, attrId);
7338 statement.setString(6, fileName);
7339 statement.setLong(7, metaAddr);
7340 statement.setInt(8, metaSeq);
7342 statement.setShort(10, (
short) 1);
7344 statement.setShort(11, dirType.
getValue());
7346 statement.setShort(12, metaType.
getValue());
7347 statement.setShort(13, dirFlag.getValue());
7348 statement.setShort(14, metaFlags);
7349 statement.setLong(15, size < 0 ? 0 : size);
7350 statement.setLong(16, ctime);
7351 statement.setLong(17, crtime);
7352 statement.setLong(18, atime);
7353 statement.setLong(19, mtime);
7354 statement.setString(20, md5Hash);
7355 statement.setString(21, sha256Hash);
7356 statement.setString(22, sha1Hash);
7357 statement.setString(23, mimeType);
7358 statement.setString(24, parentPath);
7359 final String extension = extractExtension(fileName);
7360 statement.setString(25, extension);
7361 statement.setString(26, ownerUid);
7362 if (null != osAccount) {
7363 statement.setLong(27, osAccount.getId());
7365 statement.setNull(27, java.sql.Types.BIGINT);
7367 statement.setLong(28, collected.getType());
7369 connection.executeUpdate(statement);
7371 Long osAccountId = (osAccount != null) ? osAccount.getId() : null;
7372 DerivedFile derivedFile =
new DerivedFile(
this, objectId, dataSourceObjId, fsObjId, fileName, dirType, metaType, dirFlag, metaFlags,
7373 size, ctime, crtime, atime, mtime, md5Hash, sha256Hash, sha1Hash, null, parentPath, null, parent.getId(), mimeType, null, extension, ownerUid, osAccountId);
7375 if (!timelineEventsDisabled.get()) {
7376 timelineManager.addEventsForNewFile(derivedFile, connection);
7379 for (
Attribute fileAttribute : fileAttributes) {
7380 fileAttribute.setAttributeParentId(objectId);
7381 fileAttribute.setCaseDatabase(
this);
7382 addFileAttribute(fileAttribute, connection);
7385 if (osAccount != null) {
7390 attrType, attrId, fileName, metaAddr, metaSeq,
7391 dirType, metaType, dirFlag, metaFlags,
7392 size, ctime, crtime, atime, mtime,
7393 (
short) 0, 0, 0, md5Hash, sha256Hash, sha1Hash, null, parentPath, mimeType,
7394 extension, ownerUid, osAccountId, collected, fileAttributes);
7396 }
catch (SQLException ex) {
7397 throw new TskCoreException(String.format(
"Failed to INSERT file system file %s (%s) with parent id %d in tsk_files table", fileName, parentPath, parent.getId()), ex);
7399 closeStatement(queryStatement);
7412 CaseDbConnection connection = null;
7414 ResultSet rs = null;
7417 connection = connections.getConnection();
7418 s = connection.createStatement();
7419 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE"
7421 +
" AND obj_id = data_source_obj_id"
7422 +
" ORDER BY dir_type, LOWER(name)");
7423 List<VirtualDirectory> virtDirRootIds =
new ArrayList<VirtualDirectory>();
7425 virtDirRootIds.add(virtualDirectory(rs, connection));
7427 return virtDirRootIds;
7428 }
catch (SQLException ex) {
7429 throw new TskCoreException(
"Error getting local files virtual folder id", ex);
7433 closeConnection(connection);
7451 assert (null != fileRanges);
7452 if (null == fileRanges) {
7453 throw new TskCoreException(
"TskFileRange object is null");
7456 assert (null != parent);
7457 if (null == parent) {
7458 throw new TskCoreException(
"Conent is null");
7463 parentPath = ((AbstractFile) parent).getParentPath() + parent.getName() +
'/';
7469 Statement statement = null;
7470 ResultSet resultSet = null;
7474 CaseDbConnection connection = transaction.getConnection();
7477 Long fileSystemObjectId;
7478 if (0 != parent.getId()) {
7479 fileSystemObjectId = this.getFileSystemId(parent.getId(), connection);
7480 if (fileSystemObjectId == -1) {
7481 fileSystemObjectId = null;
7484 fileSystemObjectId = null;
7487 List<LayoutFile> fileRangeLayoutFiles =
new ArrayList<>();
7495 long end_byte_in_parent = fileRange.getByteStart() + fileRange.getByteLen() - 1;
7505 PreparedStatement prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
7506 prepStmt.clearParameters();
7507 prepStmt.setLong(1, fileRangeId);
7508 if (fileSystemObjectId != null) {
7509 prepStmt.setLong(2, fileSystemObjectId);
7511 prepStmt.setNull(2, java.sql.Types.BIGINT);
7513 prepStmt.setString(3,
"Unalloc_" + parent.getId() +
"_" + fileRange.getByteStart() +
"_" + end_byte_in_parent);
7515 prepStmt.setNull(5, java.sql.Types.BIGINT);
7520 prepStmt.setLong(10, fileRange.getByteLen());
7521 prepStmt.setNull(11, java.sql.Types.BIGINT);
7522 prepStmt.setNull(12, java.sql.Types.BIGINT);
7523 prepStmt.setNull(13, java.sql.Types.BIGINT);
7524 prepStmt.setNull(14, java.sql.Types.BIGINT);
7525 prepStmt.setNull(15, java.sql.Types.VARCHAR);
7526 prepStmt.setNull(16, java.sql.Types.VARCHAR);
7527 prepStmt.setNull(17, java.sql.Types.VARCHAR);
7530 prepStmt.setNull(19, java.sql.Types.VARCHAR);
7531 prepStmt.setString(20, parentPath);
7532 prepStmt.setLong(21, parent.getId());
7535 prepStmt.setString(22, null);
7537 prepStmt.setString(23,
OsAccount.NO_OWNER_ID);
7538 prepStmt.setNull(24, java.sql.Types.BIGINT);
7541 connection.executeUpdate(prepStmt);
7548 prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LAYOUT_FILE);
7549 prepStmt.clearParameters();
7550 prepStmt.setLong(1, fileRangeId);
7551 prepStmt.setLong(2, fileRange.getByteStart());
7552 prepStmt.setLong(3, fileRange.getByteLen());
7553 prepStmt.setLong(4, fileRange.getSequence());
7554 connection.executeUpdate(prepStmt);
7559 fileRangeLayoutFiles.add(
new LayoutFile(
this,
7563 Long.toString(fileRange.getSequence()),
7569 fileRange.getByteLen(),
7573 parent.getUniquePath(),
7581 return fileRangeLayoutFiles;
7583 }
catch (SQLException ex) {
7584 throw new TskCoreException(
"Failed to add layout files to case database", ex);
7586 closeResultSet(resultSet);
7587 closeStatement(statement);
7589 if (null != transaction) {
7592 }
catch (TskCoreException ex2) {
7593 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
7605 private class CarvedFileDirInfo {
7608 AtomicInteger count;
7611 this.currentFolder = currentFolder;
7612 count =
new AtomicInteger(0);
7615 CarvedFileDirInfo(VirtualDirectory currentFolder,
int count) {
7616 this.currentFolder = currentFolder;
7617 this.count =
new AtomicInteger(count);
7627 return count.get() >= MAX_CARVED_FILES_PER_FOLDER;
7633 void incrementFileCounter() {
7634 count.incrementAndGet();
7647 private CarvedFileDirInfo getMostRecentCarvedDirInfo(VirtualDirectory carvedFilesBaseDir)
throws TskCoreException {
7648 VirtualDirectory mostRecentDir = null;
7649 for (Content child : carvedFilesBaseDir.getChildren()) {
7650 if (isValidCarvedFileSubfolder(child)) {
7651 if (mostRecentDir == null
7652 || (mostRecentDir.getId() < child.getId())) {
7653 mostRecentDir = (VirtualDirectory) child;
7658 if (mostRecentDir != null) {
7659 return new CarvedFileDirInfo(mostRecentDir, mostRecentDir.getChildrenCount());
7672 private boolean isValidCarvedFileSubfolder(Content subfolder) {
7673 if (!(subfolder instanceof VirtualDirectory)) {
7676 return subfolder.getName().matches(
"^[0-9]+$");
7692 private CarvedFileDirInfo createCarvedFilesSubfolder(Content carvedFilesBaseDir, CarvedFileDirInfo currentSubfolderInfo)
throws TskCoreException {
7694 if (currentSubfolderInfo != null) {
7696 int currentIndex = Integer.parseInt(currentSubfolderInfo.currentFolder.getName());
7697 nextIndex = currentIndex + 1;
7698 }
catch (NumberFormatException ex) {
7699 throw new TskCoreException(
"Unexpected name format for carved files subdirectory with ID: " + currentSubfolderInfo.currentFolder.getId() +
" (" + currentSubfolderInfo.currentFolder.getName() +
")", ex);
7703 VirtualDirectory carvedFilesSubdir =
addVirtualDirectory(carvedFilesBaseDir.getId(), Integer.toString(nextIndex));
7704 return new CarvedFileDirInfo(carvedFilesSubdir);
7719 assert (null != carvingResult);
7720 if (null == carvingResult) {
7721 throw new TskCoreException(
"Carving is null");
7723 assert (null != carvingResult.getParent());
7724 if (null == carvingResult.getParent()) {
7725 throw new TskCoreException(
"Carving result has null parent");
7727 assert (null != carvingResult.getCarvedFiles());
7728 if (null == carvingResult.getCarvedFiles()) {
7729 throw new TskCoreException(
"Carving result has null carved files");
7732 Statement statement = null;
7733 ResultSet resultSet = null;
7743 while (null != root) {
7757 CarvedFileDirInfo carvedFilesDirInfo = null;
7758 synchronized (carvedFileDirsLock) {
7760 carvedFilesDirInfo = rootIdsToCarvedFileDirs.get(root.
getId());
7761 if (carvedFilesDirInfo != null) {
7762 carvedFilesDirInfo.incrementFileCounter();
7765 if (carvedFilesDirInfo.isFull()) {
7766 carvedFilesDirInfo = createCarvedFilesSubfolder(carvedFilesDirInfo.currentFolder.getParent(), carvedFilesDirInfo);
7770 if (null == carvedFilesDirInfo) {
7771 List<Content> rootChildren;
7773 rootChildren = ((FileSystem) root).getRootDirectory().getChildren();
7777 for (
Content child : rootChildren) {
7778 if (child instanceof VirtualDirectory && child.getName().equals(VirtualDirectory.NAME_CARVED)) {
7780 VirtualDirectory baseDir = (VirtualDirectory) child;
7783 carvedFilesDirInfo = getMostRecentCarvedDirInfo(baseDir);
7786 if (carvedFilesDirInfo == null) {
7787 carvedFilesDirInfo = createCarvedFilesSubfolder(baseDir, null);
7791 if (carvedFilesDirInfo.isFull()) {
7792 carvedFilesDirInfo = createCarvedFilesSubfolder(baseDir, carvedFilesDirInfo);
7795 rootIdsToCarvedFileDirs.put(root.
getId(), carvedFilesDirInfo);
7799 if (carvedFilesDirInfo == null) {
7803 long parId = root.
getId();
7805 if (root instanceof FileSystem) {
7806 Content rootDir = ((FileSystem) root).getRootDirectory();
7807 parId = rootDir.
getId();
7809 VirtualDirectory carvedFilesBaseDir =
addVirtualDirectory(parId, VirtualDirectory.NAME_CARVED);
7810 carvedFilesDirInfo = createCarvedFilesSubfolder(carvedFilesBaseDir, null);
7811 rootIdsToCarvedFileDirs.put(root.
getId(), carvedFilesDirInfo);
7820 VirtualDirectory carvedFilesBaseDir = (VirtualDirectory) carvedFilesDirInfo.currentFolder.getParent();
7822 CaseDbConnection connection = transaction.getConnection();
7823 String parentPath = getFileParentPath(carvedFilesDirInfo.currentFolder.getId(), connection) + carvedFilesDirInfo.currentFolder.getName() +
"/";
7824 List<LayoutFile> carvedFiles =
new ArrayList<>();
7830 VirtualDirectory carvedFilesDir = carvedFilesDirInfo.currentFolder;
7831 if (carvedFilesDirInfo.isFull()) {
7837 synchronized (carvedFileDirsLock) {
7839 carvedFilesDirInfo = rootIdsToCarvedFileDirs.get(root.
getId());
7840 if (carvedFilesDirInfo.isFull()) {
7841 carvedFilesDirInfo = createCarvedFilesSubfolder(carvedFilesBaseDir, carvedFilesDirInfo);
7842 rootIdsToCarvedFileDirs.put(root.
getId(), carvedFilesDirInfo);
7843 carvedFilesDir = carvedFilesDirInfo.currentFolder;
7849 connection = transaction.getConnection();
7850 parentPath = getFileParentPath(carvedFilesDir.
getId(), connection) + carvedFilesDir.
getName() +
"/";
7853 carvedFilesDirInfo.incrementFileCounter();
7871 PreparedStatement prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
7872 prepStmt.clearParameters();
7873 prepStmt.setLong(1, carvedFileId);
7874 Long fileSystemObjectId;
7876 prepStmt.setLong(2, root.
getId());
7877 fileSystemObjectId = root.
getId();
7879 prepStmt.setNull(2, java.sql.Types.BIGINT);
7880 fileSystemObjectId = null;
7882 prepStmt.setString(3, carvedFile.getName());
7884 prepStmt.setShort(5, (
short) 1);
7889 prepStmt.setLong(10, carvedFile.getSizeInBytes());
7890 prepStmt.setNull(11, java.sql.Types.BIGINT);
7891 prepStmt.setNull(12, java.sql.Types.BIGINT);
7892 prepStmt.setNull(13, java.sql.Types.BIGINT);
7893 prepStmt.setNull(14, java.sql.Types.BIGINT);
7894 prepStmt.setNull(15, java.sql.Types.VARCHAR);
7895 prepStmt.setNull(16, java.sql.Types.VARCHAR);
7896 prepStmt.setNull(17, java.sql.Types.VARCHAR);
7899 prepStmt.setNull(19, java.sql.Types.VARCHAR);
7900 prepStmt.setString(20, parentPath);
7902 prepStmt.setString(22, extractExtension(carvedFile.getName()));
7904 prepStmt.setString(23,
OsAccount.NO_OWNER_ID);
7905 prepStmt.setNull(24, java.sql.Types.BIGINT);
7908 connection.executeUpdate(prepStmt);
7915 prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LAYOUT_FILE);
7916 for (
TskFileRange tskFileRange : carvedFile.getLayoutInParent()) {
7917 prepStmt.clearParameters();
7918 prepStmt.setLong(1, carvedFileId);
7919 prepStmt.setLong(2, tskFileRange.getByteStart());
7920 prepStmt.setLong(3, tskFileRange.getByteLen());
7921 prepStmt.setLong(4, tskFileRange.getSequence());
7922 connection.executeUpdate(prepStmt);
7932 carvedFile.getName(),
7938 carvedFile.getSizeInBytes(),
7952 }
catch (SQLException ex) {
7953 throw new TskCoreException(
"Failed to add carved files to case database", ex);
7955 closeResultSet(resultSet);
7956 closeStatement(statement);
7958 if (null != transaction) {
7961 }
catch (TskCoreException ex2) {
7962 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
7999 long size,
long ctime,
long crtime,
long atime,
long mtime,
8000 boolean isFile,
Content parentObj,
8001 String rederiveDetails, String toolName, String toolVersion,
8006 size, ctime, crtime, atime, mtime,
8008 rederiveDetails, toolName, toolVersion,
8009 otherDetails, encodingType, transaction);
8012 }
catch (TskCoreException ex) {
8019 long size,
long ctime,
long crtime,
long atime,
long mtime,
8020 boolean isFile,
Content parentObj,
8021 String rederiveDetails, String toolName, String toolVersion,
8024 localPath = localPath.replaceAll(
"^[/\\\\]+",
"");
8028 CaseDbConnection connection = transaction.getConnection();
8030 final long parentId = parentObj.getId();
8031 String parentPath =
"";
8033 parentPath = parentObj.getUniquePath() +
'/' + parentObj.getName() +
'/';
8035 parentPath = ((AbstractFile) parentObj).getParentPath() + parentObj.getName() +
'/';
8047 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
8048 statement.clearParameters();
8049 statement.setLong(1, newObjId);
8052 Long fsObjId = this.getFileSystemId(parentId, connection);
8053 if (fsObjId != -1) {
8054 statement.setLong(2, fsObjId);
8057 statement.setNull(2, java.sql.Types.BIGINT);
8059 statement.setString(3, fileName);
8063 statement.setShort(5, (
short) 1);
8067 statement.setShort(6, dirType.
getValue());
8069 statement.setShort(7, metaType.
getValue());
8073 statement.setShort(8, dirFlag.
getValue());
8076 statement.setShort(9, metaFlags);
8080 long savedSize = size < 0 ? 0 : size;
8081 statement.setLong(10, savedSize);
8085 statement.setLong(11, ctime);
8086 statement.setLong(12, crtime);
8087 statement.setLong(13, atime);
8088 statement.setLong(14, mtime);
8090 statement.setNull(15, java.sql.Types.VARCHAR);
8091 statement.setNull(16, java.sql.Types.VARCHAR);
8092 statement.setNull(17, java.sql.Types.VARCHAR);
8095 statement.setNull(19, java.sql.Types.VARCHAR);
8098 statement.setString(20, parentPath);
8101 long dataSourceObjId = getDataSourceObjectId(connection, parentObj);
8102 statement.setLong(21, dataSourceObjId);
8103 final String extension = extractExtension(fileName);
8105 statement.setString(22, extension);
8107 statement.setString(23,
OsAccount.NO_OWNER_ID);
8108 statement.setNull(24, java.sql.Types.BIGINT);
8111 connection.executeUpdate(statement);
8114 addFilePath(connection, newObjId, localPath, encodingType);
8116 DerivedFile derivedFile =
new DerivedFile(
this, newObjId, dataSourceObjId, fsObjId, fileName, dirType, metaType, dirFlag, metaFlags,
8117 savedSize, ctime, crtime, atime, mtime, null, null, null, null, parentPath, localPath, parentId, null, encodingType, extension,
OsAccount.NO_OWNER_ID,
OsAccount.NO_ACCOUNT);
8119 if (!timelineEventsDisabled.get()) {
8120 timelineManager.addEventsForNewFile(derivedFile, connection);
8125 }
catch (SQLException ex) {
8126 throw new TskCoreException(
"Failed to add derived file to case database", ex);
8161 long size,
long ctime,
long crtime,
long atime,
long mtime,
8162 boolean isFile, String mimeType,
8163 String rederiveDetails, String toolName, String toolVersion,
8172 size, ctime, crtime, atime, mtime,
8174 rederiveDetails, toolName, toolVersion,
8175 otherDetails, encodingType, parentObj, trans);
8178 }
catch (TskCoreException ex) {
8179 if (trans != null) {
8187 long size,
long ctime,
long crtime,
long atime,
long mtime,
8188 boolean isFile, String mimeType,
8189 String rederiveDetails, String toolName, String toolVersion,
8194 localPath = localPath.replaceAll(
"^[/\\\\]+",
"");
8196 ResultSet rs = null;
8198 final long parentId = parentObj.
getId();
8199 String parentPath =
"";
8201 parentPath = parentObj.getUniquePath() +
'/' + parentObj.getName() +
'/';
8203 parentPath = ((AbstractFile) parentObj).getParentPath() + parentObj.getName() +
'/';
8207 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.UPDATE_DERIVED_FILE);
8208 statement.clearParameters();
8215 statement.setShort(2, dirType.
getValue());
8217 statement.setShort(3, metaType.
getValue());
8221 statement.setShort(4, dirFlag.
getValue());
8224 statement.setShort(5, metaFlags);
8228 long savedSize = size < 0 ? 0 : size;
8229 statement.setLong(6, savedSize);
8233 statement.setLong(7, ctime);
8234 statement.setLong(8, crtime);
8235 statement.setLong(9, atime);
8236 statement.setLong(10, mtime);
8237 statement.setString(11, mimeType);
8238 statement.setString(12, String.valueOf(derivedFile.
getId()));
8239 trans.getConnection().executeUpdate(statement);
8242 updateFilePath(trans.getConnection(), derivedFile.
getId(), localPath, encodingType);
8244 long dataSourceObjId = getDataSourceObjectId(trans.getConnection(), parentObj);
8246 final String extension = extractExtension(derivedFile.
getName());
8247 return new DerivedFile(
this, derivedFile.
getId(), dataSourceObjId, fileSystemObjId, derivedFile.
getName(), dirType, metaType, dirFlag, metaFlags,
8248 savedSize, ctime, crtime, atime, mtime, null, null, null, null, parentPath, localPath, parentId, null, encodingType, extension,
8250 }
catch (SQLException ex) {
8251 throw new TskCoreException(
"Failed to add derived file to case database", ex);
8277 long size,
long ctime,
long crtime,
long atime,
long mtime,
8283 LocalFile created =
addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime, isFile, encodingType, parent, localTrans);
8288 if (null != localTrans) {
8291 }
catch (TskCoreException ex2) {
8292 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
8323 long size,
long ctime,
long crtime,
long atime,
long mtime,
8328 size, ctime, crtime, atime, mtime,
8330 isFile, encodingType,
8331 parent, transaction);
8363 long size,
long ctime,
long crtime,
long atime,
long mtime,
8364 String md5, String sha256,
FileKnown known, String mimeType,
8368 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime,
8369 md5, sha256, known, mimeType, isFile, encodingType,
8405 long size,
long ctime,
long crtime,
long atime,
long mtime,
8406 String md5, String sha256,
FileKnown known, String mimeType,
8411 size, ctime, crtime, atime, mtime,
8412 md5, sha256, null, known, mimeType,
8413 isFile, encodingType, osAccountId, ownerAccount,
8414 parent, transaction);
8451 long size,
long ctime,
long crtime,
long atime,
long mtime,
8452 String md5, String sha256, String sha1Hash,
FileKnown known, String mimeType,
8455 CaseDbConnection connection = transaction.getConnection();
8456 Statement queryStatement = null;
8468 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
8469 statement.clearParameters();
8470 statement.setLong(1, objectId);
8471 statement.setNull(2, java.sql.Types.BIGINT);
8472 statement.setString(3, fileName);
8474 statement.setShort(5, (
short) 1);
8476 statement.setShort(6, dirType.
getValue());
8478 statement.setShort(7, metaType.
getValue());
8480 statement.setShort(8, dirFlag.
getValue());
8482 statement.setShort(9, metaFlags);
8484 long savedSize = size < 0 ? 0 : size;
8485 statement.setLong(10, savedSize);
8486 statement.setLong(11, ctime);
8487 statement.setLong(12, crtime);
8488 statement.setLong(13, atime);
8489 statement.setLong(14, mtime);
8490 statement.setString(15, md5);
8491 statement.setString(16, sha256);
8492 statement.setString(17, sha1Hash);
8494 if (known != null) {
8495 statement.setByte(18, known.getFileKnownValue());
8499 statement.setString(19, mimeType);
8501 long dataSourceObjId;
8504 AbstractFile parentFile = (AbstractFile) parent;
8505 if (isRootDirectory(parentFile, transaction)) {
8508 parentPath = parentFile.
getParentPath() + parent.getName() +
"/";
8513 dataSourceObjId = getDataSourceObjectId(connection, parent);
8515 statement.setString(20, parentPath);
8516 statement.setLong(21, dataSourceObjId);
8517 final String extension = extractExtension(fileName);
8518 statement.setString(22, extension);
8520 if (ownerAccount != null) {
8521 statement.setString(23, ownerAccount);
8523 statement.setNull(23, java.sql.Types.VARCHAR);
8526 if (osAccountId != null) {
8527 statement.setLong(24, osAccountId);
8529 statement.setNull(24, java.sql.Types.BIGINT);
8534 connection.executeUpdate(statement);
8535 addFilePath(connection, objectId, localPath, encodingType);
8545 ctime, crtime, atime, mtime,
8546 mimeType, md5, sha256, sha1Hash, known,
8547 parent.getId(), parentPath,
8550 encodingType, extension,
8551 ownerAccount, osAccountId);
8552 if (!timelineEventsDisabled.get()) {
8557 }
catch (SQLException ex) {
8558 throw new TskCoreException(String.format(
"Failed to INSERT local file %s (%s) with parent id %d in tsk_files table", fileName, localPath, parent.getId()), ex);
8560 closeStatement(queryStatement);
8569 private class RootDirectoryKey {
8571 private long dataSourceId;
8572 private Long fileSystemId;
8574 RootDirectoryKey(
long dataSourceId, Long fileSystemId) {
8575 this.dataSourceId = dataSourceId;
8576 this.fileSystemId = fileSystemId;
8580 public int hashCode() {
8582 hash = 41 * hash + Objects.hashCode(dataSourceId);
8583 hash = 41 * hash + Objects.hashCode(fileSystemId);
8588 public boolean equals(Object obj) {
8595 if (getClass() != obj.getClass()) {
8599 RootDirectoryKey otherKey = (RootDirectoryKey) obj;
8600 if (dataSourceId != otherKey.dataSourceId) {
8604 if (fileSystemId != null) {
8605 return fileSystemId.equals(otherKey.fileSystemId);
8607 return (otherKey.fileSystemId == null);
8623 private boolean isRootDirectory(AbstractFile file, CaseDbTransaction transaction)
throws TskCoreException {
8628 Long fsObjId = null;
8629 if (file instanceof FsContent) {
8630 fsObjId = ((FsContent) file).getFileSystemId();
8633 synchronized (rootDirectoryMapLock) {
8634 if (rootDirectoryMap.containsKey(key)) {
8635 return rootDirectoryMap.get(key).equals(file.
getId());
8642 Boolean isRoot = isRootDirectoryCache.getIfPresent(file.
getId());
8643 if (isRoot != null) {
8647 CaseDbConnection connection = transaction.getConnection();
8648 Statement statement = null;
8649 ResultSet resultSet = null;
8652 String query = String.format(
"SELECT ParentRow.type AS parent_type, ParentRow.obj_id AS parent_object_id "
8653 +
"FROM tsk_objects ParentRow JOIN tsk_objects ChildRow ON ChildRow.par_obj_id = ParentRow.obj_id "
8654 +
"WHERE ChildRow.obj_id = %s;", file.
getId());
8656 statement = connection.createStatement();
8657 resultSet = statement.executeQuery(query);
8658 if (resultSet.next()) {
8659 long parentId = resultSet.getLong(
"parent_object_id");
8660 if (parentId == 0) {
8663 int type = resultSet.getInt(
"parent_type");
8664 boolean result = type == TskData.ObjectType.IMG.getObjectType()
8665 || type == TskData.ObjectType.VS.getObjectType()
8666 || type == TskData.ObjectType.VOL.getObjectType()
8667 || type == TskData.ObjectType.FS.getObjectType();
8668 if (result ==
true) {
8669 synchronized (rootDirectoryMapLock) {
8671 rootDirectoryMap.put(key, file.
getId());
8674 isRootDirectoryCache.put(file.
getId(), result);
8679 synchronized (rootDirectoryMapLock) {
8680 rootDirectoryMap.put(key, file.
getId());
8682 isRootDirectoryCache.put(file.
getId(),
true);
8687 }
catch (SQLException ex) {
8688 throw new TskCoreException(String.format(
"Failed to lookup parent of file (%s) with id %d", file.
getName(), file.
getId()), ex);
8690 closeResultSet(resultSet);
8691 closeStatement(statement);
8717 long ctime,
long crtime,
long atime,
long mtime,
8718 List<TskFileRange> fileRanges,
8719 Content parent)
throws TskCoreException {
8721 if (null == parent) {
8722 throw new TskCoreException(
"Parent can not be null");
8727 parentPath = ((AbstractFile) parent).getParentPath() + parent.getName() +
'/';
8733 Statement statement = null;
8734 ResultSet resultSet = null;
8737 CaseDbConnection connection = transaction.getConnection();
8753 PreparedStatement prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
8754 prepStmt.clearParameters();
8755 prepStmt.setLong(1, newFileId);
8758 Long fileSystemObjectId;
8759 if (0 != parent.getId()) {
8760 fileSystemObjectId = this.getFileSystemId(parent.getId(), connection);
8761 if (fileSystemObjectId != -1) {
8762 prepStmt.setLong(2, fileSystemObjectId);
8764 prepStmt.setNull(2, java.sql.Types.BIGINT);
8765 fileSystemObjectId = null;
8768 prepStmt.setNull(2, java.sql.Types.BIGINT);
8769 fileSystemObjectId = null;
8771 prepStmt.setString(3, fileName);
8773 prepStmt.setShort(5, (
short) 0);
8776 prepStmt.setShort(8, dirFlag.getValue());
8777 prepStmt.setShort(9, metaFlag.getValue());
8779 long savedSize = size < 0 ? 0 : size;
8780 prepStmt.setLong(10, savedSize);
8781 prepStmt.setLong(11, ctime);
8782 prepStmt.setLong(12, crtime);
8783 prepStmt.setLong(13, atime);
8784 prepStmt.setLong(14, mtime);
8785 prepStmt.setNull(15, java.sql.Types.VARCHAR);
8786 prepStmt.setNull(16, java.sql.Types.VARCHAR);
8787 prepStmt.setNull(17, java.sql.Types.VARCHAR);
8790 prepStmt.setNull(19, java.sql.Types.VARCHAR);
8791 prepStmt.setString(20, parentPath);
8792 prepStmt.setLong(21, parent.getDataSource().getId());
8794 prepStmt.setString(22, extractExtension(fileName));
8796 prepStmt.setString(23,
OsAccount.NO_OWNER_ID);
8797 prepStmt.setNull(24, java.sql.Types.BIGINT);
8800 connection.executeUpdate(prepStmt);
8807 prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LAYOUT_FILE);
8809 prepStmt.clearParameters();
8810 prepStmt.setLong(1, newFileId);
8811 prepStmt.setLong(2, tskFileRange.getByteStart());
8812 prepStmt.setLong(3, tskFileRange.getByteLen());
8813 prepStmt.setLong(4, tskFileRange.getSequence());
8814 connection.executeUpdate(prepStmt);
8822 parent.getDataSource().getId(),
8829 metaFlag.getValue(),
8831 ctime, crtime, atime, mtime,
8843 }
catch (SQLException ex) {
8844 throw new TskCoreException(
"Failed to add layout file " + fileName +
" to case database", ex);
8846 closeResultSet(resultSet);
8847 closeStatement(statement);
8849 if (null != transaction) {
8852 }
catch (TskCoreException ex2) {
8853 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
8868 private long getDataSourceObjectId(CaseDbConnection connection,
Content content)
throws TskCoreException {
8869 if (content == null) {
8870 throw new TskCoreException(
"Null Content parameter given");
8872 if (content instanceof AbstractFile) {
8873 return ((AbstractFile) content).getDataSourceObjectId();
8875 return getDataSourceObjectId(connection, content.getId());
8891 private long getDataSourceObjectId(CaseDbConnection connection,
long objectId)
throws TskCoreException {
8893 Statement statement = null;
8894 ResultSet resultSet = null;
8896 statement = connection.createStatement();
8897 long dataSourceObjId;
8898 long ancestorId = objectId;
8900 dataSourceObjId = ancestorId;
8901 String query = String.format(
"SELECT par_obj_id FROM tsk_objects WHERE obj_id = %s;", ancestorId);
8902 resultSet = statement.executeQuery(query);
8903 if (resultSet.next()) {
8904 ancestorId = resultSet.getLong(
"par_obj_id");
8906 throw new TskCoreException(String.format(
"tsk_objects table is corrupt, SQL query returned no result: %s", query));
8910 }
while (0 != ancestorId);
8911 return dataSourceObjId;
8912 }
catch (SQLException ex) {
8913 throw new TskCoreException(String.format(
"Error finding root data source for object (obj_id = %d)", objectId), ex);
8915 closeResultSet(resultSet);
8916 closeStatement(statement);
8932 private void addFilePath(CaseDbConnection connection,
long objId, String path, TskData.EncodingType type) throws SQLException {
8933 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LOCAL_PATH);
8934 statement.clearParameters();
8935 statement.setLong(1, objId);
8936 statement.setString(2, path);
8937 statement.setInt(3, type.getType());
8938 connection.executeUpdate(statement);
8952 private void updateFilePath(CaseDbConnection connection,
long objId, String path, TskData.EncodingType type) throws SQLException {
8953 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_LOCAL_PATH);
8954 statement.clearParameters();
8955 statement.setString(1, path);
8956 statement.setInt(2, type.getType());
8957 statement.setLong(3, objId);
8958 connection.executeUpdate(statement);
8974 public List<AbstractFile>
findFilesInFolder(String fileName, AbstractFile parentFile)
throws TskCoreException {
8976 if (!containsLikeWildcard(fileName)) {
8980 CaseDbConnection connection = null;
8981 ResultSet rs = null;
8982 long parentId = parentFile.getId();
8986 connection = connections.getConnection();
8988 PreparedStatement statement;
8989 if (ext.isEmpty()) {
8990 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_PARENT_AND_NAME);
8991 statement.clearParameters();
8992 statement.setLong(1, parentId);
8993 statement.setString(2, fileName);
8995 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_EXTENSION_AND_PARENT_AND_NAME);
8996 statement.clearParameters();
8997 statement.setString(1, ext);
8998 statement.setLong(2, parentId);
8999 statement.setString(3, fileName);
9002 rs = connection.executeQuery(statement);
9003 return resultSetToAbstractFiles(rs, connection);
9004 }
catch (SQLException ex) {
9005 throw new TskCoreException(
"Error getting AbstractFile children with name=" + fileName +
" for Content parent with ID=" + parentFile.getId(), ex);
9008 closeConnection(connection);
9025 CaseDbConnection connection = null;
9027 ResultSet rs = null;
9030 connection = connections.getConnection();
9031 s = connection.createStatement();
9032 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files WHERE " + sqlWhereClause);
9034 return rs.getLong(
"count");
9035 }
catch (SQLException e) {
9036 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.countFilesWhere().", e);
9040 closeConnection(connection);
9063 CaseDbConnection connection = null;
9065 ResultSet rs = null;
9068 connection = connections.getConnection();
9069 s = connection.createStatement();
9070 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE " + sqlWhereClause);
9071 return resultSetToAbstractFiles(rs, connection);
9072 }
catch (SQLException e) {
9073 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findAllFilesWhere(): " + sqlWhereClause, e);
9077 closeConnection(connection);
9101 String queryTemplate =
"SELECT tsk_files.* FROM tsk_files JOIN tsk_objects ON tsk_objects.obj_id = tsk_files.obj_id WHERE par_obj_id = %d AND %s";
9103 try (CaseDbConnection connection = connections.getConnection()) {
9104 String query = String.format(queryTemplate, parentId, sqlWhereClause);
9105 try (Statement s = connection.createStatement(); ResultSet rs = connection.executeQuery(s, query)) {
9106 return resultSetToAbstractFiles(rs, connection);
9107 }
catch (SQLException ex) {
9108 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findAllFilesInFolderWhere(): " + query, ex);
9128 CaseDbConnection connection = null;
9130 ResultSet rs = null;
9133 connection = connections.getConnection();
9134 s = connection.createStatement();
9135 rs = connection.executeQuery(s,
"SELECT obj_id FROM tsk_files WHERE " + sqlWhereClause);
9136 List<Long> ret =
new ArrayList<>();
9138 ret.add(rs.getLong(
"obj_id"));
9141 }
catch (SQLException e) {
9142 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findAllFileIdsWhere(): " + sqlWhereClause, e);
9146 closeConnection(connection);
9162 public List<AbstractFile>
openFiles(
Content dataSource, String filePath)
throws TskCoreException {
9166 String path = AbstractFile.createNonUniquePath(filePath).toLowerCase();
9169 int lastSlash = path.lastIndexOf(
'/');
9172 if (lastSlash == path.length()) {
9173 path = path.substring(0, lastSlash - 1);
9174 lastSlash = path.lastIndexOf(
'/');
9177 String parentPath = path.substring(0, lastSlash);
9178 String fileName = path.substring(lastSlash);
9180 return findFiles(dataSource, fileName, parentPath);
9194 CaseDbConnection connection = null;
9196 ResultSet rs = null;
9199 connection = connections.getConnection();
9200 s = connection.createStatement();
9201 rs = connection.executeQuery(s,
"SELECT * FROM tsk_file_layout WHERE obj_id = " +
id +
" ORDER BY sequence");
9202 List<TskFileRange> ranges =
new ArrayList<TskFileRange>();
9205 rs.getLong(
"byte_len"), rs.getLong(
"sequence"));
9209 }
catch (SQLException ex) {
9210 throw new TskCoreException(
"Error getting TskFileLayoutRanges by id, id = " +
id, ex);
9214 closeConnection(connection);
9230 CaseDbConnection connection = null;
9232 ResultSet rs = null;
9235 connection = connections.getConnection();
9236 s = connection.createStatement();
9237 rs = connection.executeQuery(s,
"SELECT tsk_image_info.type, tsk_image_info.ssize, tsk_image_info.tzone, tsk_image_info.size, tsk_image_info.md5, tsk_image_info.sha1, tsk_image_info.sha256, tsk_image_info.display_name, data_source_info.device_id, tsk_image_names.name "
9238 +
"FROM tsk_image_info "
9239 +
"INNER JOIN data_source_info ON tsk_image_info.obj_id = data_source_info.obj_id "
9240 +
"LEFT JOIN tsk_image_names ON tsk_image_names.obj_id = data_source_info.obj_id "
9241 +
"WHERE tsk_image_info.obj_id = " +
id);
9243 List<String> imagePaths =
new ArrayList<>();
9244 long type, ssize, size;
9245 String tzone, md5, sha1, sha256, name, device_id, imagePath;
9248 imagePath = rs.getString(
"name");
9249 if (imagePath != null) {
9250 imagePaths.add(imagePath);
9252 type = rs.getLong(
"type");
9253 ssize = rs.getLong(
"ssize");
9254 tzone = rs.getString(
"tzone");
9255 size = rs.getLong(
"size");
9256 md5 = rs.getString(
"md5");
9257 sha1 = rs.getString(
"sha1");
9258 sha256 = rs.getString(
"sha256");
9259 name = rs.getString(
"display_name");
9261 if (imagePaths.size() > 0) {
9262 String path = imagePaths.get(0);
9263 name = (
new java.io.File(path)).getName();
9268 device_id = rs.getString(
"device_id");
9270 throw new TskCoreException(
"No image found for id: " +
id);
9275 imagePath = rs.getString(
"name");
9276 if (imagePath != null) {
9277 imagePaths.add(imagePath);
9281 return new Image(
this,
id, type, device_id, ssize, name,
9282 imagePaths.toArray(
new String[imagePaths.size()]), tzone, md5, sha1, sha256, size);
9283 }
catch (SQLException ex) {
9284 throw new TskCoreException(
"Error getting Image by id, id = " +
id, ex);
9288 closeConnection(connection);
9305 CaseDbConnection connection = null;
9307 ResultSet rs = null;
9310 connection = connections.getConnection();
9311 s = connection.createStatement();
9312 rs = connection.executeQuery(s,
"SELECT * FROM tsk_vs_info "
9313 +
"where obj_id = " +
id);
9315 long type = rs.getLong(
"vs_type");
9316 long imgOffset = rs.getLong(
"img_offset");
9317 long blockSize = rs.getLong(
"block_size");
9319 vs.setParent(parent);
9322 throw new TskCoreException(
"No volume system found for id:" +
id);
9324 }
catch (SQLException ex) {
9325 throw new TskCoreException(
"Error getting Volume System by ID.", ex);
9329 closeConnection(connection);
9342 VolumeSystem getVolumeSystemById(
long id,
long parentId)
throws TskCoreException {
9343 VolumeSystem vs = getVolumeSystemById(
id, null);
9344 vs.setParentId(parentId);
9359 FileSystem getFileSystemById(
long id, Image parent)
throws TskCoreException {
9360 return getFileSystemByIdHelper(
id, parent);
9371 FileSystem getFileSystemById(
long id,
long parentId)
throws TskCoreException {
9373 FileSystem fs = getFileSystemById(
id, vol);
9374 fs.setParentId(parentId);
9389 FileSystem getFileSystemById(
long id, Volume parent)
throws TskCoreException {
9390 return getFileSystemByIdHelper(
id, parent);
9404 Pool getPoolById(
long id, Content parent)
throws TskCoreException {
9405 return getPoolByIdHelper(
id, parent);
9416 Pool getPoolById(
long id,
long parentId)
throws TskCoreException {
9417 Pool pool = getPoolById(
id, null);
9418 pool.setParentId(parentId);
9433 private Pool getPoolByIdHelper(
long id, Content parent)
throws TskCoreException {
9436 try (CaseDbConnection connection = connections.getConnection();
9437 Statement s = connection.createStatement();
9438 ResultSet rs = connection.executeQuery(s,
"SELECT * FROM tsk_pool_info "
9439 +
"where obj_id = " +
id);) {
9441 Pool pool =
new Pool(
this, rs.getLong(
"obj_id"), TskData.TSK_POOL_TYPE_ENUM.valueOf(rs.getLong(
"pool_type")).getName(), rs.getLong(
"pool_type"));
9442 pool.setParent(parent);
9446 throw new TskCoreException(
"No pool found for ID:" +
id);
9448 }
catch (SQLException ex) {
9449 throw new TskCoreException(
"Error getting Pool by ID", ex);
9466 private FileSystem getFileSystemByIdHelper(
long id, Content parent)
throws TskCoreException {
9470 synchronized (fileSystemIdMap) {
9471 if (fileSystemIdMap.containsKey(
id)) {
9472 return fileSystemIdMap.get(
id);
9475 CaseDbConnection connection = null;
9477 ResultSet rs = null;
9480 connection = connections.getConnection();
9481 s = connection.createStatement();
9482 rs = connection.executeQuery(s,
"SELECT * FROM tsk_fs_info "
9483 +
"where obj_id = " +
id);
9485 TskData.TSK_FS_TYPE_ENUM fsType = TskData.TSK_FS_TYPE_ENUM.valueOf(rs.getInt(
"fs_type"));
9486 FileSystem fs =
new FileSystem(
this, rs.getLong(
"obj_id"),
"", rs.getLong(
"img_offset"),
9487 fsType, rs.getLong(
"block_size"), rs.getLong(
"block_count"),
9488 rs.getLong(
"root_inum"), rs.getLong(
"first_inum"), rs.getLong(
"last_inum"));
9489 fs.setParent(parent);
9491 synchronized (fileSystemIdMap) {
9492 fileSystemIdMap.put(
id, fs);
9496 throw new TskCoreException(
"No file system found for id:" +
id);
9498 }
catch (SQLException ex) {
9499 throw new TskCoreException(
"Error getting File System by ID", ex);
9503 closeConnection(connection);
9519 Volume getVolumeById(
long id, VolumeSystem parent)
throws TskCoreException {
9520 CaseDbConnection connection = null;
9522 ResultSet rs = null;
9525 connection = connections.getConnection();
9526 s = connection.createStatement();
9527 rs = connection.executeQuery(s,
"SELECT * FROM tsk_vs_parts "
9528 +
"where obj_id = " +
id);
9539 description = rs.getString(
"desc");
9540 }
catch (Exception ex) {
9541 description = rs.getString(
"descr");
9543 Volume vol =
new Volume(
this, rs.getLong(
"obj_id"), rs.getLong(
"addr"),
9544 rs.getLong(
"start"), rs.getLong(
"length"), rs.getLong(
"flags"),
9546 vol.setParent(parent);
9549 throw new TskCoreException(
"No volume found for id:" +
id);
9551 }
catch (SQLException ex) {
9552 throw new TskCoreException(
"Error getting Volume by ID", ex);
9556 closeConnection(connection);
9569 Volume getVolumeById(
long id,
long parentId)
throws TskCoreException {
9570 Volume vol = getVolumeById(
id, null);
9571 vol.setParentId(parentId);
9586 Directory getDirectoryById(
long id, FileSystem parentFs)
throws TskCoreException {
9587 CaseDbConnection connection = null;
9589 ResultSet rs = null;
9592 connection = connections.getConnection();
9593 s = connection.createStatement();
9594 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files "
9595 +
"WHERE obj_id = " +
id);
9596 Directory temp = null;
9598 final short type = rs.getShort(
"type");
9599 if (type == TSK_DB_FILES_TYPE_ENUM.FS.getFileType()) {
9600 if (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()
9601 || rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue()) {
9602 temp = directory(rs, parentFs);
9604 }
else if (type == TSK_DB_FILES_TYPE_ENUM.VIRTUAL_DIR.getFileType()) {
9605 throw new TskCoreException(
"Expecting an FS-type directory, got virtual, id: " +
id);
9608 throw new TskCoreException(
"No Directory found for id:" +
id);
9611 }
catch (SQLException ex) {
9612 throw new TskCoreException(
"Error getting Directory by ID", ex);
9616 closeConnection(connection);
9631 List<FileSystem> fileSystems =
new ArrayList<>();
9632 String queryStr =
"SELECT * FROM tsk_fs_info WHERE data_source_obj_id = " + image.getId();
9634 CaseDbConnection connection = null;
9636 ResultSet rs = null;
9639 connection = connections.getConnection();
9640 s = connection.createStatement();
9641 rs = connection.executeQuery(s, queryStr);
9645 fsType, rs.getLong(
"block_size"), rs.getLong(
"block_count"),
9646 rs.getLong(
"root_inum"), rs.getLong(
"first_inum"), rs.getLong(
"last_inum"));
9648 fileSystems.add(fs);
9650 }
catch (SQLException ex) {
9651 throw new TskCoreException(
"Error looking up files systems. Query: " + queryStr, ex);
9655 closeConnection(connection);
9671 List<Content> getImageChildren(
Image img)
throws TskCoreException {
9672 Collection<ObjectInfo> childInfos = getChildrenInfo(img);
9673 List<Content> children =
new ArrayList<Content>();
9674 for (ObjectInfo info : childInfos) {
9675 if (null != info.type) {
9676 switch (info.type) {
9678 children.add(getVolumeSystemById(info.id, img));
9681 children.add(getPoolById(info.id, img));
9684 children.add(getFileSystemById(info.id, img));
9702 throw new TskCoreException(
"Image has child of invalid type: " + info.type);
9719 List<Long> getImageChildrenIds(Image img)
throws TskCoreException {
9720 Collection<ObjectInfo> childInfos = getChildrenInfo(img);
9721 List<Long> children =
new ArrayList<Long>();
9722 for (ObjectInfo info : childInfos) {
9723 if (info.type == ObjectType.VS
9724 || info.type == ObjectType.POOL
9725 || info.type == ObjectType.FS
9726 || info.type == ObjectType.ABSTRACTFILE
9727 || info.type == ObjectType.ARTIFACT) {
9728 children.add(info.id);
9729 }
else if (info.type == ObjectType.REPORT) {
9732 throw new TskCoreException(
"Image has child of invalid type: " + info.type);
9748 List<Content> getPoolChildren(Pool pool)
throws TskCoreException {
9749 Collection<ObjectInfo> childInfos = getChildrenInfo(pool);
9750 List<Content> children =
new ArrayList<Content>();
9751 for (ObjectInfo info : childInfos) {
9752 if (null != info.type) {
9753 switch (info.type) {
9755 children.add(getVolumeSystemById(info.id, pool));
9770 throw new TskCoreException(
"Pool has child of invalid type: " + info.type);
9787 List<Long> getPoolChildrenIds(Pool pool)
throws TskCoreException {
9788 Collection<ObjectInfo> childInfos = getChildrenInfo(pool);
9789 List<Long> children =
new ArrayList<Long>();
9790 for (ObjectInfo info : childInfos) {
9791 if (info.type == ObjectType.VS || info.type == ObjectType.ABSTRACTFILE || info.type == ObjectType.ARTIFACT) {
9792 children.add(info.id);
9794 throw new TskCoreException(
"Pool has child of invalid type: " + info.type);
9810 List<Content> getVolumeSystemChildren(VolumeSystem vs)
throws TskCoreException {
9811 Collection<ObjectInfo> childInfos = getChildrenInfo(vs);
9812 List<Content> children =
new ArrayList<Content>();
9813 for (ObjectInfo info : childInfos) {
9814 if (null != info.type) {
9815 switch (info.type) {
9817 children.add(getVolumeById(info.id, vs));
9832 throw new TskCoreException(
"VolumeSystem has child of invalid type: " + info.type);
9849 List<Long> getVolumeSystemChildrenIds(VolumeSystem vs)
throws TskCoreException {
9850 Collection<ObjectInfo> childInfos = getChildrenInfo(vs);
9851 List<Long> children =
new ArrayList<Long>();
9852 for (ObjectInfo info : childInfos) {
9853 if (info.type == ObjectType.VOL || info.type == ObjectType.ABSTRACTFILE || info.type == ObjectType.ARTIFACT) {
9854 children.add(info.id);
9856 throw new TskCoreException(
"VolumeSystem has child of invalid type: " + info.type);
9872 List<Content> getVolumeChildren(Volume vol)
throws TskCoreException {
9873 Collection<ObjectInfo> childInfos = getChildrenInfo(vol);
9874 List<Content> children =
new ArrayList<Content>();
9875 for (ObjectInfo info : childInfos) {
9876 if (null != info.type) {
9877 switch (info.type) {
9879 children.add(getPoolById(info.id, vol));
9882 children.add(getFileSystemById(info.id, vol));
9897 throw new TskCoreException(
"Volume has child of invalid type: " + info.type);
9914 List<Long> getVolumeChildrenIds(Volume vol)
throws TskCoreException {
9915 final Collection<ObjectInfo> childInfos = getChildrenInfo(vol);
9916 final List<Long> children =
new ArrayList<Long>();
9917 for (ObjectInfo info : childInfos) {
9918 if (info.type == ObjectType.FS || info.type == ObjectType.ABSTRACTFILE || info.type == ObjectType.ARTIFACT) {
9919 children.add(info.id);
9921 throw new TskCoreException(
"Volume has child of invalid type: " + info.type);
9940 public Image addImageInfo(
long deviceObjId, List<String> imageFilePaths, String timeZone)
throws TskCoreException {
9941 return addImageInfo(deviceObjId, imageFilePaths, timeZone, null);
9958 public Image addImageInfo(
long deviceObjId, List<String> imageFilePaths, String timeZone,
Host host)
throws TskCoreException {
9959 long imageId = this.caseHandle.addImageInfo(deviceObjId, imageFilePaths, timeZone, host,
this);
9973 CaseDbConnection connection = null;
9974 Statement s1 = null;
9975 ResultSet rs1 = null;
9978 connection = connections.getConnection();
9979 s1 = connection.createStatement();
9980 rs1 = connection.executeQuery(s1,
"SELECT tsk_image_info.obj_id, tsk_image_names.name FROM tsk_image_info "
9981 +
"LEFT JOIN tsk_image_names ON tsk_image_info.obj_id = tsk_image_names.obj_id");
9982 Map<Long, List<String>> imgPaths =
new LinkedHashMap<Long, List<String>>();
9983 while (rs1.next()) {
9984 long obj_id = rs1.getLong(
"obj_id");
9985 String name = rs1.getString(
"name");
9986 List<String> imagePaths = imgPaths.get(obj_id);
9987 if (imagePaths == null) {
9988 List<String> paths =
new ArrayList<String>();
9992 imgPaths.put(obj_id, paths);
9995 imagePaths.add(name);
10000 }
catch (SQLException ex) {
10001 throw new TskCoreException(
"Error getting image paths.", ex);
10003 closeResultSet(rs1);
10004 closeStatement(s1);
10005 closeConnection(connection);
10021 private List<String> getImagePathsById(
long objectId, CaseDbConnection connection)
throws TskCoreException {
10022 List<String> imagePaths =
new ArrayList<>();
10024 Statement statement = null;
10025 ResultSet resultSet = null;
10027 statement = connection.createStatement();
10028 resultSet = connection.executeQuery(statement,
"SELECT name FROM tsk_image_names WHERE tsk_image_names.obj_id = " + objectId);
10029 while (resultSet.next()) {
10030 imagePaths.add(resultSet.getString(
"name"));
10032 }
catch (SQLException ex) {
10033 throw new TskCoreException(String.format(
"Error getting image names with obj_id = %d", objectId), ex);
10035 closeResultSet(resultSet);
10036 closeStatement(statement);
10050 CaseDbConnection connection = null;
10051 Statement s = null;
10052 ResultSet rs = null;
10055 connection = connections.getConnection();
10056 s = connection.createStatement();
10057 rs = connection.executeQuery(s,
"SELECT obj_id FROM tsk_image_info");
10058 Collection<Long> imageIDs =
new ArrayList<Long>();
10059 while (rs.next()) {
10060 imageIDs.add(rs.getLong(
"obj_id"));
10062 List<Image> images =
new ArrayList<Image>();
10063 for (
long id : imageIDs) {
10067 }
catch (SQLException ex) {
10068 throw new TskCoreException(
"Error retrieving images.", ex);
10070 closeResultSet(rs);
10072 closeConnection(connection);
10087 public void setImagePaths(
long obj_id, List<String> paths)
throws TskCoreException {
10092 transaction = null;
10094 if (transaction != null) {
10114 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.DELETE_IMAGE_NAME);
10115 statement.clearParameters();
10116 statement.setLong(1, objId);
10117 trans.getConnection().executeUpdate(statement);
10118 for (
int i = 0; i < paths.size(); i++) {
10119 statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.INSERT_IMAGE_NAME);
10120 statement.clearParameters();
10121 statement.setLong(1, objId);
10122 statement.setString(2, paths.get(i));
10123 statement.setLong(3, i);
10124 trans.getConnection().executeUpdate(statement);
10126 }
catch (SQLException ex) {
10127 throw new TskCoreException(
"Error updating image paths.", ex);
10143 void deleteDataSource(
long dataSourceObjectId)
throws TskCoreException {
10149 Host hostToDelete = null;
10153 if (major > 9 || (major == 9 && minor >= 1)) {
10155 if (
getHostManager().getDataSourcesForHost(hostToDelete).size() != 1) {
10156 hostToDelete = null;
10160 CaseDbConnection connection = null;
10161 Statement statement;
10164 connection = connections.getConnection();
10165 statement = connection.createStatement();
10166 connection.beginTransaction();
10169 statement.execute(
"DELETE FROM tsk_objects WHERE obj_id = " + dataSourceObjectId);
10172 String accountSql =
"DELETE FROM accounts WHERE account_id in (SELECT account_id FROM accounts "
10173 +
"WHERE account_id NOT IN (SELECT account1_id FROM account_relationships) "
10174 +
"AND account_id NOT IN (SELECT account2_id FROM account_relationships))";
10175 statement.execute(accountSql);
10179 if (hostToDelete != null) {
10180 statement.execute(
"DELETE FROM tsk_hosts WHERE id = " + hostToDelete.
getHostId());
10183 String deleteOsAcctObjectsQuery =
"DELETE FROM tsk_objects "
10184 +
"WHERE type=" + TskData.ObjectType.OS_ACCOUNT.getObjectType() +
" "
10185 +
"AND obj_id NOT IN (SELECT os_account_obj_id FROM tsk_os_accounts WHERE os_account_obj_id IS NOT NULL)";
10186 statement.execute(deleteOsAcctObjectsQuery);
10189 connection.commitTransaction();
10190 }
catch (SQLException ex) {
10191 rollbackTransaction(connection);
10192 throw new TskCoreException(
"Error deleting data source.", ex);
10194 closeConnection(connection);
10224 List<AbstractFile> resultSetToAbstractFiles(ResultSet rs, CaseDbConnection connection)
throws SQLException {
10225 ArrayList<AbstractFile> results =
new ArrayList<AbstractFile>();
10227 while (rs.next()) {
10228 final short type = rs.getShort(
"type");
10229 if (type == TSK_DB_FILES_TYPE_ENUM.FS.getFileType()
10230 && (rs.getShort(
"meta_type") != TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue())) {
10232 if (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()) {
10233 result = directory(rs, null);
10235 result = file(rs, null);
10237 results.add(result);
10238 }
else if (type == TSK_DB_FILES_TYPE_ENUM.VIRTUAL_DIR.getFileType()
10239 || (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue())) {
10240 final VirtualDirectory virtDir = virtualDirectory(rs, connection);
10241 results.add(virtDir);
10242 }
else if (type == TSK_DB_FILES_TYPE_ENUM.LOCAL_DIR.getFileType()) {
10243 final LocalDirectory localDir = localDirectory(rs);
10244 results.add(localDir);
10245 }
else if (type == TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS.getFileType()
10246 || type == TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS.getFileType()
10247 || type == TSK_DB_FILES_TYPE_ENUM.CARVED.getFileType()
10248 || type == TSK_DB_FILES_TYPE_ENUM.LAYOUT_FILE.getFileType()) {
10249 TSK_DB_FILES_TYPE_ENUM atype = TSK_DB_FILES_TYPE_ENUM.valueOf(type);
10250 String parentPath = rs.getString(
"parent_path");
10251 if (parentPath == null) {
10255 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10256 if (rs.wasNull()) {
10257 osAccountObjId = null;
10260 LayoutFile lf =
new LayoutFile(
this,
10261 rs.getLong(
"obj_id"),
10262 rs.getLong(
"data_source_obj_id"),
10263 rs.getLong(
"fs_obj_id"),
10264 rs.getString(
"name"),
10266 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")), TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10267 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
10268 rs.getLong(
"size"),
10269 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10270 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10271 FileKnown.valueOf(rs.getByte(
"known")), parentPath,
10272 rs.getString(
"mime_type"),
10273 rs.getString(
"owner_uid"), osAccountObjId);
10275 }
else if (type == TSK_DB_FILES_TYPE_ENUM.DERIVED.getFileType()) {
10276 final DerivedFile df;
10277 df = derivedFile(rs, connection, AbstractContent.UNKNOWN_ID);
10279 }
else if (type == TSK_DB_FILES_TYPE_ENUM.LOCAL.getFileType()) {
10280 final LocalFile lf;
10281 lf = localFile(rs, connection, AbstractContent.UNKNOWN_ID);
10283 }
else if (type == TSK_DB_FILES_TYPE_ENUM.SLACK.getFileType()) {
10284 final SlackFile sf = slackFile(rs, null);
10288 }
catch (SQLException e) {
10289 logger.log(Level.SEVERE,
"Error getting abstract files from result set", e);
10308 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10309 if (rs.wasNull()) {
10310 osAccountObjId = null;
10314 rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
10315 TskData.TSK_FS_ATTR_TYPE_ENUM.valueOf(rs.getShort(
"attr_type")),
10316 rs.getInt(
"attr_id"), rs.getString(
"name"), rs.getLong(
"meta_addr"), rs.getInt(
"meta_seq"),
10317 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10318 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10319 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10320 rs.getShort(
"meta_flags"), rs.getLong(
"size"),
10321 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10322 (short) rs.getInt(
"mode"), rs.getInt(
"uid"), rs.getInt(
"gid"),
10323 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10324 FileKnown.valueOf(rs.getByte(
"known")),
10325 rs.getString(
"parent_path"), rs.getString(
"mime_type"), rs.getString(
"extension"), rs.getString(
"owner_uid"),
10326 osAccountObjId, TskData.CollectedStatus.valueOf(rs.getInt(
"collected")), Collections.emptyList());
10327 f.setFileSystem(fs);
10342 Directory directory(ResultSet rs, FileSystem fs)
throws SQLException {
10343 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10344 if (rs.wasNull()) {
10345 osAccountObjId = null;
10348 Directory dir =
new Directory(
this, rs.getLong(
"obj_id"), rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
10349 TskData.TSK_FS_ATTR_TYPE_ENUM.valueOf(rs.getShort(
"attr_type")),
10350 rs.getInt(
"attr_id"), rs.getString(
"name"), rs.getLong(
"meta_addr"), rs.getInt(
"meta_seq"),
10351 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10352 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10353 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10354 rs.getShort(
"meta_flags"), rs.getLong(
"size"),
10355 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10356 rs.getShort(
"mode"), rs.getInt(
"uid"), rs.getInt(
"gid"),
10357 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10358 FileKnown.valueOf(rs.getByte(
"known")),
10359 rs.getString(
"parent_path"), rs.getString(
"owner_uid"), osAccountObjId);
10360 dir.setFileSystem(fs);
10374 VirtualDirectory virtualDirectory(ResultSet rs, CaseDbConnection connection)
throws SQLException {
10375 String parentPath = rs.getString(
"parent_path");
10376 if (parentPath == null) {
10380 long objId = rs.getLong(
"obj_id");
10381 long dsObjId = rs.getLong(
"data_source_obj_id");
10382 if (objId == dsObjId) {
10384 String deviceId =
"";
10385 String timeZone =
"";
10386 Statement s = null;
10387 ResultSet rsDataSourceInfo = null;
10391 s = connection.createStatement();
10392 rsDataSourceInfo = connection.executeQuery(s,
"SELECT device_id, time_zone FROM data_source_info WHERE obj_id = " + objId);
10393 if (rsDataSourceInfo.next()) {
10394 deviceId = rsDataSourceInfo.getString(
"device_id");
10395 timeZone = rsDataSourceInfo.getString(
"time_zone");
10397 }
catch (SQLException ex) {
10398 logger.log(Level.SEVERE,
"Error data source info for datasource id " + objId, ex);
10400 closeResultSet(rsDataSourceInfo);
10405 return new LocalFilesDataSource(
this,
10408 rs.getString(
"name"),
10409 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10410 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10411 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10412 rs.getShort(
"meta_flags"),
10414 rs.getString(
"md5"),
10415 rs.getString(
"sha256"),
10416 rs.getString(
"sha1"),
10417 FileKnown.valueOf(rs.getByte(
"known")),
10420 final VirtualDirectory vd =
new VirtualDirectory(
this,
10422 rs.getLong(
"fs_obj_id"),
10423 rs.getString(
"name"),
10424 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10425 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10426 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10427 rs.getShort(
"meta_flags"), rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10428 FileKnown.valueOf(rs.getByte(
"known")), parentPath);
10442 LocalDirectory localDirectory(ResultSet rs)
throws SQLException {
10443 String parentPath = rs.getString(
"parent_path");
10444 if (parentPath == null) {
10447 final LocalDirectory ld =
new LocalDirectory(
this, rs.getLong(
"obj_id"),
10448 rs.getLong(
"data_source_obj_id"), rs.getString(
"name"),
10449 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10450 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10451 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10452 rs.getShort(
"meta_flags"), rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10453 FileKnown.valueOf(rs.getByte(
"known")), parentPath);
10470 private DerivedFile derivedFile(ResultSet rs, CaseDbConnection connection,
long parentId)
throws SQLException {
10471 boolean hasLocalPath = rs.getBoolean(
"has_path");
10472 long objId = rs.getLong(
"obj_id");
10473 String localPath = null;
10474 TskData.EncodingType encodingType = TskData.EncodingType.NONE;
10475 if (hasLocalPath) {
10476 ResultSet rsFilePath = null;
10479 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_LOCAL_PATH_AND_ENCODING_FOR_FILE);
10480 statement.clearParameters();
10481 statement.setLong(1, objId);
10482 rsFilePath = connection.executeQuery(statement);
10483 if (rsFilePath.next()) {
10484 localPath = rsFilePath.getString(
"path");
10485 encodingType = TskData.EncodingType.valueOf(rsFilePath.getInt(
"encoding_type"));
10487 }
catch (SQLException ex) {
10488 logger.log(Level.SEVERE,
"Error getting encoding type for file " + objId, ex);
10490 closeResultSet(rsFilePath);
10494 String parentPath = rs.getString(
"parent_path");
10495 if (parentPath == null) {
10499 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10500 if (rs.wasNull()) {
10501 osAccountObjId = null;
10504 final DerivedFile df =
new DerivedFile(
this, objId, rs.getLong(
"data_source_obj_id"),
10505 rs.getLong(
"fs_obj_id"),
10506 rs.getString(
"name"),
10507 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10508 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10509 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
10510 rs.getLong(
"size"),
10511 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10512 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10513 FileKnown.valueOf(rs.getByte(
"known")),
10514 parentPath, localPath, parentId, rs.getString(
"mime_type"),
10515 encodingType, rs.getString(
"extension"),
10516 rs.getString(
"owner_uid"), osAccountObjId);
10533 private LocalFile localFile(ResultSet rs, CaseDbConnection connection,
long parentId)
throws SQLException {
10534 long objId = rs.getLong(
"obj_id");
10535 String localPath = null;
10536 TskData.EncodingType encodingType = TskData.EncodingType.NONE;
10537 if (rs.getBoolean(
"has_path")) {
10538 ResultSet rsFilePath = null;
10541 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_LOCAL_PATH_AND_ENCODING_FOR_FILE);
10542 statement.clearParameters();
10543 statement.setLong(1, objId);
10544 rsFilePath = connection.executeQuery(statement);
10545 if (rsFilePath.next()) {
10546 localPath = rsFilePath.getString(
"path");
10547 encodingType = TskData.EncodingType.valueOf(rsFilePath.getInt(
"encoding_type"));
10549 }
catch (SQLException ex) {
10550 logger.log(Level.SEVERE,
"Error getting encoding type for file " + objId, ex);
10552 closeResultSet(rsFilePath);
10556 String parentPath = rs.getString(
"parent_path");
10557 if (null == parentPath) {
10560 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10561 if (rs.wasNull()) {
10562 osAccountObjId = null;
10565 LocalFile file =
new LocalFile(
this, objId, rs.getString(
"name"),
10566 TSK_DB_FILES_TYPE_ENUM.valueOf(rs.getShort(
"type")),
10567 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10568 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10569 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
10570 rs.getLong(
"size"),
10571 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10572 rs.getString(
"mime_type"), rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10573 FileKnown.valueOf(rs.getByte(
"known")),
10574 parentId, parentPath, rs.getLong(
"data_source_obj_id"),
10575 localPath, encodingType, rs.getString(
"extension"),
10576 rs.getString(
"owner_uid"), osAccountObjId);
10592 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10593 if (rs.wasNull()) {
10594 osAccountObjId = null;
10597 rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
10598 TskData.TSK_FS_ATTR_TYPE_ENUM.valueOf(rs.getShort(
"attr_type")),
10599 rs.getInt(
"attr_id"), rs.getString(
"name"), rs.getLong(
"meta_addr"), rs.getInt(
"meta_seq"),
10600 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10601 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10602 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10603 rs.getShort(
"meta_flags"), rs.getLong(
"size"),
10604 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10605 (short) rs.getInt(
"mode"), rs.getInt(
"uid"), rs.getInt(
"gid"),
10606 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10607 FileKnown.valueOf(rs.getByte(
"known")),
10608 rs.getString(
"parent_path"), rs.getString(
"mime_type"), rs.getString(
"extension"),
10609 rs.getString(
"owner_uid"), osAccountObjId);
10610 f.setFileSystem(fs);
10625 List<Content> fileChildren(ResultSet rs, CaseDbConnection connection,
long parentId)
throws SQLException {
10626 List<Content> children =
new ArrayList<Content>();
10628 while (rs.next()) {
10629 TskData.TSK_DB_FILES_TYPE_ENUM type = TskData.TSK_DB_FILES_TYPE_ENUM.valueOf(rs.getShort(
"type"));
10631 if (null != type) {
10634 if (rs.getShort(
"meta_type") != TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue()) {
10636 if (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()) {
10637 result = directory(rs, null);
10639 result = file(rs, null);
10641 children.add(result);
10643 VirtualDirectory virtDir = virtualDirectory(rs, connection);
10644 children.add(virtDir);
10648 VirtualDirectory virtDir = virtualDirectory(rs, connection);
10649 children.add(virtDir);
10652 LocalDirectory localDir = localDirectory(rs);
10653 children.add(localDir);
10655 case UNALLOC_BLOCKS:
10656 case UNUSED_BLOCKS:
10658 case LAYOUT_FILE: {
10659 String parentPath = rs.getString(
"parent_path");
10660 if (parentPath == null) {
10663 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10664 if (rs.wasNull()) {
10665 osAccountObjId = null;
10667 final LayoutFile lf =
new LayoutFile(
this, rs.getLong(
"obj_id"),
10668 rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
10669 rs.getString(
"name"), type,
10670 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10671 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10672 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
10673 rs.getLong(
"size"),
10674 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10675 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10676 FileKnown.valueOf(rs.getByte(
"known")), parentPath, rs.getString(
"mime_type"),
10677 rs.getString(
"owner_uid"), osAccountObjId);
10682 final DerivedFile df = derivedFile(rs, connection, parentId);
10686 final LocalFile lf = localFile(rs, connection, parentId);
10691 final SlackFile sf = slackFile(rs, null);
10760 CaseDbConnection getConnection() throws TskCoreException {
10761 return connections.getConnection();
10771 String getCaseHandleIdentifier() {
10772 return caseHandleIdentifier;
10775 @SuppressWarnings(
"deprecation")
10792 connections.close();
10793 }
catch (TskCoreException ex) {
10794 logger.log(Level.SEVERE,
"Error closing database connection pool.", ex);
10797 fileSystemIdMap.clear();
10800 if (this.caseHandle != null) {
10801 this.caseHandle.free();
10802 this.caseHandle = null;
10804 }
catch (TskCoreException ex) {
10805 logger.log(Level.SEVERE,
"Error freeing case handle.", ex);
10824 long id = file.getId();
10825 FileKnown currentKnown = file.getKnown();
10826 if (currentKnown.compareTo(fileKnown) > 0) {
10830 try (CaseDbConnection connection = connections.getConnection();
10831 Statement statement = connection.createStatement();) {
10832 connection.executeUpdate(statement,
"UPDATE tsk_files "
10833 +
"SET known='" + fileKnown.getFileKnownValue() +
"' "
10834 +
"WHERE obj_id=" + id);
10836 file.setKnown(fileKnown);
10837 }
catch (SQLException ex) {
10838 throw new TskCoreException(
"Error setting Known status.", ex);
10853 void setFileName(String name,
long objId)
throws TskCoreException {
10855 try (CaseDbConnection connection = connections.getConnection();) {
10857 preparedStatement.clearParameters();
10858 preparedStatement.setString(1, name);
10859 preparedStatement.setLong(2, objId);
10860 connection.executeUpdate(preparedStatement);
10861 }
catch (SQLException ex) {
10862 throw new TskCoreException(String.format(
"Error updating while the name for object ID %d to %s", objId, name), ex);
10876 void setImageName(String name,
long objId)
throws TskCoreException {
10878 try (CaseDbConnection connection = connections.getConnection();) {
10879 PreparedStatement preparedStatement = connection.getPreparedStatement(SleuthkitCase.PREPARED_STATEMENT.UPDATE_IMAGE_NAME);
10880 preparedStatement.clearParameters();
10881 preparedStatement.setString(1, name);
10882 preparedStatement.setLong(2, objId);
10883 connection.executeUpdate(preparedStatement);
10884 }
catch (SQLException ex) {
10885 throw new TskCoreException(String.format(
"Error updating while the name for object ID %d to %s", objId, name), ex);
10905 void setImageSizes(Image image,
long totalSize,
long sectorSize)
throws TskCoreException {
10908 try (CaseDbConnection connection = connections.getConnection();) {
10909 PreparedStatement preparedStatement = connection.getPreparedStatement(SleuthkitCase.PREPARED_STATEMENT.UPDATE_IMAGE_SIZES);
10910 preparedStatement.clearParameters();
10911 preparedStatement.setLong(1, totalSize);
10912 preparedStatement.setLong(2, sectorSize);
10913 preparedStatement.setLong(3, image.getId());
10914 connection.executeUpdate(preparedStatement);
10915 }
catch (SQLException ex) {
10916 throw new TskCoreException(String.format(
"Error updating image sizes to %d and sector size to %d for object ID %d ", totalSize, sectorSize, image.getId()), ex);
10933 try (CaseDbConnection connection = connections.getConnection();
10934 Statement statement = connection.createStatement()) {
10935 connection.executeUpdate(statement, String.format(
"UPDATE tsk_files SET mime_type = '%s' WHERE obj_id = %d", mimeType, file.getId()));
10936 file.setMIMEType(mimeType);
10937 }
catch (SQLException ex) {
10938 throw new TskCoreException(String.format(
"Error setting MIME type for file (obj_id = %s)", file.getId()), ex);
10957 short metaFlag = file.getMetaFlagsAsInt();
10966 try (CaseDbConnection connection = connections.getConnection();
10967 Statement statement = connection.createStatement();) {
10968 connection.executeUpdate(statement, String.format(
"UPDATE tsk_files SET meta_flags = '%d', dir_flags = '%d' WHERE obj_id = %d", newMetaFlgs, newDirFlags, file.getId()));
10975 }
catch (SQLException ex) {
10976 throw new TskCoreException(String.format(
"Error setting unalloc meta flag for file (obj_id = %s)", file.getId()), ex);
10991 void setMd5Hash(AbstractFile file, String md5Hash)
throws TskCoreException {
10992 if (md5Hash == null) {
10995 long id = file.getId();
10997 try (CaseDbConnection connection = connections.getConnection();) {
10998 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_FILE_MD5);
10999 statement.clearParameters();
11000 statement.setString(1, md5Hash.toLowerCase());
11001 statement.setLong(2,
id);
11002 connection.executeUpdate(statement);
11003 file.setMd5Hash(md5Hash.toLowerCase());
11004 }
catch (SQLException ex) {
11005 throw new TskCoreException(
"Error setting MD5 hash", ex);
11020 void setMd5ImageHash(Image img, String md5Hash)
throws TskCoreException {
11021 if (md5Hash == null) {
11024 long id = img.getId();
11026 try (CaseDbConnection connection = connections.getConnection();) {
11027 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_MD5);
11028 statement.clearParameters();
11029 statement.setString(1, md5Hash.toLowerCase());
11030 statement.setLong(2,
id);
11031 connection.executeUpdate(statement);
11032 }
catch (SQLException ex) {
11033 throw new TskCoreException(
"Error setting MD5 hash", ex);
11049 String getMd5ImageHash(Image img)
throws TskCoreException {
11050 long id = img.getId();
11051 CaseDbConnection connection = null;
11052 ResultSet rs = null;
11056 connection = connections.getConnection();
11058 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_IMAGE_MD5);
11059 statement.clearParameters();
11060 statement.setLong(1,
id);
11061 rs = connection.executeQuery(statement);
11063 hash = rs.getString(
"md5");
11066 }
catch (SQLException ex) {
11067 throw new TskCoreException(
"Error getting MD5 hash", ex);
11069 closeResultSet(rs);
11070 closeConnection(connection);
11084 void setSha1ImageHash(Image img, String sha1Hash)
throws TskCoreException {
11085 if (sha1Hash == null) {
11088 long id = img.getId();
11090 try (CaseDbConnection connection = connections.getConnection();) {
11091 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_SHA1);
11092 statement.clearParameters();
11093 statement.setString(1, sha1Hash.toLowerCase());
11094 statement.setLong(2,
id);
11095 connection.executeUpdate(statement);
11096 }
catch (SQLException ex) {
11097 throw new TskCoreException(
"Error setting SHA1 hash", ex);
11113 String getSha1ImageHash(Image img)
throws TskCoreException {
11114 long id = img.getId();
11115 CaseDbConnection connection = null;
11116 ResultSet rs = null;
11120 connection = connections.getConnection();
11122 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_IMAGE_SHA1);
11123 statement.clearParameters();
11124 statement.setLong(1,
id);
11125 rs = connection.executeQuery(statement);
11127 hash = rs.getString(
"sha1");
11130 }
catch (SQLException ex) {
11131 throw new TskCoreException(
"Error getting SHA1 hash", ex);
11133 closeResultSet(rs);
11134 closeConnection(connection);
11148 void setSha256ImageHash(Image img, String sha256Hash)
throws TskCoreException {
11149 if (sha256Hash == null) {
11152 long id = img.getId();
11154 try (CaseDbConnection connection = connections.getConnection();) {
11155 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_SHA256);
11156 statement.clearParameters();
11157 statement.setString(1, sha256Hash.toLowerCase());
11158 statement.setLong(2,
id);
11159 connection.executeUpdate(statement);
11160 }
catch (SQLException ex) {
11161 throw new TskCoreException(
"Error setting SHA256 hash", ex);
11177 String getSha256ImageHash(Image img)
throws TskCoreException {
11178 long id = img.getId();
11179 CaseDbConnection connection = null;
11180 ResultSet rs = null;
11184 connection = connections.getConnection();
11186 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_IMAGE_SHA256);
11187 statement.clearParameters();
11188 statement.setLong(1,
id);
11189 rs = connection.executeQuery(statement);
11191 hash = rs.getString(
"sha256");
11194 }
catch (SQLException ex) {
11195 throw new TskCoreException(
"Error setting SHA256 hash", ex);
11197 closeResultSet(rs);
11198 closeConnection(connection);
11211 void setAcquisitionDetails(DataSource datasource, String details)
throws TskCoreException {
11213 long id = datasource.getId();
11215 try (CaseDbConnection connection = connections.getConnection();) {
11216 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ACQUISITION_DETAILS);
11217 statement.clearParameters();
11218 statement.setString(1, details);
11219 statement.setLong(2,
id);
11220 connection.executeUpdate(statement);
11221 }
catch (SQLException ex) {
11222 throw new TskCoreException(
"Error setting acquisition details", ex);
11239 void setAcquisitionToolDetails(DataSource datasource, String name, String version, String settings)
throws TskCoreException {
11241 long id = datasource.getId();
11243 try (CaseDbConnection connection = connections.getConnection();) {
11244 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ACQUISITION_TOOL_SETTINGS);
11245 statement.clearParameters();
11246 statement.setString(1, settings);
11247 statement.setString(2, name);
11248 statement.setString(3, version);
11249 statement.setLong(4,
id);
11250 connection.executeUpdate(statement);
11251 }
catch (SQLException ex) {
11252 throw new TskCoreException(
"Error setting acquisition details", ex);
11267 void setAcquisitionDetails(
long dataSourceId, String details, CaseDbTransaction trans)
throws TskCoreException {
11269 CaseDbConnection connection = trans.getConnection();
11270 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ACQUISITION_DETAILS);
11271 statement.clearParameters();
11272 statement.setString(1, details);
11273 statement.setLong(2, dataSourceId);
11274 connection.executeUpdate(statement);
11275 }
catch (SQLException ex) {
11276 throw new TskCoreException(
"Error setting acquisition details", ex);
11289 String getAcquisitionDetails(DataSource datasource)
throws TskCoreException {
11290 long id = datasource.getId();
11291 CaseDbConnection connection = null;
11292 ResultSet rs = null;
11296 connection = connections.getConnection();
11298 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ACQUISITION_DETAILS);
11299 statement.clearParameters();
11300 statement.setLong(1,
id);
11301 rs = connection.executeQuery(statement);
11303 hash = rs.getString(
"acquisition_details");
11306 }
catch (SQLException ex) {
11307 throw new TskCoreException(
"Error setting acquisition details", ex);
11309 closeResultSet(rs);
11310 closeConnection(connection);
11325 String getDataSourceInfoString(DataSource datasource, String columnName)
throws TskCoreException {
11326 long id = datasource.getId();
11327 CaseDbConnection connection = null;
11328 ResultSet rs = null;
11329 String returnValue =
"";
11332 connection = connections.getConnection();
11334 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ACQUISITION_TOOL_SETTINGS);
11335 statement.clearParameters();
11336 statement.setLong(1,
id);
11337 rs = connection.executeQuery(statement);
11339 returnValue = rs.getString(columnName);
11341 return returnValue;
11342 }
catch (SQLException ex) {
11343 throw new TskCoreException(
"Error setting acquisition details", ex);
11345 closeResultSet(rs);
11346 closeConnection(connection);
11361 Long getDataSourceInfoLong(DataSource datasource, String columnName)
throws TskCoreException {
11362 long id = datasource.getId();
11363 CaseDbConnection connection = null;
11364 ResultSet rs = null;
11365 Long returnValue = null;
11368 connection = connections.getConnection();
11370 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ACQUISITION_TOOL_SETTINGS);
11371 statement.clearParameters();
11372 statement.setLong(1,
id);
11373 rs = connection.executeQuery(statement);
11375 returnValue = rs.getLong(columnName);
11377 return returnValue;
11378 }
catch (SQLException ex) {
11379 throw new TskCoreException(
"Error setting acquisition details", ex);
11381 closeResultSet(rs);
11382 closeConnection(connection);
11398 if (newStatus == null) {
11402 try (CaseDbConnection connection = connections.getConnection();
11403 Statement statement = connection.createStatement();) {
11404 connection.executeUpdate(statement,
"UPDATE blackboard_artifacts "
11405 +
" SET review_status_id=" + newStatus.getID()
11406 +
" WHERE blackboard_artifacts.artifact_id = " + artifact.
getArtifactID());
11407 }
catch (SQLException ex) {
11408 throw new TskCoreException(
"Error setting review status", ex);
11425 CaseDbConnection connection = null;
11426 Statement s = null;
11427 ResultSet rs = null;
11430 connection = connections.getConnection();
11431 s = connection.createStatement();
11432 Short contentShort = contentType.getValue();
11433 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files WHERE meta_type = '" + contentShort.toString() +
"'");
11436 count = rs.getInt(
"count");
11439 }
catch (SQLException ex) {
11440 throw new TskCoreException(
"Error getting number of objects.", ex);
11442 closeResultSet(rs);
11444 closeConnection(connection);
11458 String escapedText = null;
11459 if (text != null) {
11460 escapedText = text.replaceAll(
"'",
"''");
11462 return escapedText;
11473 if (md5Hash == null) {
11474 return Collections.<AbstractFile>emptyList();
11477 CaseDbConnection connection = null;
11478 Statement s = null;
11479 ResultSet rs = null;
11482 connection = connections.getConnection();
11483 s = connection.createStatement();
11484 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE "
11485 +
" md5 = '" + md5Hash.toLowerCase() +
"' "
11487 return resultSetToAbstractFiles(rs, connection);
11488 }
catch (SQLException | TskCoreException ex) {
11489 logger.log(Level.WARNING,
"Error querying database.", ex);
11491 closeResultSet(rs);
11493 closeConnection(connection);
11496 return Collections.<AbstractFile>emptyList();
11506 boolean allFilesAreHashed =
false;
11508 CaseDbConnection connection = null;
11509 Statement s = null;
11510 ResultSet rs = null;
11513 connection = connections.getConnection();
11514 s = connection.createStatement();
11515 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files "
11517 +
"AND md5 IS NULL "
11518 +
"AND size > '0'");
11519 if (rs.next() && rs.getInt(
"count") == 0) {
11520 allFilesAreHashed =
true;
11522 }
catch (SQLException | TskCoreException ex) {
11523 logger.log(Level.WARNING,
"Failed to query whether all files have MD5 hashes", ex);
11525 closeResultSet(rs);
11527 closeConnection(connection);
11530 return allFilesAreHashed;
11542 CaseDbConnection connection = null;
11543 Statement s = null;
11544 ResultSet rs = null;
11546 connection = connections.getConnection();
11547 s = connection.createStatement();
11548 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files "
11549 +
"WHERE md5 IS NOT NULL "
11550 +
"AND size > '0'");
11552 count = rs.getInt(
"count");
11554 }
catch (SQLException | TskCoreException ex) {
11555 logger.log(Level.WARNING,
"Failed to query for all the files.", ex);
11557 closeResultSet(rs);
11559 closeConnection(connection);
11575 CaseDbConnection connection = null;
11576 ResultSet resultSet = null;
11579 connection = connections.getConnection();
11582 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_TAG_NAMES);
11583 resultSet = connection.executeQuery(statement);
11584 ArrayList<TagName> tagNames =
new ArrayList<>();
11585 while (resultSet.next()) {
11586 tagNames.add(
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
11588 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank")));
11591 }
catch (SQLException ex) {
11592 throw new TskCoreException(
"Error selecting rows from tag_names table", ex);
11594 closeResultSet(resultSet);
11595 closeConnection(connection);
11611 CaseDbConnection connection = null;
11612 ResultSet resultSet = null;
11615 connection = connections.getConnection();
11618 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_TAG_NAMES_IN_USE);
11619 resultSet = connection.executeQuery(statement);
11620 ArrayList<TagName> tagNames =
new ArrayList<>();
11621 while (resultSet.next()) {
11622 tagNames.add(
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
11624 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank")));
11627 }
catch (SQLException ex) {
11628 throw new TskCoreException(
"Error selecting rows from tag_names table", ex);
11630 closeResultSet(resultSet);
11631 closeConnection(connection);
11650 ArrayList<TagName> tagNames =
new ArrayList<>();
11656 CaseDbConnection connection = null;
11657 ResultSet resultSet = null;
11660 connection = connections.getConnection();
11662 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_TAG_NAMES_IN_USE_BY_DATASOURCE);
11663 statement.setLong(1, dsObjId);
11664 statement.setLong(2, dsObjId);
11665 resultSet = connection.executeQuery(statement);
11666 while (resultSet.next()) {
11667 tagNames.add(
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
11669 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank")));
11672 }
catch (SQLException ex) {
11673 throw new TskCoreException(
"Failed to get tag names in use for data source objID : " + dsObjId, ex);
11675 closeResultSet(resultSet);
11676 closeConnection(connection);
11695 @SuppressWarnings(
"deprecation")
11749 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.DELETE_CONTENT_TAG);
11750 statement.clearParameters();
11751 statement.setLong(1, tag.getId());
11752 trans.getConnection().executeUpdate(statement);
11755 Long contentId = tag.getContent() != null ? tag.getContent().getId() : null;
11756 Long dataSourceId = tag.getContent() != null && tag.getContent().getDataSource() != null
11757 ? tag.getContent().getDataSource().getId()
11760 this.
getScoringManager().updateAggregateScoreAfterDeletion(contentId, dataSourceId, trans);
11764 }
catch (SQLException ex) {
11765 throw new TskCoreException(
"Error deleting row from content_tags table (id = " + tag.getId() +
")", ex);
11767 if (trans != null) {
11782 CaseDbConnection connection = null;
11783 ResultSet resultSet = null;
11786 connection = connections.getConnection();
11792 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS);
11793 resultSet = connection.executeQuery(statement);
11794 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
11795 while (resultSet.next()) {
11796 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
11798 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
11800 tags.add(
new ContentTag(resultSet.getLong(
"tag_id"), content, tagName, resultSet.getString(
"comment"),
11801 resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name")));
11804 }
catch (SQLException ex) {
11805 throw new TskCoreException(
"Error selecting rows from content_tags table", ex);
11807 closeResultSet(resultSet);
11808 closeConnection(connection);
11824 if (tagName.getId() ==
Tag.ID_NOT_SET) {
11825 throw new TskCoreException(
"TagName object is invalid, id not set");
11827 CaseDbConnection connection = null;
11828 ResultSet resultSet = null;
11831 connection = connections.getConnection();
11834 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CONTENT_TAGS_BY_TAG_NAME);
11835 statement.clearParameters();
11836 statement.setLong(1, tagName.getId());
11837 resultSet = connection.executeQuery(statement);
11838 if (resultSet.next()) {
11839 return resultSet.getLong(
"count");
11841 throw new TskCoreException(
"Error getting content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")");
11843 }
catch (SQLException ex) {
11844 throw new TskCoreException(
"Error getting content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")", ex);
11846 closeResultSet(resultSet);
11847 closeConnection(connection);
11869 if (tagName.getId() ==
Tag.ID_NOT_SET) {
11870 throw new TskCoreException(
"TagName object is invalid, id not set");
11873 CaseDbConnection connection = null;
11874 ResultSet resultSet = null;
11877 connection = connections.getConnection();
11882 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CONTENT_TAGS_BY_TAG_NAME_BY_DATASOURCE);
11883 statement.clearParameters();
11884 statement.setLong(1, tagName.getId());
11885 statement.setLong(2, dsObjId);
11887 resultSet = connection.executeQuery(statement);
11888 if (resultSet.next()) {
11889 return resultSet.getLong(
"count");
11891 throw new TskCoreException(
"Error getting content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")" +
" for dsObjId = " + dsObjId);
11893 }
catch (SQLException ex) {
11894 throw new TskCoreException(
"Failed to get content_tags row count for tag_name_id = " + tagName.getId() +
"data source objID : " + dsObjId, ex);
11896 closeResultSet(resultSet);
11897 closeConnection(connection);
11914 CaseDbConnection connection = null;
11915 ResultSet resultSet = null;
11919 connection = connections.getConnection();
11926 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAG_BY_ID);
11927 statement.clearParameters();
11928 statement.setLong(1, contentTagID);
11929 resultSet = connection.executeQuery(statement);
11931 while (resultSet.next()) {
11932 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
11934 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
11936 resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
11940 }
catch (SQLException ex) {
11941 throw new TskCoreException(
"Error getting content tag with id = " + contentTagID, ex);
11943 closeResultSet(resultSet);
11944 closeConnection(connection);
11962 if (tagName.getId() ==
Tag.ID_NOT_SET) {
11963 throw new TskCoreException(
"TagName object is invalid, id not set");
11965 CaseDbConnection connection = null;
11966 ResultSet resultSet = null;
11969 connection = connections.getConnection();
11975 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS_BY_TAG_NAME);
11976 statement.clearParameters();
11977 statement.setLong(1, tagName.getId());
11978 resultSet = connection.executeQuery(statement);
11979 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
11980 while (resultSet.next()) {
11982 tagName, resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
11987 }
catch (SQLException ex) {
11988 throw new TskCoreException(
"Error getting content_tags rows (tag_name_id = " + tagName.getId() +
")", ex);
11990 closeResultSet(resultSet);
11991 closeConnection(connection);
12012 CaseDbConnection connection = null;
12013 ResultSet resultSet = null;
12016 connection = connections.getConnection();
12040 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS_BY_TAG_NAME_BY_DATASOURCE);
12041 statement.clearParameters();
12042 statement.setLong(1, tagName.getId());
12043 statement.setLong(2, dsObjId);
12044 statement.setLong(3, tagName.getId());
12045 statement.setLong(4, dsObjId);
12046 resultSet = connection.executeQuery(statement);
12047 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
12048 while (resultSet.next()) {
12050 tagName, resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
12055 }
catch (SQLException ex) {
12056 throw new TskCoreException(
"Failed to get content_tags row count for tag_name_id = " + tagName.getId() +
" data source objID : " + dsObjId, ex);
12058 closeResultSet(resultSet);
12059 closeConnection(connection);
12076 CaseDbConnection connection = null;
12077 ResultSet resultSet = null;
12080 connection = connections.getConnection();
12087 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS_BY_CONTENT);
12088 statement.clearParameters();
12089 statement.setLong(1, content.getId());
12090 resultSet = connection.executeQuery(statement);
12091 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
12092 while (resultSet.next()) {
12093 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12095 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12097 resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
12101 }
catch (SQLException ex) {
12102 throw new TskCoreException(
"Error getting content tags data for content (obj_id = " + content.getId() +
")", ex);
12104 closeResultSet(resultSet);
12105 closeConnection(connection);
12138 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.DELETE_ARTIFACT_TAG);
12139 statement.clearParameters();
12140 statement.setLong(1, tag.getId());
12141 trans.getConnection().executeUpdate(statement);
12144 Long artifactObjId = tag.getArtifact().getId();
12145 Long dataSourceId = tag.getContent() != null && tag.getContent().getDataSource() != null
12146 ? tag.getContent().getDataSource().getId()
12149 this.
getScoringManager().updateAggregateScoreAfterDeletion(artifactObjId, dataSourceId, trans);
12153 }
catch (SQLException ex) {
12154 throw new TskCoreException(
"Error deleting row from blackboard_artifact_tags table (id = " + tag.getId() +
")", ex);
12156 if (trans != null) {
12172 CaseDbConnection connection = null;
12173 ResultSet resultSet = null;
12176 connection = connections.getConnection();
12182 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS);
12183 resultSet = connection.executeQuery(statement);
12184 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<>();
12185 while (resultSet.next()) {
12186 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12188 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12192 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12196 }
catch (SQLException ex) {
12197 throw new TskCoreException(
"Error selecting rows from blackboard_artifact_tags table", ex);
12199 closeResultSet(resultSet);
12200 closeConnection(connection);
12216 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12217 throw new TskCoreException(
"TagName object is invalid, id not set");
12219 CaseDbConnection connection = null;
12220 ResultSet resultSet = null;
12223 connection = connections.getConnection();
12226 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_BY_TAG_NAME);
12227 statement.clearParameters();
12228 statement.setLong(1, tagName.getId());
12229 resultSet = connection.executeQuery(statement);
12230 if (resultSet.next()) {
12231 return resultSet.getLong(
"count");
12233 throw new TskCoreException(
"Error getting blackboard_artifact_tags row count for tag name (tag_name_id = " + tagName.getId() +
")");
12235 }
catch (SQLException ex) {
12236 throw new TskCoreException(
"Error getting blackboard artifact_content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")", ex);
12238 closeResultSet(resultSet);
12239 closeConnection(connection);
12260 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12261 throw new TskCoreException(
"TagName object is invalid, id not set");
12264 CaseDbConnection connection = null;
12265 ResultSet resultSet = null;
12268 connection = connections.getConnection();
12273 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_BY_TAG_NAME_BY_DATASOURCE);
12274 statement.clearParameters();
12275 statement.setLong(1, tagName.getId());
12276 statement.setLong(2, dsObjId);
12277 resultSet = connection.executeQuery(statement);
12278 if (resultSet.next()) {
12279 return resultSet.getLong(
"count");
12281 throw new TskCoreException(
"Error getting blackboard_artifact_tags row count for tag name (tag_name_id = " + tagName.getId() +
")" +
" for dsObjId = " + dsObjId);
12283 }
catch (SQLException ex) {
12284 throw new TskCoreException(
"Failed to get blackboard_artifact_tags row count for tag_name_id = " + tagName.getId() +
"data source objID : " + dsObjId, ex);
12286 closeResultSet(resultSet);
12287 closeConnection(connection);
12304 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12305 throw new TskCoreException(
"TagName object is invalid, id not set");
12307 CaseDbConnection connection = null;
12308 ResultSet resultSet = null;
12311 connection = connections.getConnection();
12317 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS_BY_TAG_NAME);
12318 statement.clearParameters();
12319 statement.setLong(1, tagName.getId());
12320 resultSet = connection.executeQuery(statement);
12321 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<BlackboardArtifactTag>();
12322 while (resultSet.next()) {
12326 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12330 }
catch (SQLException ex) {
12331 throw new TskCoreException(
"Error getting blackboard artifact tags data (tag_name_id = " + tagName.getId() +
")", ex);
12333 closeResultSet(resultSet);
12334 closeConnection(connection);
12355 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12356 throw new TskCoreException(
"TagName object is invalid, id not set");
12359 CaseDbConnection connection = null;
12360 ResultSet resultSet = null;
12363 connection = connections.getConnection();
12371 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS_BY_TAG_NAME_BY_DATASOURCE);
12372 statement.clearParameters();
12373 statement.setLong(1, tagName.getId());
12374 statement.setLong(2, dsObjId);
12375 resultSet = connection.executeQuery(statement);
12376 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<BlackboardArtifactTag>();
12377 while (resultSet.next()) {
12381 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12385 }
catch (SQLException ex) {
12386 throw new TskCoreException(
"Failed to get blackboard_artifact_tags row count for tag_name_id = " + tagName.getId() +
"data source objID : " + dsObjId, ex);
12388 closeResultSet(resultSet);
12389 closeConnection(connection);
12408 CaseDbConnection connection = null;
12409 ResultSet resultSet = null;
12413 connection = connections.getConnection();
12420 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAG_BY_ID);
12421 statement.clearParameters();
12422 statement.setLong(1, artifactTagID);
12423 resultSet = connection.executeQuery(statement);
12425 while (resultSet.next()) {
12426 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12428 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12432 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12436 }
catch (SQLException ex) {
12437 throw new TskCoreException(
"Error getting blackboard artifact tag with id = " + artifactTagID, ex);
12439 closeResultSet(resultSet);
12440 closeConnection(connection);
12459 CaseDbConnection connection = null;
12460 ResultSet resultSet = null;
12463 connection = connections.getConnection();
12470 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS_BY_ARTIFACT);
12471 statement.clearParameters();
12472 statement.setLong(1, artifact.getArtifactID());
12473 resultSet = connection.executeQuery(statement);
12474 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<>();
12475 while (resultSet.next()) {
12476 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12478 TskData.
FileKnown.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12481 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12485 }
catch (SQLException ex) {
12486 throw new TskCoreException(
"Error getting blackboard artifact tags data (artifact_id = " + artifact.getArtifactID() +
")", ex);
12488 closeResultSet(resultSet);
12489 closeConnection(connection);
12504 try (CaseDbConnection connection = connections.getConnection();) {
12506 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_PATH);
12507 statement.clearParameters();
12508 statement.setString(1, newPath);
12509 statement.setLong(2, objectId);
12510 connection.executeUpdate(statement);
12511 }
catch (SQLException ex) {
12512 throw new TskCoreException(
"Error updating image path in database for object " + objectId, ex);
12531 public Report addReport(String localPath, String sourceModuleName, String reportName)
throws TskCoreException {
12532 return addReport(localPath, sourceModuleName, reportName, null);
12553 String relativePath =
"";
12554 long createTime = 0;
12555 String localPathLower = localPath.toLowerCase();
12557 if (localPathLower.startsWith(
"http")) {
12558 relativePath = localPathLower;
12559 createTime = System.currentTimeMillis() / 1000;
12570 int length =
new File(casePathLower).toURI().relativize(
new File(localPathLower).toURI()).getPath().length();
12571 relativePath =
new File(localPath.substring(localPathLower.length() - length)).getPath();
12572 }
catch (IllegalArgumentException ex) {
12573 String errorMessage = String.format(
"Local path %s not in the database directory or one of its subdirectories", localPath);
12574 throw new TskCoreException(errorMessage, ex);
12578 java.io.File tempFile =
new java.io.File(localPath);
12580 createTime = tempFile.lastModified() / 1000;
12581 }
catch (Exception ex) {
12582 throw new TskCoreException(
"Could not get create time for report at " + localPath, ex);
12588 try (CaseDbConnection connection = connections.getConnection();) {
12591 long parentObjId = 0;
12592 if (parent != null) {
12593 parentObjId = parent.getId();
12598 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_REPORT);
12599 statement.clearParameters();
12600 statement.setLong(1, objectId);
12601 statement.setString(2, relativePath);
12602 statement.setLong(3, createTime);
12603 statement.setString(4, sourceModuleName);
12604 statement.setString(5, reportName);
12605 connection.executeUpdate(statement);
12606 return new Report(
this, objectId, localPath, createTime, sourceModuleName, reportName, parent);
12607 }
catch (SQLException ex) {
12608 throw new TskCoreException(
"Error adding report " + localPath +
" to reports table", ex);
12623 CaseDbConnection connection = null;
12624 ResultSet resultSet = null;
12625 ResultSet parentResultSet = null;
12626 PreparedStatement statement = null;
12627 Statement parentStatement = null;
12630 connection = connections.getConnection();
12633 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_REPORTS);
12634 parentStatement = connection.createStatement();
12635 resultSet = connection.executeQuery(statement);
12636 ArrayList<Report> reports =
new ArrayList<Report>();
12637 while (resultSet.next()) {
12638 String localpath = resultSet.getString(
"path");
12639 if (localpath.toLowerCase().startsWith(
"http") ==
false) {
12641 localpath = Paths.get(
getDbDirPath(), localpath).normalize().toString();
12646 long reportId = resultSet.getLong(
"obj_id");
12647 String parentQuery = String.format(
"SELECT * FROM tsk_objects WHERE obj_id = %s;", reportId);
12648 parentResultSet = parentStatement.executeQuery(parentQuery);
12649 if (parentResultSet.next()) {
12650 long parentId = parentResultSet.getLong(
"par_obj_id");
12653 parentResultSet.close();
12655 reports.add(
new Report(
this,
12658 resultSet.getLong(
"crtime"),
12659 resultSet.getString(
"src_module_name"),
12660 resultSet.getString(
"report_name"),
12664 }
catch (SQLException ex) {
12665 throw new TskCoreException(
"Error querying reports table", ex);
12667 closeResultSet(resultSet);
12668 closeResultSet(parentResultSet);
12669 closeStatement(statement);
12670 closeStatement(parentStatement);
12672 closeConnection(connection);
12687 CaseDbConnection connection = null;
12688 PreparedStatement statement = null;
12689 Statement parentStatement = null;
12690 ResultSet resultSet = null;
12691 ResultSet parentResultSet = null;
12695 connection = connections.getConnection();
12698 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_REPORT_BY_ID);
12699 parentStatement = connection.createStatement();
12700 statement.clearParameters();
12701 statement.setLong(1,
id);
12702 resultSet = connection.executeQuery(statement);
12704 if (resultSet.next()) {
12707 String parentQuery = String.format(
"SELECT * FROM tsk_objects WHERE obj_id = %s;",
id);
12708 parentResultSet = parentStatement.executeQuery(parentQuery);
12709 if (parentResultSet.next()) {
12710 long parentId = parentResultSet.getLong(
"par_obj_id");
12714 report =
new Report(
this, resultSet.getLong(
"obj_id"),
12715 Paths.get(
getDbDirPath(), resultSet.getString(
"path")).normalize().toString(),
12716 resultSet.getLong(
"crtime"),
12717 resultSet.getString(
"src_module_name"),
12718 resultSet.getString(
"report_name"),
12721 throw new TskCoreException(
"No report found for id: " +
id);
12723 }
catch (SQLException ex) {
12724 throw new TskCoreException(
"Error querying reports table for id: " +
id, ex);
12726 closeResultSet(resultSet);
12727 closeResultSet(parentResultSet);
12728 closeStatement(statement);
12729 closeStatement(parentStatement);
12730 closeConnection(connection);
12746 try (CaseDbConnection connection = connections.getConnection();) {
12748 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.DELETE_REPORT);
12749 statement.setLong(1, report.getId());
12750 connection.executeUpdate(statement);
12752 statement = connection.getPreparedStatement(PREPARED_STATEMENT.DELETE_REPORT_TSK_OBJECT);
12753 statement.setLong(1, report.getId());
12755 connection.executeUpdate(statement);
12756 }
catch (SQLException ex) {
12757 throw new TskCoreException(
"Error querying reports table", ex);
12763 static void closeResultSet(ResultSet resultSet) {
12764 if (resultSet != null) {
12767 }
catch (SQLException ex) {
12768 logger.log(Level.SEVERE,
"Error closing ResultSet", ex);
12773 static void closeStatement(Statement statement) {
12774 if (statement != null) {
12777 }
catch (SQLException ex) {
12778 logger.log(Level.SEVERE,
"Error closing Statement", ex);
12784 static void closeConnection(CaseDbConnection connection) {
12785 if (connection != null) {
12786 connection.close();
12790 private static void rollbackTransaction(CaseDbConnection connection) {
12791 if (connection != null) {
12792 connection.rollbackTransaction();
12804 void setIngestJobEndDateTime(
long ingestJobId,
long endDateTime)
throws TskCoreException {
12806 try (CaseDbConnection connection = connections.getConnection();) {
12807 Statement statement = connection.createStatement();
12808 statement.executeUpdate(
"UPDATE ingest_jobs SET end_date_time=" + endDateTime +
" WHERE ingest_job_id=" + ingestJobId +
";");
12809 }
catch (SQLException ex) {
12810 throw new TskCoreException(
"Error updating the end date (ingest_job_id = " + ingestJobId +
".", ex);
12816 void setIngestJobStatus(
long ingestJobId, IngestJobStatusType status)
throws TskCoreException {
12818 try (CaseDbConnection connection = connections.getConnection();
12819 Statement statement = connection.createStatement();) {
12820 statement.executeUpdate(
"UPDATE ingest_jobs SET status_id=" + status.ordinal() +
" WHERE ingest_job_id=" + ingestJobId +
";");
12821 }
catch (SQLException ex) {
12822 throw new TskCoreException(
"Error ingest job status (ingest_job_id = " + ingestJobId +
".", ex);
12845 CaseDbConnection connection = null;
12847 ResultSet resultSet = null;
12848 Statement statement;
12850 connection = connections.getConnection();
12851 connection.beginTransaction();
12852 statement = connection.createStatement();
12853 PreparedStatement insertStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_INGEST_JOB, Statement.RETURN_GENERATED_KEYS);
12854 insertStatement.setLong(1, dataSource.getId());
12855 insertStatement.setString(2, hostName);
12856 insertStatement.setLong(3, jobStart.getTime());
12857 insertStatement.setLong(4, jobEnd.getTime());
12858 insertStatement.setInt(5, status.ordinal());
12859 insertStatement.setString(6, settingsDir);
12860 connection.executeUpdate(insertStatement);
12861 resultSet = insertStatement.getGeneratedKeys();
12863 long id = resultSet.getLong(1);
12864 for (
int i = 0; i < ingestModules.size(); i++) {
12866 statement.executeUpdate(
"INSERT INTO ingest_job_modules (ingest_job_id, ingest_module_id, pipeline_position) "
12867 +
"VALUES (" +
id +
", " + ingestModule.
getIngestModuleId() +
", " + i +
");");
12871 connection.commitTransaction();
12872 return new IngestJobInfo(
id, dataSource.getId(), hostName, jobStart,
"", ingestModules,
this);
12873 }
catch (SQLException ex) {
12874 rollbackTransaction(connection);
12875 throw new TskCoreException(
"Error adding the ingest job.", ex);
12877 closeResultSet(resultSet);
12878 closeConnection(connection);
12897 CaseDbConnection connection = null;
12898 ResultSet resultSet = null;
12899 Statement statement = null;
12900 String uniqueName = factoryClassName +
"-" + displayName +
"-" + version;
12903 connection = connections.getConnection();
12904 statement = connection.createStatement();
12905 resultSet = statement.executeQuery(
"SELECT * FROM ingest_modules WHERE unique_name = '" + uniqueName +
"'");
12906 if (!resultSet.next()) {
12909 PreparedStatement insertStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_INGEST_MODULE, Statement.RETURN_GENERATED_KEYS);
12910 insertStatement.setString(1, displayName);
12911 insertStatement.setString(2, uniqueName);
12912 insertStatement.setInt(3, type.ordinal());
12913 insertStatement.setString(4, version);
12914 connection.executeUpdate(insertStatement);
12915 resultSet = statement.getGeneratedKeys();
12917 long id = resultSet.getLong(1);
12922 return new IngestModuleInfo(resultSet.getInt(
"ingest_module_id"), resultSet.getString(
"display_name"),
12923 resultSet.getString(
"unique_name"),
IngestModuleType.
fromID(resultSet.getInt(
"type_id")), resultSet.getString(
"version"));
12925 }
catch (SQLException ex) {
12927 closeStatement(statement);
12928 if (connection != null) {
12929 statement = connection.createStatement();
12930 resultSet = statement.executeQuery(
"SELECT * FROM ingest_modules WHERE unique_name = '" + uniqueName +
"'");
12931 if (resultSet.next()) {
12932 return new IngestModuleInfo(resultSet.getInt(
"ingest_module_id"), resultSet.getString(
"display_name"),
12936 throw new TskCoreException(
"Couldn't add new module to database.", ex);
12937 }
catch (SQLException ex1) {
12938 throw new TskCoreException(
"Couldn't add new module to database.", ex1);
12941 closeResultSet(resultSet);
12942 closeStatement(statement);
12943 closeConnection(connection);
12956 CaseDbConnection connection = null;
12957 ResultSet resultSet = null;
12958 Statement statement = null;
12959 List<IngestJobInfo> ingestJobs =
new ArrayList<>();
12962 connection = connections.getConnection();
12963 statement = connection.createStatement();
12964 resultSet = statement.executeQuery(
"SELECT * FROM ingest_jobs");
12965 while (resultSet.next()) {
12966 ingestJobs.add(
new IngestJobInfo(resultSet.getInt(
"ingest_job_id"), resultSet.getLong(
"obj_id"),
12967 resultSet.getString(
"host_name"),
new Date(resultSet.getLong(
"start_date_time")),
12969 resultSet.getString(
"settings_dir"), this.getIngestModules(resultSet.getInt(
"ingest_job_id"), connection),
this));
12972 }
catch (SQLException ex) {
12973 throw new TskCoreException(
"Couldn't get the ingest jobs.", ex);
12975 closeResultSet(resultSet);
12976 closeStatement(statement);
12977 closeConnection(connection);
12992 private List<IngestModuleInfo> getIngestModules(
int ingestJobId, CaseDbConnection connection)
throws SQLException {
12993 ResultSet resultSet = null;
12994 Statement statement = null;
12995 List<IngestModuleInfo> ingestModules =
new ArrayList<>();
12998 statement = connection.createStatement();
12999 resultSet = statement.executeQuery(
"SELECT ingest_job_modules.ingest_module_id AS ingest_module_id, "
13000 +
"ingest_job_modules.pipeline_position AS pipeline_position, "
13001 +
"ingest_modules.display_name AS display_name, ingest_modules.unique_name AS unique_name, "
13002 +
"ingest_modules.type_id AS type_id, ingest_modules.version AS version "
13003 +
"FROM ingest_job_modules, ingest_modules "
13004 +
"WHERE ingest_job_modules.ingest_job_id = " + ingestJobId +
" "
13005 +
"AND ingest_modules.ingest_module_id = ingest_job_modules.ingest_module_id "
13006 +
"ORDER BY (ingest_job_modules.pipeline_position);");
13007 while (resultSet.next()) {
13008 ingestModules.add(
new IngestModuleInfo(resultSet.getInt(
"ingest_module_id"), resultSet.getString(
"display_name"),
13009 resultSet.getString(
"unique_name"),
IngestModuleType.
fromID(resultSet.getInt(
"type_id")), resultSet.getString(
"version")));
13011 return ingestModules;
13013 closeResultSet(resultSet);
13014 closeStatement(statement);
13029 String getInsertOrIgnoreSQL(String sql) {
13032 return " INSERT " + sql +
" ON CONFLICT DO NOTHING ";
13034 return " INSERT OR IGNORE " + sql;
13036 throw new UnsupportedOperationException(
"Unsupported DB type: " +
getDatabaseType().name());
13060 private List<? extends BlackboardArtifact> getArtifactsForValues(BlackboardArtifact.Category category, String dbColumn, List<? extends Number> values, CaseDbConnection connection)
throws TskCoreException {
13064 for (Number value : values) {
13065 if (!where.isEmpty()) {
13068 where += dbColumn +
" = " + value;
13073 if (category == BlackboardArtifact.Category.DATA_ARTIFACT) {
13083 static class ObjectInfo {
13086 private TskData.ObjectType type;
13088 ObjectInfo(
long id, ObjectType type) {
13097 TskData.ObjectType getType() {
13102 private interface DbCommand {
13104 void execute() throws SQLException;
13107 private enum PREPARED_STATEMENT {
13109 SELECT_ARTIFACTS_BY_TYPE(
"SELECT artifact_id, obj_id FROM blackboard_artifacts "
13110 +
"WHERE artifact_type_id = ?"),
13111 COUNT_ARTIFACTS_OF_TYPE(
"SELECT COUNT(*) AS count FROM blackboard_artifacts WHERE artifact_type_id = ? AND review_status_id != " + BlackboardArtifact.ReviewStatus.REJECTED.getID()),
13112 COUNT_ARTIFACTS_OF_TYPE_BY_DATA_SOURCE(
"SELECT COUNT(*) AS count FROM blackboard_artifacts WHERE data_source_obj_id = ? AND artifact_type_id = ? AND review_status_id != " + BlackboardArtifact.ReviewStatus.REJECTED.getID()),
13113 COUNT_ARTIFACTS_FROM_SOURCE(
"SELECT COUNT(*) AS count FROM blackboard_artifacts WHERE obj_id = ? AND review_status_id != " + BlackboardArtifact.ReviewStatus.REJECTED.getID()),
13114 COUNT_ARTIFACTS_BY_SOURCE_AND_TYPE(
"SELECT COUNT(*) AS count FROM blackboard_artifacts WHERE obj_id = ? AND artifact_type_id = ? AND review_status_id != " + BlackboardArtifact.ReviewStatus.REJECTED.getID()),
13115 SELECT_FILES_BY_PARENT(
"SELECT tsk_files.* "
13116 +
"FROM tsk_objects INNER JOIN tsk_files "
13117 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13118 +
"WHERE (tsk_objects.par_obj_id = ? ) "
13119 +
"ORDER BY tsk_files.meta_type DESC, LOWER(tsk_files.name)"),
13120 SELECT_FILES_BY_PARENT_AND_TYPE(
"SELECT tsk_files.* "
13121 +
"FROM tsk_objects INNER JOIN tsk_files "
13122 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13123 +
"WHERE (tsk_objects.par_obj_id = ? AND tsk_files.type = ? ) "
13124 +
"ORDER BY tsk_files.dir_type, LOWER(tsk_files.name)"),
13125 SELECT_FILES_BY_PARENT_AND_NAME(
"SELECT tsk_files.* "
13126 +
"FROM tsk_objects INNER JOIN tsk_files "
13127 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13128 +
"WHERE (tsk_objects.par_obj_id = ? AND "
13129 +
"LOWER(tsk_files.name) LIKE LOWER(?) AND LOWER(tsk_files.name) NOT LIKE LOWER('%journal%')) "
13130 +
"ORDER BY tsk_files.dir_type, LOWER(tsk_files.name)"),
13131 SELECT_FILES_BY_EXTENSION_AND_PARENT_AND_NAME(
"SELECT tsk_files.* "
13132 +
"FROM tsk_objects INNER JOIN tsk_files "
13133 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13134 +
"WHERE tsk_files.extension = ? AND "
13135 +
"(tsk_objects.par_obj_id = ? AND "
13136 +
"LOWER(tsk_files.name) LIKE LOWER(?) AND LOWER(tsk_files.name) NOT LIKE LOWER('%journal%')) "
13137 +
"ORDER BY tsk_files.dir_type, LOWER(tsk_files.name)"),
13138 SELECT_FILE_IDS_BY_PARENT(
"SELECT tsk_files.obj_id AS obj_id "
13139 +
"FROM tsk_objects INNER JOIN tsk_files "
13140 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13141 +
"WHERE (tsk_objects.par_obj_id = ?)"),
13142 SELECT_FILE_IDS_BY_PARENT_AND_TYPE(
"SELECT tsk_files.obj_id AS obj_id "
13143 +
"FROM tsk_objects INNER JOIN tsk_files "
13144 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13145 +
"WHERE (tsk_objects.par_obj_id = ? "
13146 +
"AND tsk_files.type = ? )"),
13147 SELECT_FILE_BY_ID(
"SELECT * FROM tsk_files WHERE obj_id = ? LIMIT 1"),
13148 SELECT_ARTIFACT_BY_ARTIFACT_OBJ_ID(
"SELECT * FROM blackboard_artifacts WHERE artifact_obj_id = ? LIMIT 1"),
13149 SELECT_ARTIFACT_TYPE_BY_ARTIFACT_OBJ_ID(
"SELECT artifact_type_id FROM blackboard_artifacts WHERE artifact_obj_id = ? LIMIT 1"),
13150 SELECT_ARTIFACT_BY_ARTIFACT_ID(
"SELECT * FROM blackboard_artifacts WHERE artifact_id = ? LIMIT 1"),
13151 INSERT_ARTIFACT(
"INSERT INTO blackboard_artifacts (artifact_id, obj_id, artifact_obj_id, data_source_obj_id, artifact_type_id, review_status_id) "
13152 +
"VALUES (?, ?, ?, ?, ?," + BlackboardArtifact.ReviewStatus.UNDECIDED.getID() +
")"),
13153 POSTGRESQL_INSERT_ARTIFACT(
"INSERT INTO blackboard_artifacts (artifact_id, obj_id, artifact_obj_id, data_source_obj_id, artifact_type_id, review_status_id) "
13154 +
"VALUES (DEFAULT, ?, ?, ?, ?," + BlackboardArtifact.ReviewStatus.UNDECIDED.getID() +
")"),
13155 INSERT_ANALYSIS_RESULT(
"INSERT INTO tsk_analysis_results (artifact_obj_id, conclusion, significance, priority, configuration, justification) "
13156 +
"VALUES (?, ?, ?, ?, ?, ?)"),
13157 INSERT_STRING_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_text) "
13158 +
"VALUES (?,?,?,?,?,?,?)"),
13159 INSERT_BYTE_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_byte) "
13160 +
"VALUES (?,?,?,?,?,?,?)"),
13161 INSERT_INT_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_int32) "
13162 +
"VALUES (?,?,?,?,?,?,?)"),
13163 INSERT_LONG_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_int64) "
13164 +
"VALUES (?,?,?,?,?,?,?)"),
13165 INSERT_DOUBLE_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_double) "
13166 +
"VALUES (?,?,?,?,?,?,?)"),
13167 INSERT_FILE_ATTRIBUTE(
"INSERT INTO tsk_file_attributes (obj_id, attribute_type_id, value_type, value_byte, value_text, value_int32, value_int64, value_double) "
13168 +
"VALUES (?,?,?,?,?,?,?,?)"),
13169 SELECT_FILES_BY_DATA_SOURCE_AND_NAME(
"SELECT * FROM tsk_files WHERE LOWER(name) LIKE LOWER(?) AND LOWER(name) NOT LIKE LOWER('%journal%') AND data_source_obj_id = ?"),
13170 SELECT_FILES_BY_EXTENSION_AND_DATA_SOURCE_AND_NAME(
"SELECT * FROM tsk_files WHERE extension = ? AND LOWER(name) LIKE LOWER(?) AND LOWER(name) NOT LIKE LOWER('%journal%') AND data_source_obj_id = ?"),
13171 SELECT_FILES_BY_DATA_SOURCE_AND_PARENT_PATH_AND_NAME(
"SELECT * FROM tsk_files WHERE LOWER(name) LIKE LOWER(?) AND LOWER(name) NOT LIKE LOWER('%journal%') AND LOWER(parent_path) LIKE LOWER(?) AND data_source_obj_id = ?"),
13172 SELECT_FILES_BY_EXTENSION_AND_DATA_SOURCE_AND_PARENT_PATH_AND_NAME(
"SELECT * FROM tsk_files WHERE extension = ? AND LOWER(name) LIKE LOWER(?) AND LOWER(name) NOT LIKE LOWER('%journal%') AND LOWER(parent_path) LIKE LOWER(?) AND data_source_obj_id = ?"),
13173 UPDATE_FILE_MD5(
"UPDATE tsk_files SET md5 = ? WHERE obj_id = ?"),
13174 UPDATE_IMAGE_MD5(
"UPDATE tsk_image_info SET md5 = ? WHERE obj_id = ?"),
13175 UPDATE_IMAGE_SHA1(
"UPDATE tsk_image_info SET sha1 = ? WHERE obj_id = ?"),
13176 UPDATE_IMAGE_SHA256(
"UPDATE tsk_image_info SET sha256 = ? WHERE obj_id = ?"),
13177 SELECT_IMAGE_MD5(
"SELECT md5 FROM tsk_image_info WHERE obj_id = ?"),
13178 SELECT_IMAGE_SHA1(
"SELECT sha1 FROM tsk_image_info WHERE obj_id = ?"),
13179 SELECT_IMAGE_SHA256(
"SELECT sha256 FROM tsk_image_info WHERE obj_id = ?"),
13180 UPDATE_ACQUISITION_DETAILS(
"UPDATE data_source_info SET acquisition_details = ? WHERE obj_id = ?"),
13181 UPDATE_ACQUISITION_TOOL_SETTINGS(
"UPDATE data_source_info SET acquisition_tool_settings = ?, acquisition_tool_name = ?, acquisition_tool_version = ? WHERE obj_id = ?"),
13182 SELECT_ACQUISITION_DETAILS(
"SELECT acquisition_details FROM data_source_info WHERE obj_id = ?"),
13183 SELECT_ACQUISITION_TOOL_SETTINGS(
"SELECT acquisition_tool_settings, acquisition_tool_name, acquisition_tool_version, added_date_time FROM data_source_info WHERE obj_id = ?"),
13184 SELECT_LOCAL_PATH_FOR_FILE(
"SELECT path FROM tsk_files_path WHERE obj_id = ?"),
13185 SELECT_ENCODING_FOR_FILE(
"SELECT encoding_type FROM tsk_files_path WHERE obj_id = ?"),
13186 SELECT_LOCAL_PATH_AND_ENCODING_FOR_FILE(
"SELECT path, encoding_type FROM tsk_files_path WHERE obj_id = ?"),
13187 SELECT_PATH_FOR_FILE(
"SELECT parent_path FROM tsk_files WHERE obj_id = ?"),
13188 SELECT_FILE_NAME(
"SELECT name FROM tsk_files WHERE obj_id = ?"),
13189 SELECT_DERIVED_FILE(
"SELECT derived_id, rederive FROM tsk_files_derived WHERE obj_id = ?"),
13190 SELECT_FILE_DERIVATION_METHOD(
"SELECT tool_name, tool_version, other FROM tsk_files_derived_method WHERE derived_id = ?"),
13191 SELECT_MAX_OBJECT_ID(
"SELECT MAX(obj_id) AS max_obj_id FROM tsk_objects"),
13192 INSERT_OBJECT(
"INSERT INTO tsk_objects (par_obj_id, type) VALUES (?, ?)"),
13193 INSERT_FILE(
"INSERT INTO tsk_files (obj_id, fs_obj_id, name, type, has_path, dir_type, meta_type, dir_flags, meta_flags, size, ctime, crtime, atime, mtime, md5, sha256, sha1, known, mime_type, parent_path, data_source_obj_id, extension, owner_uid, os_account_obj_id, collected) "
13194 +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13195 INSERT_FILE_SYSTEM_FILE(
"INSERT INTO tsk_files(obj_id, fs_obj_id, data_source_obj_id, attr_type, attr_id, name, meta_addr, meta_seq, type, has_path, dir_type, meta_type, dir_flags, meta_flags, size, ctime, crtime, atime, mtime, md5, sha256, sha1, mime_type, parent_path, extension, owner_uid, os_account_obj_id, collected)"
13196 +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13197 UPDATE_DERIVED_FILE(
"UPDATE tsk_files SET type = ?, dir_type = ?, meta_type = ?, dir_flags = ?, meta_flags = ?, size= ?, ctime= ?, crtime= ?, atime= ?, mtime= ?, mime_type = ? "
13198 +
"WHERE obj_id = ?"),
13199 INSERT_LAYOUT_FILE(
"INSERT INTO tsk_file_layout (obj_id, byte_start, byte_len, sequence) "
13200 +
"VALUES (?, ?, ?, ?)"),
13201 INSERT_LOCAL_PATH(
"INSERT INTO tsk_files_path (obj_id, path, encoding_type) VALUES (?, ?, ?)"),
13202 UPDATE_LOCAL_PATH(
"UPDATE tsk_files_path SET path = ?, encoding_type = ? WHERE obj_id = ?"),
13203 COUNT_CHILD_OBJECTS_BY_PARENT(
"SELECT COUNT(obj_id) AS count FROM tsk_objects WHERE par_obj_id = ?"),
13204 SELECT_FILE_SYSTEM_BY_OBJECT(
"SELECT fs_obj_id from tsk_files WHERE obj_id=?"),
13205 SELECT_TAG_NAMES(
"SELECT * FROM tag_names"),
13206 SELECT_TAG_NAMES_IN_USE(
"SELECT * FROM tag_names "
13207 +
"WHERE tag_name_id IN "
13208 +
"(SELECT tag_name_id from content_tags UNION SELECT tag_name_id FROM blackboard_artifact_tags)"),
13209 SELECT_TAG_NAMES_IN_USE_BY_DATASOURCE(
"SELECT * FROM tag_names "
13210 +
"WHERE tag_name_id IN "
13211 +
"( SELECT content_tags.tag_name_id as tag_name_id "
13212 +
"FROM content_tags as content_tags, tsk_files as tsk_files"
13213 +
" WHERE content_tags.obj_id = tsk_files.obj_id"
13214 +
" AND tsk_files.data_source_obj_id = ?"
13216 +
"SELECT artifact_tags.tag_name_id as tag_name_id "
13217 +
" FROM blackboard_artifact_tags as artifact_tags, blackboard_artifacts AS arts "
13218 +
" WHERE artifact_tags.artifact_id = arts.artifact_id"
13219 +
" AND arts.data_source_obj_id = ?"
13221 INSERT_TAG_NAME(
"INSERT INTO tag_names (display_name, description, color, knownStatus) VALUES (?, ?, ?, ?)"),
13222 INSERT_CONTENT_TAG(
"INSERT INTO content_tags (obj_id, tag_name_id, comment, begin_byte_offset, end_byte_offset, examiner_id) VALUES (?, ?, ?, ?, ?, ?)"),
13223 DELETE_CONTENT_TAG(
"DELETE FROM content_tags WHERE tag_id = ?"),
13224 COUNT_CONTENT_TAGS_BY_TAG_NAME(
"SELECT COUNT(*) AS count FROM content_tags WHERE tag_name_id = ?"),
13225 COUNT_CONTENT_TAGS_BY_TAG_NAME_BY_DATASOURCE(
13226 "SELECT COUNT(*) AS count FROM content_tags as content_tags, tsk_files as tsk_files WHERE content_tags.obj_id = tsk_files.obj_id"
13227 +
" AND content_tags.tag_name_id = ? "
13228 +
" AND tsk_files.data_source_obj_id = ? "
13230 SELECT_CONTENT_TAGS(
"SELECT content_tags.tag_id, content_tags.obj_id, content_tags.tag_name_id, content_tags.comment, content_tags.begin_byte_offset, content_tags.end_byte_offset, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tsk_examiners.login_name, tag_names.tag_set_id, tag_names.rank "
13231 +
"FROM content_tags "
13232 +
"INNER JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13233 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id"),
13234 SELECT_CONTENT_TAGS_BY_TAG_NAME(
"SELECT content_tags.tag_id, content_tags.obj_id, content_tags.tag_name_id, content_tags.comment, content_tags.begin_byte_offset, content_tags.end_byte_offset, tsk_examiners.login_name "
13235 +
"FROM content_tags "
13236 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13237 +
"WHERE tag_name_id = ?"),
13238 SELECT_CONTENT_TAGS_BY_TAG_NAME_BY_DATASOURCE(
"SELECT content_tags.tag_id, content_tags.obj_id, content_tags.tag_name_id, content_tags.comment, content_tags.begin_byte_offset, content_tags.end_byte_offset, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tag_names.tag_set_id, tsk_examiners.login_name "
13239 +
"FROM content_tags "
13240 +
"JOIN tsk_os_accounts acc ON content_tags.obj_id = acc.os_account_obj_id "
13241 +
"JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13242 +
"JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13243 +
"WHERE content_tags.tag_name_id = ? "
13244 +
"AND acc.os_account_obj_id IN (SELECT os_account_obj_id FROM tsk_os_account_instances WHERE data_source_obj_id = ?) "
13245 +
"AND acc.db_status = " + OsAccount.OsAccountDbStatus.ACTIVE.getId()
13247 +
"SELECT content_tags.tag_id, content_tags.obj_id, content_tags.tag_name_id, content_tags.comment, content_tags.begin_byte_offset, content_tags.end_byte_offset, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tag_names.tag_set_id, tsk_examiners.login_name "
13248 +
"FROM content_tags as content_tags, tsk_files as tsk_files, tag_names as tag_names, tsk_examiners as tsk_examiners "
13249 +
"WHERE content_tags.examiner_id = tsk_examiners.examiner_id "
13250 +
"AND content_tags.obj_id = tsk_files.obj_id "
13251 +
"AND content_tags.tag_name_id = tag_names.tag_name_id "
13252 +
"AND content_tags.tag_name_id = ? "
13253 +
"AND tsk_files.data_source_obj_id = ? "),
13254 SELECT_CONTENT_TAG_BY_ID(
"SELECT content_tags.tag_id, content_tags.obj_id, content_tags.tag_name_id, content_tags.comment, content_tags.begin_byte_offset, content_tags.end_byte_offset, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tsk_examiners.login_name, tag_names.tag_set_id, tag_names.rank "
13255 +
"FROM content_tags "
13256 +
"INNER JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13257 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13258 +
"WHERE tag_id = ?"),
13259 SELECT_CONTENT_TAGS_BY_CONTENT(
"SELECT content_tags.tag_id, content_tags.obj_id, content_tags.tag_name_id, content_tags.comment, content_tags.begin_byte_offset, content_tags.end_byte_offset, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tsk_examiners.login_name, tag_names.tag_set_id, tag_names.rank "
13260 +
"FROM content_tags "
13261 +
"INNER JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13262 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13263 +
"WHERE content_tags.obj_id = ?"),
13264 INSERT_ARTIFACT_TAG(
"INSERT INTO blackboard_artifact_tags (artifact_id, tag_name_id, comment, examiner_id) "
13265 +
"VALUES (?, ?, ?, ?)"),
13266 DELETE_ARTIFACT_TAG(
"DELETE FROM blackboard_artifact_tags WHERE tag_id = ?"),
13267 SELECT_ARTIFACT_TAGS(
"SELECT blackboard_artifact_tags.tag_id, blackboard_artifact_tags.artifact_id, blackboard_artifact_tags.tag_name_id, blackboard_artifact_tags.comment, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tag_names.tag_set_id, tsk_examiners.login_name, tag_names.rank "
13268 +
"FROM blackboard_artifact_tags "
13269 +
"INNER JOIN tag_names ON blackboard_artifact_tags.tag_name_id = tag_names.tag_name_id "
13270 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id"),
13271 COUNT_ARTIFACTS_BY_TAG_NAME(
"SELECT COUNT(*) AS count FROM blackboard_artifact_tags WHERE tag_name_id = ?"),
13272 COUNT_ARTIFACTS_BY_TAG_NAME_BY_DATASOURCE(
"SELECT COUNT(*) AS count FROM blackboard_artifact_tags as artifact_tags, blackboard_artifacts AS arts WHERE artifact_tags.artifact_id = arts.artifact_id"
13273 +
" AND artifact_tags.tag_name_id = ?"
13274 +
" AND arts.data_source_obj_id = ? "),
13275 SELECT_ARTIFACT_TAGS_BY_TAG_NAME(
"SELECT blackboard_artifact_tags.tag_id, blackboard_artifact_tags.artifact_id, blackboard_artifact_tags.tag_name_id, blackboard_artifact_tags.comment, tsk_examiners.login_name "
13276 +
"FROM blackboard_artifact_tags "
13277 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id "
13278 +
"WHERE tag_name_id = ?"),
13279 SELECT_ARTIFACT_TAGS_BY_TAG_NAME_BY_DATASOURCE(
"SELECT artifact_tags.tag_id, artifact_tags.artifact_id, artifact_tags.tag_name_id, artifact_tags.comment, arts.obj_id, arts.artifact_obj_id, arts.data_source_obj_id, arts.artifact_type_id, arts.review_status_id, tsk_examiners.login_name "
13280 +
"FROM blackboard_artifact_tags as artifact_tags, blackboard_artifacts AS arts, tsk_examiners AS tsk_examiners "
13281 +
"WHERE artifact_tags.examiner_id = tsk_examiners.examiner_id"
13282 +
" AND artifact_tags.artifact_id = arts.artifact_id"
13283 +
" AND artifact_tags.tag_name_id = ? "
13284 +
" AND arts.data_source_obj_id = ? "),
13285 SELECT_ARTIFACT_TAG_BY_ID(
"SELECT blackboard_artifact_tags.tag_id, blackboard_artifact_tags.artifact_id, blackboard_artifact_tags.tag_name_id, blackboard_artifact_tags.comment, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tsk_examiners.login_name, tag_names.tag_set_id, tag_names.rank "
13286 +
"FROM blackboard_artifact_tags "
13287 +
"INNER JOIN tag_names ON blackboard_artifact_tags.tag_name_id = tag_names.tag_name_id "
13288 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id "
13289 +
"WHERE blackboard_artifact_tags.tag_id = ?"),
13290 SELECT_ARTIFACT_TAGS_BY_ARTIFACT(
"SELECT blackboard_artifact_tags.tag_id, blackboard_artifact_tags.artifact_id, blackboard_artifact_tags.tag_name_id, blackboard_artifact_tags.comment, tag_names.display_name, tag_names.description, tag_names.color, tag_names.knownStatus, tsk_examiners.login_name, tag_names.tag_set_id, tag_names.rank "
13291 +
"FROM blackboard_artifact_tags "
13292 +
"INNER JOIN tag_names ON blackboard_artifact_tags.tag_name_id = tag_names.tag_name_id "
13293 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id "
13294 +
"WHERE blackboard_artifact_tags.artifact_id = ?"),
13295 SELECT_REPORTS(
"SELECT * FROM reports"),
13296 SELECT_REPORT_BY_ID(
"SELECT * FROM reports WHERE obj_id = ?"),
13297 INSERT_REPORT(
"INSERT INTO reports (obj_id, path, crtime, src_module_name, report_name) VALUES (?, ?, ?, ?, ?)"),
13298 DELETE_REPORT(
"DELETE FROM reports WHERE reports.obj_id = ?"),
13299 DELETE_REPORT_TSK_OBJECT(
"DELETE FROM tsk_objects where tsk_objects.obj_id = ? and tsk_objects.type = ?"),
13300 INSERT_INGEST_JOB(
"INSERT INTO ingest_jobs (obj_id, host_name, start_date_time, end_date_time, status_id, settings_dir) VALUES (?, ?, ?, ?, ?, ?)"),
13301 INSERT_INGEST_MODULE(
"INSERT INTO ingest_modules (display_name, unique_name, type_id, version) VALUES(?, ?, ?, ?)"),
13302 SELECT_ATTR_BY_VALUE_BYTE(
"SELECT source FROM blackboard_attributes WHERE artifact_id = ? AND attribute_type_id = ? AND value_type = 4 AND value_byte = ?"),
13303 UPDATE_ATTR_BY_VALUE_BYTE(
"UPDATE blackboard_attributes SET source = ? WHERE artifact_id = ? AND attribute_type_id = ? AND value_type = 4 AND value_byte = ?"),
13304 UPDATE_IMAGE_PATH(
"UPDATE tsk_image_names SET name = ? WHERE obj_id = ?"),
13305 SELECT_ARTIFACT_OBJECTIDS_BY_PARENT(
"SELECT blackboard_artifacts.artifact_obj_id AS artifact_obj_id "
13306 +
"FROM tsk_objects INNER JOIN blackboard_artifacts "
13307 +
"ON tsk_objects.obj_id=blackboard_artifacts.obj_id "
13308 +
"WHERE (tsk_objects.par_obj_id = ?)"),
13309 SELECT_EXAMINER_BY_ID(
"SELECT * FROM tsk_examiners WHERE examiner_id = ?"),
13310 SELECT_EXAMINER_BY_LOGIN_NAME(
"SELECT * FROM tsk_examiners WHERE login_name = ?"),
13311 INSERT_EXAMINER_POSTGRESQL(
"INSERT INTO tsk_examiners (login_name) VALUES (?) ON CONFLICT DO NOTHING"),
13312 INSERT_EXAMINER_SQLITE(
"INSERT OR IGNORE INTO tsk_examiners (login_name) VALUES (?)"),
13313 UPDATE_FILE_NAME(
"UPDATE tsk_files SET name = ? WHERE obj_id = ?"),
13314 UPDATE_IMAGE_NAME(
"UPDATE tsk_image_info SET display_name = ? WHERE obj_id = ?"),
13315 UPDATE_IMAGE_SIZES(
"UPDATE tsk_image_info SET size = ?, ssize = ? WHERE obj_id = ?"),
13316 DELETE_IMAGE_NAME(
"DELETE FROM tsk_image_names WHERE obj_id = ?"),
13317 INSERT_IMAGE_NAME(
"INSERT INTO tsk_image_names (obj_id, name, sequence) VALUES (?, ?, ?)"),
13318 INSERT_IMAGE_INFO(
"INSERT INTO tsk_image_info (obj_id, type, ssize, tzone, size, md5, sha1, sha256, display_name)"
13319 +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13320 INSERT_DATA_SOURCE_INFO(
"INSERT INTO data_source_info (obj_id, device_id, time_zone, added_date_time, host_id) VALUES (?, ?, ?, ?, ?)"),
13321 INSERT_VS_INFO(
"INSERT INTO tsk_vs_info (obj_id, vs_type, img_offset, block_size) VALUES (?, ?, ?, ?)"),
13322 INSERT_VS_PART_SQLITE(
"INSERT INTO tsk_vs_parts (obj_id, addr, start, length, desc, flags) VALUES (?, ?, ?, ?, ?, ?)"),
13323 INSERT_VS_PART_POSTGRESQL(
"INSERT INTO tsk_vs_parts (obj_id, addr, start, length, descr, flags) VALUES (?, ?, ?, ?, ?, ?)"),
13324 INSERT_POOL_INFO(
"INSERT INTO tsk_pool_info (obj_id, pool_type) VALUES (?, ?)"),
13325 INSERT_FS_INFO(
"INSERT INTO tsk_fs_info (obj_id, data_source_obj_id, img_offset, fs_type, block_size, block_count, root_inum, first_inum, last_inum, display_name)"
13326 +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13327 SELECT_TAG_NAME_BY_ID(
"SELECT * FROM tag_names where tag_name_id = ?");
13329 private final String sql;
13331 private PREPARED_STATEMENT(String sql) {
13345 abstract private class ConnectionPool {
13347 private PooledDataSource pooledDataSource;
13349 public ConnectionPool() {
13350 pooledDataSource = null;
13353 CaseDbConnection getConnection() throws TskCoreException {
13354 if (pooledDataSource == null) {
13355 throw new TskCoreException(
"Error getting case database connection - case is closed");
13358 return getPooledConnection();
13359 }
catch (SQLException exp) {
13360 throw new TskCoreException(exp.getMessage());
13364 void close() throws TskCoreException {
13365 if (pooledDataSource != null) {
13367 pooledDataSource.close();
13368 }
catch (SQLException exp) {
13369 throw new TskCoreException(exp.getMessage());
13371 pooledDataSource = null;
13376 abstract CaseDbConnection getPooledConnection() throws SQLException;
13378 public PooledDataSource getPooledDataSource() {
13379 return pooledDataSource;
13382 public void setPooledDataSource(PooledDataSource pooledDataSource) {
13383 this.pooledDataSource = pooledDataSource;
13391 private final class SQLiteConnections
extends ConnectionPool {
13393 private final Map<String, String> configurationOverrides =
new HashMap<String, String>();
13395 SQLiteConnections(String dbPath)
throws SQLException {
13396 configurationOverrides.put(
"acquireIncrement",
"2");
13397 configurationOverrides.put(
"initialPoolSize",
"5");
13398 configurationOverrides.put(
"minPoolSize",
"5");
13403 configurationOverrides.put(
"maxPoolSize",
"20");
13404 configurationOverrides.put(
"maxStatements",
"200");
13405 configurationOverrides.put(
"maxStatementsPerConnection",
"20");
13407 SQLiteConfig config =
new SQLiteConfig();
13408 config.setSynchronous(SQLiteConfig.SynchronousMode.OFF);
13409 config.setReadUncommitted(
true);
13410 config.enforceForeignKeys(
true);
13411 SQLiteDataSource unpooled =
new SQLiteDataSource(config);
13412 unpooled.setUrl(
"jdbc:sqlite:" + dbPath);
13413 setPooledDataSource((PooledDataSource) DataSources.pooledDataSource(unpooled, configurationOverrides));
13417 public CaseDbConnection getPooledConnection() throws SQLException {
13419 if (CaseDbTransaction.hasOpenTransaction(Thread.currentThread().getId())) {
13421 if (!Thread.currentThread().getName().contains(
"ImageGallery")) {
13422 logger.log(Level.WARNING, String.format(
"Thread %s (ID = %d) already has an open transaction. New connection may encounter SQLITE_BUSY error. ", Thread.currentThread().getName(), Thread.currentThread().getId()),
new Throwable());
13425 return new SQLiteConnection(getPooledDataSource().getConnection());
13433 private final class PostgreSQLConnections
extends ConnectionPool {
13435 PostgreSQLConnections(CaseDbConnectionInfo info, String dbName)
throws PropertyVetoException, UnsupportedEncodingException {
13437 ComboPooledDataSource comboPooledDataSource =
new ComboPooledDataSource();
13438 comboPooledDataSource.setDriverClass(
"org.postgresql.Driver");
13440 String connectionURL =
"jdbc:postgresql://" + info.getHost() +
":" + Integer.valueOf(info.getPort()) +
"/"
13441 + URLEncoder.encode(dbName, StandardCharsets.UTF_8.toString());
13442 if (info.isSslEnabled()) {
13443 if (info.isSslVerify()) {
13444 if (info.getCustomSslValidationClassName().isBlank()) {
13445 connectionURL += CaseDatabaseFactory.SSL_VERIFY_DEFAULT_URL;
13448 connectionURL += CaseDatabaseFactory.getCustomPostrgesSslVerificationUrl(info.getCustomSslValidationClassName());
13451 connectionURL += CaseDatabaseFactory.SSL_NONVERIFY_URL;
13454 comboPooledDataSource.setJdbcUrl(connectionURL);
13455 comboPooledDataSource.setUser(info.getUserName());
13456 comboPooledDataSource.setPassword(info.getPassword());
13457 comboPooledDataSource.setAcquireIncrement(2);
13458 comboPooledDataSource.setInitialPoolSize(5);
13459 comboPooledDataSource.setMinPoolSize(5);
13464 comboPooledDataSource.setMaxPoolSize(20);
13465 comboPooledDataSource.setMaxStatements(200);
13466 comboPooledDataSource.setMaxStatementsPerConnection(20);
13467 setPooledDataSource(comboPooledDataSource);
13471 public CaseDbConnection getPooledConnection() throws SQLException {
13472 return new PostgreSQLConnection(getPooledDataSource().getConnection());
13479 abstract class CaseDbConnection
implements AutoCloseable {
13481 static final int SLEEP_LENGTH_IN_MILLISECONDS = 5000;
13482 static final int MAX_RETRIES = 20;
13484 private class CreateStatement
implements DbCommand {
13486 private final Connection connection;
13487 private Statement statement = null;
13489 CreateStatement(Connection connection) {
13490 this.connection = connection;
13493 Statement getStatement() {
13498 public void execute() throws SQLException {
13499 statement = connection.createStatement();
13503 private class SetAutoCommit
implements DbCommand {
13505 private final Connection connection;
13506 private final boolean mode;
13508 SetAutoCommit(Connection connection,
boolean mode) {
13509 this.connection = connection;
13514 public void execute() throws SQLException {
13515 connection.setAutoCommit(mode);
13519 private class Commit
implements DbCommand {
13521 private final Connection connection;
13523 Commit(Connection connection) {
13524 this.connection = connection;
13528 public void execute() throws SQLException {
13529 connection.commit();
13541 private class AggregateScoreTablePostgreSQLWriteLock
implements DbCommand {
13543 private final Connection connection;
13545 AggregateScoreTablePostgreSQLWriteLock(Connection connection) {
13546 this.connection = connection;
13550 public void execute() throws SQLException {
13551 PreparedStatement preparedStatement = connection.prepareStatement(
"LOCK TABLE ONLY tsk_aggregate_score in SHARE ROW EXCLUSIVE MODE");
13552 preparedStatement.execute();
13557 private class ExecuteQuery
implements DbCommand {
13559 private final Statement statement;
13560 private final String query;
13561 private ResultSet resultSet;
13563 ExecuteQuery(Statement statement, String query) {
13564 this.statement = statement;
13565 this.query = query;
13568 ResultSet getResultSet() {
13573 public void execute() throws SQLException {
13574 resultSet = statement.executeQuery(query);
13578 private class ExecutePreparedStatementQuery
implements DbCommand {
13580 private final PreparedStatement preparedStatement;
13581 private ResultSet resultSet;
13583 ExecutePreparedStatementQuery(PreparedStatement preparedStatement) {
13584 this.preparedStatement = preparedStatement;
13587 ResultSet getResultSet() {
13592 public void execute() throws SQLException {
13593 resultSet = preparedStatement.executeQuery();
13597 private class ExecutePreparedStatementUpdate
implements DbCommand {
13599 private final PreparedStatement preparedStatement;
13601 ExecutePreparedStatementUpdate(PreparedStatement preparedStatement) {
13602 this.preparedStatement = preparedStatement;
13606 public void execute() throws SQLException {
13607 preparedStatement.executeUpdate();
13611 private class ExecuteStatementUpdate
implements DbCommand {
13613 private final Statement statement;
13614 private final String updateCommand;
13616 ExecuteStatementUpdate(Statement statement, String updateCommand) {
13617 this.statement = statement;
13618 this.updateCommand = updateCommand;
13622 public void execute() throws SQLException {
13623 statement.executeUpdate(updateCommand);
13627 private class ExecuteStatementUpdateGenerateKeys
implements DbCommand {
13629 private final Statement statement;
13630 private final int generateKeys;
13631 private final String updateCommand;
13633 ExecuteStatementUpdateGenerateKeys(Statement statement, String updateCommand,
int generateKeys) {
13634 this.statement = statement;
13635 this.generateKeys = generateKeys;
13636 this.updateCommand = updateCommand;
13640 public void execute() throws SQLException {
13641 statement.executeUpdate(updateCommand, generateKeys);
13645 private class PrepareStatement
implements DbCommand {
13647 private final Connection connection;
13648 private final String input;
13649 private PreparedStatement preparedStatement = null;
13651 PrepareStatement(Connection connection, String input) {
13652 this.connection = connection;
13653 this.input = input;
13656 PreparedStatement getPreparedStatement() {
13657 return preparedStatement;
13661 public void execute() throws SQLException {
13662 preparedStatement = connection.prepareStatement(input);
13666 private class PrepareStatementGenerateKeys
implements DbCommand {
13668 private final Connection connection;
13669 private final String input;
13670 private final int generateKeys;
13671 private PreparedStatement preparedStatement = null;
13673 PrepareStatementGenerateKeys(Connection connection, String input,
int generateKeysInput) {
13674 this.connection = connection;
13675 this.input = input;
13676 this.generateKeys = generateKeysInput;
13679 PreparedStatement getPreparedStatement() {
13680 return preparedStatement;
13684 public void execute() throws SQLException {
13685 preparedStatement = connection.prepareStatement(input, generateKeys);
13689 abstract void executeCommand(DbCommand command)
throws SQLException;
13691 private final Connection connection;
13692 private final Map<PREPARED_STATEMENT, PreparedStatement> preparedStatements;
13693 private final Map<String, PreparedStatement> adHocPreparedStatements;
13695 CaseDbConnection(Connection connection) {
13696 this.connection = connection;
13697 preparedStatements =
new EnumMap<PREPARED_STATEMENT, PreparedStatement>(PREPARED_STATEMENT.class);
13698 adHocPreparedStatements =
new HashMap<>();
13702 return this.connection != null;
13705 PreparedStatement getPreparedStatement(PREPARED_STATEMENT statementKey)
throws SQLException {
13706 return getPreparedStatement(statementKey, Statement.NO_GENERATED_KEYS);
13709 PreparedStatement getPreparedStatement(PREPARED_STATEMENT statementKey,
int generateKeys)
throws SQLException {
13711 PreparedStatement statement;
13712 if (this.preparedStatements.containsKey(statementKey)) {
13713 statement = this.preparedStatements.get(statementKey);
13715 statement = prepareStatement(statementKey.getSQL(), generateKeys);
13716 this.preparedStatements.put(statementKey, statement);
13732 PreparedStatement getPreparedStatement(String sqlStatement,
int generateKeys)
throws SQLException {
13733 PreparedStatement statement;
13734 String statementKey =
"SQL:" + sqlStatement +
" Key:" + generateKeys;
13735 if (adHocPreparedStatements.containsKey(statementKey) && !adHocPreparedStatements.get(statementKey).isClosed()) {
13736 statement = this.adHocPreparedStatements.get(statementKey);
13738 statement = prepareStatement(sqlStatement, generateKeys);
13739 this.adHocPreparedStatements.put(statementKey, statement);
13744 PreparedStatement prepareStatement(String sqlStatement,
int generateKeys)
throws SQLException {
13745 PrepareStatement prepareStatement =
new PrepareStatement(this.getConnection(), sqlStatement);
13746 executeCommand(prepareStatement);
13747 return prepareStatement.getPreparedStatement();
13750 Statement createStatement() throws SQLException {
13751 CreateStatement createStatement =
new CreateStatement(this.connection);
13752 executeCommand(createStatement);
13753 return createStatement.getStatement();
13757 SetAutoCommit setAutoCommit =
new SetAutoCommit(connection,
false);
13758 executeCommand(setAutoCommit);
13761 void commitTransaction() throws SQLException {
13762 Commit commit =
new Commit(connection);
13763 executeCommand(commit);
13765 SetAutoCommit setAutoCommit =
new SetAutoCommit(connection,
true);
13766 executeCommand(setAutoCommit);
13774 void rollbackTransaction() {
13776 connection.rollback();
13777 }
catch (SQLException e) {
13778 logger.log(Level.SEVERE,
"Error rolling back transaction", e);
13781 connection.setAutoCommit(
true);
13782 }
catch (SQLException e) {
13783 logger.log(Level.SEVERE,
"Error restoring auto-commit", e);
13794 void rollbackTransactionWithThrow() throws SQLException {
13796 connection.rollback();
13798 connection.setAutoCommit(
true);
13810 void getAggregateScoreTableWriteLock() throws SQLException, TskCoreException {
13813 AggregateScoreTablePostgreSQLWriteLock tableWriteLock =
new AggregateScoreTablePostgreSQLWriteLock(connection);
13814 executeCommand(tableWriteLock);
13821 throw new TskCoreException(
"Unknown DB Type: " +
getDatabaseType().name());
13825 ResultSet
executeQuery(Statement statement, String query)
throws SQLException {
13826 ExecuteQuery queryCommand =
new ExecuteQuery(statement, query);
13827 executeCommand(queryCommand);
13828 return queryCommand.getResultSet();
13840 ResultSet
executeQuery(PreparedStatement statement)
throws SQLException {
13841 ExecutePreparedStatementQuery executePreparedStatementQuery =
new ExecutePreparedStatementQuery(statement);
13842 executeCommand(executePreparedStatementQuery);
13843 return executePreparedStatementQuery.getResultSet();
13846 void executeUpdate(Statement statement, String update)
throws SQLException {
13847 executeUpdate(statement, update, Statement.NO_GENERATED_KEYS);
13850 void executeUpdate(Statement statement, String update,
int generateKeys)
throws SQLException {
13851 ExecuteStatementUpdate executeStatementUpdate =
new ExecuteStatementUpdate(statement, update);
13852 executeCommand(executeStatementUpdate);
13855 void executeUpdate(PreparedStatement statement)
throws SQLException {
13856 ExecutePreparedStatementUpdate executePreparedStatementUpdate =
new ExecutePreparedStatementUpdate(statement);
13857 executeCommand(executePreparedStatementUpdate);
13864 public void close() {
13866 for (PreparedStatement stmt : preparedStatements.values()) {
13867 closeStatement(stmt);
13869 for (PreparedStatement stmt : adHocPreparedStatements.values()) {
13870 closeStatement(stmt);
13872 connection.close();
13873 }
catch (SQLException ex) {
13874 logger.log(Level.SEVERE,
"Unable to close connection to case database", ex);
13878 Connection getConnection() {
13879 return this.connection;
13886 private final class SQLiteConnection
extends CaseDbConnection {
13888 private static final int DATABASE_LOCKED_ERROR = 0;
13889 private static final int SQLITE_BUSY_ERROR = 5;
13891 SQLiteConnection(Connection conn) {
13896 void executeCommand(DbCommand command)
throws SQLException {
13897 int retryCounter = 0;
13902 }
catch (SQLException ex) {
13903 if ((ex.getErrorCode() == SQLITE_BUSY_ERROR || ex.getErrorCode() == DATABASE_LOCKED_ERROR) && retryCounter < MAX_RETRIES) {
13910 Thread.sleep(SLEEP_LENGTH_IN_MILLISECONDS);
13911 }
catch (InterruptedException exp) {
13912 Logger.getLogger(SleuthkitCase.class.getName()).log(Level.WARNING,
"Unexpectedly unable to wait for database.", exp);
13925 private final class PostgreSQLConnection
extends CaseDbConnection {
13927 private final String COMMUNICATION_ERROR = PSQLState.COMMUNICATION_ERROR.getState();
13928 private final String SYSTEM_ERROR = PSQLState.SYSTEM_ERROR.getState();
13929 private final String UNKNOWN_STATE = PSQLState.UNKNOWN_STATE.getState();
13930 private static final int MAX_RETRIES = 3;
13932 PostgreSQLConnection(Connection conn) {
13937 void executeUpdate(Statement statement, String update,
int generateKeys)
throws SQLException {
13938 CaseDbConnection.ExecuteStatementUpdateGenerateKeys executeStatementUpdateGenerateKeys =
new CaseDbConnection.ExecuteStatementUpdateGenerateKeys(statement, update, generateKeys);
13939 executeCommand(executeStatementUpdateGenerateKeys);
13943 PreparedStatement prepareStatement(String sqlStatement,
int generateKeys)
throws SQLException {
13944 CaseDbConnection.PrepareStatementGenerateKeys prepareStatementGenerateKeys =
new CaseDbConnection.PrepareStatementGenerateKeys(this.getConnection(), sqlStatement, generateKeys);
13945 executeCommand(prepareStatementGenerateKeys);
13946 return prepareStatementGenerateKeys.getPreparedStatement();
13950 void executeCommand(DbCommand command)
throws SQLException {
13951 SQLException lastException = null;
13952 for (
int retries = 0; retries < MAX_RETRIES; retries++) {
13955 lastException = null;
13957 }
catch (SQLException ex) {
13958 lastException = ex;
13959 String sqlState = ex.getSQLState();
13960 if (sqlState == null || sqlState.equals(COMMUNICATION_ERROR) || sqlState.equals(SYSTEM_ERROR) || sqlState.equals(UNKNOWN_STATE)) {
13962 Thread.sleep(SLEEP_LENGTH_IN_MILLISECONDS);
13963 }
catch (InterruptedException exp) {
13964 Logger.getLogger(SleuthkitCase.class.getName()).log(Level.WARNING,
"Unexpectedly unable to wait for database.", exp);
13973 if (lastException != null) {
13974 throw lastException;
14012 private final CaseDbConnection connection;
14020 private Map<Long, ScoreChange> scoreChangeMap =
new HashMap<>();
14021 private List<Host> hostsAdded =
new ArrayList<>();
14022 private List<TimelineEventAddedEvent> timelineEvents =
new ArrayList<>();
14023 private List<OsAccount> accountsChanged =
new ArrayList<>();
14024 private List<OsAccount> accountsAdded =
new ArrayList<>();
14027 private List<Long> deletedOsAccountObjectIds =
new ArrayList<>();
14028 private List<Long> deletedResultObjectIds =
new ArrayList<>();
14031 private static Set<Long> threadsWithOpenTransaction =
new HashSet<>();
14032 private static final Object threadsWithOpenTransactionLock =
new Object();
14035 this.sleuthkitCase = sleuthkitCase;
14038 this.connection = sleuthkitCase.getConnection();
14040 synchronized (threadsWithOpenTransactionLock) {
14041 this.connection.beginTransaction();
14042 threadsWithOpenTransaction.add(Thread.currentThread().getId());
14044 }
catch (SQLException ex) {
14046 throw new TskCoreException(
"Failed to create transaction on case database", ex);
14058 CaseDbConnection getConnection() {
14059 return this.connection;
14067 void registerScoreChange(
ScoreChange scoreChange) {
14068 scoreChangeMap.put(scoreChange.
getObjectId(), scoreChange);
14076 if (timelineEvent != null) {
14077 timelineEvents.add(timelineEvent);
14086 void registerAddedHost(
Host host) {
14087 if (host != null) {
14088 this.hostsAdded.add(host);
14097 void registerChangedOsAccount(
OsAccount account) {
14098 if (account != null) {
14099 accountsChanged.add(account);
14108 void registerDeletedOsAccount(
long osAccountObjId) {
14109 deletedOsAccountObjectIds.add(osAccountObjId);
14117 void registerAddedOsAccount(
OsAccount account) {
14118 if (account != null) {
14119 accountsAdded.add(account);
14129 void registerMergedOsAccount(
long sourceOsAccountObjId,
long destinationOsAccountObjId) {
14139 void registerDeletedAnalysisResult(
long analysisResultObjId) {
14140 this.deletedResultObjectIds.add(analysisResultObjId);
14151 private static boolean hasOpenTransaction(
long threadId) {
14152 synchronized (threadsWithOpenTransactionLock) {
14153 return threadsWithOpenTransaction.contains(threadId);
14165 this.connection.commitTransaction();
14166 }
catch (SQLException ex) {
14167 throw new TskCoreException(
"Failed to commit transaction on case database", ex);
14171 if (!scoreChangeMap.isEmpty()) {
14172 Map<Long, List<ScoreChange>> changesByDataSource = scoreChangeMap.values().stream()
14174 for (Map.Entry<Long, List<ScoreChange>> entry : changesByDataSource.entrySet()) {
14178 if (!timelineEvents.isEmpty()) {
14180 sleuthkitCase.fireTSKEvent(evt);
14183 if (!hostsAdded.isEmpty()) {
14186 if (!accountsAdded.isEmpty()) {
14189 if (!accountsChanged.isEmpty()) {
14192 if (!accountsMerged.isEmpty()) {
14195 if (!deletedOsAccountObjectIds.isEmpty()) {
14198 if (!deletedResultObjectIds.isEmpty()) {
14212 this.connection.rollbackTransactionWithThrow();
14213 }
catch (SQLException ex) {
14214 throw new TskCoreException(
"Case database transaction rollback failed", ex);
14225 this.connection.close();
14227 synchronized (threadsWithOpenTransactionLock) {
14228 threadsWithOpenTransaction.remove(Thread.currentThread().getId());
14244 private ResultSet resultSet;
14245 private CaseDbConnection connection;
14247 private CaseDbQuery(String query)
throws TskCoreException {
14248 this(query,
false);
14251 private CaseDbQuery(String query,
boolean allowWriteQuery)
throws TskCoreException {
14252 if (!allowWriteQuery) {
14253 if (!query.regionMatches(
true, 0,
"SELECT", 0,
"SELECT".length())) {
14254 throw new TskCoreException(
"Unsupported query: Only SELECT queries are supported.");
14260 connection = connections.getConnection();
14261 resultSet = connection.executeQuery(connection.createStatement(), query);
14262 }
catch (SQLException ex) {
14264 throw new TskCoreException(
"Error executing query: ", ex);
14265 }
catch (TskCoreException ex) {
14281 public void close() throws TskCoreException {
14283 if (resultSet != null) {
14284 final Statement statement = resultSet.getStatement();
14285 if (statement != null) {
14290 closeConnection(connection);
14291 }
catch (SQLException ex) {
14292 throw new TskCoreException(
"Error closing query: ", ex);
14308 sleuthkitCaseErrorObservers.add(observer);
14320 int i = sleuthkitCaseErrorObservers.indexOf(observer);
14322 sleuthkitCaseErrorObservers.remove(i);
14336 for (
ErrorObserver observer : sleuthkitCaseErrorObservers) {
14337 if (observer != null) {
14339 observer.receiveError(context, errorMessage);
14340 }
catch (Exception ex) {
14341 logger.log(Level.SEVERE,
"Observer client unable to receive message: {0}, {1}",
new Object[]{context, errorMessage, ex});
14373 private final String contextString;
14375 private Context(String context) {
14376 this.contextString = context;
14380 return contextString;
14384 void receiveError(String context, String errorMessage);
14398 long getDataSourceObjectId(
long objectId) {
14400 CaseDbConnection connection = connections.getConnection();
14402 return getDataSourceObjectId(connection, objectId);
14404 closeConnection(connection);
14406 }
catch (TskCoreException ex) {
14407 logger.log(Level.SEVERE,
"Error getting data source object id for a file", ex);
14423 CaseDbConnection connection = null;
14424 ResultSet rs = null;
14427 connection = connections.getConnection();
14430 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_MAX_OBJECT_ID);
14431 rs = connection.executeQuery(statement);
14434 id = rs.getLong(
"max_obj_id");
14437 }
catch (SQLException e) {
14438 throw new TskCoreException(
"Error getting last object id", e);
14440 closeResultSet(rs);
14441 closeConnection(connection);
14461 CaseDbConnection connection = null;
14462 Statement s = null;
14463 ResultSet rs = null;
14466 connection = connections.getConnection();
14467 s = connection.createStatement();
14468 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE " + sqlWhereClause);
14469 List<FsContent> results =
new ArrayList<FsContent>();
14470 List<AbstractFile> temp = resultSetToAbstractFiles(rs, connection);
14471 for (AbstractFile f : temp) {
14474 results.add((FsContent) f);
14478 }
catch (SQLException e) {
14479 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findFilesWhere().", e);
14481 closeResultSet(rs);
14483 closeConnection(connection);
14501 CaseDbConnection connection = null;
14502 Statement s = null;
14503 ResultSet rs = null;
14506 connection = connections.getConnection();
14507 s = connection.createStatement();
14508 rs = connection.executeQuery(s,
"SELECT artifact_type_id FROM blackboard_artifact_types WHERE type_name = '" + artifactTypeName +
"'");
14511 typeId = rs.getInt(
"artifact_type_id");
14514 }
catch (SQLException ex) {
14515 throw new TskCoreException(
"Error getting artifact type id", ex);
14517 closeResultSet(rs);
14519 closeConnection(connection);
14552 public int addArtifactType(String artifactTypeName, String displayName)
throws TskCoreException {
14555 }
catch (TskDataException ex) {
14556 throw new TskCoreException(
"Failed to add artifact type.", ex);
14574 public int addAttrType(String attrTypeString, String displayName)
throws TskCoreException {
14577 }
catch (TskDataException ex) {
14578 throw new TskCoreException(
"Couldn't add new attribute type");
14594 CaseDbConnection connection = null;
14595 Statement s = null;
14596 ResultSet rs = null;
14599 connection = connections.getConnection();
14600 s = connection.createStatement();
14601 rs = connection.executeQuery(s,
"SELECT attribute_type_id FROM blackboard_attribute_types WHERE type_name = '" + attrTypeName +
"'");
14604 typeId = rs.getInt(
"attribute_type_id");
14607 }
catch (SQLException ex) {
14608 throw new TskCoreException(
"Error getting attribute type id", ex);
14610 closeResultSet(rs);
14612 closeConnection(connection);
14631 CaseDbConnection connection = null;
14632 Statement s = null;
14633 ResultSet rs = null;
14636 connection = connections.getConnection();
14637 s = connection.createStatement();
14638 rs = connection.executeQuery(s,
"SELECT type_name FROM blackboard_attribute_types WHERE attribute_type_id = " + attrTypeID);
14640 return rs.getString(
"type_name");
14642 throw new TskCoreException(
"No type with that id");
14644 }
catch (SQLException ex) {
14645 throw new TskCoreException(
"Error getting or creating a attribute type name", ex);
14647 closeResultSet(rs);
14649 closeConnection(connection);
14668 CaseDbConnection connection = null;
14669 Statement s = null;
14670 ResultSet rs = null;
14673 connection = connections.getConnection();
14674 s = connection.createStatement();
14675 rs = connection.executeQuery(s,
"SELECT display_name FROM blackboard_attribute_types WHERE attribute_type_id = " + attrTypeID);
14677 return rs.getString(
"display_name");
14679 throw new TskCoreException(
"No type with that id");
14681 }
catch (SQLException ex) {
14682 throw new TskCoreException(
"Error getting or creating a attribute type name", ex);
14684 closeResultSet(rs);
14686 closeConnection(connection);
14721 public ResultSet
runQuery(String query)
throws SQLException {
14722 CaseDbConnection connection = null;
14725 connection = connections.getConnection();
14726 return connection.executeQuery(connection.createStatement(), query);
14727 }
catch (TskCoreException ex) {
14728 throw new SQLException(
"Error getting connection for ad hoc query", ex);
14732 closeConnection(connection);
14748 final Statement statement = resultSet.getStatement();
14750 if (statement != null) {
14772 public LayoutFile addCarvedFile(String carvedFileName,
long carvedFileSize,
long containerId, List<TskFileRange> data)
throws TskCoreException {
14775 files.add(carvedFile);
14779 || parent instanceof
Volume
14780 || parent instanceof
Image) {
14783 throw new TskCoreException(String.format(
"Parent (id =%d) is not an file system, volume or image", containerId));
14802 public List<LayoutFile>
addCarvedFiles(List<CarvedFileContainer> filesToAdd)
throws TskCoreException {
14806 carvedFiles.add(carvedFile);
14811 || parent instanceof
Volume
14812 || parent instanceof
Image) {
14815 throw new TskCoreException(String.format(
"Parent (id =%d) is not an file system, volume or image", parent.
getId()));
14851 long size,
long ctime,
long crtime,
long atime,
long mtime,
14852 boolean isFile, AbstractFile parentFile,
14853 String rederiveDetails, String toolName, String toolVersion, String otherDetails)
throws TskCoreException {
14854 return addDerivedFile(fileName, localPath, size, ctime, crtime, atime, mtime,
14855 isFile, parentFile, rederiveDetails, toolName, toolVersion,
14890 long size,
long ctime,
long crtime,
long atime,
long mtime,
14891 String md5,
FileKnown known, String mimeType,
14895 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime,
14896 md5, null, known, mimeType, isFile, encodingType,
14897 parent, transaction);
14926 long size,
long ctime,
long crtime,
long atime,
long mtime,
14929 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime, isFile,
14954 long size,
long ctime,
long crtime,
long atime,
long mtime,
14956 AbstractFile parent)
throws TskCoreException {
14957 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime,
14979 return this.caseHandle.initAddImageProcess(timezone, addUnallocSpace, noFatFsOrphans,
"",
this);
14996 }
catch (TskCoreException ex) {
14997 logger.log(Level.SEVERE,
"Error loading all file systems for image with ID {0}", image.
getId());
14998 return new ArrayList<>();
15020 public List<AbstractFile>
findFiles(
Content dataSource, String fileName, AbstractFile parentFile)
throws TskCoreException {
Image addImageInfo(long deviceObjId, List< String > imageFilePaths, String timeZone, Host host)
List< BlackboardArtifact > getBlackboardArtifacts(BlackboardAttribute.ATTRIBUTE_TYPE attrType, long value)
final IngestJobInfo addIngestJob(Content dataSource, String hostName, List< IngestModuleInfo > ingestModules, Date jobStart, Date jobEnd, IngestJobStatusType status, String settingsDir)
static SleuthkitCase newCase(String dbPath, ContentStreamProvider contentProvider)
static Priority fromID(int id)
static ARTIFACT_TYPE fromID(int id)
FS
File that can be found in file system tree.
static FileKnown valueOf(byte known)
TagName addOrUpdateTagName(String displayName, String description, TagName.HTML_COLOR color, TskData.FileKnown knownStatus)
static Significance fromID(int id)
BlackboardArtifact getArtifactByArtifactId(long id)
AddImageProcess makeAddImageProcess(String timezone, boolean addUnallocSpace, boolean noFatFsOrphans)
BlackboardArtifact getArtifactById(long id)
List< Report > getAllReports()
ArrayList< BlackboardAttribute > getBlackboardAttributes(final BlackboardArtifact artifact)
long getBlackboardArtifactsCount(long objId)
int getArtifactTypeID(String artifactTypeName)
Host getHostByDataSource(DataSource dataSource)
long getBlackboardArtifactTagsCountByTagName(TagName tagName)
ArrayList< BlackboardArtifact > getBlackboardArtifacts(ARTIFACT_TYPE artifactType)
LocalDirectory addLocalDirectory(long parentId, String directoryName, CaseDbTransaction transaction)
ArrayList< BlackboardArtifact > getBlackboardArtifacts(String artifactTypeName)
List< BlackboardArtifact > getBlackboardArtifacts(BlackboardAttribute.ATTRIBUTE_TYPE attrType, int value)
void addBlackboardAttributes(Collection< BlackboardAttribute > attributes, int artifactTypeId)
Optional< HostAddress > getHostAddress(HostAddress.HostAddressType type, String address)
ArrayList< BlackboardArtifact > getBlackboardArtifacts(int artifactTypeID, long obj_id)
static final Score SCORE_UNKNOWN
CommunicationsManager getCommunicationsManager()
AnalysisResult getAnalysisResultById(long artifactObjId)
static Set< TSK_FS_META_FLAG_ENUM > valuesOf(short metaFlags)
DerivedFile addDerivedFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, AbstractFile parentFile, String rederiveDetails, String toolName, String toolVersion, String otherDetails)
CaseDbTransaction beginTransaction()
OsAccount getOsAccountByObjectId(long osAccountObjId)
boolean isCompatible(CaseDbSchemaVersionNumber dbSchemaVersion)
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, AbstractFile parent)
ALLOC
Metadata structure is currently in an allocated state.
int countFilesMd5Hashed()
static TSK_FS_TYPE_ENUM valueOf(int fsTypeValue)
CaseDbSchemaVersionNumber getDBSchemaCreationVersion()
ArrayList< BlackboardArtifact > getBlackboardArtifacts(int artifactTypeID)
void addErrorObserver(ErrorObserver observer)
DerivedFile updateDerivedFile(DerivedFile derivedFile, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, String mimeType, String rederiveDetails, String toolName, String toolVersion, String otherDetails, TskData.EncodingType encodingType, Content parentObj, CaseDbTransaction trans)
DerivedFile updateDerivedFile(DerivedFile derivedFile, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, String mimeType, String rederiveDetails, String toolName, String toolVersion, String otherDetails, TskData.EncodingType encodingType)
Blackboard getBlackboard()
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, String md5, FileKnown known, String mimeType, boolean isFile, TskData.EncodingType encodingType, Content parent, CaseDbTransaction transaction)
TSK_FS_META_TYPE_DIR
Directory file NON-NLS.
List< AbstractFile > findFiles(Content dataSource, String fileName, AbstractFile parentFile)
synchronized void close()
static Category fromID(int id)
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, String md5, String sha256, String sha1Hash, FileKnown known, String mimeType, boolean isFile, TskData.EncodingType encodingType, Long osAccountId, String ownerAccount, Content parent, CaseDbTransaction transaction)
TagName addOrUpdateTagName(String displayName, String description, TagName.HTML_COLOR color, TskData.FileKnown knownStatus)
void setFileMIMEType(AbstractFile file, String mimeType)
UNALLOC
Metadata structure is currently in an unallocated state.
DataArtifact newDataArtifact(BlackboardArtifact.Type artifactType, long sourceObjId, Long dataSourceObjId, Collection< BlackboardAttribute > attributes, Long osAccountId)
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, String md5, String sha256, FileKnown known, String mimeType, boolean isFile, TskData.EncodingType encodingType, Long osAccountId, String ownerAccount, Content parent, CaseDbTransaction transaction)
void addBlackboardAttribute(BlackboardAttribute attr, int artifactTypeId)
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, AbstractFile parent, CaseDbTransaction transaction)
DataArtifact newDataArtifact(BlackboardArtifact.Type artifactType, Collection< BlackboardAttribute > attributesList)
final List< LayoutFile > addLayoutFiles(Content parent, List< TskFileRange > fileRanges)
ArrayList< BlackboardAttribute > getBlackboardAttributes(final BlackboardArtifact artifact)
int addArtifactType(String artifactTypeName, String displayName)
List< DataSource > getDataSources()
BlackboardArtifactTagChange addArtifactTag(BlackboardArtifact artifact, TagName tagName, String comment)
synchronized CaseDbAccessManager getCaseDbAccessManager()
DataArtifact getDataArtifactById(long artifactObjId)
BlackboardArtifactTag getBlackboardArtifactTagByID(long artifactTagID)
List< BlackboardArtifact > getBlackboardArtifacts(BlackboardAttribute.ATTRIBUTE_TYPE attrType, double value)
List< AbstractFile > openFiles(Content dataSource, String filePath)
List< BlackboardArtifactTag > getBlackboardArtifactTagsByArtifact(BlackboardArtifact artifact)
final IngestModuleInfo addIngestModule(String displayName, String factoryClassName, IngestModuleType type, String version)
long getBlackboardArtifactsCount(String artifactTypeName, long obj_id)
Content getContentById(long id)
BlackboardArtifactTag getAddedTag()
VersionNumber getDBSchemaVersion()
static IngestJobStatusType fromID(int typeId)
List< TagName > getTagNamesInUse()
List< BlackboardArtifact > getBlackboardArtifacts(BlackboardAttribute.ATTRIBUTE_TYPE attrType, byte value)
LAYOUT_FILE
Set of blocks from an image that have been designated as a file.
List< AbstractFile > findAllFilesInFolderWhere(long parentId, String sqlWhereClause)
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, String md5, String sha256, FileKnown known, String mimeType, boolean isFile, TskData.EncodingType encodingType, Content parent, CaseDbTransaction transaction)
static SleuthkitCase openCase(String databaseName, CaseDbConnectionInfo info, String caseDir)
static IngestModuleType fromID(int typeId)
List< ContentTag > getAllContentTags()
long getDataSourceObjectId()
List< VirtualDirectory > getVirtualDirectoryRoots()
LayoutFile addLayoutFile(String fileName, long size, TSK_FS_NAME_FLAG_ENUM dirFlag, TSK_FS_META_FLAG_ENUM metaFlag, long ctime, long crtime, long atime, long mtime, List< TskFileRange > fileRanges, Content parent)
FsContent addFileSystemFile(long dataSourceObjId, long fsObjId, String fileName, long metaAddr, int metaSeq, TSK_FS_ATTR_TYPE_ENUM attrType, int attrId, TSK_FS_NAME_FLAG_ENUM dirFlag, short metaFlags, long size, long ctime, long crtime, long atime, long mtime, String md5Hash, String sha256Hash, String sha1Hash, String mimeType, boolean isFile, Content parent, String ownerUid, OsAccount osAccount, TskData.CollectedStatus collected, List< Attribute > fileAttributes, CaseDbTransaction transaction)
long getBlackboardArtifactTagsCountByTagName(TagName tagName, long dsObjId)
static SleuthkitCase openCase(String databaseName, CaseDbConnectionInfo info, String caseDir, ContentStreamProvider contentProvider)
ArrayList< BlackboardArtifact.ARTIFACT_TYPE > getBlackboardArtifactTypes()
ContentTag getContentTagByID(long contentTagID)
LOCAL
Local file that was added (not from a disk image)
HostAddressManager getHostAddressManager()
Map< Long, List< String > > getImagePaths()
List< Long > findAllFileIdsWhere(String sqlWhereClause)
synchronized TaggingManager getTaggingManager()
BlackboardArtifact getBlackboardArtifact(long artifactID)
List< BlackboardArtifact.Type > getArtifactTypesInUse()
OsAccountRealmManager getOsAccountRealmManager()
BlackboardAttribute.Type addArtifactAttributeType(String attrTypeString, TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE valueType, String displayName)
AbstractFile getAbstractFileById(long id)
CARVED
Set of blocks for a file found from carving. Could be on top of a TSK_DB_FILES_TYPE_UNALLOC_BLOCKS ra...
BlackboardArtifactTag addBlackboardArtifactTag(BlackboardArtifact artifact, TagName tagName, String comment)
List< AnalysisResult > getAnalysisResults(long dataSourceObjId, Integer artifactTypeID)
long countFilesWhere(String sqlWhereClause)
List< AnalysisResult > getAnalysisResultsWhere(String whereClause)
long getBlackboardArtifactsCount(ARTIFACT_TYPE artifactType, long obj_id)
FS
File System - see tsk_fs_info for more details.
Pool addPool(long parentObjId, TskData.TSK_POOL_TYPE_ENUM type, CaseDbTransaction transaction)
boolean isFileFromSource(Content dataSource, long fileId)
ArrayList< BlackboardArtifact > getMatchingArtifacts(String whereClause)
VirtualDirectory addVirtualDirectory(long parentId, String directoryName, CaseDbTransaction transaction)
ArrayList< BlackboardArtifact.ARTIFACT_TYPE > getBlackboardArtifactTypesInUse()
void deleteReport(Report report)
List< Image > getImages()
int getAttrTypeID(String attrTypeName)
synchronized BlackboardAttribute.Type getOrAddAttributeType(String typeName, BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE valueType, String displayName)
Image getImageById(long id)
Report addReport(String localPath, String sourceModuleName, String reportName, Content parent)
List< Content > getChildren()
USED
Metadata structure has been allocated at least once.
void unregisterForEvents(Object listener)
LOCAL_DIR
Local directory that was added (not from a disk image)
TimelineManager getTimelineManager()
final List< LayoutFile > addCarvedFiles(CarvingResult carvingResult)
void releaseSingleUserCaseReadLock()
PersonManager getPersonManager()
FsContent addFileSystemFile(long dataSourceObjId, long fsObjId, String fileName, long metaAddr, int metaSeq, TSK_FS_ATTR_TYPE_ENUM attrType, int attrId, TSK_FS_NAME_FLAG_ENUM dirFlag, short metaFlags, long size, long ctime, long crtime, long atime, long mtime, String md5Hash, String sha256Hash, String sha1Hash, String mimeType, boolean isFile, Content parent, String ownerUid, OsAccount osAccount, List< Attribute > fileAttributes, CaseDbTransaction transaction)
VOL
Volume - see tsk_vs_parts for more details.
void closeRunQuery(ResultSet resultSet)
DerivedFile addDerivedFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, Content parentObj, String rederiveDetails, String toolName, String toolVersion, String otherDetails, TskData.EncodingType encodingType)
void disableTimelineEventCreation()
static SleuthkitCase newCase(String caseName, CaseDbConnectionInfo info, String caseDirPath, ContentStreamProvider contentProvider)
int addAttrType(String attrTypeString, String displayName)
void deleteBlackboardArtifactTag(BlackboardArtifactTag tag)
long getContentTagsCountByTagName(TagName tagName, long dsObjId)
List< ContentTag > getContentTagsByTagName(TagName tagName)
BlackboardArtifact newBlackboardArtifact(int artifactTypeID, long obj_id)
static String escapeSingleQuotes(String text)
String getAttrTypeDisplayName(int attrTypeID)
List< BlackboardArtifact > getBlackboardArtifacts(ARTIFACT_TYPE artifactType, BlackboardAttribute.ATTRIBUTE_TYPE attrType, String value)
void setFileUnalloc(AbstractFile file)
List< AbstractFile > findFiles(Content dataSource, String fileName)
List< AbstractFile > findFilesInFolder(String fileName, AbstractFile parentFile)
List< TagName > getAllTagNames()
HostManager getHostManager()
Report getReportById(long id)
BlackboardAttribute.Type getAttributeType(String attrTypeName)
Image addImageInfo(long deviceObjId, List< String > imageFilePaths, String timeZone)
BlackboardArtifact.Type getArtifactType(String artTypeName)
static HTML_COLOR getColorByName(String colorName)
void acquireSingleUserCaseWriteLock()
REPORT
Artifact - see blackboard_artifacts for more details.
List< AbstractFile > findFilesByMd5(String md5Hash)
OsAccountInstance newOsAccountInstance(OsAccount osAccount, DataSource dataSource, OsAccountInstance.OsAccountInstanceType instanceType)
long getBlackboardArtifactsTypeCount(int artifactTypeID, long dataSourceID)
BlackboardArtifact.Type getArtifactType(String artTypeName)
void releaseSingleUserCaseWriteLock()
DERIVED
File derived from a parent file (i.e. from ZIP)
Host newHost(String name)
List< LayoutFile > addCarvedFiles(List< CarvedFileContainer > filesToAdd)
List< BlackboardArtifactTag > getBlackboardArtifactTagsByTagName(TagName tagName)
static TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE fromType(long typeId)
static SleuthkitCase newCase(String caseName, CaseDbConnectionInfo info, String caseDirPath)
Report addReport(String localPath, String sourceModuleName, String reportName)
void releaseExclusiveLock()
List< BlackboardArtifactTag > getAllBlackboardArtifactTags()
ArrayList< BlackboardArtifact > getBlackboardArtifacts(String artifactTypeName, long obj_id)
Image addImage(TskData.TSK_IMG_TYPE_ENUM type, long sectorSize, long size, String displayName, List< String > imagePaths, String timezone, String md5, String sha1, String sha256, String deviceId, CaseDbTransaction transaction)
void removeErrorObserver(ErrorObserver observer)
String getContextString()
List< Content > getRootObjects()
List< AbstractFile > findFiles(Content dataSource, String fileName, String dirSubString)
static short toInt(Set< TSK_FS_META_FLAG_ENUM > metaFlags)
ContentTagChange addContentTag(Content content, TagName tagName, String comment, long beginByteOffset, long endByteOffset)
FileSystem addFileSystem(long parentObjId, long imgOffset, TskData.TSK_FS_TYPE_ENUM type, long blockSize, long blockCount, long rootInum, long firstInum, long lastInum, String displayName, CaseDbTransaction transaction)
void acquireExclusiveLock()
boolean allFilesMd5Hashed()
String getAttrTypeString(int attrTypeID)
int getBlackboardAttributeTypesCount()
LayoutFile addCarvedFile(String carvedFileName, long carvedFileSize, long containerId, List< TskFileRange > data)
ArrayList< BlackboardAttribute.ATTRIBUTE_TYPE > getBlackboardAttributeTypes()
List< DataArtifact > getDataArtifactsWhere(String whereClause)
UNALLOC_BLOCKS
Set of blocks not allocated by file system. Parent should be image, volume, or file system...
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, TskData.EncodingType encodingType, AbstractFile parent)
AnalysisResultAdded newAnalysisResult(BlackboardArtifact.Type artifactType, long objId, Long dataSourceObjId, Score score, String conclusion, String configuration, String justification, Collection< BlackboardAttribute > attributesList)
ArrayList< BlackboardAttribute > getMatchingAttributes(String whereClause)
List< BlackboardArtifact > getBlackboardArtifacts(BlackboardAttribute.ATTRIBUTE_TYPE attrType, String value)
long getBlackboardArtifactsTypeCount(int artifactTypeID)
List< ContentTag > getContentTagsByTagName(TagName tagName, long dsObjId)
void deleteContentTag(ContentTag tag)
AnalysisResultAdded newAnalysisResult(BlackboardArtifact.Type artifactType, Score score, String conclusion, String configuration, String justification, Collection< BlackboardAttribute > attributesList)
BlackboardArtifact.Type getOrAddArtifactType(String typeName, String displayName)
static ObjectType valueOf(short objectType)
Optional< String > getOwnerUid()
long getContentTagsCountByTagName(TagName tagName)
FsContent addFileSystemFile(long dataSourceObjId, long fsObjId, String fileName, long metaAddr, int metaSeq, TSK_FS_ATTR_TYPE_ENUM attrType, int attrId, TSK_FS_NAME_FLAG_ENUM dirFlag, short metaFlags, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, Content parent)
Optional< Long > getFileSystemObjectId()
Collection< FileSystem > getImageFileSystems(Image image)
void updateImagePath(String newPath, long objectId)
static SleuthkitCase openCase(String dbPath, ContentStreamProvider provider)
VolumeSystem addVolumeSystem(long parentObjId, TskData.TSK_VS_TYPE_ENUM type, long imgOffset, long blockSize, CaseDbTransaction transaction)
Examiner getCurrentExaminer()
LocalFilesDataSource addLocalFilesDataSource(String deviceId, String rootDirectoryName, String timeZone, Host host, CaseDbTransaction transaction)
UNKNOWN
File marked as unknown by hash db.
List< TagName > getTagNamesInUse(long dsObjId)
List< AbstractFile > findAllFilesWhere(String sqlWhereClause)
boolean setKnown(AbstractFile file, FileKnown fileKnown)
OsAccountManager getOsAccountManager()
static void tryConnect(CaseDbConnectionInfo info)
static SleuthkitCase openCase(String dbPath)
CaseDbQuery executeInsertOrUpdate(String query)
List< BlackboardArtifactTag > getBlackboardArtifactTagsByTagName(TagName tagName, long dsObjId)
Volume addVolume(long parentObjId, long addr, long start, long length, String desc, long flags, CaseDbTransaction transaction)
long getBlackboardArtifactsCount(int artifactTypeID, long obj_id)
DerivedFile addDerivedFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, Content parentObj, String rederiveDetails, String toolName, String toolVersion, String otherDetails, TskData.EncodingType encodingType, CaseDbTransaction transaction)
void submitError(String context, String errorMessage)
final List< IngestJobInfo > getIngestJobs()
ALLOC
Name is in an allocated state.
VIRTUAL_DIR
Virtual directory (not on fs) with no meta-data entry that can be used to group files of types other ...
static SleuthkitCase newCase(String dbPath)
String getBackupDatabasePath()
void acquireSingleUserCaseReadLock()
VirtualDirectory addVirtualDirectory(long parentId, String directoryName)
LocalFile addLocalFile(String fileName, String localPath, long size, long ctime, long crtime, long atime, long mtime, boolean isFile, TskData.EncodingType encodingType, Content parent, CaseDbTransaction transaction)
List< ContentTag > getContentTagsByContent(Content content)
ArrayList< BlackboardArtifact > getBlackboardArtifacts(ARTIFACT_TYPE artifactType, long obj_id)
TagName addTagName(String displayName, String description, TagName.HTML_COLOR color)
int countFsContentType(TskData.TSK_FS_META_TYPE_ENUM contentType)
ABSTRACTFILE
File - see tsk_files for more details.
ContentTag addContentTag(Content content, TagName tagName, String comment, long beginByteOffset, long endByteOffset)
DataSource getDataSource(long objectId)
BlackboardAttribute.Type getAttributeType(String attrTypeName)
List< BlackboardArtifact > getBlackboardArtifacts(BlackboardAttribute.ATTRIBUTE_TYPE attrType, String subString, boolean startsWith)
TSK_FS_META_TYPE_REG
Regular file NON-NLS.
Iterable< BlackboardArtifact.Type > getArtifactTypes()
List< BlackboardAttribute.Type > getAttributeTypes()
LocalFilesDataSource addLocalFilesDataSource(String deviceId, String rootDirectoryName, String timeZone, CaseDbTransaction transaction)
FsContent addFileSystemFile(long dataSourceObjId, long fsObjId, String fileName, long metaAddr, int metaSeq, TSK_FS_ATTR_TYPE_ENUM attrType, int attrId, TSK_FS_NAME_FLAG_ENUM dirFlag, short metaFlags, long size, long ctime, long crtime, long atime, long mtime, String md5Hash, String sha256Hash, String mimeType, boolean isFile, Content parent, String ownerUid, OsAccount osAccount, List< Attribute > fileAttributes, CaseDbTransaction transaction)
AddImageProcess makeAddImageProcess(String timeZone, boolean addUnallocSpace, boolean noFatFsOrphans, String imageCopyPath)
List< FsContent > findFilesWhere(String sqlWhereClause)
Long getDataSourceObjectId()
static ReviewStatus withID(int id)
void copyCaseDB(String newDBPath)
FileManager getFileManager()
Image addImage(TskData.TSK_IMG_TYPE_ENUM type, long sectorSize, long size, String displayName, List< String > imagePaths, String timezone, String md5, String sha1, String sha256, String deviceId, Host host, CaseDbTransaction transaction)
void setImagePaths(long objId, List< String > paths, CaseDbTransaction trans)
ResultSet runQuery(String query)
List< TskFileRange > getFileRanges(long id)
BlackboardArtifact.Type addBlackboardArtifactType(String artifactTypeName, String displayName)
void registerForEvents(Object listener)
CaseDbQuery executeQuery(String query)
ScoringManager getScoringManager()
void setReviewStatus(BlackboardArtifact artifact, BlackboardArtifact.ReviewStatus newStatus)
void setImagePaths(long obj_id, List< String > paths)
VS
Volume System - see tsk_vs_info for more details.
IMG
Disk Image - see tsk_image_info for more details.
UNALLOC
Name is in an unallocated state.
Collection< FileSystem > getFileSystems(Image image)
LocalDirectory addLocalDirectory(long parentId, String directoryName)
Optional< Long > getOsAccountObjectId()