Http Post Indy10 Error Delphi 7: Error creating SSL context - post

I'm using Delphi 7 with Indy 10.6.2.5459 to make a POST request to a server from time to time:
sParams := '?ultimaAlteracao='+FormatDateTime('YYYY-MM-DD',now())+'T00:00:00.000';
FidHTTP := TIdHTTP.Create;
try
FidHTTP.Request.Clear;
FidHTTP.Request.Accept := 'application/json;charset=UTF-8';
FidHTTP.Request.CharSet := 'UTF-8';
FidHTTP.Response.ContentType := 'application/json;charset=UTF-8';
FidHTTP.Response.ContentEncoding := 'UTF-8';
FidHTTP.Request.CustomHeaders.AddValue('Authorization','Basic '+EncodeBase64('xx:xx#123456'));
JsonStream := TStringStream.Create('');
JsonStream.Position := 0;
try
FidHTTP.Get('https://'+server+'/LinxImportacaoArquivo/GetSelecaoDadosMDMNCM'+sParams, JsonStream);
DataString := JsonStream.DataString;
finally
FreeAndNil(JsonStream);
end;
finally
FreeAndNil(FidHTTP);
end;
After sometime, it begins to fail and returns:
Error creating SSL context. error:140A90F1:SSL
routines:SSL_CTX_new:unable to load ssl2 md5 routines
If I restart the application, it works for sometime again.
I found some people who had the same issue: here and here
From what I learned, it can be some other process which uses Indy to make a request that is interfering, and I quote
It appears to be an issue with some type of static member
initialization inside the openssl library. I have 2 libraries, both of
them use the openssl library, let's call them A and B. When the
application starts up both A & B are able to successfully create a
security context. Later, when library B tries to create another
security context it fails. Both library A and B are module plugins to
our application so they both will load but if one is not needed it is
unloaded.
Indeed, my application has a lot of others process executing, making http requests, through indy10 or WinInet.
So, my question is: Is there some procedure I can call on Indy10 to make it initialize something that had it freed on opensll library?

I found out that at unit IdSSLOpenSSL there's a procedure named UnLoadOpenSSLLibrary.
If I always call that procedure before my code, the error does not occurr.

Related

TIdHTTP.Get timeouts while the same call done with Postman succeeds: possible reasons?

I call a webapi with a Delphi app, in some pcs, the call timeouts, while in other it works fine.
The request done with Postman works fine.
It is a simple custom ping webservice (URL is in Edit1.Text in the code below), in fact the answer is a textual "Pong".
This is the Delphi code of the call:
errormsg := '';
{
old way of setting custom headers
IdHTTP1.Request.CustomHeaders.AddValue('X-HTTP-Method-Override', 'ForwardCommand');
IdHTTP1.Request.CustomHeaders.AddValue('Connection', 'keep-alive');
IdHTTP1.Request.CustomHeaders.AddValue('Accept', '*/*');
IdHTTP1.Request.CustomHeaders.AddValue('User-Agent', 'QualibusSilent');
IdHTTP1.Request.CustomHeaders.AddValue('Content-Type', 'text/plain');
}
//better way of setting custom headers
IdHTTP1.Request.MethodOverride := 'ForwardCommand';
IdHTTP1.Request.Connection := 'keep-alive';
IdHTTP1.Request.UserAgent := 'myCustomUserAgent';
IdHTTP1.Request.ContentType := 'text/plain';
IdHTTP1.Request.Accept := '*/*';
IdSSLIOHandlerSocketOpenSSL1 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Mode := sslmClient;
IdSSLIOHandlerSocketOpenSSL1.SSLOptions.SSLVersions:=
[sslvTLSv1,sslvTLSv1_1,sslvTLSv1_2];
startTime := GetTickCount;
Try
sHTML := IdHTTP1.Get(Edit1.Text);
Except
On E:Exception do
errormsg := e.Message;
End;
EndTime := GetTickCount;
ShowMessage('Time taken: ' +
IntToStr(endTime-startTime)+#13#10+'Error:'+errormsg);
Basically it is a call where instead of GET I do a custom method (ForwardCommand) that I call with X-HTTP-Method-Override.
In the code above I tried to add many headers so that the call is really as the Postman one.
If the call is done directly to the IP address it works, but if I call the https URL it timeouts, there is no evidence of error in the proxy server.
Checking the logs at the webserver side it seems the call is not performed at all.
And this occurs only from some Windows 10 machines, while in the majority of them the call is performed correctly.
Could you please suggest which could be the cause of the error? What should I try to change in the Delphi code to avoid the timeout so that Delphi behaves like Postman?
Thanks.
As stated in comments:
Why when Tidhttp uses proxyParams timeout does not occur and the call succeeds?
...
I finally got the reason for the Postman vs Indy behavior: Proxy. By passing proxy IP and port to TIdHTTP it works, Postman manages to retrieve the system proxy automatically and therefore it works.
There is no "system proxy" on Windows, however there is a proxy in the WinInet API, which is what Internet Explorer (and Edge?) relies on.
In any case, it sounds like the failing PCs don't have direct access to the Internet to begin with, only through a proxy. Indy has no concept of any "system proxy" on any platform, so you will have to assign the proxy settings to TIdHTTP manually, as you have discovered.

Delphi 10 Seattle Datasnap error: "Operation failed. Connection was closed."

I created a stand-alone Datasnap TCP/IP server using the Wizard. I selected sample methods (echostring and reversestring). I saved the server and ran it. Then I created a client application, and using the file-new-other, added a ClientModule to that client project, along with the ClientClasses unit. On the main form. I added a button. On the button's onclick event handler, I added the following code:
procedure TForm1.Button1Click(Sender: TObject);
begin
if ClientModule1.SQLConnection1.Connected then
begin
Button1.Text := 'Open';
ClientModule1.SQLConnection1.Close;
end
else
begin
Button1.Text := 'Close';
// ClientModule1.SQLConnection1.Open;
ClientModule1.ServerMethods1Client.ReverseString('myteststring');
end;
end;
The purpose here is to simulate a situation where the client is logging into and logging out of the server regularly rather than keeping a connection. This is especially important on apps deployed to mobile.
You can see I commented out the Connection.Open, because the first call to the ServerMethods1client opens the connection. The generated code is shown here:
function TClientModule1.GetServerMethods1Client: TServerMethods1Client;
begin
if FServerMethods1Client = nil then
begin
SQLConnection1.Open;
FServerMethods1Client := TServerMethods1Client.Create(SQLConnection1.DBXConnection, FInstanceOwner);
end;
Result := FServerMethods1Client;
end;
Now the problem arises. On first click to the button, the connection is opened, and the method is called. On the second click to the button, the connection is closed.
On the 3rd click, an exception is raised "Operation Failed. Connection was Closed" is raised from with the TDBXCommand code.
As a workaround, I tried this:
procedure TForm1.Button1Click(Sender: TObject);
begin
if ClientModule1.SQLConnection1.Connected then
begin
Button1.Text := 'Open';
ClientModule1.SQLConnection1.Close;
ClientModule1.ServerMethods1Client := nil;
end
else
begin
Button1.Text := 'Close';
// ClientModule1.SQLConnection1.Open;
ClientModule1.ServerMethods1Client.ReverseString('myteststring');
end;
end;
This does sort-of solve the problem, since the ClientModule1's FServerMethods1Client instance is reset so the create code runs again like it did on the first run.
The only other problem now, is (I am using Eurekalog) it creates a memory leak.
What am I doing wrong? What's the right way to connected/disconnect from a Datasnap server repeatedly without restarting the app?
The reason for the first error is that the code that binds the client side proxy (which allows server methods to be called) is tied to the local SQL connection. Note the call to create the proxy class:
FServerMethods1Client := TServerMethods1Client.Create(SQLConnection1.DBXConnection, ...)
The underlying DBExpress connection is passed by reference, and the proxy class uses that connection to call the server. You closed and re-opened the connection, but the underlying DBExpress connection that ServerMethodsClient1 was using has been destroyed. Thus, you receive the "Connection was closed" exception. The connection that ServerMethodsClient1 was using has been closed. You have to recreate ServerMethodsClient1 as you did in your second example.
I can't answer your second question, as I believe it is ARC specific. For a VCL DataSnap app, I would call ServerMethodsClient1.Free rather than setting it to nil. Based on my very, very limited understanding of Delphi's ARC implementation (which is all from the newsgroups), I believe you should call ServerMethodsClient1.DisposeOf, since the class descends from TComponent
But I'm not sure about that. I'm sure someone will jump on here that understands ARC and the proper solution to destroy the object rather than having a memory leak.
In my Android FMX implementation, I only call servermethods to get stuff done. (ie I don't use Datasnap data components). There's too much uncontrolled data transmission overhead to the Datasnap architecture to contemplate anything else realistically on a mobile device... To get around it (and not have memory leaks), I now create local instances of the TServermethods1Client as and when I need them and free them in context:
function TClientModule1.PostTheLog: Boolean;
var
Server: TServerMethods1Client;
begin
Server := TServerMethods1Client.Create(ClientModule1.SQLConnection1.DBXConnection);
try
UserID := Server.GetUserID;
...
finally
Server.Free;
end;
end;
Now the ClientModule1.SQLConnection1 can be connected and disconnected at will (preferably connected just before any call to a servermethod, and disconnected thereafter) and no further issues arise.
Which then begs the question: In which ideal world would the publicly accessible ServerMethods1Client actually be useful?

Indy FTP Failing to upload miserably

Using a simple code, such as:
procedure TForm1.cxButton1Click(Sender: TObject);
begin
ftp.Host := 'domain';
ftp.Username := 'user';
ftp.Password := 'password';
ftp.Connect;
ftp.Put('C:\_Projects\testpicture.JPG');
ftp.Quit;
ftp.Disconnect;
end;
I'm getting the following results:
Application freezes while uploading (ergo unable to see Progress Bar position).
Uploaded file goes corrupted (corrupts anything more than a few bytes).
What on earth am I doing wrong?
Thank you.
The app freezes because Indy uses blocking operations. While the code is running, the main message loop is not running, so new messages are not being processed until cxButton1Click() exits. To solve that, either place a TIdAntiFreeze component onto your TForm, or else move the TIdFTP code to a separate worker thread, and then use TIdSync or TIdNotify to update the UI safely when needed.
The file will be "corrupted" if you are transferring it in ASCII mode instead of in binary mode. Make sure the TIdFTP.TransferType property is set to ftBinary. Indy 9 and earlier defaulted to ftBinary, but Indy 10 defaults to ftASCII instead (to match the FTP protocol specs).

Need a sample/demo of using TIdTelnet to interact with telnet server

I tried to employ Indy 10.5.5 (shipped with Delphi 2010) for:
connecting to telnet server
performing username/password authentication (gaining access to the command shell)
executing a command with returning resulting data back to application
and had no success, additionally i'm completely lost in spaghetti logic of Indy's internals and now have no idea why it didnt work or how i supposed to send strings to the server and grab the results. Need some sample code to study.
Formal form of the question: Where can i get 3-rd party contributed demo covering TIdTelnet component? (indyproject.org demos webpage do not have one)
The main problem with Telnet is that it DOES NOT utilize a command/response model like most other Internet protocols do. Either party can send data at any time, and each direction of data is independant from the other direction. This is reflected in TIdTelnet by the fact that it runs an internal reading thread to receive data. Because of this, you cannot simply connect, send a command, and wait for a response in a single block of code like you can with other Indy components. You have to write the command, then wait for the OnDataAvailable event to fire, and then parse the data to determine what it actually is (and be prepared to handle situations where partial data may be received, since that is just how TCP/IP works).
If you are connecting to a server that actually implements a command/response model, then you are better off using TIdTCPClient directly instead of TIdTelnet (and then implement any Telnet sequence decoding manually if the server really is using Telnet, which is rare nowadays but not impossible). For Indy 11, we might refactor TIdTelnet's logic to support a non-threaded version, but that is undecided yet.
done with indy.
no comments.. just som old code :-)
telnet don't like the send string kommand.. use sendch.
telnetdude.Host := 1.1.1.1;
try
telnetdude.connect;
except
on E: Exception do begin
E.CleanupInstance;
end; {except}
if telnetdude.Connected then begin
for i := 1 to length(StringToSend) do telnetdude.sendch(StringToSend[i]);
telnetdude.sendch(#13);
end;
end; {while}
end; {if}
if telnetdude.Connected then telnetdude.Disconnect;
end;
I hope this helps anyone looking for answers to a similar question.
Firstly, It would seem the typical command/response model (as mentioned above, does indeed NOT apply).
So I just got it working for some very simple application (rebooting my router).
Specific additions to above code from Johnny Lanewood (and perhaps some clarification)
a) You have to send #13 to confirm the command
b) I got "hangs" on every command I sent / response I requested UNTIL I enabled ThreadedEvent. (this was my big issue)
c) the OnDataAvailable event tells you when new data is available from the Telnet Server - however there are no guarantees as to what this data is - i.e. it's pretty what you get in the command line / what ever is appended to the previous responses. But is is NOT a specific response line to your command - it's whatever the telnet server returns (could be welcome info, ASCII drawings etc etc.)
Given (c) above, one would rather check the OnDataAvailable event and parse the data (knowing what you'd expect). When the output stops (i.e. you need build a mechanism for this), you can parse the data and determine whether the server is ready for something new from the client. For the purpose of my code below, I set a read timemout and I just used Sleep(2000) - ignorantly expecting no errors and that the server would be ready after the sleep for the next command.
My biggest stumbling block was ThreadedEvent := True (see above in b)
Thus, my working solution (for specific application, and possibly horrible to some).
lIDTelnet := TIdTelnet.Create(nil);
try
lIdTelnet.ReadTimeout := 30000;
lIDTelnet.OnDataAvailable := TDummy.Response;
lIDTelnet.OnStatus := TDummy.Status;
lIdTelnet.ThreadedEvent := True;
try
lIDTelnet.Connect('192.168.0.1', 23);
if not lIDTelnet.Connected then
Raise Exception.Create('192.168.0.1 TELNET Connection Failed');
Sleep(2000);
lIdtelnet.SendString(cst_user + #13);
Sleep(2000);
lIdtelnet.SendString(cst_pass + #13);
Sleep(2000);
lIdtelnet.SendString(cst_reboot + #13);
Sleep(2000);
if lIDTelnet.Connected then
lIDTelnet.Disconnect;
except
//Do some handling
end;
finally
FreeAndNil(lIdTelnet);
end;
and then
class procedure TDummy.Response(Sender: TIdTelnet; const Buffer: TIdBytes);
begin
Write(TDummy.ByteToString(Buffer));
end;
class function TDummy.ByteToString(
const aBytes: TIdBytes): String;
var
i : integer;
begin
result := '';
for i := 0 to Length(aBytes) -1 do
begin
result := result + Char(aBytes[i]);
end;
end;

INDY 10.1.5 - Which SSL dlls work with Delphi 2006?

I'm trying to connect to google documents (following Marco Cantu's excellent REST example) but I am getting the following SSL errors:
1) If I use the SSL dlls from openssl-0.9.8i-i386-win32.zip I get the error:
"Could not load SSL library"
2) If I use the SSL dlls from indy_OpenSSL096m.zip I get the error:
"Error connecting with SSL"
3) If I use the SSL dlls from openssl-0.9.8h-i386-win32-Indy-IntraWebEdition.zip I get the error:
"Could not load SSl Library"
Now I've researched this and there are a lot of recommendations with dead links to dlls about, including links on stack overflow. I suspect I need to find the SSL dlls that are compatible with the version of INDY I am using.
My question is, does anyone know exactly which SSL dlls are compatible with Delphi 2006 & INDY 10.1.5?
I had the same problem even after I upgrading to INDY 10.2.3 and I tryed every different version of the “libeay32.dll” and “ssleay32.dll” files I could find ... Like Matt I always got one of the two errors: "Could not load SSL library" or the "Error connecting with SSL" with something like "error:00000006:lib(0):func(0):EVP lib" ...
I was very happy when I change the TidSSLioHandlerSocketOpenSSL.SSLOptions.Method to sslvSSLv23 and everything started working.
A bit more research and I quickly understood anytime I got the error "Could not load SSL library" I was using the wrong version of the DLL files and anytime I got the "Error connecting with SSL" with something like "error:00000006:lib(0):func(0):EVP lib" I was using the wrong SSLOptions.Method value.
Other Info: I'm using Delphi 2006, INDY 10.2.3 and I'm runnin on WinXP Pro
This caused me so much pain, I hope this post will save someone some time.
You could resort to some trial and error using downloads from the Fulgan site.
You might want to think about updating your copy of Indy and using the most recent OpenSSL DLLs.
FWIW, since I have spent a lot of time getting this https thing to work, here are the results of my successful efforts.
1- Delphi 7
2- indy9.0.19_d7.exe
3- IdSSLIOHandlerSocket1.SSLOptions.Method := sslvTLSv1; or,
IdSSLIOHandlerSocket1.SSLOptions.Method := sslvTLSv23; or,
IdSSLIOHandlerSocket1.SSLOptions.Method := sslvTLSv3;
I tried indy10.0.76_d7.exe and indy10.1.5_d7.exe under Delphi 7 and I cannot get them to install properly, let alone get HTTPS to work. I get the infamous message "Unit IdSysWin32 was compiled with a different version of IdException.EIdException." I searched for a solution to that problem on the web and couldn't find one - loads of others had the same message.
A useful site for testing https is https://msp.f-secure.com/web-test/common/test.html
Here is my source:
procedure TForm1.ButtonHTTPSClick(Sender: TObject);
var
IdHTTP1: TIdHTTP;
ParamStringList: TStringList;
s1: String;
MemoryStream1: TMemoryStream;
IdSSLIOHandlerSocket1: TIdSSLIOHandlerSocket;
begin // ssl works fine must have Indy version indy9.0.19_d7.exe and must use option sslvSSLv23
Screen.Cursor := crHourGlass;
IdHTTP1 := TIdHTTP.Create(nil);
IdSSLIOHandlerSocket1 := TIdSSLIOHandlerSocket.Create(nil);
IdHTTP1.IOHandler := IdSSLIOHandlerSocket1;
// IdSSLIOHandlerSocket1.SSLOptions.Method := sslvTLSv1; // sslvSSLv1 works fine
IdSSLIOHandlerSocket1.SSLOptions.Method := sslvSSLv3; // sslvSSLv3 works fine
// IdSSLIOHandlerSocket1.SSLOptions.Method := sslvSSLv23; // sslvSSLv23 works fine
// IdSSLIOHandlerSocket1.SSLOptions.Method := sslvSSLv2; sslvSSLv2 does not work
IdSSLIOHandlerSocket1.SSLOptions.Mode := sslmUnassigned;
IdSSLIOHandlerSocket1.SSLOptions.VerifyMode := [];
IdSSLIOHandlerSocket1.SSLOptions.VerifyDepth := 0;
ParamStringList := TStringList.Create;
MemoryStream1 := TMemoryStream.Create;
s1 := IdHTTP1.Post('https://msp.f-secure.com/web-test/common/test.html', ParamStringList);
MemoryStream1.Write(s1[1], Length(s1));
MemoryStream1.Position := 0;
MemoryStream1.SaveToFile('c:\temp\MemoryStream1.txt');
Memo1.Lines.Clear;
Memo1.Lines.LoadFromFile('c:\temp\MemoryStream1.txt');
MemoryStream1.Free;
ParamStringList.Free;
IdSSLIOHandlerSocket1.Free;
IdHTTP1.Free;
Screen.Cursor := crDefault;
end;
As far as I am aware the more recent versions of Indy work with standard OpenSSL binaries.
Download from here. We produced a Delphi FTP client app a while ago using Indy with SSL connections and I'm sure we just shipped the current OpenSSL dlls.
Edit: Just checked the app directory and the DLLs we used are OpenSSL 0.9.8.2 (3-Aug-06). (It's an old app)
Edit 2: And I've just copied the more recent 0.9.8k dlls over and they work fine too.
Find the Indy version you are using.Copy the Indy dlls i.e libeay32.dll,libssl32.dll and
ssleay32.dll into the Windows/System 32 Folder.It will resolve the error "Could not Load SSL Library"

Resources