darkirc.rs 19 KB

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