SecTrustEvaluate() slow down in iOS 11 - ios11

My apps could slow down in iOS 11, iPhone 6 plus. (Other iOS run as expected.)
I know SecTrustEvaluate() method is a reason that make the app slow down.
I run its in main thread takes about 3 seconds. So i use gcd to move its to background thread.
- (void)URLSession:(NSURLSession *)session didReceiveChallenge(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
BOOL allowConnect = //Server Trust Evaluation in here
dispatch_async( dispatch_get_main_queue(), ^{
if (allowConnect) {
//completionHandler;
} else {
//cancel
}
});
});
}
}
Then it do not block UI, but take 20 seconds for server trust validation.
Can someone know this issue? Please help me. Thanks.

I configure out my problem. This does not relate to iOS 11. It's my fault.
I create one NSURLSession for each security download image request on the same host.
Because TLS session is computationally expensive so that make my app slow down.
My solution is create only one session for all download request.
So evaluated server certificate’s result will be cached, and next request(on the same host, port) you don’t need evaluation server trust.
More info:
https://developer.apple.com/library/content/qa/qa1727/_index.html
Why is a HTTPS NSURLSession connection only challenged once per domain?

Related

Gatling repeat with connection re-use

With Gatling 2, is it possible to repeat with connection re-use? How?
I have the below code, but it appears to open new connection every time. I want to maintain x connections for some time.
val httpProtocol = http
.baseURL("http://mysrv.pvt")
.inferHtmlResources()
val uri1 = "http://mysrv.pvt"
val scn = scenario("Simulation").repeat(50){
pause(2 seconds,20 seconds).
exec(http("request_0")
.get("/s1/serve.html")
)
}
setUp(scn.inject(
atOnceUsers(20000)
).protocols(httpProtocol))
First, your question is not accurate enough.
By default, Gatling has one connection pool per virtual user, so each of them do re-use connections between sequential requests, and can have more than one concurrent connection when dealing with resource fetching, which you do as you enabled inferHtmlResources. This way, virtual users behave as independent browsers.
You can change this behavior and share a common connection pool, see doc. However, you have to make sure this makes sense in your case. Your workload profile will be very different, the toll on the TCP stack on both the client/Gatling and the server/your app will be way less, so make sure that's how your application is being used in production.

store data in every minute what should use Service, AsyncTask

I want to store data in database in every minute . For the same what should I use Service, AsyncTask or anything else. I go through various link which made me more confused .
I read the developer guide and came to know about getWritableDatabase
Database upgrade may take a long time, you should not call this method from the application main thread,
Then first I think I will use AsyncTask then about this
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
After that I think I can use Service then about Service
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
Here I am not able to understand what should I use to store data in database periodically. Please help me here as struck badly.
Thanks in advance
you cant do a lot work on the UI thread, so making database operations you could choose different approaches, few of them that I prefer to use are listed below;
Create a thread pool and execute each database operation via a thread, this reduces load on UI thread, also it never initializes lot of threads.
You can use services for updating the database operations. since services running on UI thread you cant write your operations in Services, so that you have to create a separate thread inside service method. or you can use Intent service directly since it is not working on UI Thread.
here is developer documentation on thread pool in android
and this is the documentation for IntentService
UPDATE
This will send an intent to your service every minute without using any processor time in your activity in between
Intent myIntent = new Intent(context, MyServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency= 60 * 1000; // in ms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);
Before that check if you really need a service to be started in each minute. or if you can have one service which checks for the data changes in each minute, starting new service would consume maybe more resources than checking itself.
UPDATE 2
private ping() {
// periodic action here.
scheduleNext();
}
private scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() { ping(); }
}, 60000);
}
int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return STICKY;
}
this is a simple example like that you can do

C HTTP Server & OpenSSL - Works fine for HTTP - Multiple/rapid/concurrent connections being dropped using HTTPS

I'm writing an HTTP server in C using sockets. It can listen on multiple ports and works on a 1-thread-per-port basis to run listening loops and each loop spawns another thread to deliver a response
The code works perfectly when delivering standard HTTP responses. I have it set up to respond with an HTML page with JavaScript code that just refreshes the browser repeatedly in order to stress test the server. I've tested this with my computer running as the server and 4 other devices spamming it with requests at the same time.
No crashes, no dropped connections and no memory leaks. CPU usage never jumps beyond 5% running on a 2.0 GHz Intel Core 2 Duo in HTTP mode with 4 devices spamming requests.
I just added OpenSSL yesterday so it can deliver secure responses over HTTPS. That went fairly smoothly as it seems that all I had to do with replace some standard socket calls with their OSSL counterparts for secure mode (based on the solution to this question: Turn a simple socket into an SSL socket).
There is one SSL context and SSL struct per connection. It does work but not very reliably. Again, each response happens on its own thread but multiple/rapid/concurrent requests in secure mode are getting dropped seemingly at random, though there are still no crashes or memory leaks in my code.
When a connection is dropped the browser will either say its waiting for a response that never happens (Chrome) or just says the connection was reset (Firefox).
For reference, here is the updated connection creation and closing code.
Connection creation code (main part of the listening loop):
// Note: sslCtx and sslConnection exist
// elsewhere in memory allocated specifically
// for each connection.
struct sockaddr_in clientAddr; // memset-ed to 0 before accept
int clientAddrLength = sizeof(clientAddr);
...
int clientSocketHandle = accept(serverSocketHandle, (struct sockaddr *)&clientAddr, &clientAddrLength);
...
if (useSSL)
{
int use_cert, use_privateKey, accept_result;
sslCtx = SSL_CTX_new(SSLv23_server_method());
SSL_CTX_set_options(sslCtx, SSL_OP_SINGLE_DH_USE);
use_cert = SSL_CTX_use_certificate_file(sslCtx, sslCertificatePath , SSL_FILETYPE_PEM);
use_privateKey = SSL_CTX_use_PrivateKey_file(sslCtx, sslCertificatePath , SSL_FILETYPE_PEM);
sslConnection = SSL_new(sslCtx);
SSL_set_fd(sslConnection, clientSocketHandle);
accept_result = SSL_accept(sslConnection);
}
... // Do other things and spawn request handling thread
Connection closing code:
int recvResult = 0;
if (!useSSL)
{
shutdown(clientSocketHandle, SHUT_WR);
while (TRUE)
{
recvResult = recv(clientSocketHandle, NULL, 0, 0);
if (recvResult <= 0) break;
}
}
else
{
SSL_shutdown(sslConnection);
while (TRUE)
{
recvResult = SSL_read(sslConnection, NULL, 0);
if (recvResult <= 0) break;
}
SSL_free(sslConnection);
SSL_CTX_free(sslCtx);
}
closesocket(clientSocketHandle);
Again, this works 100% perfect for HTTP responses. What could be going wrong for HTTPS responses?
Update
I've updated the code with OpenSSL callbacks for mutli-threaded environments and the server is slightly more reliable using code from an answer to this question: OpenSSL and multi-threads.
I wrote a small command line program to spam the server with HTTPS requests and it is not dropping any connections with 5 multiple instances of it running at the same time. Multiple instances of Firefox also appear not to be dropping any connections.
What is interesting however is that connections are still being dropped with modern WebKit-based browsers. Chrome starts to drop connections at under 30 seconds of spamming, Safari on an iPhone 4 (iOS 5.1) rarely makes it past 3 refreshes before saying the connection was lost, but Safari on an iPad 2 (iOS 5.0) seems to cope the longest but ultimately ends up dropping connections as well.
You should call SSL_accept() in your request handling thread. This will allow your listening thread to process the TCP accept/listen queue more quickly, and reduce the chance of new connections getting a RESET from the TCP stack because of a full accept/listen queue.
SSL handshake is compute intensive. I would guess that your spammer is probably not using SSL session cache, so this causes your server to use the maximum amount of CPU. This will cause it to be CPU starved in regards to servicing the other connections, or new incoming connections.

iOS 6 - Bluetooth LE disconnect

Ok what the heck is up with iOS6 and how it handles Bluetooth LE disconnections? Before the device would disconnect immediately but now, for some strange reason, the device waits to disconnect for about 30-60 seconds. I need it to disconnect ASAFP!
I've been searing all over the internet trying to figure out how to initiate an immediate disconnection from the peripheral and I found this nifty email that explains a workaround is to unsubscribe from notifications on the service characteristics.
Now I think I'm doing that.. When I want to disconnect I call [connected_device setNotifyValue:NO forCharacteristic:connected_characteristic]
Then, in the didUpdateNotificationStateForCharacteristic function, I have...
if((int)characteristic.isNotifying == 0){
[manager cancelPeripheralConnection:peripheral];
}
In the function didDisconnectPeripheral...
connected_peripheral = nil;
connected_characteristic = nil;
[connected_peripheral release];
[connected_characteristic release];
I've also taken a good hard look at Apple's CoreBluetooth Temperature Sensor example but it hasn't really helped much....
Any help on this would be amazing!! I just don't know what I'm missing.....
UPDATE: It looks like the app needs to be connected to the bluetooth device for at least a minute before it is allowed to disconnect. If the app is connected for over a minute it will disconnect immediately when the command is sent. Otherwise, it will wait until that one minute mark to actually disconnect.
UPDATE: When I try to disconnect before the one minute mark, I get the following output to the log when the device actually disconnects.
Oct 24 16:49:35 Christophers-iPhone awdd[8168] <Error>: libMobileGestalt copySystemVersionDictionaryValue: Could not lookup ReleaseType from system version dictionary
Oct 24 16:49:35 Christophers-iPhone awdd[8168] <Error>: CoreLocation: CLClient is deprecated. Will be obsolete soon.
According to Apple, this new feature is "by design".
The way we resolved this issue was to send a command to the Peripheral and have it disconnect from its end. If you do this, then the disconnect is immediate. I do not know why Apple changed this behavior from iOS5 to iOS6 but they must have had their reasons. Of course this solution only works if you have access to the Peripheral firmware and can change it. If there is a different solution, then we have not found it.
That was a bug in iOS 6.0, in 6.1 it's fixed.

java.sql.SQLRecoverableException: Connection is already in use

In my java code, I am processing huge amount of data. So I moved the code as servlet to Cron Job of App Engine. Some days it works fine. After the amount of the data increases, the cron job is not working and shows the following error message.
2012-09-26 04:18:40.627
'ServletName' 'MethodName': Inside SQLExceptionjava.sql.SQLRecoverableException:
Connection is already in use.
I 2012-09-26 04:18:40.741
This request caused a new process to be started for your application, and thus caused
your application code to be loaded for the first time. This request may thus take
longer and use more CPU than a typical request for your application.
W 2012-09-26 04:18:40.741
A problem was encountered with the process that handled this request, causing it to
exit. This is likely to cause a new process to be used for the next request to your
application. If you see this message frequently, you may be throwing exceptions during
the initialization of your application. (Error code 104)
How to handle this problem?
This exception is typical when a single connection is shared between multiple threads. This will in turn happen when your code does not follow the standard JDBC idiom of acquiring and closing the DB resources in the shortest possible scope in the very same try-finally block like so:
public Entity find(Long id) throws SQLException {
Connection connection = null;
// ...
try {
connection = dataSource.getConnection();
// ...
} finally {
// ...
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return entity;
}
Your comment on the question,
#TejasArjun i used connection pooling with servlet Init() method.
doesn't give me the impression that you're doing it the right way. This suggests that you're obtaining a DB connection in servlet's init() method and reusing the same one across all HTTP requests in all HTTP sessions. This is absolutely not right. A servlet instance is created/initialized only once during webapp's startup and reused throughout the entire remaining of the application's lifetime. This at least confirms the exception you're facing.
Just rewrite your JDBC code according the standard try-finally idiom as demonstrated above and you should be all set.
See also:
Is it safe to use a static java.sql.Connection instance in a multithreaded system?

Resources