discovery.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. use base64;
  2. use crypto;
  3. use crypto::digest::Digest;
  4. use crypto::mac::Mac;
  5. use futures::sync::mpsc;
  6. use futures::{Future, Poll, Stream};
  7. use hyper::server::{Http, Request, Response, Service};
  8. use hyper::{self, Get, Post, StatusCode};
  9. #[cfg(feature = "with-dns-sd")]
  10. use dns_sd::DNSService;
  11. #[cfg(not(feature = "with-dns-sd"))]
  12. use mdns;
  13. use num_bigint::BigUint;
  14. use rand;
  15. use std::collections::BTreeMap;
  16. use std::io;
  17. use std::sync::Arc;
  18. use tokio_core::reactor::Handle;
  19. use url;
  20. use core::authentication::Credentials;
  21. use core::config::ConnectConfig;
  22. use core::diffie_hellman::{DH_GENERATOR, DH_PRIME};
  23. use core::util;
  24. #[derive(Clone)]
  25. struct Discovery(Arc<DiscoveryInner>);
  26. struct DiscoveryInner {
  27. config: ConnectConfig,
  28. device_id: String,
  29. private_key: BigUint,
  30. public_key: BigUint,
  31. tx: mpsc::UnboundedSender<Credentials>,
  32. }
  33. impl Discovery {
  34. fn new(
  35. config: ConnectConfig,
  36. device_id: String,
  37. ) -> (Discovery, mpsc::UnboundedReceiver<Credentials>) {
  38. let (tx, rx) = mpsc::unbounded();
  39. let key_data = util::rand_vec(&mut rand::thread_rng(), 95);
  40. let private_key = BigUint::from_bytes_be(&key_data);
  41. let public_key = util::powm(&DH_GENERATOR, &private_key, &DH_PRIME);
  42. let discovery = Discovery(Arc::new(DiscoveryInner {
  43. config: config,
  44. device_id: device_id,
  45. private_key: private_key,
  46. public_key: public_key,
  47. tx: tx,
  48. }));
  49. (discovery, rx)
  50. }
  51. }
  52. impl Discovery {
  53. fn handle_get_info(
  54. &self,
  55. _params: &BTreeMap<String, String>,
  56. ) -> ::futures::Finished<Response, hyper::Error> {
  57. let public_key = self.0.public_key.to_bytes_be();
  58. let public_key = base64::encode(&public_key);
  59. let result = json!({
  60. "status": 101,
  61. "statusString": "ERROR-OK",
  62. "spotifyError": 0,
  63. "version": "2.1.0",
  64. "deviceID": (self.0.device_id),
  65. "remoteName": (self.0.config.name),
  66. "activeUser": "",
  67. "publicKey": (public_key),
  68. "deviceType": (self.0.config.device_type.to_string().to_uppercase()),
  69. "libraryVersion": "0.1.0",
  70. "accountReq": "PREMIUM",
  71. "brandDisplayName": "librespot",
  72. "modelDisplayName": "librespot",
  73. });
  74. let body = result.to_string();
  75. ::futures::finished(Response::new().with_body(body))
  76. }
  77. fn handle_add_user(
  78. &self,
  79. params: &BTreeMap<String, String>,
  80. ) -> ::futures::Finished<Response, hyper::Error> {
  81. let username = params.get("userName").unwrap();
  82. let encrypted_blob = params.get("blob").unwrap();
  83. let client_key = params.get("clientKey").unwrap();
  84. let encrypted_blob = base64::decode(encrypted_blob).unwrap();
  85. let client_key = base64::decode(client_key).unwrap();
  86. let client_key = BigUint::from_bytes_be(&client_key);
  87. let shared_key = util::powm(&client_key, &self.0.private_key, &DH_PRIME);
  88. let iv = &encrypted_blob[0..16];
  89. let encrypted = &encrypted_blob[16..encrypted_blob.len() - 20];
  90. let cksum = &encrypted_blob[encrypted_blob.len() - 20..encrypted_blob.len()];
  91. let base_key = {
  92. let mut data = [0u8; 20];
  93. let mut h = crypto::sha1::Sha1::new();
  94. h.input(&shared_key.to_bytes_be());
  95. h.result(&mut data);
  96. data[..16].to_owned()
  97. };
  98. let checksum_key = {
  99. let mut h = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &base_key);
  100. h.input(b"checksum");
  101. h.result().code().to_owned()
  102. };
  103. let encryption_key = {
  104. let mut h = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &base_key);
  105. h.input(b"encryption");
  106. h.result().code().to_owned()
  107. };
  108. let mac = {
  109. let mut h = crypto::hmac::Hmac::new(crypto::sha1::Sha1::new(), &checksum_key);
  110. h.input(encrypted);
  111. h.result().code().to_owned()
  112. };
  113. if mac != cksum {
  114. warn!("Login error for user {:?}: MAC mismatch", username);
  115. let result = json!({
  116. "status": 102,
  117. "spotifyError": 1,
  118. "statusString": "ERROR-MAC"
  119. });
  120. let body = result.to_string();
  121. return ::futures::finished(Response::new().with_body(body))
  122. }
  123. let decrypted = {
  124. let mut data = vec![0u8; encrypted.len()];
  125. let mut cipher =
  126. crypto::aes::ctr(crypto::aes::KeySize::KeySize128, &encryption_key[0..16], iv);
  127. cipher.process(encrypted, &mut data);
  128. String::from_utf8(data).unwrap()
  129. };
  130. let credentials = Credentials::with_blob(username.to_owned(), &decrypted, &self.0.device_id);
  131. self.0.tx.unbounded_send(credentials).unwrap();
  132. let result = json!({
  133. "status": 101,
  134. "spotifyError": 0,
  135. "statusString": "ERROR-OK"
  136. });
  137. let body = result.to_string();
  138. ::futures::finished(Response::new().with_body(body))
  139. }
  140. fn not_found(&self) -> ::futures::Finished<Response, hyper::Error> {
  141. ::futures::finished(Response::new().with_status(StatusCode::NotFound))
  142. }
  143. }
  144. impl Service for Discovery {
  145. type Request = Request;
  146. type Response = Response;
  147. type Error = hyper::Error;
  148. type Future = Box<Future<Item = Response, Error = hyper::Error>>;
  149. fn call(&self, request: Request) -> Self::Future {
  150. let mut params = BTreeMap::new();
  151. let (method, uri, _, _, body) = request.deconstruct();
  152. if let Some(query) = uri.query() {
  153. params.extend(url::form_urlencoded::parse(query.as_bytes()).into_owned());
  154. }
  155. if method != Get {
  156. debug!("{:?} {:?} {:?}", method, uri.path(), params);
  157. }
  158. let this = self.clone();
  159. Box::new(
  160. body.fold(Vec::new(), |mut acc, chunk| {
  161. acc.extend_from_slice(chunk.as_ref());
  162. Ok::<_, hyper::Error>(acc)
  163. }).map(move |body| {
  164. params.extend(url::form_urlencoded::parse(&body).into_owned());
  165. params
  166. })
  167. .and_then(
  168. move |params| match (method, params.get("action").map(AsRef::as_ref)) {
  169. (Get, Some("getInfo")) => this.handle_get_info(&params),
  170. (Post, Some("addUser")) => this.handle_add_user(&params),
  171. _ => this.not_found(),
  172. },
  173. ),
  174. )
  175. }
  176. }
  177. #[cfg(feature = "with-dns-sd")]
  178. pub struct DiscoveryStream {
  179. credentials: mpsc::UnboundedReceiver<Credentials>,
  180. _svc: DNSService,
  181. }
  182. #[cfg(not(feature = "with-dns-sd"))]
  183. pub struct DiscoveryStream {
  184. credentials: mpsc::UnboundedReceiver<Credentials>,
  185. _svc: mdns::Service,
  186. }
  187. pub fn discovery(
  188. handle: &Handle,
  189. config: ConnectConfig,
  190. device_id: String,
  191. port: u16,
  192. ) -> io::Result<DiscoveryStream> {
  193. let (discovery, creds_rx) = Discovery::new(config.clone(), device_id);
  194. let serve = {
  195. let http = Http::new();
  196. http.serve_addr_handle(
  197. &format!("0.0.0.0:{}", port).parse().unwrap(),
  198. &handle,
  199. move || Ok(discovery.clone()),
  200. ).unwrap()
  201. };
  202. let s_port = serve.incoming_ref().local_addr().port();
  203. debug!("Zeroconf server listening on 0.0.0.0:{}", s_port);
  204. let server_future = {
  205. let handle = handle.clone();
  206. serve
  207. .for_each(move |connection| {
  208. handle.spawn(connection.then(|_| Ok(())));
  209. Ok(())
  210. })
  211. .then(|_| Ok(()))
  212. };
  213. handle.spawn(server_future);
  214. #[cfg(feature = "with-dns-sd")]
  215. let svc = DNSService::register(
  216. Some(&*config.name),
  217. "_spotify-connect._tcp",
  218. None,
  219. None,
  220. s_port,
  221. &["VERSION=1.0", "CPath=/"],
  222. ).unwrap();
  223. #[cfg(not(feature = "with-dns-sd"))]
  224. let responder = mdns::Responder::spawn(&handle)?;
  225. #[cfg(not(feature = "with-dns-sd"))]
  226. let svc = responder.register(
  227. "_spotify-connect._tcp".to_owned(),
  228. config.name,
  229. s_port,
  230. &["VERSION=1.0", "CPath=/"],
  231. );
  232. Ok(DiscoveryStream {
  233. credentials: creds_rx,
  234. _svc: svc,
  235. })
  236. }
  237. impl Stream for DiscoveryStream {
  238. type Item = Credentials;
  239. type Error = ();
  240. fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
  241. self.credentials.poll()
  242. }
  243. }