Autopsy  4.17.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
JythonModuleLoader.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2014 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.python;
20 
21 import java.io.File;
22 import java.io.FileNotFoundException;
23 import java.io.FilenameFilter;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Scanner;
29 import java.util.Set;
30 import java.util.logging.Level;
31 import java.util.regex.Matcher;
32 import org.openide.DialogDisplayer;
33 import org.openide.NotifyDescriptor;
34 import org.openide.modules.InstalledFileLocator;
35 import org.openide.util.NbBundle;
36 import org.openide.util.NbBundle.Messages;
37 import org.python.util.PythonInterpreter;
44 import java.io.BufferedReader;
45 import java.io.FileReader;
46 
51 public final class JythonModuleLoader {
52 
53  private static final Logger logger = Logger.getLogger(JythonModuleLoader.class.getName());
54 
61  public static synchronized List<IngestModuleFactory> getIngestModuleFactories() {
63  }
64 
71  public static synchronized List<GeneralReportModule> getGeneralReportModules() {
73  }
74  @Messages({"JythonModuleLoader.pythonInterpreterError.title=Python Modules",
75  "JythonModuleLoader.pythonInterpreterError.msg=Failed to load python modules, See log for more details"})
76  private static <T> List<T> getInterfaceImplementations(LineFilter filter, Class<T> interfaceClass) {
77  List<T> objects = new ArrayList<>();
78  Set<File> pythonModuleDirs = new HashSet<>();
79  PythonInterpreter interpreter = null;
80  // This method has previously thrown unchecked exceptions when it could not load because of non-latin characters.
81  try {
82  interpreter = new PythonInterpreter();
83  } catch (Exception ex) {
84  logger.log(Level.SEVERE, "Failed to load python Intepreter. Cannot load python modules", ex);
86  MessageNotifyUtil.Notify.show(Bundle.JythonModuleLoader_pythonInterpreterError_title(),Bundle.JythonModuleLoader_pythonInterpreterError_msg(), MessageNotifyUtil.MessageType.ERROR);
87  }
88  return objects;
89  }
90  // add python modules from 'autospy/build/cluster/InternalPythonModules' folder
91  // which are copied from 'autopsy/*/release/InternalPythonModules' folders.
92  for (File f : InstalledFileLocator.getDefault().locateAll("InternalPythonModules", "org.sleuthkit.autopsy.core", false)) { //NON-NLS
93  Collections.addAll(pythonModuleDirs, f.listFiles());
94  }
95  // add python modules from 'testuserdir/python_modules' folder
96  Collections.addAll(pythonModuleDirs, new File(PlatformUtil.getUserPythonModulesPath()).listFiles());
97 
98  for (File file : pythonModuleDirs) {
99  if (file.isDirectory()) {
100  File[] pythonScripts = file.listFiles(new PythonScriptFileFilter());
101  for (File script : pythonScripts) {
102  try (Scanner fileScanner = new Scanner(new BufferedReader(new FileReader(script)))) {
103  while (fileScanner.hasNextLine()) {
104  String line = fileScanner.nextLine();
105  if (line.startsWith("class ") && filter.accept(line)) { //NON-NLS
106  String className = line.substring(6, line.indexOf("("));
107  try {
108  objects.add(createObjectFromScript(interpreter, script, className, interfaceClass));
109  } catch (Exception ex) {
110  logger.log(Level.SEVERE, String.format("Failed to load %s from %s", className, script.getAbsolutePath()), ex); //NON-NLS
111  // NOTE: using ex.toString() because the current version is always returning null for ex.getMessage().
112  DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
113  NbBundle.getMessage(JythonModuleLoader.class, "JythonModuleLoader.errorMessages.failedToLoadModule", className, ex.toString()),
114  NotifyDescriptor.ERROR_MESSAGE));
115  }
116  }
117  }
118  } catch (FileNotFoundException ex) {
119  logger.log(Level.SEVERE, String.format("Failed to open %s", script.getAbsolutePath()), ex); //NON-NLS
120  DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
121  NbBundle.getMessage(JythonModuleLoader.class, "JythonModuleLoader.errorMessages.failedToOpenModule", script.getAbsolutePath()),
122  NotifyDescriptor.ERROR_MESSAGE));
123  }
124  }
125  }
126  }
127  return objects;
128  }
129 
130  private static <T> T createObjectFromScript(PythonInterpreter interpreter, File script, String className, Class<T> interfaceClass) {
131  // Add the directory where the Python script resides to the Python
132  // module search path to allow the script to use other scripts bundled
133  // with it.
134  interpreter.exec("import sys"); //NON-NLS
135  String path = Matcher.quoteReplacement(script.getParent());
136  interpreter.exec("sys.path.append('" + path + "')"); //NON-NLS
137  String moduleName = script.getName().replaceAll("\\.py$", ""); //NON-NLS
138 
139  // reload the module so that the changes made to it can be loaded.
140  interpreter.exec("import " + moduleName); //NON-NLS
141  interpreter.exec("reload(" + moduleName + ")"); //NON-NLS
142 
143  // Importing the appropriate class from the Py Script which contains multiple classes.
144  interpreter.exec("from " + moduleName + " import " + className); //NON-NLS
145  interpreter.exec("obj = " + className + "()"); //NON-NLS
146 
147  T obj = interpreter.get("obj", interfaceClass); //NON-NLS
148 
149  // Remove the directory where the Python script resides from the Python
150  // module search path.
151  interpreter.exec("sys.path.remove('" + path + "')"); //NON-NLS
152 
153  return obj;
154  }
155 
156  private static class PythonScriptFileFilter implements FilenameFilter {
157 
158  @Override
159  public boolean accept(File dir, String name) {
160  return name.endsWith(".py"); //NON-NLS
161  } //NON-NLS
162  }
163 
164  private static interface LineFilter {
165 
166  boolean accept(String line);
167  }
168 
169  private static class IngestModuleFactoryDefFilter implements LineFilter {
170 
171  @Override
172  public boolean accept(String line) {
173  return (line.contains("IngestModuleFactoryAdapter") || line.contains("IngestModuleFactory")); //NON-NLS
174  }
175  }
176 
177  private static class GeneralReportModuleDefFilter implements LineFilter {
178 
179  @Override
180  public boolean accept(String line) {
181  return (line.contains("GeneralReportModuleAdapter") || line.contains("GeneralReportModule")); //NON-NLS
182  }
183  }
184 }
static< T > List< T > getInterfaceImplementations(LineFilter filter, Class< T > interfaceClass)
static synchronized List< IngestModuleFactory > getIngestModuleFactories()
static< T > T createObjectFromScript(PythonInterpreter interpreter, File script, String className, Class< T > interfaceClass)
static synchronized List< GeneralReportModule > getGeneralReportModules()
synchronized static Logger getLogger(String name)
Definition: Logger.java:124
static void show(String title, String message, MessageType type, ActionListener actionListener)

Copyright © 2012-2021 Basis Technology. Generated on: Tue Jan 19 2021
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.