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.google.gson.Gson;
27 import com.mchange.v2.c3p0.ComboPooledDataSource;
28 import com.mchange.v2.c3p0.DataSources;
29 import com.mchange.v2.c3p0.PooledDataSource;
30 import com.zaxxer.sparsebits.SparseBitSet;
31 import java.beans.PropertyVetoException;
32 import java.io.BufferedInputStream;
33 import java.io.BufferedOutputStream;
35 import java.io.FileInputStream;
36 import java.io.FileOutputStream;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.OutputStream;
40 import java.io.UnsupportedEncodingException;
41 import java.net.InetAddress;
42 import java.net.URLEncoder;
43 import java.nio.charset.StandardCharsets;
44 import java.nio.file.Paths;
45 import java.sql.Connection;
46 import java.sql.DriverManager;
47 import java.sql.PreparedStatement;
48 import java.sql.ResultSet;
49 import java.sql.SQLException;
50 import java.sql.Statement;
51 import java.text.SimpleDateFormat;
52 import java.util.ArrayList;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.Collections;
56 import java.util.concurrent.atomic.AtomicBoolean;
57 import java.util.concurrent.atomic.AtomicInteger;
58 import java.util.Date;
59 import java.util.EnumMap;
60 import java.util.HashMap;
61 import java.util.HashSet;
62 import java.util.LinkedHashMap;
63 import java.util.List;
65 import java.util.MissingResourceException;
66 import java.util.Objects;
67 import java.util.Properties;
68 import java.util.ResourceBundle;
70 import java.util.UUID;
71 import java.util.concurrent.CompletableFuture;
72 import java.util.concurrent.CountDownLatch;
73 import java.util.concurrent.TimeUnit;
74 import java.util.concurrent.locks.ReentrantLock;
75 import java.util.concurrent.locks.ReentrantReadWriteLock;
76 import java.util.logging.Level;
77 import java.util.logging.Logger;
78 import java.util.stream.Collectors;
79 import org.apache.commons.lang3.StringUtils;
80 import org.postgresql.util.PSQLState;
101 import org.sqlite.SQLiteConfig;
102 import org.sqlite.SQLiteDataSource;
103 import org.sqlite.SQLiteJDBCLoader;
111 private static final int MAX_DB_NAME_LEN_BEFORE_TIMESTAMP = 47;
116 private static final long BASE_ARTIFACT_ID = Long.MIN_VALUE;
117 private static final Logger logger = Logger.getLogger(
SleuthkitCase.class.getName());
118 private static final ResourceBundle bundle = ResourceBundle.getBundle(
"org.sleuthkit.datamodel.Bundle");
119 private static final int IS_REACHABLE_TIMEOUT_MS = 1000;
120 private static final String SQL_ERROR_CONNECTION_GROUP =
"08";
122 private static final String SQL_CONNECTION_REJECTED =
"08004";
123 private static final String UNABLE_TO_VERIFY_SSL =
"08006";
125 private static final String SQL_ERROR_AUTHENTICATION_GROUP =
"28";
126 private static final String SQL_ERROR_PRIVILEGE_GROUP =
"42";
127 private static final String SQL_ERROR_RESOURCE_GROUP =
"53";
128 private static final String SQL_ERROR_LIMIT_GROUP =
"54";
129 private static final String SQL_ERROR_INTERNAL_GROUP =
"xx";
131 private static final Set<String> CORE_TABLE_NAMES = ImmutableSet.of(
133 "tsk_event_descriptions",
146 "tsk_files_derived_method",
149 "blackboard_artifact_tags",
150 "blackboard_artifacts",
151 "blackboard_attributes",
152 "blackboard_artifact_types",
153 "blackboard_attribute_types",
155 "file_encoding_types",
156 "file_collection_status_types",
157 "ingest_module_types",
158 "ingest_job_status_types",
161 "ingest_job_modules",
164 "account_relationships",
168 private static final Set<String> CORE_INDEX_NAMES = ImmutableSet.of(
172 "artifact_artifact_objID",
177 "relationships_account1",
178 "relationships_account2",
179 "relationships_relationship_source_obj_id",
180 "relationships_date_time",
181 "relationships_relationship_type",
182 "relationships_data_source_obj_id",
185 "events_data_source_obj_id",
186 "events_file_obj_id",
187 "events_artifact_id");
189 private static final String TSK_VERSION_KEY =
"TSK_VER";
190 private static final String SCHEMA_MAJOR_VERSION_KEY =
"SCHEMA_MAJOR_VERSION";
191 private static final String SCHEMA_MINOR_VERSION_KEY =
"SCHEMA_MINOR_VERSION";
192 private static final String CREATION_SCHEMA_MAJOR_VERSION_KEY =
"CREATION_SCHEMA_MAJOR_VERSION";
193 private static final String CREATION_SCHEMA_MINOR_VERSION_KEY =
"CREATION_SCHEMA_MINOR_VERSION";
196 static final String IMAGE_PASSWORD_KEY =
"imagePassword";
198 private final ConnectionPool connections;
199 private final Object carvedFileDirsLock =
new Object();
200 private final static int MAX_CARVED_FILES_PER_FOLDER = 2000;
201 private final Map<Long, CarvedFileDirInfo> rootIdsToCarvedFileDirs =
new HashMap<>();
202 private final Map<Long, FileSystem> fileSystemIdMap =
new HashMap<>();
203 private final List<ErrorObserver> sleuthkitCaseErrorObservers =
new ArrayList<>();
204 private final String databaseName;
205 private final String dbPath;
206 private final DbType dbType;
207 private final String caseDirPath;
209 private final String caseHandleIdentifier;
210 private String dbBackupPath;
211 private AtomicBoolean timelineEventsDisabled =
new AtomicBoolean(
false);
216 private final Object rootDirectoryMapLock =
new Object();
217 private final Map<RootDirectoryKey, Long> rootDirectoryMap =
new HashMap<>();
218 private final Cache<Long, Boolean> isRootDirectoryCache
219 = CacheBuilder.newBuilder().maximumSize(200000).expireAfterAccess(5, TimeUnit.MINUTES).build();
222 private final LockResources lockResources;
228 private final Map<Long, SparseBitSet> hasChildrenBitSetMap =
new HashMap<>();
230 private final ReentrantLock childrenBitSetLock =
new ReentrantLock();
232 private final CountDownLatch childrenBitSetInitLatch =
new CountDownLatch(1);
235 private long nextArtifactId;
240 private final ReentrantReadWriteLock rwLock =
new ReentrantReadWriteLock(
true);
255 private final Map<String, Set<Long>> deviceIdToDatasourceObjIdMap =
new HashMap<>();
257 private final EventBus eventBus =
new EventBus(
"SleuthkitCase-EventBus");
260 eventBus.register(listener);
264 eventBus.unregister(listener);
267 void fireTSKEvent(Object event) {
268 eventBus.post(event);
272 private final Map<Long, Content> frequentlyUsedContentMap =
new HashMap<>();
274 private Examiner cachedCurrentExaminer = null;
277 Properties p =
new Properties(System.getProperties());
278 p.put(
"com.mchange.v2.log.MLog",
"com.mchange.v2.log.FallbackMLog");
279 p.put(
"com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL",
"SEVERE");
280 System.setProperties(p);
299 if (info.getHost() == null || info.getHost().isEmpty()) {
300 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingHostname"));
301 }
else if (info.getPort() == null || info.getPort().isEmpty()) {
302 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingPort"));
303 }
else if (info.getUserName() == null || info.getUserName().isEmpty()) {
304 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingUsername"));
305 }
else if (info.getPassword() == null || info.getPassword().isEmpty()) {
306 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.MissingPassword"));
310 Class.forName(
"org.postgresql.Driver");
311 String connectionURL =
"jdbc:postgresql://" + info.getHost() +
":" + info.getPort() +
"/postgres";
312 if (info.isSslEnabled()) {
313 if (info.isSslVerify()) {
314 if (info.getCustomSslValidationClassName().isBlank()) {
315 connectionURL += CaseDatabaseFactory.SSL_VERIFY_DEFAULT_URL;
318 connectionURL += CaseDatabaseFactory.getCustomPostrgesSslVerificationUrl(info.getCustomSslValidationClassName());
321 connectionURL += CaseDatabaseFactory.SSL_NONVERIFY_URL;
324 Connection conn = DriverManager.getConnection(connectionURL, info.getUserName(), info.getPassword());
328 }
catch (SQLException ex) {
330 String sqlState = ex.getSQLState().toLowerCase();
331 if (sqlState.startsWith(SQL_ERROR_CONNECTION_GROUP)) {
332 if (SQL_CONNECTION_REJECTED.equals(ex.getSQLState())) {
333 if (info.isSslEnabled()) {
334 result =
"Server rejected the SSL connection attempt. Check SSL configuration.";
336 result =
"Server rejected the connection attempt. Check server configuration.";
338 }
else if (UNABLE_TO_VERIFY_SSL.equals(ex.getSQLState())) {
339 result =
"Unable to verify SSL certificates. Check SSL configuration.";
342 if (InetAddress.getByName(info.getHost()).isReachable(IS_REACHABLE_TIMEOUT_MS)) {
344 result = bundle.getString(
"DatabaseConnectionCheck.Port");
346 result = bundle.getString(
"DatabaseConnectionCheck.HostnameOrPort");
348 }
catch (IOException | MissingResourceException any) {
350 result = bundle.getString(
"DatabaseConnectionCheck.Everything");
353 }
else if (sqlState.startsWith(SQL_ERROR_AUTHENTICATION_GROUP)) {
354 result = bundle.getString(
"DatabaseConnectionCheck.Authentication");
355 }
else if (sqlState.startsWith(SQL_ERROR_PRIVILEGE_GROUP)) {
356 result = bundle.getString(
"DatabaseConnectionCheck.Access");
357 }
else if (sqlState.startsWith(SQL_ERROR_RESOURCE_GROUP)) {
358 result = bundle.getString(
"DatabaseConnectionCheck.ServerDiskSpace");
359 }
else if (sqlState.startsWith(SQL_ERROR_LIMIT_GROUP)) {
360 result = bundle.getString(
"DatabaseConnectionCheck.ServerRestart");
361 }
else if (sqlState.startsWith(SQL_ERROR_INTERNAL_GROUP)) {
362 result = bundle.getString(
"DatabaseConnectionCheck.InternalServerIssue");
364 result = bundle.getString(
"DatabaseConnectionCheck.Connection");
367 }
catch (ClassNotFoundException ex) {
368 throw new TskCoreException(bundle.getString(
"DatabaseConnectionCheck.Installation"));
390 Class.forName(
"org.sqlite.JDBC");
391 this.dbPath = dbPath;
392 this.dbType = dbType;
394 this.caseDirPath = dbFile.getParentFile().getAbsolutePath();
395 this.databaseName = dbFile.
getName();
397 this.lockResources = lockingApplicationName == null
399 : LockResources.tryAcquireFileLock(this.caseDirPath, this.databaseName, lockingApplicationName);
401 this.connections =
new SQLiteConnections(dbPath);
402 this.caseHandle = caseHandle;
403 this.caseHandleIdentifier = caseHandle.getCaseDbIdentifier();
404 this.contentProvider = contentProvider;
406 logSQLiteJDBCDriverInfo();
420 private SleuthkitCase(CaseDbConnectionInfo info, String dbName, SleuthkitJNI.CaseDbHandle caseHandle, String caseDirPath, ContentStreamProvider contentProvider)
throws Exception {
422 this.databaseName = dbName;
423 this.dbType = info.getDbType();
424 this.caseDirPath = caseDirPath;
425 this.connections =
new PostgreSQLConnections(info, dbName);
426 this.caseHandle = caseHandle;
427 this.caseHandleIdentifier = caseHandle.getCaseDbIdentifier();
428 this.contentProvider = contentProvider;
429 this.lockResources = null;
433 private void init() throws Exception {
434 blackboard =
new Blackboard(
this);
435 updateDatabaseSchema(null);
436 try (CaseDbConnection connection = connections.getConnection()) {
437 blackboard.initBlackboardArtifactTypes(connection);
438 blackboard.initBlackboardAttributeTypes(connection);
439 initNextArtifactId(connection);
440 initIngestModuleTypes(connection);
441 initIngestStatusTypes(connection);
442 initReviewStatuses(connection);
443 initEncodingTypes(connection);
444 initCollectedStatusTypes(connection);
445 populateHasChildrenMap(
true);
446 updateExaminers(connection);
447 initDBSchemaCreationVersion(connection);
450 fileManager =
new FileManager(
this);
451 communicationsMgr =
new CommunicationsManager(
this);
452 timelineMgr =
new TimelineManager(
this);
453 dbAccessManager =
new CaseDbAccessManager(
this);
454 taggingMgr =
new TaggingManager(
this);
455 scoringManager =
new ScoringManager(
this);
456 osAccountRealmManager =
new OsAccountRealmManager(
this);
457 osAccountManager =
new OsAccountManager(
this);
458 hostManager =
new HostManager(
this);
459 personManager =
new PersonManager(
this);
460 hostAddressManager =
new HostAddressManager(
this);
470 ContentStreamProvider getContentProvider() {
471 return this.contentProvider;
479 static Set<String> getCoreTableNames() {
480 return Collections.unmodifiableSet(CORE_TABLE_NAMES);
488 static Set<String> getCoreIndexNames() {
489 return Collections.unmodifiableSet(CORE_INDEX_NAMES);
500 boolean getHasChildren(Content content) {
504 childrenBitSetInitLatch.await();
505 }
catch (InterruptedException ex) {
506 throw new AssertionError(
"Interrupted Exception awaiting Children bit set initialization", ex);
508 childrenBitSetLock.lock();
510 long objId = content.getId();
511 long mapIndex = objId / Integer.MAX_VALUE;
512 int mapValue = (int) (objId % Integer.MAX_VALUE);
514 if (hasChildrenBitSetMap.containsKey(mapIndex)) {
515 return hasChildrenBitSetMap.get(mapIndex).get(mapValue);
520 childrenBitSetLock.unlock();
529 private void setHasChildren(Long objId) {
530 setHasChildren(objId,
false);
538 private void setHasChildren(Long objId,
boolean initializing) {
542 childrenBitSetInitLatch.await();
544 }
catch (InterruptedException ex) {
545 throw new AssertionError(
"Interrupted Exception awaiting Children bit set initialization",ex);
548 childrenBitSetLock.lock();
550 long mapIndex = objId / Integer.MAX_VALUE;
551 int mapValue = (int) (objId % Integer.MAX_VALUE);
553 if (hasChildrenBitSetMap.containsKey(mapIndex)) {
554 hasChildrenBitSetMap.get(mapIndex).set(mapValue);
556 SparseBitSet bitSet =
new SparseBitSet();
557 bitSet.set(mapValue);
558 hasChildrenBitSetMap.put(mapIndex, bitSet);
561 childrenBitSetLock.unlock();
573 return communicationsMgr;
613 return dbAccessManager;
633 return scoringManager;
644 return osAccountRealmManager;
655 return osAccountManager;
677 return personManager;
688 return hostAddressManager;
700 private void initNextArtifactId(CaseDbConnection connection)
throws SQLException {
702 try (Statement statement = connection.createStatement()) {
703 ResultSet resultSet = connection.executeQuery(statement,
"SELECT MAX(artifact_id) AS max_artifact_id FROM blackboard_artifacts");
705 nextArtifactId = resultSet.getLong(
"max_artifact_id") + 1;
706 if (nextArtifactId == 1) {
707 nextArtifactId = BASE_ARTIFACT_ID;
721 private void initIngestModuleTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
722 Statement statement = null;
723 ResultSet resultSet = null;
726 statement = connection.createStatement();
727 for (IngestModuleType type : IngestModuleType.values()) {
729 String query =
"INSERT INTO ingest_module_types (type_id, type_name) VALUES (" + type.ordinal() +
", '" + type.toString() +
"')";
731 query +=
" ON CONFLICT ON CONSTRAINT ingest_module_types_pkey DO NOTHING";
733 statement.execute(query);
734 }
catch (SQLException ex) {
735 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM ingest_module_types WHERE type_id = " + type.ordinal() +
";");
737 if (resultSet.getLong(
"count") == 0) {
745 closeResultSet(resultSet);
746 closeStatement(statement);
758 private void initIngestStatusTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
759 Statement statement = null;
760 ResultSet resultSet = null;
763 statement = connection.createStatement();
764 for (IngestJobStatusType type : IngestJobStatusType.values()) {
766 String query =
"INSERT INTO ingest_job_status_types (type_id, type_name) VALUES (" + type.ordinal() +
", '" + type.toString() +
"')";
768 query +=
" ON CONFLICT ON CONSTRAINT ingest_job_status_types_pkey DO NOTHING";
770 statement.execute(query);
771 }
catch (SQLException ex) {
772 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM ingest_job_status_types WHERE type_id = " + type.ordinal() +
";");
774 if (resultSet.getLong(
"count") == 0) {
782 closeResultSet(resultSet);
783 closeStatement(statement);
794 private void initReviewStatuses(CaseDbConnection connection)
throws SQLException, TskCoreException {
795 Statement statement = null;
796 ResultSet resultSet = null;
799 statement = connection.createStatement();
800 for (BlackboardArtifact.ReviewStatus status : BlackboardArtifact.ReviewStatus.values()) {
802 String query =
"INSERT INTO review_statuses (review_status_id, review_status_name, display_name) "
803 +
"VALUES (" + status.getID() +
",'" + status.getName() +
"','" + status.getDisplayName() +
"')";
805 query +=
" ON CONFLICT ON CONSTRAINT review_statuses_pkey DO NOTHING";
807 statement.execute(query);
808 }
catch (SQLException ex) {
809 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM review_statuses WHERE review_status_id = " + status.getID());
811 if (resultSet.getLong(
"count") == 0) {
819 closeResultSet(resultSet);
820 closeStatement(statement);
832 private void initEncodingTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
833 Statement statement = null;
834 ResultSet resultSet = null;
837 statement = connection.createStatement();
838 for (TskData.EncodingType type : TskData.EncodingType.values()) {
840 String query =
"INSERT INTO file_encoding_types (encoding_type, name) VALUES (" + type.getType() +
" , '" + type.name() +
"')";
842 query +=
" ON CONFLICT ON CONSTRAINT file_encoding_types_pkey DO NOTHING";
844 statement.execute(query);
845 }
catch (SQLException ex) {
846 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM file_encoding_types WHERE encoding_type = " + type.getType());
848 if (resultSet.getLong(
"count") == 0) {
856 closeResultSet(resultSet);
857 closeStatement(statement);
869 private void initCollectedStatusTypes(CaseDbConnection connection)
throws SQLException, TskCoreException {
870 Statement statement = null;
871 ResultSet resultSet = null;
874 statement = connection.createStatement();
875 for (TskData.CollectedStatus type : TskData.CollectedStatus.values()) {
877 String query =
"INSERT INTO file_collection_status_types (collection_status_type, name) VALUES (" + type.getType() +
" , '" + type.name() +
"')";
879 query +=
" ON CONFLICT ON CONSTRAINT file_collection_status_types_pkey DO NOTHING";
881 statement.execute(query);
882 }
catch (SQLException ex) {
883 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) as count FROM file_collection_status_types WHERE collection_status_type = " + type.getType());
885 if (resultSet.getLong(
"count") == 0) {
893 closeResultSet(resultSet);
894 closeStatement(statement);
907 private void updateExaminers(CaseDbConnection connection)
throws SQLException, TskCoreException {
909 String loginName = System.getProperty(
"user.name");
910 if (loginName.isEmpty()) {
911 logger.log(Level.SEVERE,
"Cannot determine logged in user name");
917 PreparedStatement statement;
920 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_EXAMINER_POSTGRESQL);
923 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_EXAMINER_SQLITE);
926 throw new TskCoreException(
"Unknown DB Type: " +
getDatabaseType().name());
928 statement.clearParameters();
929 statement.setString(1, loginName);
930 connection.executeUpdate(statement);
931 }
catch (SQLException ex) {
932 throw new TskCoreException(
"Error inserting row in tsk_examiners. login name: " + loginName, ex);
943 private void populateHasChildrenMap(
boolean async)
throws TskCoreException {
945 Runnable childrenBitSetLockInitRunnable = () -> {
952 childrenBitSetLock.lock();
959 long timestamp = System.currentTimeMillis();
961 Statement statement = null;
962 ResultSet resultSet = null;
964 try (CaseDbConnection neoConnection = connections.getConnection()) {
965 statement = neoConnection.createStatement();
966 String query =
"select distinct par_obj_id from tsk_objects";
968 query =
"select distinct ON (par_obj_id) par_obj_id from tsk_objects";
971 resultSet = statement.executeQuery(query);
976 while (resultSet.next()) {
977 setHasChildren(resultSet.getLong(
"par_obj_id"),
true);
980 long delay = System.currentTimeMillis() - timestamp;
981 logger.log(Level.INFO,
"Time to initialize parent node cache: {0} ms", delay);
982 }
catch (SQLException ex) {
983 logger.log(Level.SEVERE,
"Error populating parent node cache", ex);
985 throw new AssertionError(
"Error populating parent node cache",ex);
986 }
catch (TskCoreException ex) {
987 logger.log(Level.SEVERE,
"Error acquiring connection", ex);
988 throw new AssertionError(
"Error acquiring connection",ex);
990 closeResultSet(resultSet);
991 closeStatement(statement);
993 childrenBitSetLock.unlock();
995 childrenBitSetInitLatch.countDown();
1000 CompletableFuture.runAsync(childrenBitSetLockInitRunnable);
1002 childrenBitSetLockInitRunnable.run();
1012 void addDataSourceToHasChildrenMap() throws TskCoreException {
1015 childrenBitSetInitLatch.await();
1016 }
catch (InterruptedException ex) {
1017 throw new AssertionError(
"Interrupted Exception awaiting Children bit set initialization", ex);
1019 populateHasChildrenMap(
false);
1031 private void updateDatabaseSchema(String dbPath)
throws Exception {
1032 CaseDbConnection connection = null;
1033 ResultSet resultSet = null;
1034 Statement statement = null;
1037 connection = connections.getConnection();
1038 connection.beginTransaction();
1040 boolean hasMinorVersion =
false;
1041 ResultSet columns = connection.getConnection().getMetaData().getColumns(null, null,
"tsk_db_info",
"schema%");
1042 while (columns.next()) {
1043 if (columns.getString(
"COLUMN_NAME").equals(
"schema_minor_ver")) {
1044 hasMinorVersion =
true;
1049 int dbSchemaMajorVersion;
1050 int dbSchemaMinorVersion = 0;
1052 statement = connection.createStatement();
1053 resultSet = connection.executeQuery(statement,
"SELECT schema_ver"
1054 + (hasMinorVersion ?
", schema_minor_ver" :
"")
1055 +
" FROM tsk_db_info");
1056 if (resultSet.next()) {
1057 dbSchemaMajorVersion = resultSet.getInt(
"schema_ver");
1058 if (hasMinorVersion) {
1060 dbSchemaMinorVersion = resultSet.getInt(
"schema_minor_ver");
1063 throw new TskCoreException();
1065 CaseDbSchemaVersionNumber dbSchemaVersion =
new CaseDbSchemaVersionNumber(dbSchemaMajorVersion, dbSchemaMinorVersion);
1072 if (
false == CURRENT_DB_SCHEMA_VERSION.
isCompatible(dbSchemaVersion)) {
1074 throw new TskUnsupportedSchemaVersionException(
1075 "Unsupported DB schema version " + dbSchemaVersion +
", the highest supported schema version is " + CURRENT_DB_SCHEMA_VERSION.
getMajor() +
".X");
1076 }
else if (dbSchemaVersion.compareTo(CURRENT_DB_SCHEMA_VERSION) < 0) {
1079 if (null != dbPath) {
1082 String backupFilePath = dbPath +
".schemaVer" + dbSchemaVersion.toString() +
".backup";
1084 dbBackupPath = backupFilePath;
1091 dbSchemaVersion = updateFromSchema2toSchema3(dbSchemaVersion, connection);
1092 dbSchemaVersion = updateFromSchema3toSchema4(dbSchemaVersion, connection);
1093 dbSchemaVersion = updateFromSchema4toSchema5(dbSchemaVersion, connection);
1094 dbSchemaVersion = updateFromSchema5toSchema6(dbSchemaVersion, connection);
1095 dbSchemaVersion = updateFromSchema6toSchema7(dbSchemaVersion, connection);
1096 dbSchemaVersion = updateFromSchema7toSchema7dot1(dbSchemaVersion, connection);
1097 dbSchemaVersion = updateFromSchema7dot1toSchema7dot2(dbSchemaVersion, connection);
1098 dbSchemaVersion = updateFromSchema7dot2toSchema8dot0(dbSchemaVersion, connection);
1099 dbSchemaVersion = updateFromSchema8dot0toSchema8dot1(dbSchemaVersion, connection);
1100 dbSchemaVersion = updateFromSchema8dot1toSchema8dot2(dbSchemaVersion, connection);
1101 dbSchemaVersion = updateFromSchema8dot2toSchema8dot3(dbSchemaVersion, connection);
1102 dbSchemaVersion = updateFromSchema8dot3toSchema8dot4(dbSchemaVersion, connection);
1103 dbSchemaVersion = updateFromSchema8dot4toSchema8dot5(dbSchemaVersion, connection);
1104 dbSchemaVersion = updateFromSchema8dot5toSchema8dot6(dbSchemaVersion, connection);
1105 dbSchemaVersion = updateFromSchema8dot6toSchema9dot0(dbSchemaVersion, connection);
1106 dbSchemaVersion = updateFromSchema9dot0toSchema9dot1(dbSchemaVersion, connection);
1107 dbSchemaVersion = updateFromSchema9dot1toSchema9dot2(dbSchemaVersion, connection);
1108 dbSchemaVersion = updateFromSchema9dot2toSchema9dot3(dbSchemaVersion, connection);
1109 dbSchemaVersion = updateFromSchema9dot3toSchema9dot4(dbSchemaVersion, connection);
1110 dbSchemaVersion = updateFromSchema9dot4toSchema9dot5(dbSchemaVersion, connection);
1111 dbSchemaVersion = updateFromSchema9dot5toSchema9dot6(dbSchemaVersion, connection);
1114 statement = connection.createStatement();
1115 connection.executeUpdate(statement,
"UPDATE tsk_db_info SET schema_ver = " + dbSchemaVersion.getMajor() +
", schema_minor_ver = " + dbSchemaVersion.getMinor());
1116 connection.executeUpdate(statement,
"UPDATE tsk_db_info_extended SET value = " + dbSchemaVersion.getMajor() +
" WHERE name = '" + SCHEMA_MAJOR_VERSION_KEY +
"'");
1117 connection.executeUpdate(statement,
"UPDATE tsk_db_info_extended SET value = " + dbSchemaVersion.getMinor() +
" WHERE name = '" + SCHEMA_MINOR_VERSION_KEY +
"'");
1122 connection.commitTransaction();
1123 }
catch (Exception ex) {
1124 rollbackTransaction(connection);
1127 closeResultSet(resultSet);
1128 closeStatement(statement);
1129 closeConnection(connection);
1141 private void initDBSchemaCreationVersion(CaseDbConnection connection)
throws SQLException {
1143 Statement statement = null;
1144 ResultSet resultSet = null;
1145 String createdSchemaMajorVersion =
"0";
1146 String createdSchemaMinorVersion =
"0";
1149 statement = connection.createStatement();
1150 resultSet = connection.executeQuery(statement,
"SELECT name, value FROM tsk_db_info_extended");
1151 while (resultSet.next()) {
1152 String name = resultSet.getString(
"name");
1153 if (name.equals(CREATION_SCHEMA_MAJOR_VERSION_KEY) || name.equals(
"CREATED_SCHEMA_MAJOR_VERSION")) {
1154 createdSchemaMajorVersion = resultSet.getString(
"value");
1155 }
else if (name.equals(CREATION_SCHEMA_MINOR_VERSION_KEY) || name.equals(
"CREATED_SCHEMA_MINOR_VERSION")) {
1156 createdSchemaMinorVersion = resultSet.getString(
"value");
1161 closeResultSet(resultSet);
1162 closeStatement(statement);
1166 caseDBSchemaCreationVersion =
new CaseDbSchemaVersionNumber(Integer.parseInt(createdSchemaMajorVersion), Integer.parseInt(createdSchemaMinorVersion));
1179 if (dbPath.isEmpty()) {
1180 throw new IOException(
"Copying case database files is not supported for this type of case database");
1182 InputStream in = null;
1183 OutputStream out = null;
1186 InputStream inFile =
new FileInputStream(dbPath);
1187 in =
new BufferedInputStream(inFile);
1188 OutputStream outFile =
new FileOutputStream(newDBPath);
1189 out =
new BufferedOutputStream(outFile);
1190 int bytesRead = in.read();
1191 while (bytesRead != -1) {
1192 out.write(bytesRead);
1193 bytesRead = in.read();
1204 }
catch (IOException e) {
1205 logger.log(Level.WARNING,
"Could not close streams after db copy", e);
1214 private void logSQLiteJDBCDriverInfo() {
1216 SleuthkitCase.logger.info(String.format(
"sqlite-jdbc version %s loaded in %s mode",
1217 SQLiteJDBCLoader.getVersion(), SQLiteJDBCLoader.isNativeMode()
1218 ?
"native" :
"pure-java"));
1219 }
catch (Exception ex) {
1220 SleuthkitCase.logger.log(Level.SEVERE,
"Error querying case database mode", ex);
1237 @SuppressWarnings(
"deprecation")
1238 private CaseDbSchemaVersionNumber updateFromSchema2toSchema3(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection) throws SQLException, TskCoreException {
1239 if (schemaVersion.getMajor() != 2) {
1240 return schemaVersion;
1242 Statement statement = null;
1243 Statement statement2 = null;
1244 Statement updateStatement = null;
1245 ResultSet resultSet = null;
1248 statement = connection.createStatement();
1249 statement2 = connection.createStatement();
1252 statement.execute(
"CREATE TABLE tag_names (tag_name_id INTEGER PRIMARY KEY, display_name TEXT UNIQUE, description TEXT NOT NULL, color TEXT NOT NULL)");
1253 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)");
1254 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)");
1257 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)");
1260 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN size INTEGER;");
1261 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN md5 TEXT;");
1262 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN display_name TEXT;");
1265 statement.execute(
"ALTER TABLE tsk_fs_info ADD COLUMN display_name TEXT;");
1268 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN meta_seq INTEGER;");
1273 statement.execute(
"ALTER TABLE blackboard_attributes ADD COLUMN artifact_type_id INTEGER NULL NOT NULL DEFAULT -1;");
1274 statement.execute(
"CREATE INDEX attribute_artifactTypeId ON blackboard_attributes(artifact_type_id);");
1275 statement.execute(
"CREATE INDEX attribute_valueText ON blackboard_attributes(value_text);");
1276 statement.execute(
"CREATE INDEX attribute_valueInt32 ON blackboard_attributes(value_int32);");
1277 statement.execute(
"CREATE INDEX attribute_valueInt64 ON blackboard_attributes(value_int64);");
1278 statement.execute(
"CREATE INDEX attribute_valueDouble ON blackboard_attributes(value_double);");
1279 resultSet = statement.executeQuery(
"SELECT attrs.artifact_id AS artifact_id, "
1280 +
"arts.artifact_type_id AS artifact_type_id "
1281 +
"FROM blackboard_attributes AS attrs "
1282 +
"INNER JOIN blackboard_artifacts AS arts "
1283 +
"WHERE attrs.artifact_id = arts.artifact_id;");
1284 updateStatement = connection.createStatement();
1285 while (resultSet.next()) {
1286 long artifactId = resultSet.getLong(
"artifact_id");
1287 int artifactTypeId = resultSet.getInt(
"artifact_type_id");
1288 updateStatement.executeUpdate(
1289 "UPDATE blackboard_attributes "
1290 +
"SET artifact_type_id = " + artifactTypeId
1291 +
" WHERE blackboard_attributes.artifact_id = " + artifactId +
";");
1296 Map<String, Long> tagNames =
new HashMap<>();
1297 long tagNameCounter = 1;
1301 resultSet = statement.executeQuery(
"SELECT * FROM \n"
1302 +
"(SELECT blackboard_artifacts.obj_id AS objId, blackboard_attributes.artifact_id AS artifactId, blackboard_attributes.value_text AS name\n"
1303 +
"FROM blackboard_artifacts INNER JOIN blackboard_attributes \n"
1304 +
"ON blackboard_artifacts.artifact_id = blackboard_attributes.artifact_id \n"
1305 +
"WHERE blackboard_artifacts.artifact_type_id = "
1306 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID()
1307 +
" AND blackboard_attributes.attribute_type_id = " + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TAG_NAME.getTypeID()
1308 +
") AS tagNames \n"
1310 +
"(SELECT tsk_files.obj_id as objId2, tsk_files.size AS fileSize \n"
1311 +
"FROM blackboard_artifacts INNER JOIN tsk_files \n"
1312 +
"ON blackboard_artifacts.obj_id = tsk_files.obj_id) AS fileData \n"
1313 +
"ON tagNames.objId = fileData.objId2 \n"
1315 +
"(SELECT value_text AS comment, artifact_id AS tagArtifactId FROM blackboard_attributes WHERE attribute_type_id = "
1316 + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT.getTypeID() +
") AS tagComments \n"
1317 +
"ON tagNames.artifactId = tagComments.tagArtifactId");
1319 while (resultSet.next()) {
1320 long objId = resultSet.getLong(
"objId");
1321 long fileSize = resultSet.getLong(
"fileSize");
1322 String tagName = resultSet.getString(
"name");
1323 String tagComment = resultSet.getString(
"comment");
1324 if (tagComment == null) {
1328 if (tagName != null && !tagName.isEmpty()) {
1331 if (tagNames.containsKey(tagName)) {
1332 tagNameIndex = tagNames.get(tagName);
1334 statement2.execute(
"INSERT INTO tag_names (display_name, description, color) "
1335 +
"VALUES(\"" + tagName +
"\", \"\", \"None\")");
1336 tagNames.put(tagName, tagNameCounter);
1337 tagNameIndex = tagNameCounter;
1341 statement2.execute(
"INSERT INTO content_tags (obj_id, tag_name_id, comment, begin_byte_offset, end_byte_offset) "
1342 +
"VALUES(" + objId +
", " + tagNameIndex +
", \"" + tagComment +
"\", 0, " + fileSize +
")");
1349 resultSet = statement.executeQuery(
"SELECT * FROM \n"
1350 +
"(SELECT blackboard_artifacts.obj_id AS objId, blackboard_attributes.artifact_id AS artifactId, "
1351 +
"blackboard_attributes.value_text AS name\n"
1352 +
"FROM blackboard_artifacts INNER JOIN blackboard_attributes \n"
1353 +
"ON blackboard_artifacts.artifact_id = blackboard_attributes.artifact_id \n"
1354 +
"WHERE blackboard_artifacts.artifact_type_id = "
1355 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID()
1356 +
" AND blackboard_attributes.attribute_type_id = " + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TAG_NAME.getTypeID()
1357 +
") AS tagNames \n"
1359 +
"(SELECT value_int64 AS taggedArtifactId, artifact_id AS associatedArtifactId FROM blackboard_attributes WHERE attribute_type_id = "
1360 + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TAGGED_ARTIFACT.getTypeID() +
") AS tagArtifacts \n"
1361 +
"ON tagNames.artifactId = tagArtifacts.associatedArtifactId \n"
1363 +
"(SELECT value_text AS comment, artifact_id AS commentArtifactId FROM blackboard_attributes WHERE attribute_type_id = "
1364 + BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT.getTypeID() +
") AS tagComments \n"
1365 +
"ON tagNames.artifactId = tagComments.commentArtifactId");
1367 while (resultSet.next()) {
1368 long artifactId = resultSet.getLong(
"taggedArtifactId");
1369 String tagName = resultSet.getString(
"name");
1370 String tagComment = resultSet.getString(
"comment");
1371 if (tagComment == null) {
1374 if (tagName != null && !tagName.isEmpty()) {
1377 if (tagNames.containsKey(tagName)) {
1378 tagNameIndex = tagNames.get(tagName);
1380 statement2.execute(
"INSERT INTO tag_names (display_name, description, color) "
1381 +
"VALUES(\"" + tagName +
"\", \"\", \"None\")");
1382 tagNames.put(tagName, tagNameCounter);
1383 tagNameIndex = tagNameCounter;
1387 statement2.execute(
"INSERT INTO blackboard_artifact_tags (artifact_id, tag_name_id, comment) "
1388 +
"VALUES(" + artifactId +
", " + tagNameIndex +
", \"" + tagComment +
"\")");
1394 "DELETE FROM blackboard_attributes WHERE artifact_id IN "
1395 +
"(SELECT artifact_id FROM blackboard_artifacts WHERE artifact_type_id = "
1396 + ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID()
1397 +
" OR artifact_type_id = " + ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID() +
");");
1399 "DELETE FROM blackboard_artifacts WHERE artifact_type_id = "
1400 + ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID()
1401 +
" OR artifact_type_id = " + ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID() +
";");
1403 return new CaseDbSchemaVersionNumber(3, 0);
1405 closeStatement(updateStatement);
1406 closeResultSet(resultSet);
1407 closeStatement(statement);
1408 closeStatement(statement2);
1426 private CaseDbSchemaVersionNumber updateFromSchema3toSchema4(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1427 if (schemaVersion.getMajor() != 3) {
1428 return schemaVersion;
1431 Statement statement = null;
1432 ResultSet resultSet = null;
1433 Statement queryStatement = null;
1434 ResultSet queryResultSet = null;
1435 Statement updateStatement = null;
1440 statement = connection.createStatement();
1441 updateStatement = connection.createStatement();
1442 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN mime_type TEXT;");
1443 resultSet = statement.executeQuery(
"SELECT files.obj_id AS obj_id, attrs.value_text AS value_text "
1444 +
"FROM tsk_files AS files, blackboard_attributes AS attrs, blackboard_artifacts AS arts "
1445 +
"WHERE files.obj_id = arts.obj_id AND "
1446 +
"arts.artifact_id = attrs.artifact_id AND "
1447 +
"arts.artifact_type_id = 1 AND "
1448 +
"attrs.attribute_type_id = 62");
1449 while (resultSet.next()) {
1450 updateStatement.executeUpdate(
1452 +
"SET mime_type = '" + resultSet.getString(
"value_text") +
"' "
1453 +
"WHERE tsk_files.obj_id = " + resultSet.getInt(
"obj_id") +
";");
1458 statement.execute(
"ALTER TABLE blackboard_attribute_types ADD COLUMN value_type INTEGER NOT NULL DEFAULT -1;");
1459 resultSet = statement.executeQuery(
"SELECT * FROM blackboard_attribute_types AS types");
1460 while (resultSet.next()) {
1461 int attributeTypeId = resultSet.getInt(
"attribute_type_id");
1462 String attributeLabel = resultSet.getString(
"type_name");
1463 if (attributeTypeId < Blackboard.MIN_USER_DEFINED_TYPE_ID) {
1464 updateStatement.executeUpdate(
1465 "UPDATE blackboard_attribute_types "
1466 +
"SET value_type = " + ATTRIBUTE_TYPE.fromLabel(attributeLabel).getValueType().getType() +
" "
1467 +
"WHERE blackboard_attribute_types.attribute_type_id = " + attributeTypeId +
";");
1473 queryStatement = connection.createStatement();
1474 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));");
1475 resultSet = statement.executeQuery(
"SELECT * FROM tsk_objects WHERE par_obj_id IS NULL");
1476 while (resultSet.next()) {
1477 long objectId = resultSet.getLong(
"obj_id");
1478 String timeZone =
"";
1479 queryResultSet = queryStatement.executeQuery(
"SELECT tzone FROM tsk_image_info WHERE obj_id = " + objectId);
1480 if (queryResultSet.next()) {
1481 timeZone = queryResultSet.getString(
"tzone");
1483 queryResultSet.close();
1484 updateStatement.executeUpdate(
"INSERT INTO data_source_info (obj_id, device_id, time_zone) "
1485 +
"VALUES(" + objectId +
", '" + UUID.randomUUID().toString() +
"' , '" + timeZone +
"');");
1499 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN data_source_obj_id BIGINT NOT NULL DEFAULT -1;");
1500 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");
1501 while (resultSet.next()) {
1502 long fileId = resultSet.getLong(
"obj_id");
1503 long dataSourceId = getDataSourceObjectId(connection, fileId);
1504 updateStatement.executeUpdate(
"UPDATE tsk_files SET data_source_obj_id = " + dataSourceId +
" WHERE obj_id = " + fileId +
";");
1507 statement.execute(
"CREATE TABLE ingest_module_types (type_id INTEGER PRIMARY KEY, type_name TEXT NOT NULL)");
1508 statement.execute(
"CREATE TABLE ingest_job_status_types (type_id INTEGER PRIMARY KEY, type_name TEXT NOT NULL)");
1509 if (this.dbType.equals(DbType.SQLITE)) {
1510 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));");
1511 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));");
1513 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));");
1514 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));");
1517 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));");
1518 initIngestModuleTypes(connection);
1519 initIngestStatusTypes(connection);
1521 return new CaseDbSchemaVersionNumber(4, 0);
1524 closeResultSet(queryResultSet);
1525 closeStatement(queryStatement);
1526 closeStatement(updateStatement);
1527 closeResultSet(resultSet);
1528 closeStatement(statement);
1546 private CaseDbSchemaVersionNumber updateFromSchema4toSchema5(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1547 if (schemaVersion.getMajor() != 4) {
1548 return schemaVersion;
1551 Statement statement = null;
1555 statement = connection.createStatement();
1556 statement.execute(
"CREATE TABLE review_statuses (review_status_id INTEGER PRIMARY KEY, review_status_name TEXT NOT NULL, display_name TEXT NOT NULL)");
1566 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN review_status_id INTEGER NOT NULL DEFAULT " + BlackboardArtifact.ReviewStatus.UNDECIDED.getID());
1569 statement.execute(
"CREATE TABLE file_encoding_types (encoding_type INTEGER PRIMARY KEY, name TEXT NOT NULL);");
1570 initEncodingTypes(connection);
1577 initReviewStatuses(connection);
1582 statement.execute(
"ALTER TABLE tsk_files_path ADD COLUMN encoding_type INTEGER NOT NULL DEFAULT 0;");
1584 return new CaseDbSchemaVersionNumber(5, 0);
1587 closeStatement(statement);
1605 private CaseDbSchemaVersionNumber updateFromSchema5toSchema6(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1606 if (schemaVersion.getMajor() != 5) {
1607 return schemaVersion;
1614 Statement statement = null;
1615 ResultSet resultSet = null;
1621 statement = connection.createStatement();
1622 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)");
1624 resultSet = connection.executeQuery(statement,
"SELECT COUNT(*) AS count FROM review_statuses");
1626 if (resultSet.getLong(
"count") == 0) {
1635 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN review_status_id INTEGER NOT NULL DEFAULT " + BlackboardArtifact.ReviewStatus.UNDECIDED.getID());
1638 return new CaseDbSchemaVersionNumber(6, 0);
1641 closeResultSet(resultSet);
1642 closeStatement(statement);
1660 private CaseDbSchemaVersionNumber updateFromSchema6toSchema7(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1661 if (schemaVersion.getMajor() != 6) {
1662 return schemaVersion;
1668 Statement statement = null;
1669 Statement updstatement = null;
1670 ResultSet resultSet = null;
1673 statement = connection.createStatement();
1674 updstatement = connection.createStatement();
1675 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN extension TEXT");
1677 resultSet = connection.executeQuery(statement,
"SELECT obj_id,name FROM tsk_files");
1678 while (resultSet.next()) {
1679 long objID = resultSet.getLong(
"obj_id");
1680 String name = resultSet.getString(
"name");
1681 updstatement.executeUpdate(
"UPDATE tsk_files SET extension = '" +
escapeSingleQuotes(extractExtension(name)) +
"' "
1682 +
"WHERE obj_id = " + objID);
1685 statement.execute(
"CREATE INDEX file_extension ON tsk_files ( extension )");
1688 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN artifact_obj_id INTEGER NOT NULL DEFAULT -1");
1690 return new CaseDbSchemaVersionNumber(7, 0);
1693 closeResultSet(resultSet);
1694 closeStatement(statement);
1695 closeStatement(updstatement);
1713 private CaseDbSchemaVersionNumber updateFromSchema7toSchema7dot1(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1714 if (schemaVersion.getMajor() != 7) {
1715 return schemaVersion;
1718 if (schemaVersion.getMinor() != 0) {
1719 return schemaVersion;
1725 Statement statement = null;
1726 ResultSet resultSet = null;
1729 statement = connection.createStatement();
1732 if (schemaVersion.getMinor() == 0) {
1734 statement.execute(
"ALTER TABLE tsk_db_info ADD COLUMN schema_minor_ver INTEGER DEFAULT 1");
1736 return new CaseDbSchemaVersionNumber(7, 1);
1739 closeResultSet(resultSet);
1740 closeStatement(statement);
1758 private CaseDbSchemaVersionNumber updateFromSchema7dot1toSchema7dot2(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1759 if (schemaVersion.getMajor() != 7) {
1760 return schemaVersion;
1763 if (schemaVersion.getMinor() != 1) {
1764 return schemaVersion;
1767 Statement statement = null;
1768 Statement updstatement = null;
1769 ResultSet resultSet = null;
1773 statement = connection.createStatement();
1774 statement.execute(
"ALTER TABLE blackboard_artifacts ADD COLUMN data_source_obj_id INTEGER NOT NULL DEFAULT -1");
1777 updstatement = connection.createStatement();
1778 resultSet = connection.executeQuery(statement,
"SELECT artifact_id, obj_id FROM blackboard_artifacts");
1779 while (resultSet.next()) {
1780 long artifact_id = resultSet.getLong(
"artifact_id");
1781 long obj_id = resultSet.getLong(
"obj_id");
1782 long data_source_obj_id = getDataSourceObjectId(connection, obj_id);
1783 updstatement.executeUpdate(
"UPDATE blackboard_artifacts SET data_source_obj_id = " + data_source_obj_id +
" "
1784 +
"WHERE artifact_id = " + artifact_id);
1786 closeResultSet(resultSet);
1787 closeStatement(statement);
1788 closeStatement(updstatement);
1793 statement = connection.createStatement();
1794 statement.execute(
"ALTER TABLE tag_names ADD COLUMN knownStatus INTEGER NOT NULL DEFAULT " + TskData.FileKnown.UNKNOWN.getFileKnownValue());
1797 if (this.dbType.equals(DbType.SQLITE)) {
1798 statement.execute(
"CREATE TABLE account_types (account_type_id INTEGER PRIMARY KEY, type_name TEXT UNIQUE NOT NULL, display_name TEXT NOT NULL)");
1799 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))");
1800 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))");
1802 statement.execute(
"CREATE TABLE account_types (account_type_id BIGSERIAL PRIMARY KEY, type_name TEXT UNIQUE NOT NULL, display_name TEXT NOT NULL)");
1803 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))");
1804 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))");
1808 statement.execute(
"CREATE INDEX artifact_artifact_objID ON blackboard_artifacts(artifact_obj_id)");
1809 statement.execute(
"CREATE INDEX relationships_account1 ON account_relationships(account1_id)");
1810 statement.execute(
"CREATE INDEX relationships_account2 ON account_relationships(account2_id)");
1811 statement.execute(
"CREATE INDEX relationships_relationship_source_obj_id ON account_relationships(relationship_source_obj_id)");
1812 statement.execute(
"CREATE INDEX relationships_date_time ON account_relationships(date_time)");
1813 statement.execute(
"CREATE INDEX relationships_relationship_type ON account_relationships(relationship_type)");
1814 statement.execute(
"CREATE INDEX relationships_data_source_obj_id ON account_relationships(data_source_obj_id)");
1816 return new CaseDbSchemaVersionNumber(7, 2);
1818 closeResultSet(resultSet);
1819 closeStatement(statement);
1820 closeStatement(updstatement);
1838 private CaseDbSchemaVersionNumber updateFromSchema7dot2toSchema8dot0(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1839 if (schemaVersion.getMajor() != 7) {
1840 return schemaVersion;
1843 if (schemaVersion.getMinor() != 2) {
1844 return schemaVersion;
1847 Statement updateSchemaStatement = connection.createStatement();
1848 Statement getExistingReportsStatement = connection.createStatement();
1849 ResultSet resultSet = null;
1850 ResultSet existingReports = null;
1858 updateSchemaStatement.execute(
"ALTER TABLE reports RENAME TO old_reports");
1861 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))");
1864 existingReports = getExistingReportsStatement.executeQuery(
"SELECT * FROM old_reports");
1865 while (existingReports.next()) {
1866 String path = existingReports.getString(2);
1867 long crtime = existingReports.getInt(3);
1868 String sourceModule = existingReports.getString(4);
1869 String reportName = existingReports.getString(5);
1871 PreparedStatement insertObjectStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_OBJECT, Statement.RETURN_GENERATED_KEYS);
1872 insertObjectStatement.clearParameters();
1873 insertObjectStatement.setNull(1, java.sql.Types.BIGINT);
1874 insertObjectStatement.setLong(2, TskData.ObjectType.REPORT.getObjectType());
1875 connection.executeUpdate(insertObjectStatement);
1876 resultSet = insertObjectStatement.getGeneratedKeys();
1877 if (!resultSet.next()) {
1878 throw new TskCoreException(String.format(
"Failed to INSERT report %s (%s) in tsk_objects table", reportName, path));
1880 long objectId = resultSet.getLong(1);
1883 PreparedStatement insertReportStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_REPORT);
1884 insertReportStatement.clearParameters();
1885 insertReportStatement.setLong(1, objectId);
1886 insertReportStatement.setString(2, path);
1887 insertReportStatement.setLong(3, crtime);
1888 insertReportStatement.setString(4, sourceModule);
1889 insertReportStatement.setString(5, reportName);
1890 connection.executeUpdate(insertReportStatement);
1894 updateSchemaStatement.execute(
"DROP TABLE old_reports");
1896 return new CaseDbSchemaVersionNumber(8, 0);
1898 closeResultSet(resultSet);
1899 closeResultSet(existingReports);
1900 closeStatement(updateSchemaStatement);
1901 closeStatement(getExistingReportsStatement);
1919 private CaseDbSchemaVersionNumber updateFromSchema8dot0toSchema8dot1(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1920 if (schemaVersion.getMajor() != 8) {
1921 return schemaVersion;
1924 if (schemaVersion.getMinor() != 0) {
1925 return schemaVersion;
1930 try (Statement statement = connection.createStatement();) {
1932 if (this.dbType.equals(DbType.SQLITE)) {
1933 statement.execute(
"CREATE TABLE tsk_examiners (examiner_id INTEGER PRIMARY KEY, login_name TEXT NOT NULL, display_name TEXT, UNIQUE(login_name) )");
1934 statement.execute(
"ALTER TABLE content_tags ADD COLUMN examiner_id INTEGER REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1935 statement.execute(
"ALTER TABLE blackboard_artifact_tags ADD COLUMN examiner_id INTEGER REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1937 statement.execute(
"CREATE TABLE tsk_examiners (examiner_id BIGSERIAL PRIMARY KEY, login_name TEXT NOT NULL, display_name TEXT, UNIQUE(login_name))");
1938 statement.execute(
"ALTER TABLE content_tags ADD COLUMN examiner_id BIGINT REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1939 statement.execute(
"ALTER TABLE blackboard_artifact_tags ADD COLUMN examiner_id BIGINT REFERENCES tsk_examiners(examiner_id) DEFAULT NULL");
1942 return new CaseDbSchemaVersionNumber(8, 1);
1961 private CaseDbSchemaVersionNumber updateFromSchema8dot1toSchema8dot2(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
1962 if (schemaVersion.getMajor() != 8) {
1963 return schemaVersion;
1966 if (schemaVersion.getMinor() != 1) {
1967 return schemaVersion;
1972 try (Statement statement = connection.createStatement();) {
1973 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN sha1 TEXT DEFAULT NULL");
1974 statement.execute(
"ALTER TABLE tsk_image_info ADD COLUMN sha256 TEXT DEFAULT NULL");
1976 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_details TEXT");
1984 statement.execute(
"CREATE TABLE tsk_db_info_extended (name TEXT PRIMARY KEY, value TEXT NOT NULL)");
1985 ResultSet result = statement.executeQuery(
"SELECT tsk_ver FROM tsk_db_info");
1987 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + TSK_VERSION_KEY +
"', '" + result.getLong(
"tsk_ver") +
"')");
1988 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + SCHEMA_MAJOR_VERSION_KEY +
"', '8')");
1989 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + SCHEMA_MINOR_VERSION_KEY +
"', '2')");
1990 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + CREATION_SCHEMA_MAJOR_VERSION_KEY +
"', '0')");
1991 statement.execute(
"INSERT INTO tsk_db_info_extended (name, value) VALUES ('" + CREATION_SCHEMA_MINOR_VERSION_KEY +
"', '0')");
1993 String primaryKeyType;
1996 primaryKeyType =
"BIGSERIAL";
1999 primaryKeyType =
"INTEGER";
2002 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
2006 statement.execute(
"CREATE TABLE tsk_event_types ("
2007 +
" event_type_id " + primaryKeyType +
" PRIMARY KEY, "
2008 +
" display_name TEXT UNIQUE NOT NULL, "
2009 +
" super_type_id INTEGER REFERENCES tsk_event_types(event_type_id) )");
2010 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2011 +
" values( 0, 'Event Types', null)");
2012 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2013 +
" values(1, 'File System', 0)");
2014 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2015 +
" values(2, 'Web Activity', 0)");
2016 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2017 +
" values(3, 'Misc Types', 0)");
2018 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2019 +
" values(4, 'Modified', 1)");
2020 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2021 +
" values(5, 'Accessed', 1)");
2022 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2023 +
" values(6, 'Created', 1)");
2024 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2025 +
" values(7, 'Changed', 1)");
2028 statement.execute(
"CREATE TABLE tsk_event_descriptions ("
2029 +
" event_description_id " + primaryKeyType +
" PRIMARY KEY, "
2030 +
" full_description TEXT NOT NULL, "
2031 +
" med_description TEXT, "
2032 +
" short_description TEXT,"
2033 +
" data_source_obj_id BIGINT NOT NULL, "
2034 +
" file_obj_id BIGINT NOT NULL, "
2035 +
" artifact_id BIGINT, "
2036 +
" hash_hit INTEGER NOT NULL, "
2037 +
" tagged INTEGER NOT NULL, "
2038 +
" FOREIGN KEY(data_source_obj_id) REFERENCES data_source_info(obj_id), "
2039 +
" FOREIGN KEY(file_obj_id) REFERENCES tsk_files(obj_id), "
2040 +
" FOREIGN KEY(artifact_id) REFERENCES blackboard_artifacts(artifact_id))"
2043 statement.execute(
"CREATE TABLE tsk_events ( "
2044 +
" event_id " + primaryKeyType +
" PRIMARY KEY, "
2045 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
2046 +
" event_description_id BIGINT NOT NULL REFERENCES tsk_event_descriptions(event_description_id) ,"
2047 +
" time INTEGER NOT NULL) "
2051 statement.execute(
"CREATE INDEX events_time ON tsk_events(time)");
2052 statement.execute(
"CREATE INDEX events_type ON tsk_events(event_type_id)");
2053 statement.execute(
"CREATE INDEX events_data_source_obj_id ON tsk_event_descriptions(data_source_obj_id) ");
2054 statement.execute(
"CREATE INDEX events_file_obj_id ON tsk_event_descriptions(file_obj_id) ");
2055 statement.execute(
"CREATE INDEX events_artifact_id ON tsk_event_descriptions(artifact_id) ");
2056 statement.execute(
"CREATE INDEX events_sub_type_time ON tsk_events(event_type_id, time) ");
2057 return new CaseDbSchemaVersionNumber(8, 2);
2077 private CaseDbSchemaVersionNumber updateFromSchema8dot2toSchema8dot3(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2078 if (schemaVersion.getMajor() != 8) {
2079 return schemaVersion;
2082 if (schemaVersion.getMinor() != 2) {
2083 return schemaVersion;
2088 ResultSet resultSet = null;
2090 try (Statement statement = connection.createStatement();) {
2095 String primaryKeyType;
2098 primaryKeyType =
"BIGSERIAL";
2101 primaryKeyType =
"INTEGER";
2104 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
2108 statement.execute(
"CREATE TABLE IF NOT EXISTS tsk_event_types ("
2109 +
" event_type_id " + primaryKeyType +
" PRIMARY KEY, "
2110 +
" display_name TEXT UNIQUE NOT NULL, "
2111 +
" super_type_id INTEGER REFERENCES tsk_event_types(event_type_id) )");
2113 resultSet = statement.executeQuery(
"SELECT * from tsk_event_types");
2117 if (!resultSet.next()) {
2119 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2120 +
" values( 0, 'Event Types', null)");
2121 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2122 +
" values(1, 'File System', 0)");
2123 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2124 +
" values(2, 'Web Activity', 0)");
2125 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2126 +
" values(3, 'Misc Types', 0)");
2127 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2128 +
" values(4, 'Modified', 1)");
2129 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2130 +
" values(5, 'Accessed', 1)");
2131 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2132 +
" values(6, 'Created', 1)");
2133 statement.execute(
"insert into tsk_event_types(event_type_id, display_name, super_type_id)"
2134 +
" values(7, 'Changed', 1)");
2139 statement.execute(
"DROP TABLE IF EXISTS tsk_events");
2143 statement.execute(
"DROP TABLE IF EXISTS tsk_event_descriptions");
2146 statement.execute(
"CREATE TABLE tsk_event_descriptions ("
2147 +
" event_description_id " + primaryKeyType +
" PRIMARY KEY, "
2148 +
" full_description TEXT NOT NULL, "
2149 +
" med_description TEXT, "
2150 +
" short_description TEXT,"
2151 +
" data_source_obj_id BIGINT NOT NULL, "
2152 +
" file_obj_id BIGINT NOT NULL, "
2153 +
" artifact_id BIGINT, "
2154 +
" hash_hit INTEGER NOT NULL, "
2155 +
" tagged INTEGER NOT NULL, "
2156 +
" UNIQUE(full_description, file_obj_id, artifact_id), "
2157 +
" FOREIGN KEY(data_source_obj_id) REFERENCES data_source_info(obj_id), "
2158 +
" FOREIGN KEY(file_obj_id) REFERENCES tsk_files(obj_id), "
2159 +
" FOREIGN KEY(artifact_id) REFERENCES blackboard_artifacts(artifact_id))"
2163 statement.execute(
"CREATE TABLE tsk_events ( "
2164 +
" event_id " + primaryKeyType +
" PRIMARY KEY, "
2165 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
2166 +
" event_description_id BIGINT NOT NULL REFERENCES tsk_event_descriptions(event_description_id) ,"
2167 +
" time INTEGER NOT NULL, "
2168 +
" UNIQUE (event_type_id, event_description_id, time))"
2172 statement.execute(
"UPDATE tsk_db_info_extended SET name = 'CREATION_SCHEMA_MAJOR_VERSION' WHERE name = 'CREATED_SCHEMA_MAJOR_VERSION'");
2173 statement.execute(
"UPDATE tsk_db_info_extended SET name = 'CREATION_SCHEMA_MINOR_VERSION' WHERE name = 'CREATED_SCHEMA_MINOR_VERSION'");
2175 return new CaseDbSchemaVersionNumber(8, 3);
2177 closeResultSet(resultSet);
2203 private CaseDbSchemaVersionNumber updateFromSchema8dot3toSchema8dot4(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2204 if (schemaVersion.getMajor() != 8) {
2205 return schemaVersion;
2208 if (schemaVersion.getMinor() != 3) {
2209 return schemaVersion;
2212 Statement statement = connection.createStatement();
2213 ResultSet results = null;
2220 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
2226 results = statement.executeQuery(
"SELECT column_name FROM information_schema.columns "
2227 +
"WHERE table_name='tsk_event_descriptions' and column_name='file_obj_id'");
2228 if (results.next()) {
2230 statement.execute(
"ALTER TABLE tsk_event_descriptions "
2231 +
"RENAME COLUMN file_obj_id TO content_obj_id");
2235 statement.execute(
"CREATE TABLE temp_tsk_events ( "
2236 +
" event_id BIGSERIAL PRIMARY KEY, "
2237 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
2238 +
" event_description_id BIGINT NOT NULL REFERENCES tsk_event_descriptions(event_description_id),"
2239 +
" time BIGINT NOT NULL, "
2240 +
" UNIQUE (event_type_id, event_description_id, time))"
2244 statement.execute(
"INSERT INTO temp_tsk_events(event_id, event_type_id, "
2245 +
"event_description_id, time) SELECT * FROM tsk_events");
2248 statement.execute(
"DROP TABLE tsk_events");
2251 statement.execute(
"ALTER TABLE temp_tsk_events RENAME TO tsk_events");
2254 statement.execute(
"CREATE INDEX events_data_source_obj_id ON tsk_event_descriptions(data_source_obj_id) ");
2255 statement.execute(
"CREATE INDEX events_content_obj_id ON tsk_event_descriptions(content_obj_id) ");
2256 statement.execute(
"CREATE INDEX events_artifact_id ON tsk_event_descriptions(artifact_id) ");
2257 statement.execute(
"CREATE INDEX events_sub_type_time ON tsk_events(event_type_id, time) ");
2258 statement.execute(
"CREATE INDEX events_time ON tsk_events(time) ");
2262 boolean hasMisnamedColumn =
false;
2263 results = statement.executeQuery(
"pragma table_info('tsk_event_descriptions')");
2264 while (results.next()) {
2265 if (results.getString(
"name") != null && results.getString(
"name").equals(
"file_obj_id")) {
2266 hasMisnamedColumn =
true;
2271 if (hasMisnamedColumn) {
2273 statement.execute(
"CREATE TABLE temp_tsk_event_descriptions ("
2274 +
" event_description_id INTEGER PRIMARY KEY, "
2275 +
" full_description TEXT NOT NULL, "
2276 +
" med_description TEXT, "
2277 +
" short_description TEXT,"
2278 +
" data_source_obj_id BIGINT NOT NULL, "
2279 +
" content_obj_id BIGINT NOT NULL, "
2280 +
" artifact_id BIGINT, "
2281 +
" hash_hit INTEGER NOT NULL, "
2282 +
" tagged INTEGER NOT NULL, "
2283 +
" UNIQUE(full_description, content_obj_id, artifact_id), "
2284 +
" FOREIGN KEY(data_source_obj_id) REFERENCES data_source_info(obj_id), "
2285 +
" FOREIGN KEY(content_obj_id) REFERENCES tsk_files(obj_id), "
2286 +
" FOREIGN KEY(artifact_id) REFERENCES blackboard_artifacts(artifact_id))"
2289 statement.execute(
"CREATE TABLE temp_tsk_events ( "
2290 +
" event_id INTEGER PRIMARY KEY, "
2291 +
" event_type_id BIGINT NOT NULL REFERENCES tsk_event_types(event_type_id) ,"
2292 +
" event_description_id BIGINT NOT NULL REFERENCES temp_tsk_event_descriptions(event_description_id),"
2293 +
" time INTEGER NOT NULL, "
2294 +
" UNIQUE (event_type_id, event_description_id, time))"
2298 statement.execute(
"INSERT INTO temp_tsk_event_descriptions(event_description_id, full_description, "
2299 +
"med_description, short_description, data_source_obj_id, content_obj_id, artifact_id, "
2300 +
"hash_hit, tagged) SELECT * FROM tsk_event_descriptions");
2302 statement.execute(
"INSERT INTO temp_tsk_events(event_id, event_type_id, "
2303 +
"event_description_id, time) SELECT * FROM tsk_events");
2306 statement.execute(
"DROP TABLE tsk_events");
2307 statement.execute(
"DROP TABLE tsk_event_descriptions");
2310 statement.execute(
"ALTER TABLE temp_tsk_event_descriptions RENAME TO tsk_event_descriptions");
2311 statement.execute(
"ALTER TABLE temp_tsk_events RENAME TO tsk_events");
2314 statement.execute(
"CREATE INDEX events_data_source_obj_id ON tsk_event_descriptions(data_source_obj_id) ");
2315 statement.execute(
"CREATE INDEX events_content_obj_id ON tsk_event_descriptions(content_obj_id) ");
2316 statement.execute(
"CREATE INDEX events_artifact_id ON tsk_event_descriptions(artifact_id) ");
2317 statement.execute(
"CREATE INDEX events_sub_type_time ON tsk_events(event_type_id, time) ");
2318 statement.execute(
"CREATE INDEX events_time ON tsk_events(time) ");
2322 throw new TskCoreException(
"Unsupported data base type: " +
getDatabaseType().toString());
2326 if (this.dbType.equals(DbType.SQLITE)) {
2327 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)");
2329 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)");
2333 insertAccountTypeIfNotExists(statement,
"IMO",
"IMO");
2334 insertAccountTypeIfNotExists(statement,
"LINE",
"LINE");
2335 insertAccountTypeIfNotExists(statement,
"SKYPE",
"Skype");
2336 insertAccountTypeIfNotExists(statement,
"TANGO",
"Tango");
2337 insertAccountTypeIfNotExists(statement,
"TEXTNOW",
"TextNow");
2338 insertAccountTypeIfNotExists(statement,
"THREEMA",
"ThreeMa");
2339 insertAccountTypeIfNotExists(statement,
"VIBER",
"Viber");
2340 insertAccountTypeIfNotExists(statement,
"XENDER",
"Xender");
2341 insertAccountTypeIfNotExists(statement,
"ZAPYA",
"Zapya");
2342 insertAccountTypeIfNotExists(statement,
"SHAREIT",
"ShareIt");
2344 return new CaseDbSchemaVersionNumber(8, 4);
2346 closeResultSet(results);
2347 closeStatement(statement);
2352 private CaseDbSchemaVersionNumber updateFromSchema8dot4toSchema8dot5(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2353 if (schemaVersion.getMajor() != 8) {
2354 return schemaVersion;
2357 if (schemaVersion.getMinor() != 4) {
2358 return schemaVersion;
2361 Statement statement = connection.createStatement();
2366 statement.execute(
"CREATE TABLE tsk_tag_sets (tag_set_id BIGSERIAL PRIMARY KEY, name TEXT UNIQUE)");
2367 statement.execute(
"ALTER TABLE tag_names ADD COLUMN tag_set_id BIGINT REFERENCES tsk_tag_sets(tag_set_id)");
2370 statement.execute(
"CREATE TABLE tsk_tag_sets (tag_set_id INTEGER PRIMARY KEY, name TEXT UNIQUE)");
2371 statement.execute(
"ALTER TABLE tag_names ADD COLUMN tag_set_id INTEGER REFERENCES tsk_tag_sets(tag_set_id)");
2375 statement.execute(
"ALTER TABLE tag_names ADD COLUMN rank INTEGER");
2383 String insertStmt =
"INSERT INTO tsk_tag_sets (name) VALUES ('Project VIC')";
2385 statement.execute(insertStmt, Statement.RETURN_GENERATED_KEYS);
2387 statement.execute(insertStmt);
2389 try (ResultSet resultSet = statement.getGeneratedKeys()) {
2390 if (resultSet != null && resultSet.next()) {
2391 int tagSetId = resultSet.getInt(1);
2393 String updateQuery =
"UPDATE tag_names SET tag_set_id = %d, color = '%s', rank = %d, display_name = '%s' WHERE display_name = '%s'";
2394 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Red", 1,
"Child Exploitation (Illegal)",
"CAT-1: Child Exploitation (Illegal)"));
2395 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Lime", 2,
"Child Exploitation (Non-Illegal/Age Difficult)",
"CAT-2: Child Exploitation (Non-Illegal/Age Difficult)"));
2396 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Yellow", 3,
"CGI/Animation (Child Exploitive)",
"CAT-3: CGI/Animation (Child Exploitive)"));
2397 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Purple", 4,
"Exemplar/Comparison (Internal Use Only)",
"CAT-4: Exemplar/Comparison (Internal Use Only)"));
2398 statement.executeUpdate(String.format(updateQuery, tagSetId,
"Fuchsia", 5,
"Non-pertinent",
"CAT-5: Non-pertinent"));
2400 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')";
2401 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')";
2402 String deleteCat0 =
"DELETE FROM tag_names WHERE display_name = 'CAT-0: Uncategorized'";
2403 statement.executeUpdate(deleteContentTag);
2404 statement.executeUpdate(deleteArtifactTag);
2405 statement.executeUpdate(deleteCat0);
2408 throw new TskCoreException(
"Failed to retrieve the default tag_set_id from DB");
2418 statement.execute(
"ALTER TABLE tsk_fs_info ADD COLUMN data_source_obj_id BIGINT NOT NULL DEFAULT -1;");
2421 statement.execute(
"ALTER TABLE tsk_fs_info ADD COLUMN data_source_obj_id INTEGER NOT NULL DEFAULT -1;");
2424 Statement updateStatement = connection.createStatement();
2425 try (ResultSet resultSet = statement.executeQuery(
"SELECT obj_id FROM tsk_fs_info")) {
2426 while (resultSet.next()) {
2427 long fsId = resultSet.getLong(
"obj_id");
2428 long dataSourceId = getDataSourceObjectId(connection, fsId);
2429 updateStatement.executeUpdate(
"UPDATE tsk_fs_info SET data_source_obj_id = " + dataSourceId +
" WHERE obj_id = " + fsId +
";");
2432 closeStatement(updateStatement);
2435 return new CaseDbSchemaVersionNumber(8, 5);
2438 closeStatement(statement);
2443 private CaseDbSchemaVersionNumber updateFromSchema8dot5toSchema8dot6(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2444 if (schemaVersion.getMajor() != 8) {
2445 return schemaVersion;
2448 if (schemaVersion.getMinor() != 5) {
2449 return schemaVersion;
2452 Statement statement = connection.createStatement();
2455 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN sha256 TEXT");
2457 return new CaseDbSchemaVersionNumber(8, 6);
2460 closeStatement(statement);
2465 @SuppressWarnings(
"deprecation")
2466 private CaseDbSchemaVersionNumber updateFromSchema8dot6toSchema9dot0(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection) throws SQLException, TskCoreException {
2467 if (schemaVersion.getMajor() != 8) {
2468 return schemaVersion;
2471 if (schemaVersion.getMinor() != 6) {
2472 return schemaVersion;
2475 Statement statement = connection.createStatement();
2478 String dateDataType =
"BIGINT";
2479 String bigIntDataType =
"BIGINT";
2480 String blobDataType =
"BYTEA";
2481 String primaryKeyType =
"BIGSERIAL";
2483 if (this.dbType.equals(DbType.SQLITE)) {
2484 dateDataType =
"INTEGER";
2485 bigIntDataType =
"INTEGER";
2486 blobDataType =
"BLOB";
2487 primaryKeyType =
"INTEGER";
2489 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN added_date_time " + dateDataType);
2490 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_tool_settings TEXT");
2491 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_tool_name TEXT");
2492 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN acquisition_tool_version TEXT");
2497 statement.execute(
"ALTER TABLE blackboard_artifact_types ADD COLUMN category_type INTEGER DEFAULT 0");
2498 String analysisTypeObjIdList
2499 = BlackboardArtifact.ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID() +
", "
2500 + BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID() +
", "
2501 + BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT.getTypeID() +
", "
2502 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_FILE.getTypeID() +
", "
2503 + BlackboardArtifact.ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getTypeID() +
", "
2504 + BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED.getTypeID() +
", "
2505 + BlackboardArtifact.ARTIFACT_TYPE.TSK_EXT_MISMATCH_DETECTED.getTypeID() +
", "
2506 + BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID() +
", "
2507 + BlackboardArtifact.ARTIFACT_TYPE.TSK_FACE_DETECTED.getTypeID() +
", "
2508 + BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_SUSPECTED.getTypeID() +
", "
2509 + BlackboardArtifact.ARTIFACT_TYPE.TSK_OBJECT_DETECTED.getTypeID() +
", "
2510 + BlackboardArtifact.ARTIFACT_TYPE.TSK_VERIFICATION_FAILED.getTypeID() +
", "
2511 + BlackboardArtifact.ARTIFACT_TYPE.TSK_DATA_SOURCE_USAGE.getTypeID() +
", "
2512 + BlackboardArtifact.ARTIFACT_TYPE.TSK_USER_CONTENT_SUSPECTED.getTypeID() +
", "
2513 + BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_ACCOUNT_TYPE.getTypeID() +
", "
2514 + BlackboardArtifact.ARTIFACT_TYPE.TSK_YARA_HIT.getTypeID() +
", "
2515 + BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_CATEGORIZATION.getTypeID();
2516 statement.execute(
"UPDATE blackboard_artifact_types SET category_type = " + BlackboardArtifact.Category.ANALYSIS_RESULT.getID()
2517 +
" WHERE artifact_type_id IN (" + analysisTypeObjIdList +
")");
2520 statement.execute(
"CREATE TABLE tsk_file_attributes (id " + primaryKeyType +
" PRIMARY KEY, "
2521 +
"obj_id " + bigIntDataType +
" NOT NULL, "
2522 +
"attribute_type_id " + bigIntDataType +
" NOT NULL, "
2523 +
"value_type INTEGER NOT NULL, value_byte " + blobDataType +
", "
2524 +
"value_text TEXT, value_int32 INTEGER, value_int64 " + bigIntDataType +
", value_double NUMERIC(20, 10), "
2525 +
"FOREIGN KEY(obj_id) REFERENCES tsk_files(obj_id) ON DELETE CASCADE, "
2526 +
"FOREIGN KEY(attribute_type_id) REFERENCES blackboard_attribute_types(attribute_type_id))");
2529 statement.execute(
"CREATE TABLE tsk_analysis_results (artifact_obj_id " + bigIntDataType +
" PRIMARY KEY, "
2530 +
"conclusion TEXT, "
2531 +
"significance INTEGER NOT NULL, "
2539 +
"configuration TEXT, justification TEXT, "
2540 +
"ignore_score INTEGER DEFAULT 0 "
2543 statement.execute(
"CREATE TABLE tsk_aggregate_score( obj_id " + bigIntDataType +
" PRIMARY KEY, "
2544 +
"data_source_obj_id " + bigIntDataType +
", "
2545 +
"significance INTEGER NOT NULL, "
2548 +
"UNIQUE (obj_id),"
2549 +
"FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE, "
2550 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE "
2554 statement.execute(
"CREATE TABLE tsk_persons (id " + primaryKeyType +
" PRIMARY KEY, "
2555 +
"name TEXT NOT NULL, "
2556 +
"UNIQUE(name)) ");
2559 statement.execute(
"CREATE TABLE tsk_hosts (id " + primaryKeyType +
" PRIMARY KEY, "
2560 +
"name TEXT NOT NULL, "
2561 +
"db_status INTEGER DEFAULT 0, "
2562 +
"person_id INTEGER, "
2563 +
"merged_into " + bigIntDataType +
", "
2564 +
"FOREIGN KEY(person_id) REFERENCES tsk_persons(id) ON DELETE SET NULL, "
2565 +
"FOREIGN KEY(merged_into) REFERENCES tsk_hosts(id), "
2566 +
"UNIQUE(name)) ");
2569 statement.execute(
"CREATE TABLE tsk_os_account_realms (id " + primaryKeyType +
" PRIMARY KEY, "
2570 +
"realm_name TEXT DEFAULT NULL, "
2571 +
"realm_addr TEXT DEFAULT NULL, "
2572 +
"realm_signature TEXT NOT NULL, "
2573 +
"scope_host_id " + bigIntDataType +
" DEFAULT NULL, "
2574 +
"scope_confidence INTEGER, "
2575 +
"db_status INTEGER DEFAULT 0, "
2576 +
"merged_into " + bigIntDataType +
" DEFAULT NULL, "
2577 +
"UNIQUE(realm_signature), "
2578 +
"FOREIGN KEY(scope_host_id) REFERENCES tsk_hosts(id),"
2579 +
"FOREIGN KEY(merged_into) REFERENCES tsk_os_account_realms(id) )");
2584 statement.execute(
"ALTER TABLE data_source_info ADD COLUMN host_id INTEGER REFERENCES tsk_hosts(id)");
2585 Statement updateStatement = connection.createStatement();
2586 try (ResultSet resultSet = statement.executeQuery(
"SELECT obj_id, device_id FROM data_source_info")) {
2587 Map<String, Long> hostMap =
new HashMap<>();
2589 while (resultSet.next()) {
2590 long objId = resultSet.getLong(
"obj_id");
2591 String deviceId = resultSet.getString(
"device_id");
2593 if (!hostMap.containsKey(deviceId)) {
2594 String hostName =
"Host " + hostIndex;
2595 updateStatement.execute(
"INSERT INTO tsk_hosts (name, db_status) VALUES ('" + hostName +
"', 0)");
2596 hostMap.put(deviceId, hostIndex);
2599 updateStatement.execute(
"UPDATE data_source_info SET host_id = " + hostMap.get(deviceId) +
" WHERE obj_id = " + objId);
2602 closeStatement(updateStatement);
2605 statement.execute(
"CREATE TABLE tsk_os_accounts (os_account_obj_id " + bigIntDataType +
" PRIMARY KEY, "
2606 +
"login_name TEXT DEFAULT NULL, "
2607 +
"full_name TEXT DEFAULT NULL, "
2608 +
"realm_id " + bigIntDataType +
" NOT NULL, "
2609 +
"addr TEXT DEFAULT NULL, "
2610 +
"signature TEXT NOT NULL, "
2611 +
"status INTEGER, "
2613 +
"created_date " + bigIntDataType +
" DEFAULT NULL, "
2614 +
"db_status INTEGER DEFAULT 0, "
2615 +
"merged_into " + bigIntDataType +
" DEFAULT NULL, "
2616 +
"UNIQUE(signature, realm_id), "
2617 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE, "
2618 +
"FOREIGN KEY(realm_id) REFERENCES tsk_os_account_realms(id),"
2619 +
"FOREIGN KEY(merged_into) REFERENCES tsk_os_accounts(os_account_obj_id) )");
2621 statement.execute(
"CREATE TABLE tsk_os_account_attributes (id " + primaryKeyType +
" PRIMARY KEY, "
2622 +
"os_account_obj_id " + bigIntDataType +
" NOT NULL, "
2623 +
"host_id " + bigIntDataType +
", "
2624 +
"source_obj_id " + bigIntDataType +
", "
2625 +
"attribute_type_id " + bigIntDataType +
" NOT NULL, "
2626 +
"value_type INTEGER NOT NULL, "
2627 +
"value_byte " + bigIntDataType +
", "
2628 +
"value_text TEXT, "
2629 +
"value_int32 INTEGER, value_int64 " + bigIntDataType +
", "
2630 +
"value_double NUMERIC(20, 10), "
2631 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id), "
2632 +
"FOREIGN KEY(host_id) REFERENCES tsk_hosts(id), "
2633 +
"FOREIGN KEY(source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE SET NULL, "
2634 +
"FOREIGN KEY(attribute_type_id) REFERENCES blackboard_attribute_types(attribute_type_id))");
2636 statement.execute(
"CREATE TABLE tsk_os_account_instances (id " + primaryKeyType +
" PRIMARY KEY, "
2637 +
"os_account_obj_id " + bigIntDataType +
" NOT NULL, "
2638 +
"data_source_obj_id " + bigIntDataType +
" NOT NULL, "
2639 +
"instance_type INTEGER NOT NULL, "
2640 +
"UNIQUE(os_account_obj_id, data_source_obj_id), "
2641 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id), "
2642 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE )");
2644 statement.execute(
"CREATE TABLE tsk_data_artifacts ( "
2645 +
"artifact_obj_id " + bigIntDataType +
" PRIMARY KEY, "
2646 +
"os_account_obj_id " + bigIntDataType +
", "
2647 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id)) ");
2650 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN owner_uid TEXT DEFAULT NULL");
2651 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN os_account_obj_id " + bigIntDataType +
" DEFAULT NULL REFERENCES tsk_os_accounts(os_account_obj_id) ");
2654 statement.execute(
"CREATE TABLE tsk_host_addresses (id " + primaryKeyType +
" PRIMARY KEY, "
2655 +
"address_type INTEGER NOT NULL, "
2656 +
"address TEXT NOT NULL, "
2657 +
"UNIQUE(address_type, address)) ");
2659 statement.execute(
"CREATE TABLE tsk_host_address_map (id " + primaryKeyType +
" PRIMARY KEY, "
2660 +
"host_id " + bigIntDataType +
" NOT NULL, "
2661 +
"addr_obj_id " + bigIntDataType +
" NOT NULL, "
2662 +
"source_obj_id " + bigIntDataType +
", "
2663 +
"time " + bigIntDataType +
", "
2664 +
"UNIQUE(host_id, addr_obj_id, time), "
2665 +
"FOREIGN KEY(host_id) REFERENCES tsk_hosts(id) ON DELETE CASCADE, "
2666 +
"FOREIGN KEY(addr_obj_id) REFERENCES tsk_host_addresses(id), "
2667 +
"FOREIGN KEY(source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE SET NULL )");
2670 statement.execute(
"CREATE TABLE tsk_host_address_dns_ip_map (id " + primaryKeyType +
" PRIMARY KEY, "
2671 +
"dns_address_id " + bigIntDataType +
" NOT NULL, "
2672 +
"ip_address_id " + bigIntDataType +
" NOT NULL, "
2673 +
"source_obj_id " + bigIntDataType +
", "
2674 +
"time " + bigIntDataType +
", "
2675 +
"UNIQUE(dns_address_id, ip_address_id, time), "
2676 +
"FOREIGN KEY(dns_address_id) REFERENCES tsk_host_addresses(id) ON DELETE CASCADE, "
2677 +
"FOREIGN KEY(ip_address_id) REFERENCES tsk_host_addresses(id) ON DELETE CASCADE,"
2678 +
"FOREIGN KEY(source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE SET NULL )");
2681 statement.execute(
"CREATE TABLE tsk_host_address_usage (id " + primaryKeyType +
" PRIMARY KEY, "
2682 +
"addr_obj_id " + bigIntDataType +
" NOT NULL, "
2683 +
"obj_id " + bigIntDataType +
" NOT NULL, "
2684 +
"data_source_obj_id " + bigIntDataType +
" NOT NULL, "
2685 +
"UNIQUE(addr_obj_id, obj_id), "
2686 +
"FOREIGN KEY(addr_obj_id) REFERENCES tsk_host_addresses(id) ON DELETE CASCADE, "
2687 +
"FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE )");
2689 return new CaseDbSchemaVersionNumber(9, 0);
2692 closeStatement(statement);
2697 private CaseDbSchemaVersionNumber updateFromSchema9dot0toSchema9dot1(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2698 if (schemaVersion.getMajor() != 9) {
2699 return schemaVersion;
2702 if (schemaVersion.getMinor() != 0) {
2703 return schemaVersion;
2706 Statement statement = connection.createStatement();
2707 ResultSet results = null;
2715 results = statement.executeQuery(
"SELECT column_name FROM information_schema.columns "
2716 +
"WHERE table_name='tsk_analysis_results' and column_name='method_category'");
2717 if (results.next()) {
2719 statement.execute(
"ALTER TABLE tsk_analysis_results "
2720 +
"DROP COLUMN method_category");
2721 statement.execute(
"ALTER TABLE tsk_aggregate_score "
2722 +
"DROP COLUMN method_category");
2728 boolean hasMisnamedColumn =
false;
2729 results = statement.executeQuery(
"pragma table_info('tsk_analysis_results')");
2730 while (results.next()) {
2731 if (results.getString(
"name") != null && results.getString(
"name").equals(
"method_category")) {
2732 hasMisnamedColumn =
true;
2737 if (hasMisnamedColumn) {
2740 statement.execute(
"CREATE TABLE temp_tsk_analysis_results (artifact_obj_id INTEGER PRIMARY KEY, "
2741 +
"conclusion TEXT, "
2742 +
"significance INTEGER NOT NULL, "
2743 +
"configuration TEXT, justification TEXT, "
2744 +
"ignore_score INTEGER DEFAULT 0 "
2746 statement.execute(
"CREATE TABLE temp_tsk_aggregate_score( obj_id INTEGER PRIMARY KEY, "
2747 +
"data_source_obj_id INTEGER, "
2748 +
"significance INTEGER NOT NULL, "
2749 +
"UNIQUE (obj_id),"
2750 +
"FOREIGN KEY(obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE, "
2751 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE "
2755 statement.execute(
"INSERT INTO temp_tsk_analysis_results(artifact_obj_id, "
2756 +
"conclusion, justification, significance, configuration, ignore_score) "
2757 +
"SELECT artifact_obj_id, conclusion, justification, significance, configuration, ignore_score FROM tsk_analysis_results");
2758 statement.execute(
"INSERT INTO temp_tsk_aggregate_score(obj_id, "
2759 +
"data_source_obj_id, significance) "
2760 +
"SELECT obj_id, data_source_obj_id, significance FROM tsk_aggregate_score");
2763 statement.execute(
"DROP TABLE tsk_analysis_results");
2764 statement.execute(
"DROP TABLE tsk_aggregate_score");
2767 statement.execute(
"ALTER TABLE temp_tsk_analysis_results RENAME TO tsk_analysis_results");
2768 statement.execute(
"ALTER TABLE temp_tsk_aggregate_score RENAME TO tsk_aggregate_score");
2773 throw new TskCoreException(
"Unsupported database type: " +
getDatabaseType().toString());
2777 statement.execute(
"CREATE INDEX tsk_file_attributes_obj_id ON tsk_file_attributes(obj_id)");
2779 statement.execute(
"ALTER TABLE tsk_analysis_results ADD COLUMN priority INTEGER NOT NULL DEFAULT " + Score.Priority.NORMAL.getId());
2780 statement.execute(
"ALTER TABLE tsk_aggregate_score ADD COLUMN priority INTEGER NOT NULL DEFAULT " + Score.Priority.NORMAL.getId());
2782 statement.execute(
"UPDATE blackboard_artifact_types SET category_type = 1 WHERE artifact_type_id = 16");
2784 return new CaseDbSchemaVersionNumber(9, 1);
2786 closeResultSet(results);
2787 closeStatement(statement);
2805 private CaseDbSchemaVersionNumber updateFromSchema9dot1toSchema9dot2(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2806 if (schemaVersion.getMajor() != 9) {
2807 return schemaVersion;
2810 if (schemaVersion.getMinor() != 1) {
2811 return schemaVersion;
2814 Statement updateSchemaStatement = connection.createStatement();
2815 ResultSet results = null;
2819 String bigIntDataType =
"BIGINT";
2820 String primaryKeyType =
"BIGSERIAL";
2822 if (this.dbType.equals(DbType.SQLITE)) {
2823 bigIntDataType =
"INTEGER";
2824 primaryKeyType =
"INTEGER";
2830 updateSchemaStatement.execute(
"ALTER TABLE tsk_os_account_instances RENAME TO old_tsk_os_account_instances");
2833 updateSchemaStatement.execute(
"CREATE TABLE tsk_os_account_instances (id " + primaryKeyType +
" PRIMARY KEY, "
2834 +
"os_account_obj_id " + bigIntDataType +
" NOT NULL, "
2835 +
"data_source_obj_id " + bigIntDataType +
" NOT NULL, "
2836 +
"instance_type INTEGER NOT NULL, "
2837 +
"UNIQUE(os_account_obj_id, data_source_obj_id, instance_type), "
2838 +
"FOREIGN KEY(os_account_obj_id) REFERENCES tsk_os_accounts(os_account_obj_id) ON DELETE CASCADE, "
2839 +
"FOREIGN KEY(data_source_obj_id) REFERENCES tsk_objects(obj_id) ON DELETE CASCADE ) ");
2842 updateSchemaStatement.execute(
"INSERT INTO tsk_os_account_instances(os_account_obj_id, "
2843 +
"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");
2846 updateSchemaStatement.execute(
"DROP TABLE old_tsk_os_account_instances");
2848 return new CaseDbSchemaVersionNumber(9, 2);
2850 closeResultSet(results);
2851 closeStatement(updateSchemaStatement);
2856 private CaseDbSchemaVersionNumber updateFromSchema9dot2toSchema9dot3(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2857 if (schemaVersion.getMajor() != 9) {
2858 return schemaVersion;
2861 if (schemaVersion.getMinor() != 2) {
2862 return schemaVersion;
2865 Statement statement = connection.createStatement();
2869 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN sha1 TEXT");
2872 return new CaseDbSchemaVersionNumber(9, 3);
2875 closeStatement(statement);
2880 private CaseDbSchemaVersionNumber updateFromSchema9dot3toSchema9dot4(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2881 if (schemaVersion.getMajor() != 9) {
2882 return schemaVersion;
2885 if (schemaVersion.getMinor() != 3) {
2886 return schemaVersion;
2889 Statement statement = connection.createStatement();
2893 statement.execute(
"CREATE TABLE file_collection_status_types (collection_status_type INTEGER PRIMARY KEY, name TEXT NOT NULL);");
2894 initCollectedStatusTypes(connection);
2897 statement.execute(
"ALTER TABLE tsk_files ADD COLUMN collected INTEGER NOT NULL DEFAULT " +
2898 TskData.CollectedStatus.UNKNOWN.getType() +
";");
2900 return new CaseDbSchemaVersionNumber(9, 4);
2903 closeStatement(statement);
2908 private CaseDbSchemaVersionNumber updateFromSchema9dot4toSchema9dot5(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2909 if (schemaVersion.getMajor() != 9) {
2910 return schemaVersion;
2913 if (schemaVersion.getMinor() != 4) {
2914 return schemaVersion;
2917 Statement statement = connection.createStatement();
2921 statement.execute(
"CREATE INDEX tsk_os_accounts_login_name_idx ON tsk_os_accounts(login_name, db_status, realm_id)");
2922 statement.execute(
"CREATE INDEX tsk_os_accounts_addr_idx ON tsk_os_accounts(addr, db_status, realm_id)");
2923 statement.execute(
"CREATE INDEX tsk_os_account_realms_realm_name_idx ON tsk_os_account_realms(realm_name)");
2924 statement.execute(
"CREATE INDEX tsk_os_account_realms_realm_addr_idx ON tsk_os_account_realms(realm_addr)");
2926 return new CaseDbSchemaVersionNumber(9, 5);
2929 closeStatement(statement);
2934 private CaseDbSchemaVersionNumber updateFromSchema9dot5toSchema9dot6(CaseDbSchemaVersionNumber schemaVersion, CaseDbConnection connection)
throws SQLException, TskCoreException {
2935 if (schemaVersion.getMajor() != 9) {
2936 return schemaVersion;
2939 if (schemaVersion.getMinor() != 5) {
2940 return schemaVersion;
2943 String insertSQL =
"";
2946 insertSQL =
"CREATE INDEX tsk_files_datasrc_md5_size_partial_index ON tsk_files(data_source_obj_id, md5, size) WHERE md5 IS NOT NULL AND size > 0";
2949 insertSQL =
"CREATE INDEX tsk_files_datasrc_md5_size_index ON tsk_files(data_source_obj_id, md5, size)";
2952 throw new TskCoreException(
"Unknown DB Type: " +
getDatabaseType().name());
2955 Statement statement = connection.createStatement();
2959 statement.execute(insertSQL);
2961 return new CaseDbSchemaVersionNumber(9, 6);
2964 closeStatement(statement);
2980 private void insertAccountTypeIfNotExists(Statement statement, String type_name, String display_name)
throws TskCoreException, SQLException {
2982 String insertSQL = String.format(
"INTO account_types(type_name, display_name) VALUES ('%s', '%s')", type_name, display_name);
2985 insertSQL =
"INSERT " + insertSQL +
" ON CONFLICT DO NOTHING";
2988 insertSQL =
"INSERT OR IGNORE " + insertSQL;
2991 throw new TskCoreException(
"Unknown DB Type: " +
getDatabaseType().name());
2993 statement.execute(insertSQL);
3003 static String extractExtension(
final String fileName) {
3005 int i = fileName.lastIndexOf(
".");
3007 if ((i > 0) && ((i + 1) < fileName.length())) {
3008 ext = fileName.substring(i + 1);
3019 return ext.toLowerCase();
3043 return CURRENT_DB_SCHEMA_VERSION;
3053 return caseDBSchemaCreationVersion;
3072 return dbBackupPath;
3099 return databaseName;
3119 rwLock.writeLock().lock();
3130 rwLock.writeLock().unlock();
3141 rwLock.readLock().lock();
3152 rwLock.readLock().unlock();
3181 return openCase(dbPath, provider, null);
3204 }
catch (Exception ex) {
3205 throw new TskCoreException(
"Failed to open case database at " + dbPath, ex);
3224 return openCase(databaseName, info, caseDir, null);
3255 return new SleuthkitCase(info, databaseName, caseHandle, caseDir, contentProvider);
3256 }
catch (PropertyVetoException exp) {
3258 throw new TskCoreException(exp.getMessage(), exp);
3262 }
catch (Exception exp) {
3264 throw new TskCoreException(exp.getMessage(), exp);
3293 return newCase(dbPath, contentProvider, null);
3315 CaseDatabaseFactory factory =
new CaseDatabaseFactory(dbPath);
3316 factory.createCaseDatabase();
3320 }
catch (Exception ex) {
3321 throw new TskCoreException(
"Failed to create case database at " + dbPath, ex);
3341 return newCase(caseName, info, caseDirPath, null);
3363 String databaseName = createCaseDataBaseName(caseName);
3377 CaseDatabaseFactory factory =
new CaseDatabaseFactory(databaseName, info);
3378 factory.createCaseDatabase();
3381 return new SleuthkitCase(info, databaseName, caseHandle, caseDirPath, contentProvider);
3382 }
catch (PropertyVetoException exp) {
3384 throw new TskCoreException(exp.getMessage(), exp);
3385 }
catch (Exception exp) {
3387 throw new TskCoreException(exp.getMessage(), exp);
3400 private static String createCaseDataBaseName(String candidateDbName) {
3402 if (!candidateDbName.isEmpty()) {
3406 dbName = candidateDbName.replaceAll(
"[^\\p{ASCII}]",
"_");
3411 dbName = dbName.replaceAll(
"[\\p{Cntrl}]",
"_");
3416 dbName = dbName.replaceAll(
"[ /?:'\"\\\\]",
"_");
3421 dbName = dbName.toLowerCase();
3427 if ((dbName.length() > 0 && !(Character.isLetter(dbName.codePointAt(0))) && !(dbName.codePointAt(0) ==
'_'))) {
3428 dbName =
"_" + dbName;
3435 if (dbName.length() > MAX_DB_NAME_LEN_BEFORE_TIMESTAMP) {
3436 dbName = dbName.substring(0, MAX_DB_NAME_LEN_BEFORE_TIMESTAMP);
3448 SimpleDateFormat dateFormat =
new SimpleDateFormat(
"yyyyMMdd_HHmmss");
3449 Date date =
new Date();
3450 dbName = dbName +
"_" + dateFormat.format(date);
3462 timelineEventsDisabled.set(
true);
3475 if (cachedCurrentExaminer != null) {
3476 return cachedCurrentExaminer;
3478 String loginName = System.getProperty(
"user.name");
3479 if (loginName == null || loginName.isEmpty()) {
3480 throw new TskCoreException(
"Failed to determine logged in user name.");
3483 ResultSet resultSet = null;
3484 CaseDbConnection connection = null;
3487 connection = connections.getConnection();
3488 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_EXAMINER_BY_LOGIN_NAME);
3489 statement.clearParameters();
3490 statement.setString(1, loginName);
3491 resultSet = connection.executeQuery(statement);
3492 if (resultSet.next()) {
3493 cachedCurrentExaminer =
new Examiner(resultSet.getLong(
"examiner_id"), resultSet.getString(
"login_name"), resultSet.getString(
"display_name"));
3494 return cachedCurrentExaminer;
3496 throw new TskCoreException(
"Error getting examaminer for name = " + loginName);
3499 }
catch (SQLException ex) {
3500 throw new TskCoreException(
"Error getting examaminer for name = " + loginName, ex);
3502 closeResultSet(resultSet);
3503 closeConnection(connection);
3518 Examiner getExaminerById(
long id)
throws TskCoreException {
3520 CaseDbConnection connection = null;
3521 ResultSet resultSet = null;
3524 connection = connections.getConnection();
3525 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_EXAMINER_BY_ID);
3526 statement.clearParameters();
3527 statement.setLong(1,
id);
3528 resultSet = connection.executeQuery(statement);
3529 if (resultSet.next()) {
3530 return new Examiner(resultSet.getLong(
"examiner_id"), resultSet.getString(
"login_name"), resultSet.getString(
"full_name"));
3532 throw new TskCoreException(
"Error getting examaminer for id = " +
id);
3534 }
catch (SQLException ex) {
3535 throw new TskCoreException(
"Error getting examaminer for id = " +
id, ex);
3537 closeResultSet(resultSet);
3538 closeConnection(connection);
3561 return makeAddImageProcess(timeZone, addUnallocSpace, noFatFsOrphans, imageCopyPath, null);
3585 return this.caseHandle.initAddImageProcess(timeZone, addUnallocSpace, noFatFsOrphans, imageCopyPath, password,
this);
3597 CaseDbConnection connection = null;
3599 ResultSet rs = null;
3602 connection = connections.getConnection();
3603 s = connection.createStatement();
3604 rs = connection.executeQuery(s,
"SELECT obj_id, type FROM tsk_objects "
3605 +
"WHERE par_obj_id IS NULL");
3606 Collection<ObjectInfo> infos =
new ArrayList<ObjectInfo>();
3608 infos.add(
new ObjectInfo(rs.getLong(
"obj_id"),
ObjectType.
valueOf(rs.getShort(
"type"))));
3611 List<Content> rootObjs =
new ArrayList<Content>();
3612 for (ObjectInfo i : infos) {
3613 if (null != i.type) {
3624 throw new TskCoreException(
"Parentless object has wrong type to be a root (ABSTRACTFILE, but not VIRTUAL_DIRECTORY: " + i.type);
3636 throw new TskCoreException(
"Parentless object has wrong type to be a root: " + i.type);
3641 }
catch (SQLException ex) {
3642 throw new TskCoreException(
"Error getting root objects", ex);
3646 closeConnection(connection);
3662 List<Long> getDataSourceObjIds(String deviceId)
throws TskCoreException {
3665 synchronized (deviceIdToDatasourceObjIdMap) {
3666 if (deviceIdToDatasourceObjIdMap.containsKey(deviceId)) {
3667 return new ArrayList<Long>(deviceIdToDatasourceObjIdMap.get(deviceId));
3670 CaseDbConnection connection = null;
3672 ResultSet rs = null;
3675 connection = connections.getConnection();
3676 s = connection.createStatement();
3677 rs = connection.executeQuery(s,
"SELECT obj_id FROM data_source_info WHERE device_id = '" + deviceId +
"'");
3678 List<Long> dataSourceObjIds =
new ArrayList<Long>();
3680 dataSourceObjIds.add(rs.getLong(
"obj_id"));
3683 long ds_obj_id = rs.getLong(
"obj_id");
3684 if (deviceIdToDatasourceObjIdMap.containsKey(deviceId)) {
3685 deviceIdToDatasourceObjIdMap.get(deviceId).add(ds_obj_id);
3687 deviceIdToDatasourceObjIdMap.put(deviceId,
new HashSet<Long>(Arrays.asList(ds_obj_id)));
3690 return dataSourceObjIds;
3691 }
catch (SQLException ex) {
3692 throw new TskCoreException(
"Error getting data sources", ex);
3696 closeConnection(connection);
3719 CaseDbConnection connection = null;
3720 Statement statement = null;
3721 ResultSet resultSet = null;
3722 Statement statement2 = null;
3723 ResultSet resultSet2 = null;
3726 connection = connections.getConnection();
3727 statement = connection.createStatement();
3728 statement2 = connection.createStatement();
3729 resultSet = connection.executeQuery(statement,
3730 "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 "
3731 +
"FROM data_source_info AS ds "
3732 +
"LEFT JOIN tsk_image_info AS img "
3733 +
"ON ds.obj_id = img.obj_id");
3735 List<DataSource> dataSourceList =
new ArrayList<DataSource>();
3738 while (resultSet.next()) {
3740 Long objectId = resultSet.getLong(
"obj_id");
3741 String deviceId = resultSet.getString(
"device_id");
3742 String timezone = resultSet.getString(
"time_zone");
3743 String type = resultSet.getString(
"type");
3751 resultSet2 = connection.executeQuery(statement2,
"SELECT name FROM tsk_files WHERE tsk_files.obj_id = " + objectId);
3752 String dsName = (resultSet2.next()) ? resultSet2.getString(
"name") :
"";
3760 String parentPath =
"/";
3761 dataSource =
new LocalFilesDataSource(
this, objectId, objectId, deviceId, dsName, dirType, metaType, dirFlag, metaFlags, timezone, null, null, null,
FileKnown.
UNKNOWN, parentPath);
3766 Long ssize = resultSet.getLong(
"ssize");
3767 Long size = resultSet.getLong(
"size");
3768 String md5 = resultSet.getString(
"md5");
3769 String sha1 = resultSet.getString(
"sha1");
3770 String sha256 = resultSet.getString(
"sha256");
3771 String name = resultSet.getString(
"display_name");
3773 List<String> imagePaths = imagePathsMap.get(objectId);
3775 if (imagePaths.size() > 0) {
3776 String path = imagePaths.get(0);
3777 name = (
new java.io.File(path)).getName();
3783 dataSource =
new Image(
this, objectId, Long.valueOf(type), deviceId, ssize, name,
3784 imagePaths.toArray(
new String[imagePaths.size()]), timezone, md5, sha1, sha256, size);
3787 dataSourceList.add(dataSource);
3790 return dataSourceList;
3792 }
catch (SQLException ex) {
3793 throw new TskCoreException(
"Error getting data sources", ex);
3795 closeResultSet(resultSet);
3796 closeStatement(statement);
3797 closeResultSet(resultSet2);
3798 closeStatement(statement2);
3799 closeConnection(connection);
3825 CaseDbConnection connection = null;
3826 Statement statement = null;
3827 ResultSet resultSet = null;
3828 Statement statement2 = null;
3829 ResultSet resultSet2 = null;
3832 connection = connections.getConnection();
3833 statement = connection.createStatement();
3834 statement2 = connection.createStatement();
3835 resultSet = connection.executeQuery(statement,
3836 "SELECT ds.device_id, ds.time_zone, img.type, img.ssize, img.size, img.md5, img.sha1, img.sha256, img.display_name "
3837 +
"FROM data_source_info AS ds "
3838 +
"LEFT JOIN tsk_image_info AS img "
3839 +
"ON ds.obj_id = img.obj_id "
3840 +
"WHERE ds.obj_id = " + objectId);
3841 if (resultSet.next()) {
3842 String deviceId = resultSet.getString(
"device_id");
3843 String timezone = resultSet.getString(
"time_zone");
3844 String type = resultSet.getString(
"type");
3852 resultSet2 = connection.executeQuery(statement2,
"SELECT name FROM tsk_files WHERE tsk_files.obj_id = " + objectId);
3853 String dsName = (resultSet2.next()) ? resultSet2.getString(
"name") :
"";
3860 String parentPath =
"/";
3861 dataSource =
new LocalFilesDataSource(
this, objectId, objectId, deviceId, dsName, dirType, metaType, dirFlag, metaFlags, timezone, null, null, null,
FileKnown.
UNKNOWN, parentPath);
3866 Long ssize = resultSet.getLong(
"ssize");
3867 Long size = resultSet.getLong(
"size");
3868 String md5 = resultSet.getString(
"md5");
3869 String sha1 = resultSet.getString(
"sha1");
3870 String sha256 = resultSet.getString(
"sha256");
3871 String name = resultSet.getString(
"display_name");
3873 List<String> imagePaths = getImagePathsById(objectId, connection);
3875 if (imagePaths.size() > 0) {
3876 String path = imagePaths.get(0);
3877 name = (
new java.io.File(path)).getName();
3883 dataSource =
new Image(
this, objectId, Long.valueOf(type), deviceId, ssize, name,
3884 imagePaths.toArray(
new String[imagePaths.size()]), timezone, md5, sha1, sha256, size);
3887 throw new TskDataException(String.format(
"There is no data source with obj_id = %d", objectId));
3889 }
catch (SQLException ex) {
3890 throw new TskCoreException(String.format(
"Error getting data source with obj_id = %d", objectId), ex);
3892 closeResultSet(resultSet);
3893 closeStatement(statement);
3894 closeResultSet(resultSet2);
3895 closeStatement(statement2);
3896 closeConnection(connection);
3917 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
3918 artifacts.addAll(blackboard.getArtifactsByType(blackboard.
getArtifactType(artifactTypeID)));
3933 CaseDbConnection connection = null;
3934 ResultSet rs = null;
3937 connection = connections.getConnection();
3940 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_FROM_SOURCE);
3941 statement.clearParameters();
3942 statement.setLong(1, objId);
3943 rs = connection.executeQuery(statement);
3946 count = rs.getLong(
"count");
3949 }
catch (SQLException ex) {
3950 throw new TskCoreException(
"Error getting number of blackboard artifacts by content", ex);
3953 closeConnection(connection);
3969 CaseDbConnection connection = null;
3970 ResultSet rs = null;
3973 connection = connections.getConnection();
3976 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_OF_TYPE);
3977 statement.clearParameters();
3978 statement.setInt(1, artifactTypeID);
3979 rs = connection.executeQuery(statement);
3982 count = rs.getLong(
"count");
3985 }
catch (SQLException ex) {
3986 throw new TskCoreException(
"Error getting number of blackboard artifacts by type", ex);
3989 closeConnection(connection);
4006 CaseDbConnection connection = null;
4007 ResultSet rs = null;
4010 connection = connections.getConnection();
4013 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_OF_TYPE_BY_DATA_SOURCE);
4014 statement.clearParameters();
4015 statement.setInt(2, artifactTypeID);
4016 statement.setLong(1, dataSourceID);
4017 rs = connection.executeQuery(statement);
4020 count = rs.getLong(
"count");
4023 }
catch (SQLException ex) {
4024 throw new TskCoreException(String.format(
"Error getting number of blackboard artifacts by type (%d) and data source (%d)", artifactTypeID, dataSourceID), ex);
4027 closeConnection(connection);
4051 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4052 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4053 +
"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, "
4054 +
"types.type_name AS type_name, types.display_name AS display_name, "
4055 +
" arts.review_status_id AS review_status_id "
4056 +
"FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4057 +
"WHERE arts.artifact_id = attrs.artifact_id "
4058 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4059 +
" AND attrs.value_text = '" + value +
"'"
4060 +
" AND types.artifact_type_id=arts.artifact_type_id"
4063 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4064 List<Long> dataArtifactObjIds =
new ArrayList<>();
4065 while (resultSet.next()) {
4068 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4070 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4074 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4075 if (!analysisArtifactObjIds.isEmpty()) {
4079 if (!dataArtifactObjIds.isEmpty()) {
4083 }
catch (SQLException ex) {
4084 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
4110 String valSubStr =
"%" + subString;
4111 if (startsWith ==
false) {
4116 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4117 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4118 +
" 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, "
4119 +
" types.type_name AS type_name, types.display_name AS display_name, "
4120 +
" arts.review_status_id AS review_status_id "
4121 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4122 +
" WHERE arts.artifact_id = attrs.artifact_id "
4123 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4124 +
" AND LOWER(attrs.value_text) LIKE LOWER('" + valSubStr +
"')"
4125 +
" AND types.artifact_type_id=arts.artifact_type_id "
4127 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4128 List<Long> dataArtifactObjIds =
new ArrayList<>();
4129 while (resultSet.next()) {
4132 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4134 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4138 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4139 if (!analysisArtifactObjIds.isEmpty()) {
4143 if (!dataArtifactObjIds.isEmpty()) {
4147 }
catch (SQLException ex) {
4148 throw new TskCoreException(
"Error getting blackboard artifacts by attribute. " + ex.getMessage(), ex);
4172 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4173 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4174 +
" 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, "
4175 +
" types.type_name AS type_name, types.display_name AS display_name, "
4176 +
" arts.review_status_id AS review_status_id "
4177 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4178 +
"WHERE arts.artifact_id = attrs.artifact_id "
4179 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4180 +
" AND attrs.value_int32 = " + value
4181 +
" AND types.artifact_type_id=arts.artifact_type_id "
4183 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4184 List<Long> dataArtifactObjIds =
new ArrayList<>();
4185 while (resultSet.next()) {
4188 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4190 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4194 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4195 if (!analysisArtifactObjIds.isEmpty()) {
4199 if (!dataArtifactObjIds.isEmpty()) {
4203 }
catch (SQLException ex) {
4204 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
4229 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4230 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4231 +
" 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, "
4232 +
" types.type_name AS type_name, types.display_name AS display_name, "
4233 +
" arts.review_status_id AS review_status_id "
4234 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4235 +
" WHERE arts.artifact_id = attrs.artifact_id "
4236 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4237 +
" AND attrs.value_int64 = " + value
4238 +
" AND types.artifact_type_id=arts.artifact_type_id "
4240 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4241 List<Long> dataArtifactObjIds =
new ArrayList<>();
4242 while (resultSet.next()) {
4245 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4247 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4251 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4252 if (!analysisArtifactObjIds.isEmpty()) {
4256 if (!dataArtifactObjIds.isEmpty()) {
4260 }
catch (SQLException ex) {
4261 throw new TskCoreException(
"Error getting blackboard artifacts by attribute. " + ex.getMessage(), ex);
4286 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4287 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4288 +
" 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, "
4289 +
" types.type_name AS type_name, types.display_name AS display_name, "
4290 +
" arts.review_status_id AS review_status_id "
4291 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4292 +
" WHERE arts.artifact_id = attrs.artifact_id "
4293 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4294 +
" AND attrs.value_double = " + value
4295 +
" AND types.artifact_type_id=arts.artifact_type_id "
4297 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4298 List<Long> dataArtifactObjIds =
new ArrayList<>();
4299 while (resultSet.next()) {
4302 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4304 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4308 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4309 if (!analysisArtifactObjIds.isEmpty()) {
4313 if (!dataArtifactObjIds.isEmpty()) {
4317 }
catch (SQLException ex) {
4318 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
4344 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement();
4345 ResultSet resultSet = connection.executeQuery(statement,
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4346 +
" 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, "
4347 +
" types.type_name AS type_name, types.display_name AS display_name, "
4348 +
" arts.review_status_id AS review_status_id "
4349 +
" FROM blackboard_artifacts AS arts, blackboard_attributes AS attrs, blackboard_artifact_types AS types "
4350 +
" WHERE arts.artifact_id = attrs.artifact_id "
4351 +
" AND attrs.attribute_type_id = " + attrType.getTypeID()
4352 +
" AND attrs.value_byte = " + value
4353 +
" AND types.artifact_type_id=arts.artifact_type_id "
4355 List<Long> analysisArtifactObjIds =
new ArrayList<>();
4356 List<Long> dataArtifactObjIds =
new ArrayList<>();
4357 while (resultSet.next()) {
4360 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4362 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
4366 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4367 if (!analysisArtifactObjIds.isEmpty()) {
4371 if (!dataArtifactObjIds.isEmpty()) {
4375 }
catch (SQLException ex) {
4376 throw new TskCoreException(
"Error getting blackboard artifacts by attribute", ex);
4390 CaseDbConnection connection = null;
4392 ResultSet rs = null;
4395 connection = connections.getConnection();
4396 s = connection.createStatement();
4397 rs = connection.executeQuery(s,
"SELECT artifact_type_id, type_name, display_name, category_type FROM blackboard_artifact_types");
4401 rs.getString(
"type_name"), rs.getString(
"display_name"),
4404 return artifactTypes;
4405 }
catch (SQLException ex) {
4406 throw new TskCoreException(
"Error getting artifact types", ex);
4410 closeConnection(connection);
4424 String typeIdList =
"";
4431 String query =
"SELECT DISTINCT artifact_type_id FROM blackboard_artifacts "
4432 +
"WHERE artifact_type_id IN (" + typeIdList +
")";
4433 CaseDbConnection connection = null;
4435 ResultSet rs = null;
4438 connection = connections.getConnection();
4439 s = connection.createStatement();
4440 rs = connection.executeQuery(s, query);
4446 }
catch (SQLException ex) {
4447 throw new TskCoreException(
"Error getting artifact types in use", ex);
4451 closeConnection(connection);
4467 CaseDbConnection connection = null;
4469 ResultSet rs = null;
4472 connection = connections.getConnection();
4473 s = connection.createStatement();
4474 rs = connection.executeQuery(s,
4475 "SELECT DISTINCT arts.artifact_type_id AS artifact_type_id, "
4476 +
"types.type_name AS type_name, "
4477 +
"types.display_name AS display_name, "
4478 +
"types.category_type AS category_type "
4479 +
"FROM blackboard_artifact_types AS types "
4480 +
"INNER JOIN blackboard_artifacts AS arts "
4481 +
"ON arts.artifact_type_id = types.artifact_type_id");
4485 rs.getString(
"type_name"), rs.getString(
"display_name"),
4488 return uniqueArtifactTypes;
4489 }
catch (SQLException ex) {
4490 throw new TskCoreException(
"Error getting attribute types", ex);
4494 closeConnection(connection);
4507 CaseDbConnection connection = null;
4509 ResultSet rs = null;
4512 connection = connections.getConnection();
4513 s = connection.createStatement();
4514 rs = connection.executeQuery(s,
"SELECT attribute_type_id, type_name, display_name, value_type FROM blackboard_attribute_types");
4520 return attribute_types;
4521 }
catch (SQLException ex) {
4522 throw new TskCoreException(
"Error getting attribute types", ex);
4526 closeConnection(connection);
4543 CaseDbConnection connection = null;
4545 ResultSet rs = null;
4548 connection = connections.getConnection();
4549 s = connection.createStatement();
4550 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM blackboard_attribute_types");
4553 count = rs.getInt(
"count");
4556 }
catch (SQLException ex) {
4557 throw new TskCoreException(
"Error getting number of blackboard artifacts by type", ex);
4561 closeConnection(connection);
4578 private long getArtifactsCountHelper(
int artifactTypeID,
long obj_id)
throws TskCoreException {
4579 CaseDbConnection connection = null;
4580 ResultSet rs = null;
4583 connection = connections.getConnection();
4586 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_BY_SOURCE_AND_TYPE);
4587 statement.clearParameters();
4588 statement.setLong(1, obj_id);
4589 statement.setInt(2, artifactTypeID);
4590 rs = connection.executeQuery(statement);
4593 count = rs.getLong(
"count");
4596 }
catch (SQLException ex) {
4597 throw new TskCoreException(
"Error getting blackboard artifact count", ex);
4600 closeConnection(connection);
4618 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4619 artifacts.addAll(blackboard.getArtifactsBySourceId(
getArtifactType(artifactTypeName), obj_id));
4636 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4637 artifacts.addAll(blackboard.getArtifactsBySourceId(blackboard.
getArtifactType(artifactTypeID), obj_id));
4670 int artifactTypeID = this.
getArtifactType(artifactTypeName).getTypeID();
4671 if (artifactTypeID == -1) {
4674 return getArtifactsCountHelper(artifactTypeID, obj_id);
4690 return getArtifactsCountHelper(artifactTypeID, obj_id);
4706 return getArtifactsCountHelper(artifactType.getTypeID(), obj_id);
4721 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4722 artifacts.addAll(blackboard.getArtifactsByType(
getArtifactType(artifactTypeName)));
4738 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4739 artifacts.addAll(blackboard.getArtifactsByType(blackboard.
getArtifactType(artifactType.getTypeID())));
4761 String dataArtifactJoin =
"tsk_data_artifacts AS datarts ON datarts.artifact_obj_id = arts.artifact_obj_id";
4762 String analysisResultJoin =
"tsk_analysis_results AS anresult ON anresult.artifact_obj_id = arts.artifact_obj_id";
4763 String dataArtifactColumns =
", datarts.os_account_obj_id AS os_account_obj_id";
4764 String analysResultColumns =
", anresult.conclusion AS conclusion, anresult.significance AS significance, anresult.priority AS priority, anresult.configuration AS configuration, anresult.justification AS justification ";
4766 String formatQuery =
"SELECT DISTINCT arts.artifact_id AS artifact_id, "
4767 +
"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, "
4768 +
"types.type_name AS type_name, types.display_name AS display_name,"
4769 +
"arts.review_status_id AS review_status_id %s "
4770 +
"FROM blackboard_artifacts AS arts "
4771 +
"JOIN blackboard_attributes AS attrs ON arts.artifact_id = attrs.artifact_id "
4772 +
"JOIN blackboard_artifact_types AS types ON types.artifact_type_id = arts.artifact_type_id "
4774 +
"WHERE arts.artifact_id = attrs.artifact_id "
4775 +
"AND attrs.attribute_type_id = %d "
4776 +
" AND arts.artifact_type_id = %d "
4777 +
" AND attrs.value_text = '%s' "
4778 +
" AND types.artifact_type_id=arts.artifact_type_id "
4779 +
" AND arts.review_status_id != %d";
4781 String query = String.format(formatQuery,
4784 attrType.getTypeID(),
4785 artifactType.getTypeID(),
4790 try (CaseDbConnection connection = connections.getConnection(); Statement s = connection.createStatement(); ResultSet rs = connection.executeQuery(s, query)) {
4791 ArrayList<BlackboardArtifact> artifacts =
new ArrayList<>();
4794 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
4796 osAccountObjId = null;
4799 artifacts.add(
new DataArtifact(
this, rs.getLong(
"artifact_id"), rs.getLong(
"obj_id"),
4800 rs.getLong(
"artifact_obj_id"),
4801 rs.getObject(
"data_source_obj_id") != null ? rs.getLong(
"data_source_obj_id") : null,
4802 rs.getInt(
"artifact_type_id"), rs.getString(
"type_name"), rs.getString(
"display_name"),
4805 artifacts.add(
new AnalysisResult(
this, rs.getLong(
"artifact_id"), rs.getLong(
"obj_id"),
4806 rs.getLong(
"artifact_obj_id"),
4807 rs.getObject(
"data_source_obj_id") != null ? rs.getLong(
"data_source_obj_id") : null,
4808 rs.getInt(
"artifact_type_id"), rs.getString(
"type_name"), rs.getString(
"display_name"),
4811 rs.getString(
"conclusion"), rs.getString(
"configuration"), rs.getString(
"justification")));
4815 }
catch (SQLException ex) {
4816 throw new TskCoreException(
"Error getting blackboard artifacts by artifact type and attribute. " + ex.getMessage(), ex);
4834 List<DataArtifact> dataArtifacts = blackboard.
getDataArtifactsWhere(
"artifacts.artifact_id = " + artifactID);
4835 if (!dataArtifacts.isEmpty()) {
4836 return dataArtifacts.get(0);
4839 List<AnalysisResult> analysisResults = blackboard.
getAnalysisResultsWhere(
"artifacts.artifact_id = " + artifactID);
4840 if (!analysisResults.isEmpty()) {
4841 return analysisResults.get(0);
4844 throw new TskCoreException(
"No blackboard artifact with id " + artifactID);
4857 try (CaseDbConnection connection = connections.getConnection();) {
4858 addBlackBoardAttribute(attr, artifactTypeId, connection);
4859 }
catch (SQLException ex) {
4860 throw new TskCoreException(
"Error adding blackboard attribute " + attr.toString(), ex);
4876 CaseDbConnection connection = null;
4879 connection = connections.getConnection();
4880 connection.beginTransaction();
4882 addBlackBoardAttribute(attr, artifactTypeId, connection);
4884 connection.commitTransaction();
4885 }
catch (SQLException ex) {
4886 rollbackTransaction(connection);
4887 throw new TskCoreException(
"Error adding blackboard attributes", ex);
4889 closeConnection(connection);
4894 void addBlackBoardAttribute(
BlackboardAttribute attr,
int artifactTypeId, CaseDbConnection connection)
throws SQLException, TskCoreException {
4895 PreparedStatement statement;
4896 switch (attr.getAttributeType().getValueType()) {
4899 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_STRING_ATTRIBUTE);
4900 statement.clearParameters();
4901 statement.setString(7, attr.getValueString());
4904 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_BYTE_ATTRIBUTE);
4905 statement.clearParameters();
4906 statement.setBytes(7, attr.getValueBytes());
4909 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_INT_ATTRIBUTE);
4910 statement.clearParameters();
4911 statement.setInt(7, attr.getValueInt());
4914 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LONG_ATTRIBUTE);
4915 statement.clearParameters();
4916 statement.setLong(7, attr.getValueLong());
4919 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_DOUBLE_ATTRIBUTE);
4920 statement.clearParameters();
4921 statement.setDouble(7, attr.getValueDouble());
4924 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LONG_ATTRIBUTE);
4925 statement.clearParameters();
4926 statement.setLong(7, attr.getValueLong());
4929 throw new TskCoreException(
"Unrecognized artifact attribute value type");
4931 statement.setLong(1, attr.getArtifactID());
4932 statement.setInt(2, artifactTypeId);
4933 statement.setString(3, attr.getSourcesCSV());
4934 statement.setString(4,
"");
4935 statement.setInt(5, attr.getAttributeType().getTypeID());
4936 statement.setLong(6, attr.getAttributeType().getValueType().getType());
4937 connection.executeUpdate(statement);
4940 void addFileAttribute(Attribute attr, CaseDbConnection connection)
throws SQLException, TskCoreException {
4941 PreparedStatement statement;
4942 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE_ATTRIBUTE, Statement.RETURN_GENERATED_KEYS);
4943 statement.clearParameters();
4945 statement.setLong(1, attr.getAttributeParentId());
4946 statement.setInt(2, attr.getAttributeType().getTypeID());
4947 statement.setLong(3, attr.getAttributeType().getValueType().getType());
4949 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE) {
4950 statement.setBytes(4, attr.getValueBytes());
4952 statement.setBytes(4, null);
4955 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.STRING
4956 || attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.JSON) {
4957 statement.setString(5, attr.getValueString());
4959 statement.setString(5, null);
4961 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.INTEGER) {
4962 statement.setInt(6, attr.getValueInt());
4964 statement.setNull(6, java.sql.Types.INTEGER);
4967 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME
4968 || attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.LONG) {
4969 statement.setLong(7, attr.getValueLong());
4971 statement.setNull(7, java.sql.Types.BIGINT);
4974 if (attr.getAttributeType().getValueType() == TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DOUBLE) {
4975 statement.setDouble(8, attr.getValueDouble());
4977 statement.setNull(8, java.sql.Types.DOUBLE);
4980 connection.executeUpdate(statement);
4981 try (ResultSet resultSet = statement.getGeneratedKeys()) {
4982 if (!resultSet.next()) {
4983 throw new TskCoreException(String.format(
"Failed to insert file attribute "
4984 +
"with id=%d. The expected key was not generated", attr.getId()));
4987 attr.setId(resultSet.getLong(1));
5001 String addSourceToArtifactAttribute(BlackboardAttribute attr, String source)
throws TskCoreException {
5009 if (null == source || source.isEmpty()) {
5010 throw new TskCoreException(
"Attempt to add null or empty source module name to artifact attribute");
5012 CaseDbConnection connection = null;
5014 Statement queryStmt = null;
5015 Statement updateStmt = null;
5016 ResultSet result = null;
5017 String newSources =
"";
5019 connection = connections.getConnection();
5020 connection.beginTransaction();
5021 String valueClause =
"";
5022 BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE valueType = attr.getAttributeType().getValueType();
5023 if (BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE != valueType) {
5024 switch (valueType) {
5030 valueClause =
" value_int32 = " + attr.getValueInt();
5034 valueClause =
" value_int64 = " + attr.getValueLong();
5037 valueClause =
" value_double = " + attr.getValueDouble();
5040 throw new TskCoreException(String.format(
"Unrecognized value type for attribute %s", attr.getDisplayString()));
5042 String query =
"SELECT source FROM blackboard_attributes WHERE"
5043 +
" artifact_id = " + attr.getArtifactID()
5044 +
" AND attribute_type_id = " + attr.getAttributeType().getTypeID()
5045 +
" AND value_type = " + attr.getAttributeType().getValueType().getType()
5046 +
" AND " + valueClause +
";";
5047 queryStmt = connection.createStatement();
5048 updateStmt = connection.createStatement();
5049 result = connection.executeQuery(queryStmt, query);
5056 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ATTR_BY_VALUE_BYTE);
5057 statement.clearParameters();
5058 statement.setLong(1, attr.getArtifactID());
5059 statement.setLong(2, attr.getAttributeType().getTypeID());
5060 statement.setBytes(3, attr.getValueBytes());
5061 result = connection.executeQuery(statement);
5063 while (result.next()) {
5064 String oldSources = result.getString(
"source");
5065 if (null != oldSources && !oldSources.isEmpty()) {
5066 Set<String> uniqueSources =
new HashSet<String>(Arrays.asList(oldSources.split(
",")));
5067 if (!uniqueSources.contains(source)) {
5068 newSources = oldSources +
"," + source;
5070 newSources = oldSources;
5073 newSources = source;
5075 if (BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE != valueType) {
5076 String update =
"UPDATE blackboard_attributes SET source = '" + newSources +
"' WHERE"
5077 +
" artifact_id = " + attr.getArtifactID()
5078 +
" AND attribute_type_id = " + attr.getAttributeType().getTypeID()
5079 +
" AND value_type = " + attr.getAttributeType().getValueType().getType()
5080 +
" AND " + valueClause +
";";
5081 connection.executeUpdate(updateStmt, update);
5088 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ATTR_BY_VALUE_BYTE);
5089 statement.clearParameters();
5090 statement.setString(1, newSources);
5091 statement.setLong(2, attr.getArtifactID());
5092 statement.setLong(3, attr.getAttributeType().getTypeID());
5093 statement.setBytes(4, attr.getValueBytes());
5094 connection.executeUpdate(statement);
5097 connection.commitTransaction();
5099 }
catch (SQLException ex) {
5100 rollbackTransaction(connection);
5101 throw new TskCoreException(String.format(
"Error adding source module to attribute %s", attr.getDisplayString()), ex);
5103 closeResultSet(result);
5104 closeStatement(updateStmt);
5105 closeStatement(queryStmt);
5106 closeConnection(connection);
5130 throw new TskCoreException(
"Error adding artifact type: " + attrTypeString, ex);
5206 }
catch (BlackboardException ex) {
5207 throw new TskCoreException(
"Error getting or adding artifact type with name: " + artifactTypeName, ex);
5241 CaseDbConnection connection = null;
5243 ResultSet rs = null;
5246 connection = connections.getConnection();
5247 s = connection.createStatement();
5248 rs = connection.executeQuery(s,
"SELECT blackboard_attributes.artifact_id AS artifact_id, "
5249 +
"blackboard_attributes.source AS source, blackboard_attributes.context AS context, "
5250 +
"blackboard_attributes.attribute_type_id AS attribute_type_id, "
5251 +
"blackboard_attributes.value_type AS value_type, blackboard_attributes.value_byte AS value_byte, "
5252 +
"blackboard_attributes.value_text AS value_text, blackboard_attributes.value_int32 AS value_int32, "
5253 +
"blackboard_attributes.value_int64 AS value_int64, blackboard_attributes.value_double AS value_double "
5254 +
"FROM blackboard_attributes " + whereClause);
5255 ArrayList<BlackboardAttribute> matches =
new ArrayList<>();
5261 rs.getLong(
"artifact_id"),
5263 rs.getString(
"source"),
5264 rs.getString(
"context"),
5265 rs.getInt(
"value_int32"),
5266 rs.getLong(
"value_int64"),
5267 rs.getDouble(
"value_double"),
5268 rs.getString(
"value_text"),
5269 rs.getBytes(
"value_byte"), this
5274 }
catch (SQLException ex) {
5275 throw new TskCoreException(
"Error getting attributes using this where clause: " + whereClause, ex);
5279 closeConnection(connection);
5296 String query =
"SELECT blackboard_artifacts.artifact_id AS artifact_id, "
5297 +
"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, "
5298 +
"blackboard_artifacts.review_status_id AS review_status_id "
5299 +
"FROM blackboard_artifacts " + whereClause;
5301 try (CaseDbConnection connection = connections.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) {
5303 List<Long> analysisArtifactObjIds =
new ArrayList<>();
5304 List<Long> dataArtifactObjIds =
new ArrayList<>();
5305 while (resultSet.next()) {
5308 analysisArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
5310 dataArtifactObjIds.add(resultSet.getLong(
"artifact_obj_id"));
5314 ArrayList<BlackboardArtifact> matches =
new ArrayList<>();
5315 if (!analysisArtifactObjIds.isEmpty()) {
5319 if (!dataArtifactObjIds.isEmpty()) {
5324 }
catch (SQLException ex) {
5325 throw new TskCoreException(
"Error getting attributes using this where clause: " + whereClause, ex);
5349 throw new TskCoreException(
"Unknown artifact type for id: " + artifactTypeID);
5352 Category category = type.getCategory();
5353 if (category == null) {
5354 throw new TskCoreException(String.format(
"No category for %s (id: %d)",
5355 type.getDisplayName() == null ?
"<null>" : type.getDisplayName(),
5360 if (content == null) {
5361 throw new TskCoreException(
"No content found for object id: " + obj_id);
5365 case ANALYSIS_RESULT:
5367 .getAnalysisResult();
5371 throw new TskCoreException(
"Unknown category type: " + category.
getName());
5388 @SuppressWarnings(
"deprecation")
5409 @SuppressWarnings(
"deprecation")
5412 try (CaseDbConnection connection = connections.getConnection()) {
5413 return newBlackboardArtifact(artifactTypeID, obj_id, type.getTypeName(), type.getDisplayName(), data_source_obj_id, connection);
5418 private BlackboardArtifact
newBlackboardArtifact(
int artifact_type_id,
long obj_id, String artifactTypeName, String artifactDisplayName)
throws TskCoreException {
5419 try (CaseDbConnection connection = connections.getConnection()) {
5420 long data_source_obj_id = getDataSourceObjectId(connection, obj_id);
5421 return this.
newBlackboardArtifact(artifact_type_id, obj_id, artifactTypeName, artifactDisplayName, data_source_obj_id, connection);
5425 PreparedStatement createInsertArtifactStatement(
int artifact_type_id,
long obj_id,
long artifact_obj_id,
long data_source_obj_id, CaseDbConnection connection)
throws TskCoreException, SQLException {
5427 PreparedStatement statement;
5429 statement = connection.getPreparedStatement(PREPARED_STATEMENT.POSTGRESQL_INSERT_ARTIFACT, Statement.RETURN_GENERATED_KEYS);
5430 statement.clearParameters();
5431 statement.setLong(1, obj_id);
5432 statement.setLong(2, artifact_obj_id);
5433 statement.setLong(3, data_source_obj_id);
5434 statement.setInt(4, artifact_type_id);
5436 statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_ARTIFACT, Statement.RETURN_GENERATED_KEYS);
5437 statement.clearParameters();
5438 this.nextArtifactId++;
5439 statement.setLong(1, this.nextArtifactId);
5440 statement.setLong(2, obj_id);
5441 statement.setLong(3, artifact_obj_id);
5442 statement.setLong(4, data_source_obj_id);
5443 statement.setInt(5, artifact_type_id);
5466 private BlackboardArtifact
newBlackboardArtifact(
int artifact_type_id,
long obj_id, String artifactTypeName, String artifactDisplayName,
long data_source_obj_id, CaseDbConnection connection)
throws TskCoreException {
5469 if (type.getCategory() == BlackboardArtifact.Category.ANALYSIS_RESULT) {
5470 return blackboard.
newAnalysisResult(type, obj_id, data_source_obj_id, Score.SCORE_UNKNOWN, null, null, null, Collections.emptyList()).getAnalysisResult();
5472 return blackboard.
newDataArtifact(type, obj_id, data_source_obj_id, Collections.emptyList(), null);
5474 }
catch (BlackboardException ex) {
5475 throw new TskCoreException(
"Error creating a blackboard artifact", ex);
5497 AnalysisResult newAnalysisResult(BlackboardArtifact.Type artifactType,
long objId, Long dataSourceObjId, Score score, String conclusion, String configuration, String justification, CaseDbConnection connection)
throws TskCoreException {
5499 if (artifactType.getCategory() != BlackboardArtifact.Category.ANALYSIS_RESULT) {
5500 throw new TskCoreException(String.format(
"Artifact type (name = %s) is not of the AnalysisResult category. ", artifactType.getTypeName()));
5507 long artifactObjId = addObject(objId, TskData.ObjectType.ARTIFACT.getObjectType(), connection);
5510 PreparedStatement insertArtifactstatement;
5511 ResultSet resultSet = null;
5513 insertArtifactstatement = createInsertArtifactStatement(artifactType.getTypeID(), objId, artifactObjId, dataSourceObjId, connection);
5514 connection.executeUpdate(insertArtifactstatement);
5515 resultSet = insertArtifactstatement.getGeneratedKeys();
5517 artifactID = resultSet.getLong(1);
5520 if (score.getSignificance() != Score.Significance.UNKNOWN
5521 || !StringUtils.isBlank(conclusion)
5522 || !StringUtils.isBlank(configuration)
5523 || !StringUtils.isBlank(justification)) {
5525 PreparedStatement analysisResultsStatement;
5527 analysisResultsStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_ANALYSIS_RESULT);
5528 analysisResultsStatement.clearParameters();
5530 analysisResultsStatement.setLong(1, artifactObjId);
5531 analysisResultsStatement.setString(2, (conclusion != null) ? conclusion :
"");
5532 analysisResultsStatement.setInt(3, score.getSignificance().getId());
5533 analysisResultsStatement.setInt(4, score.getPriority().getId());
5534 analysisResultsStatement.setString(5, (configuration != null) ? configuration :
"");
5535 analysisResultsStatement.setString(6, (justification != null) ? justification :
"");
5537 connection.executeUpdate(analysisResultsStatement);
5540 return new AnalysisResult(
this, artifactID, objId, artifactObjId, dataSourceObjId, artifactType.getTypeID(),
5541 artifactType.getTypeName(), artifactType.getDisplayName(),
5542 BlackboardArtifact.ReviewStatus.UNDECIDED,
true,
5543 score, (conclusion != null) ? conclusion :
"",
5544 (configuration != null) ? configuration :
"", (justification != null) ? justification :
"");
5547 closeResultSet(resultSet);
5550 }
catch (SQLException ex) {
5551 throw new TskCoreException(
"Error creating a analysis result", ex);
5569 boolean getContentHasChildren(Content content)
throws TskCoreException {
5570 CaseDbConnection connection = null;
5571 ResultSet rs = null;
5574 connection = connections.getConnection();
5577 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CHILD_OBJECTS_BY_PARENT);
5578 statement.clearParameters();
5579 statement.setLong(1, content.getId());
5580 rs = connection.executeQuery(statement);
5581 boolean hasChildren =
false;
5583 hasChildren = rs.getInt(
"count") > 0;
5586 }
catch (SQLException e) {
5587 throw new TskCoreException(
"Error checking for children of parent " + content, e);
5590 closeConnection(connection);
5607 int getContentChildrenCount(Content content)
throws TskCoreException {
5609 if (!this.getHasChildren(content)) {
5613 CaseDbConnection connection = null;
5614 ResultSet rs = null;
5617 connection = connections.getConnection();
5620 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CHILD_OBJECTS_BY_PARENT);
5621 statement.clearParameters();
5622 statement.setLong(1, content.getId());
5623 rs = connection.executeQuery(statement);
5624 int countChildren = -1;
5626 countChildren = rs.getInt(
"count");
5628 return countChildren;
5629 }
catch (SQLException e) {
5630 throw new TskCoreException(
"Error checking for children of parent " + content, e);
5633 closeConnection(connection);
5657 int getAbstractFileChildrenCountByType(Content content, List<TSK_FS_NAME_TYPE_ENUM> types)
throws TskCoreException {
5659 if (!this.getHasChildren(content)) {
5663 if (types == null || types.isEmpty()) {
5667 CaseDbConnection connection = null;
5668 ResultSet rs = null;
5671 connection = connections.getConnection();
5674 StringBuilder inClause =
new StringBuilder(
"?");
5675 for (
int i = 1; i < types.size(); i++) {
5676 inClause.append(
", ?");
5679 String sql =
"SELECT COUNT(*) AS count "
5680 +
"FROM tsk_objects "
5681 +
"INNER JOIN tsk_files ON tsk_objects.obj_id = tsk_files.obj_id "
5682 +
"WHERE (tsk_objects.par_obj_id = ? AND tsk_files.dir_type IN (" + inClause.toString() +
"))";
5684 PreparedStatement statement = connection.getConnection().prepareStatement(sql);
5685 statement.clearParameters();
5686 statement.setLong(1, content.getId());
5688 for (
int i = 0; i < types.size(); i++) {
5689 statement.setInt(i + 2, types.get(i).getValue());
5692 rs = connection.executeQuery(statement);
5693 int countChildren = -1;
5695 countChildren = rs.getInt(
"count");
5697 return countChildren;
5698 }
catch (SQLException e) {
5699 throw new TskCoreException(
"Error checking for children of parent " + content, e);
5702 closeConnection(connection);
5718 List<Content> getAbstractFileChildren(Content parent, TSK_DB_FILES_TYPE_ENUM type)
throws TskCoreException {
5719 CaseDbConnection connection = null;
5720 ResultSet rs = null;
5723 connection = connections.getConnection();
5725 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_PARENT_AND_TYPE);
5726 statement.clearParameters();
5727 long parentId = parent.getId();
5728 statement.setLong(1, parentId);
5729 statement.setShort(2, type.getFileType());
5730 rs = connection.executeQuery(statement);
5731 return fileChildren(rs, connection, parentId);
5732 }
catch (SQLException ex) {
5733 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5736 closeConnection(connection);
5750 List<Content> getAbstractFileChildren(Content parent)
throws TskCoreException {
5751 CaseDbConnection connection = null;
5752 ResultSet rs = null;
5755 connection = connections.getConnection();
5757 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_PARENT);
5758 statement.clearParameters();
5759 long parentId = parent.getId();
5760 statement.setLong(1, parentId);
5761 rs = connection.executeQuery(statement);
5762 return fileChildren(rs, connection, parentId);
5763 }
catch (SQLException ex) {
5764 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5767 closeConnection(connection);
5783 List<Long> getAbstractFileChildrenIds(Content parent, TSK_DB_FILES_TYPE_ENUM type)
throws TskCoreException {
5784 CaseDbConnection connection = null;
5785 ResultSet rs = null;
5788 connection = connections.getConnection();
5790 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_IDS_BY_PARENT_AND_TYPE);
5791 statement.clearParameters();
5792 statement.setLong(1, parent.getId());
5793 statement.setShort(2, type.getFileType());
5794 rs = connection.executeQuery(statement);
5795 List<Long> children =
new ArrayList<Long>();
5797 children.add(rs.getLong(
"obj_id"));
5800 }
catch (SQLException ex) {
5801 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5804 closeConnection(connection);
5818 List<Long> getAbstractFileChildrenIds(Content parent)
throws TskCoreException {
5819 CaseDbConnection connection = null;
5820 ResultSet rs = null;
5823 connection = connections.getConnection();
5825 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_IDS_BY_PARENT);
5826 statement.clearParameters();
5827 statement.setLong(1, parent.getId());
5828 rs = connection.executeQuery(statement);
5829 List<Long> children =
new ArrayList<Long>();
5831 children.add(rs.getLong(
"obj_id"));
5834 }
catch (SQLException ex) {
5835 throw new TskCoreException(
"Error getting AbstractFile children for Content", ex);
5838 closeConnection(connection);
5853 List<Long> getBlackboardArtifactChildrenIds(Content parent)
throws TskCoreException {
5854 CaseDbConnection connection = null;
5855 ResultSet rs = null;
5858 connection = connections.getConnection();
5860 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_OBJECTIDS_BY_PARENT);
5861 statement.clearParameters();
5862 statement.setLong(1, parent.getId());
5863 rs = connection.executeQuery(statement);
5864 List<Long> children =
new ArrayList<Long>();
5866 children.add(rs.getLong(
"obj_id"));
5869 }
catch (SQLException ex) {
5870 throw new TskCoreException(
"Error getting children for BlackboardArtifact", ex);
5873 closeConnection(connection);
5887 List<Content> getBlackboardArtifactChildren(Content parent)
throws TskCoreException {
5888 long parentId = parent.getId();
5889 List<Content> lc =
new ArrayList<>();
5891 lc.addAll(blackboard.getDataArtifactsBySource(parentId));
5903 Collection<ObjectInfo> getChildrenInfo(Content c)
throws TskCoreException {
5904 CaseDbConnection connection = null;
5906 ResultSet rs = null;
5909 connection = connections.getConnection();
5910 s = connection.createStatement();
5911 rs = connection.executeQuery(s,
"SELECT tsk_objects.obj_id AS obj_id, tsk_objects.type AS type "
5912 +
"FROM tsk_objects LEFT JOIN tsk_files "
5913 +
"ON tsk_objects.obj_id = tsk_files.obj_id "
5914 +
"WHERE tsk_objects.par_obj_id = " + c.getId()
5915 +
" ORDER BY tsk_objects.obj_id");
5916 Collection<ObjectInfo> infos =
new ArrayList<ObjectInfo>();
5918 infos.add(
new ObjectInfo(rs.getLong(
"obj_id"), ObjectType.valueOf(rs.getShort(
"type"))));
5921 }
catch (SQLException ex) {
5922 throw new TskCoreException(
"Error getting Children Info for Content", ex);
5926 closeConnection(connection);
5941 ObjectInfo getParentInfo(Content c)
throws TskCoreException {
5942 return getParentInfo(c.getId());
5955 ObjectInfo getParentInfo(
long contentId)
throws TskCoreException {
5957 CaseDbConnection connection = null;
5959 ResultSet rs = null;
5961 connection = connections.getConnection();
5962 s = connection.createStatement();
5963 rs = connection.executeQuery(s,
"SELECT parent.obj_id AS obj_id, parent.type AS type "
5964 +
"FROM tsk_objects AS parent INNER JOIN tsk_objects AS child "
5965 +
"ON child.par_obj_id = parent.obj_id "
5966 +
"WHERE child.obj_id = " + contentId);
5968 return new ObjectInfo(rs.getLong(
"obj_id"), ObjectType.valueOf(rs.getShort(
"type")));
5972 }
catch (SQLException ex) {
5973 throw new TskCoreException(
"Error getting Parent Info for Content: " + contentId, ex);
5977 closeConnection(connection);
5992 Directory getParentDirectory(FsContent fsc)
throws TskCoreException {
5997 ObjectInfo parentInfo = getParentInfo(fsc);
5998 if (parentInfo == null) {
6001 Directory parent = null;
6002 if (parentInfo.type == ObjectType.ABSTRACTFILE) {
6003 parent = getDirectoryById(parentInfo.id, fsc.getFileSystem());
6005 throw new TskCoreException(
"Parent of FsContent (id: " + fsc.getId() +
") has wrong type to be directory: " + parentInfo.type);
6024 Content content = frequentlyUsedContentMap.get(
id);
6025 if (null != content) {
6032 CaseDbConnection connection = null;
6034 ResultSet rs = null;
6037 connection = connections.getConnection();
6038 s = connection.createStatement();
6039 rs = connection.executeQuery(s,
"SELECT * FROM tsk_objects WHERE obj_id = " +
id +
" LIMIT 1");
6043 parentId = rs.getLong(
"par_obj_id");
6045 }
catch (SQLException ex) {
6046 throw new TskCoreException(
"Error getting Content by ID.", ex);
6050 closeConnection(connection);
6058 frequentlyUsedContentMap.put(
id, content);
6061 content = getVolumeSystemById(
id, parentId);
6064 content = getVolumeById(
id, parentId);
6065 frequentlyUsedContentMap.put(
id, content);
6068 content = getPoolById(
id, parentId);
6071 content = getFileSystemById(
id, parentId);
6072 frequentlyUsedContentMap.put(
id, content);
6083 frequentlyUsedContentMap.put(
id, content);
6112 String getFilePath(
long id) {
6114 String filePath = null;
6115 CaseDbConnection connection = null;
6116 ResultSet rs = null;
6119 connection = connections.getConnection();
6121 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_LOCAL_PATH_FOR_FILE);
6122 statement.clearParameters();
6123 statement.setLong(1,
id);
6124 rs = connection.executeQuery(statement);
6126 filePath = rs.getString(
"path");
6128 }
catch (SQLException | TskCoreException ex) {
6129 logger.log(Level.SEVERE,
"Error getting file path for file " +
id, ex);
6132 closeConnection(connection);
6145 TskData.EncodingType getEncodingType(
long id) {
6147 TskData.EncodingType type = TskData.EncodingType.NONE;
6148 CaseDbConnection connection = null;
6149 ResultSet rs = null;
6152 connection = connections.getConnection();
6153 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ENCODING_FOR_FILE);
6154 statement.clearParameters();
6155 statement.setLong(1,
id);
6156 rs = connection.executeQuery(statement);
6158 type = TskData.EncodingType.valueOf(rs.getInt(1));
6160 }
catch (SQLException | TskCoreException ex) {
6161 logger.log(Level.SEVERE,
"Error getting encoding type for file " +
id, ex);
6164 closeConnection(connection);
6178 String getFileParentPath(
long objectId, CaseDbConnection connection) {
6179 String parentPath = null;
6181 ResultSet rs = null;
6183 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_PATH_FOR_FILE);
6184 statement.clearParameters();
6185 statement.setLong(1, objectId);
6186 rs = connection.executeQuery(statement);
6188 parentPath = rs.getString(
"parent_path");
6190 }
catch (SQLException ex) {
6191 logger.log(Level.SEVERE,
"Error getting file parent_path for file " + objectId, ex);
6207 String getFileName(
long objectId, CaseDbConnection connection) {
6208 String fileName = null;
6210 ResultSet rs = null;
6212 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_NAME);
6213 statement.clearParameters();
6214 statement.setLong(1, objectId);
6215 rs = connection.executeQuery(statement);
6217 fileName = rs.getString(
"name");
6219 }
catch (SQLException ex) {
6220 logger.log(Level.SEVERE,
"Error getting file parent_path for file " + objectId, ex);
6238 DerivedFile.DerivedMethod getDerivedMethod(
long id)
throws TskCoreException {
6240 DerivedFile.DerivedMethod method = null;
6241 CaseDbConnection connection = null;
6242 ResultSet rs1 = null;
6243 ResultSet rs2 = null;
6246 connection = connections.getConnection();
6248 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_DERIVED_FILE);
6249 statement.clearParameters();
6250 statement.setLong(1,
id);
6251 rs1 = connection.executeQuery(statement);
6253 int method_id = rs1.getInt(
"derived_id");
6254 String rederive = rs1.getString(
"rederive");
6255 method =
new DerivedFile.DerivedMethod(method_id, rederive);
6256 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_DERIVATION_METHOD);
6257 statement.clearParameters();
6258 statement.setInt(1, method_id);
6259 rs2 = connection.executeQuery(statement);
6261 method.setToolName(rs2.getString(
"tool_name"));
6262 method.setToolVersion(rs2.getString(
"tool_version"));
6263 method.setOther(rs2.getString(
"other"));
6266 }
catch (SQLException e) {
6267 logger.log(Level.SEVERE,
"Error getting derived method for file: " +
id, e);
6269 closeResultSet(rs2);
6270 closeResultSet(rs1);
6271 closeConnection(connection);
6288 CaseDbConnection connection = connections.getConnection();
6292 closeConnection(connection);
6310 ResultSet rs = null;
6312 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_BY_ID);
6313 statement.clearParameters();
6314 statement.setLong(1, objectId);
6315 rs = connection.executeQuery(statement);
6316 List<AbstractFile> files = resultSetToAbstractFiles(rs, connection);
6317 if (files.size() > 0) {
6318 return files.get(0);
6322 }
catch (SQLException ex) {
6323 throw new TskCoreException(
"Error getting file by id, id = " + objectId, ex);
6343 CaseDbConnection connection = null;
6344 ResultSet rs = null;
6347 connection = connections.getConnection();
6350 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TYPE_BY_ARTIFACT_OBJ_ID);
6351 statement.clearParameters();
6352 statement.setLong(1,
id);
6354 rs = connection.executeQuery(statement);
6356 throw new TskCoreException(
"Error getting artifacttype for artifact with artifact_obj_id = " +
id);
6361 switch (artifactType.getCategory()) {
6362 case ANALYSIS_RESULT:
6367 throw new TskCoreException(String.format(
"Unknown artifact category for artifact with artifact_obj_id = %d, and artifact type = %s",
id, artifactType.getTypeName()));
6370 }
catch (SQLException ex) {
6371 throw new TskCoreException(
"Error getting artifacts by artifact_obj_id, artifact_obj_id = " +
id, ex);
6374 closeConnection(connection);
6394 String query =
"SELECT artifact_type_id, artifact_obj_id FROM blackboard_artifacts WHERE artifact_id = " + id;
6397 try (CaseDbConnection connection = connections.getConnection();
6398 Statement statement = connection.createStatement();
6399 ResultSet resultSet = statement.executeQuery(query);) {
6400 if (resultSet != null && resultSet.next()) {
6402 long artifactObjId = resultSet.getLong(
"artifact_obj_id");
6403 switch (artifactType.getCategory()) {
6404 case ANALYSIS_RESULT:
6411 }
catch (SQLException ex) {
6412 throw new TskCoreException(
"Error getting artifacts by artifact id, artifact id = " +
id, ex);
6430 private long getFileSystemId(
long fileId, CaseDbConnection connection) {
6432 ResultSet rs = null;
6435 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILE_SYSTEM_BY_OBJECT);
6436 statement.clearParameters();
6437 statement.setLong(1, fileId);
6438 rs = connection.executeQuery(statement);
6440 ret = rs.getLong(
"fs_obj_id");
6445 }
catch (SQLException e) {
6446 logger.log(Level.SEVERE,
"Error checking file system id of a file, id = " + fileId, e);
6466 String query = String.format(
"SELECT COUNT(*) AS count FROM tsk_files WHERE obj_id = %d AND data_source_obj_id = %d", fileId, dataSource.getId());
6467 CaseDbConnection connection = null;
6468 Statement statement = null;
6469 ResultSet resultSet = null;
6472 connection = connections.getConnection();
6473 statement = connection.createStatement();
6474 resultSet = connection.executeQuery(statement, query);
6476 return (resultSet.getLong(
"count") > 0L);
6477 }
catch (SQLException ex) {
6478 throw new TskCoreException(String.format(
"Error executing query %s", query), ex);
6480 closeResultSet(resultSet);
6481 closeStatement(statement);
6482 closeConnection(connection);
6496 private static boolean containsLikeWildcard(String str) {
6500 return str.contains(
"%") || str.contains(
"_");
6515 public List<AbstractFile>
findFiles(
Content dataSource, String fileName)
throws TskCoreException {
6517 if (!containsLikeWildcard(fileName)) {
6521 List<AbstractFile> files =
new ArrayList<>();
6522 CaseDbConnection connection = null;
6523 ResultSet resultSet = null;
6526 connection = connections.getConnection();
6528 PreparedStatement statement;
6529 if (ext.isEmpty()) {
6530 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_DATA_SOURCE_AND_NAME);
6531 statement.clearParameters();
6532 statement.setString(1, fileName.toLowerCase());
6533 statement.setLong(2, dataSource.getId());
6535 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_EXTENSION_AND_DATA_SOURCE_AND_NAME);
6536 statement.clearParameters();
6537 statement.setString(1, ext);
6538 statement.setString(2, fileName.toLowerCase());
6539 statement.setLong(3, dataSource.getId());
6542 resultSet = connection.executeQuery(statement);
6543 files.addAll(resultSetToAbstractFiles(resultSet, connection));
6544 }
catch (SQLException e) {
6545 throw new TskCoreException(bundle.getString(
"SleuthkitCase.findFiles.exception.msg3.text"), e);
6547 closeResultSet(resultSet);
6548 closeConnection(connection);
6567 public List<AbstractFile>
findFiles(
Content dataSource, String fileName, String dirSubString)
throws TskCoreException {
6569 if (!containsLikeWildcard(fileName)) {
6573 List<AbstractFile> files =
new ArrayList<>();
6574 CaseDbConnection connection = null;
6575 ResultSet resultSet = null;
6578 connection = connections.getConnection();
6579 PreparedStatement statement;
6580 if (ext.isEmpty()) {
6581 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_DATA_SOURCE_AND_PARENT_PATH_AND_NAME);
6582 statement.clearParameters();
6583 statement.setString(1, fileName.toLowerCase());
6584 statement.setString(2,
"%" + dirSubString.toLowerCase() +
"%");
6585 statement.setLong(3, dataSource.getId());
6587 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_EXTENSION_AND_DATA_SOURCE_AND_PARENT_PATH_AND_NAME);
6588 statement.clearParameters();
6589 statement.setString(1, ext);
6590 statement.setString(2, fileName.toLowerCase());
6591 statement.setString(3,
"%" + dirSubString.toLowerCase() +
"%");
6592 statement.setLong(4, dataSource.getId());
6595 resultSet = connection.executeQuery(statement);
6596 files.addAll(resultSetToAbstractFiles(resultSet, connection));
6597 }
catch (SQLException e) {
6598 throw new TskCoreException(bundle.getString(
"SleuthkitCase.findFiles3.exception.msg3.text"), e);
6600 closeResultSet(resultSet);
6601 closeConnection(connection);
6626 if (null != localTrans) {
6629 }
catch (TskCoreException ex2) {
6630 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
6648 long addObject(
long parentId,
int objectType, CaseDbConnection connection)
throws SQLException {
6649 ResultSet resultSet = null;
6653 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_OBJECT, Statement.RETURN_GENERATED_KEYS);
6654 statement.clearParameters();
6655 if (parentId != 0) {
6656 statement.setLong(1, parentId);
6658 statement.setNull(1, java.sql.Types.BIGINT);
6660 statement.setInt(2, objectType);
6661 connection.executeUpdate(statement);
6662 resultSet = statement.getGeneratedKeys();
6664 if (resultSet.next()) {
6665 if (parentId != 0) {
6666 setHasChildren(parentId);
6668 return resultSet.getLong(1);
6670 throw new SQLException(
"Error inserting object with parent " + parentId +
" into tsk_objects");
6673 closeResultSet(resultSet);
6696 if (transaction == null) {
6697 throw new TskCoreException(
"Passed null CaseDbTransaction");
6700 ResultSet resultSet = null;
6703 CaseDbConnection connection = transaction.getConnection();
6708 if (isRootDirectory((AbstractFile) parent, transaction)) {
6709 if (parent.
getName().isEmpty()) {
6712 parentPath =
"/" + parent.
getName() +
"/";
6715 parentPath = ((AbstractFile) parent).getParentPath() + parent.
getName() +
"/";
6729 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
6730 statement.clearParameters();
6731 statement.setLong(1, newObjId);
6734 Long fileSystemObjectId = null;
6735 if (0 != parentId) {
6736 fileSystemObjectId = this.getFileSystemId(parentId, connection);
6737 if (fileSystemObjectId != -1) {
6738 statement.setLong(2, fileSystemObjectId);
6740 statement.setNull(2, java.sql.Types.BIGINT);
6741 fileSystemObjectId = null;
6744 statement.setNull(2, java.sql.Types.BIGINT);
6748 statement.setString(3, directoryName);
6752 statement.setShort(5, (
short) 1);
6756 statement.setShort(6, dirType.
getValue());
6758 statement.setShort(7, metaType.
getValue());
6762 statement.setShort(8, dirFlag.
getValue());
6765 statement.setShort(9, metaFlags);
6768 statement.setLong(10, 0);
6771 statement.setNull(11, java.sql.Types.BIGINT);
6772 statement.setNull(12, java.sql.Types.BIGINT);
6773 statement.setNull(13, java.sql.Types.BIGINT);
6774 statement.setNull(14, java.sql.Types.BIGINT);
6776 statement.setNull(15, java.sql.Types.VARCHAR);
6777 statement.setNull(16, java.sql.Types.VARCHAR);
6778 statement.setNull(17, java.sql.Types.VARCHAR);
6781 statement.setNull(19, java.sql.Types.VARCHAR);
6784 statement.setString(20, parentPath);
6787 long dataSourceObjectId;
6788 if (0 == parentId) {
6789 dataSourceObjectId = newObjId;
6791 dataSourceObjectId = getDataSourceObjectId(connection, parentId);
6793 statement.setLong(21, dataSourceObjectId);
6796 statement.setString(22, null);
6798 statement.setString(23,
OsAccount.NO_OWNER_ID);
6799 statement.setNull(24, java.sql.Types.BIGINT);
6802 connection.executeUpdate(statement);
6804 return new VirtualDirectory(
this, newObjId, dataSourceObjectId, fileSystemObjectId, directoryName, dirType,
6807 }
catch (SQLException e) {
6808 throw new TskCoreException(
"Error creating virtual directory '" + directoryName +
"'", e);
6810 closeResultSet(resultSet);
6832 }
catch (TskCoreException ex) {
6835 }
catch (TskCoreException ex2) {
6836 logger.log(Level.SEVERE, String.format(
"Failed to rollback transaction after exception: %s", ex.getMessage()), ex2);
6860 if (transaction == null) {
6861 throw new TskCoreException(
"Passed null CaseDbTransaction");
6864 ResultSet resultSet = null;
6867 CaseDbConnection connection = transaction.getConnection();
6870 if ((parent == null) || isRootDirectory(parent, transaction)) {
6883 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
6884 statement.clearParameters();
6885 statement.setLong(1, newObjId);
6888 statement.setNull(2, java.sql.Types.BIGINT);
6891 statement.setString(3, directoryName);
6895 statement.setShort(5, (
short) 1);
6899 statement.setShort(6, dirType.
getValue());
6901 statement.setShort(7, metaType.
getValue());
6905 statement.setShort(8, dirFlag.
getValue());
6908 statement.setShort(9, metaFlags);
6911 statement.setLong(10, 0);
6914 statement.setNull(11, java.sql.Types.BIGINT);
6915 statement.setNull(12, java.sql.Types.BIGINT);
6916 statement.setNull(13, java.sql.Types.BIGINT);
6917 statement.setNull(14, java.sql.Types.BIGINT);
6919 statement.setNull(15, java.sql.Types.VARCHAR);
6920 statement.setNull(16, java.sql.Types.VARCHAR);
6921 statement.setNull(17, java.sql.Types.VARCHAR);
6924 statement.setNull(19, java.sql.Types.VARCHAR);
6927 statement.setString(20, parentPath);
6930 long dataSourceObjectId = getDataSourceObjectId(connection, parentId);
6931 statement.setLong(21, dataSourceObjectId);
6934 statement.setString(22, null);
6936 statement.setString(23,
OsAccount.NO_OWNER_ID);
6937 statement.setNull(24, java.sql.Types.BIGINT);
6940 connection.executeUpdate(statement);
6942 return new LocalDirectory(
this, newObjId, dataSourceObjectId, directoryName, dirType,
6945 }
catch (SQLException e) {
6946 throw new TskCoreException(
"Error creating local directory '" + directoryName +
"'", e);
6948 closeResultSet(resultSet);
6997 Statement statement = null;
6999 CaseDbConnection connection = transaction.getConnection();
7012 statement = connection.createStatement();
7013 statement.executeUpdate(
"INSERT INTO data_source_info (obj_id, device_id, time_zone, host_id) "
7014 +
"VALUES(" + newObjId +
", '" + deviceId +
"', '" + timeZone +
"', " + host.getHostId() +
");");
7023 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
7024 preparedStatement.clearParameters();
7025 preparedStatement.setLong(1, newObjId);
7026 preparedStatement.setNull(2, java.sql.Types.BIGINT);
7027 preparedStatement.setString(3, rootDirectoryName);
7029 preparedStatement.setShort(5, (
short) 1);
7033 preparedStatement.setShort(7, metaType.
getValue());
7035 preparedStatement.setShort(8, dirFlag.
getValue());
7038 preparedStatement.setShort(9, metaFlags);
7039 preparedStatement.setLong(10, 0);
7040 preparedStatement.setNull(11, java.sql.Types.BIGINT);
7041 preparedStatement.setNull(12, java.sql.Types.BIGINT);
7042 preparedStatement.setNull(13, java.sql.Types.BIGINT);
7043 preparedStatement.setNull(14, java.sql.Types.BIGINT);
7044 preparedStatement.setNull(15, java.sql.Types.VARCHAR);
7045 preparedStatement.setNull(16, java.sql.Types.VARCHAR);
7046 preparedStatement.setNull(17, java.sql.Types.VARCHAR);
7048 preparedStatement.setNull(19, java.sql.Types.VARCHAR);
7049 String parentPath =
"/";
7050 preparedStatement.setString(20, parentPath);
7051 preparedStatement.setLong(21, newObjId);
7052 preparedStatement.setString(22, null);
7053 preparedStatement.setString(23,
OsAccount.NO_OWNER_ID);
7054 preparedStatement.setNull(24, java.sql.Types.BIGINT);
7058 connection.executeUpdate(preparedStatement);
7060 return new LocalFilesDataSource(
this, newObjId, newObjId, deviceId, rootDirectoryName, dirType, metaType, dirFlag, metaFlags, timeZone, null, null, null,
FileKnown.
UNKNOWN, parentPath);
7062 }
catch (SQLException ex) {
7063 throw new TskCoreException(String.format(
"Error creating local files data source with device id %s and directory name %s", deviceId, rootDirectoryName), ex);
7065 closeStatement(statement);
7089 String timezone, String md5, String sha1, String sha256,
7092 return addImage(type, sectorSize, size, displayName, imagePaths, timezone, md5, sha1, sha256, deviceId, null, transaction);
7116 String timezone, String md5, String sha1, String sha256,
7117 String deviceId,
Host host,
7120 return addImage(type, sectorSize, size, displayName, imagePaths, timezone, md5, sha1, sha256, deviceId, host, null, transaction);
7146 String timezone, String md5, String sha1, String sha256,
7147 String deviceId,
Host host, String password,
7149 Statement statement = null;
7152 CaseDbConnection connection = transaction.getConnection();
7157 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_IMAGE_INFO);
7158 preparedStatement.clearParameters();
7159 preparedStatement.setLong(1, newObjId);
7160 preparedStatement.setShort(2, (
short) type.getValue());
7161 preparedStatement.setLong(3, sectorSize);
7162 preparedStatement.setString(4, timezone);
7164 long savedSize = size < 0 ? 0 : size;
7165 preparedStatement.setLong(5, savedSize);
7166 preparedStatement.setString(6, md5);
7167 preparedStatement.setString(7, sha1);
7168 preparedStatement.setString(8, sha256);
7169 preparedStatement.setString(9, displayName);
7170 connection.executeUpdate(preparedStatement);
7173 for (
int i = 0; i < imagePaths.size(); i++) {
7174 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_IMAGE_NAME);
7175 preparedStatement.clearParameters();
7176 preparedStatement.setLong(1, newObjId);
7177 preparedStatement.setString(2, imagePaths.get(i));
7178 preparedStatement.setLong(3, i);
7179 connection.executeUpdate(preparedStatement);
7183 String name = displayName;
7184 if (name == null || name.isEmpty()) {
7185 if (imagePaths.size() > 0) {
7186 String path = imagePaths.get(0);
7187 name = (
new java.io.File(path)).getName();
7195 if (name.isEmpty()) {
7202 Map<String, Object> acquisitionToolMap =
new HashMap<>();
7203 if (password != null) {
7204 acquisitionToolMap.put(IMAGE_PASSWORD_KEY, password);
7206 String acquisitionToolJson = (
new Gson()).toJson(acquisitionToolMap);
7209 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_DATA_SOURCE_INFO);
7210 statement = connection.createStatement();
7211 preparedStatement.setLong(1, newObjId);
7212 preparedStatement.setString(2, deviceId);
7213 preparedStatement.setString(3, timezone);
7214 preparedStatement.setLong(4,
new Date().getTime());
7215 preparedStatement.setLong(5, host.getHostId());
7216 preparedStatement.setString(6, acquisitionToolJson);
7217 connection.executeUpdate(preparedStatement);
7220 return new Image(
this, newObjId, type.getValue(), deviceId, sectorSize, name,
7221 imagePaths.toArray(
new String[imagePaths.size()]), timezone, md5, sha1, sha256, savedSize);
7222 }
catch (SQLException ex) {
7223 if (!imagePaths.isEmpty()) {
7224 throw new TskCoreException(String.format(
"Error adding image with path %s to database", imagePaths.get(0)), ex);
7226 throw new TskCoreException(String.format(
"Error adding image with display name %s to database", displayName), ex);
7229 closeStatement(statement);
7250 CaseDbConnection connection = transaction.getConnection();
7251 long newObjId = addObject(parentObjId,
TskData.
ObjectType.
VS.getObjectType(), connection);
7255 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_VS_INFO);
7256 preparedStatement.clearParameters();
7257 preparedStatement.setLong(1, newObjId);
7258 preparedStatement.setShort(2, (
short) type.getVsType());
7259 preparedStatement.setLong(3, imgOffset);
7260 preparedStatement.setLong(4, blockSize);
7261 connection.executeUpdate(preparedStatement);
7264 return new VolumeSystem(
this, newObjId,
"", type.getVsType(), imgOffset, blockSize);
7265 }
catch (SQLException ex) {
7266 throw new TskCoreException(String.format(
"Error creating volume system with parent ID %d and image offset %d",
7267 parentObjId, imgOffset), ex);
7286 public Volume addVolume(
long parentObjId,
long addr,
long start,
long length, String desc,
7290 CaseDbConnection connection = transaction.getConnection();
7295 PreparedStatement preparedStatement;
7297 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_VS_PART_POSTGRESQL);
7299 preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_VS_PART_SQLITE);
7301 preparedStatement.clearParameters();
7302 preparedStatement.setLong(1, newObjId);
7303 preparedStatement.setLong(2, addr);
7304 preparedStatement.setLong(3, start);
7305 preparedStatement.setLong(4, length);
7306 preparedStatement.setString(5, desc);
7307 preparedStatement.setShort(6, (
short) flags);
7308 connection.executeUpdate(preparedStatement);
7311 return new Volume(
this, newObjId, addr, start, length, flags, desc);
7312 }
catch (SQLException ex) {
7313 throw new TskCoreException(String.format(
"Error creating volume with address %d and parent ID %d", addr, parentObjId), ex);
7331 CaseDbConnection connection = transaction.getConnection();
7336 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_POOL_INFO);
7337 preparedStatement.clearParameters();
7338 preparedStatement.setLong(1, newObjId);
7339 preparedStatement.setShort(2, type.getValue());
7340 connection.executeUpdate(preparedStatement);
7343 return new Pool(
this, newObjId, type.getName(), type.getValue());
7344 }
catch (SQLException ex) {
7345 throw new TskCoreException(String.format(
"Error creating pool with type %d and parent ID %d", type.getValue(), parentObjId), ex);
7368 long rootInum,
long firstInum,
long lastInum, String displayName,
7372 CaseDbConnection connection = transaction.getConnection();
7373 long newObjId = addObject(parentObjId,
TskData.
ObjectType.
FS.getObjectType(), connection);
7376 long dataSourceId = getDataSourceObjectId(connection, newObjId);
7380 PreparedStatement preparedStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FS_INFO);
7381 preparedStatement.clearParameters();
7382 preparedStatement.setLong(1, newObjId);
7383 preparedStatement.setLong(2, dataSourceId);
7384 preparedStatement.setLong(3, imgOffset);
7385 preparedStatement.setInt(4, type.getValue());
7386 preparedStatement.setLong(5, blockSize);
7387 preparedStatement.setLong(6, blockCount);
7388 preparedStatement.setLong(7, rootInum);
7389 preparedStatement.setLong(8, firstInum);
7390 preparedStatement.setLong(9, lastInum);
7391 preparedStatement.setString(10, displayName);
7392 connection.executeUpdate(preparedStatement);
7395 return new FileSystem(
this, newObjId, displayName, imgOffset, type, blockSize, blockCount, rootInum,
7396 firstInum, lastInum);
7397 }
catch (SQLException ex) {
7398 throw new TskCoreException(String.format(
"Error creating file system with image offset %d and parent ID %d",
7399 imgOffset, parentObjId), ex);
7430 long metaAddr,
int metaSeq,
7433 long ctime,
long crtime,
long atime,
long mtime,
7434 boolean isFile,
Content parent)
throws TskCoreException {
7440 metaAddr, metaSeq, attrType, attrId, dirFlag, metaFlags, size,
7441 ctime, crtime, atime, mtime, null, null, null, isFile, parent,
7443 Collections.emptyList(), transaction);
7447 return fileSystemFile;
7449 if (null != transaction) {
7452 }
catch (TskCoreException ex2) {
7453 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
7498 long metaAddr,
int metaSeq,
7501 long ctime,
long crtime,
long atime,
long mtime,
7502 String md5Hash, String sha256Hash, String mimeType,
7503 boolean isFile,
Content parent, String ownerUid,
7504 OsAccount osAccount, List<Attribute> fileAttributes,
7511 dirFlag, metaFlags, size,
7512 ctime, crtime, atime, mtime,
7513 md5Hash, sha256Hash, null,
7515 isFile, parent, ownerUid,
7516 osAccount, fileAttributes,
7561 long metaAddr,
int metaSeq,
7564 long ctime,
long crtime,
long atime,
long mtime,
7565 String md5Hash, String sha256Hash, String sha1Hash,
7566 String mimeType,
boolean isFile,
7567 Content parent, String ownerUid,
7568 OsAccount osAccount, List<Attribute> fileAttributes,
7574 dirFlag, metaFlags, size,
7575 ctime, crtime, atime, mtime,
7576 md5Hash, sha256Hash, sha1Hash,
7578 isFile, parent, ownerUid,
7625 long metaAddr,
int metaSeq,
7628 long ctime,
long crtime,
long atime,
long mtime,
7629 String md5Hash, String sha256Hash, String sha1Hash,
7630 String mimeType,
boolean isFile,
7631 Content parent, String ownerUid,
7633 List<Attribute> fileAttributes,
7637 Statement queryStatement = null;
7638 String parentPath =
"/";
7640 CaseDbConnection connection = transaction.getConnection();
7647 AbstractFile parentFile = (AbstractFile) parent;
7648 if (isRootDirectory(parentFile, transaction)) {
7651 parentPath = parentFile.
getParentPath() + parent.getName() +
"/";
7657 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE_SYSTEM_FILE);
7658 statement.clearParameters();
7659 statement.setLong(1, objectId);
7660 statement.setLong(2, fsObjId);
7661 statement.setLong(3, dataSourceObjId);
7662 statement.setShort(4, (
short) attrType.getValue());
7663 statement.setInt(5, attrId);
7664 statement.setString(6, fileName);
7665 statement.setLong(7, metaAddr);
7666 statement.setInt(8, metaSeq);
7668 statement.setShort(10, (
short) 1);
7670 statement.setShort(11, dirType.
getValue());
7672 statement.setShort(12, metaType.
getValue());
7673 statement.setShort(13, dirFlag.getValue());
7674 statement.setShort(14, metaFlags);
7675 statement.setLong(15, size < 0 ? 0 : size);
7676 statement.setLong(16, ctime);
7677 statement.setLong(17, crtime);
7678 statement.setLong(18, atime);
7679 statement.setLong(19, mtime);
7680 statement.setString(20, md5Hash);
7681 statement.setString(21, sha256Hash);
7682 statement.setString(22, sha1Hash);
7683 statement.setString(23, mimeType);
7684 statement.setString(24, parentPath);
7685 final String extension = extractExtension(fileName);
7686 statement.setString(25, extension);
7687 statement.setString(26, ownerUid);
7688 if (null != osAccount) {
7689 statement.setLong(27, osAccount.getId());
7691 statement.setNull(27, java.sql.Types.BIGINT);
7693 statement.setLong(28, collected.getType());
7695 connection.executeUpdate(statement);
7697 Long osAccountId = (osAccount != null) ? osAccount.getId() : null;
7698 DerivedFile derivedFile =
new DerivedFile(
this, objectId, dataSourceObjId, fsObjId, fileName, dirType, metaType, dirFlag, metaFlags,
7699 size, ctime, crtime, atime, mtime, md5Hash, sha256Hash, sha1Hash, null, parentPath, null, parent.getId(), mimeType, null, extension, ownerUid, osAccountId);
7701 if (!timelineEventsDisabled.get()) {
7702 timelineManager.addEventsForNewFile(derivedFile, connection);
7705 for (
Attribute fileAttribute : fileAttributes) {
7706 fileAttribute.setAttributeParentId(objectId);
7707 fileAttribute.setCaseDatabase(
this);
7708 addFileAttribute(fileAttribute, connection);
7711 if (osAccount != null) {
7716 attrType, attrId, fileName, metaAddr, metaSeq,
7717 dirType, metaType, dirFlag, metaFlags,
7718 size, ctime, crtime, atime, mtime,
7719 (
short) 0, 0, 0, md5Hash, sha256Hash, sha1Hash, null, parentPath, mimeType,
7720 extension, ownerUid, osAccountId, collected, fileAttributes);
7722 }
catch (SQLException ex) {
7723 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);
7725 closeStatement(queryStatement);
7738 CaseDbConnection connection = null;
7740 ResultSet rs = null;
7743 connection = connections.getConnection();
7744 s = connection.createStatement();
7745 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE"
7747 +
" AND obj_id = data_source_obj_id"
7748 +
" ORDER BY dir_type, LOWER(name)");
7749 List<VirtualDirectory> virtDirRootIds =
new ArrayList<VirtualDirectory>();
7751 virtDirRootIds.add(virtualDirectory(rs, connection));
7753 return virtDirRootIds;
7754 }
catch (SQLException ex) {
7755 throw new TskCoreException(
"Error getting local files virtual folder id", ex);
7759 closeConnection(connection);
7777 assert (null != fileRanges);
7778 if (null == fileRanges) {
7779 throw new TskCoreException(
"TskFileRange object is null");
7782 assert (null != parent);
7783 if (null == parent) {
7784 throw new TskCoreException(
"Conent is null");
7789 parentPath = ((AbstractFile) parent).getParentPath() + parent.getName() +
'/';
7795 Statement statement = null;
7796 ResultSet resultSet = null;
7800 CaseDbConnection connection = transaction.getConnection();
7803 Long fileSystemObjectId;
7804 if (0 != parent.getId()) {
7805 fileSystemObjectId = this.getFileSystemId(parent.getId(), connection);
7806 if (fileSystemObjectId == -1) {
7807 fileSystemObjectId = null;
7810 fileSystemObjectId = null;
7813 List<LayoutFile> fileRangeLayoutFiles =
new ArrayList<>();
7821 long end_byte_in_parent = fileRange.getByteStart() + fileRange.getByteLen() - 1;
7831 PreparedStatement prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
7832 prepStmt.clearParameters();
7833 prepStmt.setLong(1, fileRangeId);
7834 if (fileSystemObjectId != null) {
7835 prepStmt.setLong(2, fileSystemObjectId);
7837 prepStmt.setNull(2, java.sql.Types.BIGINT);
7839 prepStmt.setString(3,
"Unalloc_" + parent.getId() +
"_" + fileRange.getByteStart() +
"_" + end_byte_in_parent);
7841 prepStmt.setNull(5, java.sql.Types.BIGINT);
7846 prepStmt.setLong(10, fileRange.getByteLen());
7847 prepStmt.setNull(11, java.sql.Types.BIGINT);
7848 prepStmt.setNull(12, java.sql.Types.BIGINT);
7849 prepStmt.setNull(13, java.sql.Types.BIGINT);
7850 prepStmt.setNull(14, java.sql.Types.BIGINT);
7851 prepStmt.setNull(15, java.sql.Types.VARCHAR);
7852 prepStmt.setNull(16, java.sql.Types.VARCHAR);
7853 prepStmt.setNull(17, java.sql.Types.VARCHAR);
7856 prepStmt.setNull(19, java.sql.Types.VARCHAR);
7857 prepStmt.setString(20, parentPath);
7858 prepStmt.setLong(21, parent.getId());
7861 prepStmt.setString(22, null);
7863 prepStmt.setString(23,
OsAccount.NO_OWNER_ID);
7864 prepStmt.setNull(24, java.sql.Types.BIGINT);
7867 connection.executeUpdate(prepStmt);
7874 prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LAYOUT_FILE);
7875 prepStmt.clearParameters();
7876 prepStmt.setLong(1, fileRangeId);
7877 prepStmt.setLong(2, fileRange.getByteStart());
7878 prepStmt.setLong(3, fileRange.getByteLen());
7879 prepStmt.setLong(4, fileRange.getSequence());
7880 connection.executeUpdate(prepStmt);
7885 fileRangeLayoutFiles.add(
new LayoutFile(
this,
7889 Long.toString(fileRange.getSequence()),
7895 fileRange.getByteLen(),
7899 parent.getUniquePath(),
7907 return fileRangeLayoutFiles;
7909 }
catch (SQLException ex) {
7910 throw new TskCoreException(
"Failed to add layout files to case database", ex);
7912 closeResultSet(resultSet);
7913 closeStatement(statement);
7915 if (null != transaction) {
7918 }
catch (TskCoreException ex2) {
7919 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
7931 private class CarvedFileDirInfo {
7934 AtomicInteger count;
7937 this.currentFolder = currentFolder;
7938 count =
new AtomicInteger(0);
7941 CarvedFileDirInfo(VirtualDirectory currentFolder,
int count) {
7942 this.currentFolder = currentFolder;
7943 this.count =
new AtomicInteger(count);
7953 return count.get() >= MAX_CARVED_FILES_PER_FOLDER;
7959 void incrementFileCounter() {
7960 count.incrementAndGet();
7973 private CarvedFileDirInfo getMostRecentCarvedDirInfo(VirtualDirectory carvedFilesBaseDir)
throws TskCoreException {
7974 VirtualDirectory mostRecentDir = null;
7975 for (Content child : carvedFilesBaseDir.getChildren()) {
7976 if (isValidCarvedFileSubfolder(child)) {
7977 if (mostRecentDir == null
7978 || (mostRecentDir.getId() < child.getId())) {
7979 mostRecentDir = (VirtualDirectory) child;
7984 if (mostRecentDir != null) {
7985 return new CarvedFileDirInfo(mostRecentDir, mostRecentDir.getChildrenCount());
7998 private boolean isValidCarvedFileSubfolder(Content subfolder) {
7999 if (!(subfolder instanceof VirtualDirectory)) {
8002 return subfolder.getName().matches(
"^[0-9]+$");
8018 private CarvedFileDirInfo createCarvedFilesSubfolder(Content carvedFilesBaseDir, CarvedFileDirInfo currentSubfolderInfo)
throws TskCoreException {
8020 if (currentSubfolderInfo != null) {
8022 int currentIndex = Integer.parseInt(currentSubfolderInfo.currentFolder.getName());
8023 nextIndex = currentIndex + 1;
8024 }
catch (NumberFormatException ex) {
8025 throw new TskCoreException(
"Unexpected name format for carved files subdirectory with ID: " + currentSubfolderInfo.currentFolder.getId() +
" (" + currentSubfolderInfo.currentFolder.getName() +
")", ex);
8029 VirtualDirectory carvedFilesSubdir =
addVirtualDirectory(carvedFilesBaseDir.getId(), Integer.toString(nextIndex));
8030 return new CarvedFileDirInfo(carvedFilesSubdir);
8045 assert (null != carvingResult);
8046 if (null == carvingResult) {
8047 throw new TskCoreException(
"Carving is null");
8049 assert (null != carvingResult.getParent());
8050 if (null == carvingResult.getParent()) {
8051 throw new TskCoreException(
"Carving result has null parent");
8053 assert (null != carvingResult.getCarvedFiles());
8054 if (null == carvingResult.getCarvedFiles()) {
8055 throw new TskCoreException(
"Carving result has null carved files");
8058 Statement statement = null;
8059 ResultSet resultSet = null;
8069 while (null != root) {
8083 CarvedFileDirInfo carvedFilesDirInfo = null;
8084 synchronized (carvedFileDirsLock) {
8086 carvedFilesDirInfo = rootIdsToCarvedFileDirs.get(root.
getId());
8087 if (carvedFilesDirInfo != null) {
8088 carvedFilesDirInfo.incrementFileCounter();
8091 if (carvedFilesDirInfo.isFull()) {
8092 carvedFilesDirInfo = createCarvedFilesSubfolder(carvedFilesDirInfo.currentFolder.getParent(), carvedFilesDirInfo);
8096 if (null == carvedFilesDirInfo) {
8097 List<Content> rootChildren;
8099 rootChildren = ((FileSystem) root).getRootDirectory().getChildren();
8103 for (
Content child : rootChildren) {
8104 if (child instanceof VirtualDirectory && child.getName().equals(VirtualDirectory.NAME_CARVED)) {
8106 VirtualDirectory baseDir = (VirtualDirectory) child;
8109 carvedFilesDirInfo = getMostRecentCarvedDirInfo(baseDir);
8112 if (carvedFilesDirInfo == null) {
8113 carvedFilesDirInfo = createCarvedFilesSubfolder(baseDir, null);
8117 if (carvedFilesDirInfo.isFull()) {
8118 carvedFilesDirInfo = createCarvedFilesSubfolder(baseDir, carvedFilesDirInfo);
8121 rootIdsToCarvedFileDirs.put(root.
getId(), carvedFilesDirInfo);
8125 if (carvedFilesDirInfo == null) {
8129 long parId = root.
getId();
8131 if (root instanceof FileSystem) {
8132 Content rootDir = ((FileSystem) root).getRootDirectory();
8133 parId = rootDir.
getId();
8135 VirtualDirectory carvedFilesBaseDir =
addVirtualDirectory(parId, VirtualDirectory.NAME_CARVED);
8136 carvedFilesDirInfo = createCarvedFilesSubfolder(carvedFilesBaseDir, null);
8137 rootIdsToCarvedFileDirs.put(root.
getId(), carvedFilesDirInfo);
8146 VirtualDirectory carvedFilesBaseDir = (VirtualDirectory) carvedFilesDirInfo.currentFolder.getParent();
8148 CaseDbConnection connection = transaction.getConnection();
8149 String parentPath = getFileParentPath(carvedFilesDirInfo.currentFolder.getId(), connection) + carvedFilesDirInfo.currentFolder.getName() +
"/";
8150 List<LayoutFile> carvedFiles =
new ArrayList<>();
8156 VirtualDirectory carvedFilesDir = carvedFilesDirInfo.currentFolder;
8157 if (carvedFilesDirInfo.isFull()) {
8163 synchronized (carvedFileDirsLock) {
8165 carvedFilesDirInfo = rootIdsToCarvedFileDirs.get(root.
getId());
8166 if (carvedFilesDirInfo.isFull()) {
8167 carvedFilesDirInfo = createCarvedFilesSubfolder(carvedFilesBaseDir, carvedFilesDirInfo);
8168 rootIdsToCarvedFileDirs.put(root.
getId(), carvedFilesDirInfo);
8169 carvedFilesDir = carvedFilesDirInfo.currentFolder;
8175 connection = transaction.getConnection();
8176 parentPath = getFileParentPath(carvedFilesDir.
getId(), connection) + carvedFilesDir.
getName() +
"/";
8179 carvedFilesDirInfo.incrementFileCounter();
8197 PreparedStatement prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
8198 prepStmt.clearParameters();
8199 prepStmt.setLong(1, carvedFileId);
8200 Long fileSystemObjectId;
8202 prepStmt.setLong(2, root.
getId());
8203 fileSystemObjectId = root.
getId();
8205 prepStmt.setNull(2, java.sql.Types.BIGINT);
8206 fileSystemObjectId = null;
8208 prepStmt.setString(3, carvedFile.getName());
8210 prepStmt.setShort(5, (
short) 1);
8215 prepStmt.setLong(10, carvedFile.getSizeInBytes());
8216 prepStmt.setNull(11, java.sql.Types.BIGINT);
8217 prepStmt.setNull(12, java.sql.Types.BIGINT);
8218 prepStmt.setNull(13, java.sql.Types.BIGINT);
8219 prepStmt.setNull(14, java.sql.Types.BIGINT);
8220 prepStmt.setNull(15, java.sql.Types.VARCHAR);
8221 prepStmt.setNull(16, java.sql.Types.VARCHAR);
8222 prepStmt.setNull(17, java.sql.Types.VARCHAR);
8225 prepStmt.setNull(19, java.sql.Types.VARCHAR);
8226 prepStmt.setString(20, parentPath);
8228 prepStmt.setString(22, extractExtension(carvedFile.getName()));
8230 prepStmt.setString(23,
OsAccount.NO_OWNER_ID);
8231 prepStmt.setNull(24, java.sql.Types.BIGINT);
8234 connection.executeUpdate(prepStmt);
8241 prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LAYOUT_FILE);
8242 for (
TskFileRange tskFileRange : carvedFile.getLayoutInParent()) {
8243 prepStmt.clearParameters();
8244 prepStmt.setLong(1, carvedFileId);
8245 prepStmt.setLong(2, tskFileRange.getByteStart());
8246 prepStmt.setLong(3, tskFileRange.getByteLen());
8247 prepStmt.setLong(4, tskFileRange.getSequence());
8248 connection.executeUpdate(prepStmt);
8258 carvedFile.getName(),
8264 carvedFile.getSizeInBytes(),
8278 }
catch (SQLException ex) {
8279 throw new TskCoreException(
"Failed to add carved files to case database", ex);
8281 closeResultSet(resultSet);
8282 closeStatement(statement);
8284 if (null != transaction) {
8287 }
catch (TskCoreException ex2) {
8288 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
8325 long size,
long ctime,
long crtime,
long atime,
long mtime,
8326 boolean isFile,
Content parentObj,
8327 String rederiveDetails, String toolName, String toolVersion,
8332 size, ctime, crtime, atime, mtime,
8334 rederiveDetails, toolName, toolVersion,
8335 otherDetails, encodingType, transaction);
8338 }
catch (TskCoreException ex) {
8345 long size,
long ctime,
long crtime,
long atime,
long mtime,
8346 boolean isFile,
Content parentObj,
8347 String rederiveDetails, String toolName, String toolVersion,
8350 localPath = localPath.replaceAll(
"^[/\\\\]+",
"");
8354 CaseDbConnection connection = transaction.getConnection();
8356 final long parentId = parentObj.getId();
8357 String parentPath =
"";
8359 parentPath = parentObj.getUniquePath() +
'/' + parentObj.getName() +
'/';
8361 parentPath = ((AbstractFile) parentObj).getParentPath() + parentObj.getName() +
'/';
8373 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
8374 statement.clearParameters();
8375 statement.setLong(1, newObjId);
8378 Long fsObjId = this.getFileSystemId(parentId, connection);
8379 if (fsObjId != -1) {
8380 statement.setLong(2, fsObjId);
8383 statement.setNull(2, java.sql.Types.BIGINT);
8385 statement.setString(3, fileName);
8389 statement.setShort(5, (
short) 1);
8393 statement.setShort(6, dirType.
getValue());
8395 statement.setShort(7, metaType.
getValue());
8399 statement.setShort(8, dirFlag.
getValue());
8402 statement.setShort(9, metaFlags);
8406 long savedSize = size < 0 ? 0 : size;
8407 statement.setLong(10, savedSize);
8411 statement.setLong(11, ctime);
8412 statement.setLong(12, crtime);
8413 statement.setLong(13, atime);
8414 statement.setLong(14, mtime);
8416 statement.setNull(15, java.sql.Types.VARCHAR);
8417 statement.setNull(16, java.sql.Types.VARCHAR);
8418 statement.setNull(17, java.sql.Types.VARCHAR);
8421 statement.setNull(19, java.sql.Types.VARCHAR);
8424 statement.setString(20, parentPath);
8427 long dataSourceObjId = getDataSourceObjectId(connection, parentObj);
8428 statement.setLong(21, dataSourceObjId);
8429 final String extension = extractExtension(fileName);
8431 statement.setString(22, extension);
8433 statement.setString(23,
OsAccount.NO_OWNER_ID);
8434 statement.setNull(24, java.sql.Types.BIGINT);
8437 connection.executeUpdate(statement);
8440 addFilePath(connection, newObjId, localPath, encodingType);
8442 DerivedFile derivedFile =
new DerivedFile(
this, newObjId, dataSourceObjId, fsObjId, fileName, dirType, metaType, dirFlag, metaFlags,
8443 savedSize, ctime, crtime, atime, mtime, null, null, null, null, parentPath, localPath, parentId, null, encodingType, extension,
OsAccount.NO_OWNER_ID,
OsAccount.NO_ACCOUNT);
8445 if (!timelineEventsDisabled.get()) {
8446 timelineManager.addEventsForNewFile(derivedFile, connection);
8451 }
catch (SQLException ex) {
8452 throw new TskCoreException(
"Failed to add derived file to case database", ex);
8487 long size,
long ctime,
long crtime,
long atime,
long mtime,
8488 boolean isFile, String mimeType,
8489 String rederiveDetails, String toolName, String toolVersion,
8498 size, ctime, crtime, atime, mtime,
8500 rederiveDetails, toolName, toolVersion,
8501 otherDetails, encodingType, parentObj, trans);
8504 }
catch (TskCoreException ex) {
8505 if (trans != null) {
8513 long size,
long ctime,
long crtime,
long atime,
long mtime,
8514 boolean isFile, String mimeType,
8515 String rederiveDetails, String toolName, String toolVersion,
8520 localPath = localPath.replaceAll(
"^[/\\\\]+",
"");
8522 ResultSet rs = null;
8524 final long parentId = parentObj.
getId();
8525 String parentPath =
"";
8527 parentPath = parentObj.getUniquePath() +
'/' + parentObj.getName() +
'/';
8529 parentPath = ((AbstractFile) parentObj).getParentPath() + parentObj.getName() +
'/';
8533 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.UPDATE_DERIVED_FILE);
8534 statement.clearParameters();
8541 statement.setShort(2, dirType.
getValue());
8543 statement.setShort(3, metaType.
getValue());
8547 statement.setShort(4, dirFlag.
getValue());
8550 statement.setShort(5, metaFlags);
8554 long savedSize = size < 0 ? 0 : size;
8555 statement.setLong(6, savedSize);
8559 statement.setLong(7, ctime);
8560 statement.setLong(8, crtime);
8561 statement.setLong(9, atime);
8562 statement.setLong(10, mtime);
8563 statement.setString(11, mimeType);
8564 statement.setString(12, String.valueOf(derivedFile.
getId()));
8565 trans.getConnection().executeUpdate(statement);
8568 updateFilePath(trans.getConnection(), derivedFile.
getId(), localPath, encodingType);
8570 long dataSourceObjId = getDataSourceObjectId(trans.getConnection(), parentObj);
8572 final String extension = extractExtension(derivedFile.
getName());
8573 return new DerivedFile(
this, derivedFile.
getId(), dataSourceObjId, fileSystemObjId, derivedFile.
getName(), dirType, metaType, dirFlag, metaFlags,
8574 savedSize, ctime, crtime, atime, mtime, null, null, null, null, parentPath, localPath, parentId, null, encodingType, extension,
8576 }
catch (SQLException ex) {
8577 throw new TskCoreException(
"Failed to add derived file to case database", ex);
8603 long size,
long ctime,
long crtime,
long atime,
long mtime,
8609 LocalFile created =
addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime, isFile, encodingType, parent, localTrans);
8614 if (null != localTrans) {
8617 }
catch (TskCoreException ex2) {
8618 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
8649 long size,
long ctime,
long crtime,
long atime,
long mtime,
8654 size, ctime, crtime, atime, mtime,
8656 isFile, encodingType,
8657 parent, transaction);
8689 long size,
long ctime,
long crtime,
long atime,
long mtime,
8690 String md5, String sha256,
FileKnown known, String mimeType,
8694 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime,
8695 md5, sha256, known, mimeType, isFile, encodingType,
8731 long size,
long ctime,
long crtime,
long atime,
long mtime,
8732 String md5, String sha256,
FileKnown known, String mimeType,
8737 size, ctime, crtime, atime, mtime,
8738 md5, sha256, null, known, mimeType,
8739 isFile, encodingType, osAccountId, ownerAccount,
8740 parent, transaction);
8777 long size,
long ctime,
long crtime,
long atime,
long mtime,
8778 String md5, String sha256, String sha1Hash,
FileKnown known, String mimeType,
8781 CaseDbConnection connection = transaction.getConnection();
8782 Statement queryStatement = null;
8794 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
8795 statement.clearParameters();
8796 statement.setLong(1, objectId);
8797 statement.setNull(2, java.sql.Types.BIGINT);
8798 statement.setString(3, fileName);
8800 statement.setShort(5, (
short) 1);
8802 statement.setShort(6, dirType.
getValue());
8804 statement.setShort(7, metaType.
getValue());
8806 statement.setShort(8, dirFlag.
getValue());
8808 statement.setShort(9, metaFlags);
8810 long savedSize = size < 0 ? 0 : size;
8811 statement.setLong(10, savedSize);
8812 statement.setLong(11, ctime);
8813 statement.setLong(12, crtime);
8814 statement.setLong(13, atime);
8815 statement.setLong(14, mtime);
8816 statement.setString(15, md5);
8817 statement.setString(16, sha256);
8818 statement.setString(17, sha1Hash);
8820 if (known != null) {
8821 statement.setByte(18, known.getFileKnownValue());
8825 statement.setString(19, mimeType);
8827 long dataSourceObjId;
8830 AbstractFile parentFile = (AbstractFile) parent;
8831 if (isRootDirectory(parentFile, transaction)) {
8834 parentPath = parentFile.
getParentPath() + parent.getName() +
"/";
8839 dataSourceObjId = getDataSourceObjectId(connection, parent);
8841 statement.setString(20, parentPath);
8842 statement.setLong(21, dataSourceObjId);
8843 final String extension = extractExtension(fileName);
8844 statement.setString(22, extension);
8846 if (ownerAccount != null) {
8847 statement.setString(23, ownerAccount);
8849 statement.setNull(23, java.sql.Types.VARCHAR);
8852 if (osAccountId != null) {
8853 statement.setLong(24, osAccountId);
8855 statement.setNull(24, java.sql.Types.BIGINT);
8860 connection.executeUpdate(statement);
8861 addFilePath(connection, objectId, localPath, encodingType);
8871 ctime, crtime, atime, mtime,
8872 mimeType, md5, sha256, sha1Hash, known,
8873 parent.getId(), parentPath,
8876 encodingType, extension,
8877 ownerAccount, osAccountId);
8878 if (!timelineEventsDisabled.get()) {
8883 }
catch (SQLException ex) {
8884 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);
8886 closeStatement(queryStatement);
8895 private class RootDirectoryKey {
8897 private long dataSourceId;
8898 private Long fileSystemId;
8900 RootDirectoryKey(
long dataSourceId, Long fileSystemId) {
8901 this.dataSourceId = dataSourceId;
8902 this.fileSystemId = fileSystemId;
8906 public int hashCode() {
8908 hash = 41 * hash + Objects.hashCode(dataSourceId);
8909 hash = 41 * hash + Objects.hashCode(fileSystemId);
8914 public boolean equals(Object obj) {
8921 if (getClass() != obj.getClass()) {
8925 RootDirectoryKey otherKey = (RootDirectoryKey) obj;
8926 if (dataSourceId != otherKey.dataSourceId) {
8930 if (fileSystemId != null) {
8931 return fileSystemId.equals(otherKey.fileSystemId);
8933 return (otherKey.fileSystemId == null);
8949 private boolean isRootDirectory(AbstractFile file, CaseDbTransaction transaction)
throws TskCoreException {
8954 Long fsObjId = null;
8955 if (file instanceof FsContent) {
8956 fsObjId = ((FsContent) file).getFileSystemId();
8959 synchronized (rootDirectoryMapLock) {
8960 if (rootDirectoryMap.containsKey(key)) {
8961 return rootDirectoryMap.get(key).equals(file.
getId());
8968 Boolean isRoot = isRootDirectoryCache.getIfPresent(file.
getId());
8969 if (isRoot != null) {
8973 CaseDbConnection connection = transaction.getConnection();
8974 Statement statement = null;
8975 ResultSet resultSet = null;
8978 String query = String.format(
"SELECT ParentRow.type AS parent_type, ParentRow.obj_id AS parent_object_id "
8979 +
"FROM tsk_objects ParentRow JOIN tsk_objects ChildRow ON ChildRow.par_obj_id = ParentRow.obj_id "
8980 +
"WHERE ChildRow.obj_id = %s;", file.
getId());
8982 statement = connection.createStatement();
8983 resultSet = statement.executeQuery(query);
8984 if (resultSet.next()) {
8985 long parentId = resultSet.getLong(
"parent_object_id");
8986 if (parentId == 0) {
8989 int type = resultSet.getInt(
"parent_type");
8990 boolean result = type == TskData.ObjectType.IMG.getObjectType()
8991 || type == TskData.ObjectType.VS.getObjectType()
8992 || type == TskData.ObjectType.VOL.getObjectType()
8993 || type == TskData.ObjectType.FS.getObjectType();
8994 if (result ==
true) {
8995 synchronized (rootDirectoryMapLock) {
8997 rootDirectoryMap.put(key, file.
getId());
9000 isRootDirectoryCache.put(file.
getId(), result);
9005 synchronized (rootDirectoryMapLock) {
9006 rootDirectoryMap.put(key, file.
getId());
9008 isRootDirectoryCache.put(file.
getId(),
true);
9013 }
catch (SQLException ex) {
9014 throw new TskCoreException(String.format(
"Failed to lookup parent of file (%s) with id %d", file.
getName(), file.
getId()), ex);
9016 closeResultSet(resultSet);
9017 closeStatement(statement);
9043 long ctime,
long crtime,
long atime,
long mtime,
9044 List<TskFileRange> fileRanges,
9045 Content parent)
throws TskCoreException {
9047 if (null == parent) {
9048 throw new TskCoreException(
"Parent can not be null");
9053 parentPath = ((AbstractFile) parent).getParentPath() + parent.getName() +
'/';
9059 Statement statement = null;
9060 ResultSet resultSet = null;
9063 CaseDbConnection connection = transaction.getConnection();
9079 PreparedStatement prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_FILE);
9080 prepStmt.clearParameters();
9081 prepStmt.setLong(1, newFileId);
9084 Long fileSystemObjectId;
9085 if (0 != parent.getId()) {
9086 fileSystemObjectId = this.getFileSystemId(parent.getId(), connection);
9087 if (fileSystemObjectId != -1) {
9088 prepStmt.setLong(2, fileSystemObjectId);
9090 prepStmt.setNull(2, java.sql.Types.BIGINT);
9091 fileSystemObjectId = null;
9094 prepStmt.setNull(2, java.sql.Types.BIGINT);
9095 fileSystemObjectId = null;
9097 prepStmt.setString(3, fileName);
9099 prepStmt.setShort(5, (
short) 0);
9102 prepStmt.setShort(8, dirFlag.getValue());
9103 prepStmt.setShort(9, metaFlag.getValue());
9105 long savedSize = size < 0 ? 0 : size;
9106 prepStmt.setLong(10, savedSize);
9107 prepStmt.setLong(11, ctime);
9108 prepStmt.setLong(12, crtime);
9109 prepStmt.setLong(13, atime);
9110 prepStmt.setLong(14, mtime);
9111 prepStmt.setNull(15, java.sql.Types.VARCHAR);
9112 prepStmt.setNull(16, java.sql.Types.VARCHAR);
9113 prepStmt.setNull(17, java.sql.Types.VARCHAR);
9116 prepStmt.setNull(19, java.sql.Types.VARCHAR);
9117 prepStmt.setString(20, parentPath);
9118 prepStmt.setLong(21, parent.getDataSource().getId());
9120 prepStmt.setString(22, extractExtension(fileName));
9122 prepStmt.setString(23,
OsAccount.NO_OWNER_ID);
9123 prepStmt.setNull(24, java.sql.Types.BIGINT);
9126 connection.executeUpdate(prepStmt);
9133 prepStmt = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LAYOUT_FILE);
9135 prepStmt.clearParameters();
9136 prepStmt.setLong(1, newFileId);
9137 prepStmt.setLong(2, tskFileRange.getByteStart());
9138 prepStmt.setLong(3, tskFileRange.getByteLen());
9139 prepStmt.setLong(4, tskFileRange.getSequence());
9140 connection.executeUpdate(prepStmt);
9148 parent.getDataSource().getId(),
9155 metaFlag.getValue(),
9157 ctime, crtime, atime, mtime,
9169 }
catch (SQLException ex) {
9170 throw new TskCoreException(
"Failed to add layout file " + fileName +
" to case database", ex);
9172 closeResultSet(resultSet);
9173 closeStatement(statement);
9175 if (null != transaction) {
9178 }
catch (TskCoreException ex2) {
9179 logger.log(Level.SEVERE,
"Failed to rollback transaction after exception", ex2);
9194 private long getDataSourceObjectId(CaseDbConnection connection,
Content content)
throws TskCoreException {
9195 if (content == null) {
9196 throw new TskCoreException(
"Null Content parameter given");
9198 if (content instanceof AbstractFile) {
9199 return ((AbstractFile) content).getDataSourceObjectId();
9201 return getDataSourceObjectId(connection, content.getId());
9217 private long getDataSourceObjectId(CaseDbConnection connection,
long objectId)
throws TskCoreException {
9219 Statement statement = null;
9220 ResultSet resultSet = null;
9222 statement = connection.createStatement();
9223 long dataSourceObjId;
9224 long ancestorId = objectId;
9226 dataSourceObjId = ancestorId;
9227 String query = String.format(
"SELECT par_obj_id FROM tsk_objects WHERE obj_id = %s;", ancestorId);
9228 resultSet = statement.executeQuery(query);
9229 if (resultSet.next()) {
9230 ancestorId = resultSet.getLong(
"par_obj_id");
9232 throw new TskCoreException(String.format(
"tsk_objects table is corrupt, SQL query returned no result: %s", query));
9236 }
while (0 != ancestorId);
9237 return dataSourceObjId;
9238 }
catch (SQLException ex) {
9239 throw new TskCoreException(String.format(
"Error finding root data source for object (obj_id = %d)", objectId), ex);
9241 closeResultSet(resultSet);
9242 closeStatement(statement);
9258 private void addFilePath(CaseDbConnection connection,
long objId, String path, TskData.EncodingType type) throws SQLException {
9259 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_LOCAL_PATH);
9260 statement.clearParameters();
9261 statement.setLong(1, objId);
9262 statement.setString(2, path);
9263 statement.setInt(3, type.getType());
9264 connection.executeUpdate(statement);
9278 private void updateFilePath(CaseDbConnection connection,
long objId, String path, TskData.EncodingType type) throws SQLException {
9279 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_LOCAL_PATH);
9280 statement.clearParameters();
9281 statement.setString(1, path);
9282 statement.setInt(2, type.getType());
9283 statement.setLong(3, objId);
9284 connection.executeUpdate(statement);
9300 public List<AbstractFile>
findFilesInFolder(String fileName, AbstractFile parentFile)
throws TskCoreException {
9302 if (!containsLikeWildcard(fileName)) {
9306 CaseDbConnection connection = null;
9307 ResultSet rs = null;
9308 long parentId = parentFile.getId();
9312 connection = connections.getConnection();
9314 PreparedStatement statement;
9315 if (ext.isEmpty()) {
9316 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_PARENT_AND_NAME);
9317 statement.clearParameters();
9318 statement.setLong(1, parentId);
9319 statement.setString(2, fileName);
9321 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_FILES_BY_EXTENSION_AND_PARENT_AND_NAME);
9322 statement.clearParameters();
9323 statement.setString(1, ext);
9324 statement.setLong(2, parentId);
9325 statement.setString(3, fileName);
9328 rs = connection.executeQuery(statement);
9329 return resultSetToAbstractFiles(rs, connection);
9330 }
catch (SQLException ex) {
9331 throw new TskCoreException(
"Error getting AbstractFile children with name=" + fileName +
" for Content parent with ID=" + parentFile.getId(), ex);
9334 closeConnection(connection);
9351 CaseDbConnection connection = null;
9353 ResultSet rs = null;
9356 connection = connections.getConnection();
9357 s = connection.createStatement();
9358 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files WHERE " + sqlWhereClause);
9360 return rs.getLong(
"count");
9361 }
catch (SQLException e) {
9362 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.countFilesWhere().", e);
9366 closeConnection(connection);
9389 CaseDbConnection connection = null;
9391 ResultSet rs = null;
9394 connection = connections.getConnection();
9395 s = connection.createStatement();
9396 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE " + sqlWhereClause);
9397 return resultSetToAbstractFiles(rs, connection);
9398 }
catch (SQLException e) {
9399 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findAllFilesWhere(): " + sqlWhereClause, e);
9403 closeConnection(connection);
9427 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";
9429 try (CaseDbConnection connection = connections.getConnection()) {
9430 String query = String.format(queryTemplate, parentId, sqlWhereClause);
9431 try (Statement s = connection.createStatement(); ResultSet rs = connection.executeQuery(s, query)) {
9432 return resultSetToAbstractFiles(rs, connection);
9433 }
catch (SQLException ex) {
9434 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findAllFilesInFolderWhere(): " + query, ex);
9454 CaseDbConnection connection = null;
9456 ResultSet rs = null;
9459 connection = connections.getConnection();
9460 s = connection.createStatement();
9461 rs = connection.executeQuery(s,
"SELECT obj_id FROM tsk_files WHERE " + sqlWhereClause);
9462 List<Long> ret =
new ArrayList<>();
9464 ret.add(rs.getLong(
"obj_id"));
9467 }
catch (SQLException e) {
9468 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findAllFileIdsWhere(): " + sqlWhereClause, e);
9472 closeConnection(connection);
9488 public List<AbstractFile>
openFiles(
Content dataSource, String filePath)
throws TskCoreException {
9492 String path = AbstractFile.createNonUniquePath(filePath).toLowerCase();
9495 int lastSlash = path.lastIndexOf(
'/');
9498 if (lastSlash == path.length()) {
9499 path = path.substring(0, lastSlash - 1);
9500 lastSlash = path.lastIndexOf(
'/');
9503 String parentPath = path.substring(0, lastSlash);
9504 String fileName = path.substring(lastSlash);
9506 return findFiles(dataSource, fileName, parentPath);
9520 CaseDbConnection connection = null;
9522 ResultSet rs = null;
9525 connection = connections.getConnection();
9526 s = connection.createStatement();
9527 rs = connection.executeQuery(s,
"SELECT * FROM tsk_file_layout WHERE obj_id = " +
id +
" ORDER BY sequence");
9528 List<TskFileRange> ranges =
new ArrayList<TskFileRange>();
9531 rs.getLong(
"byte_len"), rs.getLong(
"sequence"));
9535 }
catch (SQLException ex) {
9536 throw new TskCoreException(
"Error getting TskFileLayoutRanges by id, id = " +
id, ex);
9540 closeConnection(connection);
9556 CaseDbConnection connection = null;
9558 ResultSet rs = null;
9561 connection = connections.getConnection();
9562 s = connection.createStatement();
9563 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 "
9564 +
"FROM tsk_image_info "
9565 +
"INNER JOIN data_source_info ON tsk_image_info.obj_id = data_source_info.obj_id "
9566 +
"LEFT JOIN tsk_image_names ON tsk_image_names.obj_id = data_source_info.obj_id "
9567 +
"WHERE tsk_image_info.obj_id = " +
id);
9569 List<String> imagePaths =
new ArrayList<>();
9570 long type, ssize, size;
9571 String tzone, md5, sha1, sha256, name, device_id, imagePath;
9574 imagePath = rs.getString(
"name");
9575 if (imagePath != null) {
9576 imagePaths.add(imagePath);
9578 type = rs.getLong(
"type");
9579 ssize = rs.getLong(
"ssize");
9580 tzone = rs.getString(
"tzone");
9581 size = rs.getLong(
"size");
9582 md5 = rs.getString(
"md5");
9583 sha1 = rs.getString(
"sha1");
9584 sha256 = rs.getString(
"sha256");
9585 name = rs.getString(
"display_name");
9587 if (imagePaths.size() > 0) {
9588 String path = imagePaths.get(0);
9589 name = (
new java.io.File(path)).getName();
9594 device_id = rs.getString(
"device_id");
9596 throw new TskCoreException(
"No image found for id: " +
id);
9601 imagePath = rs.getString(
"name");
9602 if (imagePath != null) {
9603 imagePaths.add(imagePath);
9607 return new Image(
this,
id, type, device_id, ssize, name,
9608 imagePaths.toArray(
new String[imagePaths.size()]), tzone, md5, sha1, sha256, size);
9609 }
catch (SQLException ex) {
9610 throw new TskCoreException(
"Error getting Image by id, id = " +
id, ex);
9614 closeConnection(connection);
9631 CaseDbConnection connection = null;
9633 ResultSet rs = null;
9636 connection = connections.getConnection();
9637 s = connection.createStatement();
9638 rs = connection.executeQuery(s,
"SELECT * FROM tsk_vs_info "
9639 +
"where obj_id = " +
id);
9641 long type = rs.getLong(
"vs_type");
9642 long imgOffset = rs.getLong(
"img_offset");
9643 long blockSize = rs.getLong(
"block_size");
9645 vs.setParent(parent);
9648 throw new TskCoreException(
"No volume system found for id:" +
id);
9650 }
catch (SQLException ex) {
9651 throw new TskCoreException(
"Error getting Volume System by ID.", ex);
9655 closeConnection(connection);
9668 VolumeSystem getVolumeSystemById(
long id,
long parentId)
throws TskCoreException {
9669 VolumeSystem vs = getVolumeSystemById(
id, null);
9670 vs.setParentId(parentId);
9685 FileSystem getFileSystemById(
long id, Image parent)
throws TskCoreException {
9686 return getFileSystemByIdHelper(
id, parent);
9697 FileSystem getFileSystemById(
long id,
long parentId)
throws TskCoreException {
9699 FileSystem fs = getFileSystemById(
id, vol);
9700 fs.setParentId(parentId);
9715 FileSystem getFileSystemById(
long id, Volume parent)
throws TskCoreException {
9716 return getFileSystemByIdHelper(
id, parent);
9730 Pool getPoolById(
long id, Content parent)
throws TskCoreException {
9731 return getPoolByIdHelper(
id, parent);
9742 Pool getPoolById(
long id,
long parentId)
throws TskCoreException {
9743 Pool pool = getPoolById(
id, null);
9744 pool.setParentId(parentId);
9759 private Pool getPoolByIdHelper(
long id, Content parent)
throws TskCoreException {
9762 try (CaseDbConnection connection = connections.getConnection();
9763 Statement s = connection.createStatement();
9764 ResultSet rs = connection.executeQuery(s,
"SELECT * FROM tsk_pool_info "
9765 +
"where obj_id = " +
id);) {
9767 Pool pool =
new Pool(
this, rs.getLong(
"obj_id"), TskData.TSK_POOL_TYPE_ENUM.valueOf(rs.getLong(
"pool_type")).getName(), rs.getLong(
"pool_type"));
9768 pool.setParent(parent);
9772 throw new TskCoreException(
"No pool found for ID:" +
id);
9774 }
catch (SQLException ex) {
9775 throw new TskCoreException(
"Error getting Pool by ID", ex);
9792 private FileSystem getFileSystemByIdHelper(
long id, Content parent)
throws TskCoreException {
9796 synchronized (fileSystemIdMap) {
9797 if (fileSystemIdMap.containsKey(
id)) {
9798 return fileSystemIdMap.get(
id);
9801 CaseDbConnection connection = null;
9803 ResultSet rs = null;
9806 connection = connections.getConnection();
9807 s = connection.createStatement();
9808 rs = connection.executeQuery(s,
"SELECT * FROM tsk_fs_info "
9809 +
"where obj_id = " +
id);
9811 TskData.TSK_FS_TYPE_ENUM fsType = TskData.TSK_FS_TYPE_ENUM.valueOf(rs.getInt(
"fs_type"));
9812 FileSystem fs =
new FileSystem(
this, rs.getLong(
"obj_id"),
"", rs.getLong(
"img_offset"),
9813 fsType, rs.getLong(
"block_size"), rs.getLong(
"block_count"),
9814 rs.getLong(
"root_inum"), rs.getLong(
"first_inum"), rs.getLong(
"last_inum"));
9815 fs.setParent(parent);
9817 synchronized (fileSystemIdMap) {
9818 fileSystemIdMap.put(
id, fs);
9822 throw new TskCoreException(
"No file system found for id:" +
id);
9824 }
catch (SQLException ex) {
9825 throw new TskCoreException(
"Error getting File System by ID", ex);
9829 closeConnection(connection);
9845 Volume getVolumeById(
long id, VolumeSystem parent)
throws TskCoreException {
9846 CaseDbConnection connection = null;
9848 ResultSet rs = null;
9851 connection = connections.getConnection();
9852 s = connection.createStatement();
9853 rs = connection.executeQuery(s,
"SELECT * FROM tsk_vs_parts "
9854 +
"where obj_id = " +
id);
9865 description = rs.getString(
"desc");
9866 }
catch (Exception ex) {
9867 description = rs.getString(
"descr");
9869 Volume vol =
new Volume(
this, rs.getLong(
"obj_id"), rs.getLong(
"addr"),
9870 rs.getLong(
"start"), rs.getLong(
"length"), rs.getLong(
"flags"),
9872 vol.setParent(parent);
9875 throw new TskCoreException(
"No volume found for id:" +
id);
9877 }
catch (SQLException ex) {
9878 throw new TskCoreException(
"Error getting Volume by ID", ex);
9882 closeConnection(connection);
9895 Volume getVolumeById(
long id,
long parentId)
throws TskCoreException {
9896 Volume vol = getVolumeById(
id, null);
9897 vol.setParentId(parentId);
9912 Directory getDirectoryById(
long id, FileSystem parentFs)
throws TskCoreException {
9913 CaseDbConnection connection = null;
9915 ResultSet rs = null;
9918 connection = connections.getConnection();
9919 s = connection.createStatement();
9920 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files "
9921 +
"WHERE obj_id = " +
id);
9922 Directory temp = null;
9924 final short type = rs.getShort(
"type");
9925 if (type == TSK_DB_FILES_TYPE_ENUM.FS.getFileType()) {
9926 if (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()
9927 || rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue()) {
9928 temp = directory(rs, parentFs);
9930 }
else if (type == TSK_DB_FILES_TYPE_ENUM.VIRTUAL_DIR.getFileType()) {
9931 throw new TskCoreException(
"Expecting an FS-type directory, got virtual, id: " +
id);
9934 throw new TskCoreException(
"No Directory found for id:" +
id);
9937 }
catch (SQLException ex) {
9938 throw new TskCoreException(
"Error getting Directory by ID", ex);
9942 closeConnection(connection);
9957 List<FileSystem> fileSystems =
new ArrayList<>();
9958 String queryStr =
"SELECT * FROM tsk_fs_info WHERE data_source_obj_id = " + image.getId();
9960 CaseDbConnection connection = null;
9962 ResultSet rs = null;
9965 connection = connections.getConnection();
9966 s = connection.createStatement();
9967 rs = connection.executeQuery(s, queryStr);
9971 fsType, rs.getLong(
"block_size"), rs.getLong(
"block_count"),
9972 rs.getLong(
"root_inum"), rs.getLong(
"first_inum"), rs.getLong(
"last_inum"));
9974 fileSystems.add(fs);
9976 }
catch (SQLException ex) {
9977 throw new TskCoreException(
"Error looking up files systems. Query: " + queryStr, ex);
9981 closeConnection(connection);
9997 List<Content> getImageChildren(
Image img)
throws TskCoreException {
9998 Collection<ObjectInfo> childInfos = getChildrenInfo(img);
9999 List<Content> children =
new ArrayList<Content>();
10000 for (ObjectInfo info : childInfos) {
10001 if (null != info.type) {
10002 switch (info.type) {
10004 children.add(getVolumeSystemById(info.id, img));
10007 children.add(getPoolById(info.id, img));
10010 children.add(getFileSystemById(info.id, img));
10028 throw new TskCoreException(
"Image has child of invalid type: " + info.type);
10045 List<Long> getImageChildrenIds(Image img)
throws TskCoreException {
10046 Collection<ObjectInfo> childInfos = getChildrenInfo(img);
10047 List<Long> children =
new ArrayList<Long>();
10048 for (ObjectInfo info : childInfos) {
10049 if (info.type == ObjectType.VS
10050 || info.type == ObjectType.POOL
10051 || info.type == ObjectType.FS
10052 || info.type == ObjectType.ABSTRACTFILE
10053 || info.type == ObjectType.ARTIFACT) {
10054 children.add(info.id);
10055 }
else if (info.type == ObjectType.REPORT) {
10058 throw new TskCoreException(
"Image has child of invalid type: " + info.type);
10074 List<Content> getPoolChildren(Pool pool)
throws TskCoreException {
10075 Collection<ObjectInfo> childInfos = getChildrenInfo(pool);
10076 List<Content> children =
new ArrayList<Content>();
10077 for (ObjectInfo info : childInfos) {
10078 if (null != info.type) {
10079 switch (info.type) {
10081 children.add(getVolumeSystemById(info.id, pool));
10096 throw new TskCoreException(
"Pool has child of invalid type: " + info.type);
10113 List<Long> getPoolChildrenIds(Pool pool)
throws TskCoreException {
10114 Collection<ObjectInfo> childInfos = getChildrenInfo(pool);
10115 List<Long> children =
new ArrayList<Long>();
10116 for (ObjectInfo info : childInfos) {
10117 if (info.type == ObjectType.VS || info.type == ObjectType.ABSTRACTFILE || info.type == ObjectType.ARTIFACT) {
10118 children.add(info.id);
10120 throw new TskCoreException(
"Pool has child of invalid type: " + info.type);
10136 List<Content> getVolumeSystemChildren(VolumeSystem vs)
throws TskCoreException {
10137 Collection<ObjectInfo> childInfos = getChildrenInfo(vs);
10138 List<Content> children =
new ArrayList<Content>();
10139 for (ObjectInfo info : childInfos) {
10140 if (null != info.type) {
10141 switch (info.type) {
10143 children.add(getVolumeById(info.id, vs));
10158 throw new TskCoreException(
"VolumeSystem has child of invalid type: " + info.type);
10175 List<Long> getVolumeSystemChildrenIds(VolumeSystem vs)
throws TskCoreException {
10176 Collection<ObjectInfo> childInfos = getChildrenInfo(vs);
10177 List<Long> children =
new ArrayList<Long>();
10178 for (ObjectInfo info : childInfos) {
10179 if (info.type == ObjectType.VOL || info.type == ObjectType.ABSTRACTFILE || info.type == ObjectType.ARTIFACT) {
10180 children.add(info.id);
10182 throw new TskCoreException(
"VolumeSystem has child of invalid type: " + info.type);
10198 List<Content> getVolumeChildren(Volume vol)
throws TskCoreException {
10199 Collection<ObjectInfo> childInfos = getChildrenInfo(vol);
10200 List<Content> children =
new ArrayList<Content>();
10201 for (ObjectInfo info : childInfos) {
10202 if (null != info.type) {
10203 switch (info.type) {
10205 children.add(getPoolById(info.id, vol));
10208 children.add(getFileSystemById(info.id, vol));
10223 throw new TskCoreException(
"Volume has child of invalid type: " + info.type);
10240 List<Long> getVolumeChildrenIds(Volume vol)
throws TskCoreException {
10241 final Collection<ObjectInfo> childInfos = getChildrenInfo(vol);
10242 final List<Long> children =
new ArrayList<Long>();
10243 for (ObjectInfo info : childInfos) {
10244 if (info.type == ObjectType.FS || info.type == ObjectType.ABSTRACTFILE || info.type == ObjectType.ARTIFACT) {
10245 children.add(info.id);
10247 throw new TskCoreException(
"Volume has child of invalid type: " + info.type);
10266 public Image addImageInfo(
long deviceObjId, List<String> imageFilePaths, String timeZone)
throws TskCoreException {
10267 return addImageInfo(deviceObjId, imageFilePaths, timeZone, null);
10284 public Image addImageInfo(
long deviceObjId, List<String> imageFilePaths, String timeZone,
Host host)
throws TskCoreException {
10285 return addImageInfo(deviceObjId, imageFilePaths, timeZone, host, null);
10305 public Image addImageInfo(
long deviceObjId, List<String> imageFilePaths, String timeZone,
Host host, String password)
throws TskCoreException {
10306 long imageId = this.caseHandle.addImageInfo(deviceObjId, imageFilePaths, timeZone, host, password,
this);
10320 CaseDbConnection connection = null;
10321 Statement s1 = null;
10322 ResultSet rs1 = null;
10325 connection = connections.getConnection();
10326 s1 = connection.createStatement();
10327 rs1 = connection.executeQuery(s1,
"SELECT tsk_image_info.obj_id, tsk_image_names.name FROM tsk_image_info "
10328 +
"LEFT JOIN tsk_image_names ON tsk_image_info.obj_id = tsk_image_names.obj_id");
10329 Map<Long, List<String>> imgPaths =
new LinkedHashMap<Long, List<String>>();
10330 while (rs1.next()) {
10331 long obj_id = rs1.getLong(
"obj_id");
10332 String name = rs1.getString(
"name");
10333 List<String> imagePaths = imgPaths.get(obj_id);
10334 if (imagePaths == null) {
10335 List<String> paths =
new ArrayList<String>();
10336 if (name != null) {
10339 imgPaths.put(obj_id, paths);
10341 if (name != null) {
10342 imagePaths.add(name);
10347 }
catch (SQLException ex) {
10348 throw new TskCoreException(
"Error getting image paths.", ex);
10350 closeResultSet(rs1);
10351 closeStatement(s1);
10352 closeConnection(connection);
10368 private List<String> getImagePathsById(
long objectId, CaseDbConnection connection)
throws TskCoreException {
10369 List<String> imagePaths =
new ArrayList<>();
10371 Statement statement = null;
10372 ResultSet resultSet = null;
10374 statement = connection.createStatement();
10375 resultSet = connection.executeQuery(statement,
"SELECT name FROM tsk_image_names WHERE tsk_image_names.obj_id = " + objectId);
10376 while (resultSet.next()) {
10377 imagePaths.add(resultSet.getString(
"name"));
10379 }
catch (SQLException ex) {
10380 throw new TskCoreException(String.format(
"Error getting image names with obj_id = %d", objectId), ex);
10382 closeResultSet(resultSet);
10383 closeStatement(statement);
10397 CaseDbConnection connection = null;
10398 Statement s = null;
10399 ResultSet rs = null;
10402 connection = connections.getConnection();
10403 s = connection.createStatement();
10404 rs = connection.executeQuery(s,
"SELECT obj_id FROM tsk_image_info");
10405 Collection<Long> imageIDs =
new ArrayList<Long>();
10406 while (rs.next()) {
10407 imageIDs.add(rs.getLong(
"obj_id"));
10409 List<Image> images =
new ArrayList<Image>();
10410 for (
long id : imageIDs) {
10414 }
catch (SQLException ex) {
10415 throw new TskCoreException(
"Error retrieving images.", ex);
10417 closeResultSet(rs);
10419 closeConnection(connection);
10434 public void setImagePaths(
long obj_id, List<String> paths)
throws TskCoreException {
10439 transaction = null;
10441 if (transaction != null) {
10461 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.DELETE_IMAGE_NAME);
10462 statement.clearParameters();
10463 statement.setLong(1, objId);
10464 trans.getConnection().executeUpdate(statement);
10465 for (
int i = 0; i < paths.size(); i++) {
10466 statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.INSERT_IMAGE_NAME);
10467 statement.clearParameters();
10468 statement.setLong(1, objId);
10469 statement.setString(2, paths.get(i));
10470 statement.setLong(3, i);
10471 trans.getConnection().executeUpdate(statement);
10473 }
catch (SQLException ex) {
10474 throw new TskCoreException(
"Error updating image paths.", ex);
10490 void deleteDataSource(
long dataSourceObjectId)
throws TskCoreException {
10496 Host hostToDelete = null;
10500 if (major > 9 || (major == 9 && minor >= 1)) {
10502 if (
getHostManager().getDataSourcesForHost(hostToDelete).size() != 1) {
10503 hostToDelete = null;
10507 CaseDbConnection connection = null;
10508 Statement statement;
10511 connection = connections.getConnection();
10512 statement = connection.createStatement();
10513 connection.beginTransaction();
10516 statement.execute(
"DELETE FROM tsk_objects WHERE obj_id = " + dataSourceObjectId);
10519 String accountSql =
"DELETE FROM accounts WHERE account_id in (SELECT account_id FROM accounts "
10520 +
"WHERE account_id NOT IN (SELECT account1_id FROM account_relationships) "
10521 +
"AND account_id NOT IN (SELECT account2_id FROM account_relationships))";
10522 statement.execute(accountSql);
10526 if (hostToDelete != null) {
10527 statement.execute(
"DELETE FROM tsk_hosts WHERE id = " + hostToDelete.
getHostId());
10530 String deleteOsAcctObjectsQuery =
"DELETE FROM tsk_objects "
10531 +
"WHERE type=" + TskData.ObjectType.OS_ACCOUNT.getObjectType() +
" "
10532 +
"AND obj_id NOT IN (SELECT os_account_obj_id FROM tsk_os_accounts WHERE os_account_obj_id IS NOT NULL)";
10533 statement.execute(deleteOsAcctObjectsQuery);
10536 connection.commitTransaction();
10537 }
catch (SQLException ex) {
10538 rollbackTransaction(connection);
10539 throw new TskCoreException(
"Error deleting data source.", ex);
10541 closeConnection(connection);
10571 List<AbstractFile> resultSetToAbstractFiles(ResultSet rs, CaseDbConnection connection)
throws SQLException {
10572 ArrayList<AbstractFile> results =
new ArrayList<AbstractFile>();
10574 while (rs.next()) {
10575 final short type = rs.getShort(
"type");
10576 if (type == TSK_DB_FILES_TYPE_ENUM.FS.getFileType()
10577 && (rs.getShort(
"meta_type") != TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue())) {
10579 if (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()) {
10580 result = directory(rs, null);
10582 result = file(rs, null);
10584 results.add(result);
10585 }
else if (type == TSK_DB_FILES_TYPE_ENUM.VIRTUAL_DIR.getFileType()
10586 || (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue())) {
10587 final VirtualDirectory virtDir = virtualDirectory(rs, connection);
10588 results.add(virtDir);
10589 }
else if (type == TSK_DB_FILES_TYPE_ENUM.LOCAL_DIR.getFileType()) {
10590 final LocalDirectory localDir = localDirectory(rs);
10591 results.add(localDir);
10592 }
else if (type == TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS.getFileType()
10593 || type == TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS.getFileType()
10594 || type == TSK_DB_FILES_TYPE_ENUM.CARVED.getFileType()
10595 || type == TSK_DB_FILES_TYPE_ENUM.LAYOUT_FILE.getFileType()) {
10596 TSK_DB_FILES_TYPE_ENUM atype = TSK_DB_FILES_TYPE_ENUM.valueOf(type);
10597 String parentPath = rs.getString(
"parent_path");
10598 if (parentPath == null) {
10602 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10603 if (rs.wasNull()) {
10604 osAccountObjId = null;
10607 LayoutFile lf =
new LayoutFile(
this,
10608 rs.getLong(
"obj_id"),
10609 rs.getLong(
"data_source_obj_id"),
10610 rs.getLong(
"fs_obj_id"),
10611 rs.getString(
"name"),
10613 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")), TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10614 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
10615 rs.getLong(
"size"),
10616 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10617 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10618 FileKnown.valueOf(rs.getByte(
"known")), parentPath,
10619 rs.getString(
"mime_type"),
10620 rs.getString(
"owner_uid"), osAccountObjId);
10622 }
else if (type == TSK_DB_FILES_TYPE_ENUM.DERIVED.getFileType()) {
10623 final DerivedFile df;
10624 df = derivedFile(rs, connection, AbstractContent.UNKNOWN_ID);
10626 }
else if (type == TSK_DB_FILES_TYPE_ENUM.LOCAL.getFileType()) {
10627 final LocalFile lf;
10628 lf = localFile(rs, connection, AbstractContent.UNKNOWN_ID);
10630 }
else if (type == TSK_DB_FILES_TYPE_ENUM.SLACK.getFileType()) {
10631 final SlackFile sf = slackFile(rs, null);
10635 }
catch (SQLException e) {
10636 logger.log(Level.SEVERE,
"Error getting abstract files from result set", e);
10655 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10656 if (rs.wasNull()) {
10657 osAccountObjId = null;
10661 rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
10662 TskData.TSK_FS_ATTR_TYPE_ENUM.valueOf(rs.getShort(
"attr_type")),
10663 rs.getInt(
"attr_id"), rs.getString(
"name"), rs.getLong(
"meta_addr"), rs.getInt(
"meta_seq"),
10664 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10665 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10666 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10667 rs.getShort(
"meta_flags"), rs.getLong(
"size"),
10668 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10669 (short) rs.getInt(
"mode"), rs.getInt(
"uid"), rs.getInt(
"gid"),
10670 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10671 FileKnown.valueOf(rs.getByte(
"known")),
10672 rs.getString(
"parent_path"), rs.getString(
"mime_type"), rs.getString(
"extension"), rs.getString(
"owner_uid"),
10673 osAccountObjId, TskData.CollectedStatus.valueOf(rs.getInt(
"collected")), Collections.emptyList());
10674 f.setFileSystem(fs);
10689 Directory directory(ResultSet rs, FileSystem fs)
throws SQLException {
10690 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10691 if (rs.wasNull()) {
10692 osAccountObjId = null;
10695 Directory dir =
new Directory(
this, rs.getLong(
"obj_id"), rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
10696 TskData.TSK_FS_ATTR_TYPE_ENUM.valueOf(rs.getShort(
"attr_type")),
10697 rs.getInt(
"attr_id"), rs.getString(
"name"), rs.getLong(
"meta_addr"), rs.getInt(
"meta_seq"),
10698 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10699 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10700 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10701 rs.getShort(
"meta_flags"), rs.getLong(
"size"),
10702 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10703 rs.getShort(
"mode"), rs.getInt(
"uid"), rs.getInt(
"gid"),
10704 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10705 FileKnown.valueOf(rs.getByte(
"known")),
10706 rs.getString(
"parent_path"), rs.getString(
"owner_uid"), osAccountObjId);
10707 dir.setFileSystem(fs);
10721 VirtualDirectory virtualDirectory(ResultSet rs, CaseDbConnection connection)
throws SQLException {
10722 String parentPath = rs.getString(
"parent_path");
10723 if (parentPath == null) {
10727 long objId = rs.getLong(
"obj_id");
10728 long dsObjId = rs.getLong(
"data_source_obj_id");
10729 if (objId == dsObjId) {
10731 String deviceId =
"";
10732 String timeZone =
"";
10733 Statement s = null;
10734 ResultSet rsDataSourceInfo = null;
10738 s = connection.createStatement();
10739 rsDataSourceInfo = connection.executeQuery(s,
"SELECT device_id, time_zone FROM data_source_info WHERE obj_id = " + objId);
10740 if (rsDataSourceInfo.next()) {
10741 deviceId = rsDataSourceInfo.getString(
"device_id");
10742 timeZone = rsDataSourceInfo.getString(
"time_zone");
10744 }
catch (SQLException ex) {
10745 logger.log(Level.SEVERE,
"Error data source info for datasource id " + objId, ex);
10747 closeResultSet(rsDataSourceInfo);
10752 return new LocalFilesDataSource(
this,
10755 rs.getString(
"name"),
10756 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10757 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10758 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10759 rs.getShort(
"meta_flags"),
10761 rs.getString(
"md5"),
10762 rs.getString(
"sha256"),
10763 rs.getString(
"sha1"),
10764 FileKnown.valueOf(rs.getByte(
"known")),
10767 final VirtualDirectory vd =
new VirtualDirectory(
this,
10769 rs.getLong(
"fs_obj_id"),
10770 rs.getString(
"name"),
10771 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10772 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10773 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10774 rs.getShort(
"meta_flags"), rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10775 FileKnown.valueOf(rs.getByte(
"known")), parentPath);
10789 LocalDirectory localDirectory(ResultSet rs)
throws SQLException {
10790 String parentPath = rs.getString(
"parent_path");
10791 if (parentPath == null) {
10794 final LocalDirectory ld =
new LocalDirectory(
this, rs.getLong(
"obj_id"),
10795 rs.getLong(
"data_source_obj_id"), rs.getString(
"name"),
10796 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10797 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10798 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10799 rs.getShort(
"meta_flags"), rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10800 FileKnown.valueOf(rs.getByte(
"known")), parentPath);
10817 private DerivedFile derivedFile(ResultSet rs, CaseDbConnection connection,
long parentId)
throws SQLException {
10818 boolean hasLocalPath = rs.getBoolean(
"has_path");
10819 long objId = rs.getLong(
"obj_id");
10820 String localPath = null;
10821 TskData.EncodingType encodingType = TskData.EncodingType.NONE;
10822 if (hasLocalPath) {
10823 ResultSet rsFilePath = null;
10826 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_LOCAL_PATH_AND_ENCODING_FOR_FILE);
10827 statement.clearParameters();
10828 statement.setLong(1, objId);
10829 rsFilePath = connection.executeQuery(statement);
10830 if (rsFilePath.next()) {
10831 localPath = rsFilePath.getString(
"path");
10832 encodingType = TskData.EncodingType.valueOf(rsFilePath.getInt(
"encoding_type"));
10834 }
catch (SQLException ex) {
10835 logger.log(Level.SEVERE,
"Error getting encoding type for file " + objId, ex);
10837 closeResultSet(rsFilePath);
10841 String parentPath = rs.getString(
"parent_path");
10842 if (parentPath == null) {
10846 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10847 if (rs.wasNull()) {
10848 osAccountObjId = null;
10851 final DerivedFile df =
new DerivedFile(
this, objId, rs.getLong(
"data_source_obj_id"),
10852 rs.getLong(
"fs_obj_id"),
10853 rs.getString(
"name"),
10854 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10855 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10856 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
10857 rs.getLong(
"size"),
10858 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10859 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10860 FileKnown.valueOf(rs.getByte(
"known")),
10861 parentPath, localPath, parentId, rs.getString(
"mime_type"),
10862 encodingType, rs.getString(
"extension"),
10863 rs.getString(
"owner_uid"), osAccountObjId);
10880 private LocalFile localFile(ResultSet rs, CaseDbConnection connection,
long parentId)
throws SQLException {
10881 long objId = rs.getLong(
"obj_id");
10882 String localPath = null;
10883 TskData.EncodingType encodingType = TskData.EncodingType.NONE;
10884 if (rs.getBoolean(
"has_path")) {
10885 ResultSet rsFilePath = null;
10888 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_LOCAL_PATH_AND_ENCODING_FOR_FILE);
10889 statement.clearParameters();
10890 statement.setLong(1, objId);
10891 rsFilePath = connection.executeQuery(statement);
10892 if (rsFilePath.next()) {
10893 localPath = rsFilePath.getString(
"path");
10894 encodingType = TskData.EncodingType.valueOf(rsFilePath.getInt(
"encoding_type"));
10896 }
catch (SQLException ex) {
10897 logger.log(Level.SEVERE,
"Error getting encoding type for file " + objId, ex);
10899 closeResultSet(rsFilePath);
10903 String parentPath = rs.getString(
"parent_path");
10904 if (null == parentPath) {
10907 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10908 if (rs.wasNull()) {
10909 osAccountObjId = null;
10912 LocalFile file =
new LocalFile(
this, objId, rs.getString(
"name"),
10913 TSK_DB_FILES_TYPE_ENUM.valueOf(rs.getShort(
"type")),
10914 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10915 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10916 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
10917 rs.getLong(
"size"),
10918 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10919 rs.getString(
"mime_type"), rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10920 FileKnown.valueOf(rs.getByte(
"known")),
10921 parentId, parentPath, rs.getLong(
"data_source_obj_id"),
10922 localPath, encodingType, rs.getString(
"extension"),
10923 rs.getString(
"owner_uid"), osAccountObjId);
10939 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
10940 if (rs.wasNull()) {
10941 osAccountObjId = null;
10944 rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
10945 TskData.TSK_FS_ATTR_TYPE_ENUM.valueOf(rs.getShort(
"attr_type")),
10946 rs.getInt(
"attr_id"), rs.getString(
"name"), rs.getLong(
"meta_addr"), rs.getInt(
"meta_seq"),
10947 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
10948 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
10949 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")),
10950 rs.getShort(
"meta_flags"), rs.getLong(
"size"),
10951 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
10952 (short) rs.getInt(
"mode"), rs.getInt(
"uid"), rs.getInt(
"gid"),
10953 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
10954 FileKnown.valueOf(rs.getByte(
"known")),
10955 rs.getString(
"parent_path"), rs.getString(
"mime_type"), rs.getString(
"extension"),
10956 rs.getString(
"owner_uid"), osAccountObjId);
10957 f.setFileSystem(fs);
10972 List<Content> fileChildren(ResultSet rs, CaseDbConnection connection,
long parentId)
throws SQLException {
10973 List<Content> children =
new ArrayList<Content>();
10975 while (rs.next()) {
10976 TskData.TSK_DB_FILES_TYPE_ENUM type = TskData.TSK_DB_FILES_TYPE_ENUM.valueOf(rs.getShort(
"type"));
10978 if (null != type) {
10981 if (rs.getShort(
"meta_type") != TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_VIRT_DIR.getValue()) {
10983 if (rs.getShort(
"meta_type") == TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()) {
10984 result = directory(rs, null);
10986 result = file(rs, null);
10988 children.add(result);
10990 VirtualDirectory virtDir = virtualDirectory(rs, connection);
10991 children.add(virtDir);
10995 VirtualDirectory virtDir = virtualDirectory(rs, connection);
10996 children.add(virtDir);
10999 LocalDirectory localDir = localDirectory(rs);
11000 children.add(localDir);
11002 case UNALLOC_BLOCKS:
11003 case UNUSED_BLOCKS:
11005 case LAYOUT_FILE: {
11006 String parentPath = rs.getString(
"parent_path");
11007 if (parentPath == null) {
11010 Long osAccountObjId = rs.getLong(
"os_account_obj_id");
11011 if (rs.wasNull()) {
11012 osAccountObjId = null;
11014 final LayoutFile lf =
new LayoutFile(
this, rs.getLong(
"obj_id"),
11015 rs.getLong(
"data_source_obj_id"), rs.getLong(
"fs_obj_id"),
11016 rs.getString(
"name"), type,
11017 TSK_FS_NAME_TYPE_ENUM.valueOf(rs.getShort(
"dir_type")),
11018 TSK_FS_META_TYPE_ENUM.valueOf(rs.getShort(
"meta_type")),
11019 TSK_FS_NAME_FLAG_ENUM.valueOf(rs.getShort(
"dir_flags")), rs.getShort(
"meta_flags"),
11020 rs.getLong(
"size"),
11021 rs.getLong(
"ctime"), rs.getLong(
"crtime"), rs.getLong(
"atime"), rs.getLong(
"mtime"),
11022 rs.getString(
"md5"), rs.getString(
"sha256"), rs.getString(
"sha1"),
11023 FileKnown.valueOf(rs.getByte(
"known")), parentPath, rs.getString(
"mime_type"),
11024 rs.getString(
"owner_uid"), osAccountObjId);
11029 final DerivedFile df = derivedFile(rs, connection, parentId);
11033 final LocalFile lf = localFile(rs, connection, parentId);
11038 final SlackFile sf = slackFile(rs, null);
11107 CaseDbConnection getConnection() throws TskCoreException {
11108 return connections.getConnection();
11118 String getCaseHandleIdentifier() {
11119 return caseHandleIdentifier;
11122 @SuppressWarnings(
"deprecation")
11139 connections.close();
11140 }
catch (TskCoreException ex) {
11141 logger.log(Level.SEVERE,
"Error closing database connection pool.", ex);
11144 fileSystemIdMap.clear();
11147 if (this.caseHandle != null) {
11148 this.caseHandle.free();
11149 this.caseHandle = null;
11151 }
catch (TskCoreException ex) {
11152 logger.log(Level.SEVERE,
"Error freeing case handle.", ex);
11157 if (this.lockResources != null) {
11159 this.lockResources.close();
11160 }
catch (Exception ex) {
11161 logger.log(Level.SEVERE,
"Error closing lock resources.", ex);
11179 long id = file.getId();
11180 FileKnown currentKnown = file.getKnown();
11181 if (currentKnown.compareTo(fileKnown) > 0) {
11185 try (CaseDbConnection connection = connections.getConnection();
11186 Statement statement = connection.createStatement();) {
11187 connection.executeUpdate(statement,
"UPDATE tsk_files "
11188 +
"SET known='" + fileKnown.getFileKnownValue() +
"' "
11189 +
"WHERE obj_id=" + id);
11191 file.setKnown(fileKnown);
11192 }
catch (SQLException ex) {
11193 throw new TskCoreException(
"Error setting Known status.", ex);
11208 void setFileName(String name,
long objId)
throws TskCoreException {
11210 try (CaseDbConnection connection = connections.getConnection();) {
11212 preparedStatement.clearParameters();
11213 preparedStatement.setString(1, name);
11214 preparedStatement.setLong(2, objId);
11215 connection.executeUpdate(preparedStatement);
11216 }
catch (SQLException ex) {
11217 throw new TskCoreException(String.format(
"Error updating while the name for object ID %d to %s", objId, name), ex);
11231 void setImageName(String name,
long objId)
throws TskCoreException {
11233 try (CaseDbConnection connection = connections.getConnection();) {
11234 PreparedStatement preparedStatement = connection.getPreparedStatement(SleuthkitCase.PREPARED_STATEMENT.UPDATE_IMAGE_NAME);
11235 preparedStatement.clearParameters();
11236 preparedStatement.setString(1, name);
11237 preparedStatement.setLong(2, objId);
11238 connection.executeUpdate(preparedStatement);
11239 }
catch (SQLException ex) {
11240 throw new TskCoreException(String.format(
"Error updating while the name for object ID %d to %s", objId, name), ex);
11260 void setImageSizes(Image image,
long totalSize,
long sectorSize)
throws TskCoreException {
11263 try (CaseDbConnection connection = connections.getConnection();) {
11264 PreparedStatement preparedStatement = connection.getPreparedStatement(SleuthkitCase.PREPARED_STATEMENT.UPDATE_IMAGE_SIZES);
11265 preparedStatement.clearParameters();
11266 preparedStatement.setLong(1, totalSize);
11267 preparedStatement.setLong(2, sectorSize);
11268 preparedStatement.setLong(3, image.getId());
11269 connection.executeUpdate(preparedStatement);
11270 }
catch (SQLException ex) {
11271 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);
11292 public void updateFile(
long fileObjId,
long size,
long mtime,
long atime,
long ctime,
long crtime, String userSid, Long osAcctObjId)
throws TskCoreException {
11294 String updateString =
"UPDATE tsk_files SET size = ?, mtime = ?, atime = ?, ctime = ?, crtime = ?, "
11295 +
" owner_uid = ?, os_account_obj_id = ? WHERE obj_id = ?";
11298 try (CaseDbConnection connection = connections.getConnection();
11299 PreparedStatement preparedStatement = connection.getPreparedStatement(updateString, Statement.NO_GENERATED_KEYS);) {
11301 preparedStatement.clearParameters();
11303 preparedStatement.setLong(1, size);
11304 preparedStatement.setLong(2, mtime);
11305 preparedStatement.setLong(3, atime);
11306 preparedStatement.setLong(4, ctime);
11307 preparedStatement.setLong(5, crtime);
11308 preparedStatement.setString(6, userSid);
11310 if (osAcctObjId != null) {
11311 preparedStatement.setLong(7, osAcctObjId);
11313 preparedStatement.setNull(7, java.sql.Types.BIGINT);
11316 preparedStatement.setLong(8, fileObjId);
11318 connection.executeUpdate(preparedStatement);
11319 }
catch (SQLException ex) {
11320 throw new TskCoreException(String.format(
"Error updating file (obj_id = %s)", fileObjId), ex);
11337 try (CaseDbConnection connection = connections.getConnection();
11338 Statement statement = connection.createStatement()) {
11339 connection.executeUpdate(statement, String.format(
"UPDATE tsk_files SET mime_type = '%s' WHERE obj_id = %d", mimeType, file.getId()));
11340 file.setMIMEType(mimeType);
11341 }
catch (SQLException ex) {
11342 throw new TskCoreException(String.format(
"Error setting MIME type for file (obj_id = %s)", file.getId()), ex);
11361 short metaFlag = file.getMetaFlagsAsInt();
11370 try (CaseDbConnection connection = connections.getConnection();
11371 Statement statement = connection.createStatement();) {
11372 connection.executeUpdate(statement, String.format(
"UPDATE tsk_files SET meta_flags = '%d', dir_flags = '%d' WHERE obj_id = %d", newMetaFlgs, newDirFlags, file.getId()));
11379 }
catch (SQLException ex) {
11380 throw new TskCoreException(String.format(
"Error setting unalloc meta flag for file (obj_id = %s)", file.getId()), ex);
11395 void setMd5Hash(AbstractFile file, String md5Hash)
throws TskCoreException {
11396 if (md5Hash == null) {
11399 long id = file.getId();
11401 try (CaseDbConnection connection = connections.getConnection();) {
11402 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_FILE_MD5);
11403 statement.clearParameters();
11404 statement.setString(1, md5Hash.toLowerCase());
11405 statement.setLong(2,
id);
11406 connection.executeUpdate(statement);
11407 file.setMd5Hash(md5Hash.toLowerCase());
11408 }
catch (SQLException ex) {
11409 throw new TskCoreException(
"Error setting MD5 hash", ex);
11424 void setMd5ImageHash(Image img, String md5Hash)
throws TskCoreException {
11425 if (md5Hash == null) {
11428 long id = img.getId();
11430 try (CaseDbConnection connection = connections.getConnection();) {
11431 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_MD5);
11432 statement.clearParameters();
11433 statement.setString(1, md5Hash.toLowerCase());
11434 statement.setLong(2,
id);
11435 connection.executeUpdate(statement);
11436 }
catch (SQLException ex) {
11437 throw new TskCoreException(
"Error setting MD5 hash", ex);
11453 String getMd5ImageHash(Image img)
throws TskCoreException {
11454 long id = img.getId();
11455 CaseDbConnection connection = null;
11456 ResultSet rs = null;
11460 connection = connections.getConnection();
11462 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_IMAGE_MD5);
11463 statement.clearParameters();
11464 statement.setLong(1,
id);
11465 rs = connection.executeQuery(statement);
11467 hash = rs.getString(
"md5");
11470 }
catch (SQLException ex) {
11471 throw new TskCoreException(
"Error getting MD5 hash", ex);
11473 closeResultSet(rs);
11474 closeConnection(connection);
11488 void setSha1ImageHash(Image img, String sha1Hash)
throws TskCoreException {
11489 if (sha1Hash == null) {
11492 long id = img.getId();
11494 try (CaseDbConnection connection = connections.getConnection();) {
11495 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_SHA1);
11496 statement.clearParameters();
11497 statement.setString(1, sha1Hash.toLowerCase());
11498 statement.setLong(2,
id);
11499 connection.executeUpdate(statement);
11500 }
catch (SQLException ex) {
11501 throw new TskCoreException(
"Error setting SHA1 hash", ex);
11517 String getSha1ImageHash(Image img)
throws TskCoreException {
11518 long id = img.getId();
11519 CaseDbConnection connection = null;
11520 ResultSet rs = null;
11524 connection = connections.getConnection();
11526 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_IMAGE_SHA1);
11527 statement.clearParameters();
11528 statement.setLong(1,
id);
11529 rs = connection.executeQuery(statement);
11531 hash = rs.getString(
"sha1");
11534 }
catch (SQLException ex) {
11535 throw new TskCoreException(
"Error getting SHA1 hash", ex);
11537 closeResultSet(rs);
11538 closeConnection(connection);
11552 void setSha256ImageHash(Image img, String sha256Hash)
throws TskCoreException {
11553 if (sha256Hash == null) {
11556 long id = img.getId();
11558 try (CaseDbConnection connection = connections.getConnection();) {
11559 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_SHA256);
11560 statement.clearParameters();
11561 statement.setString(1, sha256Hash.toLowerCase());
11562 statement.setLong(2,
id);
11563 connection.executeUpdate(statement);
11564 }
catch (SQLException ex) {
11565 throw new TskCoreException(
"Error setting SHA256 hash", ex);
11581 String getSha256ImageHash(Image img)
throws TskCoreException {
11582 long id = img.getId();
11583 CaseDbConnection connection = null;
11584 ResultSet rs = null;
11588 connection = connections.getConnection();
11590 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_IMAGE_SHA256);
11591 statement.clearParameters();
11592 statement.setLong(1,
id);
11593 rs = connection.executeQuery(statement);
11595 hash = rs.getString(
"sha256");
11598 }
catch (SQLException ex) {
11599 throw new TskCoreException(
"Error setting SHA256 hash", ex);
11601 closeResultSet(rs);
11602 closeConnection(connection);
11615 void setAcquisitionDetails(DataSource datasource, String details)
throws TskCoreException {
11617 long id = datasource.getId();
11619 try (CaseDbConnection connection = connections.getConnection();) {
11620 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ACQUISITION_DETAILS);
11621 statement.clearParameters();
11622 statement.setString(1, details);
11623 statement.setLong(2,
id);
11624 connection.executeUpdate(statement);
11625 }
catch (SQLException ex) {
11626 throw new TskCoreException(
"Error setting acquisition details", ex);
11643 void setAcquisitionToolDetails(DataSource datasource, String name, String version, String settings)
throws TskCoreException {
11645 long id = datasource.getId();
11647 try (CaseDbConnection connection = connections.getConnection();) {
11648 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ACQUISITION_TOOL_SETTINGS);
11649 statement.clearParameters();
11650 statement.setString(1, settings);
11651 statement.setString(2, name);
11652 statement.setString(3, version);
11653 statement.setLong(4,
id);
11654 connection.executeUpdate(statement);
11655 }
catch (SQLException ex) {
11656 throw new TskCoreException(
"Error setting acquisition details", ex);
11671 void setAcquisitionDetails(
long dataSourceId, String details, CaseDbTransaction trans)
throws TskCoreException {
11673 CaseDbConnection connection = trans.getConnection();
11674 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_ACQUISITION_DETAILS);
11675 statement.clearParameters();
11676 statement.setString(1, details);
11677 statement.setLong(2, dataSourceId);
11678 connection.executeUpdate(statement);
11679 }
catch (SQLException ex) {
11680 throw new TskCoreException(
"Error setting acquisition details", ex);
11693 String getAcquisitionDetails(DataSource datasource)
throws TskCoreException {
11694 long id = datasource.getId();
11695 CaseDbConnection connection = null;
11696 ResultSet rs = null;
11700 connection = connections.getConnection();
11702 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ACQUISITION_DETAILS);
11703 statement.clearParameters();
11704 statement.setLong(1,
id);
11705 rs = connection.executeQuery(statement);
11707 hash = rs.getString(
"acquisition_details");
11710 }
catch (SQLException ex) {
11711 throw new TskCoreException(
"Error setting acquisition details", ex);
11713 closeResultSet(rs);
11714 closeConnection(connection);
11729 String getDataSourceInfoString(DataSource datasource, String columnName)
throws TskCoreException {
11730 long id = datasource.getId();
11731 CaseDbConnection connection = null;
11732 ResultSet rs = null;
11733 String returnValue =
"";
11736 connection = connections.getConnection();
11738 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ACQUISITION_TOOL_SETTINGS);
11739 statement.clearParameters();
11740 statement.setLong(1,
id);
11741 rs = connection.executeQuery(statement);
11743 returnValue = rs.getString(columnName);
11745 return returnValue;
11746 }
catch (SQLException ex) {
11747 throw new TskCoreException(
"Error setting acquisition details", ex);
11749 closeResultSet(rs);
11750 closeConnection(connection);
11765 Long getDataSourceInfoLong(DataSource datasource, String columnName)
throws TskCoreException {
11766 long id = datasource.getId();
11767 CaseDbConnection connection = null;
11768 ResultSet rs = null;
11769 Long returnValue = null;
11772 connection = connections.getConnection();
11774 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ACQUISITION_TOOL_SETTINGS);
11775 statement.clearParameters();
11776 statement.setLong(1,
id);
11777 rs = connection.executeQuery(statement);
11779 returnValue = rs.getLong(columnName);
11781 return returnValue;
11782 }
catch (SQLException ex) {
11783 throw new TskCoreException(
"Error setting acquisition details", ex);
11785 closeResultSet(rs);
11786 closeConnection(connection);
11802 if (newStatus == null) {
11806 try (CaseDbConnection connection = connections.getConnection();
11807 Statement statement = connection.createStatement();) {
11808 connection.executeUpdate(statement,
"UPDATE blackboard_artifacts "
11809 +
" SET review_status_id=" + newStatus.getID()
11810 +
" WHERE blackboard_artifacts.artifact_id = " + artifact.
getArtifactID());
11811 }
catch (SQLException ex) {
11812 throw new TskCoreException(
"Error setting review status", ex);
11829 CaseDbConnection connection = null;
11830 Statement s = null;
11831 ResultSet rs = null;
11834 connection = connections.getConnection();
11835 s = connection.createStatement();
11836 Short contentShort = contentType.getValue();
11837 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files WHERE meta_type = '" + contentShort.toString() +
"'");
11840 count = rs.getInt(
"count");
11843 }
catch (SQLException ex) {
11844 throw new TskCoreException(
"Error getting number of objects.", ex);
11846 closeResultSet(rs);
11848 closeConnection(connection);
11862 String escapedText = null;
11863 if (text != null) {
11864 escapedText = text.replaceAll(
"'",
"''");
11866 return escapedText;
11877 if (md5Hash == null) {
11878 return Collections.<AbstractFile>emptyList();
11881 CaseDbConnection connection = null;
11882 Statement s = null;
11883 ResultSet rs = null;
11886 connection = connections.getConnection();
11887 s = connection.createStatement();
11888 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE "
11889 +
" md5 = '" + md5Hash.toLowerCase() +
"' "
11891 return resultSetToAbstractFiles(rs, connection);
11892 }
catch (SQLException | TskCoreException ex) {
11893 logger.log(Level.WARNING,
"Error querying database.", ex);
11895 closeResultSet(rs);
11897 closeConnection(connection);
11900 return Collections.<AbstractFile>emptyList();
11910 boolean allFilesAreHashed =
false;
11912 CaseDbConnection connection = null;
11913 Statement s = null;
11914 ResultSet rs = null;
11917 connection = connections.getConnection();
11918 s = connection.createStatement();
11919 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files "
11921 +
"AND md5 IS NULL "
11922 +
"AND size > '0'");
11923 if (rs.next() && rs.getInt(
"count") == 0) {
11924 allFilesAreHashed =
true;
11926 }
catch (SQLException | TskCoreException ex) {
11927 logger.log(Level.WARNING,
"Failed to query whether all files have MD5 hashes", ex);
11929 closeResultSet(rs);
11931 closeConnection(connection);
11934 return allFilesAreHashed;
11946 CaseDbConnection connection = null;
11947 Statement s = null;
11948 ResultSet rs = null;
11950 connection = connections.getConnection();
11951 s = connection.createStatement();
11952 rs = connection.executeQuery(s,
"SELECT COUNT(*) AS count FROM tsk_files "
11953 +
"WHERE md5 IS NOT NULL "
11954 +
"AND size > '0'");
11956 count = rs.getInt(
"count");
11958 }
catch (SQLException | TskCoreException ex) {
11959 logger.log(Level.WARNING,
"Failed to query for all the files.", ex);
11961 closeResultSet(rs);
11963 closeConnection(connection);
11979 CaseDbConnection connection = null;
11980 ResultSet resultSet = null;
11983 connection = connections.getConnection();
11986 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_TAG_NAMES);
11987 resultSet = connection.executeQuery(statement);
11988 ArrayList<TagName> tagNames =
new ArrayList<>();
11989 while (resultSet.next()) {
11990 tagNames.add(
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
11992 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank")));
11995 }
catch (SQLException ex) {
11996 throw new TskCoreException(
"Error selecting rows from tag_names table", ex);
11998 closeResultSet(resultSet);
11999 closeConnection(connection);
12015 CaseDbConnection connection = null;
12016 ResultSet resultSet = null;
12019 connection = connections.getConnection();
12022 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_TAG_NAMES_IN_USE);
12023 resultSet = connection.executeQuery(statement);
12024 ArrayList<TagName> tagNames =
new ArrayList<>();
12025 while (resultSet.next()) {
12026 tagNames.add(
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12028 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank")));
12031 }
catch (SQLException ex) {
12032 throw new TskCoreException(
"Error selecting rows from tag_names table", ex);
12034 closeResultSet(resultSet);
12035 closeConnection(connection);
12054 ArrayList<TagName> tagNames =
new ArrayList<>();
12060 CaseDbConnection connection = null;
12061 ResultSet resultSet = null;
12064 connection = connections.getConnection();
12066 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_TAG_NAMES_IN_USE_BY_DATASOURCE);
12067 statement.setLong(1, dsObjId);
12068 statement.setLong(2, dsObjId);
12069 resultSet = connection.executeQuery(statement);
12070 while (resultSet.next()) {
12071 tagNames.add(
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12073 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank")));
12076 }
catch (SQLException ex) {
12077 throw new TskCoreException(
"Failed to get tag names in use for data source objID : " + dsObjId, ex);
12079 closeResultSet(resultSet);
12080 closeConnection(connection);
12099 @SuppressWarnings(
"deprecation")
12153 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.DELETE_CONTENT_TAG);
12154 statement.clearParameters();
12155 statement.setLong(1, tag.getId());
12156 trans.getConnection().executeUpdate(statement);
12159 Long contentId = tag.getContent() != null ? tag.getContent().getId() : null;
12160 Long dataSourceId = tag.getContent() != null && tag.getContent().getDataSource() != null
12161 ? tag.getContent().getDataSource().getId()
12164 this.
getScoringManager().updateAggregateScoreAfterDeletion(contentId, dataSourceId, trans);
12168 }
catch (SQLException ex) {
12169 throw new TskCoreException(
"Error deleting row from content_tags table (id = " + tag.getId() +
")", ex);
12171 if (trans != null) {
12186 CaseDbConnection connection = null;
12187 ResultSet resultSet = null;
12190 connection = connections.getConnection();
12196 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS);
12197 resultSet = connection.executeQuery(statement);
12198 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
12199 while (resultSet.next()) {
12200 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12202 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12204 tags.add(
new ContentTag(resultSet.getLong(
"tag_id"), content, tagName, resultSet.getString(
"comment"),
12205 resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name")));
12208 }
catch (SQLException ex) {
12209 throw new TskCoreException(
"Error selecting rows from content_tags table", ex);
12211 closeResultSet(resultSet);
12212 closeConnection(connection);
12228 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12229 throw new TskCoreException(
"TagName object is invalid, id not set");
12231 CaseDbConnection connection = null;
12232 ResultSet resultSet = null;
12235 connection = connections.getConnection();
12238 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CONTENT_TAGS_BY_TAG_NAME);
12239 statement.clearParameters();
12240 statement.setLong(1, tagName.getId());
12241 resultSet = connection.executeQuery(statement);
12242 if (resultSet.next()) {
12243 return resultSet.getLong(
"count");
12245 throw new TskCoreException(
"Error getting content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")");
12247 }
catch (SQLException ex) {
12248 throw new TskCoreException(
"Error getting content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")", ex);
12250 closeResultSet(resultSet);
12251 closeConnection(connection);
12273 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12274 throw new TskCoreException(
"TagName object is invalid, id not set");
12277 CaseDbConnection connection = null;
12278 ResultSet resultSet = null;
12281 connection = connections.getConnection();
12286 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_CONTENT_TAGS_BY_TAG_NAME_BY_DATASOURCE);
12287 statement.clearParameters();
12288 statement.setLong(1, tagName.getId());
12289 statement.setLong(2, dsObjId);
12291 resultSet = connection.executeQuery(statement);
12292 if (resultSet.next()) {
12293 return resultSet.getLong(
"count");
12295 throw new TskCoreException(
"Error getting content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")" +
" for dsObjId = " + dsObjId);
12297 }
catch (SQLException ex) {
12298 throw new TskCoreException(
"Failed to get content_tags row count for tag_name_id = " + tagName.getId() +
"data source objID : " + dsObjId, ex);
12300 closeResultSet(resultSet);
12301 closeConnection(connection);
12318 CaseDbConnection connection = null;
12319 ResultSet resultSet = null;
12323 connection = connections.getConnection();
12330 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAG_BY_ID);
12331 statement.clearParameters();
12332 statement.setLong(1, contentTagID);
12333 resultSet = connection.executeQuery(statement);
12335 while (resultSet.next()) {
12336 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12338 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12340 resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
12344 }
catch (SQLException ex) {
12345 throw new TskCoreException(
"Error getting content tag with id = " + contentTagID, ex);
12347 closeResultSet(resultSet);
12348 closeConnection(connection);
12366 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12367 throw new TskCoreException(
"TagName object is invalid, id not set");
12369 CaseDbConnection connection = null;
12370 ResultSet resultSet = null;
12373 connection = connections.getConnection();
12379 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS_BY_TAG_NAME);
12380 statement.clearParameters();
12381 statement.setLong(1, tagName.getId());
12382 resultSet = connection.executeQuery(statement);
12383 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
12384 while (resultSet.next()) {
12386 tagName, resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
12391 }
catch (SQLException ex) {
12392 throw new TskCoreException(
"Error getting content_tags rows (tag_name_id = " + tagName.getId() +
")", ex);
12394 closeResultSet(resultSet);
12395 closeConnection(connection);
12416 CaseDbConnection connection = null;
12417 ResultSet resultSet = null;
12420 connection = connections.getConnection();
12444 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS_BY_TAG_NAME_BY_DATASOURCE);
12445 statement.clearParameters();
12446 statement.setLong(1, tagName.getId());
12447 statement.setLong(2, dsObjId);
12448 statement.setLong(3, tagName.getId());
12449 statement.setLong(4, dsObjId);
12450 resultSet = connection.executeQuery(statement);
12451 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
12452 while (resultSet.next()) {
12454 tagName, resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
12459 }
catch (SQLException ex) {
12460 throw new TskCoreException(
"Failed to get content_tags row count for tag_name_id = " + tagName.getId() +
" data source objID : " + dsObjId, ex);
12462 closeResultSet(resultSet);
12463 closeConnection(connection);
12480 CaseDbConnection connection = null;
12481 ResultSet resultSet = null;
12484 connection = connections.getConnection();
12491 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_CONTENT_TAGS_BY_CONTENT);
12492 statement.clearParameters();
12493 statement.setLong(1, content.getId());
12494 resultSet = connection.executeQuery(statement);
12495 ArrayList<ContentTag> tags =
new ArrayList<ContentTag>();
12496 while (resultSet.next()) {
12497 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12499 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12501 resultSet.getString(
"comment"), resultSet.getLong(
"begin_byte_offset"), resultSet.getLong(
"end_byte_offset"), resultSet.getString(
"login_name"));
12505 }
catch (SQLException ex) {
12506 throw new TskCoreException(
"Error getting content tags data for content (obj_id = " + content.getId() +
")", ex);
12508 closeResultSet(resultSet);
12509 closeConnection(connection);
12542 PreparedStatement statement = trans.getConnection().getPreparedStatement(PREPARED_STATEMENT.DELETE_ARTIFACT_TAG);
12543 statement.clearParameters();
12544 statement.setLong(1, tag.getId());
12545 trans.getConnection().executeUpdate(statement);
12548 Long artifactObjId = tag.getArtifact().getId();
12549 Long dataSourceId = tag.getContent() != null && tag.getContent().getDataSource() != null
12550 ? tag.getContent().getDataSource().getId()
12553 this.
getScoringManager().updateAggregateScoreAfterDeletion(artifactObjId, dataSourceId, trans);
12557 }
catch (SQLException ex) {
12558 throw new TskCoreException(
"Error deleting row from blackboard_artifact_tags table (id = " + tag.getId() +
")", ex);
12560 if (trans != null) {
12576 CaseDbConnection connection = null;
12577 ResultSet resultSet = null;
12580 connection = connections.getConnection();
12586 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS);
12587 resultSet = connection.executeQuery(statement);
12588 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<>();
12589 while (resultSet.next()) {
12590 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12592 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12596 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12600 }
catch (SQLException ex) {
12601 throw new TskCoreException(
"Error selecting rows from blackboard_artifact_tags table", ex);
12603 closeResultSet(resultSet);
12604 closeConnection(connection);
12620 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12621 throw new TskCoreException(
"TagName object is invalid, id not set");
12623 CaseDbConnection connection = null;
12624 ResultSet resultSet = null;
12627 connection = connections.getConnection();
12630 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_BY_TAG_NAME);
12631 statement.clearParameters();
12632 statement.setLong(1, tagName.getId());
12633 resultSet = connection.executeQuery(statement);
12634 if (resultSet.next()) {
12635 return resultSet.getLong(
"count");
12637 throw new TskCoreException(
"Error getting blackboard_artifact_tags row count for tag name (tag_name_id = " + tagName.getId() +
")");
12639 }
catch (SQLException ex) {
12640 throw new TskCoreException(
"Error getting blackboard artifact_content_tags row count for tag name (tag_name_id = " + tagName.getId() +
")", ex);
12642 closeResultSet(resultSet);
12643 closeConnection(connection);
12664 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12665 throw new TskCoreException(
"TagName object is invalid, id not set");
12668 CaseDbConnection connection = null;
12669 ResultSet resultSet = null;
12672 connection = connections.getConnection();
12677 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.COUNT_ARTIFACTS_BY_TAG_NAME_BY_DATASOURCE);
12678 statement.clearParameters();
12679 statement.setLong(1, tagName.getId());
12680 statement.setLong(2, dsObjId);
12681 resultSet = connection.executeQuery(statement);
12682 if (resultSet.next()) {
12683 return resultSet.getLong(
"count");
12685 throw new TskCoreException(
"Error getting blackboard_artifact_tags row count for tag name (tag_name_id = " + tagName.getId() +
")" +
" for dsObjId = " + dsObjId);
12687 }
catch (SQLException ex) {
12688 throw new TskCoreException(
"Failed to get blackboard_artifact_tags row count for tag_name_id = " + tagName.getId() +
"data source objID : " + dsObjId, ex);
12690 closeResultSet(resultSet);
12691 closeConnection(connection);
12708 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12709 throw new TskCoreException(
"TagName object is invalid, id not set");
12711 CaseDbConnection connection = null;
12712 ResultSet resultSet = null;
12715 connection = connections.getConnection();
12721 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS_BY_TAG_NAME);
12722 statement.clearParameters();
12723 statement.setLong(1, tagName.getId());
12724 resultSet = connection.executeQuery(statement);
12725 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<BlackboardArtifactTag>();
12726 while (resultSet.next()) {
12730 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12734 }
catch (SQLException ex) {
12735 throw new TskCoreException(
"Error getting blackboard artifact tags data (tag_name_id = " + tagName.getId() +
")", ex);
12737 closeResultSet(resultSet);
12738 closeConnection(connection);
12759 if (tagName.getId() ==
Tag.ID_NOT_SET) {
12760 throw new TskCoreException(
"TagName object is invalid, id not set");
12763 CaseDbConnection connection = null;
12764 ResultSet resultSet = null;
12767 connection = connections.getConnection();
12775 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS_BY_TAG_NAME_BY_DATASOURCE);
12776 statement.clearParameters();
12777 statement.setLong(1, tagName.getId());
12778 statement.setLong(2, dsObjId);
12779 resultSet = connection.executeQuery(statement);
12780 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<BlackboardArtifactTag>();
12781 while (resultSet.next()) {
12785 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12789 }
catch (SQLException ex) {
12790 throw new TskCoreException(
"Failed to get blackboard_artifact_tags row count for tag_name_id = " + tagName.getId() +
"data source objID : " + dsObjId, ex);
12792 closeResultSet(resultSet);
12793 closeConnection(connection);
12812 CaseDbConnection connection = null;
12813 ResultSet resultSet = null;
12817 connection = connections.getConnection();
12824 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAG_BY_ID);
12825 statement.clearParameters();
12826 statement.setLong(1, artifactTagID);
12827 resultSet = connection.executeQuery(statement);
12829 while (resultSet.next()) {
12830 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12832 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12836 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12840 }
catch (SQLException ex) {
12841 throw new TskCoreException(
"Error getting blackboard artifact tag with id = " + artifactTagID, ex);
12843 closeResultSet(resultSet);
12844 closeConnection(connection);
12863 CaseDbConnection connection = null;
12864 ResultSet resultSet = null;
12867 connection = connections.getConnection();
12874 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_ARTIFACT_TAGS_BY_ARTIFACT);
12875 statement.clearParameters();
12876 statement.setLong(1, artifact.getArtifactID());
12877 resultSet = connection.executeQuery(statement);
12878 ArrayList<BlackboardArtifactTag> tags =
new ArrayList<>();
12879 while (resultSet.next()) {
12880 TagName tagName =
new TagName(resultSet.getLong(
"tag_name_id"), resultSet.getString(
"display_name"),
12882 TskData.
TagType.
valueOf(resultSet.getByte(
"knownStatus")), resultSet.getLong(
"tag_set_id"), resultSet.getInt(
"rank"));
12885 artifact, content, tagName, resultSet.getString(
"comment"), resultSet.getString(
"login_name"));
12889 }
catch (SQLException ex) {
12890 throw new TskCoreException(
"Error getting blackboard artifact tags data (artifact_id = " + artifact.getArtifactID() +
")", ex);
12892 closeResultSet(resultSet);
12893 closeConnection(connection);
12908 try (CaseDbConnection connection = connections.getConnection();) {
12910 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.UPDATE_IMAGE_PATH);
12911 statement.clearParameters();
12912 statement.setString(1, newPath);
12913 statement.setLong(2, objectId);
12914 connection.executeUpdate(statement);
12915 }
catch (SQLException ex) {
12916 throw new TskCoreException(
"Error updating image path in database for object " + objectId, ex);
12935 public Report addReport(String localPath, String sourceModuleName, String reportName)
throws TskCoreException {
12936 return addReport(localPath, sourceModuleName, reportName, null);
12957 String relativePath =
"";
12958 long createTime = 0;
12959 String localPathLower = localPath.toLowerCase();
12961 if (localPathLower.startsWith(
"http")) {
12962 relativePath = localPathLower;
12963 createTime = System.currentTimeMillis() / 1000;
12974 int length =
new File(casePathLower).toURI().relativize(
new File(localPathLower).toURI()).getPath().length();
12975 relativePath =
new File(localPath.substring(localPathLower.length() - length)).getPath();
12976 }
catch (IllegalArgumentException ex) {
12977 String errorMessage = String.format(
"Local path %s not in the database directory or one of its subdirectories", localPath);
12978 throw new TskCoreException(errorMessage, ex);
12982 java.io.File tempFile =
new java.io.File(localPath);
12984 createTime = tempFile.lastModified() / 1000;
12985 }
catch (Exception ex) {
12986 throw new TskCoreException(
"Could not get create time for report at " + localPath, ex);
12992 try (CaseDbConnection connection = connections.getConnection();) {
12995 long parentObjId = 0;
12996 if (parent != null) {
12997 parentObjId = parent.getId();
13002 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_REPORT);
13003 statement.clearParameters();
13004 statement.setLong(1, objectId);
13005 statement.setString(2, relativePath);
13006 statement.setLong(3, createTime);
13007 statement.setString(4, sourceModuleName);
13008 statement.setString(5, reportName);
13009 connection.executeUpdate(statement);
13010 return new Report(
this, objectId, localPath, createTime, sourceModuleName, reportName, parent);
13011 }
catch (SQLException ex) {
13012 throw new TskCoreException(
"Error adding report " + localPath +
" to reports table", ex);
13027 CaseDbConnection connection = null;
13028 ResultSet resultSet = null;
13029 ResultSet parentResultSet = null;
13030 PreparedStatement statement = null;
13031 Statement parentStatement = null;
13034 connection = connections.getConnection();
13037 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_REPORTS);
13038 parentStatement = connection.createStatement();
13039 resultSet = connection.executeQuery(statement);
13040 ArrayList<Report> reports =
new ArrayList<Report>();
13041 while (resultSet.next()) {
13042 String localpath = resultSet.getString(
"path");
13043 if (localpath.toLowerCase().startsWith(
"http") ==
false) {
13045 localpath = Paths.get(
getDbDirPath(), localpath).normalize().toString();
13050 long reportId = resultSet.getLong(
"obj_id");
13051 String parentQuery = String.format(
"SELECT * FROM tsk_objects WHERE obj_id = %s;", reportId);
13052 parentResultSet = parentStatement.executeQuery(parentQuery);
13053 if (parentResultSet.next()) {
13054 long parentId = parentResultSet.getLong(
"par_obj_id");
13057 parentResultSet.close();
13059 reports.add(
new Report(
this,
13062 resultSet.getLong(
"crtime"),
13063 resultSet.getString(
"src_module_name"),
13064 resultSet.getString(
"report_name"),
13068 }
catch (SQLException ex) {
13069 throw new TskCoreException(
"Error querying reports table", ex);
13071 closeResultSet(resultSet);
13072 closeResultSet(parentResultSet);
13073 closeStatement(statement);
13074 closeStatement(parentStatement);
13076 closeConnection(connection);
13091 CaseDbConnection connection = null;
13092 PreparedStatement statement = null;
13093 Statement parentStatement = null;
13094 ResultSet resultSet = null;
13095 ResultSet parentResultSet = null;
13099 connection = connections.getConnection();
13102 statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_REPORT_BY_ID);
13103 parentStatement = connection.createStatement();
13104 statement.clearParameters();
13105 statement.setLong(1,
id);
13106 resultSet = connection.executeQuery(statement);
13108 if (resultSet.next()) {
13111 String parentQuery = String.format(
"SELECT * FROM tsk_objects WHERE obj_id = %s;",
id);
13112 parentResultSet = parentStatement.executeQuery(parentQuery);
13113 if (parentResultSet.next()) {
13114 long parentId = parentResultSet.getLong(
"par_obj_id");
13118 report =
new Report(
this, resultSet.getLong(
"obj_id"),
13119 Paths.get(
getDbDirPath(), resultSet.getString(
"path")).normalize().toString(),
13120 resultSet.getLong(
"crtime"),
13121 resultSet.getString(
"src_module_name"),
13122 resultSet.getString(
"report_name"),
13125 throw new TskCoreException(
"No report found for id: " +
id);
13127 }
catch (SQLException ex) {
13128 throw new TskCoreException(
"Error querying reports table for id: " +
id, ex);
13130 closeResultSet(resultSet);
13131 closeResultSet(parentResultSet);
13132 closeStatement(statement);
13133 closeStatement(parentStatement);
13134 closeConnection(connection);
13150 try (CaseDbConnection connection = connections.getConnection();) {
13152 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.DELETE_REPORT);
13153 statement.setLong(1, report.getId());
13154 connection.executeUpdate(statement);
13156 statement = connection.getPreparedStatement(PREPARED_STATEMENT.DELETE_REPORT_TSK_OBJECT);
13157 statement.setLong(1, report.getId());
13159 connection.executeUpdate(statement);
13160 }
catch (SQLException ex) {
13161 throw new TskCoreException(
"Error querying reports table", ex);
13167 static void closeResultSet(ResultSet resultSet) {
13168 if (resultSet != null) {
13171 }
catch (SQLException ex) {
13172 logger.log(Level.SEVERE,
"Error closing ResultSet", ex);
13177 static void closeStatement(Statement statement) {
13178 if (statement != null) {
13181 }
catch (SQLException ex) {
13182 logger.log(Level.SEVERE,
"Error closing Statement", ex);
13188 static void closeConnection(CaseDbConnection connection) {
13189 if (connection != null) {
13190 connection.close();
13194 private static void rollbackTransaction(CaseDbConnection connection) {
13195 if (connection != null) {
13196 connection.rollbackTransaction();
13208 void setIngestJobEndDateTime(
long ingestJobId,
long endDateTime)
throws TskCoreException {
13210 try (CaseDbConnection connection = connections.getConnection();) {
13211 Statement statement = connection.createStatement();
13212 statement.executeUpdate(
"UPDATE ingest_jobs SET end_date_time=" + endDateTime +
" WHERE ingest_job_id=" + ingestJobId +
";");
13213 }
catch (SQLException ex) {
13214 throw new TskCoreException(
"Error updating the end date (ingest_job_id = " + ingestJobId +
".", ex);
13220 void setIngestJobStatus(
long ingestJobId, IngestJobStatusType status)
throws TskCoreException {
13222 try (CaseDbConnection connection = connections.getConnection();
13223 Statement statement = connection.createStatement();) {
13224 statement.executeUpdate(
"UPDATE ingest_jobs SET status_id=" + status.ordinal() +
" WHERE ingest_job_id=" + ingestJobId +
";");
13225 }
catch (SQLException ex) {
13226 throw new TskCoreException(
"Error ingest job status (ingest_job_id = " + ingestJobId +
".", ex);
13249 CaseDbConnection connection = null;
13251 ResultSet resultSet = null;
13252 Statement statement;
13254 connection = connections.getConnection();
13255 connection.beginTransaction();
13256 statement = connection.createStatement();
13257 PreparedStatement insertStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_INGEST_JOB, Statement.RETURN_GENERATED_KEYS);
13258 insertStatement.setLong(1, dataSource.getId());
13259 insertStatement.setString(2, hostName);
13260 insertStatement.setLong(3, jobStart.getTime());
13261 insertStatement.setLong(4, jobEnd.getTime());
13262 insertStatement.setInt(5, status.ordinal());
13263 insertStatement.setString(6, settingsDir);
13264 connection.executeUpdate(insertStatement);
13265 resultSet = insertStatement.getGeneratedKeys();
13267 long id = resultSet.getLong(1);
13268 for (
int i = 0; i < ingestModules.size(); i++) {
13270 statement.executeUpdate(
"INSERT INTO ingest_job_modules (ingest_job_id, ingest_module_id, pipeline_position) "
13271 +
"VALUES (" +
id +
", " + ingestModule.
getIngestModuleId() +
", " + i +
");");
13275 connection.commitTransaction();
13276 return new IngestJobInfo(
id, dataSource.getId(), hostName, jobStart,
"", ingestModules,
this);
13277 }
catch (SQLException ex) {
13278 rollbackTransaction(connection);
13279 throw new TskCoreException(
"Error adding the ingest job.", ex);
13281 closeResultSet(resultSet);
13282 closeConnection(connection);
13301 CaseDbConnection connection = null;
13302 ResultSet resultSet = null;
13303 Statement statement = null;
13304 String uniqueName = factoryClassName +
"-" + displayName +
"-" + version;
13307 connection = connections.getConnection();
13308 statement = connection.createStatement();
13309 resultSet = statement.executeQuery(
"SELECT * FROM ingest_modules WHERE unique_name = '" + uniqueName +
"'");
13310 if (!resultSet.next()) {
13313 PreparedStatement insertStatement = connection.getPreparedStatement(PREPARED_STATEMENT.INSERT_INGEST_MODULE, Statement.RETURN_GENERATED_KEYS);
13314 insertStatement.setString(1, displayName);
13315 insertStatement.setString(2, uniqueName);
13316 insertStatement.setInt(3, type.ordinal());
13317 insertStatement.setString(4, version);
13318 connection.executeUpdate(insertStatement);
13319 resultSet = insertStatement.getGeneratedKeys();
13321 long id = resultSet.getLong(1);
13326 return new IngestModuleInfo(resultSet.getInt(
"ingest_module_id"), resultSet.getString(
"display_name"),
13327 resultSet.getString(
"unique_name"),
IngestModuleType.
fromID(resultSet.getInt(
"type_id")), resultSet.getString(
"version"));
13329 }
catch (SQLException ex) {
13331 closeStatement(statement);
13332 if (connection != null) {
13333 statement = connection.createStatement();
13334 resultSet = statement.executeQuery(
"SELECT * FROM ingest_modules WHERE unique_name = '" + uniqueName +
"'");
13335 if (resultSet.next()) {
13336 return new IngestModuleInfo(resultSet.getInt(
"ingest_module_id"), resultSet.getString(
"display_name"),
13340 throw new TskCoreException(
"Couldn't add new module to database.", ex);
13341 }
catch (SQLException ex1) {
13342 throw new TskCoreException(
"Couldn't add new module to database.", ex1);
13345 closeResultSet(resultSet);
13346 closeStatement(statement);
13347 closeConnection(connection);
13360 CaseDbConnection connection = null;
13361 ResultSet resultSet = null;
13362 Statement statement = null;
13363 List<IngestJobInfo> ingestJobs =
new ArrayList<>();
13366 connection = connections.getConnection();
13367 statement = connection.createStatement();
13368 resultSet = statement.executeQuery(
"SELECT * FROM ingest_jobs");
13369 while (resultSet.next()) {
13370 ingestJobs.add(
new IngestJobInfo(resultSet.getInt(
"ingest_job_id"), resultSet.getLong(
"obj_id"),
13371 resultSet.getString(
"host_name"),
new Date(resultSet.getLong(
"start_date_time")),
13373 resultSet.getString(
"settings_dir"), this.getIngestModules(resultSet.getInt(
"ingest_job_id"), connection),
this));
13376 }
catch (SQLException ex) {
13377 throw new TskCoreException(
"Couldn't get the ingest jobs.", ex);
13379 closeResultSet(resultSet);
13380 closeStatement(statement);
13381 closeConnection(connection);
13396 private List<IngestModuleInfo> getIngestModules(
int ingestJobId, CaseDbConnection connection)
throws SQLException {
13397 ResultSet resultSet = null;
13398 Statement statement = null;
13399 List<IngestModuleInfo> ingestModules =
new ArrayList<>();
13402 statement = connection.createStatement();
13403 resultSet = statement.executeQuery(
"SELECT ingest_job_modules.ingest_module_id AS ingest_module_id, "
13404 +
"ingest_job_modules.pipeline_position AS pipeline_position, "
13405 +
"ingest_modules.display_name AS display_name, ingest_modules.unique_name AS unique_name, "
13406 +
"ingest_modules.type_id AS type_id, ingest_modules.version AS version "
13407 +
"FROM ingest_job_modules, ingest_modules "
13408 +
"WHERE ingest_job_modules.ingest_job_id = " + ingestJobId +
" "
13409 +
"AND ingest_modules.ingest_module_id = ingest_job_modules.ingest_module_id "
13410 +
"ORDER BY (ingest_job_modules.pipeline_position);");
13411 while (resultSet.next()) {
13412 ingestModules.add(
new IngestModuleInfo(resultSet.getInt(
"ingest_module_id"), resultSet.getString(
"display_name"),
13413 resultSet.getString(
"unique_name"),
IngestModuleType.
fromID(resultSet.getInt(
"type_id")), resultSet.getString(
"version")));
13415 return ingestModules;
13417 closeResultSet(resultSet);
13418 closeStatement(statement);
13433 String getInsertOrIgnoreSQL(String sql) {
13436 return " INSERT " + sql +
" ON CONFLICT DO NOTHING ";
13438 return " INSERT OR IGNORE " + sql;
13440 throw new UnsupportedOperationException(
"Unsupported DB type: " +
getDatabaseType().name());
13464 private List<? extends BlackboardArtifact> getArtifactsForValues(BlackboardArtifact.Category category, String dbColumn, List<? extends Number> values, CaseDbConnection connection)
throws TskCoreException {
13468 for (Number value : values) {
13469 if (!where.isEmpty()) {
13472 where += dbColumn +
" = " + value;
13477 if (category == BlackboardArtifact.Category.DATA_ARTIFACT) {
13487 static class ObjectInfo {
13490 private TskData.ObjectType type;
13492 ObjectInfo(
long id, ObjectType type) {
13501 TskData.ObjectType getType() {
13506 private interface DbCommand {
13508 void execute() throws SQLException;
13511 private enum PREPARED_STATEMENT {
13513 SELECT_ARTIFACTS_BY_TYPE(
"SELECT artifact_id, obj_id FROM blackboard_artifacts "
13514 +
"WHERE artifact_type_id = ?"),
13515 COUNT_ARTIFACTS_OF_TYPE(
"SELECT COUNT(*) AS count FROM blackboard_artifacts WHERE artifact_type_id = ? AND review_status_id != " + BlackboardArtifact.ReviewStatus.REJECTED.getID()),
13516 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()),
13517 COUNT_ARTIFACTS_FROM_SOURCE(
"SELECT COUNT(*) AS count FROM blackboard_artifacts WHERE obj_id = ? AND review_status_id != " + BlackboardArtifact.ReviewStatus.REJECTED.getID()),
13518 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()),
13519 SELECT_FILES_BY_PARENT(
"SELECT tsk_files.* "
13520 +
"FROM tsk_objects INNER JOIN tsk_files "
13521 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13522 +
"WHERE (tsk_objects.par_obj_id = ? ) "
13523 +
"ORDER BY tsk_files.meta_type DESC, LOWER(tsk_files.name)"),
13524 SELECT_FILES_BY_PARENT_AND_TYPE(
"SELECT tsk_files.* "
13525 +
"FROM tsk_objects INNER JOIN tsk_files "
13526 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13527 +
"WHERE (tsk_objects.par_obj_id = ? AND tsk_files.type = ? ) "
13528 +
"ORDER BY tsk_files.dir_type, LOWER(tsk_files.name)"),
13529 SELECT_FILES_BY_PARENT_AND_NAME(
"SELECT tsk_files.* "
13530 +
"FROM tsk_objects INNER JOIN tsk_files "
13531 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13532 +
"WHERE (tsk_objects.par_obj_id = ? AND "
13533 +
"LOWER(tsk_files.name) LIKE LOWER(?) AND LOWER(tsk_files.name) NOT LIKE LOWER('%journal%')) "
13534 +
"ORDER BY tsk_files.dir_type, LOWER(tsk_files.name)"),
13535 SELECT_FILES_BY_EXTENSION_AND_PARENT_AND_NAME(
"SELECT tsk_files.* "
13536 +
"FROM tsk_objects INNER JOIN tsk_files "
13537 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13538 +
"WHERE tsk_files.extension = ? AND "
13539 +
"(tsk_objects.par_obj_id = ? AND "
13540 +
"LOWER(tsk_files.name) LIKE LOWER(?) AND LOWER(tsk_files.name) NOT LIKE LOWER('%journal%')) "
13541 +
"ORDER BY tsk_files.dir_type, LOWER(tsk_files.name)"),
13542 SELECT_FILE_IDS_BY_PARENT(
"SELECT tsk_files.obj_id AS obj_id "
13543 +
"FROM tsk_objects INNER JOIN tsk_files "
13544 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13545 +
"WHERE (tsk_objects.par_obj_id = ?)"),
13546 SELECT_FILE_IDS_BY_PARENT_AND_TYPE(
"SELECT tsk_files.obj_id AS obj_id "
13547 +
"FROM tsk_objects INNER JOIN tsk_files "
13548 +
"ON tsk_objects.obj_id=tsk_files.obj_id "
13549 +
"WHERE (tsk_objects.par_obj_id = ? "
13550 +
"AND tsk_files.type = ? )"),
13551 SELECT_FILE_BY_ID(
"SELECT * FROM tsk_files WHERE obj_id = ? LIMIT 1"),
13552 SELECT_ARTIFACT_BY_ARTIFACT_OBJ_ID(
"SELECT * FROM blackboard_artifacts WHERE artifact_obj_id = ? LIMIT 1"),
13553 SELECT_ARTIFACT_TYPE_BY_ARTIFACT_OBJ_ID(
"SELECT artifact_type_id FROM blackboard_artifacts WHERE artifact_obj_id = ? LIMIT 1"),
13554 SELECT_ARTIFACT_BY_ARTIFACT_ID(
"SELECT * FROM blackboard_artifacts WHERE artifact_id = ? LIMIT 1"),
13555 INSERT_ARTIFACT(
"INSERT INTO blackboard_artifacts (artifact_id, obj_id, artifact_obj_id, data_source_obj_id, artifact_type_id, review_status_id) "
13556 +
"VALUES (?, ?, ?, ?, ?," + BlackboardArtifact.ReviewStatus.UNDECIDED.getID() +
")"),
13557 POSTGRESQL_INSERT_ARTIFACT(
"INSERT INTO blackboard_artifacts (artifact_id, obj_id, artifact_obj_id, data_source_obj_id, artifact_type_id, review_status_id) "
13558 +
"VALUES (DEFAULT, ?, ?, ?, ?," + BlackboardArtifact.ReviewStatus.UNDECIDED.getID() +
")"),
13559 INSERT_ANALYSIS_RESULT(
"INSERT INTO tsk_analysis_results (artifact_obj_id, conclusion, significance, priority, configuration, justification) "
13560 +
"VALUES (?, ?, ?, ?, ?, ?)"),
13561 INSERT_STRING_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_text) "
13562 +
"VALUES (?,?,?,?,?,?,?)"),
13563 INSERT_BYTE_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_byte) "
13564 +
"VALUES (?,?,?,?,?,?,?)"),
13565 INSERT_INT_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_int32) "
13566 +
"VALUES (?,?,?,?,?,?,?)"),
13567 INSERT_LONG_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_int64) "
13568 +
"VALUES (?,?,?,?,?,?,?)"),
13569 INSERT_DOUBLE_ATTRIBUTE(
"INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_double) "
13570 +
"VALUES (?,?,?,?,?,?,?)"),
13571 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) "
13572 +
"VALUES (?,?,?,?,?,?,?,?)"),
13573 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 = ?"),
13574 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 = ?"),
13575 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 = ?"),
13576 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 = ?"),
13577 UPDATE_FILE_MD5(
"UPDATE tsk_files SET md5 = ? WHERE obj_id = ?"),
13578 UPDATE_IMAGE_MD5(
"UPDATE tsk_image_info SET md5 = ? WHERE obj_id = ?"),
13579 UPDATE_IMAGE_SHA1(
"UPDATE tsk_image_info SET sha1 = ? WHERE obj_id = ?"),
13580 UPDATE_IMAGE_SHA256(
"UPDATE tsk_image_info SET sha256 = ? WHERE obj_id = ?"),
13581 SELECT_IMAGE_MD5(
"SELECT md5 FROM tsk_image_info WHERE obj_id = ?"),
13582 SELECT_IMAGE_SHA1(
"SELECT sha1 FROM tsk_image_info WHERE obj_id = ?"),
13583 SELECT_IMAGE_SHA256(
"SELECT sha256 FROM tsk_image_info WHERE obj_id = ?"),
13584 UPDATE_ACQUISITION_DETAILS(
"UPDATE data_source_info SET acquisition_details = ? WHERE obj_id = ?"),
13585 UPDATE_ACQUISITION_TOOL_SETTINGS(
"UPDATE data_source_info SET acquisition_tool_settings = ?, acquisition_tool_name = ?, acquisition_tool_version = ? WHERE obj_id = ?"),
13586 SELECT_ACQUISITION_DETAILS(
"SELECT acquisition_details FROM data_source_info WHERE obj_id = ?"),
13587 SELECT_ACQUISITION_TOOL_SETTINGS(
"SELECT acquisition_tool_settings, acquisition_tool_name, acquisition_tool_version, added_date_time FROM data_source_info WHERE obj_id = ?"),
13588 SELECT_LOCAL_PATH_FOR_FILE(
"SELECT path FROM tsk_files_path WHERE obj_id = ?"),
13589 SELECT_ENCODING_FOR_FILE(
"SELECT encoding_type FROM tsk_files_path WHERE obj_id = ?"),
13590 SELECT_LOCAL_PATH_AND_ENCODING_FOR_FILE(
"SELECT path, encoding_type FROM tsk_files_path WHERE obj_id = ?"),
13591 SELECT_PATH_FOR_FILE(
"SELECT parent_path FROM tsk_files WHERE obj_id = ?"),
13592 SELECT_FILE_NAME(
"SELECT name FROM tsk_files WHERE obj_id = ?"),
13593 SELECT_DERIVED_FILE(
"SELECT derived_id, rederive FROM tsk_files_derived WHERE obj_id = ?"),
13594 SELECT_FILE_DERIVATION_METHOD(
"SELECT tool_name, tool_version, other FROM tsk_files_derived_method WHERE derived_id = ?"),
13595 SELECT_MAX_OBJECT_ID(
"SELECT MAX(obj_id) AS max_obj_id FROM tsk_objects"),
13596 INSERT_OBJECT(
"INSERT INTO tsk_objects (par_obj_id, type) VALUES (?, ?)"),
13597 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) "
13598 +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13599 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)"
13600 +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13601 UPDATE_DERIVED_FILE(
"UPDATE tsk_files SET type = ?, dir_type = ?, meta_type = ?, dir_flags = ?, meta_flags = ?, size= ?, ctime= ?, crtime= ?, atime= ?, mtime= ?, mime_type = ? "
13602 +
"WHERE obj_id = ?"),
13603 INSERT_LAYOUT_FILE(
"INSERT INTO tsk_file_layout (obj_id, byte_start, byte_len, sequence) "
13604 +
"VALUES (?, ?, ?, ?)"),
13605 INSERT_LOCAL_PATH(
"INSERT INTO tsk_files_path (obj_id, path, encoding_type) VALUES (?, ?, ?)"),
13606 UPDATE_LOCAL_PATH(
"UPDATE tsk_files_path SET path = ?, encoding_type = ? WHERE obj_id = ?"),
13607 COUNT_CHILD_OBJECTS_BY_PARENT(
"SELECT COUNT(obj_id) AS count FROM tsk_objects WHERE par_obj_id = ?"),
13608 SELECT_FILE_SYSTEM_BY_OBJECT(
"SELECT fs_obj_id from tsk_files WHERE obj_id=?"),
13609 SELECT_TAG_NAMES(
"SELECT * FROM tag_names"),
13610 SELECT_TAG_NAMES_IN_USE(
"SELECT * FROM tag_names "
13611 +
"WHERE tag_name_id IN "
13612 +
"(SELECT tag_name_id from content_tags UNION SELECT tag_name_id FROM blackboard_artifact_tags)"),
13613 SELECT_TAG_NAMES_IN_USE_BY_DATASOURCE(
"SELECT * FROM tag_names "
13614 +
"WHERE tag_name_id IN "
13615 +
"( SELECT content_tags.tag_name_id as tag_name_id "
13616 +
"FROM content_tags as content_tags, tsk_files as tsk_files"
13617 +
" WHERE content_tags.obj_id = tsk_files.obj_id"
13618 +
" AND tsk_files.data_source_obj_id = ?"
13620 +
"SELECT artifact_tags.tag_name_id as tag_name_id "
13621 +
" FROM blackboard_artifact_tags as artifact_tags, blackboard_artifacts AS arts "
13622 +
" WHERE artifact_tags.artifact_id = arts.artifact_id"
13623 +
" AND arts.data_source_obj_id = ?"
13625 INSERT_TAG_NAME(
"INSERT INTO tag_names (display_name, description, color, knownStatus) VALUES (?, ?, ?, ?)"),
13626 INSERT_CONTENT_TAG(
"INSERT INTO content_tags (obj_id, tag_name_id, comment, begin_byte_offset, end_byte_offset, examiner_id) VALUES (?, ?, ?, ?, ?, ?)"),
13627 DELETE_CONTENT_TAG(
"DELETE FROM content_tags WHERE tag_id = ?"),
13628 COUNT_CONTENT_TAGS_BY_TAG_NAME(
"SELECT COUNT(*) AS count FROM content_tags WHERE tag_name_id = ?"),
13629 COUNT_CONTENT_TAGS_BY_TAG_NAME_BY_DATASOURCE(
13630 "SELECT COUNT(*) AS count FROM content_tags as content_tags, tsk_files as tsk_files WHERE content_tags.obj_id = tsk_files.obj_id"
13631 +
" AND content_tags.tag_name_id = ? "
13632 +
" AND tsk_files.data_source_obj_id = ? "
13634 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 "
13635 +
"FROM content_tags "
13636 +
"INNER JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13637 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id"),
13638 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 "
13639 +
"FROM content_tags "
13640 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13641 +
"WHERE tag_name_id = ?"),
13642 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 "
13643 +
"FROM content_tags "
13644 +
"JOIN tsk_os_accounts acc ON content_tags.obj_id = acc.os_account_obj_id "
13645 +
"JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13646 +
"JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13647 +
"WHERE content_tags.tag_name_id = ? "
13648 +
"AND acc.os_account_obj_id IN (SELECT os_account_obj_id FROM tsk_os_account_instances WHERE data_source_obj_id = ?) "
13649 +
"AND acc.db_status = " + OsAccount.OsAccountDbStatus.ACTIVE.getId()
13651 +
"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 "
13652 +
"FROM content_tags as content_tags, tsk_files as tsk_files, tag_names as tag_names, tsk_examiners as tsk_examiners "
13653 +
"WHERE content_tags.examiner_id = tsk_examiners.examiner_id "
13654 +
"AND content_tags.obj_id = tsk_files.obj_id "
13655 +
"AND content_tags.tag_name_id = tag_names.tag_name_id "
13656 +
"AND content_tags.tag_name_id = ? "
13657 +
"AND tsk_files.data_source_obj_id = ? "),
13658 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 "
13659 +
"FROM content_tags "
13660 +
"INNER JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13661 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13662 +
"WHERE tag_id = ?"),
13663 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 "
13664 +
"FROM content_tags "
13665 +
"INNER JOIN tag_names ON content_tags.tag_name_id = tag_names.tag_name_id "
13666 +
"LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id "
13667 +
"WHERE content_tags.obj_id = ?"),
13668 INSERT_ARTIFACT_TAG(
"INSERT INTO blackboard_artifact_tags (artifact_id, tag_name_id, comment, examiner_id) "
13669 +
"VALUES (?, ?, ?, ?)"),
13670 DELETE_ARTIFACT_TAG(
"DELETE FROM blackboard_artifact_tags WHERE tag_id = ?"),
13671 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 "
13672 +
"FROM blackboard_artifact_tags "
13673 +
"INNER JOIN tag_names ON blackboard_artifact_tags.tag_name_id = tag_names.tag_name_id "
13674 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id"),
13675 COUNT_ARTIFACTS_BY_TAG_NAME(
"SELECT COUNT(*) AS count FROM blackboard_artifact_tags WHERE tag_name_id = ?"),
13676 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"
13677 +
" AND artifact_tags.tag_name_id = ?"
13678 +
" AND arts.data_source_obj_id = ? "),
13679 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 "
13680 +
"FROM blackboard_artifact_tags "
13681 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id "
13682 +
"WHERE tag_name_id = ?"),
13683 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 "
13684 +
"FROM blackboard_artifact_tags as artifact_tags, blackboard_artifacts AS arts, tsk_examiners AS tsk_examiners "
13685 +
"WHERE artifact_tags.examiner_id = tsk_examiners.examiner_id"
13686 +
" AND artifact_tags.artifact_id = arts.artifact_id"
13687 +
" AND artifact_tags.tag_name_id = ? "
13688 +
" AND arts.data_source_obj_id = ? "),
13689 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 "
13690 +
"FROM blackboard_artifact_tags "
13691 +
"INNER JOIN tag_names ON blackboard_artifact_tags.tag_name_id = tag_names.tag_name_id "
13692 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id "
13693 +
"WHERE blackboard_artifact_tags.tag_id = ?"),
13694 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 "
13695 +
"FROM blackboard_artifact_tags "
13696 +
"INNER JOIN tag_names ON blackboard_artifact_tags.tag_name_id = tag_names.tag_name_id "
13697 +
"LEFT OUTER JOIN tsk_examiners ON blackboard_artifact_tags.examiner_id = tsk_examiners.examiner_id "
13698 +
"WHERE blackboard_artifact_tags.artifact_id = ?"),
13699 SELECT_REPORTS(
"SELECT * FROM reports"),
13700 SELECT_REPORT_BY_ID(
"SELECT * FROM reports WHERE obj_id = ?"),
13701 INSERT_REPORT(
"INSERT INTO reports (obj_id, path, crtime, src_module_name, report_name) VALUES (?, ?, ?, ?, ?)"),
13702 DELETE_REPORT(
"DELETE FROM reports WHERE reports.obj_id = ?"),
13703 DELETE_REPORT_TSK_OBJECT(
"DELETE FROM tsk_objects where tsk_objects.obj_id = ? and tsk_objects.type = ?"),
13704 INSERT_INGEST_JOB(
"INSERT INTO ingest_jobs (obj_id, host_name, start_date_time, end_date_time, status_id, settings_dir) VALUES (?, ?, ?, ?, ?, ?)"),
13705 INSERT_INGEST_MODULE(
"INSERT INTO ingest_modules (display_name, unique_name, type_id, version) VALUES(?, ?, ?, ?)"),
13706 SELECT_ATTR_BY_VALUE_BYTE(
"SELECT source FROM blackboard_attributes WHERE artifact_id = ? AND attribute_type_id = ? AND value_type = 4 AND value_byte = ?"),
13707 UPDATE_ATTR_BY_VALUE_BYTE(
"UPDATE blackboard_attributes SET source = ? WHERE artifact_id = ? AND attribute_type_id = ? AND value_type = 4 AND value_byte = ?"),
13708 UPDATE_IMAGE_PATH(
"UPDATE tsk_image_names SET name = ? WHERE obj_id = ?"),
13709 SELECT_ARTIFACT_OBJECTIDS_BY_PARENT(
"SELECT blackboard_artifacts.artifact_obj_id AS artifact_obj_id "
13710 +
"FROM tsk_objects INNER JOIN blackboard_artifacts "
13711 +
"ON tsk_objects.obj_id=blackboard_artifacts.obj_id "
13712 +
"WHERE (tsk_objects.par_obj_id = ?)"),
13713 SELECT_EXAMINER_BY_ID(
"SELECT * FROM tsk_examiners WHERE examiner_id = ?"),
13714 SELECT_EXAMINER_BY_LOGIN_NAME(
"SELECT * FROM tsk_examiners WHERE login_name = ?"),
13715 INSERT_EXAMINER_POSTGRESQL(
"INSERT INTO tsk_examiners (login_name) VALUES (?) ON CONFLICT DO NOTHING"),
13716 INSERT_EXAMINER_SQLITE(
"INSERT OR IGNORE INTO tsk_examiners (login_name) VALUES (?)"),
13717 UPDATE_FILE_NAME(
"UPDATE tsk_files SET name = ? WHERE obj_id = ?"),
13718 UPDATE_IMAGE_NAME(
"UPDATE tsk_image_info SET display_name = ? WHERE obj_id = ?"),
13719 UPDATE_IMAGE_SIZES(
"UPDATE tsk_image_info SET size = ?, ssize = ? WHERE obj_id = ?"),
13720 DELETE_IMAGE_NAME(
"DELETE FROM tsk_image_names WHERE obj_id = ?"),
13721 INSERT_IMAGE_NAME(
"INSERT INTO tsk_image_names (obj_id, name, sequence) VALUES (?, ?, ?)"),
13722 INSERT_IMAGE_INFO(
"INSERT INTO tsk_image_info (obj_id, type, ssize, tzone, size, md5, sha1, sha256, display_name)"
13723 +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13724 INSERT_DATA_SOURCE_INFO(
"INSERT INTO data_source_info (obj_id, device_id, time_zone, added_date_time, host_id, acquisition_tool_settings) VALUES (?, ?, ?, ?, ?, ?)"),
13725 INSERT_VS_INFO(
"INSERT INTO tsk_vs_info (obj_id, vs_type, img_offset, block_size) VALUES (?, ?, ?, ?)"),
13726 INSERT_VS_PART_SQLITE(
"INSERT INTO tsk_vs_parts (obj_id, addr, start, length, desc, flags) VALUES (?, ?, ?, ?, ?, ?)"),
13727 INSERT_VS_PART_POSTGRESQL(
"INSERT INTO tsk_vs_parts (obj_id, addr, start, length, descr, flags) VALUES (?, ?, ?, ?, ?, ?)"),
13728 INSERT_POOL_INFO(
"INSERT INTO tsk_pool_info (obj_id, pool_type) VALUES (?, ?)"),
13729 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)"
13730 +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
13731 SELECT_TAG_NAME_BY_ID(
"SELECT * FROM tag_names where tag_name_id = ?");
13733 private final String sql;
13735 private PREPARED_STATEMENT(String sql) {
13749 abstract private class ConnectionPool {
13751 private PooledDataSource pooledDataSource;
13753 public ConnectionPool() {
13754 pooledDataSource = null;
13757 CaseDbConnection getConnection() throws TskCoreException {
13758 if (pooledDataSource == null) {
13759 throw new TskCoreException(
"Error getting case database connection - case is closed");
13762 return getPooledConnection();
13763 }
catch (SQLException exp) {
13764 throw new TskCoreException(exp.getMessage());
13768 void close() throws TskCoreException {
13769 if (pooledDataSource != null) {
13771 pooledDataSource.close();
13772 }
catch (SQLException exp) {
13773 throw new TskCoreException(exp.getMessage());
13775 pooledDataSource = null;
13780 abstract CaseDbConnection getPooledConnection() throws SQLException;
13782 public PooledDataSource getPooledDataSource() {
13783 return pooledDataSource;
13786 public void setPooledDataSource(PooledDataSource pooledDataSource) {
13787 this.pooledDataSource = pooledDataSource;
13795 private final class SQLiteConnections
extends ConnectionPool {
13797 private final Map<String, String> configurationOverrides =
new HashMap<String, String>();
13799 SQLiteConnections(String dbPath)
throws SQLException {
13800 configurationOverrides.put(
"acquireIncrement",
"2");
13801 configurationOverrides.put(
"initialPoolSize",
"5");
13802 configurationOverrides.put(
"minPoolSize",
"5");
13807 configurationOverrides.put(
"maxPoolSize",
"20");
13808 configurationOverrides.put(
"maxStatements",
"200");
13809 configurationOverrides.put(
"maxStatementsPerConnection",
"20");
13811 SQLiteConfig config =
new SQLiteConfig();
13812 config.setSynchronous(SQLiteConfig.SynchronousMode.OFF);
13813 config.setReadUncommitted(
true);
13814 config.enforceForeignKeys(
true);
13815 SQLiteDataSource unpooled =
new SQLiteDataSource(config);
13816 unpooled.setUrl(
"jdbc:sqlite:" + dbPath);
13817 setPooledDataSource((PooledDataSource) DataSources.pooledDataSource(unpooled, configurationOverrides));
13821 public CaseDbConnection getPooledConnection() throws SQLException {
13823 if (CaseDbTransaction.hasOpenTransaction(Thread.currentThread().getId())) {
13825 if (!Thread.currentThread().getName().contains(
"ImageGallery")) {
13826 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());
13829 return new SQLiteConnection(getPooledDataSource().getConnection());
13837 private final class PostgreSQLConnections
extends ConnectionPool {
13839 PostgreSQLConnections(CaseDbConnectionInfo info, String dbName)
throws PropertyVetoException, UnsupportedEncodingException {
13841 ComboPooledDataSource comboPooledDataSource =
new ComboPooledDataSource();
13842 comboPooledDataSource.setDriverClass(
"org.postgresql.Driver");
13844 String connectionURL =
"jdbc:postgresql://" + info.getHost() +
":" + Integer.valueOf(info.getPort()) +
"/"
13845 + URLEncoder.encode(dbName, StandardCharsets.UTF_8.toString());
13846 if (info.isSslEnabled()) {
13847 if (info.isSslVerify()) {
13848 if (info.getCustomSslValidationClassName().isBlank()) {
13849 connectionURL += CaseDatabaseFactory.SSL_VERIFY_DEFAULT_URL;
13852 connectionURL += CaseDatabaseFactory.getCustomPostrgesSslVerificationUrl(info.getCustomSslValidationClassName());
13855 connectionURL += CaseDatabaseFactory.SSL_NONVERIFY_URL;
13858 comboPooledDataSource.setJdbcUrl(connectionURL);
13859 comboPooledDataSource.setUser(info.getUserName());
13860 comboPooledDataSource.setPassword(info.getPassword());
13861 comboPooledDataSource.setAcquireIncrement(2);
13862 comboPooledDataSource.setInitialPoolSize(5);
13863 comboPooledDataSource.setMinPoolSize(5);
13868 comboPooledDataSource.setMaxPoolSize(20);
13869 comboPooledDataSource.setMaxStatements(200);
13870 comboPooledDataSource.setMaxStatementsPerConnection(20);
13871 setPooledDataSource(comboPooledDataSource);
13875 public CaseDbConnection getPooledConnection() throws SQLException {
13876 return new PostgreSQLConnection(getPooledDataSource().getConnection());
13883 abstract class CaseDbConnection
implements AutoCloseable {
13885 static final int SLEEP_LENGTH_IN_MILLISECONDS = 5000;
13886 static final int MAX_RETRIES = 20;
13888 private class CreateStatement
implements DbCommand {
13890 private final Connection connection;
13891 private Statement statement = null;
13893 CreateStatement(Connection connection) {
13894 this.connection = connection;
13897 Statement getStatement() {
13902 public void execute() throws SQLException {
13903 statement = connection.createStatement();
13907 private class SetAutoCommit
implements DbCommand {
13909 private final Connection connection;
13910 private final boolean mode;
13912 SetAutoCommit(Connection connection,
boolean mode) {
13913 this.connection = connection;
13918 public void execute() throws SQLException {
13919 connection.setAutoCommit(mode);
13923 private class Commit
implements DbCommand {
13925 private final Connection connection;
13927 Commit(Connection connection) {
13928 this.connection = connection;
13932 public void execute() throws SQLException {
13933 connection.commit();
13945 private class AggregateScoreTablePostgreSQLWriteLock
implements DbCommand {
13947 private final Connection connection;
13949 AggregateScoreTablePostgreSQLWriteLock(Connection connection) {
13950 this.connection = connection;
13954 public void execute() throws SQLException {
13955 PreparedStatement preparedStatement = connection.prepareStatement(
"LOCK TABLE ONLY tsk_aggregate_score in SHARE ROW EXCLUSIVE MODE");
13956 preparedStatement.execute();
13961 private class ExecuteQuery
implements DbCommand {
13963 private final Statement statement;
13964 private final String query;
13965 private ResultSet resultSet;
13967 ExecuteQuery(Statement statement, String query) {
13968 this.statement = statement;
13969 this.query = query;
13972 ResultSet getResultSet() {
13977 public void execute() throws SQLException {
13978 resultSet = statement.executeQuery(query);
13982 private class ExecutePreparedStatementQuery
implements DbCommand {
13984 private final PreparedStatement preparedStatement;
13985 private ResultSet resultSet;
13987 ExecutePreparedStatementQuery(PreparedStatement preparedStatement) {
13988 this.preparedStatement = preparedStatement;
13991 ResultSet getResultSet() {
13996 public void execute() throws SQLException {
13997 resultSet = preparedStatement.executeQuery();
14001 private class ExecutePreparedStatementUpdate
implements DbCommand {
14003 private final PreparedStatement preparedStatement;
14005 ExecutePreparedStatementUpdate(PreparedStatement preparedStatement) {
14006 this.preparedStatement = preparedStatement;
14010 public void execute() throws SQLException {
14011 preparedStatement.executeUpdate();
14015 private class ExecuteStatementUpdate
implements DbCommand {
14017 private final Statement statement;
14018 private final String updateCommand;
14020 ExecuteStatementUpdate(Statement statement, String updateCommand) {
14021 this.statement = statement;
14022 this.updateCommand = updateCommand;
14026 public void execute() throws SQLException {
14027 statement.executeUpdate(updateCommand);
14031 private class ExecuteStatementUpdateGenerateKeys
implements DbCommand {
14033 private final Statement statement;
14034 private final int generateKeys;
14035 private final String updateCommand;
14037 ExecuteStatementUpdateGenerateKeys(Statement statement, String updateCommand,
int generateKeys) {
14038 this.statement = statement;
14039 this.generateKeys = generateKeys;
14040 this.updateCommand = updateCommand;
14044 public void execute() throws SQLException {
14045 statement.executeUpdate(updateCommand, generateKeys);
14049 private class PrepareStatement
implements DbCommand {
14051 private final Connection connection;
14052 private final String input;
14053 private PreparedStatement preparedStatement = null;
14055 PrepareStatement(Connection connection, String input) {
14056 this.connection = connection;
14057 this.input = input;
14060 PreparedStatement getPreparedStatement() {
14061 return preparedStatement;
14065 public void execute() throws SQLException {
14066 preparedStatement = connection.prepareStatement(input);
14070 private class PrepareStatementGenerateKeys
implements DbCommand {
14072 private final Connection connection;
14073 private final String input;
14074 private final int generateKeys;
14075 private PreparedStatement preparedStatement = null;
14077 PrepareStatementGenerateKeys(Connection connection, String input,
int generateKeysInput) {
14078 this.connection = connection;
14079 this.input = input;
14080 this.generateKeys = generateKeysInput;
14083 PreparedStatement getPreparedStatement() {
14084 return preparedStatement;
14088 public void execute() throws SQLException {
14089 preparedStatement = connection.prepareStatement(input, generateKeys);
14093 abstract void executeCommand(DbCommand command)
throws SQLException;
14095 private final Connection connection;
14096 private final Map<PREPARED_STATEMENT, PreparedStatement> preparedStatements;
14097 private final Map<String, PreparedStatement> adHocPreparedStatements;
14099 CaseDbConnection(Connection connection) {
14100 this.connection = connection;
14101 preparedStatements =
new EnumMap<PREPARED_STATEMENT, PreparedStatement>(PREPARED_STATEMENT.class);
14102 adHocPreparedStatements =
new HashMap<>();
14106 return this.connection != null;
14109 PreparedStatement getPreparedStatement(PREPARED_STATEMENT statementKey)
throws SQLException {
14110 return getPreparedStatement(statementKey, Statement.NO_GENERATED_KEYS);
14113 PreparedStatement getPreparedStatement(PREPARED_STATEMENT statementKey,
int generateKeys)
throws SQLException {
14115 PreparedStatement statement;
14116 if (this.preparedStatements.containsKey(statementKey)) {
14117 statement = this.preparedStatements.get(statementKey);
14119 statement = prepareStatement(statementKey.getSQL(), generateKeys);
14120 this.preparedStatements.put(statementKey, statement);
14136 PreparedStatement getPreparedStatement(String sqlStatement,
int generateKeys)
throws SQLException {
14137 PreparedStatement statement;
14138 String statementKey =
"SQL:" + sqlStatement +
" Key:" + generateKeys;
14139 if (adHocPreparedStatements.containsKey(statementKey) && !adHocPreparedStatements.get(statementKey).isClosed()) {
14140 statement = this.adHocPreparedStatements.get(statementKey);
14142 statement = prepareStatement(sqlStatement, generateKeys);
14143 this.adHocPreparedStatements.put(statementKey, statement);
14148 PreparedStatement prepareStatement(String sqlStatement,
int generateKeys)
throws SQLException {
14149 PrepareStatement prepareStatement =
new PrepareStatement(this.getConnection(), sqlStatement);
14150 executeCommand(prepareStatement);
14151 return prepareStatement.getPreparedStatement();
14154 Statement createStatement() throws SQLException {
14155 CreateStatement createStatement =
new CreateStatement(this.connection);
14156 executeCommand(createStatement);
14157 return createStatement.getStatement();
14161 SetAutoCommit setAutoCommit =
new SetAutoCommit(connection,
false);
14162 executeCommand(setAutoCommit);
14165 void commitTransaction() throws SQLException {
14166 Commit commit =
new Commit(connection);
14167 executeCommand(commit);
14169 SetAutoCommit setAutoCommit =
new SetAutoCommit(connection,
true);
14170 executeCommand(setAutoCommit);
14178 void rollbackTransaction() {
14180 connection.rollback();
14181 }
catch (SQLException e) {
14182 logger.log(Level.SEVERE,
"Error rolling back transaction", e);
14185 connection.setAutoCommit(
true);
14186 }
catch (SQLException e) {
14187 logger.log(Level.SEVERE,
"Error restoring auto-commit", e);
14198 void rollbackTransactionWithThrow() throws SQLException {
14200 connection.rollback();
14202 connection.setAutoCommit(
true);
14214 void getAggregateScoreTableWriteLock() throws SQLException, TskCoreException {
14217 AggregateScoreTablePostgreSQLWriteLock tableWriteLock =
new AggregateScoreTablePostgreSQLWriteLock(connection);
14218 executeCommand(tableWriteLock);
14225 throw new TskCoreException(
"Unknown DB Type: " +
getDatabaseType().name());
14229 ResultSet
executeQuery(Statement statement, String query)
throws SQLException {
14230 ExecuteQuery queryCommand =
new ExecuteQuery(statement, query);
14231 executeCommand(queryCommand);
14232 return queryCommand.getResultSet();
14244 ResultSet
executeQuery(PreparedStatement statement)
throws SQLException {
14245 ExecutePreparedStatementQuery executePreparedStatementQuery =
new ExecutePreparedStatementQuery(statement);
14246 executeCommand(executePreparedStatementQuery);
14247 return executePreparedStatementQuery.getResultSet();
14250 void executeUpdate(Statement statement, String update)
throws SQLException {
14251 executeUpdate(statement, update, Statement.NO_GENERATED_KEYS);
14254 void executeUpdate(Statement statement, String update,
int generateKeys)
throws SQLException {
14255 ExecuteStatementUpdate executeStatementUpdate =
new ExecuteStatementUpdate(statement, update);
14256 executeCommand(executeStatementUpdate);
14259 void executeUpdate(PreparedStatement statement)
throws SQLException {
14260 ExecutePreparedStatementUpdate executePreparedStatementUpdate =
new ExecutePreparedStatementUpdate(statement);
14261 executeCommand(executePreparedStatementUpdate);
14268 public void close() {
14270 for (PreparedStatement stmt : preparedStatements.values()) {
14271 closeStatement(stmt);
14273 for (PreparedStatement stmt : adHocPreparedStatements.values()) {
14274 closeStatement(stmt);
14276 connection.close();
14277 }
catch (SQLException ex) {
14278 logger.log(Level.SEVERE,
"Unable to close connection to case database", ex);
14282 Connection getConnection() {
14283 return this.connection;
14290 private final class SQLiteConnection
extends CaseDbConnection {
14292 private static final int DATABASE_LOCKED_ERROR = 0;
14293 private static final int SQLITE_BUSY_ERROR = 5;
14295 SQLiteConnection(Connection conn) {
14300 void executeCommand(DbCommand command)
throws SQLException {
14301 int retryCounter = 0;
14306 }
catch (SQLException ex) {
14307 if ((ex.getErrorCode() == SQLITE_BUSY_ERROR || ex.getErrorCode() == DATABASE_LOCKED_ERROR) && retryCounter < MAX_RETRIES) {
14314 Thread.sleep(SLEEP_LENGTH_IN_MILLISECONDS);
14315 }
catch (InterruptedException exp) {
14316 Logger.getLogger(SleuthkitCase.class.getName()).log(Level.WARNING,
"Unexpectedly unable to wait for database.", exp);
14329 private final class PostgreSQLConnection
extends CaseDbConnection {
14331 private final String COMMUNICATION_ERROR = PSQLState.COMMUNICATION_ERROR.getState();
14332 private final String SYSTEM_ERROR = PSQLState.SYSTEM_ERROR.getState();
14333 private final String UNKNOWN_STATE = PSQLState.UNKNOWN_STATE.getState();
14334 private static final int MAX_RETRIES = 3;
14336 PostgreSQLConnection(Connection conn) {
14341 void executeUpdate(Statement statement, String update,
int generateKeys)
throws SQLException {
14342 CaseDbConnection.ExecuteStatementUpdateGenerateKeys executeStatementUpdateGenerateKeys =
new CaseDbConnection.ExecuteStatementUpdateGenerateKeys(statement, update, generateKeys);
14343 executeCommand(executeStatementUpdateGenerateKeys);
14347 PreparedStatement prepareStatement(String sqlStatement,
int generateKeys)
throws SQLException {
14348 CaseDbConnection.PrepareStatementGenerateKeys prepareStatementGenerateKeys =
new CaseDbConnection.PrepareStatementGenerateKeys(this.getConnection(), sqlStatement, generateKeys);
14349 executeCommand(prepareStatementGenerateKeys);
14350 return prepareStatementGenerateKeys.getPreparedStatement();
14354 void executeCommand(DbCommand command)
throws SQLException {
14355 SQLException lastException = null;
14356 for (
int retries = 0; retries < MAX_RETRIES; retries++) {
14359 lastException = null;
14361 }
catch (SQLException ex) {
14362 lastException = ex;
14363 String sqlState = ex.getSQLState();
14364 if (sqlState == null || sqlState.equals(COMMUNICATION_ERROR) || sqlState.equals(SYSTEM_ERROR) || sqlState.equals(UNKNOWN_STATE)) {
14366 Thread.sleep(SLEEP_LENGTH_IN_MILLISECONDS);
14367 }
catch (InterruptedException exp) {
14368 Logger.getLogger(SleuthkitCase.class.getName()).log(Level.WARNING,
"Unexpectedly unable to wait for database.", exp);
14377 if (lastException != null) {
14378 throw lastException;
14416 private final CaseDbConnection connection;
14424 private Map<Long, ScoreChange> scoreChangeMap =
new HashMap<>();
14425 private List<Host> hostsAdded =
new ArrayList<>();
14426 private List<TimelineEventAddedEvent> timelineEvents =
new ArrayList<>();
14427 private List<OsAccount> accountsChanged =
new ArrayList<>();
14428 private List<OsAccount> accountsAdded =
new ArrayList<>();
14431 private List<Long> deletedOsAccountObjectIds =
new ArrayList<>();
14432 private List<Long> deletedResultObjectIds =
new ArrayList<>();
14435 private static Set<Long> threadsWithOpenTransaction =
new HashSet<>();
14436 private static final Object threadsWithOpenTransactionLock =
new Object();
14439 this.sleuthkitCase = sleuthkitCase;
14442 this.connection = sleuthkitCase.getConnection();
14444 synchronized (threadsWithOpenTransactionLock) {
14445 this.connection.beginTransaction();
14446 threadsWithOpenTransaction.add(Thread.currentThread().getId());
14448 }
catch (SQLException ex) {
14450 throw new TskCoreException(
"Failed to create transaction on case database", ex);
14462 CaseDbConnection getConnection() {
14463 return this.connection;
14471 void registerScoreChange(
ScoreChange scoreChange) {
14472 scoreChangeMap.put(scoreChange.
getObjectId(), scoreChange);
14480 if (timelineEvent != null) {
14481 timelineEvents.add(timelineEvent);
14490 void registerAddedHost(
Host host) {
14491 if (host != null) {
14492 this.hostsAdded.add(host);
14501 void registerChangedOsAccount(
OsAccount account) {
14502 if (account != null) {
14503 accountsChanged.add(account);
14512 void registerDeletedOsAccount(
long osAccountObjId) {
14513 deletedOsAccountObjectIds.add(osAccountObjId);
14521 void registerAddedOsAccount(
OsAccount account) {
14522 if (account != null) {
14523 accountsAdded.add(account);
14533 void registerMergedOsAccount(
long sourceOsAccountObjId,
long destinationOsAccountObjId) {
14543 void registerDeletedAnalysisResult(
long analysisResultObjId) {
14544 this.deletedResultObjectIds.add(analysisResultObjId);
14555 private static boolean hasOpenTransaction(
long threadId) {
14556 synchronized (threadsWithOpenTransactionLock) {
14557 return threadsWithOpenTransaction.contains(threadId);
14569 this.connection.commitTransaction();
14570 }
catch (SQLException ex) {
14571 throw new TskCoreException(
"Failed to commit transaction on case database", ex);
14575 if (!scoreChangeMap.isEmpty()) {
14576 Map<Long, List<ScoreChange>> changesByDataSource = scoreChangeMap.values().stream()
14578 for (Map.Entry<Long, List<ScoreChange>> entry : changesByDataSource.entrySet()) {
14582 if (!timelineEvents.isEmpty()) {
14584 sleuthkitCase.fireTSKEvent(evt);
14587 if (!hostsAdded.isEmpty()) {
14590 if (!accountsAdded.isEmpty()) {
14593 if (!accountsChanged.isEmpty()) {
14596 if (!accountsMerged.isEmpty()) {
14599 if (!deletedOsAccountObjectIds.isEmpty()) {
14602 if (!deletedResultObjectIds.isEmpty()) {
14616 this.connection.rollbackTransactionWithThrow();
14617 }
catch (SQLException ex) {
14618 throw new TskCoreException(
"Case database transaction rollback failed", ex);
14629 this.connection.close();
14631 synchronized (threadsWithOpenTransactionLock) {
14632 threadsWithOpenTransaction.remove(Thread.currentThread().getId());
14648 private ResultSet resultSet;
14649 private CaseDbConnection connection;
14651 private CaseDbQuery(String query)
throws TskCoreException {
14652 this(query,
false);
14655 private CaseDbQuery(String query,
boolean allowWriteQuery)
throws TskCoreException {
14656 if (!allowWriteQuery) {
14657 if (!query.regionMatches(
true, 0,
"SELECT", 0,
"SELECT".length())) {
14658 throw new TskCoreException(
"Unsupported query: Only SELECT queries are supported.");
14664 connection = connections.getConnection();
14665 resultSet = connection.executeQuery(connection.createStatement(), query);
14666 }
catch (SQLException ex) {
14668 throw new TskCoreException(
"Error executing query: ", ex);
14669 }
catch (TskCoreException ex) {
14685 public void close() throws TskCoreException {
14687 if (resultSet != null) {
14688 final Statement statement = resultSet.getStatement();
14689 if (statement != null) {
14694 closeConnection(connection);
14695 }
catch (SQLException ex) {
14696 throw new TskCoreException(
"Error closing query: ", ex);
14712 sleuthkitCaseErrorObservers.add(observer);
14724 int i = sleuthkitCaseErrorObservers.indexOf(observer);
14726 sleuthkitCaseErrorObservers.remove(i);
14740 for (
ErrorObserver observer : sleuthkitCaseErrorObservers) {
14741 if (observer != null) {
14743 observer.receiveError(context, errorMessage);
14744 }
catch (Exception ex) {
14745 logger.log(Level.SEVERE,
"Observer client unable to receive message: {0}, {1}",
new Object[]{context, errorMessage, ex});
14777 private final String contextString;
14779 private Context(String context) {
14780 this.contextString = context;
14784 return contextString;
14788 void receiveError(String context, String errorMessage);
14802 long getDataSourceObjectId(
long objectId) {
14804 CaseDbConnection connection = connections.getConnection();
14806 return getDataSourceObjectId(connection, objectId);
14808 closeConnection(connection);
14810 }
catch (TskCoreException ex) {
14811 logger.log(Level.SEVERE,
"Error getting data source object id for a file", ex);
14827 CaseDbConnection connection = null;
14828 ResultSet rs = null;
14831 connection = connections.getConnection();
14834 PreparedStatement statement = connection.getPreparedStatement(PREPARED_STATEMENT.SELECT_MAX_OBJECT_ID);
14835 rs = connection.executeQuery(statement);
14838 id = rs.getLong(
"max_obj_id");
14841 }
catch (SQLException e) {
14842 throw new TskCoreException(
"Error getting last object id", e);
14844 closeResultSet(rs);
14845 closeConnection(connection);
14865 CaseDbConnection connection = null;
14866 Statement s = null;
14867 ResultSet rs = null;
14870 connection = connections.getConnection();
14871 s = connection.createStatement();
14872 rs = connection.executeQuery(s,
"SELECT * FROM tsk_files WHERE " + sqlWhereClause);
14873 List<FsContent> results =
new ArrayList<FsContent>();
14874 List<AbstractFile> temp = resultSetToAbstractFiles(rs, connection);
14875 for (AbstractFile f : temp) {
14878 results.add((FsContent) f);
14882 }
catch (SQLException e) {
14883 throw new TskCoreException(
"SQLException thrown when calling 'SleuthkitCase.findFilesWhere().", e);
14885 closeResultSet(rs);
14887 closeConnection(connection);
14905 CaseDbConnection connection = null;
14906 Statement s = null;
14907 ResultSet rs = null;
14910 connection = connections.getConnection();
14911 s = connection.createStatement();
14912 rs = connection.executeQuery(s,
"SELECT artifact_type_id FROM blackboard_artifact_types WHERE type_name = '" + artifactTypeName +
"'");
14915 typeId = rs.getInt(
"artifact_type_id");
14918 }
catch (SQLException ex) {
14919 throw new TskCoreException(
"Error getting artifact type id", ex);
14921 closeResultSet(rs);
14923 closeConnection(connection);
14956 public int addArtifactType(String artifactTypeName, String displayName)
throws TskCoreException {
14959 }
catch (TskDataException ex) {
14960 throw new TskCoreException(
"Failed to add artifact type.", ex);
14978 public int addAttrType(String attrTypeString, String displayName)
throws TskCoreException {
14981 }
catch (TskDataException ex) {
14982 throw new TskCoreException(
"Couldn't add new attribute type");
14998 CaseDbConnection connection = null;
14999 Statement s = null;
15000 ResultSet rs = null;
15003 connection = connections.getConnection();
15004 s = connection.createStatement();
15005 rs = connection.executeQuery(s,
"SELECT attribute_type_id FROM blackboard_attribute_types WHERE type_name = '" + attrTypeName +
"'");
15008 typeId = rs.getInt(
"attribute_type_id");
15011 }
catch (SQLException ex) {
15012 throw new TskCoreException(
"Error getting attribute type id", ex);
15014 closeResultSet(rs);
15016 closeConnection(connection);
15035 CaseDbConnection connection = null;
15036 Statement s = null;
15037 ResultSet rs = null;
15040 connection = connections.getConnection();
15041 s = connection.createStatement();
15042 rs = connection.executeQuery(s,
"SELECT type_name FROM blackboard_attribute_types WHERE attribute_type_id = " + attrTypeID);
15044 return rs.getString(
"type_name");
15046 throw new TskCoreException(
"No type with that id");
15048 }
catch (SQLException ex) {
15049 throw new TskCoreException(
"Error getting or creating a attribute type name", ex);
15051 closeResultSet(rs);
15053 closeConnection(connection);
15072 CaseDbConnection connection = null;
15073 Statement s = null;
15074 ResultSet rs = null;
15077 connection = connections.getConnection();
15078 s = connection.createStatement();
15079 rs = connection.executeQuery(s,
"SELECT display_name FROM blackboard_attribute_types WHERE attribute_type_id = " + attrTypeID);
15081 return rs.getString(
"display_name");
15083 throw new TskCoreException(
"No type with that id");
15085 }
catch (SQLException ex) {
15086 throw new TskCoreException(
"Error getting or creating a attribute type name", ex);
15088 closeResultSet(rs);
15090 closeConnection(connection);
15125 public ResultSet
runQuery(String query)
throws SQLException {
15126 CaseDbConnection connection = null;
15129 connection = connections.getConnection();
15130 return connection.executeQuery(connection.createStatement(), query);
15131 }
catch (TskCoreException ex) {
15132 throw new SQLException(
"Error getting connection for ad hoc query", ex);
15136 closeConnection(connection);
15152 final Statement statement = resultSet.getStatement();
15154 if (statement != null) {
15176 public LayoutFile addCarvedFile(String carvedFileName,
long carvedFileSize,
long containerId, List<TskFileRange> data)
throws TskCoreException {
15179 files.add(carvedFile);
15183 || parent instanceof
Volume
15184 || parent instanceof
Image) {
15187 throw new TskCoreException(String.format(
"Parent (id =%d) is not an file system, volume or image", containerId));
15206 public List<LayoutFile>
addCarvedFiles(List<CarvedFileContainer> filesToAdd)
throws TskCoreException {
15210 carvedFiles.add(carvedFile);
15215 || parent instanceof
Volume
15216 || parent instanceof
Image) {
15219 throw new TskCoreException(String.format(
"Parent (id =%d) is not an file system, volume or image", parent.
getId()));
15255 long size,
long ctime,
long crtime,
long atime,
long mtime,
15256 boolean isFile, AbstractFile parentFile,
15257 String rederiveDetails, String toolName, String toolVersion, String otherDetails)
throws TskCoreException {
15258 return addDerivedFile(fileName, localPath, size, ctime, crtime, atime, mtime,
15259 isFile, parentFile, rederiveDetails, toolName, toolVersion,
15294 long size,
long ctime,
long crtime,
long atime,
long mtime,
15295 String md5,
FileKnown known, String mimeType,
15299 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime,
15300 md5, null, known, mimeType, isFile, encodingType,
15301 parent, transaction);
15330 long size,
long ctime,
long crtime,
long atime,
long mtime,
15333 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime, isFile,
15358 long size,
long ctime,
long crtime,
long atime,
long mtime,
15360 AbstractFile parent)
throws TskCoreException {
15361 return addLocalFile(fileName, localPath, size, ctime, crtime, atime, mtime,
15383 return this.caseHandle.initAddImageProcess(timezone, addUnallocSpace, noFatFsOrphans,
"", null,
this);
15400 }
catch (TskCoreException ex) {
15401 logger.log(Level.SEVERE,
"Error loading all file systems for image with ID {0}", image.
getId());
15402 return new ArrayList<>();
15424 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.
TagName addOrUpdateTagName(String displayName, String description, TagName.HTML_COLOR color, TskData.FileKnown knownStatus)
static Significance fromID(int id)
BlackboardArtifact getArtifactByArtifactId(long 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, Host host, String password, CaseDbTransaction transaction)
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)
static SleuthkitCase openCase(String dbPath, ContentStreamProvider provider, String lockingApplicationName)
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)
static SleuthkitCase newCase(String dbPath, ContentStreamProvider contentProvider, String lockingApplicationName)
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)
AddImageProcess makeAddImageProcess(String timeZone, boolean addUnallocSpace, boolean noFatFsOrphans, String imageCopyPath, String password)
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)
Image addImageInfo(long deviceObjId, List< String > imageFilePaths, String timeZone, Host host, String password)
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 TagType valueOf(byte type)
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()
void updateFile(long fileObjId, long size, long mtime, long atime, long ctime, long crtime, String userSid, Long osAcctObjId)
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()