nickserv.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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. str::{FromStr, SplitAsciiWhitespace},
  20. sync::Arc,
  21. };
  22. use darkfi::Result;
  23. use darkfi_sdk::crypto::SecretKey;
  24. use darkfi_serial::serialize_async;
  25. use smol::lock::RwLock;
  26. use super::{
  27. super::{client::ReplyType, rpl::*},
  28. rln::RlnIdentity,
  29. };
  30. use crate::IrcServer;
  31. const ACCOUNTS_DB_PREFIX: &str = "darkirc_account_";
  32. const ACCOUNTS_KEY_RLN_IDENTITY: &[u8] = b"rln_identity";
  33. const NICKSERV_USAGE: &str = r#"***** NickServ Help *****
  34. NickServ allows a client to perform account management on DarkIRC.
  35. The following commands are available:
  36. INFO Displays information on registrations.
  37. REGISTER Register an account.
  38. DEREGISTER Deregister an account.
  39. SET Select an account to use.
  40. For more information on a NickServ command, type:
  41. /msg NickServ HELP <command>
  42. ***** End of Help *****
  43. "#;
  44. /// NickServ implementation used for IRC account management
  45. pub struct NickServ {
  46. /// Client username
  47. pub _username: Arc<RwLock<String>>,
  48. /// Client nickname
  49. pub nickname: Arc<RwLock<String>>,
  50. /// Pointer to parent `IrcServer`
  51. pub server: Arc<IrcServer>,
  52. }
  53. impl NickServ {
  54. /// Instantiate a new `NickServ` for a client. This should be called after
  55. /// the user/nick are successfully registered.
  56. pub async fn new(
  57. _username: Arc<RwLock<String>>,
  58. nickname: Arc<RwLock<String>>,
  59. server: Arc<IrcServer>,
  60. ) -> Result<Self> {
  61. Ok(Self { _username, nickname, server })
  62. }
  63. /// Handle a `NickServ` query. This is the main command handler.
  64. /// Called from `command::handle_cmd_privmsg`.
  65. pub async fn handle_query(&self, query: &str) -> Result<Vec<ReplyType>> {
  66. let nick = self.nickname.read().await.to_string();
  67. let mut tokens = query.split_ascii_whitespace();
  68. let Some(command) = tokens.next() else {
  69. return Ok(vec![ReplyType::Server((
  70. ERR_NOTEXTTOSEND,
  71. format!("{} :No text to send", nick),
  72. ))])
  73. };
  74. match command.to_uppercase().as_str() {
  75. "INFO" => self.handle_info(&nick, &mut tokens).await,
  76. "REGISTER" => self.handle_register(&nick, &mut tokens).await,
  77. "DEREGISTER" => self.handle_deregister(&nick, &mut tokens).await,
  78. "SET" => self.handle_set(&nick, &mut tokens).await,
  79. "HELP" => self.handle_help(&nick).await,
  80. _ => self.handle_invalid(&nick).await,
  81. }
  82. }
  83. /// Handle the INFO command
  84. pub async fn handle_info(
  85. &self,
  86. _nick: &str,
  87. _tokens: &mut SplitAsciiWhitespace<'_>,
  88. ) -> Result<Vec<ReplyType>> {
  89. todo!()
  90. }
  91. /// Handle the REGISTER command
  92. pub async fn handle_register(
  93. &self,
  94. nick: &str,
  95. tokens: &mut SplitAsciiWhitespace<'_>,
  96. ) -> Result<Vec<ReplyType>> {
  97. // Gather the tokens
  98. let account_name = tokens.next();
  99. let identity_nullifier = tokens.next();
  100. let identity_trapdoor = tokens.next();
  101. let leaf_pos = tokens.next();
  102. if account_name.is_none() ||
  103. identity_nullifier.is_none() ||
  104. identity_trapdoor.is_none() ||
  105. leaf_pos.is_none()
  106. {
  107. return Ok(vec![
  108. ReplyType::Notice((
  109. "NickServ".to_string(),
  110. nick.to_string(),
  111. "Invalid syntax.".to_string(),
  112. )),
  113. ReplyType::Notice((
  114. "NickServ".to_string(),
  115. nick.to_string(),
  116. "Use `REGISTER <account_name> <identity_nullifier> <identity_trapdoor> <leaf_pos>`."
  117. .to_string(),
  118. )),
  119. ])
  120. };
  121. let account_name = account_name.unwrap();
  122. let identity_nullifier = identity_nullifier.unwrap();
  123. let identity_trapdoor = identity_trapdoor.unwrap();
  124. let leaf_pos = leaf_pos.unwrap();
  125. // Open the sled tree
  126. let db = self
  127. .server
  128. .darkirc
  129. .sled
  130. .open_tree(format!("{}{}", ACCOUNTS_DB_PREFIX, account_name))?;
  131. if !db.is_empty() {
  132. return Ok(vec![ReplyType::Notice((
  133. "NickServ".to_string(),
  134. nick.to_string(),
  135. "This account name is already registered.".to_string(),
  136. ))])
  137. }
  138. // TODO: WIF
  139. // Parse the secrets
  140. let identity_nullifier = match SecretKey::from_str(identity_nullifier) {
  141. Ok(v) => v,
  142. Err(e) => {
  143. return Ok(vec![ReplyType::Notice((
  144. "NickServ".to_string(),
  145. nick.to_string(),
  146. format!("Invalid identity_nullifier: {}", e),
  147. ))])
  148. }
  149. };
  150. let identity_trapdoor = match SecretKey::from_str(identity_trapdoor) {
  151. Ok(v) => v,
  152. Err(e) => {
  153. return Ok(vec![ReplyType::Notice((
  154. "NickServ".to_string(),
  155. nick.to_string(),
  156. format!("Invalid identity_trapdoor: {}", e),
  157. ))])
  158. }
  159. };
  160. let leaf_pos = match u64::from_str(leaf_pos) {
  161. Ok(v) => v,
  162. Err(e) => {
  163. return Ok(vec![ReplyType::Notice((
  164. "NickServ".to_string(),
  165. nick.to_string(),
  166. format!("Invalid leaf_pos: {}", e),
  167. ))])
  168. }
  169. };
  170. // Create a new RLN identity and insert it into the db tree
  171. let rln_identity =
  172. RlnIdentity { identity_nullifier, identity_trapdoor, leaf_pos: leaf_pos.into() };
  173. db.insert(ACCOUNTS_KEY_RLN_IDENTITY, serialize_async(&rln_identity).await)?;
  174. Ok(vec![ReplyType::Notice((
  175. "NickServ".to_string(),
  176. nick.to_string(),
  177. format!("Successfully registered account \"{}\"", account_name),
  178. ))])
  179. }
  180. /// Handle the DEREGISTER command
  181. pub async fn handle_deregister(
  182. &self,
  183. nick: &str,
  184. tokens: &mut SplitAsciiWhitespace<'_>,
  185. ) -> Result<Vec<ReplyType>> {
  186. let Some(account_name) = tokens.next() else {
  187. return Ok(vec![ReplyType::Notice((
  188. "NickServ".to_string(),
  189. nick.to_string(),
  190. "Invalid syntax. Use `DEREGISTER <account_name>`.".to_string(),
  191. ))])
  192. };
  193. // Drop the tree
  194. self.server.darkirc.sled.drop_tree(format!("{}{}", ACCOUNTS_DB_PREFIX, account_name))?;
  195. Ok(vec![ReplyType::Notice((
  196. "NickServ".to_string(),
  197. nick.to_string(),
  198. format!("Successfully deregistered account \"{}\"", account_name),
  199. ))])
  200. }
  201. /// Handle the SET command
  202. pub async fn handle_set(
  203. &self,
  204. _nick: &str,
  205. _tokens: &mut SplitAsciiWhitespace<'_>,
  206. ) -> Result<Vec<ReplyType>> {
  207. todo!()
  208. }
  209. /// Reply to the HELP command
  210. pub async fn handle_help(&self, nick: &str) -> Result<Vec<ReplyType>> {
  211. let replies = NICKSERV_USAGE
  212. .lines()
  213. .map(|x| ReplyType::Notice(("NickServ".to_string(), nick.to_string(), x.to_string())))
  214. .collect();
  215. Ok(replies)
  216. }
  217. /// Reply to an invalid command
  218. pub async fn handle_invalid(&self, nick: &str) -> Result<Vec<ReplyType>> {
  219. let replies = vec![
  220. ReplyType::Notice((
  221. "NickServ".to_string(),
  222. nick.to_string(),
  223. "Invalid NickServ command.".to_string(),
  224. )),
  225. ReplyType::Notice((
  226. "NickServ".to_string(),
  227. nick.to_string(),
  228. "Use /msg NickServ HELP for a NickServ command listing.".to_string(),
  229. )),
  230. ];
  231. Ok(replies)
  232. }
  233. }