discovery.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. use base64;
  2. use sha1::{Sha1, Digest};
  3. use hmac::{Hmac, Mac};
  4. use aes_ctr::Aes128Ctr;
  5. use aes_ctr::stream_cipher::{NewStreamCipher, SyncStreamCipher};
  6. use aes_ctr::stream_cipher::generic_array::GenericArray;
  7. use futures::sync::mpsc;
  8. use futures::{Future, Poll, Stream};
  9. use hyper::server::{Http, Request, Response, Service};
  10. use hyper::{self, Get, Post, StatusCode};
  11. #[cfg(feature = "with-dns-sd")]
  12. use dns_sd::DNSService;
  13. #[cfg(not(feature = "with-dns-sd"))]
  14. use mdns;
  15. use num_bigint::BigUint;
  16. use rand;
  17. use std::collections::BTreeMap;
  18. use std::io;
  19. use std::sync::Arc;
  20. use tokio_core::reactor::Handle;
  21. use url;
  22. use librespot_core::authentication::Credentials;
  23. use librespot_core::config::ConnectConfig;
  24. use librespot_core::diffie_hellman::{DH_GENERATOR, DH_PRIME};
  25. use librespot_core::util;
  26. type HmacSha1 = Hmac<Sha1>;
  27. #[derive(Clone)]
  28. struct Discovery(Arc<DiscoveryInner>);
  29. struct DiscoveryInner {
  30. config: ConnectConfig,
  31. device_id: String,
  32. private_key: BigUint,
  33. public_key: BigUint,
  34. tx: mpsc::UnboundedSender<Credentials>,
  35. }
  36. impl Discovery {
  37. fn new(
  38. config: ConnectConfig,
  39. device_id: String,
  40. ) -> (Discovery, mpsc::UnboundedReceiver<Credentials>) {
  41. let (tx, rx) = mpsc::unbounded();
  42. let key_data = util::rand_vec(&mut rand::thread_rng(), 95);
  43. let private_key = BigUint::from_bytes_be(&key_data);
  44. let public_key = util::powm(&DH_GENERATOR, &private_key, &DH_PRIME);
  45. let discovery = Discovery(Arc::new(DiscoveryInner {
  46. config: config,
  47. device_id: device_id,
  48. private_key: private_key,
  49. public_key: public_key,
  50. tx: tx,
  51. }));
  52. (discovery, rx)
  53. }
  54. }
  55. impl Discovery {
  56. fn handle_get_info(
  57. &self,
  58. _params: &BTreeMap<String, String>,
  59. ) -> ::futures::Finished<Response, hyper::Error> {
  60. let public_key = self.0.public_key.to_bytes_be();
  61. let public_key = base64::encode(&public_key);
  62. let result = json!({
  63. "status": 101,
  64. "statusString": "ERROR-OK",
  65. "spotifyError": 0,
  66. "version": "2.1.0",
  67. "deviceID": (self.0.device_id),
  68. "remoteName": (self.0.config.name),
  69. "activeUser": "",
  70. "publicKey": (public_key),
  71. "deviceType": (self.0.config.device_type.to_string().to_uppercase()),
  72. "libraryVersion": "0.1.0",
  73. "accountReq": "PREMIUM",
  74. "brandDisplayName": "librespot",
  75. "modelDisplayName": "librespot",
  76. });
  77. let body = result.to_string();
  78. ::futures::finished(Response::new().with_body(body))
  79. }
  80. fn handle_add_user(
  81. &self,
  82. params: &BTreeMap<String, String>,
  83. ) -> ::futures::Finished<Response, hyper::Error> {
  84. let username = params.get("userName").unwrap();
  85. let encrypted_blob = params.get("blob").unwrap();
  86. let client_key = params.get("clientKey").unwrap();
  87. let encrypted_blob = base64::decode(encrypted_blob).unwrap();
  88. let client_key = base64::decode(client_key).unwrap();
  89. let client_key = BigUint::from_bytes_be(&client_key);
  90. let shared_key = util::powm(&client_key, &self.0.private_key, &DH_PRIME);
  91. let iv = &encrypted_blob[0..16];
  92. let encrypted = &encrypted_blob[16..encrypted_blob.len() - 20];
  93. let cksum = &encrypted_blob[encrypted_blob.len() - 20..encrypted_blob.len()];
  94. let base_key = Sha1::digest(&shared_key.to_bytes_be());
  95. let base_key = &base_key[..16];
  96. let checksum_key = {
  97. let mut h = HmacSha1::new_varkey(base_key)
  98. .expect("HMAC can take key of any size");
  99. h.input(b"checksum");
  100. h.result().code()
  101. };
  102. let encryption_key = {
  103. let mut h = HmacSha1::new_varkey(&base_key)
  104. .expect("HMAC can take key of any size");
  105. h.input(b"encryption");
  106. h.result().code()
  107. };
  108. let mut h = HmacSha1::new_varkey(&checksum_key)
  109. .expect("HMAC can take key of any size");
  110. h.input(encrypted);
  111. if let Err(_) = h.verify(cksum) {
  112. warn!("Login error for user {:?}: MAC mismatch", username);
  113. let result = json!({
  114. "status": 102,
  115. "spotifyError": 1,
  116. "statusString": "ERROR-MAC"
  117. });
  118. let body = result.to_string();
  119. return ::futures::finished(Response::new().with_body(body))
  120. }
  121. let decrypted = {
  122. let mut data = encrypted.to_vec();
  123. let mut cipher = Aes128Ctr::new(
  124. &GenericArray::from_slice(&encryption_key[0..16]),
  125. &GenericArray::from_slice(iv),
  126. );
  127. cipher.apply_keystream(&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. }