darkirc.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. io::Cursor,
  20. sync::{Arc, Mutex as SyncMutex, OnceLock, Weak},
  21. time::UNIX_EPOCH,
  22. };
  23. use async_trait::async_trait;
  24. use darkfi::{
  25. event_graph::{
  26. self,
  27. proto::{EventPut, ProtocolEventGraph},
  28. EventGraph, EventGraphPtr,
  29. },
  30. net::{
  31. session::SESSION_DEFAULT,
  32. settings::{MagicBytes, NetworkProfile, Settings as NetSettings},
  33. ChannelPtr, P2p, P2pPtr,
  34. },
  35. system::{sleep, Subscription},
  36. Result as DarkFiResult,
  37. };
  38. use darkfi_serial::{
  39. deserialize_async, serialize, serialize_async, AsyncEncodable, Decodable, Encodable,
  40. SerialDecodable, SerialEncodable,
  41. };
  42. use sled_overlay::sled;
  43. use crate::{
  44. error::{Error, Result},
  45. prop::{BatchGuardPtr, PropertyAtomicGuard, PropertyStr, Role},
  46. scene::{MethodCallSub, Pimpl, SceneNode, SceneNodePtr, SceneNodeType, SceneNodeWeak, Slot},
  47. ui::{
  48. chatview::{MessageId, Timestamp},
  49. OnModify,
  50. },
  51. ExecutorPtr,
  52. };
  53. use super::PluginSettings;
  54. const P2P_RETRY_TIME: u64 = 20;
  55. const COOLOFF_SLEEP_TIME: u64 = 20;
  56. const COOLOFF_SYNC_ATTEMPTS: usize = 6;
  57. const SYNC_MIN_PEERS: usize = 2;
  58. const P2P_OUTBOUND_ACTIVE: usize = 6;
  59. const P2P_OUTBOUND_SLEEP: usize = 1;
  60. /// Due to drift between different machine's clocks, if the message timestamp is recent
  61. /// then we will just correct it to the current time so messages appear sequential in the UI.
  62. const RECENT_TIME_DIST: u64 = 25_000;
  63. #[cfg(target_os = "android")]
  64. mod paths {
  65. use crate::android::{get_appdata_path, get_external_storage_path};
  66. use std::path::PathBuf;
  67. pub fn get_evgrdb_path() -> PathBuf {
  68. get_external_storage_path().join("evgr")
  69. }
  70. pub fn get_use_tor_filename() -> PathBuf {
  71. get_external_storage_path().join("use_tor.txt")
  72. }
  73. pub fn nick_filename() -> PathBuf {
  74. get_appdata_path().join("/nick.txt")
  75. }
  76. pub fn p2p_datastore_path() -> PathBuf {
  77. get_appdata_path().join("darkirc_p2p")
  78. }
  79. pub fn hostlist_path() -> PathBuf {
  80. get_appdata_path().join("hostlist.tsv")
  81. }
  82. }
  83. #[cfg(not(target_os = "android"))]
  84. mod paths {
  85. use std::path::PathBuf;
  86. pub fn get_evgrdb_path() -> PathBuf {
  87. dirs::data_local_dir().unwrap().join("darkfi/app/evgr")
  88. }
  89. pub fn get_use_tor_filename() -> PathBuf {
  90. dirs::data_local_dir().unwrap().join("darkfi/app/use_tor.txt")
  91. }
  92. pub fn nick_filename() -> PathBuf {
  93. dirs::cache_dir().unwrap().join("darkfi/app/nick.txt")
  94. }
  95. pub fn p2p_datastore_path() -> PathBuf {
  96. dirs::cache_dir().unwrap().join("darkfi/app/darkirc_p2p")
  97. }
  98. pub fn hostlist_path() -> PathBuf {
  99. dirs::cache_dir().unwrap().join("darkfi/app/hostlist.tsv")
  100. }
  101. }
  102. use paths::*;
  103. macro_rules! t { ($($arg:tt)*) => { trace!(target: "plugin::darkirc", $($arg)*); } }
  104. macro_rules! d { ($($arg:tt)*) => { debug!(target: "plugin::darkirc", $($arg)*); } }
  105. macro_rules! i { ($($arg:tt)*) => { info!(target: "plugin::darkirc", $($arg)*); } }
  106. macro_rules! e { ($($arg:tt)*) => { error!(target: "plugin::darkirc", $($arg)*); } }
  107. macro_rules! w { ($($arg:tt)*) => { warn!(target: "plugin::darkirc", $($arg)*); } }
  108. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  109. pub struct Privmsg {
  110. pub channel: String,
  111. pub nick: String,
  112. pub msg: String,
  113. }
  114. impl Privmsg {
  115. pub fn new(channel: String, nick: String, msg: String) -> Self {
  116. Self { channel, nick, msg }
  117. }
  118. pub fn msg_id(&self, timest: u64) -> MessageId {
  119. let mut hasher = blake3::Hasher::new();
  120. 0u8.encode(&mut hasher).unwrap();
  121. 0u8.encode(&mut hasher).unwrap();
  122. timest.encode(&mut hasher).unwrap();
  123. self.channel.encode(&mut hasher).unwrap();
  124. self.nick.encode(&mut hasher).unwrap();
  125. self.msg.encode(&mut hasher).unwrap();
  126. MessageId(hasher.finalize().into())
  127. }
  128. }
  129. struct SeenMsg {
  130. id: MessageId,
  131. is_self: bool,
  132. seen_times: usize,
  133. }
  134. struct SeenMessages {
  135. seen: Vec<SeenMsg>,
  136. }
  137. impl SeenMessages {
  138. fn new() -> Self {
  139. Self { seen: vec![] }
  140. }
  141. fn get_status(&self, id: &MessageId) -> Option<&SeenMsg> {
  142. self.seen.iter().find(|s| s.id == *id)
  143. }
  144. fn push(&mut self, id: MessageId, is_self: bool) {
  145. self.seen.push(SeenMsg { id, is_self, seen_times: 0 });
  146. }
  147. }
  148. pub type DarkIrcPtr = Arc<DarkIrc>;
  149. pub struct DarkIrc {
  150. node: SceneNodeWeak,
  151. tasks: OnceLock<Vec<smol::Task<()>>>,
  152. p2p: P2pPtr,
  153. event_graph: EventGraphPtr,
  154. seen_msgs: SyncMutex<SeenMessages>,
  155. nick: PropertyStr,
  156. settings: PluginSettings,
  157. }
  158. impl DarkIrc {
  159. pub async fn new(node: SceneNodeWeak, sg_root: SceneNodePtr, ex: ExecutorPtr) -> Result<Pimpl> {
  160. let node_ref = &node.upgrade().unwrap();
  161. let nick = PropertyStr::wrap(node_ref, Role::Internal, "nick", 0).unwrap();
  162. let setting_root = Arc::new(SceneNode::new("setting", SceneNodeType::SettingRoot));
  163. node_ref.link(setting_root.clone());
  164. i!("Starting DarkIRC backend");
  165. let evgr_path = get_evgrdb_path();
  166. let db = match sled::open(&evgr_path) {
  167. Ok(db) => db,
  168. Err(err) => {
  169. e!("Sled database '{}' failed to open: {err}!", evgr_path.display());
  170. return Err(Error::SledDbErr)
  171. }
  172. };
  173. let setting_tree = db.open_tree("settings")?;
  174. let settings = PluginSettings { setting_root, sled_tree: setting_tree };
  175. let mut p2p_settings: NetSettings = Default::default();
  176. p2p_settings.magic_bytes = MagicBytes([251, 229, 199, 181]);
  177. p2p_settings.app_version = semver::Version::parse("0.5.0").unwrap();
  178. p2p_settings.app_name = "darkirc".to_string();
  179. if get_use_tor_filename().exists() {
  180. i!("Setup P2P network [tor]");
  181. let mut tor_profile = NetworkProfile::tor_default();
  182. tor_profile.outbound_connect_timeout = 60;
  183. p2p_settings.profiles.insert("tor".to_string(), tor_profile);
  184. p2p_settings.outbound_peer_discovery_cooloff_time = 60;
  185. p2p_settings.seeds.push(
  186. url::Url::parse(
  187. "tor://g7fxelebievvpr27w7gt24lflptpw3jeeuvafovgliq5utdst6xyruyd.onion:25552",
  188. )
  189. .unwrap(),
  190. );
  191. p2p_settings.seeds.push(
  192. url::Url::parse(
  193. "tor://yvklzjnfmwxhyodhrkpomawjcdvcaushsj6torjz2gyd7e25f3gfunyd.onion:25552",
  194. )
  195. .unwrap(),
  196. );
  197. p2p_settings.active_profiles = vec!["tor".to_string()];
  198. } else {
  199. i!("Setup P2P network [clearnet]");
  200. let mut profile = NetworkProfile::default();
  201. profile.outbound_connect_timeout = 40;
  202. profile.channel_handshake_timeout = 30;
  203. p2p_settings.profiles.insert("tcp+tls".to_string(), profile);
  204. p2p_settings.outbound_connections = 5;
  205. p2p_settings.inbound_connections = 2;
  206. p2p_settings.seeds.push(url::Url::parse("tcp+tls://lilith0.dark.fi:25551").unwrap());
  207. p2p_settings.seeds.push(url::Url::parse("tcp+tls://lilith1.dark.fi:25551").unwrap());
  208. p2p_settings.active_profiles = vec!["tcp+tls".to_string()];
  209. }
  210. p2p_settings.p2p_datastore = p2p_datastore_path().into_os_string().into_string().ok();
  211. p2p_settings.hostlist = hostlist_path().into_os_string().into_string().ok();
  212. settings.add_p2p_settings(&p2p_settings);
  213. settings.load_settings();
  214. settings.update_p2p_settings(&mut p2p_settings);
  215. let p2p = match P2p::new(p2p_settings.clone(), ex.clone()).await {
  216. Ok(p2p) => p2p,
  217. Err(err) => {
  218. e!("Create p2p network failed: {err}!");
  219. return Err(Error::ServiceFailed)
  220. }
  221. };
  222. let event_graph = match EventGraph::new(
  223. p2p.clone(),
  224. db.clone(),
  225. std::path::PathBuf::new(),
  226. false,
  227. "darkirc_dag",
  228. 1,
  229. ex.clone(),
  230. )
  231. .await
  232. {
  233. Ok(evgr) => evgr,
  234. Err(err) => {
  235. e!("Create event graph failed: {err}!");
  236. return Err(Error::ServiceFailed)
  237. }
  238. };
  239. if let Ok(prev_nick) = std::fs::read_to_string(nick_filename()) {
  240. nick.set(&mut PropertyAtomicGuard::none(), prev_nick);
  241. }
  242. let self_ = Arc::new(Self {
  243. node: node.clone(),
  244. tasks: OnceLock::new(),
  245. p2p,
  246. event_graph,
  247. seen_msgs: SyncMutex::new(SeenMessages::new()),
  248. nick,
  249. settings,
  250. });
  251. self_.clone().start(sg_root, ex).await;
  252. Ok(Pimpl::DarkIrc(self_))
  253. }
  254. async fn dag_sync(self: Arc<Self>, channel_sub: Subscription<DarkFiResult<ChannelPtr>>) {
  255. i!("Starting p2p network");
  256. while let Err(err) = self.p2p.clone().start().await {
  257. // This usually means we cannot listen on the inbound ports
  258. e!("Failed to start p2p network: {err}!");
  259. e!("Usually this means there is another process listening on the same ports.");
  260. e!("Trying again in {P2P_RETRY_TIME} secs");
  261. sleep(P2P_RETRY_TIME).await;
  262. }
  263. i!("Waiting for some P2P connections...");
  264. let mut sync_attempt = 0;
  265. loop {
  266. // Wait for a channel
  267. if let Err(err) = channel_sub.receive().await {
  268. w!("There was an error listening for channels. The service closed unexpectedly with error: {err}");
  269. continue
  270. }
  271. let peers_count = self.p2p.peers_count();
  272. self.notify_connect(peers_count, false).await;
  273. // Wait until we have enough connections
  274. if peers_count < SYNC_MIN_PEERS {
  275. i!("Connected to {peers_count} peers. Waiting for more connections.");
  276. continue
  277. }
  278. sync_attempt += 1;
  279. // Cool off periodically
  280. if sync_attempt > COOLOFF_SYNC_ATTEMPTS {
  281. i!("Wasn't able to sync yet. Cooling off for {COOLOFF_SLEEP_TIME} then will try again.");
  282. sleep(COOLOFF_SLEEP_TIME).await;
  283. sync_attempt = 0;
  284. }
  285. i!("Syncing event DAG (attempt #{sync_attempt})");
  286. match self.event_graph.dag_sync().await {
  287. Ok(()) => break,
  288. Err(e) => {
  289. // TODO: Maybe at this point we should prune or something?
  290. // TODO: Or maybe just tell the user to delete the DAG from FS.
  291. w!("Failed DAG sync: ({e}). Waiting for more connections before retry.");
  292. }
  293. }
  294. }
  295. let peers_count = self.p2p.peers_count();
  296. self.notify_connect(peers_count, true).await;
  297. // Initial sync finished. Now just notify of connection changes
  298. loop {
  299. // Wait for a channel
  300. if let Err(err) = channel_sub.receive().await {
  301. w!("There was an error listening for channels. The service closed unexpectedly with error: {err}");
  302. continue
  303. }
  304. let peers_count = self.p2p.peers_count();
  305. self.notify_connect(peers_count, true).await;
  306. }
  307. }
  308. async fn notify_connect(&self, peers_count: usize, is_dag_synced: bool) {
  309. let node = self.node.upgrade().unwrap();
  310. node.trigger("connect", serialize(&(peers_count as u32, is_dag_synced))).await.unwrap();
  311. }
  312. async fn relay_events(self: Arc<Self>, ev_sub: Subscription<event_graph::Event>) {
  313. loop {
  314. let ev = ev_sub.receive().await;
  315. // Try to deserialize the `Event`'s content into a `Privmsg`
  316. let privmsg: Privmsg = match deserialize_async(ev.content()).await {
  317. Ok(v) => v,
  318. Err(e) => {
  319. e!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {}", e);
  320. continue
  321. }
  322. };
  323. let mut timest = ev.timestamp;
  324. let msg_id = privmsg.msg_id(timest);
  325. t!(
  326. "Relaying ev_id={:?}, ev={ev:?}, msg_id={msg_id}, privmsg={privmsg:?}, timest={timest}",
  327. ev.id(),
  328. );
  329. let is_self = {
  330. let mut is_self = false;
  331. let mut seen = self.seen_msgs.lock().unwrap();
  332. match seen.get_status(&msg_id) {
  333. Some(msg) => {
  334. is_self = msg.is_self;
  335. if !msg.is_self || msg.seen_times > 1 {
  336. warn!(target: "plugin::darkirc", "Skipping duplicate seen message: {msg_id}");
  337. continue
  338. }
  339. }
  340. None => {
  341. seen.push(msg_id.clone(), false);
  342. }
  343. }
  344. is_self
  345. };
  346. // This is a hack to make messages appear sequentially in the UI
  347. let now_timest = UNIX_EPOCH.elapsed().unwrap().as_millis() as u64;
  348. if !is_self && timest.abs_diff(now_timest) < RECENT_TIME_DIST {
  349. d!("Applied timestamp correction: <{timest}> => <{now_timest}>");
  350. timest = now_timest;
  351. }
  352. // Strip off starting #
  353. let mut channel = privmsg.channel;
  354. if channel.is_empty() {
  355. warn!(target: "plugin::darkirc", "Received privmsg with empty channel!");
  356. continue
  357. }
  358. if channel.chars().next().unwrap() != '#' {
  359. warn!(target: "plugin::darkirc", "Skipping encrypted channel: {channel}");
  360. continue
  361. }
  362. channel.remove(0);
  363. // Workaround for the chatview hack. This nick is off limits!
  364. let mut nick = privmsg.nick;
  365. if nick == "NOTICE" {
  366. nick = "noticer".to_string();
  367. }
  368. let mut arg_data = vec![];
  369. channel.encode(&mut arg_data).unwrap();
  370. timest.encode(&mut arg_data).unwrap();
  371. msg_id.encode(&mut arg_data).unwrap();
  372. nick.encode(&mut arg_data).unwrap();
  373. privmsg.msg.encode(&mut arg_data).unwrap();
  374. let node = self.node.upgrade().unwrap();
  375. node.trigger("recv", arg_data).await.unwrap();
  376. }
  377. }
  378. async fn process_send(me: &Weak<Self>, sub: &MethodCallSub) -> bool {
  379. let Ok(method_call) = sub.receive().await else {
  380. d!("Event relayer closed");
  381. return false
  382. };
  383. t!("method called: send({method_call:?})");
  384. assert!(method_call.send_res.is_none());
  385. fn decode_data(data: &[u8]) -> std::io::Result<(Timestamp, String, String)> {
  386. let mut cur = Cursor::new(&data);
  387. let timest = Timestamp::decode(&mut cur).unwrap();
  388. let channel = String::decode(&mut cur)?;
  389. let msg = String::decode(&mut cur)?;
  390. Ok((timest, channel, msg))
  391. }
  392. let Ok((timest, channel, msg)) = decode_data(&method_call.data) else {
  393. e!("send() method invalid arg data");
  394. return true
  395. };
  396. let Some(self_) = me.upgrade() else {
  397. // Should not happen
  398. panic!("self destroyed before send_method_task was stopped!");
  399. };
  400. self_.handle_send(timest, channel, msg).await;
  401. true
  402. }
  403. async fn handle_send(&self, timest: Timestamp, channel: String, msg: String) {
  404. let nick = self.nick.get();
  405. // Send text to channel
  406. d!("Sending privmsg: {timest} {channel}: <{nick}> {msg}");
  407. let msg = Privmsg::new(channel, nick, msg);
  408. let evgr = self.event_graph.clone();
  409. let mut event = event_graph::Event::new(serialize_async(&msg).await, &evgr).await;
  410. event.timestamp = timest;
  411. let msg_id = msg.msg_id(timest);
  412. // Keep track of our own messages so we don't apply timestamp correction to them
  413. // which messes up the msg id.
  414. {
  415. let mut seen = self.seen_msgs.lock().unwrap();
  416. seen.push(msg_id.clone(), true);
  417. }
  418. let mut arg_data = vec![];
  419. timest.encode_async(&mut arg_data).await.unwrap();
  420. msg_id.encode_async(&mut arg_data).await.unwrap();
  421. msg.nick.encode_async(&mut arg_data).await.unwrap();
  422. msg.msg.encode_async(&mut arg_data).await.unwrap();
  423. // Broadcast the msg
  424. if let Err(e) = evgr.dag_insert(&[event.clone()]).await {
  425. error!(target: "darkirc", "Failed inserting new event to DAG: {}", e);
  426. }
  427. self.p2p.broadcast(&EventPut(event)).await;
  428. }
  429. async fn apply_settings(self_: Arc<Self>, _: BatchGuardPtr) {
  430. self_.settings.save_settings();
  431. let p2p_settings = self_.p2p.settings();
  432. let mut write_guard = p2p_settings.write().await;
  433. self_.settings.update_p2p_settings(&mut write_guard);
  434. }
  435. async fn start(self: Arc<Self>, sg_root: SceneNodePtr, ex: ExecutorPtr) {
  436. i!("Registering EventGraph P2P protocol");
  437. let event_graph_ = Arc::clone(&self.event_graph);
  438. let registry = self.p2p.protocol_registry();
  439. registry
  440. .register(SESSION_DEFAULT, move |channel, _| {
  441. let event_graph_ = event_graph_.clone();
  442. async move { ProtocolEventGraph::init(event_graph_, channel).await.unwrap() }
  443. })
  444. .await;
  445. let me = Arc::downgrade(&self);
  446. let node = &self.node.upgrade().unwrap();
  447. let method_sub = node.subscribe_method_call("send").unwrap();
  448. let me2 = me.clone();
  449. let send_method_task =
  450. ex.spawn(async move { while Self::process_send(&me2, &method_sub).await {} });
  451. let mut on_modify = OnModify::new(ex.clone(), self.node.clone(), me.clone());
  452. async fn save_nick(self_: Arc<DarkIrc>, _batch: BatchGuardPtr) {
  453. let _ = std::fs::write(nick_filename(), self_.nick.get());
  454. }
  455. on_modify.when_change(self.nick.prop(), save_nick);
  456. // `apply_settings` is triggered if any setting changes
  457. for setting_node in self.settings.setting_root.get_children().iter() {
  458. on_modify.when_change(
  459. setting_node.get_property("value").clone().unwrap(),
  460. Self::apply_settings,
  461. );
  462. }
  463. let ev_sub = self.event_graph.event_pub.clone().subscribe().await;
  464. let ev_task = ex.spawn(self.clone().relay_events(ev_sub));
  465. // Sync the DAG
  466. let channel_sub = self.p2p.hosts().subscribe_channel().await;
  467. let dag_task = ex.spawn(self.clone().dag_sync(channel_sub));
  468. // Subscribe to window start/stop signals for dynamic outbound connections
  469. let window_node = sg_root.lookup_node("/window").unwrap();
  470. let (start_slot, start_recv) = Slot::new("app_start");
  471. window_node.register("start", start_slot).unwrap();
  472. let p2p = self.p2p.clone();
  473. let start_task = ex.spawn(async move {
  474. while let Ok(_) = start_recv.recv().await {
  475. i!("App started: set outbound connections to {P2P_OUTBOUND_ACTIVE}");
  476. p2p.settings().write().await.outbound_connections = P2P_OUTBOUND_ACTIVE;
  477. p2p.clone().reload().await;
  478. }
  479. });
  480. let (stop_slot, stop_recv) = Slot::new("app_stop");
  481. window_node.register("stop", stop_slot).unwrap();
  482. let p2p = self.p2p.clone();
  483. let stop_task = ex.spawn(async move {
  484. while let Ok(_) = stop_recv.recv().await {
  485. i!("App stopped: set outbound connections to {P2P_OUTBOUND_SLEEP}");
  486. p2p.settings().write().await.outbound_connections = P2P_OUTBOUND_SLEEP;
  487. p2p.clone().reload().await;
  488. }
  489. });
  490. let mut tasks = vec![send_method_task, ev_task, dag_task, start_task, stop_task];
  491. tasks.append(&mut on_modify.tasks);
  492. self.tasks.set(tasks).unwrap();
  493. }
  494. }