mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-10-20 14:08:20 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4afd257371 | ||
|
|
4a0d5e5edd | ||
|
|
069bd402d9 | ||
|
|
6c791532c6 |
No files matched your search
+25
-3
@@ -47,7 +47,7 @@ while getopts ":dpa:snt:xbc:i:j:Tuh" opt; do
|
||||
u )
|
||||
export BUILD_TARGET="universal"
|
||||
;;
|
||||
h ) echo "Usage: ./build_release_macos.sh [-d]"
|
||||
h ) echo "Usage: ./build_release_macos.sh [-d] [-- CMAKE_ARGS...]"
|
||||
echo " -d: Build deps only"
|
||||
echo " -a: Set ARCHITECTURE (arm64 or x86_64 or universal)"
|
||||
echo " -s: Build slicer only"
|
||||
@@ -60,13 +60,33 @@ while getopts ":dpa:snt:xbc:i:j:Tuh" opt; do
|
||||
echo " -i: Add a prefix to ignore during CMake dependency discovery (repeatable), defaults to /opt/local:/usr/local:/opt/homebrew"
|
||||
echo " -j: Set the number of parallel build jobs (CMAKE_BUILD_PARALLEL_LEVEL)"
|
||||
echo " -T: Build and run tests (set ORCA_TESTS_BUILD_ONLY=1 to build without running)"
|
||||
echo " -- CMAKE_ARGS...: pass everything after '--' to the cmake configure step of the deps (-d) and slicer (-s) builds,"
|
||||
echo " e.g. -DDESTDIR=<dir> for the deps, -DCMAKE_PREFIX_PATH=<dir>/usr/local -DSLIC3R_PCH=OFF for the slicer, --fresh."
|
||||
echo " They come last on the cmake command line. Use absolute paths: cmake runs in the build directory."
|
||||
exit 0
|
||||
;;
|
||||
: )
|
||||
echo "Option -${OPTARG} requires an argument, aborting."
|
||||
exit 1
|
||||
;;
|
||||
* )
|
||||
echo "Unknown option -${OPTARG}, aborting. CMake arguments must follow '--'."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# getopts stops at '--'; whatever follows is handed to cmake unchanged.
|
||||
if [[ ${OPTIND} -le $# ]] ; then
|
||||
separator_index=$((OPTIND-1))
|
||||
if [[ "${!separator_index}" != "--" ]] ; then
|
||||
echo "Unexpected argument '${!OPTIND}': cmake arguments must follow '--', aborting."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
shift $((OPTIND-1))
|
||||
EXTRA_CMAKE_ARGS=("$@")
|
||||
|
||||
# Set defaults
|
||||
|
||||
if [ -z "$ARCH" ]; then
|
||||
@@ -211,7 +231,8 @@ function build_deps() {
|
||||
-DCMAKE_OSX_DEPLOYMENT_TARGET="${OSX_DEPLOYMENT_TARGET}" \
|
||||
-DCMAKE_IGNORE_PREFIX_PATH="${CMAKE_IGNORE_PREFIX_PATH}" \
|
||||
"${CMAKE_CCACHE_ARGS[@]}" \
|
||||
${CMAKE_POLICY_COMPAT}
|
||||
${CMAKE_POLICY_COMPAT} \
|
||||
"${EXTRA_CMAKE_ARGS[@]}"
|
||||
fi
|
||||
cmake --build . --config "$BUILD_CONFIG" --target deps
|
||||
)
|
||||
@@ -314,7 +335,8 @@ function build_slicer() {
|
||||
-DCMAKE_OSX_DEPLOYMENT_TARGET="${OSX_DEPLOYMENT_TARGET}" \
|
||||
-DCMAKE_IGNORE_PREFIX_PATH="${CMAKE_IGNORE_PREFIX_PATH}" \
|
||||
"${CMAKE_CCACHE_ARGS[@]}" \
|
||||
${CMAKE_POLICY_COMPAT}
|
||||
${CMAKE_POLICY_COMPAT} \
|
||||
"${EXTRA_CMAKE_ARGS[@]}"
|
||||
fi
|
||||
cmake --build . --config "$BUILD_CONFIG" --target "$SLICER_BUILD_TARGET"
|
||||
)
|
||||
|
||||
@@ -122,8 +122,8 @@ void update_arrange_params(ArrangeParams& params, const DynamicPrintConfig* prin
|
||||
|
||||
void update_selected_items_inflation(ArrangePolygons& selected, const DynamicPrintConfig* print_cfg, ArrangeParams& params) {
|
||||
// do not inflate brim_width. Objects are allowed to have overlapped brim.
|
||||
// A brim reaching the printable area's edge is fine, so measure against the full bed.
|
||||
BoundingBox bedbb = Polygon(get_bed_shape(*print_cfg)).bounding_box();
|
||||
Points bedpts = get_shrink_bedpts(print_cfg, params);
|
||||
BoundingBox bedbb = Polygon(bedpts).bounding_box();
|
||||
// set obj distance for auto seq_print
|
||||
if (params.is_seq_print) {
|
||||
bool all_objects_are_short = std::all_of(selected.begin(), selected.end(), [&](ArrangePolygon& ap) { return ap.height < params.nozzle_height; });
|
||||
@@ -144,30 +144,14 @@ void update_selected_items_inflation(ArrangePolygons& selected, const DynamicPri
|
||||
// 3. otherwise, use each object's own brim width
|
||||
ap.inflation = params.min_obj_distance != 0 ? params.min_obj_distance / 2 :
|
||||
plate_has_tree_support ? scaled(brim_max / 2) : scaled(ap.brim_width);
|
||||
if (params.min_obj_distance != 0)
|
||||
return; // an explicit object distance is the user's call, not ours to shrink
|
||||
// An item cannot be larger than the printable area, inflation included. Inflating
|
||||
// an almost bed filling item would leave it too big to ever be placed.
|
||||
BoundingBox apbb = ap.poly.contour.bounding_box();
|
||||
auto diffx = bedbb.size().x() - apbb.size().x();
|
||||
auto diffy = bedbb.size().y() - apbb.size().y();
|
||||
ap.inflation = std::max<coord_t>(0, std::min({ ap.inflation, diffx / 2, diffy / 2 }));
|
||||
});
|
||||
|
||||
// Give the bed margin, which the arrange bed keeps from the printable area, back
|
||||
// where the largest item needs it. The skirt keeps its room: pushing a skirt off
|
||||
// the bed is worse than saying the item does not fit.
|
||||
if (!selected.empty()) {
|
||||
coord_t max_width = 0, max_height = 0;
|
||||
for (const ArrangePolygon &ap : selected) {
|
||||
BoundingBox apbb = ap.poly.contour.bounding_box();
|
||||
max_width = std::max(max_width, apbb.size().x() + 2 * ap.inflation);
|
||||
max_height = std::max(max_height, apbb.size().y() + 2 * ap.inflation);
|
||||
BoundingBox apbb = ap.poly.contour.bounding_box();
|
||||
auto diffx = bedbb.size().x() - apbb.size().x() - 5;
|
||||
auto diffy = bedbb.size().y() - apbb.size().y() - 5;
|
||||
if (diffx > 0 && diffy > 0) {
|
||||
auto min_diff = std::min(diffx, diffy);
|
||||
ap.inflation = std::min(min_diff / 2, ap.inflation);
|
||||
}
|
||||
auto margin = [](coord_t bed, coord_t item) { return std::max(0., unscale<double>(bed - item) / 2.); };
|
||||
params.bed_shrink_x = std::min<double>(params.bed_shrink_x, std::max<double>(params.brim_skirt_distance, margin(bedbb.size().x(), max_width)));
|
||||
params.bed_shrink_y = std::min<double>(params.bed_shrink_y, std::max<double>(params.brim_skirt_distance, margin(bedbb.size().y(), max_height)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void update_unselected_items_inflation(ArrangePolygons& unselected, const DynamicPrintConfig* print_cfg, const ArrangeParams& params)
|
||||
|
||||
@@ -213,29 +213,13 @@ int find_plane_at_point(const std::vector<LayOnFacePlane> &planes, const Transfo
|
||||
return -1;
|
||||
}
|
||||
|
||||
Transform3d lay_on_face_rotation(const Vec3d &normal, const Transform3d &instance_matrix_no_offset)
|
||||
{
|
||||
// Normal in instance coordinates: a normal transforms by the inverse transpose.
|
||||
const Vec3d tnormal = (instance_matrix_no_offset.matrix().block(0, 0, 3, 3).inverse().transpose() * normal).normalized();
|
||||
const Vec3d down = -Vec3d::UnitZ();
|
||||
|
||||
// A face already pointing straight up needs a half turn, and every horizontal axis does
|
||||
// that equally well. setFromTwoVectors() resolves the choice through an SVD whose null
|
||||
// space is the whole XY plane, so the axis follows rounding noise and the object lands at
|
||||
// an arbitrary angle in the plate plane. Turn it over about X instead, which keeps the
|
||||
// footprint the object already had.
|
||||
if (tnormal.dot(down) < -1. + 1e-9)
|
||||
return Transform3d(Eigen::AngleAxisd(PI, Vec3d::UnitX()));
|
||||
|
||||
return Transform3d(Eigen::Quaterniond().setFromTwoVectors(tnormal, down));
|
||||
}
|
||||
|
||||
void lay_on_face(ModelObject &object, size_t instance_idx, const Vec3d &normal)
|
||||
{
|
||||
ModelInstance &instance = *object.instances[instance_idx];
|
||||
const Geometry::Transformation &trafo = instance.get_transformation();
|
||||
// Same rotation as Selection::flattening_rotate(), which the gizmo uses.
|
||||
const Transform3d rotation = lay_on_face_rotation(normal, trafo.get_matrix_no_offset());
|
||||
// Same rotation as Selection::flattening_rotate(): turn the transformed normal to point down.
|
||||
const Vec3d tnormal = trafo.get_matrix().matrix().block(0, 0, 3, 3).inverse().transpose() * normal;
|
||||
const Transform3d rotation = Transform3d(Eigen::Quaterniond().setFromTwoVectors(tnormal, -Vec3d::UnitZ()));
|
||||
instance.set_transformation(Geometry::Transformation(trafo.get_offset_matrix() * rotation * trafo.get_matrix_no_offset()));
|
||||
// Drop this instance only: ensure_on_bed() skips instances without auto_drop and measures the first instance.
|
||||
object.translate_instance(instance_idx, -object.instance_bounding_box(instance_idx).min.z() * Vec3d::UnitZ());
|
||||
|
||||
@@ -46,10 +46,4 @@ int find_plane_at_point(const std::vector<LayOnFacePlane> &planes, const Transfo
|
||||
// the gizmo applies, then drops the instance so its lowest point is at z = 0.
|
||||
void lay_on_face(ModelObject &object, size_t instance_idx, const Vec3d &normal);
|
||||
|
||||
// The rotation that turns `normal` (object coordinates) to point down, given the instance's
|
||||
// rotation, scale and mirror. A face that already points straight up is turned over about X:
|
||||
// the axis setFromTwoVectors() picks there is arbitrary, and it lands the object at a random
|
||||
// angle in the plate plane.
|
||||
Transform3d lay_on_face_rotation(const Vec3d &normal, const Transform3d &instance_matrix_no_offset);
|
||||
|
||||
} // namespace Slic3r
|
||||
@@ -771,17 +771,6 @@ void ArrangeJob::finalize(bool canceled, std::exception_ptr &eptr) {
|
||||
if (canceled || eptr)
|
||||
return;
|
||||
|
||||
// Nothing could be placed: leave the plates and the instances exactly as they were.
|
||||
// Rebuilding the plates would only re-home the instances by their bounds, which moves
|
||||
// a too large item to whichever plate it happens to reach over.
|
||||
const bool nothing_arranged = !m_selected.empty() &&
|
||||
std::all_of(m_selected.begin(), m_selected.end(), [](const ArrangePolygon &ap) { return !ap.is_arranged(); });
|
||||
if (nothing_arranged) {
|
||||
m_plater->get_notification_manager()->close_notification_of_type(NotificationType::ArrangeOngoing);
|
||||
m_plater->m_arrange_running.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Unprintable items go to the last virtual bed
|
||||
int beds = 0;
|
||||
|
||||
@@ -881,13 +870,12 @@ void ArrangeJob::finalize(bool canceled, std::exception_ptr &eptr) {
|
||||
}
|
||||
m_plater->get_notification_manager()->close_notification_of_type(NotificationType::ArrangeOngoing);
|
||||
|
||||
//BBS: reload all objects due to arrange. Plates are never recycled here: arranging
|
||||
// must not remove a plate the user created, even when the arrange left it empty.
|
||||
//BBS: reload all objects due to arrange
|
||||
if (only_on_partplate) {
|
||||
plate_list.rebuild_plates_after_arrangement(false, true, current_plate_index);
|
||||
plate_list.rebuild_plates_after_arrangement(!only_on_partplate, true, current_plate_index);
|
||||
}
|
||||
else {
|
||||
plate_list.rebuild_plates_after_arrangement(false, true);
|
||||
plate_list.rebuild_plates_after_arrangement(!only_on_partplate, true);
|
||||
}
|
||||
|
||||
// unlock the plates we just locked
|
||||
|
||||
@@ -248,6 +248,7 @@ void FillBedJob::process(Ctl &ctl)
|
||||
if (m_object_idx == -1 || m_selected.empty()) return;
|
||||
|
||||
update_arrange_params(params, m_plater->config(), m_selected);
|
||||
m_bedpts = get_shrink_bedpts(m_plater->config(), params);
|
||||
|
||||
auto &partplate_list = m_plater->get_partplate_list();
|
||||
auto &print = wxGetApp().plater()->get_partplate_list().get_current_fff_print();
|
||||
@@ -259,8 +260,6 @@ void FillBedJob::process(Ctl &ctl)
|
||||
|
||||
update_selected_items_inflation(m_selected, m_plater->config(), params);
|
||||
update_unselected_items_inflation(m_unselected, m_plater->config(), params);
|
||||
// After the inflation, which may give back part of the bed margin.
|
||||
m_bedpts = get_shrink_bedpts(m_plater->config(), params);
|
||||
|
||||
bool do_stop = false;
|
||||
params.stopcondition = [&ctl, &do_stop]() {
|
||||
|
||||
@@ -7048,14 +7048,19 @@ void PartPlateList::postprocess_arrange_polygon(arrangement::ArrangePolygon& arr
|
||||
{
|
||||
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": bed_idx %1%, selected %2%, translation(x) %3%, (y) %4%") % arrange_polygon.bed_idx % selected % unscale<double>(arrange_polygon.translation(X)) % unscale<double>(arrange_polygon.translation(Y));
|
||||
|
||||
// UNARRANGED means the item could not be placed, so it has no bed to map onto and
|
||||
// must be left where the user had it. Moving it to a virtual bed here would shift
|
||||
// it off the plate, because no such plate is created for it afterwards.
|
||||
if (arrange_polygon.bed_idx == arrangement::UNARRANGED)
|
||||
return;
|
||||
|
||||
if ((selected) || (arrange_polygon.bed_idx != PartPlateList::MAX_PLATES_COUNT))
|
||||
{
|
||||
if (arrange_polygon.bed_idx == -1)
|
||||
{
|
||||
// outarea for large object
|
||||
arrange_polygon.bed_idx = m_plate_list.size();
|
||||
BoundingBox apbox = get_extents(arrange_polygon.transformed_poly()); // the item may have been rotated
|
||||
auto apbox_size = apbox.size();
|
||||
|
||||
arrange_polygon.translation(X) = 0.5 * apbox_size[0];
|
||||
arrange_polygon.translation(Y) = scaled<double>(static_cast<double>(m_plate_depth)) - 0.5 * apbox_size[1];
|
||||
}
|
||||
|
||||
arrange_polygon.row = arrange_polygon.bed_idx / m_plate_cols;
|
||||
arrange_polygon.col = arrange_polygon.bed_idx % m_plate_cols;
|
||||
arrange_polygon.translation(X) += scaled<double>(plate_stride_x() * arrange_polygon.col);
|
||||
|
||||
@@ -11034,17 +11034,7 @@ void Plater::priv::split_volume()
|
||||
void Plater::priv::scale_selection_to_fit_print_volume()
|
||||
{
|
||||
#if ENABLE_ENHANCED_PRINT_VOLUME_FIT
|
||||
const BuildVolume volume = this->bed.build_volume();
|
||||
// Every plate shares the bed size, but each sits at its own origin: fit onto the
|
||||
// plate the selection is on instead of always onto the first one.
|
||||
PartPlate* plate = this->partplate_list.get_curr_plate();
|
||||
const Vec3d bed_center = plate != nullptr ? plate->get_center_origin() :
|
||||
Vec3d(volume.bed_center().x(), volume.bed_center().y(), 0.);
|
||||
// On a multi-nozzle printer each nozzle reaches only part of the bed, so a model fitted
|
||||
// to the bed can still exceed a nozzle's printable range. Fit into the volume every
|
||||
// nozzle shares, which is also the area Arrange places items in.
|
||||
const BoundingBoxf3 print_volume = plate != nullptr ? plate->get_build_volume(true) : volume.bounding_volume();
|
||||
this->view3D->get_canvas3d()->get_selection().scale_to_fit_print_volume(volume, Vec2d(bed_center.x(), bed_center.y()), print_volume);
|
||||
this->view3D->get_canvas3d()->get_selection().scale_to_fit_print_volume(this->bed.build_volume());
|
||||
#else
|
||||
this->view3D->get_canvas3d()->get_selection().scale_to_fit_print_volume(*config);
|
||||
#endif // ENABLE_ENHANCED_PRINT_VOLUME_FIT
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
#include "libslic3r/Color.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/Geometry.hpp"
|
||||
#include "libslic3r/LayOnFace.hpp"
|
||||
#include "slic3r/GUI/GLModel.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -1473,9 +1472,11 @@ void Selection::flattening_rotate(const Vec3d& normal)
|
||||
|
||||
for (unsigned int i : m_list) {
|
||||
GLVolume& v = *(*m_volumes)[i];
|
||||
// Additional rotation to align the face normal with the down vector in the world coordinate space.
|
||||
// Normal transformed from the object coordinate space to the world coordinate space.
|
||||
const Geometry::Transformation& old_inst_trafo = v.get_instance_transformation();
|
||||
const Transform3d rotation_matrix = lay_on_face_rotation(normal, old_inst_trafo.get_matrix_no_offset());
|
||||
const Vec3d tnormal = old_inst_trafo.get_matrix().matrix().block(0, 0, 3, 3).inverse().transpose() * normal;
|
||||
// Additional rotation to align tnormal with the down vector in the world coordinate space.
|
||||
const Transform3d rotation_matrix = Transform3d(Eigen::Quaterniond().setFromTwoVectors(tnormal, -Vec3d::UnitZ()));
|
||||
v.set_instance_transformation(old_inst_trafo.get_offset_matrix() * rotation_matrix * old_inst_trafo.get_matrix_no_offset());
|
||||
}
|
||||
|
||||
@@ -1495,7 +1496,7 @@ void Selection::scale(const Vec3d& scale, TransformationType transformation_type
|
||||
}
|
||||
|
||||
#if ENABLE_ENHANCED_PRINT_VOLUME_FIT
|
||||
void Selection::scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d& bed_center, const BoundingBoxf3& print_volume)
|
||||
void Selection::scale_to_fit_print_volume(const BuildVolume& volume)
|
||||
{
|
||||
auto fit = [this](double s, Vec3d offset) {
|
||||
if (s <= 0.0 || s == 1.0)
|
||||
@@ -1525,7 +1526,8 @@ void Selection::scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d
|
||||
//wxGetApp().obj_manipul()->set_dirty();
|
||||
};
|
||||
|
||||
auto fit_rectangle = [this, fit, &print_volume]() {
|
||||
auto fit_rectangle = [this, fit](const BuildVolume& volume) {
|
||||
const BoundingBoxf3 print_volume = volume.bounding_volume();
|
||||
const Vec3d print_volume_size = print_volume.size();
|
||||
|
||||
// adds 1/100th of a mm on all sides to avoid false out of print volume detections due to floating-point roundings
|
||||
@@ -1539,7 +1541,7 @@ void Selection::scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d
|
||||
fit(std::min(sx, std::min(sy, sz)), print_volume.center() - get_bounding_box().center());
|
||||
};
|
||||
|
||||
auto fit_circle = [this, fit, &bed_center](const BuildVolume& volume) {
|
||||
auto fit_circle = [this, fit](const BuildVolume& volume) {
|
||||
const Geometry::Circled& print_circle = volume.circle();
|
||||
double print_circle_radius = unscale<double>(print_circle.radius);
|
||||
|
||||
@@ -1570,9 +1572,7 @@ void Selection::scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d
|
||||
const double s = std::min(print_circle_radius / circle_radius, volume.printable_height() / max_z);
|
||||
const Vec3d sel_center = get_bounding_box().center();
|
||||
const Vec3d offset = s * (Vec3d(unscale<double>(circle.center.x()), unscale<double>(circle.center.y()), 0.5 * max_z) - sel_center);
|
||||
// The active plate's bed is the same circle, moved by its centre.
|
||||
const Vec3d plate_shift = Vec3d(bed_center.x() - volume.bed_center().x(), bed_center.y() - volume.bed_center().y(), 0.);
|
||||
const Vec3d print_center = Vec3d(unscale<double>(print_circle.center.x()), unscale<double>(print_circle.center.y()), 0.5 * volume.printable_height()) + plate_shift;
|
||||
const Vec3d print_center = { unscale<double>(print_circle.center.x()), unscale<double>(print_circle.center.y()), 0.5 * volume.printable_height() };
|
||||
fit(s, print_center - (sel_center + offset));
|
||||
};
|
||||
|
||||
@@ -1581,7 +1581,7 @@ void Selection::scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d
|
||||
|
||||
switch (volume.type())
|
||||
{
|
||||
case BuildVolume_Type::Rectangle: { fit_rectangle(); break; }
|
||||
case BuildVolume_Type::Rectangle: { fit_rectangle(volume); break; }
|
||||
case BuildVolume_Type::Circle: { fit_circle(volume); break; }
|
||||
default: { break; }
|
||||
}
|
||||
|
||||
@@ -354,10 +354,7 @@ public:
|
||||
void flattening_rotate(const Vec3d& normal);
|
||||
void scale(const Vec3d& scale, TransformationType transformation_type);
|
||||
#if ENABLE_ENHANCED_PRINT_VOLUME_FIT
|
||||
// bed_center is the centre of the plate the selection is on: every plate shares the
|
||||
// bed size, but each sits at its own origin. print_volume is the box the selection must
|
||||
// fit in, which is the area every nozzle reaches rather than the whole bed.
|
||||
void scale_to_fit_print_volume(const BuildVolume& volume, const Vec2d& bed_center, const BoundingBoxf3& print_volume);
|
||||
void scale_to_fit_print_volume(const BuildVolume& volume);
|
||||
#else
|
||||
void scale_to_fit_print_volume(const DynamicPrintConfig& config);
|
||||
#endif // ENABLE_ENHANCED_PRINT_VOLUME_FIT
|
||||
|
||||
@@ -5,10 +5,13 @@
|
||||
#include "libslic3r/libslic3r.h" // GCODEVIEWER_APP_KEY, and SLIC3R_APP_KEY via libslic3r_version.h
|
||||
#include "libslic3r_version.h"
|
||||
|
||||
#include <boost/algorithm/string/case_conv.hpp>
|
||||
#include <boost/algorithm/string/predicate.hpp>
|
||||
#include <boost/algorithm/string/trim.hpp>
|
||||
#include <boost/filesystem/path.hpp>
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <boost/system/error_code.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
@@ -161,6 +164,180 @@ static bool is_fs_category(AuditEventCategory category)
|
||||
}
|
||||
}
|
||||
|
||||
// HTTP and raw-socket events are governed by the same network permission: a declared host may be
|
||||
// reached through either layer, and the layers nest for one plugin action (urllib -> http.client
|
||||
// -> socket).
|
||||
static bool is_network_category(AuditEventCategory category)
|
||||
{
|
||||
return category == AuditEventCategory::Http || category == AuditEventCategory::Socket;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Network permission identity
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static std::string ascii_lower(std::string value)
|
||||
{
|
||||
boost::algorithm::to_lower(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
static std::string trim_ascii_space(std::string value)
|
||||
{
|
||||
boost::algorithm::trim(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
// Canonical storage keeps IPv6 literals bracketed (https://[::1]), while a socket address
|
||||
// exposes the bare literal (::1). Compare them without the brackets.
|
||||
static std::string without_ipv6_brackets(std::string host)
|
||||
{
|
||||
if (host.size() >= 2 && host.front() == '[' && host.back() == ']')
|
||||
host = host.substr(1, host.size() - 2);
|
||||
return host;
|
||||
}
|
||||
|
||||
// Returns the host part of a URL authority, dropping userinfo and port. IPv6 literals keep their
|
||||
// brackets so that a URL and a bare address compare consistently.
|
||||
static std::string host_from_authority(std::string authority)
|
||||
{
|
||||
const size_t at = authority.rfind('@');
|
||||
if (at != std::string::npos)
|
||||
authority.erase(0, at + 1);
|
||||
|
||||
if (authority.empty())
|
||||
return {};
|
||||
|
||||
if (authority.front() == '[') {
|
||||
const size_t close = authority.find(']');
|
||||
if (close == std::string::npos)
|
||||
return {};
|
||||
authority.erase(close + 1);
|
||||
return ascii_lower(authority);
|
||||
}
|
||||
|
||||
const size_t colon = authority.find(':');
|
||||
if (colon != std::string::npos)
|
||||
authority.erase(colon);
|
||||
|
||||
if (authority.find_first_of(" \t\r\n/?#@") != std::string::npos)
|
||||
return {};
|
||||
|
||||
return ascii_lower(authority);
|
||||
}
|
||||
|
||||
// Extracts a host from a target that is not a URL: "host", "host:443", "[::1]:443", "('host',
|
||||
// 443)" (the form older releases persisted for socket address events), or "'host'".
|
||||
static std::string network_host_from_target(const std::string& target)
|
||||
{
|
||||
std::string value = trim_ascii_space(target);
|
||||
if (value.empty())
|
||||
return {};
|
||||
|
||||
if (value.front() == '(') {
|
||||
// Legacy persisted address tuple: ("host", 443) or ("host", 443, 0, 0).
|
||||
const size_t quote = value.find_first_of("'\"");
|
||||
if (quote != std::string::npos) {
|
||||
const char delimiter = value[quote];
|
||||
const size_t end = value.find(delimiter, quote + 1);
|
||||
if (end == std::string::npos)
|
||||
return {};
|
||||
value = value.substr(quote + 1, end - quote - 1);
|
||||
} else {
|
||||
value = value.substr(1);
|
||||
const size_t comma = value.find(',');
|
||||
if (comma != std::string::npos)
|
||||
value.erase(comma);
|
||||
}
|
||||
} else if (value.front() == '[') {
|
||||
const size_t close = value.find(']');
|
||||
if (close == std::string::npos)
|
||||
return {};
|
||||
value.erase(close + 1);
|
||||
} else {
|
||||
// Strip a ":port" suffix, but leave a bare IPv6 literal ("::1") intact.
|
||||
const size_t colon = value.find(':');
|
||||
if (colon != std::string::npos && value.find(':', colon + 1) == std::string::npos)
|
||||
value.erase(colon);
|
||||
}
|
||||
|
||||
value = trim_ascii_space(value);
|
||||
if (value.empty() || value.find_first_of(" \t\r\n/?#@") != std::string::npos)
|
||||
return {};
|
||||
|
||||
return ascii_lower(value);
|
||||
}
|
||||
|
||||
std::string PluginAuditManager::normalize_network_url(const std::string& url)
|
||||
{
|
||||
const size_t scheme_end = url.find("://");
|
||||
if (scheme_end == std::string::npos || scheme_end == 0)
|
||||
return {};
|
||||
|
||||
const std::string scheme = ascii_lower(url.substr(0, scheme_end));
|
||||
if (scheme != "http" && scheme != "https")
|
||||
return {};
|
||||
|
||||
const size_t authority_start = scheme_end + 3;
|
||||
const size_t authority_end = url.find_first_of("/?#", authority_start);
|
||||
const std::string authority = url.substr(authority_start, authority_end == std::string::npos
|
||||
? std::string::npos
|
||||
: authority_end - authority_start);
|
||||
|
||||
const std::string host = host_from_authority(authority);
|
||||
if (host.empty())
|
||||
return {};
|
||||
|
||||
return scheme + "://" + host;
|
||||
}
|
||||
|
||||
bool PluginAuditManager::network_permission_matches(const std::vector<std::string>& granted,
|
||||
const std::string& target)
|
||||
{
|
||||
if (target.empty())
|
||||
return false;
|
||||
|
||||
const bool target_is_url = target.find("://") != std::string::npos;
|
||||
const std::string target_url = normalize_network_url(target);
|
||||
if (target_is_url && target_url.empty()) {
|
||||
// A non-http(s) URL has no network identity we can generalize; only an exact grant
|
||||
// recorded by an earlier approval stays valid, so an unrelated scheme never matches.
|
||||
return std::find(granted.begin(), granted.end(), target) != granted.end();
|
||||
}
|
||||
|
||||
const std::string target_host =
|
||||
target_is_url ? std::string{} : without_ipv6_brackets(network_host_from_target(target));
|
||||
if (!target_is_url && target_host.empty())
|
||||
return false;
|
||||
|
||||
for (const std::string& entry : granted) {
|
||||
// Preserve an exact grant recorded by an older release, e.g. a full URL with a query.
|
||||
if (entry == target)
|
||||
return true;
|
||||
|
||||
const std::string entry_url = normalize_network_url(entry);
|
||||
if (target_is_url) {
|
||||
// Canonical scheme://host grants are host-wide. Older grants that persisted a full
|
||||
// URL remain scoped to that exact URL, preserving the operation-root URL check.
|
||||
if (!entry_url.empty() && entry_url == entry && entry_url == target_url)
|
||||
return true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!entry_url.empty()) {
|
||||
// Bare hosts carry no scheme: match the host part of a scheme://host grant.
|
||||
const std::string entry_host = entry_url.substr(entry_url.find("://") + 3);
|
||||
if (without_ipv6_brackets(entry_host) == target_host)
|
||||
return true;
|
||||
} else if (without_ipv6_brackets(network_host_from_target(entry)) == target_host) {
|
||||
// Legacy persisted address tuples, e.g. "('host', 443)".
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// The category's name in a saved event grant, e.g. "FsRead" in "FsRead:open".
|
||||
static const char* category_name(AuditEventCategory category)
|
||||
{
|
||||
@@ -528,6 +705,39 @@ AuditDecision PluginAuditManager::check_open(const std::string& path_str, const
|
||||
return check_path_access(boost::filesystem::path(path_str), is_write);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Builds and shows the modal confirmation. Must run on the GUI thread.
|
||||
bool show_permission_dialog(const wxString& message, const wxString& title)
|
||||
{
|
||||
wxMessageDialog dialog(nullptr, message, title, wxYES_NO | wxICON_WARNING);
|
||||
return dialog.ShowModal() == wxID_YES;
|
||||
}
|
||||
|
||||
// Shows a permission prompt on the GUI thread and waits for the answer. The caller may be the
|
||||
// plugin-load worker, so off the main thread the dialog is marshaled with CallAfter.
|
||||
bool ask_permission(const wxString& message)
|
||||
{
|
||||
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
|
||||
return false;
|
||||
|
||||
if (wxIsMainThread())
|
||||
return show_permission_dialog(message, _L("Plugin permissions"));
|
||||
|
||||
auto result = std::make_shared<std::promise<bool>>();
|
||||
auto future = result->get_future();
|
||||
GUI::wxGetApp().CallAfter([result, message]() {
|
||||
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) {
|
||||
result->set_value(false);
|
||||
return;
|
||||
}
|
||||
result->set_value(show_permission_dialog(message, _L("Plugin permissions")));
|
||||
});
|
||||
return future.get();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool PluginAuditManager::request_filesystem_read_permissions(const std::string& plugin_key,
|
||||
const std::vector<std::string>& paths)
|
||||
{
|
||||
@@ -549,60 +759,80 @@ bool PluginAuditManager::request_filesystem_read_permissions(const std::string&
|
||||
if (missing.empty())
|
||||
return true;
|
||||
|
||||
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
|
||||
wxString requested_paths;
|
||||
for (const std::string& path : missing)
|
||||
requested_paths += wxString::FromUTF8(path.c_str()) + "\n";
|
||||
|
||||
if (!ask_permission(wxString::Format(_L("Plugin \"%s\" requests filesystem read access to:\n%s"),
|
||||
wxString::FromUTF8(descriptor.name.c_str()), requested_paths)))
|
||||
return false;
|
||||
|
||||
auto show_dialog = [&descriptor, &missing]() {
|
||||
wxString requested_paths;
|
||||
for (const std::string& path : missing)
|
||||
requested_paths += wxString::FromUTF8(path.c_str()) + "\n";
|
||||
|
||||
wxMessageDialog dialog(
|
||||
nullptr,
|
||||
wxString::Format(_L("Plugin \"%s\" requests filesystem read access to:\n%s"),
|
||||
wxString::FromUTF8(descriptor.name.c_str()), requested_paths),
|
||||
_L("Plugin permissions"),
|
||||
wxYES_NO | wxICON_WARNING);
|
||||
return dialog.ShowModal() == wxID_YES;
|
||||
};
|
||||
|
||||
bool granted = false;
|
||||
if (wxIsMainThread()) {
|
||||
granted = show_dialog();
|
||||
} else {
|
||||
auto result = std::make_shared<std::promise<bool>>();
|
||||
auto future = result->get_future();
|
||||
GUI::wxGetApp().CallAfter([result, descriptor_name = descriptor.name, missing]() {
|
||||
wxString requested_paths;
|
||||
for (const std::string& path : missing)
|
||||
requested_paths += wxString::FromUTF8(path.c_str()) + "\n";
|
||||
|
||||
wxMessageDialog dialog(
|
||||
nullptr,
|
||||
wxString::Format(_L("Plugin \"%s\" requests filesystem read access to:\n%s"),
|
||||
wxString::FromUTF8(descriptor_name.c_str()), requested_paths),
|
||||
_L("Plugin permissions"),
|
||||
wxYES_NO | wxICON_WARNING);
|
||||
result->set_value(dialog.ShowModal() == wxID_YES);
|
||||
});
|
||||
granted = future.get();
|
||||
}
|
||||
|
||||
if (!granted)
|
||||
return false;
|
||||
|
||||
if (state.plugin_name.empty()) {
|
||||
state.installed_from = descriptor.is_cloud_plugin() ? "cloud" : "local";
|
||||
state.installed_version = !descriptor.installed_version.empty() ? descriptor.installed_version : descriptor.version;
|
||||
state.plugin_name = descriptor.name;
|
||||
state.cloud_uuid = descriptor.cloud_uuid();
|
||||
state.enabled = true;
|
||||
}
|
||||
seed_install_metadata(state, descriptor);
|
||||
|
||||
state.permissions.fs_read.insert(state.permissions.fs_read.end(), missing.begin(), missing.end());
|
||||
return write_install_state(boost::filesystem::path(descriptor.plugin_root), state);
|
||||
}
|
||||
|
||||
bool PluginAuditManager::request_network_permissions(const std::string& plugin_key,
|
||||
const std::vector<std::string>& urls)
|
||||
{
|
||||
if (plugin_key.empty() || urls.empty())
|
||||
return true;
|
||||
|
||||
PluginDescriptor descriptor;
|
||||
if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty())
|
||||
return false;
|
||||
|
||||
// Reduce every request to scheme://host before comparing or persisting it, so a URL with a
|
||||
// path or query cannot create a second grant for the same host.
|
||||
std::vector<std::string> requested;
|
||||
for (const std::string& url : urls) {
|
||||
const std::string normalized = normalize_network_url(url);
|
||||
if (normalized.empty()) {
|
||||
BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Invalid network permission request for plugin " << plugin_key << ": " << url;
|
||||
return false;
|
||||
}
|
||||
if (std::find(requested.begin(), requested.end(), normalized) == requested.end())
|
||||
requested.push_back(normalized);
|
||||
}
|
||||
|
||||
PluginInstallState state;
|
||||
read_install_state(boost::filesystem::path(descriptor.plugin_root), state);
|
||||
|
||||
std::vector<std::string> missing;
|
||||
for (const std::string& entry : requested) {
|
||||
if (!network_permission_matches(state.permissions.network_http, entry) &&
|
||||
!network_permission_matches(state.permissions.network_socket, entry))
|
||||
missing.push_back(entry);
|
||||
}
|
||||
if (missing.empty())
|
||||
return true;
|
||||
|
||||
wxString requested_hosts;
|
||||
for (const std::string& entry : missing)
|
||||
requested_hosts += wxString::FromUTF8(entry.c_str()) + "\n";
|
||||
|
||||
if (!ask_permission(wxString::Format(_L("Plugin \"%s\" requests network access to:\n%s"),
|
||||
wxString::FromUTF8(descriptor.name.c_str()), requested_hosts)))
|
||||
return false;
|
||||
|
||||
seed_install_metadata(state, descriptor);
|
||||
|
||||
// A declared host is reachable through both HTTP and raw socket events. Recording the grant in
|
||||
// both existing lists keeps the sidecar self-describing and means either event layer matches
|
||||
// it without relying on the other list.
|
||||
for (const std::string& entry : missing) {
|
||||
if (std::find(state.permissions.network_http.begin(), state.permissions.network_http.end(), entry) ==
|
||||
state.permissions.network_http.end())
|
||||
state.permissions.network_http.push_back(entry);
|
||||
if (std::find(state.permissions.network_socket.begin(), state.permissions.network_socket.end(), entry) ==
|
||||
state.permissions.network_socket.end())
|
||||
state.permissions.network_socket.push_back(entry);
|
||||
}
|
||||
|
||||
return write_install_state(boost::filesystem::path(descriptor.plugin_root), state);
|
||||
}
|
||||
|
||||
void PluginAuditManager::report_violation(const AuditViolation& violation)
|
||||
{
|
||||
m_last_violation = violation;
|
||||
@@ -645,6 +875,39 @@ PyObject* tuple_item(PyObject* args, Py_ssize_t index)
|
||||
return PyTuple_GET_ITEM(args, index);
|
||||
}
|
||||
|
||||
std::string python_unicode(PyObject* object)
|
||||
{
|
||||
if (!object || !PyUnicode_Check(object))
|
||||
return {};
|
||||
const char* text = PyUnicode_AsUTF8(object);
|
||||
if (!text) {
|
||||
PyErr_Clear();
|
||||
return {};
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
// Converts a str/bytes leaf to text, clearing a failed conversion. Returns false when `object` is
|
||||
// neither str nor bytes, so callers can apply their own fallback.
|
||||
bool python_text(PyObject* object, std::string& out)
|
||||
{
|
||||
if (PyUnicode_Check(object)) {
|
||||
out = python_unicode(object);
|
||||
return true;
|
||||
}
|
||||
if (PyBytes_Check(object)) {
|
||||
const char* value = PyBytes_AsString(object);
|
||||
if (!value) {
|
||||
PyErr_Clear();
|
||||
out.clear();
|
||||
return true;
|
||||
}
|
||||
out = value;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string python_path(PyObject* object)
|
||||
{
|
||||
if (!object)
|
||||
@@ -656,26 +919,12 @@ std::string python_path(PyObject* object)
|
||||
return {};
|
||||
}
|
||||
|
||||
const char* path = PyUnicode_Check(path_object) ? PyUnicode_AsUTF8(path_object) : PyBytes_AsString(path_object);
|
||||
std::string result = path ? path : "";
|
||||
std::string result;
|
||||
python_text(path_object, result);
|
||||
Py_DECREF(path_object);
|
||||
if (!path)
|
||||
PyErr_Clear();
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string python_unicode(PyObject* object)
|
||||
{
|
||||
if (!object || !PyUnicode_Check(object))
|
||||
return {};
|
||||
const char* text = PyUnicode_AsUTF8(object);
|
||||
if (!text) {
|
||||
PyErr_Clear();
|
||||
return {};
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
std::string python_str(PyObject* object)
|
||||
{
|
||||
if (!object)
|
||||
@@ -894,6 +1143,20 @@ bool has_permission(const std::vector<std::string>& granted, const std::string&
|
||||
return std::find(granted.begin(), granted.end(), target) != granted.end();
|
||||
}
|
||||
|
||||
// A declared or previously approved network grant may live in either network list: an HTTP grant
|
||||
// covers the sockets the same request opens, and a raw socket grant covers a later HTTP call to
|
||||
// the same host.
|
||||
bool has_network_permission(const PluginPermissions& permissions, const std::string& target)
|
||||
{
|
||||
return PluginAuditManager::network_permission_matches(permissions.network_http, target) ||
|
||||
PluginAuditManager::network_permission_matches(permissions.network_socket, target);
|
||||
}
|
||||
|
||||
bool has_any_network_permission(const PluginPermissions& permissions)
|
||||
{
|
||||
return !permissions.network_http.empty() || !permissions.network_socket.empty();
|
||||
}
|
||||
|
||||
bool persist_permission(const std::string& plugin_key,
|
||||
PluginInstallState& state,
|
||||
std::vector<std::string>& permission_list,
|
||||
@@ -903,15 +1166,7 @@ bool persist_permission(const std::string& plugin_key,
|
||||
if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty())
|
||||
return false;
|
||||
|
||||
// A sandbox plugin may not have a sidecar yet. Seed the small amount of install metadata
|
||||
// needed by the writer so clicking Yes still creates the JSON file.
|
||||
if (state.plugin_name.empty()) {
|
||||
state.installed_from = descriptor.is_cloud_plugin() ? "cloud" : "local";
|
||||
state.installed_version = !descriptor.installed_version.empty() ? descriptor.installed_version : descriptor.version;
|
||||
state.plugin_name = descriptor.name;
|
||||
state.cloud_uuid = descriptor.cloud_uuid();
|
||||
state.enabled = true;
|
||||
}
|
||||
seed_install_metadata(state, descriptor);
|
||||
|
||||
if (!has_permission(permission_list, target))
|
||||
permission_list.push_back(target);
|
||||
@@ -990,11 +1245,10 @@ bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_n
|
||||
for (const auto& target : unresolved)
|
||||
target_list += wxString::FromUTF8(target.c_str()) + "\n";
|
||||
|
||||
wxMessageDialog dialog(nullptr,
|
||||
audit_message(category, wxString::FromUTF8(plugin_name.c_str()),
|
||||
wxString::FromUTF8(event_name.c_str()), target_list, unresolved.size()),
|
||||
_L("Plugin permission request"), wxYES_NO | wxICON_WARNING);
|
||||
return dialog.ShowModal() == wxID_YES;
|
||||
return show_permission_dialog(
|
||||
audit_message(category, wxString::FromUTF8(plugin_name.c_str()), wxString::FromUTF8(event_name.c_str()),
|
||||
target_list, unresolved.size()),
|
||||
_L("Plugin permission request"));
|
||||
}
|
||||
|
||||
// Records a grant in the plugin's sidecar so it is not asked again. Reads the install state
|
||||
@@ -1066,10 +1320,13 @@ int decide_audited_event(PluginAuditManager& mgr,
|
||||
std::vector<std::string>* permission_list = permission_list_for(category, by_event, state.permissions);
|
||||
|
||||
std::vector<std::string> unresolved = keys;
|
||||
if (permission_list) {
|
||||
if (permission_list || is_network_category(category)) {
|
||||
unresolved.clear();
|
||||
for (const auto& key : keys)
|
||||
if (!has_permission(*permission_list, key))
|
||||
if (!(permission_list && has_permission(*permission_list, key)) &&
|
||||
!(is_network_category(category) &&
|
||||
(by_event ? has_any_network_permission(state.permissions)
|
||||
: has_network_permission(state.permissions, key))))
|
||||
unresolved.push_back(key);
|
||||
if (unresolved.empty())
|
||||
return 0;
|
||||
|
||||
@@ -137,6 +137,29 @@ public:
|
||||
bool request_filesystem_read_permissions(const std::string& plugin_key,
|
||||
const std::vector<std::string>& paths);
|
||||
|
||||
// Ask the user to grant network access to the given http(s) URLs. Each URL is reduced to its
|
||||
// scheme and host before prompting and persisting, so one approval covers every path, query
|
||||
// and port on that host. The grant is written to both network_http and network_socket: the
|
||||
// same declared host can surface through HTTP events (urllib/http.client) and raw socket
|
||||
// events. Like request_filesystem_read_permissions, the request may originate on a plugin
|
||||
// load worker; denial aborts the plugin load without adding a permission.
|
||||
bool request_network_permissions(const std::string& plugin_key,
|
||||
const std::vector<std::string>& urls);
|
||||
|
||||
// Canonical scheme://host form used to store and match network permissions. Returns an empty
|
||||
// string unless `url` is an absolute http(s) URL with a host. The path, query, fragment,
|
||||
// userinfo and port are discarded; scheme and host are lowercased.
|
||||
static std::string normalize_network_url(const std::string& url);
|
||||
|
||||
// True when a granted scheme://host entry covers `target`. `target` is a URL (urllib.Request),
|
||||
// a bare host (http.client.connect, socket.getaddrinfo) or an address as exposed by the audit
|
||||
// event (a hostname, a host:port pair, or a legacy persisted tuple such as "('host', 443)").
|
||||
// URL targets must match both scheme and host. Canonical scheme://host grants cover all paths;
|
||||
// older full-URL grants remain exact. A bare host carries no scheme, so it matches the host
|
||||
// part of any grant; it never matches a different host.
|
||||
static bool network_permission_matches(const std::vector<std::string>& granted,
|
||||
const std::string& target);
|
||||
|
||||
void report_violation(const AuditViolation& violation);
|
||||
bool audit_denial_pending() const;
|
||||
void clear_audit_denial();
|
||||
@@ -187,6 +210,7 @@ private:
|
||||
|
||||
// mutable: is_denied_filename() is a const query that must lock.
|
||||
mutable std::mutex m_mutex;
|
||||
|
||||
std::vector<AllowedRoot> m_global_allowed_roots;
|
||||
std::vector<std::string> m_denied_filenames;
|
||||
std::vector<std::string> m_denied_path_keywords;
|
||||
|
||||
@@ -833,6 +833,29 @@ bool read_install_state(const boost::filesystem::path& plugin_dir, PluginInstall
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The single descriptor -> sidecar metadata mapping. Prefer installed_version (fetched at install
|
||||
// time and preserved across rewrites) over a possibly stale manifest version.
|
||||
void apply_install_metadata(PluginInstallState& state, const PluginDescriptor& entry)
|
||||
{
|
||||
state.installed_from = entry.is_cloud_plugin() ? "cloud" : "local";
|
||||
state.installed_version = !entry.installed_version.empty() ? entry.installed_version : entry.version;
|
||||
state.plugin_name = entry.name;
|
||||
state.cloud_uuid = entry.cloud_uuid();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void seed_install_metadata(PluginInstallState& state, const PluginDescriptor& entry)
|
||||
{
|
||||
if (!state.plugin_name.empty())
|
||||
return;
|
||||
|
||||
apply_install_metadata(state, entry);
|
||||
state.enabled = true;
|
||||
}
|
||||
|
||||
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginInstallState& state)
|
||||
{
|
||||
namespace fs = boost::filesystem;
|
||||
@@ -876,16 +899,9 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin
|
||||
// Loading a plugin updates its lifecycle/capability state, but must retain permissions granted
|
||||
// during register_capabilities() or by a previous runtime audit prompt.
|
||||
read_install_state(plugin_dir, state);
|
||||
state.installed_from = entry.is_cloud_plugin() ? "cloud" : "local";
|
||||
// Prefer the descriptor's recorded installed_version (the version fetched from the cloud
|
||||
// at install time, preserved across sidecar re-writes) so a stale manifest/PEP723 header
|
||||
// never overwrites the source-of-truth version. Fall back to the manifest version for
|
||||
// first-time/local installs where installed_version is not yet populated.
|
||||
state.installed_version = !entry.installed_version.empty() ? entry.installed_version : entry.version;
|
||||
state.plugin_name = entry.name;
|
||||
state.cloud_uuid = entry.cloud_uuid();
|
||||
state.enabled = enabled;
|
||||
state.capabilities = capabilities;
|
||||
apply_install_metadata(state, entry);
|
||||
state.enabled = enabled;
|
||||
state.capabilities = capabilities;
|
||||
return write_install_state(plugin_dir, state);
|
||||
}
|
||||
|
||||
@@ -896,11 +912,7 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin
|
||||
// permissions on a fresh install/reinstall. PluginManager writes the real per-capability flags
|
||||
// while preserving permissions once the package is loaded, via the overload above.
|
||||
PluginInstallState state;
|
||||
state.installed_from = entry.is_cloud_plugin() ? "cloud" : "local";
|
||||
state.installed_version = !entry.installed_version.empty() ? entry.installed_version : entry.version;
|
||||
state.plugin_name = entry.name;
|
||||
state.cloud_uuid = entry.cloud_uuid();
|
||||
state.enabled = true;
|
||||
seed_install_metadata(state, entry);
|
||||
return write_install_state(plugin_dir, state);
|
||||
}
|
||||
|
||||
|
||||
@@ -186,12 +186,19 @@ std::vector<std::string> collect_resource_texture_files(const std::string& dir,
|
||||
|
||||
// Canonical writer: emits the .install_state.json schema for the given state.
|
||||
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginInstallState& state);
|
||||
|
||||
// Builds a PluginInstallState from the descriptor and delegates to the canonical writer.
|
||||
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginDescriptor& entry, bool enabled,
|
||||
const std::vector<std::pair<std::string, bool>>& capabilities);
|
||||
// Convenience overload: write(dir, entry, /*enabled=*/true, /*capabilities=*/{}).
|
||||
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginDescriptor& entry);
|
||||
|
||||
// Fill the descriptor-derived install metadata into a sidecar state that does not describe an
|
||||
// installed plugin yet, and mark it enabled. Leaves permissions and capabilities untouched.
|
||||
// Single source for the metadata mapping used by the install writer and by the audit prompt path
|
||||
// that creates a sidecar on demand.
|
||||
void seed_install_metadata(PluginInstallState& state, const PluginDescriptor& entry);
|
||||
|
||||
// Reads install state back into the descriptor; plugin_key is always derived. Returns whether the
|
||||
// sidecar was present and valid.
|
||||
bool read_install_state(const boost::filesystem::path& plugin_dir, PluginDescriptor& entry);
|
||||
|
||||
@@ -1180,12 +1180,8 @@ void PluginManager::mark_plugin_install_state_disabled(const std::string& plugin
|
||||
|
||||
const boost::filesystem::path root(descriptor.plugin_root);
|
||||
PluginInstallState state;
|
||||
if (!read_install_state(root, state)) {
|
||||
state.installed_from = descriptor.is_cloud_plugin() ? "cloud" : "local";
|
||||
state.installed_version = !descriptor.installed_version.empty() ? descriptor.installed_version : descriptor.version;
|
||||
state.plugin_name = descriptor.name;
|
||||
state.cloud_uuid = descriptor.cloud_uuid();
|
||||
}
|
||||
if (!read_install_state(root, state))
|
||||
seed_install_metadata(state, descriptor);
|
||||
state.enabled = false;
|
||||
if (!write_install_state(root, state))
|
||||
return;
|
||||
|
||||
@@ -50,6 +50,7 @@ std::mutex g_registry_mutex;
|
||||
std::unordered_map<std::string, std::vector<py::object>> g_pending_capabilities;
|
||||
std::unordered_map<std::string, py::object> g_pending_package;
|
||||
std::unordered_map<std::string, std::vector<std::string>> g_pending_fs_read_permissions;
|
||||
std::unordered_map<std::string, std::vector<std::string>> g_pending_network_permissions;
|
||||
struct PluginInstanceHandle
|
||||
{
|
||||
// The C++ plugin interface points into a Python object. Keep both alive through one
|
||||
@@ -89,6 +90,7 @@ void discard_pending_capture_without_python(const std::string& plugin_key)
|
||||
}
|
||||
|
||||
g_pending_fs_read_permissions.erase(plugin_key);
|
||||
g_pending_network_permissions.erase(plugin_key);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -114,6 +116,7 @@ void PythonPluginBridge::begin_plugin_capture(const std::string& plugin_key)
|
||||
g_pending_capabilities.erase(plugin_key);
|
||||
g_pending_package.erase(plugin_key);
|
||||
g_pending_fs_read_permissions.erase(plugin_key);
|
||||
g_pending_network_permissions.erase(plugin_key);
|
||||
}
|
||||
// From now until finalize/cancel, @orca.plugin and register_capability() calls made by
|
||||
// Python code on this thread are attributed to this plugin.
|
||||
@@ -145,6 +148,7 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
|
||||
g_pending_capabilities.erase(capture_key);
|
||||
g_pending_package.erase(capture_key);
|
||||
g_pending_fs_read_permissions.erase(capture_key);
|
||||
g_pending_network_permissions.erase(capture_key);
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -200,6 +204,30 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> network_permissions;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_registry_mutex);
|
||||
auto it = g_pending_network_permissions.find(capture_key);
|
||||
if (it != g_pending_network_permissions.end()) {
|
||||
network_permissions = std::move(it->second);
|
||||
g_pending_network_permissions.erase(it);
|
||||
}
|
||||
}
|
||||
if (!network_permissions.empty()) {
|
||||
bool granted = false;
|
||||
{
|
||||
py::gil_scoped_release release;
|
||||
granted = PluginAuditManager::instance().request_network_permissions(plugin_key, network_permissions);
|
||||
}
|
||||
if (!granted) {
|
||||
error = _u8L("Plugin network permission request denied");
|
||||
BOOST_LOG_TRIVIAL(warning) << error << " for key " << plugin_key;
|
||||
discard_pending_for_key();
|
||||
clear_active_key();
|
||||
return {};
|
||||
}
|
||||
}
|
||||
} catch (py::error_already_set& err) {
|
||||
log_python_exception_keep(err);
|
||||
error = err.what();
|
||||
@@ -323,6 +351,7 @@ void PythonPluginBridge::cancel_plugin_capture(const std::string& plugin_key)
|
||||
g_pending_capabilities.erase(plugin_key);
|
||||
g_pending_package.erase(plugin_key);
|
||||
g_pending_fs_read_permissions.erase(plugin_key);
|
||||
g_pending_network_permissions.erase(plugin_key);
|
||||
}
|
||||
|
||||
if (g_active_plugin_key == plugin_key)
|
||||
@@ -350,6 +379,7 @@ void PythonPluginBridge::clear_pending_captures()
|
||||
}
|
||||
g_pending_package.clear();
|
||||
g_pending_fs_read_permissions.clear();
|
||||
g_pending_network_permissions.clear();
|
||||
g_active_plugin_key.clear();
|
||||
return;
|
||||
}
|
||||
@@ -359,6 +389,7 @@ void PythonPluginBridge::clear_pending_captures()
|
||||
g_pending_capabilities.clear();
|
||||
g_pending_package.clear();
|
||||
g_pending_fs_read_permissions.clear();
|
||||
g_pending_network_permissions.clear();
|
||||
g_active_plugin_key.clear();
|
||||
}
|
||||
|
||||
@@ -558,24 +589,50 @@ void bind_python_api(pybind11::module_& m)
|
||||
|
||||
m.def(
|
||||
"request_permissions",
|
||||
[](const std::vector<std::string>& fs_read) {
|
||||
[](const std::vector<std::string>& fs_read, const std::vector<std::string>& network) {
|
||||
if (g_active_plugin_key.empty())
|
||||
throw py::value_error("request_permissions() called outside plugin discovery context");
|
||||
|
||||
std::lock_guard<std::mutex> lock(g_registry_mutex);
|
||||
auto& requested = g_pending_fs_read_permissions[g_active_plugin_key];
|
||||
// Validate and canonicalize everything before touching the pending registry, so a
|
||||
// partially invalid call cannot leave a half-recorded request behind.
|
||||
std::vector<std::string> normalized_network;
|
||||
normalized_network.reserve(network.size());
|
||||
for (const std::string& url : network) {
|
||||
const std::string normalized = PluginAuditManager::normalize_network_url(url);
|
||||
if (normalized.empty())
|
||||
throw py::value_error(
|
||||
"request_permissions(network=...) requires an http:// or https:// URL with a host");
|
||||
if (std::find(normalized_network.begin(), normalized_network.end(), normalized) == normalized_network.end())
|
||||
normalized_network.push_back(normalized);
|
||||
}
|
||||
|
||||
for (const std::string& path : fs_read) {
|
||||
if (path.empty())
|
||||
throw py::value_error("request_permissions(fs_read=...) does not accept empty paths");
|
||||
if (std::find(requested.begin(), requested.end(), path) == requested.end())
|
||||
requested.push_back(path);
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(g_registry_mutex);
|
||||
auto& requested_fs = g_pending_fs_read_permissions[g_active_plugin_key];
|
||||
for (const std::string& path : fs_read) {
|
||||
if (std::find(requested_fs.begin(), requested_fs.end(), path) == requested_fs.end())
|
||||
requested_fs.push_back(path);
|
||||
}
|
||||
|
||||
if (!normalized_network.empty()) {
|
||||
auto& requested_network = g_pending_network_permissions[g_active_plugin_key];
|
||||
for (const std::string& entry : normalized_network) {
|
||||
if (std::find(requested_network.begin(), requested_network.end(), entry) == requested_network.end())
|
||||
requested_network.push_back(entry);
|
||||
}
|
||||
}
|
||||
},
|
||||
py::arg("fs_read") = std::vector<std::string>{},
|
||||
R"pbdoc(Request filesystem read permissions while OrcaSlicer loads your module.
|
||||
py::arg("fs_read") = std::vector<std::string>{}, py::arg("network") = std::vector<std::string>{},
|
||||
R"pbdoc(Request permissions while OrcaSlicer loads your module.
|
||||
|
||||
The host presents the request to the user after register_capabilities() returns. Denying the
|
||||
request aborts the plugin load.)pbdoc");
|
||||
`fs_read` lists filesystem paths to read. `network` lists http(s) URLs; each is reduced to its
|
||||
scheme and host, so one grant covers every path, query and port on that host. The host presents
|
||||
the requests to the user after register_capabilities() returns. Denying a request aborts the
|
||||
plugin load.)pbdoc");
|
||||
|
||||
m.def("plugin", [](py::object cls) {
|
||||
if (g_active_plugin_key.empty())
|
||||
|
||||
@@ -220,39 +220,11 @@ TEST_CASE("An item larger than the bed cannot be placed", "[Arrange]")
|
||||
ArrangePolygons items;
|
||||
items.emplace_back(make_square(scaled(20.)));
|
||||
items.emplace_back(make_square(scaled(400.))); // far bigger than the bed
|
||||
// An item that cannot be placed keeps the position it came in with, so the
|
||||
// caller can leave it where the user had it.
|
||||
items[1].translation = {scaled(10.), scaled(20.)};
|
||||
|
||||
arrange(items, bed(200, 200), quiet_params(scaled(1.)));
|
||||
|
||||
REQUIRE(items[0].bed_idx == 0);
|
||||
REQUIRE(items[1].bed_idx == UNARRANGED);
|
||||
REQUIRE(items[1].translation.x() == scaled(10.));
|
||||
REQUIRE(items[1].translation.y() == scaled(20.));
|
||||
}
|
||||
|
||||
TEST_CASE("An item filling the printable area is arranged", "[Arrange]")
|
||||
{
|
||||
// The arrange bed keeps a margin from the printable area and the item is widened by
|
||||
// its brim. Neither may keep an item that fits the printable area from being placed.
|
||||
DynamicPrintConfig cfg = bed_config(); // 200 x 200
|
||||
ArrangeParams p = quiet_params();
|
||||
|
||||
ArrangePolygons items = squares(1, 197.);
|
||||
items.front().brim_width = 1.;
|
||||
update_arrange_params(p, &cfg, items);
|
||||
update_selected_items_inflation(items, &cfg, p);
|
||||
arrange(items, get_shrink_bedpts(&cfg, p), p);
|
||||
REQUIRE(items.front().bed_idx == 0);
|
||||
|
||||
// Larger than the printable area is still refused.
|
||||
ArrangeParams p_large = quiet_params();
|
||||
ArrangePolygons large = squares(1, 201.);
|
||||
update_arrange_params(p_large, &cfg, large);
|
||||
update_selected_items_inflation(large, &cfg, p_large);
|
||||
arrange(large, get_shrink_bedpts(&cfg, p_large), p_large);
|
||||
REQUIRE(large.front().bed_idx == UNARRANGED);
|
||||
}
|
||||
|
||||
TEST_CASE("Items overflowing one bed spill onto virtual beds", "[Arrange]")
|
||||
|
||||
@@ -187,23 +187,6 @@ TEST_CASE("A part rests on its largest hull face even when parallel inner faces
|
||||
check_on_bed(plate);
|
||||
}
|
||||
|
||||
TEST_CASE("A box laid on its top face is turned over about X", "[LayOnFace]")
|
||||
{
|
||||
// A face pointing straight up leaves the half turn's axis open to every horizontal
|
||||
// direction. It must be the fixed X flip both times, keep the footprint and not follow
|
||||
// rounding noise to an arbitrary angle.
|
||||
Model model;
|
||||
ModelObject &box = add_box_object(model, { 40, 20, 10 });
|
||||
lay_on_face(box, 0, { 0, 0, 1 });
|
||||
|
||||
check_size(box, { 40, 20, 10 });
|
||||
check_on_bed(box);
|
||||
const Matrix3d rotation = box.instances.front()->get_matrix_no_offset().linear();
|
||||
CHECK_THAT(rotation(0, 0), WithinAbs(1., 1e-9));
|
||||
CHECK_THAT(rotation(1, 1), WithinAbs(-1., 1e-9));
|
||||
CHECK_THAT(rotation(2, 2), WithinAbs(-1., 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Faces are selected in object coordinates whatever the instance rotation", "[LayOnFace]")
|
||||
{
|
||||
Model model;
|
||||
|
||||
@@ -351,6 +351,93 @@ TEST_CASE("Plugin audit a read-only allowed root blocks writes but not reads", "
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin audit network permissions match by scheme and host", "[audit]")
|
||||
{
|
||||
SECTION("a URL is reduced to its scheme and host")
|
||||
{
|
||||
CHECK(PluginAuditManager::normalize_network_url("https://API.Example.com:8443/v1/items?page=2#top") ==
|
||||
"https://api.example.com");
|
||||
CHECK(PluginAuditManager::normalize_network_url("http://example.com") == "http://example.com");
|
||||
CHECK(PluginAuditManager::normalize_network_url("https://[2001:db8::1]:443/path") == "https://[2001:db8::1]");
|
||||
}
|
||||
|
||||
SECTION("non-http schemes and targets without a scheme are not network URLs")
|
||||
{
|
||||
CHECK(PluginAuditManager::normalize_network_url("ftp://example.com").empty());
|
||||
CHECK(PluginAuditManager::normalize_network_url("api.example.com").empty());
|
||||
CHECK(PluginAuditManager::normalize_network_url("https://").empty());
|
||||
}
|
||||
|
||||
SECTION("a URL target matches the same scheme and host regardless of path and port")
|
||||
{
|
||||
const std::vector<std::string> granted{"https://api.example.com"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "https://api.example.com/v1/items?page=2"));
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "https://api.example.com:8443/upload"));
|
||||
}
|
||||
|
||||
SECTION("canonical host grants are broad but persisted full-URL grants stay exact")
|
||||
{
|
||||
const std::vector<std::string> declared_host{"https://api.example.com"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(declared_host, "https://api.example.com/v1"));
|
||||
|
||||
const std::vector<std::string> saved_url{"https://api.example.com/v1"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(saved_url, "https://api.example.com/v1"));
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(saved_url, "https://api.example.com/v2"));
|
||||
}
|
||||
|
||||
SECTION("a URL target does not match a different host or a different scheme")
|
||||
{
|
||||
const std::vector<std::string> granted{"https://api.example.com"};
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "https://evil.example.com/v1"));
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "http://api.example.com/v1"));
|
||||
}
|
||||
|
||||
SECTION("a bare host target matches the host of a grant")
|
||||
{
|
||||
const std::vector<std::string> granted{"https://api.example.com"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "api.example.com"));
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "api.example.com:443"));
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "other.example.com"));
|
||||
}
|
||||
|
||||
SECTION("legacy persisted address tuples keep matching their host")
|
||||
{
|
||||
const std::vector<std::string> legacy_granted{"('api.example.com', 443)"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(legacy_granted, "api.example.com"));
|
||||
|
||||
const std::vector<std::string> granted{"https://api.example.com"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "('api.example.com', 443)"));
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "('93.184.216.34', 443)"));
|
||||
}
|
||||
|
||||
SECTION("an IPv6 literal matches across bracketed and bare forms")
|
||||
{
|
||||
const std::vector<std::string> granted{"https://[2001:db8::1]"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "2001:db8::1"));
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "[2001:db8::1]:443"));
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "2001:db8::2"));
|
||||
}
|
||||
|
||||
SECTION("a non-http URL only matches an exact grant")
|
||||
{
|
||||
const std::vector<std::string> granted{"ftp://example.com/file"};
|
||||
CHECK(PluginAuditManager::network_permission_matches(granted, "ftp://example.com/file"));
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "ftp://example.com/other"));
|
||||
|
||||
const std::vector<std::string> https{"https://api.example.com"};
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(https, "ftp://api.example.com/file"));
|
||||
}
|
||||
|
||||
SECTION("an empty grant list or an empty target never matches")
|
||||
{
|
||||
const std::vector<std::string> granted{};
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "https://api.example.com"));
|
||||
|
||||
const std::vector<std::string> any{"https://api.example.com"};
|
||||
CHECK_FALSE(PluginAuditManager::network_permission_matches(any, ""));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin audit a scoped root can also be registered read-only", "[audit]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-audit-scoped-readonly");
|
||||
|
||||
Reference in new issue
Block a user