Https proxy to URLSession - swift

My code:
init() {
let configuration = URLSessionConfiguration.default
configuration.httpCookieStorage = HTTPCookieStorage.shared
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.urlCache = nil
var proxy = [AnyHashable: Any]()
proxy[AnyHashable(kCFNetworkProxiesHTTPSEnable)] = 1
proxy[AnyHashable(kCFNetworkProxiesHTTPSProxy)] = "..."
proxy[AnyHashable(kCFNetworkProxiesHTTPSPort)] = 14283
proxy[AnyHashable(kCFProxyUsernameKey)] = "..."
proxy[AnyHashable(kCFProxyPasswordKey)] = "..."
configuration.connectionProxyDictionary = proxy
When I run the application, I see this:
2017-10-25 00:45:44.768947+0500 ... Api[58675:12224660] *** WARNING: CFMachPortSetInvalidationCallBack() called on a CFMachPort with a Mach port (0x3613) which does not have any send rights. This is not going to work. Callback function: 0x7fff389e734f
2017-10-25 00:45:44.769328+0500 ... Api[58675:12224660] TIC Read Status [1:0x100f91800]: 1:57
2017-10-25 00:45:44.798125+0500 ... Api[58675:12224660] Task <4EFD78A7-1055-4D1C-9322-D0954B2B3760>.<1> HTTP load failed (error code: 310 [4:-2096])
2017-10-25 00:45:44.798300+0500 ... Api[58675:12224656] Task <4EFD78A7-1055-4D1C-9322-D0954B2B3760>.<1> finished with error - code: 310
URL Session Task Failed: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 310.)
Program ended with exit code: 0
What could be the problem?

Either the username and password is not correct or the port mentioned is used by any other program. Restart the phone and run this app and check it again.

Related

IOS Parse LiveQuery: Error processing message: Optional(POSIXErrorCode: Software caused connection abort)

I've developed an app in SwiftUI where I also use a chat with Parse LiveQuery.
The chat is working perfectly in real time until the app goes in background or the phone screen is closed.
If I receive a notification for a new message and I open the app from the notification then the LiveQuery stopes working and I recieve the error : "Parse LiveQuery: Error processing message: Optional(POSIXErrorCode: Software caused connection abort)"
I register the Message class
class Message: PFObject, PFSubclassing {
#NSManaged var message : String
#NSManaged var receiver : PFObject
#NSManaged var thread_id : PFObject
#NSManaged var produs : PFObject
#NSManaged var sender : PFObject
#NSManaged var picture : PFObject
class func parseClassName() -> String {
return "Message"
}
}
On the ChatView I have .onReceive where I start the function for chat and liveQuery
var messagesQuery: PFQuery<Message> {
return (Message.query()?
.whereKey("thread_id", equalTo: self.mainThread_obj)
.order(byDescending: "createdAt")) as! PFQuery<Message>
}
self.StartMessagesLiveQuery(messagesQuery: messagesQuery)
The func StartMessagesLiveQuery is:
let subscription: Subscription<Message> = Client.shared.subscribe(messagesQuery)
subscription.handle(Event.created) { query, object in
print("Live Query Trigered")
print(object)
DispatchQueue.global(qos: .background).async {
///reading object and appending to array}}
The only problem is when the app is opened from Notification.
I've there any way to force ParseLiveQuery to reconnect?
Error stack:
2021-03-03 10:15:47.442021+0200 App[35496:6350370] [connection] nw_read_request_report [C2] Receive failed with error "Software caused connection abort"
2021-03-03 10:15:47.449044+0200 App[35496:6350370] [connection] nw_read_request_report [C3] Receive failed with error "Software caused connection abort"
2021-03-03 10:15:47.449291+0200 App[35496:6350370] [connection] nw_read_request_report [C1] Receive failed with error "Software caused connection abort"
2021-03-03 10:15:47.455008+0200 App[35496:6350370] [connection] nw_flow_add_write_request [C2.1 52.1.38.170:443 failed channel-flow (satisfied (Path is satisfied), viable, interface: en0, ipv4, dns)] cannot accept write requests
2021-03-03 10:15:47.455055+0200 App[35496:6350370] [connection] nw_write_request_report [C2] Send failed with error "Socket is not connected"
2021-03-03 10:15:47.455815+0200 App[35496:6350657] ParseLiveQuery: Error processing message: Optional(POSIXErrorCode: Software caused connection abort)
2021-03-03 10:15:47.456612+0200 App[35496:6350370] Task <F6A87098-D5D3-444B-B656-D1999D5089D1>.<44> HTTP load failed, 42/0 bytes (error code: -1005 [1:53])
2021-03-03 10:15:47.462120+0200 App[35496:6350657] Task <F6A87098-D5D3-444B-B656-D1999D5089D1>.<44> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=53, NSUnderlyingError=0x282d11830 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x280174aa0 [0x20a814660]>{length = 16, capacity = 16, bytes = 0x100201bb344692570000000000000000}, _kCFStreamErrorCodeKey=53, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <F6A87098-D5D3-444B-B656-D1999D5089D1>.<44>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <F6A87098-D5D3-444B-B656-D1999D5089D1>.<44>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://site.b4a.app/classes/_User, NSErrorFailingURLKey=https://site.b4a.app/classes/_User, _kCFStreamErrorDomainKey=1}
2021-03-03 10:15:47.462237+0200 App[35496:6350657] [Error]: The network connection was lost. (Code: 100, Version: 1.19.1)
2021-03-03 10:15:47.462335+0200 Bazar[35496:6350657] [Error]: Network connection failed. Making attempt 1 after sleeping for 1.588128 seconds.
After this the network connection is restored and the app is functional, only the LiveQuery are not working.
I think i’ve solved it.
I've modified function StartMessagesLiveQuery:
func StartMessagesLiveQuery(messagesQuery: PFQuery<Message>){}
Inside the function I had:
let subscription: Subscription<Message> = Client.shared.subscribe(messagesQuery)
subscription!.handle(Event.created) { query, object in ... }
Now i’ve modified and put inside the Class
var subscription: Subscription<Message>?
 var subscriber: ParseLiveQuery.Client!
and in the function i’ve modified with:
subscriber = ParseLiveQuery.Client()
subscription = subscriber.subscribe(messagesQuery)

Disable checking https certificate: Swift

I trying to make a https call to my web service from a ios application.
So I used:
//...
func sendMessage() {
let defaults = UserDefaults.standard
let url = URL(string: defaults.string(forKey:"host")! + ":" + defaults.string(forKey:"port")! + "/garage")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: String] = [
"identifier": defaults.string(forKey: "secret")!
]
request.httpBody = parameters.percentEncoded()
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
let responseString = String(data: data, encoding: .utf8)
debugPrint("responseString = \(responseString)")
}
task.resume()
}
//...
extension ViewController: URLSessionDelegate {
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//Trust the certificate even if not valid
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}
}
I installed the ca at on the target system too. But I also try to ignore the certificate.
I always get following error instead of a response:
2020-07-03 14:41:27.742361+0200 GarageOpener[5177:223905] ATS failed system trust
2020-07-03 14:41:27.742484+0200 GarageOpener[5177:223905] Connection 1: system TLS Trust evaluation failed(-9802)
2020-07-03 14:41:27.742642+0200 GarageOpener[5177:223905] Connection 1: TLS Trust encountered error 3:-9802
2020-07-03 14:41:27.742776+0200 GarageOpener[5177:223905] Connection 1: encountered error(3:-9802)
2020-07-03 14:41:27.746709+0200 GarageOpener[5177:223905] Task <63EC553D-485C-478D-813B-AF0C1D3D3223>.<1> HTTP load failed, 0/0 bytes (error code: -1200 [3:-9802])
2020-07-03 14:41:27.749778+0200 GarageOpener[5177:223905] Task <63EC553D-485C-478D-813B-AF0C1D3D3223>.<1> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x600002b187e0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
), NSUnderlyingError=0x600001773cf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x600002b187e0>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://subdomain.mydomain.de:443/garage, NSErrorFailingURLStringKey=https://subdomain.mydomain.de:443/garage, NSErrorClientCertificateStateKey=0}
"3"
error Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x600002b187e0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
), NSUnderlyingError=0x600001773cf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x600002b187e0>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
"<cert(0x7fd6f2035600) s: *.mydomain.de i: *.mydomain.de>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://subdomain.mydomain.de:443/garage, NSErrorFailingURLStringKey=https://subdomain.mydomain.de:443/garage, NSErrorClientCertificateStateKey=0}
I know ignore isn't a good idea and it would allow man in the middle attacks. But at least the connection would be encrypted. And if somebody has the ability to make a man in the middle attack in my WLAN I have bigger problems than this.
Please help ;)
Okay, maybe it's time to answer my question.
The first I did wrong was the signing of the certificate.
I just set the domain/ip-address of the server in the Common Name (CN) entry of the certificate.
That is an outdated solution. You need to set the subjectAltName for modern applications: http://wiki.cacert.org/FAQ/subjectAltName .
But it feels very ugly to use the instructions from that wiki site to self-sign a certificate. So I used the awesome tool certstrap: https://github.com/square/certstrap
After that:
I passed the server.key and server.crt (private and signed public
key) to the server and configured everything fine.
I downloaded the CA (ca.crt) that I created (on the iphone).
You need to go to the settings->general->profiles and trust your
certificate.
Finally, you need to trust the certificate again:
https://support.apple.com/en-us/HT204477#:~:text=If%20you%20want%20to%20turn,Mobile%20Device%20Management%20(MDM).
Done. My application worked!

http APi request failed to connect error 1004

I have a problem with my http request from my custom Api using URLSession in Xcode with Swift. This is my code:
let forecast = self.forecastList[forecastIndex]
let url : URL = URL(string: "https:laundryireland.tk/getForecast?pwd=\(self.CustomApiKey)&temp=\(forecast.temp)&hum=\(forecast.humidity)&pres=\(forecast.pressure)&weat=\(forecast.weather)&wind=\(forecast.windspeed)")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
do {
let scores = try JSONDecoder().decode(Scores.self, from: data)
// ...
} catch {
print("ops")
}
}
task.resume()
This code throw an error at the third line already:
2019-11-04 12:53:26.701212+0000 DIYP[2554:1119528] [] tcp_input [C6.1:3] flags=[R.] seq=0, ack=2949324956, win=0 state=SYN_SENT rcv_nxt=0, snd_una=2949324955
2019-11-04 12:53:26.702757+0000 DIYP[2554:1119528] Connection 6: received failure notification
2019-11-04 12:53:26.702843+0000 DIYP[2554:1119528] Connection 6: failed to connect 1:61, reason -1
2019-11-04 12:53:26.702897+0000 DIYP[2554:1119528] Connection 6: encountered error(1:61)
2019-11-04 12:53:26.706142+0000 DIYP[2554:1119528] Task <46A61430-630E-48F8-B121-82B1C7BEE5DF>.<2> HTTP load failed, 0/0 bytes (error code: -1004 [1:61])
I saw here: TIC TCP Conn Failed [4:0x604000360300]: 1:61 Err(61) <1> HTTP load failed (error code: -1004 that the error 1004 is something related to the device not able to resolve the host but this seems odd to me because my URL is on a registered domain running on a remote server which is accessible from everywhere (just type: http://laundryireland.tk in your browser to see that it's working).
How do I fix this issue?
So the problem was first of all a typo: my domain is http://laundryireland.tk while in the code I wrote https://laundryireland.tk .
I found out is still possible to change the app settings to allow http connections: right click on Info.plist, Open As > Source Code then copy paste the following code right after <dict> at the top:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

Swift 5.0: How to fix nw_path_close_fd Failed to close guarded necp fd 4 [9: Bad file descriptor] error

Problem:
An error message displayed when I tried to access stdout while running a linux executable file inside my MacOS application. The stdout messages only appeared much later in blocks.
Context:
I wanted to update my user interface with the data being printed to the XCode console. I tried several tutorials, but I kept getting the same error message that wasn't covered in the material.
Attempts:
I couldn't find any resources that addressed and actually solved this problem.
Error:
2019-08-09 09:22:21.792908-0700 executable-filename-here[19975:508824] nw_path_close_fd Failed to close guarded necp fd 4 [9: Bad file descriptor]
2019-08-09 09:22:21.811325-0700 executable-filename-here[19976:508830] nw_path_close_fd Failed to close guarded necp fd 4 [9: Bad file descriptor]
2019-08-09 09:22:21.819582-0700 executable-filename-here[19977:508836] nw_path_close_fd Failed to close guarded necp fd 4 [9: Bad file descriptor]
2019-08-09 09:22:21.828539-0700 executable-filename-here[19978:508842] nw_path_close_fd Failed to close guarded necp fd 4 [9: Bad file descriptor]
Solution:
I found this solution while implementing a tutorial about intercepting stdout in Swift. Although, the article didn't address this error specifically. I noticed the error went away. Apparently, dup2 helped set the correct file descriptor for inputPipe and outputPipe.
Intercepting stdout in Swift
Mac OS X Developer Tools Manual Page For dup2(2)
import Cocoa
var process = Process()
var inputPipe = Pipe()
var outputPipe = Pipe()
private func runExecutable() {
let url = Bundle.main.url(forResource: "filename_here", withExtension: "")
let arguments = ["argument1", "argument2", "argument3", "etc"]
process.arguments = arguments
process.launchPath = url?.path
// dup2(): Duplicate an existing file descriptor
// Copy STDOUT file descriptor to outputPipe for writing strings back to STDOUT
dup2(STDOUT_FILENO, outputPipe.fileHandleForWriting.fileDescriptor)
// Intercept STDOUT with inputPipe
dup2(inputPipe.fileHandleForWriting.fileDescriptor, STDOUT_FILENO)
process.standardInput = inputPipe
process.standardOutput = outputPipe
try? process.run()
// Restore stdout
freopen("/dev/stdout", "a", stdout)
}

Getting lots of CloudKit errors (500) all of a sudden

Nearly everything my app does in CloudKit now returns this error:
<CKError 0x14ecff70: "Server Rejected Request" (15/2001); "Request failed with http status code 500">
(lldb) po [error userInfo]
{
CKDHTTPHeaders = {
Connection = close;
"Content-Length" = 0;
"X-Apple-Request-UUID" = "F8E4C91A-5F72-4792-9F13-BB5FBB10BA8E";
"X-Responding-Instance" = "ckdatabaseservice:32400203:mr11p24ic-ztbu11100101:8103:15B153:16274";
};
CKHTTPStatus = 500;
NSDebugDescription = "CKInternalErrorDomain: 2001";
NSLocalizedDescription = "Request failed with http status code 500";
NSUnderlyingError = "<CKError 0x14d5af70: \"Unknown Error\" (2001)>";
}
Any ideas why this could be happening? I'm tempted to blame it on temporary CloudKit server issues (which is how I would want to interpret an error 500)...but I don't know if that's appropriate.
This is a bug on the iCloud server that's affecting your container. I've grabbed logs from that request and the server team will clean up your container soon. In the meantime you can use a different container name for testing.
If you'd like to file a radar for this we can let you know when the container gets cleaned up.