Commit 1934ca1f41

1934ca1f418d4b1038e61466ab94284e9c9505ff

parent: f2f65f98be

Unregistered key

Ulyssa <git@ulyssa.dev> · 2026-08-15 22:33 UTC
committer: <noreply@github.com>

Add support for SOCKS and HTTPS proxying (#640)

Co-authored-by: vaw <git@nlih.de>
Co-authored-by: Kara Zajac <kara@soulstone.org>

Layout: unified · split

Cargo.lock +11
@@ -2269,6 +2269,16 @@ dependencies = [
22692269 "pin-project-lite",
22702270]
22712271
2272[[package]]
2273name = "http-serde"
2274version = "2.1.1"
2275source = "registry+https://github.com/rust-lang/crates.io-index"
2276checksum = "0f056c8559e3757392c8d091e796416e4649d8e49e88b8d76df6c002f05027fd"
2277dependencies = [
2278 "http",
2279 "serde",
2280]
2281
22722282[[package]]
22732283name = "httparse"
22742284version = "1.10.1"
@@ -2368,6 +2378,7 @@ dependencies = [
23682378 "futures",
23692379 "gethostname",
23702380 "html5ever",
2381 "http-serde",
23712382 "humansize",
23722383 "image",
23732384 "lazy_static 1.5.0",
Cargo.toml +2 −1
@@ -38,6 +38,7 @@ feruca = "0.11"
3838futures = "0.3"
3939gethostname = "1.1"
4040html5ever = "0.39.0"
41http-serde = "2.1.1"
4142humansize = "2.0.0"
4243image = "0.25.6"
4344libc = "0.2"
@@ -89,7 +90,7 @@ version = "0.0.25"
8990[dependencies.matrix-sdk]
9091version = "0.18.0"
9192default-features = false
92features = ["e2e-encryption", "sqlite", "sso-login"]
93features = ["e2e-encryption", "socks", "sqlite", "sso-login"]
9394
9495[dependencies.matrix-sdk-crypto]
9596version = "0.18.0"
config.example.toml +5
@@ -30,6 +30,11 @@ indicator_location = "title|prompt"
3030protocol.type = "sixel"
3131size = { "width" = 66, "height" = 10 }
3232
33[settings.proxy]
34url = "" # An empty string disables any proxying
35auth = "Bearer abcd1234"
36headers.X-Proxy-Config = "foobar"
37
3338[settings.sort]
3439rooms = ["favorite", "lowpriority", "unread", "name"]
3540members = ["power", "id"]
docs/iamb.1 +6 −1
@@ -309,12 +309,17 @@ The behaviour of
309309.Nm
310310is affected by the following environment variables.
311311.Bl -tag -width Ds
312.It Sy "ALL_PROXY, HTTP_PROXY, HTTPS_PROXY"
313Sets the proxy server to use.
314These names also work in lowercase.
315Example:
316.Dq export ALL_PROXY=socks5://localhost:9050 .
312317.It Sy "RUST_LOG"
313318Overwrites the value set by the
314319.Sy log_level
315320config value.
316321The syntax is defined at
317.Lk https://docs.rs/tracing-subscriber/0.3.16/tracing_subscriber/filter/struct.EnvFilter.html
322.Lk https://docs.rs/tracing_subscriber/0.3.16/tracing_subscriber/filter/struct.EnvFilter.html
318323
319324.Sh EXAMPLES
320325.Ss Example 1: Starting with a specific profile
docs/iamb.5 +33
@@ -218,6 +218,11 @@ for more details.
218218Defines a custom command and its arguments to run when opening downloads instead of the default.
219219(For example,
220220.Sy ["my-open",\ "--file"] . )
221.Sy proxy
222When this subsection is present, you can configure how requests are proxied to the homeserver.
223See
224.Sx PROXYING
225for more details.
221226.It Sy reaction_display
222227Defines whether or not reactions should be shown.
223228.It Sy reaction_shortcode_display
@@ -376,6 +381,34 @@ enabled = true
376381sound_hint = "message-new-instant" # Linux
377382sound_hint = "IM" # Windows
378383.Ed
384.Sh "PROXYING"
385The
386.Sy settings.proxy
387subsection allows configuring proxying for requests to the homeserver.
388.Pp
389Fields available within this subsection are:
390.Bl -tag -width Ds
391.It Sy url
392Either a
393.Sy socks5://IP:PORT
394URL for a SOCKS server to proxy request through,
395or a
396.Sy http[s]://[USER:PASS@]HOST[:PORT]/
397URL to do HTTP(S) proxying through.
398Setting this to the empty string will explicitly disable proxying, and any environment variables will be ignored.
399.It Sy auth
400A value to send in a
401.Sy Proxy-Authorization
402header if your HTTP(S) proxy requires it,
403such as for doing Bearer authentication with a token.
404.It Sy headers
405A subsection for specifying additional headers and values to include in requests sent to the proxy.
406For example, custom HTTPS proxy server software may require specifying a
407.Sy User-Agent
408or a custom header like
409.Sy X-Proxy-Token
410in order to be allowed to send request through it.
411.El
379412.Sh "SORTING LISTS"
380413The
381414.Sy settings.sort
src/config.rs +192 −50
@@ -9,9 +9,11 @@ use std::hash::{Hash, Hasher};
99use std::io::{BufReader, BufWriter, Write};
1010use std::path::{Path, PathBuf};
1111use std::process;
12use std::str::FromStr;
1213
1314use clap::Parser;
1415use matrix_sdk::authentication::matrix::MatrixSession;
16use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
1517use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
1618use matrix_sdk::EncryptionState;
1719use ratatui::style::{Color, Modifier as StyleModifier, Style};
@@ -123,6 +125,20 @@ fn validate_profile_names(names: &BTreeMap<String, ProfileConfig>) {
123125 }
124126}
125127
128fn deserialize_from_str_opt<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
129where
130 D: serde::de::Deserializer<'de>,
131 T: FromStr,
132 <T as FromStr>::Err: fmt::Display,
133{
134 <Option<&'de str>>::deserialize(deserializer)?
135 .map(|s| {
136 let t = T::from_str(s);
137 t.map_err(|e| D::Error::custom(format!("failed to parse string: {e}")))
138 })
139 .transpose()
140}
141
126142const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
127143 None => env!("CARGO_PKG_VERSION"),
128144 Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
@@ -154,6 +170,26 @@ pub enum ConfigError {
154170 InvalidJSON(#[from] serde_json::Error),
155171}
156172
173macro_rules! deserialize_str_with_visitor {
174 ($t: ident, $v: ident) => {
175 impl<'de> Deserialize<'de> for $t {
176 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
177 where
178 D: Deserializer<'de>,
179 {
180 deserializer.deserialize_str($v)
181 }
182 }
183 };
184}
185
186deserialize_str_with_visitor!(Keys, KeysVisitor);
187deserialize_str_with_visitor!(VimModes, VimModesVisitor);
188deserialize_str_with_visitor!(UserColor, UserColorVisitor);
189deserialize_str_with_visitor!(EncryptionIndicatorLocation, EncryptionIndicatorLocationVisitor);
190deserialize_str_with_visitor!(NotifyVia, NotifyViaVisitor);
191deserialize_str_with_visitor!(ProxyUrl, ProxyUrlVisitor);
192
157193#[derive(Clone, Debug, Eq, Hash, PartialEq)]
158194pub struct Keys(pub Vec<TerminalKey>, pub String);
159195pub struct KeysVisitor;
@@ -176,15 +212,6 @@ impl Visitor<'_> for KeysVisitor {
176212 }
177213}
178214
179impl<'de> Deserialize<'de> for Keys {
180 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
181 where
182 D: Deserializer<'de>,
183 {
184 deserializer.deserialize_str(KeysVisitor)
185 }
186}
187
188215#[derive(Clone, Debug, Eq, Hash, PartialEq)]
189216pub struct VimModes(pub Vec<VimMode>);
190217pub struct VimModesVisitor;
@@ -220,15 +247,6 @@ impl Visitor<'_> for VimModesVisitor {
220247 }
221248}
222249
223impl<'de> Deserialize<'de> for VimModes {
224 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225 where
226 D: Deserializer<'de>,
227 {
228 deserializer.deserialize_str(VimModesVisitor)
229 }
230}
231
232250#[derive(Clone, Debug, Eq, PartialEq)]
233251pub struct UserColor(pub Color);
234252pub struct UserColorVisitor;
@@ -267,15 +285,6 @@ impl Visitor<'_> for UserColorVisitor {
267285 }
268286}
269287
270impl<'de> Deserialize<'de> for UserColor {
271 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
272 where
273 D: Deserializer<'de>,
274 {
275 deserializer.deserialize_str(UserColorVisitor)
276 }
277}
278
279288#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
280289pub struct Session {
281290 access_token: String,
@@ -392,15 +401,6 @@ impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
392401 }
393402}
394403
395impl<'de> Deserialize<'de> for EncryptionIndicatorLocation {
396 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
397 where
398 D: Deserializer<'de>,
399 {
400 deserializer.deserialize_str(EncryptionIndicatorLocationVisitor)
401 }
402}
403
404404#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
405405#[serde(rename_all = "lowercase")]
406406pub enum UserDisplayStyle {
@@ -485,15 +485,6 @@ impl Visitor<'_> for NotifyViaVisitor {
485485 }
486486}
487487
488impl<'de> Deserialize<'de> for NotifyVia {
489 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
490 where
491 D: Deserializer<'de>,
492 {
493 deserializer.deserialize_str(NotifyViaVisitor)
494 }
495}
496
497488#[derive(Clone, Debug, Default, Deserialize)]
498489pub struct Encryption {
499490 indicator: Option<EncryptionIndicator>,
@@ -564,6 +555,69 @@ impl EncryptionValues {
564555 }
565556}
566557
558#[derive(Clone, Debug, Default, Eq, PartialEq)]
559pub enum ProxyUrl {
560 Disabled,
561 Endpoint(Url),
562 #[default]
563 System,
564}
565
566pub struct ProxyUrlVisitor;
567
568impl Visitor<'_> for ProxyUrlVisitor {
569 type Value = ProxyUrl;
570
571 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
572 formatter.write_str("a valid proxy URL (e.g. \"socks5://localhost:9050\")")
573 }
574
575 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
576 where
577 E: SerdeError,
578 {
579 if value.is_empty() {
580 return Ok(ProxyUrl::Disabled);
581 }
582
583 match Url::from_str(value) {
584 Ok(uri) => Ok(ProxyUrl::Endpoint(uri)),
585 Err(e) => Err(E::custom(format!("could not parse {value:?}: {e}"))),
586 }
587 }
588}
589
590#[derive(Clone, Debug, Default, Deserialize)]
591pub struct Proxy {
592 /// How and where to proxy the client's requests to the homeserver.
593 url: Option<ProxyUrl>,
594
595 /// An optional value to include in the `Proxy-Authorization` header.
596 #[serde(default, deserialize_with = "deserialize_from_str_opt")]
597 auth: Option<HeaderValue>,
598
599 /// Optional headers to include in requests sent to the proxy.
600 #[serde(default, with = "http_serde::header_map")]
601 headers: HeaderMap,
602}
603
604impl Proxy {
605 pub fn values(self) -> ProxyValues {
606 ProxyValues {
607 url: self.url.unwrap_or_default(),
608 auth: self.auth,
609 headers: self.headers,
610 }
611 }
612}
613
614#[derive(Clone, Debug, Default)]
615pub struct ProxyValues {
616 pub url: ProxyUrl,
617 pub auth: Option<HeaderValue>,
618 pub headers: HeaderMap,
619}
620
567621#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
568622pub struct Mouse {
569623 #[serde(default)]
@@ -589,7 +643,7 @@ pub struct ImagePreviewValues {
589643 pub protocol: Option<ImagePreviewProtocolValues>,
590644}
591645
592#[derive(Clone, Default, Deserialize)]
646#[derive(Clone, Debug, Default, Deserialize)]
593647pub struct ImagePreview {
594648 pub lazy_load: Option<bool>,
595649 pub size: Option<ImagePreviewSize>,
@@ -618,7 +672,7 @@ impl Default for ImagePreviewSize {
618672 }
619673}
620674
621#[derive(Clone, Deserialize)]
675#[derive(Clone, Debug, Deserialize)]
622676pub struct ImagePreviewProtocolValues {
623677 pub r#type: Option<ProtocolType>,
624678 pub font_size: Option<(u16, u16)>,
@@ -633,7 +687,7 @@ pub struct SortValues {
633687 pub members: Vec<SortColumn<SortFieldUser>>,
634688}
635689
636#[derive(Clone, Default, Deserialize)]
690#[derive(Clone, Debug, Default, Deserialize)]
637691pub struct SortOverrides {
638692 pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
639693 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
@@ -696,6 +750,8 @@ pub struct TerminalValues {
696750 pub enable_title: bool,
697751}
698752
753/// The configuration settings to run with, after merging the
754/// per-profile overrides on top of the global settings.
699755#[derive(Clone)]
700756pub struct TunableValues {
701757 pub encryption: EncryptionValues,
@@ -703,6 +759,7 @@ pub struct TunableValues {
703759 pub max_log_files: usize,
704760 pub message_shortcode_display: bool,
705761 pub normal_after_send: bool,
762 pub proxy: ProxyValues,
706763 pub reaction_display: bool,
707764 pub reaction_shortcode_display: bool,
708765 pub read_receipt_send: bool,
@@ -728,12 +785,15 @@ pub struct TunableValues {
728785 pub ssl_verify: bool,
729786}
730787
731#[derive(Clone, Default, Deserialize)]
788#[derive(Clone, Debug, Default, Deserialize)]
732789pub struct Tunables {
733790 /// Subsection for overriding encryption-related settings.
734791 #[serde(default)]
735792 pub encryption: Encryption,
736793
794 /// Subsection for configuring an HTTP(S) proxy.
795 pub proxy: Option<Proxy>,
796
737797 /// Subsection for overriding sort orders in UI lists.
738798 #[serde(default)]
739799 pub sort: SortOverrides,
@@ -779,6 +839,11 @@ impl Tunables {
779839 terminal: Terminal::merge(self.terminal, other.terminal),
780840 users: merge_maps(self.users, other.users),
781841
842 // Proxy configuration sub-field do *not* get merged, so that a
843 // per-profile override won't inherit auth or headers from the
844 // global settings.
845 proxy: self.proxy.or(other.proxy),
846
782847 log_level: self.log_level.or(other.log_level),
783848 max_log_files: self.max_log_files.or(other.max_log_files),
784849 message_shortcode_display: self
@@ -815,8 +880,10 @@ impl Tunables {
815880 fn values(self) -> TunableValues {
816881 TunableValues {
817882 encryption: self.encryption.values(),
883 proxy: self.proxy.unwrap_or_default().values(),
818884 sort: self.sort.values(),
819885 terminal: self.terminal.values(),
886 users: self.users.unwrap_or_default(),
820887
821888 log_level: self.log_level.unwrap_or_else(|| "warn".to_string()),
822889 max_log_files: self.max_log_files.unwrap_or(7),
@@ -830,7 +897,6 @@ impl Tunables {
830897 state_event_display: self.state_event_display.unwrap_or(true),
831898 typing_notice_send: self.typing_notice_send.unwrap_or(true),
832899 typing_notice_display: self.typing_notice_display.unwrap_or(true),
833 users: self.users.unwrap_or_default(),
834900 username_display: self.username_display.unwrap_or_default(),
835901 message_user_color: self.message_user_color.unwrap_or(false),
836902 default_room: self.default_room,
@@ -1424,6 +1490,82 @@ mod tests {
14241490 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
14251491 }
14261492
1493 #[test]
1494 fn test_parse_tunables_proxy_invalid() {
1495 let res =
1496 serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();
1497
1498 // Should result in a validation error:
1499 assert_eq!(res.classify(), serde_json::error::Category::Data);
1500 }
1501
1502 #[test]
1503 fn test_parse_tunables_proxy_empty() {
1504 let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
1505 let proxy = res.proxy.unwrap();
1506 assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
1507 }
1508
1509 #[test]
1510 fn test_parse_tunables_proxy_socks5() {
1511 let res: Tunables =
1512 serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1513 let proxy = res.proxy.unwrap();
1514 let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1515 panic!("should parse ProxyUrl::Endpoint")
1516 };
1517
1518 assert_eq!(url.scheme(), "socks5");
1519 assert_eq!(url.host_str().unwrap(), "localhost");
1520 assert_eq!(url.port().unwrap(), 1080);
1521 assert_eq!(url.authority(), "localhost:1080");
1522 }
1523
1524 #[test]
1525 fn test_parse_tunables_proxy_https() {
1526 let res: Tunables = serde_json::from_str(
1527 r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1528 ).unwrap();
1529 let proxy = res.proxy.unwrap();
1530 let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1531 panic!("should parse ProxyUrl::Endpoint")
1532 };
1533
1534 // Verify URL fields:
1535 assert_eq!(url.scheme(), "https");
1536 assert_eq!(url.host_str().unwrap(), "localhost");
1537 assert_eq!(url.port().unwrap(), 8080);
1538 assert_eq!(url.authority(), "localhost:8080");
1539
1540 // Verify our `Proxy-Authorization` value:
1541 assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");
1542
1543 // Verify our custom header is present:
1544 assert_eq!(proxy.headers.len(), 1);
1545 assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
1546 }
1547
1548 #[test]
1549 fn test_parse_tunables_proxy_merge() {
1550 let global: Tunables = serde_json::from_str(
1551 r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1552 ).unwrap();
1553 let profile: Tunables =
1554 serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1555
1556 // The configuration merge should select the entirety of the profile proxy config,
1557 // and not merge subfields, to ensure that things like `auth` and `headers` are
1558 // not ever sent to a `url` they were meant for.
1559 let merged = profile.merge(global).values();
1560 let ProxyUrl::Endpoint(url) = merged.proxy.url else {
1561 panic!("should parse ProxyUrl::Endpoint")
1562 };
1563 assert_eq!(url.scheme(), "socks5");
1564 assert_eq!(url.authority(), "localhost:1080");
1565 assert_eq!(merged.proxy.auth, None);
1566 assert_eq!(merged.proxy.headers.is_empty(), true);
1567 }
1568
14271569 #[test]
14281570 fn test_parse_layout() {
14291571 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
src/tests.rs +2 −16
@@ -23,22 +23,7 @@ use tokio::sync::mpsc::unbounded_channel;
2323use crate::message::MessageTimeStamp;
2424use crate::{
2525 base::{ChatStore, EventLocation, ProgramStore, RoomInfo},
26 config::{
27 user_color,
28 user_style_from_color,
29 ApplicationSettings,
30 DirectoryValues,
31 Encryption,
32 Notifications,
33 NotifyVia,
34 ProfileConfig,
35 SortOverrides,
36 Terminal,
37 TunableValues,
38 UserColor,
39 UserDisplayStyle,
40 UserDisplayTunables,
41 },
26 config::*,
4227 message::{Message, MessageEvent, MessageKey, Messages},
4328 worker::Requester,
4429};
@@ -187,6 +172,7 @@ pub fn mock_tunables() -> TunableValues {
187172 max_log_files: 7,
188173 message_shortcode_display: false,
189174 normal_after_send: true,
175 proxy: Proxy::default().values(),
190176 reaction_display: true,
191177 reaction_shortcode_display: false,
192178 read_receipt_send: true,
src/worker.rs +31 −5
@@ -95,7 +95,7 @@ use modalkit::errors::UIError;
9595use modalkit::prelude::{EditInfo, InfoMessage};
9696
9797use crate::base::{EchoLocation, MessageNeed};
98use crate::config::ImagePreviewSize;
98use crate::config::{ImagePreviewSize, ProxyUrl};
9999use crate::message::{Message, MessageEvent, MessageId, MessageKey};
100100use crate::notifications::register_notifications;
101101use crate::preview::load_image;
@@ -808,15 +808,41 @@ async fn create_client_inner(
808808 let req_timeout = Duration::from_secs(settings.tunables.request_timeout);
809809
810810 // Set up the HTTP client.
811 let http = reqwest::Client::builder()
811 let mut builder = reqwest::Client::builder()
812812 .user_agent(IAMB_USER_AGENT)
813813 .timeout(req_timeout)
814814 .pool_idle_timeout(Duration::from_secs(60))
815815 .pool_max_idle_per_host(10)
816816 .tcp_keepalive(Duration::from_secs(10))
817 .danger_accept_invalid_certs(!settings.tunables.ssl_verify)
818 .build()
819 .unwrap();
817 .danger_accept_invalid_certs(!settings.tunables.ssl_verify);
818
819 // Configure the HTTP client to use any provided proxy settings:
820 let proxy_config = &settings.tunables.proxy;
821
822 match &proxy_config.url {
823 ProxyUrl::Disabled => builder = builder.no_proxy(),
824 ProxyUrl::Endpoint(url) => {
825 let mut proxy =
826 reqwest::Proxy::all(url.clone()).map_err(matrix_sdk::HttpError::Reqwest)?;
827
828 if !proxy_config.headers.is_empty() {
829 proxy = proxy.headers(proxy_config.headers.clone());
830 }
831
832 if let Some(auth) = proxy_config.auth.clone() {
833 proxy = proxy.custom_http_auth(auth);
834 }
835
836 builder = builder.proxy(proxy)
837 },
838 ProxyUrl::System => {
839 // `reqwest` will use the *_PROXY environment variables from the
840 // system by default (through `hyper_util::client::proxy`), so do
841 // nothing and let it just figure things out for us.
842 },
843 }
844
845 let http = builder.build().map_err(matrix_sdk::HttpError::Reqwest)?;
820846
821847 let req_config = RequestConfig::new().timeout(req_timeout).max_retry_time(req_timeout);
822848