

Kas Ob.
Members-
Content Count
626 -
Joined
-
Last visited
-
Days Won
10
Everything posted by Kas Ob.
-
DELETE can have content, also between all HTTP methods only GET and HEAD are not allowed to have content (but with a twist) From the same section of the the RFC you referred to: 1) from https://www.rfc-editor.org/rfc/rfc9110.html#name-delete This imply, well it does not imply it does clearly say the error cause is no content. 2) from https://www.rfc-editor.org/rfc/rfc9110.html#name-get So there is access where GET request is allowed to have content but only in special case with origin server is already on the same page with client, or lets say server and client has their own communication semantics, (their own API/SDK), in that case then such content is handled only by such server, other servers should drop it (drop the content) or refuse to serve with an error, the risk here is coming from request smuggling, this is interesting class of attacks against cache proxies and/or load balancers. 3) HEAD has the same paragraph as GET about request content. 4) Now back to (1) of DELETE, the same paragraph as GET and HEAD but we have specified error to return in case of absence of the content, in other words it is likely that there is generally defined semantics for DELETE (between client and server) hence the request content is needed.
-
FindNLSStringEx() and next pos
Kas Ob. replied to bk31415's topic in Algorithms, Data Structures and Class Design
Few things to know about this API 1) FoundLength is critical to know and adjust to, as the result of found string might be longer or shorter. 2) ACaseKind can/must be none of the above for default behavior and ignoring nothing. Anyway here an example, and as usual the forum sometime corrupt the text, and in this case is more delicate to reserve it as it contain very non popular encoded strings, i suggest to use the files instead of copy from the forum program FindNLSstring; {$APPTYPE CONSOLE} {$R *.res} uses SysUtils, Windows, Classes; type TNLSFindKind = (nlsFindFromStart, nlsFindFromEnd, nlsFindStartsWith, nlsFindEndsWith); TNLSCaseKind = (nlsNotSpecified, nlsLangIgnoreCase, nlsLangIgnoreDiacritic, nlsNormIgnoreCase, nlsNormIgnoreKanatype, nlsNormIgnoreNonspace, nlsNormIgnoreSymbols, nlsNormIgnoreWidth, nlsNormLangCasing); function TextPos(ASubText: UnicodeString; AText: UnicodeString; ACaseKind: TNLSCaseKind; var FoundLen: Integer; ALocale: PChar = nil; AFromPos: Integer = 1): Integer; var Flags: DWORD; begin Flags := FIND_FROMSTART; case ACaseKind of nlsLangIgnoreCase: Flags := Flags or LINGUISTIC_IGNORECASE; nlsLangIgnoreDiacritic: Flags := Flags or LINGUISTIC_IGNOREDIACRITIC; nlsNormIgnoreCase: Flags := Flags or NORM_IGNORECASE; nlsNormIgnoreKanatype: Flags := Flags or NORM_IGNOREKANATYPE; nlsNormIgnoreNonspace: Flags := Flags or NORM_IGNORENONSPACE; nlsNormIgnoreSymbols: Flags := Flags or NORM_IGNORESYMBOLS; nlsNormIgnoreWidth: Flags := Flags or NORM_IGNOREWIDTH; nlsNormLangCasing: Flags := Flags or NORM_LINGUISTIC_CASING; nlsNotSpecified: // we need this end; Result := FindNLSStringEx(ALocale, Flags, @AText[AFromPos], Length(AText) - AFromPos, PChar(ASubText), Length(ASubText), @FoundLen, nil, nil, 0); if Result >= 0 then Inc(Result, AFromPos); // adjusting the position end; const SUB_STR_1 = 'Götterdämmerung'; SUB_STR_2 = 'Götterdämmerung'; // we can use LOCALE_NAME as empty , the system will use the default for user LOCALE_NAME_USER_DEFAULT // LOCALE_NAME_USER_DEFAULT does override LOCALE_NAME_SYSTEM_DEFAULT LOCALE_NAME = ''; procedure LoadFileAndSearch(SubString: string); var StringList: TStringList; OurLongText: string; FoundPos, FoundLen: Integer; FoundString:string; begin StringList := TStringList.Create; try StringList.LoadFromFile('MacOS_ItunesContent_Small.txt'); OurLongText := StringList.Text; FoundPos := 0; Writeln('Searching for ', SubString, ' Found :'); while True do begin FoundLen := 0; FoundPos := TextPos(SubString, OurLongText, nlsNotSpecified, FoundLen, LOCALE_NAME, FoundPos); if FoundPos < 0 then Break; FoundString := Copy(OurLongText,FoundPos,FoundLen); Writeln(#9,FoundPos, ' Length : ', FoundLen,' ',FoundString); Inc(FoundPos, FoundLen); end; finally StringList.Free; end; end; begin try SetConsoleOutputCP(CP_UTF8); // don't know which code page can display the strings in question like it does in a VCL Memo // OS supported code pages are listed at registry path HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage //SetConsoleOutputCP(1252); LoadFileAndSearch(SUB_STR_1); LoadFileAndSearch(SUB_STR_2); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; Writeln('Done.'); Readln; end. the needed sample file content, copied form the German forum without permission dummy line Götterdämmerung Götterdämmerung Track 4344 Track ID: 11572 Titel: Morgendämmerung und Siegfried's Rheinfahrt aus "Götterdämmerung" Artist: Richard Wagner Album: Rheingold Track-Art: Abgeglichene AAC-Audiodatei GUID: Hinzugefügt: 14.12.2017 17:57:46 Persistent ID: 91453A3B4084EC74 Tracktype: File Speicherort: Macintosh HD/Users/AlfonsYondraschek/Music/iTunes 1/iTunes Media/Music/Richard Wagner/Rheingold/05 Morgendämmerung und Siegfried's Rheinfahrt aus _Götterdämmerung_.m4a Track 4345 Track ID: 11574 Titel: Siegfried's Trauermarsch und Finale aus "Götterdämmerung" Artist: Richard Wagner Album: Rheingold Track-Art: Abgeglichene AAC-Audiodatei GUID: Hinzugefügt: 14.12.2017 17:57:46 Persistent ID: 6C45FF4271B8A57B Tracktype: File Speicherort: Macintosh HD/Users/AlfonsYondraschek/Music/iTunes 1/iTunes Media/Music/Richard Wagner/Rheingold/06 Siegfried's Trauermarsch und Finale aus _Götterdämmerung_.m4a the result should be like this Searching for Götterdämmerung Found : 15 Length : 15 Götterdämmerung 32 Length : 17 Götterdämmerung 135 Length : 15 Götterdämmerung 488 Length : 17 Götterdämmerung 591 Length : 15 Götterdämmerung 936 Length : 17 Götterdämmerung Searching for Götterdämmerung Found : 15 Length : 15 Götterdämmerung 32 Length : 17 Götterdämmerung 135 Length : 15 Götterdämmerung 488 Length : 17 Götterdämmerung 591 Length : 15 Götterdämmerung 936 Length : 17 Götterdämmerung Done. the files FindNLSstring.dpr MacOS_ItunesContent_Small.txt Notice the output on my console is like this using CP_UTF8, but pasting in the bowser fixed it, outputting to lets say TMemo will show correct text like notepad or the text in the forum. -
The picture still not clear for me, If i understand it right, then you have a server running IIS and you installed software (SDK) from Global Payment, right ? If the answer is yes then it has nothing to do with Global Payment, the TCP connection is blocked between me (not only me many others) and your server, it is on your Windows and the host that is hosting your IIS, Also you said cloud, what you mean by cloud is it VPS or dedicated, what is the host company ? this one who you need their support to diagnose the blocked connections. I am confirming again the connections are not established, so not TCP handshake, nothing, it has nothing to do with software that is running on IIS, It can be IIS failure or a filter but this is very unlikely, or a firewall, that firewall can either be on your Windows (your server) or running by the host company of your server.
-
I tried these links and nothing is no one answer the connection timed out. Using WireShark also showed the connection didn't establish and no answer or anything came back, acted like black hole. Using SSLabs.com as you did shows result and successful server response, using two other similar services also shows online server. The problem is not in your IIS at all, it is fine and responding, but when it get connections, there is firewall or monitoring service blocking IP(s), in case my ISP is blocked, find out what is monitoring/protecting your server traffic and reconfigure it, it could be missed/updated configuration on the host part, or simply you did select wrong or tight security template or something there. In short that is not IIS problem at all, and most likely your host security software/hardware, test with disabled Windows Firewall to make sure, beyond that it is not IIS or Windows problem.
-
Absolute directive with record and array
Kas Ob. replied to DelphiUdIT's topic in Algorithms, Data Structures and Class Design
Here a faster suggestion procedure FooBar(const X1, Y1, X2, Y2: Single); var Y1bin: Cardinal absolute Y1; Y2bin: Cardinal absolute Y2; begin // Check if both Y1 and Y2 are zero using a single bitwise operation if (Y1bin or Y2bin) shl 1 = 0 then Exit; ... end; Or using AND instead of bit shifting procedure FooBar(const X1, Y1, X2, Y2: Single); var Y1bin: Cardinal absolute Y1; Y2bin: Cardinal absolute Y2; begin if (Y1bin or Y2bin) and $7FFFFFFF = 0 then Exit; ... end; -
Shadow underneath Form does not always appear (CS_DROPSHADOW)
Kas Ob. replied to PeaShooter_OMO's topic in Windows API
If only it was this simple ! The idea is right, but the complications can be huge. 1) The code is not handling the failure of UnregisterClass. 2) UnregisterClass will fail if there is a Window still online associated with that class, by online i mean created and/or visible, simply a window with that class exists, from https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unregisterclassa Before calling this function, an application must destroy all windows created with the specified class. 3) even if did pass and succeeded then there is the other caching software that might already read and copied the Class and its information and might fail, like live translation software or the one for accessibility that read the content of the screen or the ones that completely redraw them in different way (out of the OS theming), such software will behave erratically if performed something at that moment and Windows reported an error with the associated WindowClass. So, i don't recommend such approach, if UnregisterClass should be called then it should put at lower level (deep) in the VCL in appropriated place, and it must recreate all the already created Forms, dialogs, controls... it is huge adjustment. -
Shadow underneath Form does not always appear (CS_DROPSHADOW)
Kas Ob. replied to PeaShooter_OMO's topic in Windows API
Found the culprit of this discrepancy, but don't have a solution, or lets say nice solution, on top of that my old VCL is irrelevant to the most , so , someone else should have a deeper look into this. There is two different RegisterClass functions, one belong to Delphi RTL and the other is an OS API, Delphi Forms like other controls do register them selves with RegisterClass with unique name, on both API and RTL, the one is causing this problem is API how Windows store the style, Delphi RTL doesn't handle UnregisterClass (API) correctly or not calling it at all, hence CreateParams and the following creating the control (and setting its modern and advanced style) stay short from performing as intended. As a workaround a suggest to refactor your popup into base and two inherited ones hence forcing the class name used by RegisterClass to be different, one with shadow and the other without, this will be the most clean way, though it must be tested. ps: @PeaShooter_OMO don't call "FreeAndNil(FormPopup);" on Self, this is problematic and dangerous, just use "Release;" and it will be released in orderly form, and you can skip the var usage altogether by using with TFormPopup.Create(True) do Show; // or with TFormPopup.Create(False) do Show; -
Shadow underneath Form does not always appear (CS_DROPSHADOW)
Kas Ob. replied to PeaShooter_OMO's topic in Windows API
Testing the real project and now i see even with RecreateWnd it is not reliable, and acting as there is something is not initialized. On XE8, the same code with RecreateWnd, act differently with or without debug dcu included in project settings !, and if there is a break point that halted the code execution then the shadow might appear more frequently. -
Shadow underneath Form does not always appear (CS_DROPSHADOW)
Kas Ob. replied to PeaShooter_OMO's topic in Windows API
It is beyond me why it is needed, short coming in CM_RECREATEWND that used to trigger the recreation and when it is received, (i think ) It could be made better but will break things, also may be things changed in newer VCLs but in the older ones RecreateWnd is needed, even it means the recreation will happen twice. -
Shadow underneath Form does not always appear (CS_DROPSHADOW)
Kas Ob. replied to PeaShooter_OMO's topic in Windows API
Nothing wrong, just missed "RecreateWnd;" after setting the Params. -
I see undefined behaviour, this can go beyond degraded performance and go into literally corrupting the memory or the the worse the stack, triggering very hard to diagnose behavior, see.. calling ".classname" might land on an arbitrary method, and who knows what have been changed in that method/procedure/function... , literally nightmare stuff, and reproducing it is near impossible ! And of course the exception doesn't have to be silent, it could be triggered but after altering memory/stack, disguise the expected behavior and hide what have being changed somewhere.
-
Winapi.Windows.PROCESS_QUERY_LIMITED_INFORMATION not found
Kas Ob. replied to PeterPanettone's topic in Windows API
No, that is misuse between declaration and definition, use what Remy suggested. IFDEF/IFNDEF about definition, literally defined, these are not for the code but for the compiler variables. DECLARED()/NOT DECLARED() these about your code, namely anything that can be declared like consts, records, classes .... It compile in your case because there is no defined directives (compiler directive) under that name. Example: var i: Integer; B: Integer; // comment this and the compilation will fail {$IF NOT DECLARED(B)} This should cause an error only if you comment or remove B from variables {$IFEND} -
Capture as soon as file paste is selected
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
Hi Anders, I want to list some facts 1) Windows Explorer is an application like any other, and it is not essential to the OS itself, so when RDP application run it will interact between two application, hence the need to capture and handle the clipboard, when i copy a file/dir form my own desktop and try to paste it on remote using RDP, then i am pasting the on my application (or RDP), and this should trigger RDP or on the remote to paste, so it should simulate clipboard is filled then send data. 2) CFSTR_TARGETCLSID is irrelevant here as it used internally by Explorer itself. 3) Microsoft RDP does send file in two different ways, one capturing clipboard and its content then simulate on the other hand, well usually it does that, unless Local resources being shared per setting in the RDP connection, this initiate completely different path to share files and synchronize them between host and guest. 4) SHChangeNotifyRegister can capture files changes and many others like copy and paste or rename, initiated by keyboard and/or by mouse. ( might not be useful or needed after all) 5) Th trick is to capture the event then using IShellExplorer to emulate pasting file in the specified directory, (also might be not needed at all) So in short the solution is not to circumvent any thing, not really, because , as example, i built a RDP application, then on the remote part capture the copy event from clipboard (yes using clipboard APIs), then trigger filling the clipboard on my local PC, then on paste on my local i will initiate the sending file after locking the directory same as RDP (this locking will need shell APIs), same can happen in the other way around. Now sounding this loud, i don't understand the need for monitoring the shell operation using SHChangeNotifyRegister ! may be i lost it there or over complicate things, but the copy and paste is happening into different applications, either my remote RDP with the remote Explorer, or local RDP viewer and local Explorer, sending data is handled by the RDP two parts not involving any Explorer. ps: I spent near 3 hours trying to make SHChangeNotification_Lock work, but i think it is working at last ! -
Capture as soon as file paste is selected
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
Yes. Yes. In two different way, one when to upload and one to download, but this is somehow irrelevant to your usage, as like Windows RDP it comes baked with special integration with for Windows Explorer aka Windows Shell, these are undocumented API and COM objects. How to do it ? You must understand and use these : 1) IFileOperation https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifileoperation this will capture (and monitor) copying files, moving ,renaming .... 2) IFolderView https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifolderview to find the focused folder in Windows Explorer 3) SHChangeNotifyRegister for hooking shell operation https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shchangenotifyregister 4) IShellWindows https://learn.microsoft.com/en-us/windows/win32/api/exdisp/nn-exdisp-ishellwindows this is the core one to start with and needed to find opened folders ..etc Using these will remove the need for key logger and mouse tracking event, yet in case it failed or and because i can't remember how the hooking was triggered as only reporting or intercepting, meaning you can block, in case that the case and you need to prevent the operation, then you will need key and mouse logger, there is few methods to intercept then cancel if you want. Hope that help, as for all the above, there is many questions on the internet and resources on how to do it, but you specific case need to understand and mix and match an approach. -
First you missing few details about the problem at hand, 1) You are using Client and the client doesn't need a certificate, to be more accurate the default usage for validation on the client side is to check and validate the path of certificate(s) from the server against trusted root or trusted CA. 2) What certificate is on the server, is it valid ? not revoked ? not expired ?.... 3) What is this certificate you mentioned, is it the root or the CA or the end point that server has used to establish the connection ? Now, what you can do or what you should do 1) By default like any TLS connection, the client must have a trusted root store, to resolve the server certificate to, this include any CA in-between them (i mean the end point one aka server and its root), generally either you have a store (punch of certificates) included with in (shipped) your own application, or depend on the OS provided store. 2) Your client doesn't have a store, then it is OK, you can have one root and resolve the path to like above. 3) You are binning the certificate, meaning you will included one certificate, no store, no validation, not best practice at all !, yet it is OK, will work , and fail later ! , but should work (highly not recommended as it is bad and fragile and can render you communication useless any time when the server lose its private key or the certificate leak and you have to replace it...etc), in this exact case and if this is what you are trying to do , then just compare the server certificate against the one in the pem Hope that help, ps: though you had searched the internet, so i will assume you are loading the pem right and you know to validate or compare, but in case you still missing the point and how it should done, then i recommend to use ICS demos, even if you are not going to use that library, but you can study and understand how to validate a certificate ( or try to shoot your self in the foot by comparing against end point only, against all recommendations )
-
Is this VM a developing machine or daily driver for browsing internet and download everything you being offered by an advertisement ? 1) developing machine, then you don't need security scanning for everything all the time, right ? 2) daily driver and testing everything you can download, then leave the defender and install like ten more anti viruses, and make sure to uninstall Delphi for your own security and integrity of your code and generated binaries. It is simple, my developing machine is not allowed to see Internet or access anything outside my home network, i don't download anything suspicious from unknown providers on that machine, heck, i even don't allow Windows to update or to contact Microsoft, so i don't need an virus scanner at all. Anyway, it is up to you keep Windows Defender running or just remove most of this useless scanning each time, in worst case scenario let it scan once, and then disable behavior control and live protection or what ever called, by each AV, also make sure to disable sending samples to laboratories to any AV home, also don't even allow any AV to scan your traffic, this compromise you and your data the most,... i am sure i forgot to mention tens of thing to not do, so the most critical advise of them all think of everything they offer in the settings and use logic, and remember if a malicious code is on your device then it only be detected if it is in the AV database, in other words already known !, so all of this crap of detecting illegal behavior in real time is useless crap, if it is know then cold scan will detect it, if it is unknown then it will run unless real time monitoring is kicking it hence will ask you about everything running on your device, the only good thing from a good scanner if that question happen once only.
-
MsMpEng.exe is Windows Defender scanner and smart locker, and it will repeat the above or similar report for each file or library that bds.exe will load, in that report it is only for one bindcompfmx290.bpl trying to load. So yes disable Defender.
-
Run as admin on unauthorized Windows username
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
Not sure what are you talking about ?! Elevate package and zip file ! You don't need to rerun your process with higher (elevated) privileges, you can elevate or lets say enable a specific privilege for the current process (or token in general, which is most the time is a handle) by using AdjustTokenPrivileges https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges You can use something like this function EnablePrivilege(const PrivilegeName: string): Boolean; var TokenHandle: THandle; NewState: TOKEN_PRIVILEGES; ReturnLength: DWORD; begin Result := False; if OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TokenHandle) then try NewState.PrivilegeCount := 1; NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; if LookupPrivilegeValue(nil, PChar(PrivilegeName), NewState.Privileges[0].Luid) then begin if AdjustTokenPrivileges(TokenHandle, False, NewState, SizeOf(NewState), nil, ReturnLength) then Result := GetLastError <> ERROR_NOT_ALL_ASSIGNED; end; finally CloseHandle(TokenHandle); end; end; .. const SE_ASSIGN_PRIMARY_TOKEN_NAME = 'SeAssignPrimaryTokenPrivilege'; .. // call it with something like this if EnablePrivilege(SE_ASSIGN_PRIMARY_TOKEN_NAME) then begin .. Just remember to check for elevated process before calling as it will fail, in other words if you are not administrator will not be able to enable SeAssignPrimaryTokenPrivilege hence your process will most likely will be able to run remove process with login etc.. If your account doesn't have TOKEN_ADJUST_PRIVILEGES enabled which is enabled for Administrator ... users then you can't adjust for the current process. Also i said i am not sure if this will solve your problem in full or it will be enough, as there is different causes might prevent such execution, also there is policies should be enabled allowing the such run for a remote process. in all cases run your application or test one, then use Process Explorer, you can see in the Security tab for that application like this screenshot I put a break point using the debugger and confirmed that the SeAssignPrimaryTokenPrivilege privilege is enabled or elevated for this particular privilege, one thing though Process explorer tab need to be closed and reopened to refresh these information. -
Run as admin on unauthorized Windows username
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
As Francois pointed, your user itself doesn't privilege to execute such operation, which is in this case CreateProcess(xx) with different token on different station, not %100 sure but i think your user should be have SeAssignPrimaryTokenPrivilege https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/security-policy-settings/user-rights-assignment https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/security-policy-settings/replace-a-process-level-token -
Please, pretty please, make it [0..63] not [0..64], it is triggering my OCD ! Also having goosebumps from that off by one to an odd number !
-
Overflow Checking from 10.4 onwards
Kas Ob. replied to pmcgee's topic in RTL and Delphi Object Pascal
I think 48 was there and the code changed and that comment along that excerpt stayed, Anyhow, the random generation algorithm is LCG, and it is fast and enough for general purposes, it is like PCG https://en.wikipedia.org/wiki/Permuted_congruential_generator , also there is many others, they are fast, extremely fast but they are not cryptographically secure, what does that means ? It means if i get hold on few (or lot, it depends) of the output random of that algorithm then i can predict the exact state (seed) at that moment, hence i can predict all the future random output. Why this is critically insecure ? I will give an example, in TLS connection key are randomly generated (private keys), while only public key are sent over the wire and they can NOT compromise the private key but there is different things in the SSL/TLS header that can help break the private key, if the software is using weak random generator like LCG then it also will be used in the sessionID and in the IV and nonces ..etc that are plainly sent in the TLS header for the handshake, hence if the attacker predicted the state then it at least he can just produce random numbers and all your private keys (future ones) are exposed. LCG is fins for general big numbers library but it can not be used with PKI and any cryptographic library/implementation, as you are using RSA, then for your own learning it is fine, but do not trust its random or key coming form it. ps : in the mentioned library LCG is defined as form here https://en.wikipedia.org/wiki/Permuted_congruential_generator and constants are a,c and m , you can see them here https://github.com/rvelthuis/DelphiBigNumbers/blob/master/Source/Velthuis.RandomNumbers.pas#L116C1-L136C5 m is a little not so obvious but it is in the bit shift meaning m=64-Bits rendering, with this known and as Bits is used in Next which called with three variant 31,32 and 64, all this values just render it more predictable, at 32 all you need is somethign around 32 byte to calculate the state (seed) ! also SessionID in TLS is 32byte ! meaning with the wrong PRNG it is enough to predict the exact state and predict the all exact private keys, breaking the secure connection alltogether. Also 48 bits (the comment) it should reflect on 64-Bits (or Bits) being 48, but i don't see that anywhere, may it was there in the past. -
I believe the needed buffer is 56 (2*28) for IPv6 so [0..55] bytes should be enough, if i am not missing something.
-
I forgot to mention important thing about that structure and its size. You can't and must not put it on the stack !, it will overflow and destroy/corrupt the stack, so it must be on the heap and must be zeroed before usage as best practice, because there is two addresses (pointing to two structures) will be filled by that API and it will put them right after the initial structure and fix the addresses.
-
Here a fully working example, modified from a code for different thing, yet it shows successful use of SO_BSP_STATE unit uReadSocketInfo; interface uses Windows, Winsock2; function WSAInitialize(MajorVersion, MinorVerion: Integer): Boolean; function WSADeInitialize: Boolean; function CheckTCPPortNB(const IP: string; Port: Integer; out TimeMS: Integer): Boolean; var CHECKPOINT_TIMEOUT_MS: integer = 1000; implementation procedure GetSocketInformation(s: TSocket); var pSockAddresssI: PCSADDR_INFO; Res, WsaLError, OptLen: Integer; begin OptLen := SizeOf(CSADDR_INFO) + 128; // yes the original size is 24, but more is needed and will fail on 24 // for IPv4 an extra of 32 bytes is enough instead of 128 pSockAddresssI := GetMemory(OptLen); try Res := getsockopt(s, SOL_SOCKET, SO_BSP_STATE, PAnsiChar(pSockAddresssI), OptLen); if Res = SOCKET_ERROR then WsaLError := WSAGetLastError else Writeln('Socket information :'); finally FreeMemory(pSockAddresssI); end; end; function CheckTCPPortNB(const IP: string; Port: Integer; out TimeMS: Integer): Boolean; var s: TSocket; Addr: TSockAddrIn; SAddr: TSockAddr absolute Addr; QPF, QPC1: Int64; NonBlockMode: DWORD; Res: Integer; FDW, FDE: fd_set; TimeVal: TTimeVal; function GetElapsedTime: Integer; var QPC2: Int64; begin QueryPerformanceCounter(QPC2); Result := (QPC2 - QPC1) div (QPF div 1000); end; begin Result := False; TimeMS := 0; s := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if s = INVALID_SOCKET then Exit; NonBlockMode := 1; ioctlsocket(s, Integer(FIONBIO), NonBlockMode); Addr.sin_family := AF_INET; Addr.sin_addr.S_addr := inet_addr(PAnsiChar(AnsiString(IP))); Addr.sin_port := htons(Port); QueryPerformanceFrequency(QPF); QueryPerformanceCounter(QPC1); Res := connect(s, SAddr, SizeOf(SAddr)); if (Res = SOCKET_ERROR) and (WSAGetLastError = WSAEWOULDBLOCK) then begin TimeVal.tv_sec := 0; // 1 sec = 1000000 usec TimeVal.tv_usec := 1000; // 1 ms = 1000 usec repeat FDW.fd_count := 1; FDW.fd_array[0] := s; FDE.fd_count := 1; FDE.fd_array[0] := s; TimeMS := GetElapsedTime; Res := select(1, nil, @FDW, @FDE, @TimeVal); until (Res > 0) or (TimeMS >= CHECKPOINT_TIMEOUT_MS); end; Result := (FDW.fd_count = 1) and (FDE.fd_count = 0); /// we have connected socket with full valid information if Result then begin GetSocketInformation(s); end; /// TimeMS := GetElapsedTime; if s <> INVALID_SOCKET then closesocket(s); end; function WSAInitialize(MajorVersion, MinorVerion: Integer): Boolean; var WSA: TWsaData; begin Result := WSAStartup(MakeWord(MajorVersion, MinorVerion), WSA) = 0; if Result then begin Result := (Byte(WSA.wVersion shr 8) = MinorVerion) and (Byte(WSA.wVersion) = MajorVersion); if not Result then begin Result := False; WSADeInitialize; end; end; end; function WSADeInitialize: Boolean; begin Result := WSACleanup = 0; end; initialization WSAInitialize(2, 2); finalization //WSADeInitialize; end. a small project to use it program SocketInformation; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, uReadSocketInfo in 'uReadSocketInfo.pas'; var Time : Integer; begin try CheckTCPPortNB('142.251.36.46', 80, Time); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; Readln; end. Put a break point with debugger on the getsockopt and you will get 32 bytes additional bytes (on top the 24 bytes, the structure size) is needed for IPv4 so i suspect more is needed for IPv6, this is undocumented behavior.
-
Overflow Checking from 10.4 onwards
Kas Ob. replied to pmcgee's topic in RTL and Delphi Object Pascal
Literally the definition of Karatsuba, to split in half and perform on half length thus reducing the complexity of time needed not the complexity of the implementation, in case of 64bit then only two half is needed with no recursion, Wikipedia page explain it, but there is simpler resources on the Internet to explain it. Fun fact : There is also an algorithm named Toom-Cook https://en.wikipedia.org/wiki/Toom–Cook_multiplication reduce the multiplication further but increase the complexity of implementation more, both algorithm shift the operation into smaller part reducing the need for multiplication carry but increase the addition operation with its carry. Just common knowledge to whom may be interested. Yes it is simple, but if you want the most beautiful mathematically algorithm (i see it like that), is El-Gamal (sometimes written (ElGamal), and once you built your RSA you will find implementing ElGamal is relatively close and not any more a complex task, as you will need the little different or adjusted arithmetic, i mean you will have primality test along with GCD (GCD might be needed but that depend on your approach or method), ElGamal has a feature which can be used with Elliptic Curve and their finite fields hence decreasing the length of the keys substantially, so it might interest you and your friends ! https://en.wikipedia.org/wiki/ElGamal_encryption https://en.wikipedia.org/wiki/ElGamal_signature_scheme A little more detailed resources https://www.geeksforgeeks.org/elgamal-encryption-algorithm/ https://compare-encryption-algorithms.mojoauth.com/rsa-4096-vs-elgamal-variable-key-size/ Yup, nothing beats Miller–Rabin test in speed, it looks nice book. Focus on RSA !, ElGamal will need different beast https://en.wikipedia.org/wiki/Modular_exponentiation but after RSA you will find it easy as it is pretty straight forward as listed in Wikipedia. Again good luck.