session.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. use crypto::digest::Digest;
  2. use crypto::sha1::Sha1;
  3. use eventual::Future;
  4. use protobuf::{self, Message};
  5. use rand::thread_rng;
  6. use std::sync::{Mutex, RwLock, Arc, mpsc};
  7. use std::path::PathBuf;
  8. use connection::{self, PlainConnection, CipherConnection};
  9. use keys::PrivateKeys;
  10. use librespot_protocol as protocol;
  11. use util::{SpotifyId, FileId, mkdir_existing};
  12. use mercury::{MercuryManager, MercuryRequest, MercuryResponse};
  13. use metadata::{MetadataManager, MetadataRef, MetadataTrait};
  14. use stream::{StreamManager, StreamEvent};
  15. use audio_key::{AudioKeyManager, AudioKey, AudioKeyError};
  16. use audio_file::{AudioFileManager, AudioFile};
  17. use connection::PacketHandler;
  18. use util;
  19. pub struct Config {
  20. pub application_key: Vec<u8>,
  21. pub user_agent: String,
  22. pub device_id: String,
  23. pub cache_location: PathBuf,
  24. }
  25. pub struct SessionData {
  26. pub country: String,
  27. pub canonical_username: String,
  28. }
  29. pub struct SessionInternal {
  30. pub config: Config,
  31. pub data: RwLock<SessionData>,
  32. mercury: Mutex<MercuryManager>,
  33. metadata: Mutex<MetadataManager>,
  34. stream: Mutex<StreamManager>,
  35. audio_key: Mutex<AudioKeyManager>,
  36. audio_file: Mutex<AudioFileManager>,
  37. rx_connection: Mutex<CipherConnection>,
  38. tx_connection: Mutex<CipherConnection>,
  39. }
  40. #[derive(Clone)]
  41. pub struct Session(pub Arc<SessionInternal>);
  42. impl Session {
  43. pub fn new(mut config: Config) -> Session {
  44. config.device_id = {
  45. let mut h = Sha1::new();
  46. h.input_str(&config.device_id);
  47. h.result_str()
  48. };
  49. mkdir_existing(&config.cache_location).unwrap();
  50. let keys = PrivateKeys::new();
  51. let mut connection = PlainConnection::connect().unwrap();
  52. let request = protobuf_init!(protocol::keyexchange::ClientHello::new(), {
  53. build_info => {
  54. product: protocol::keyexchange::Product::PRODUCT_LIBSPOTIFY_EMBEDDED,
  55. platform: protocol::keyexchange::Platform::PLATFORM_LINUX_X86,
  56. version: 0x10800000000,
  57. },
  58. /*
  59. fingerprints_supported => [
  60. protocol::keyexchange::Fingerprint::FINGERPRINT_GRAIN
  61. ],
  62. */
  63. cryptosuites_supported => [
  64. protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_SHANNON,
  65. //protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_RC4_SHA1_HMAC
  66. ],
  67. /*
  68. powschemes_supported => [
  69. protocol::keyexchange::Powscheme::POW_HASH_CASH
  70. ],
  71. */
  72. login_crypto_hello.diffie_hellman => {
  73. gc: keys.public_key(),
  74. server_keys_known: 1,
  75. },
  76. client_nonce: util::rand_vec(&mut thread_rng(), 0x10),
  77. padding: vec![0x1e],
  78. feature_set => {
  79. autoupdate2: true,
  80. }
  81. });
  82. let init_client_packet =
  83. connection.send_packet_prefix(&[0,4], &request.write_to_bytes().unwrap()).unwrap();
  84. let init_server_packet =
  85. connection.recv_packet().unwrap();
  86. let response : protocol::keyexchange::APResponseMessage =
  87. protobuf::parse_from_bytes(&init_server_packet[4..]).unwrap();
  88. protobuf_bind!(response, {
  89. challenge => {
  90. login_crypto_challenge.diffie_hellman => {
  91. gs: remote_key,
  92. }
  93. }
  94. });
  95. let shared_keys = keys.add_remote_key(remote_key, &init_client_packet, &init_server_packet);
  96. let packet = protobuf_init!(protocol::keyexchange::ClientResponsePlaintext::new(), {
  97. login_crypto_response.diffie_hellman => {
  98. hmac: shared_keys.challenge().to_vec()
  99. },
  100. pow_response => {},
  101. crypto_response => {},
  102. });
  103. connection.send_packet(&packet.write_to_bytes().unwrap()).unwrap();
  104. let cipher_connection = connection.setup_cipher(shared_keys);
  105. Session(Arc::new(SessionInternal {
  106. config: config,
  107. data: RwLock::new(SessionData {
  108. country: String::new(),
  109. canonical_username: String::new(),
  110. }),
  111. rx_connection: Mutex::new(cipher_connection.clone()),
  112. tx_connection: Mutex::new(cipher_connection),
  113. mercury: Mutex::new(MercuryManager::new()),
  114. metadata: Mutex::new(MetadataManager::new()),
  115. stream: Mutex::new(StreamManager::new()),
  116. audio_key: Mutex::new(AudioKeyManager::new()),
  117. audio_file: Mutex::new(AudioFileManager::new()),
  118. }))
  119. }
  120. pub fn login(&self, username: String, password: String) {
  121. let packet = protobuf_init!(protocol::authentication::ClientResponseEncrypted::new(), {
  122. login_credentials => {
  123. username: username,
  124. typ: protocol::authentication::AuthenticationType::AUTHENTICATION_USER_PASS,
  125. auth_data: password.into_bytes(),
  126. },
  127. system_info => {
  128. cpu_family: protocol::authentication::CpuFamily::CPU_UNKNOWN,
  129. os: protocol::authentication::Os::OS_UNKNOWN,
  130. system_information_string: "librespot".to_owned(),
  131. device_id: self.0.config.device_id.clone()
  132. },
  133. version_string: util::version::version_string(),
  134. appkey => {
  135. version: self.0.config.application_key[0] as u32,
  136. devkey: self.0.config.application_key[0x1..0x81].to_vec(),
  137. signature: self.0.config.application_key[0x81..0x141].to_vec(),
  138. useragent: self.0.config.user_agent.clone(),
  139. callback_hash: vec![0; 20],
  140. }
  141. });
  142. self.send_packet(0xab, &packet.write_to_bytes().unwrap()).unwrap();
  143. }
  144. pub fn poll(&self) {
  145. let (cmd, data) =
  146. self.0.rx_connection.lock().unwrap().recv_packet().unwrap();
  147. match cmd {
  148. 0x4 => self.send_packet(0x49, &data).unwrap(),
  149. 0x4a => (),
  150. 0x9 => self.0.stream.lock().unwrap().handle(cmd, data),
  151. 0xd | 0xe => self.0.audio_key.lock().unwrap().handle(cmd, data),
  152. 0x1b => {
  153. self.0.data.write().unwrap().country =
  154. String::from_utf8(data).unwrap();
  155. },
  156. 0xb2...0xb6 => self.0.mercury.lock().unwrap().handle(cmd, data),
  157. 0xac => {
  158. let welcome_data : protocol::authentication::APWelcome =
  159. protobuf::parse_from_bytes(&data).unwrap();
  160. self.0.data.write().unwrap().canonical_username =
  161. welcome_data.get_canonical_username().to_string();
  162. eprintln!("Authentication succeeded")
  163. },
  164. 0xad => eprintln!("Authentication failed"),
  165. _ => ()
  166. }
  167. }
  168. pub fn send_packet(&self, cmd: u8, data: &[u8]) -> connection::Result<()> {
  169. self.0.tx_connection.lock().unwrap().send_packet(cmd, data)
  170. }
  171. pub fn audio_key(&self, track: SpotifyId, file: FileId) -> Future<AudioKey, AudioKeyError> {
  172. self.0.audio_key.lock().unwrap().request(self, track, file)
  173. }
  174. pub fn audio_file(&self, file: FileId) -> AudioFile {
  175. self.0.audio_file.lock().unwrap().request(self, file)
  176. }
  177. pub fn stream(&self, file: FileId, offset: u32, size: u32) -> mpsc::Receiver<StreamEvent> {
  178. self.0.stream.lock().unwrap().request(self, file, offset, size)
  179. }
  180. pub fn metadata<T: MetadataTrait>(&self, id: SpotifyId) -> MetadataRef<T> {
  181. self.0.metadata.lock().unwrap().get(self, id)
  182. }
  183. pub fn mercury(&self, req: MercuryRequest) -> Future<MercuryResponse, ()> {
  184. self.0.mercury.lock().unwrap().request(self, req)
  185. }
  186. pub fn mercury_sub(&self, uri: String) -> mpsc::Receiver<MercuryResponse> {
  187. self.0.mercury.lock().unwrap().subscribe(self, uri)
  188. }
  189. }