session.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. use crypto::digest::Digest;
  2. use crypto::sha1::Sha1;
  3. use crypto::hmac::Hmac;
  4. use crypto::mac::Mac;
  5. use eventual;
  6. use eventual::Future;
  7. use eventual::Async;
  8. use protobuf::{self, Message};
  9. use rand::thread_rng;
  10. use std::io::{Read, Write, Cursor};
  11. use std::result::Result;
  12. use std::sync::{Mutex, RwLock, Arc, mpsc};
  13. use std::str::FromStr;
  14. use album_cover::AlbumCover;
  15. use apresolve::apresolve;
  16. use audio_key::{AudioKeyManager, AudioKey, AudioKeyError};
  17. use audio_file::AudioFile;
  18. use authentication::Credentials;
  19. use cache::Cache;
  20. use connection::{self, PlainConnection, CipherConnection};
  21. use diffie_hellman::DHLocalKeys;
  22. use mercury::{MercuryManager, MercuryRequest, MercuryResponse};
  23. use metadata::{MetadataManager, MetadataRef, MetadataTrait};
  24. use protocol;
  25. use stream::StreamManager;
  26. use util::{self, SpotifyId, FileId, ReadSeek};
  27. use version;
  28. use stream;
  29. #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
  30. pub enum Bitrate {
  31. Bitrate96,
  32. Bitrate160,
  33. Bitrate320,
  34. }
  35. impl FromStr for Bitrate {
  36. type Err = String;
  37. fn from_str(s: &str) -> Result<Self, Self::Err> {
  38. match s {
  39. "96" => Ok(Bitrate::Bitrate96),
  40. "160" => Ok(Bitrate::Bitrate160),
  41. "320" => Ok(Bitrate::Bitrate320),
  42. _ => Err(s.into()),
  43. }
  44. }
  45. }
  46. pub struct Config {
  47. pub user_agent: String,
  48. pub device_name: String,
  49. pub bitrate: Bitrate,
  50. pub onstart: Option<String>,
  51. pub onstop: Option<String>,
  52. }
  53. pub struct SessionData {
  54. country: String,
  55. canonical_username: String,
  56. }
  57. pub struct SessionInternal {
  58. config: Config,
  59. device_id: String,
  60. data: RwLock<SessionData>,
  61. cache: Box<Cache + Send + Sync>,
  62. mercury: Mutex<MercuryManager>,
  63. metadata: Mutex<MetadataManager>,
  64. stream: Mutex<StreamManager>,
  65. audio_key: Mutex<AudioKeyManager>,
  66. rx_connection: Mutex<Option<CipherConnection>>,
  67. tx_connection: Mutex<Option<CipherConnection>>,
  68. }
  69. #[derive(Clone)]
  70. pub struct Session(pub Arc<SessionInternal>);
  71. impl Session {
  72. pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session {
  73. let device_id = {
  74. let mut h = Sha1::new();
  75. h.input_str(&config.device_name);
  76. h.result_str()
  77. };
  78. Session(Arc::new(SessionInternal {
  79. config: config,
  80. device_id: device_id,
  81. data: RwLock::new(SessionData {
  82. country: String::new(),
  83. canonical_username: String::new(),
  84. }),
  85. rx_connection: Mutex::new(None),
  86. tx_connection: Mutex::new(None),
  87. cache: cache,
  88. mercury: Mutex::new(MercuryManager::new()),
  89. metadata: Mutex::new(MetadataManager::new()),
  90. stream: Mutex::new(StreamManager::new()),
  91. audio_key: Mutex::new(AudioKeyManager::new()),
  92. }))
  93. }
  94. fn connect(&self) -> CipherConnection {
  95. let local_keys = DHLocalKeys::random(&mut thread_rng());
  96. let ap = apresolve();
  97. info!("Connecting to AP {}", ap);
  98. let mut connection = PlainConnection::connect(&ap).unwrap();
  99. let request = protobuf_init!(protocol::keyexchange::ClientHello::new(), {
  100. build_info => {
  101. product: protocol::keyexchange::Product::PRODUCT_PARTNER,
  102. platform: protocol::keyexchange::Platform::PLATFORM_LINUX_X86,
  103. version: 0x10800000000,
  104. },
  105. cryptosuites_supported => [
  106. protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_SHANNON,
  107. ],
  108. login_crypto_hello.diffie_hellman => {
  109. gc: local_keys.public_key(),
  110. server_keys_known: 1,
  111. },
  112. client_nonce: util::rand_vec(&mut thread_rng(), 0x10),
  113. padding: vec![0x1e],
  114. });
  115. let init_client_packet = connection.send_packet_prefix(&[0, 4],
  116. &request.write_to_bytes().unwrap())
  117. .unwrap();
  118. let init_server_packet = connection.recv_packet().unwrap();
  119. let response: protocol::keyexchange::APResponseMessage =
  120. protobuf::parse_from_bytes(&init_server_packet[4..]).unwrap();
  121. let remote_key = response.get_challenge()
  122. .get_login_crypto_challenge()
  123. .get_diffie_hellman()
  124. .get_gs();
  125. let shared_secret = local_keys.shared_secret(remote_key);
  126. let (challenge, send_key, recv_key) = {
  127. let mut data = Vec::with_capacity(0x64);
  128. let mut mac = Hmac::new(Sha1::new(), &shared_secret);
  129. for i in 1..6 {
  130. mac.input(&init_client_packet);
  131. mac.input(&init_server_packet);
  132. mac.input(&[i]);
  133. data.write(&mac.result().code()).unwrap();
  134. mac.reset();
  135. }
  136. mac = Hmac::new(Sha1::new(), &data[..0x14]);
  137. mac.input(&init_client_packet);
  138. mac.input(&init_server_packet);
  139. (mac.result().code().to_vec(),
  140. data[0x14..0x34].to_vec(),
  141. data[0x34..0x54].to_vec())
  142. };
  143. let packet = protobuf_init!(protocol::keyexchange::ClientResponsePlaintext::new(), {
  144. login_crypto_response.diffie_hellman => {
  145. hmac: challenge
  146. },
  147. pow_response => {},
  148. crypto_response => {},
  149. });
  150. connection.send_packet(&packet.write_to_bytes().unwrap()).unwrap();
  151. CipherConnection::new(connection.into_stream(),
  152. &send_key,
  153. &recv_key)
  154. }
  155. pub fn login(&self, credentials: Credentials) -> Result<Credentials, ()> {
  156. let packet = protobuf_init!(protocol::authentication::ClientResponseEncrypted::new(), {
  157. login_credentials => {
  158. username: credentials.username,
  159. typ: credentials.auth_type,
  160. auth_data: credentials.auth_data,
  161. },
  162. system_info => {
  163. cpu_family: protocol::authentication::CpuFamily::CPU_UNKNOWN,
  164. os: protocol::authentication::Os::OS_UNKNOWN,
  165. system_information_string: "librespot".to_owned(),
  166. device_id: self.device_id().to_owned(),
  167. },
  168. version_string: version::version_string(),
  169. });
  170. let mut connection = self.connect();
  171. connection.send_packet(0xab, &packet.write_to_bytes().unwrap()).unwrap();
  172. let (cmd, data) = connection.recv_packet().unwrap();
  173. match cmd {
  174. 0xac => {
  175. let welcome_data: protocol::authentication::APWelcome =
  176. protobuf::parse_from_bytes(&data).unwrap();
  177. let username = welcome_data.get_canonical_username().to_owned();
  178. self.0.data.write().unwrap().canonical_username = username.clone();
  179. *self.0.rx_connection.lock().unwrap() = Some(connection.clone());
  180. *self.0.tx_connection.lock().unwrap() = Some(connection);
  181. info!("Authenticated !");
  182. let reusable_credentials = Credentials {
  183. username: username,
  184. auth_type: welcome_data.get_reusable_auth_credentials_type(),
  185. auth_data: welcome_data.get_reusable_auth_credentials().to_owned(),
  186. };
  187. self.0.cache.put_credentials(&reusable_credentials);
  188. Ok(reusable_credentials)
  189. }
  190. 0xad => {
  191. let msg: protocol::keyexchange::APLoginFailed =
  192. protobuf::parse_from_bytes(&data).unwrap();
  193. error!("Authentication failed, {:?}", msg);
  194. Err(())
  195. }
  196. _ => {
  197. error!("Unexpected message {:x}", cmd);
  198. Err(())
  199. }
  200. }
  201. }
  202. pub fn poll(&self) {
  203. let (cmd, data) = self.recv();
  204. match cmd {
  205. 0x4 => self.send_packet(0x49, &data).unwrap(),
  206. 0x4a => (),
  207. 0x9 | 0xa => self.0.stream.lock().unwrap().handle(cmd, data, self),
  208. 0xd | 0xe => self.0.audio_key.lock().unwrap().handle(cmd, data, self),
  209. 0x1b => {
  210. self.0.data.write().unwrap().country = String::from_utf8(data).unwrap();
  211. }
  212. 0xb2...0xb6 => self.0.mercury.lock().unwrap().handle(cmd, data, self),
  213. _ => (),
  214. }
  215. }
  216. pub fn recv(&self) -> (u8, Vec<u8>) {
  217. self.0.rx_connection.lock().unwrap().as_mut().unwrap().recv_packet().unwrap()
  218. }
  219. pub fn send_packet(&self, cmd: u8, data: &[u8]) -> connection::Result<()> {
  220. self.0.tx_connection.lock().unwrap().as_mut().unwrap().send_packet(cmd, data)
  221. }
  222. pub fn audio_key(&self, track: SpotifyId, file_id: FileId) -> Future<AudioKey, AudioKeyError> {
  223. self.0.cache
  224. .get_audio_key(track, file_id)
  225. .map(Future::of)
  226. .unwrap_or_else(|| {
  227. let self_ = self.clone();
  228. self.0.audio_key.lock().unwrap()
  229. .request(self, track, file_id)
  230. .map(move |key| {
  231. self_.0.cache.put_audio_key(track, file_id, key);
  232. key
  233. })
  234. })
  235. }
  236. pub fn audio_file(&self, file_id: FileId) -> Box<ReadSeek> {
  237. self.0.cache
  238. .get_file(file_id)
  239. .unwrap_or_else(|| {
  240. let (audio_file, complete_rx) = AudioFile::new(self, file_id);
  241. let self_ = self.clone();
  242. complete_rx.map(move |mut complete_file| {
  243. self_.0.cache.put_file(file_id, &mut complete_file)
  244. }).fire();
  245. Box::new(audio_file.await().unwrap())
  246. })
  247. }
  248. pub fn album_cover(&self, file_id: FileId) -> eventual::Future<Vec<u8>, ()> {
  249. self.0.cache
  250. .get_file(file_id)
  251. .map(|mut f| {
  252. let mut data = Vec::new();
  253. f.read_to_end(&mut data).unwrap();
  254. Future::of(data)
  255. })
  256. .unwrap_or_else(|| {
  257. let self_ = self.clone();
  258. AlbumCover::get(file_id, self)
  259. .map(move |data| {
  260. self_.0.cache.put_file(file_id, &mut Cursor::new(&data));
  261. data
  262. })
  263. })
  264. }
  265. pub fn stream(&self, handler: Box<stream::Handler>) {
  266. self.0.stream.lock().unwrap().create(handler, self)
  267. }
  268. pub fn metadata<T: MetadataTrait>(&self, id: SpotifyId) -> MetadataRef<T> {
  269. self.0.metadata.lock().unwrap().get(self, id)
  270. }
  271. pub fn mercury(&self, req: MercuryRequest) -> Future<MercuryResponse, ()> {
  272. self.0.mercury.lock().unwrap().request(self, req)
  273. }
  274. pub fn mercury_sub(&self, uri: String) -> mpsc::Receiver<MercuryResponse> {
  275. self.0.mercury.lock().unwrap().subscribe(self, uri)
  276. }
  277. pub fn cache(&self) -> &Cache {
  278. self.0.cache.as_ref()
  279. }
  280. pub fn config(&self) -> &Config {
  281. &self.0.config
  282. }
  283. pub fn username(&self) -> String {
  284. self.0.data.read().unwrap().canonical_username.clone()
  285. }
  286. pub fn country(&self) -> String {
  287. self.0.data.read().unwrap().country.clone()
  288. }
  289. pub fn device_id(&self) -> &str {
  290. &self.0.device_id
  291. }
  292. }
  293. pub trait PacketHandler {
  294. fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session);
  295. }