CallDiagnosticViewController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2017-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import UIKit
  21. import ThreemaFramework
  22. import WebRTC
  23. class CallDiagnosticViewController: UIViewController, RTCPeerConnectionDelegate {
  24. @IBOutlet weak var descriptionLabel: UILabel!
  25. @IBOutlet weak var startButton: UIButton!
  26. @IBOutlet weak var copyButton: UIButton!
  27. @IBOutlet weak var diagnosticTextView: UITextView!
  28. @IBOutlet weak var finishLabel: UILabel!
  29. @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  30. var connection:RTCPeerConnection?
  31. var factory: RTCPeerConnectionFactory = RTCPeerConnectionFactory()
  32. var isDiagnosticRunning: Bool = false
  33. internal var kCANDIDATE_ATTRIBUTE: NSRegularExpression?
  34. internal var kSP: String = "\\s"
  35. internal var kICE_CHAR: String = "[a-zA-Z\\d\\+\\/]"
  36. internal var kFOUNDATION: String
  37. internal var kCOMPONENT_ID: String = "\\d{1,5}"
  38. internal var kTRANSPORT: String = "[uU][dD][pP]"
  39. internal var kPRIORITY: String = "\\d{1,10}"
  40. internal var kCANDIDATE_TYPES: String = "(host|srflx|prflx|relay)"
  41. internal var kCAND_TYPE: String
  42. internal var kCONNECTION_ADDRESS: String = "\\S+"
  43. internal var kREL_ADDR: String
  44. internal var kPORT: String = "\\d{1,5}"
  45. internal var kREL_PORT: String
  46. internal var kBYTE_STRING: String = "\\S+"
  47. internal var kEXTENSION_ATT_NAME: String
  48. internal var kEXTENSION_ATT_VALUE: String
  49. required init?(coder aDecoder: NSCoder) {
  50. kFOUNDATION = String.init(format: "%@{1,32}", kICE_CHAR)
  51. kCAND_TYPE = String.init(format: "typ%@%@", kSP, kCANDIDATE_TYPES)
  52. kREL_ADDR = String.init(format: "raddr%@(%@)", kSP, kCONNECTION_ADDRESS)
  53. kREL_PORT = String.init(format: "rport%@(%@)", kSP, kPORT)
  54. kEXTENSION_ATT_NAME = kBYTE_STRING
  55. kEXTENSION_ATT_VALUE = kBYTE_STRING
  56. do {
  57. kCANDIDATE_ATTRIBUTE = try NSRegularExpression(pattern: String.init(format: "candidate:(%@)%@(%@)%@(%@)%@(%@)%@(%@)%@(%@)%@%@(%@%@)?(%@%@)?((%@%@%@%@)*)", kFOUNDATION, kSP, kCOMPONENT_ID, kSP, kTRANSPORT, kSP, kPRIORITY, kSP, kCONNECTION_ADDRESS, kSP, kPORT, kSP, kCAND_TYPE, kSP, kREL_ADDR, kSP, kREL_PORT, kSP, kEXTENSION_ATT_NAME, kSP, kEXTENSION_ATT_VALUE), options: [])
  58. }
  59. catch {
  60. }
  61. super.init(coder: aDecoder)
  62. }
  63. override func viewDidLoad() {
  64. super.viewDidLoad()
  65. setupColors()
  66. setupLocalizables()
  67. activityIndicator.stopAnimating()
  68. activityIndicator.isHidden = true
  69. if diagnosticTextView.text.count == 0 {
  70. finishLabel.isHidden = true
  71. diagnosticTextView.isHidden = true
  72. copyButton.isHidden = true
  73. }
  74. }
  75. override func viewDidDisappear(_ animated: Bool) {
  76. super.viewDidDisappear(animated)
  77. DispatchQueue.main.async {
  78. if self.isDiagnosticRunning {
  79. self.printStatus("Diagnostic cancelled")
  80. }
  81. if self.connection != nil {
  82. self.connection?.close()
  83. self.connection = nil
  84. }
  85. }
  86. }
  87. // MARK: Private functions
  88. private func setupColors() {
  89. descriptionLabel.font = UIFont.systemFont(ofSize: 17.0)
  90. finishLabel.font = UIFont.systemFont(ofSize: 17.0)
  91. descriptionLabel.textColor = Colors.fontNormal()
  92. finishLabel.textColor = Colors.fontNormal()
  93. startButton.setTitleColor(Colors.main(), for: .normal)
  94. startButton.setTitleColor(Colors.main(), for: .highlighted)
  95. startButton.setTitleColor(Colors.main(), for: .selected)
  96. copyButton.setTitleColor(Colors.main(), for: .normal)
  97. copyButton.setTitleColor(Colors.main(), for: .highlighted)
  98. copyButton.setTitleColor(Colors.main(), for: .selected)
  99. self.view.backgroundColor = Colors.background()
  100. switch Colors.getTheme() {
  101. case ColorThemeDark, ColorThemeDarkWork:
  102. diagnosticTextView.textColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
  103. activityIndicator.style = .white
  104. break
  105. case ColorThemeUndefined, ColorThemeLight, ColorThemeLightWork:
  106. diagnosticTextView.textColor = Colors.fontLight()
  107. activityIndicator.style = .gray
  108. break
  109. default:
  110. diagnosticTextView.textColor = Colors.fontLight()
  111. activityIndicator.style = .gray
  112. break
  113. }
  114. diagnosticTextView.font = UIFont.systemFont(ofSize: 15.0)
  115. diagnosticTextView.layer.borderWidth = 1.0
  116. diagnosticTextView.layer.borderColor = Colors.fontVeryLight().cgColor
  117. }
  118. private func setupLocalizables() {
  119. self.title = NSLocalizedString("webrtc_diagnostics.title", comment: "")
  120. descriptionLabel.text = NSLocalizedString("webrtc_diagnostics.description", comment: "")
  121. finishLabel.text = NSLocalizedString("webrtc_diagnostics.done", comment: "")
  122. startButton.setTitle(NSLocalizedString("webrtc_diagnostics.start", comment: ""), for: .normal)
  123. copyButton.setTitle(NSLocalizedString("webrtc_diagnostics.copyToClipboard", comment: ""), for: .normal)
  124. }
  125. private func startDiagnostic() {
  126. isDiagnosticRunning = true
  127. diagnosticTextView.text = ""
  128. let ipv6 = UserSettings.shared().enableIPv6 ? "IPv6 enabled" : "IPv6 disabled"
  129. let relay = UserSettings.shared().alwaysRelayCalls ? "Always relay enabled" : "Always relay disabled"
  130. printStatus("Start diagnostic (\(ipv6), \(relay))")
  131. let constraints = defaultPeerConnectionConstraints()
  132. defaultRTCConfiguration { [self] (result) in
  133. guard case .success(let configuration) = result else {
  134. printStatus("Cannot obtain TURN servers: \(result)")
  135. return
  136. }
  137. connection = factory.peerConnection(with: configuration, constraints: constraints, delegate: self)
  138. let localStream = createLocalMediaStreamWithFactory(factory: factory)
  139. connection?.add(localStream)
  140. connection?.offer(for: constraints) { (sdp, error) in
  141. if (sdp != nil) {
  142. self.connection?.setLocalDescription(sdp!, completionHandler: { (error) in
  143. })
  144. }
  145. }
  146. }
  147. }
  148. private func defaultPeerConnectionConstraints() -> RTCMediaConstraints {
  149. let optionalConstraints = ["DtlsSrtpKeyAgreement": "true"]
  150. let constraints = RTCMediaConstraints.init(mandatoryConstraints: nil, optionalConstraints: optionalConstraints)
  151. return constraints
  152. }
  153. private func defaultAudioConstraints() -> RTCMediaConstraints {
  154. let constraints = RTCMediaConstraints.init(mandatoryConstraints: nil, optionalConstraints: nil)
  155. return constraints
  156. }
  157. private func defaultRTCConfiguration(completion: @escaping (Result<RTCConfiguration, Error>) -> Void) {
  158. VoIPIceServerSource.obtainIceServers(dualStack: false) { (result) in
  159. do {
  160. let configuration = RTCConfiguration()
  161. configuration.iceServers = [try result.get()]
  162. configuration.iceTransportPolicy = .all
  163. configuration.bundlePolicy = .maxBundle
  164. configuration.rtcpMuxPolicy = .require
  165. configuration.tcpCandidatePolicy = .disabled
  166. configuration.continualGatheringPolicy = .gatherOnce
  167. completion(.success(configuration))
  168. } catch let error {
  169. completion(.failure(error))
  170. }
  171. }
  172. }
  173. private func createLocalMediaStreamWithFactory(factory:RTCPeerConnectionFactory) -> RTCMediaStream {
  174. let source = factory.audioSource(with: defaultAudioConstraints())
  175. let localStream = factory.mediaStream(withStreamId: "AMACALL")
  176. localStream.addAudioTrack(factory.audioTrack(with: source, trackId: "AMACALLa0"))
  177. return localStream
  178. }
  179. private func printCandidate(candidate: RTCIceCandidate) {
  180. DispatchQueue.main.sync {
  181. var diagnosticString = ""
  182. if diagnosticTextView.text.count > 0 {
  183. diagnosticString = diagnosticTextView.text + "\n" + "--------------------" + "\n"
  184. }
  185. let candidateDatas = self.parseCandidates(sdp: candidate.sdp)
  186. for candidateData in candidateDatas {
  187. diagnosticString = diagnosticString + "[" + candidateData.candType + "] " + candidateData.transport + " " + candidateData.connectionAddress + ":"
  188. if candidateData.port != nil {
  189. diagnosticString = diagnosticString + String(candidateData.port!)
  190. }
  191. if candidateData.relAddr != nil && candidateData.relPort != nil {
  192. diagnosticString = diagnosticString + " via " + candidateData.relAddr! + ":" + String(candidateData.relPort!)
  193. }
  194. diagnosticTextView.text = diagnosticString
  195. }
  196. }
  197. }
  198. private func parseCandidates(sdp: String) -> [CandidateData] {
  199. if kCANDIDATE_ATTRIBUTE != nil {
  200. let matches = kCANDIDATE_ATTRIBUTE!.matches(in: sdp, options: [], range: NSRange(location: 0, length: sdp.count))
  201. let candidateData = matches.map { result -> CandidateData in
  202. var foundation: String
  203. var componentId: Int?
  204. var transport: String
  205. var priority: Int?
  206. var connectionAddress: String
  207. var port: Int?
  208. var candType: String
  209. var relAddr: String?
  210. var relPort: Int?
  211. var extensions: [String: String] = [String: String]()
  212. var range = result.range(at:1)
  213. var swiftRange = Range(range, in: sdp)
  214. foundation = String(sdp[swiftRange!])
  215. range = result.range(at:2)
  216. swiftRange = Range(range, in: sdp)
  217. if swiftRange != nil {
  218. componentId = Int(String(sdp[swiftRange!]))
  219. }
  220. range = result.range(at:3)
  221. swiftRange = Range(range, in: sdp)
  222. transport = String(sdp[swiftRange!])
  223. range = result.range(at:4)
  224. swiftRange = Range(range, in: sdp)
  225. if swiftRange != nil {
  226. priority = Int(String(sdp[swiftRange!]))
  227. }
  228. range = result.range(at:5)
  229. swiftRange = Range(range, in: sdp)
  230. connectionAddress = String(sdp[swiftRange!])
  231. range = result.range(at:6)
  232. swiftRange = Range(range, in: sdp)
  233. if swiftRange != nil {
  234. port = Int(String(sdp[swiftRange!]))
  235. }
  236. range = result.range(at:7)
  237. swiftRange = Range(range, in: sdp)
  238. candType = String(sdp[swiftRange!])
  239. range = result.range(at:9)
  240. swiftRange = Range(range, in: sdp)
  241. if swiftRange != nil {
  242. relAddr = String(sdp[swiftRange!])
  243. }
  244. range = result.range(at:11)
  245. swiftRange = Range(range, in: sdp)
  246. if swiftRange != nil {
  247. relPort = Int(String(sdp[swiftRange!]))!
  248. }
  249. range = result.range(at:12)
  250. swiftRange = Range(range, in: sdp)
  251. if swiftRange != nil {
  252. let extensionsString = String(sdp[swiftRange!])
  253. let extensionsArray = extensionsString.components(separatedBy: " ")
  254. var key: String? = nil
  255. for extensionValue in extensionsArray {
  256. if extensionValue.count > 0 {
  257. if key == nil {
  258. key = extensionValue
  259. } else {
  260. extensions.updateValue(extensionValue, forKey: key!)
  261. key = nil
  262. }
  263. }
  264. }
  265. }
  266. return CandidateData.init(theFoundation: foundation, theComponentId: componentId, theTransport: transport, thePriority: priority, theConnectionAddress: connectionAddress, thePort: port, theCandType: candType, theRelAddr: relAddr, theRelPort: relPort, theExtensions: extensions)
  267. }
  268. return candidateData
  269. } else {
  270. return []
  271. }
  272. }
  273. private func printStatus(_ status: String) {
  274. var diagnosticString = ""
  275. if diagnosticTextView.text.count > 0 {
  276. diagnosticString = diagnosticTextView.text + "\n\n"
  277. }
  278. diagnosticTextView.text = diagnosticString + status
  279. }
  280. // MARK: IBActions
  281. @IBAction func startButtonTapped(_ sender: AnyObject) {
  282. diagnosticTextView.isHidden = false
  283. activityIndicator.startAnimating()
  284. activityIndicator.isHidden = false
  285. startButton.isHidden = true
  286. startDiagnostic()
  287. }
  288. @IBAction func copyButtonTapped(_ sender: AnyObject) {
  289. UIPasteboard.general.string = self.diagnosticTextView.text
  290. UIAlertTemplate.showAlert(owner: self, title: nil, message: NSLocalizedString("webrtc_diagnostics.copy", comment: ""))
  291. }
  292. // MARK: RTCPeerConnectionDelegate
  293. func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {
  294. if newState == .complete {
  295. isDiagnosticRunning = false
  296. DispatchQueue.main.async {
  297. self.printStatus("IceGathering complete")
  298. self.activityIndicator.stopAnimating()
  299. self.activityIndicator.isHidden = true
  300. self.finishLabel.isHidden = false
  301. self.copyButton.isHidden = false
  302. }
  303. }
  304. if newState == .gathering {
  305. DispatchQueue.main.async {
  306. self.printStatus("IceGathering start")
  307. }
  308. }
  309. }
  310. func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {
  311. printCandidate(candidate: candidate)
  312. }
  313. func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
  314. }
  315. func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {
  316. }
  317. func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {
  318. }
  319. func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {
  320. }
  321. func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {
  322. }
  323. func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {
  324. }
  325. func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {
  326. }
  327. }
  328. struct CandidateData {
  329. var foundation: String
  330. var componentId: Int?
  331. var transport: String
  332. var priority: Int?
  333. var connectionAddress: String
  334. var port: Int?
  335. var candType: String
  336. var relAddr: String?
  337. var relPort: Int?
  338. var extensions: [String: String]
  339. init(theFoundation: String, theComponentId: Int?, theTransport: String, thePriority: Int?, theConnectionAddress: String, thePort: Int?, theCandType: String, theRelAddr: String?, theRelPort: Int?, theExtensions:[String: String]) {
  340. foundation = theFoundation
  341. componentId = theComponentId
  342. transport = theTransport
  343. priority = thePriority
  344. connectionAddress = theConnectionAddress
  345. port = thePort
  346. candType = theCandType
  347. relAddr = theRelAddr
  348. relPort = theRelPort
  349. extensions = theExtensions
  350. }
  351. }