Restrict import paths to not use random python libs in the system

This commit is contained in:
Michael Zanetti 2020-07-23 17:29:17 +02:00
parent 75f4877f82
commit be01d4c802

View File

@ -270,15 +270,27 @@ bool PythonIntegrationPlugin::loadScript(const QString &scriptFile)
m_nymeaModule = PyImport_ImportModule("nymea"); m_nymeaModule = PyImport_ImportModule("nymea");
// Set up import path for the plugin directory // Set up import path for the plugin directory
// We intentionally strip site-packages and dist-packages because
// that's too unpredictive in distribution. Instead all dependencies
// should be installed into the plugins "modules" subdir.
PyObject* sysPath = PySys_GetObject("path"); PyObject* sysPath = PySys_GetObject("path");
PyObject* pluginImportPath = PyUnicode_FromString(fi.absolutePath().toUtf8()); QStringList importPaths;
PyList_Append(sysPath, pluginImportPath); for (int i = 0; i < PyList_Size(sysPath); i++) {
Py_DECREF(pluginImportPath); QString path = QString::fromUtf8(PyUnicode_AsUTF8(PyList_GetItem(sysPath, i)));
if (!path.contains("site-packages") && !path.contains("dist-packages")) {
importPaths.append(path);
}
}
importPaths.append(fi.absolutePath());
importPaths.append(QString("%1/modules/").arg(fi.absolutePath()));
// Set up import path for the "modules" subdir in the plugin directory PyObject* pluginPaths = PyList_New(importPaths.length());
PyObject* pluginModulesImportPath = PyUnicode_FromString(QString("%1/modules/").arg(fi.absolutePath()).toUtf8()); for (int i = 0; i < importPaths.length(); i++) {
PyList_Append(sysPath, pluginModulesImportPath); const QString &path = importPaths.at(i);
Py_DECREF(pluginModulesImportPath); PyObject *pyPath = PyUnicode_FromString(path.toUtf8());
PyList_SetItem(pluginPaths, i, pyPath);
}
PySys_SetObject("path", pluginPaths);
// Import the plugin // Import the plugin
m_pluginModule = PyImport_ImportModule(fi.baseName().toUtf8()); m_pluginModule = PyImport_ImportModule(fi.baseName().toUtf8());