Skip to content

Commit

Permalink
[autofix.ci] apply automated fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
autofix-ci[bot] authored Dec 27, 2024
1 parent 954d287 commit bdee0d1
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 56 deletions.
12 changes: 6 additions & 6 deletions mitmproxy-linux-ebpf-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ impl Pattern {
pub fn matches(&self, command: Option<&[u8; TASK_COMM_LEN]>, pid: PID) -> bool {
match self {
Pattern::Pid(p) => pid == *p,
Pattern::Process(process) => command
.map(|command| command.eq(process))
.unwrap_or(false),
Pattern::Process(process) => {
command.map(|command| command.eq(process)).unwrap_or(false)
}
}
}
}

impl From<&str> for Action {
fn from(value: &str) -> Self{
fn from(value: &str) -> Self {
let value = value.trim();
if let Some(value) = value.strip_prefix('!') {
Action::Exclude(Pattern::from(value))
Expand All @@ -56,7 +56,7 @@ impl From<&str> for Pattern {
let len = core::cmp::min(TASK_COMM_LEN - 1, src.len());
val[..len].copy_from_slice(&src[..len]);
Pattern::Process(val)
},
}
}
}
}
}
11 changes: 4 additions & 7 deletions mitmproxy-linux-ebpf/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,23 @@
#![no_main]

use aya_ebpf::macros::{cgroup_sock, map};
use aya_ebpf::programs::SockContext;
use aya_ebpf::{EbpfContext};
use aya_ebpf::maps::Array;
use aya_log_ebpf::{debug};
use aya_ebpf::programs::SockContext;
use aya_ebpf::EbpfContext;
use aya_log_ebpf::debug;
use mitmproxy_linux_ebpf_common::{Action, INTERCEPT_CONF_LEN};

#[no_mangle]
static INTERFACE_ID: u32 = 0;


#[map]
static INTERCEPT_CONF: Array<Action> = Array::with_max_entries(INTERCEPT_CONF_LEN, 0);

#[cgroup_sock(sock_create)]
pub fn cgroup_sock_create(ctx: SockContext) -> i32 {
if should_intercept(&ctx) {
debug!(&ctx, "intercepting in sock_create");
let interface_id = unsafe {
core::ptr::read_volatile(&INTERFACE_ID)
};
let interface_id = unsafe { core::ptr::read_volatile(&INTERFACE_ID) };
unsafe {
(*ctx.sock).bound_dev_if = interface_id;
}
Expand Down
20 changes: 14 additions & 6 deletions mitmproxy-macos/redirector/ipc/mitmproxy_ipc.pb.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,14 @@ struct MitmproxyIpc_TunnelInfo: Sendable {
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.

var pid: UInt32 = 0
var pid: UInt32 {
get {return _pid ?? 0}
set {_pid = newValue}
}
/// Returns true if `pid` has been explicitly set.
var hasPid: Bool {return self._pid != nil}
/// Clears the value of `pid`. Subsequent reads from it will return its default value.
mutating func clearPid() {self._pid = nil}

var processName: String {
get {return _processName ?? String()}
Expand All @@ -65,6 +72,7 @@ struct MitmproxyIpc_TunnelInfo: Sendable {

init() {}

fileprivate var _pid: UInt32? = nil
fileprivate var _processName: String? = nil
}

Expand Down Expand Up @@ -322,7 +330,7 @@ extension MitmproxyIpc_TunnelInfo: SwiftProtobuf.Message, SwiftProtobuf._Message
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularUInt32Field(value: &self.pid) }()
case 1: try { try decoder.decodeSingularUInt32Field(value: &self._pid) }()
case 2: try { try decoder.decodeSingularStringField(value: &self._processName) }()
default: break
}
Expand All @@ -334,17 +342,17 @@ extension MitmproxyIpc_TunnelInfo: SwiftProtobuf.Message, SwiftProtobuf._Message
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
if self.pid != 0 {
try visitor.visitSingularUInt32Field(value: self.pid, fieldNumber: 1)
}
try { if let v = self._pid {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1)
} }()
try { if let v = self._processName {
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
} }()
try unknownFields.traverse(visitor: &visitor)
}

static func ==(lhs: MitmproxyIpc_TunnelInfo, rhs: MitmproxyIpc_TunnelInfo) -> Bool {
if lhs.pid != rhs.pid {return false}
if lhs._pid != rhs._pid {return false}
if lhs._processName != rhs._processName {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
Expand Down
40 changes: 20 additions & 20 deletions src/ipc/mitmproxy_ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,88 +8,88 @@
/// Packet with associated tunnel info (Windows pipe to mitmproxy)
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PacketWithMeta {
#[prost(bytes="bytes", tag="1")]
#[prost(bytes = "bytes", tag = "1")]
pub data: ::prost::bytes::Bytes,
#[prost(message, optional, tag="2")]
#[prost(message, optional, tag = "2")]
pub tunnel_info: ::core::option::Option<TunnelInfo>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TunnelInfo {
#[prost(uint32, optional, tag="1")]
#[prost(uint32, optional, tag = "1")]
pub pid: ::core::option::Option<u32>,
#[prost(string, optional, tag="2")]
#[prost(string, optional, tag = "2")]
pub process_name: ::core::option::Option<::prost::alloc::string::String>,
}
/// Packet or intercept spec (Windows pipe to redirector)
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FromProxy {
#[prost(oneof="from_proxy::Message", tags="1, 2")]
#[prost(oneof = "from_proxy::Message", tags = "1, 2")]
pub message: ::core::option::Option<from_proxy::Message>,
}
/// Nested message and enum types in `FromProxy`.
pub mod from_proxy {
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Message {
#[prost(message, tag="1")]
#[prost(message, tag = "1")]
Packet(super::Packet),
#[prost(message, tag="2")]
#[prost(message, tag = "2")]
InterceptConf(super::InterceptConf),
}
}
/// Packet (macOS UDP Stream)
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Packet {
#[prost(bytes="bytes", tag="1")]
#[prost(bytes = "bytes", tag = "1")]
pub data: ::prost::bytes::Bytes,
}
/// Intercept conf (macOS Control Stream)
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct InterceptConf {
#[prost(string, repeated, tag="1")]
#[prost(string, repeated, tag = "1")]
pub actions: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
}
/// New flow (macOS TCP/UDP Stream)
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewFlow {
#[prost(oneof="new_flow::Message", tags="1, 2")]
#[prost(oneof = "new_flow::Message", tags = "1, 2")]
pub message: ::core::option::Option<new_flow::Message>,
}
/// Nested message and enum types in `NewFlow`.
pub mod new_flow {
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Message {
#[prost(message, tag="1")]
#[prost(message, tag = "1")]
Tcp(super::TcpFlow),
#[prost(message, tag="2")]
#[prost(message, tag = "2")]
Udp(super::UdpFlow),
}
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TcpFlow {
#[prost(message, optional, tag="1")]
#[prost(message, optional, tag = "1")]
pub remote_address: ::core::option::Option<Address>,
#[prost(message, optional, tag="2")]
#[prost(message, optional, tag = "2")]
pub tunnel_info: ::core::option::Option<TunnelInfo>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UdpFlow {
#[prost(message, optional, tag="1")]
#[prost(message, optional, tag = "1")]
pub local_address: ::core::option::Option<Address>,
#[prost(message, optional, tag="3")]
#[prost(message, optional, tag = "3")]
pub tunnel_info: ::core::option::Option<TunnelInfo>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UdpPacket {
#[prost(bytes="bytes", tag="1")]
#[prost(bytes = "bytes", tag = "1")]
pub data: ::prost::bytes::Bytes,
#[prost(message, optional, tag="2")]
#[prost(message, optional, tag = "2")]
pub remote_address: ::core::option::Option<Address>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Address {
#[prost(string, tag="1")]
#[prost(string, tag = "1")]
pub host: ::prost::alloc::string::String,
#[prost(uint32, tag="2")]
#[prost(uint32, tag = "2")]
pub port: u32,
}
// @@protoc_insertion_point(module)
43 changes: 29 additions & 14 deletions src/packet_sources/linux.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::io::Error;
use std::net::Shutdown;
use anyhow::{anyhow, bail, Context, Result};
use log::{debug, error, log, Level};
use std::io::Error;
use std::net::Shutdown;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
Expand All @@ -16,10 +16,10 @@ use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use crate::intercept_conf::InterceptConf;
use crate::messages::{TransportCommand, TransportEvent};
use crate::packet_sources::{forward_packets, PacketSourceConf, PacketSourceTask};
use tempfile::{tempdir, TempDir};
use tokio::net::UnixDatagram;
use tokio::process::Command;
use tokio::time::timeout;
use tempfile::{tempdir, TempDir};

async fn start_redirector(executable: &Path, listener_addr: &Path) -> Result<PathBuf> {
debug!("Elevating privileges...");
Expand Down Expand Up @@ -85,10 +85,10 @@ async fn start_redirector(executable: &Path, listener_addr: &Path) -> Result<Pat
Duration::new(5, 0),
BufReader::new(stdout).lines().next_line(),
)
.await
.context("failed to establish connection to Linux redirector")??
.ok_or(anyhow!("redirector did not produce stdout"))
.map(PathBuf::from)
.await
.context("failed to establish connection to Linux redirector")??
.ok_or(anyhow!("redirector did not produce stdout"))
.map(PathBuf::from)
}

pub struct LinuxConf {
Expand All @@ -98,20 +98,34 @@ pub struct LinuxConf {
pub struct AsyncUnixDatagram(UnixDatagram);

impl AsyncRead for AsyncUnixDatagram {
fn poll_read(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
self.0.poll_recv(cx, buf)
}
}
impl AsyncWrite for AsyncUnixDatagram {
fn poll_write(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &[u8]) -> Poll<std::result::Result<usize, Error>> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> Poll<std::result::Result<usize, Error>> {
self.0.poll_send(cx, buf)
}

fn poll_flush(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<std::result::Result<(), Error>> {
fn poll_flush(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<std::result::Result<(), Error>> {
self.0.poll_send_ready(cx)
}

fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut std::task::Context<'_>) -> Poll<std::result::Result<(), Error>> {
fn poll_shutdown(
self: Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> Poll<std::result::Result<(), Error>> {
Poll::Ready(self.0.shutdown(Shutdown::Write))
}
}
Expand All @@ -130,15 +144,16 @@ impl PacketSourceConf for LinuxConf {
transport_commands_rx: UnboundedReceiver<TransportCommand>,
shutdown: broadcast::Receiver<()>,
) -> Result<(Self::Task, Self::Data)> {

let datagram_dir = tempdir().context("failed to create temp dir")?;

let channel = UnixDatagram::bind(datagram_dir.path().join("mitmproxy"))?;
let dst = start_redirector(&self.executable_path, datagram_dir.path()).await?;

let _ = datagram_dir.into_path(); let datagram_dir = tempdir()?; // FIXME
let _ = datagram_dir.into_path();
let datagram_dir = tempdir()?; // FIXME

channel.connect(&dst)
channel
.connect(&dst)
.with_context(|| format!("Failed to connect to redirector at {}", dst.display()))?;

let (conf_tx, conf_rx) = unbounded_channel();
Expand Down
6 changes: 3 additions & 3 deletions src/packet_sources/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use crate::intercept_conf::InterceptConf;
use crate::{ipc, MAX_PACKET_SIZE};
use crate::ipc::PacketWithMeta;
use crate::messages::{
NetworkCommand, NetworkEvent, SmolPacket, TransportCommand, TransportEvent, TunnelInfo,
};
use crate::network::add_network_layer;
use crate::{ipc, MAX_PACKET_SIZE};
use anyhow::{anyhow, Context, Result};
use log::{info, warn};
use prost::bytes::Bytes;
use prost::Message;
use std::future::Future;
use std::io::Cursor;
use log::{info, warn};
use prost::bytes::Bytes;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::mpsc::{Sender, UnboundedReceiver};
use tokio::sync::{broadcast, mpsc};
Expand Down

0 comments on commit bdee0d1

Please sign in to comment.