blcksock.pas 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415
  1. {==============================================================================|
  2. | Project : Ararat Synapse | 009.010.002 |
  3. |==============================================================================|
  4. | Content: Library base |
  5. |==============================================================================|
  6. | Copyright (c)1999-2021, Lukas Gebauer |
  7. | All rights reserved. |
  8. | |
  9. | Redistribution and use in source and binary forms, with or without |
  10. | modification, are permitted provided that the following conditions are met: |
  11. | |
  12. | Redistributions of source code must retain the above copyright notice, this |
  13. | list of conditions and the following disclaimer. |
  14. | |
  15. | Redistributions in binary form must reproduce the above copyright notice, |
  16. | this list of conditions and the following disclaimer in the documentation |
  17. | and/or other materials provided with the distribution. |
  18. | |
  19. | Neither the name of Lukas Gebauer nor the names of its contributors may |
  20. | be used to endorse or promote products derived from this software without |
  21. | specific prior written permission. |
  22. | |
  23. | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
  24. | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
  25. | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
  26. | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
  27. | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
  28. | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
  29. | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
  30. | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  31. | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
  32. | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
  33. | DAMAGE. |
  34. |==============================================================================|
  35. | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
  36. | Portions created by Lukas Gebauer are Copyright (c)1999-2021. |
  37. | All Rights Reserved. |
  38. |==============================================================================|
  39. | Contributor(s): |
  40. |==============================================================================|
  41. | History: see HISTORY.HTM from distribution package |
  42. | (Found at URL: http://www.ararat.cz/synapse/) |
  43. |==============================================================================}
  44. {
  45. Special thanks to Gregor Ibic <[email protected]>
  46. (Intelicom d.o.o., http://www.intelicom.si)
  47. for good inspiration about SSL programming.
  48. }
  49. {$DEFINE ONCEWINSOCK}
  50. {Note about define ONCEWINSOCK:
  51. If you remove this compiler directive, then socket interface is loaded and
  52. initialized on constructor of TBlockSocket class for each socket separately.
  53. Socket interface is used only if your need it.
  54. If you leave this directive here, then socket interface is loaded and
  55. initialized only once at start of your program! It boost performace on high
  56. count of created and destroyed sockets. It eliminate possible small resource
  57. leak on Windows systems too.
  58. }
  59. //{$DEFINE RAISEEXCEPT}
  60. {When you enable this define, then is Raiseexcept property is on by default
  61. }
  62. {:@abstract(Synapse's library core)
  63. Core with implementation basic socket classes.
  64. }
  65. {$IFDEF FPC}
  66. {$MODE DELPHI}
  67. {$ENDIF}
  68. {$IFDEF VER125}
  69. {$DEFINE BCB}
  70. {$ENDIF}
  71. {$IFDEF BCB}
  72. {$ObjExportAll On}
  73. {$ENDIF}
  74. {$Q-}
  75. {$H+}
  76. {$M+}
  77. {$TYPEDADDRESS OFF}
  78. //old Delphi does not have MSWINDOWS define.
  79. {$IFDEF WIN32}
  80. {$IFNDEF MSWINDOWS}
  81. {$DEFINE MSWINDOWS}
  82. {$ENDIF}
  83. {$ENDIF}
  84. {$IFDEF UNICODE}
  85. {$WARN IMPLICIT_STRING_CAST OFF}
  86. {$WARN IMPLICIT_STRING_CAST_LOSS OFF}
  87. {$ENDIF}
  88. {$IFDEF NEXTGEN}
  89. {$ZEROBASEDSTRINGS OFF}
  90. {$ENDIF}
  91. unit blcksock;
  92. interface
  93. uses
  94. SysUtils, Classes,
  95. synafpc,
  96. synsock, synautil, synacode, synaip
  97. {$IFDEF POSIX}
  98. ,System.Generics.Collections, System.Generics.Defaults
  99. {$ENDIF}
  100. {$IfDef CIL}
  101. ,System.Net
  102. ,System.Net.Sockets
  103. ,System.Text
  104. {$EndIf}
  105. ;
  106. const
  107. SynapseRelease = '40';
  108. cLocalhost = '127.0.0.1';
  109. cAnyHost = '0.0.0.0';
  110. cBroadcast = '255.255.255.255';
  111. c6Localhost = '::1';
  112. c6AnyHost = '::0';
  113. c6Broadcast = 'ffff::1';
  114. cAnyPort = '0';
  115. CR = #$0d;
  116. LF = #$0a;
  117. CRLF = CR + LF;
  118. c64k = 65536;
  119. type
  120. {:@abstract(Exception clas used by Synapse)
  121. When you enable generating of exceptions, this exception is raised by
  122. Synapse's units.}
  123. ESynapseError = class(Exception)
  124. private
  125. FErrorCode: Integer;
  126. FErrorMessage: string;
  127. published
  128. {:Code of error. Value depending on used operating system}
  129. property ErrorCode: Integer read FErrorCode Write FErrorCode;
  130. {:Human readable description of error.}
  131. property ErrorMessage: string read FErrorMessage Write FErrorMessage;
  132. end;
  133. {:Types of OnStatus events}
  134. THookSocketReason = (
  135. {:Resolving is begin. Resolved IP and port is in parameter in format like:
  136. 'localhost.somewhere.com:25'.}
  137. HR_ResolvingBegin,
  138. {:Resolving is done. Resolved IP and port is in parameter in format like:
  139. 'localhost.somewhere.com:25'. It is always same as in HR_ResolvingBegin!}
  140. HR_ResolvingEnd,
  141. {:Socket created by CreateSocket method. It reporting Family of created
  142. socket too!}
  143. HR_SocketCreate,
  144. {:Socket closed by CloseSocket method.}
  145. HR_SocketClose,
  146. {:Socket binded to IP and Port. Binded IP and Port is in parameter in format
  147. like: 'localhost.somewhere.com:25'.}
  148. HR_Bind,
  149. {:Socket connected to IP and Port. Connected IP and Port is in parameter in
  150. format like: 'localhost.somewhere.com:25'.}
  151. HR_Connect,
  152. {:Called when CanRead method is used with @True result.}
  153. HR_CanRead,
  154. {:Called when CanWrite method is used with @True result.}
  155. HR_CanWrite,
  156. {:Socket is swithed to Listen mode. (TCP socket only)}
  157. HR_Listen,
  158. {:Socket Accepting client connection. (TCP socket only)}
  159. HR_Accept,
  160. {:report count of bytes readed from socket. Number is in parameter string.
  161. If you need is in integer, you must use StrToInt function!}
  162. HR_ReadCount,
  163. {:report count of bytes writed to socket. Number is in parameter string. If
  164. you need is in integer, you must use StrToInt function!}
  165. HR_WriteCount,
  166. {:If is limiting of bandwidth on, then this reason is called when sending or
  167. receiving is stopped for satisfy bandwidth limit. Parameter is count of
  168. waiting milliseconds.}
  169. HR_Wait,
  170. {:report situation where communication error occured. When raiseexcept is
  171. @true, then exception is called after this Hook reason.}
  172. HR_Error
  173. );
  174. {:Procedural type for OnStatus event. Sender is calling TBlockSocket object,
  175. Reason is one of set Status events and value is optional data.}
  176. THookSocketStatus = procedure(Sender: TObject; Reason: THookSocketReason;
  177. const Value: String) of object;
  178. {:This procedural type is used for DataFilter hooks.}
  179. THookDataFilter = procedure(Sender: TObject; var Value: AnsiString) of object;
  180. {:This procedural type is used for hook OnCreateSocket. By this hook you can
  181. insert your code after initialisation of socket. (you can set special socket
  182. options, etc.)}
  183. THookCreateSocket = procedure(Sender: TObject) of object;
  184. {:This procedural type is used for monitoring of communication.}
  185. THookMonitor = procedure(Sender: TObject; Writing: Boolean;
  186. const Buffer: TMemory; Len: Integer) of object;
  187. {:This procedural type is used for hook OnAfterConnect. By this hook you can
  188. insert your code after TCP socket has been sucessfully connected.}
  189. THookAfterConnect = procedure(Sender: TObject) of object;
  190. {:This procedural type is used for hook OnVerifyCert. By this hook you can
  191. insert your additional certificate verification code. Usefull to verify server
  192. CN against URL. }
  193. THookVerifyCert = function(Sender: TObject):boolean of object;
  194. {:This procedural type is used for hook OnHeartbeat. By this hook you can
  195. call your code repeately during long socket operations.
  196. You must enable heartbeats by @Link(HeartbeatRate) property!}
  197. THookHeartbeat = procedure(Sender: TObject) of object;
  198. {:Specify family of socket.}
  199. TSocketFamily = (
  200. {:Default mode. Socket family is defined by target address for connection.
  201. It allows instant access to IPv4 and IPv6 nodes. When you need IPv6 address
  202. as destination, then is used IPv6 mode. othervise is used IPv4 mode.
  203. However this mode not working properly with preliminary IPv6 supports!}
  204. SF_Any,
  205. {:Turn this class to pure IPv4 mode. This mode is totally compatible with
  206. previous Synapse releases.}
  207. SF_IP4,
  208. {:Turn to only IPv6 mode.}
  209. SF_IP6
  210. );
  211. {:specify possible values of SOCKS modes.}
  212. TSocksType = (
  213. ST_Socks5,
  214. ST_Socks4
  215. );
  216. {:Specify requested SSL/TLS version for secure connection.}
  217. TSSLType = (
  218. LT_all,
  219. LT_SSLv2,
  220. LT_SSLv3,
  221. LT_TLSv1,
  222. LT_TLSv1_1,
  223. LT_TLSv1_2,
  224. LT_TLSv1_3,
  225. LT_SSHv2
  226. );
  227. {:Specify type of socket delayed option.}
  228. TSynaOptionType = (
  229. SOT_Linger,
  230. SOT_RecvBuff,
  231. SOT_SendBuff,
  232. SOT_NonBlock,
  233. SOT_RecvTimeout,
  234. SOT_SendTimeout,
  235. SOT_Reuse,
  236. SOT_TTL,
  237. SOT_Broadcast,
  238. SOT_MulticastTTL,
  239. SOT_MulticastLoop
  240. );
  241. {:@abstract(this object is used for remember delayed socket option set.)}
  242. TSynaOption = class(TObject)
  243. public
  244. Option: TSynaOptionType;
  245. Enabled: Boolean;
  246. Value: Integer;
  247. end;
  248. TCustomSSL = class;
  249. TSSLClass = class of TCustomSSL;
  250. TBlockSocket = class;
  251. {$IFDEF POSIX}
  252. TOptionList = TList<TSynaOption>;
  253. TSocketList = TList<TBlockSocket>;
  254. {$ELSE}
  255. TOptionList = TList;
  256. TSocketList = TList;
  257. {$ENDIF}
  258. {:@abstract(Basic IP object.)
  259. This is parent class for other class with protocol implementations. Do not
  260. use this class directly! Use @link(TICMPBlockSocket), @link(TRAWBlockSocket),
  261. @link(TTCPBlockSocket) or @link(TUDPBlockSocket) instead.}
  262. TBlockSocket = class(TObject)
  263. private
  264. FOnStatus: THookSocketStatus;
  265. FOnReadFilter: THookDataFilter;
  266. FOnCreateSocket: THookCreateSocket;
  267. FOnMonitor: THookMonitor;
  268. FOnHeartbeat: THookHeartbeat;
  269. FLocalSin: TVarSin;
  270. FRemoteSin: TVarSin;
  271. FTag: integer;
  272. FBuffer: AnsiString;
  273. FRaiseExcept: Boolean;
  274. FNonBlockMode: Boolean;
  275. FMaxLineLength: Integer;
  276. FMaxSendBandwidth: Integer;
  277. FNextSend: LongWord;
  278. FMaxRecvBandwidth: Integer;
  279. FNextRecv: LongWord;
  280. FConvertLineEnd: Boolean;
  281. FLastCR: Boolean;
  282. FLastLF: Boolean;
  283. FBinded: Boolean;
  284. FFamily: TSocketFamily;
  285. FFamilySave: TSocketFamily;
  286. FIP6used: Boolean;
  287. FPreferIP4: Boolean;
  288. FDelayedOptions: TOptionList;
  289. FInterPacketTimeout: Boolean;
  290. {$IFNDEF CIL}
  291. FFDSet: TFDSet;
  292. {$ENDIF}
  293. FRecvCounter: int64;
  294. FSendCounter: int64;
  295. FSendMaxChunk: Integer;
  296. FStopFlag: Boolean;
  297. FNonblockSendTimeout: Integer;
  298. FHeartbeatRate: integer;
  299. FConnectionTimeout: integer;
  300. {$IFNDEF ONCEWINSOCK}
  301. FWsaDataOnce: TWSADATA;
  302. {$ENDIF}
  303. function GetSizeRecvBuffer: Integer;
  304. procedure SetSizeRecvBuffer(Size: Integer);
  305. function GetSizeSendBuffer: Integer;
  306. procedure SetSizeSendBuffer(Size: Integer);
  307. procedure SetNonBlockMode(Value: Boolean);
  308. procedure SetTTL(TTL: integer);
  309. function GetTTL:integer;
  310. procedure SetFamily(Value: TSocketFamily); virtual;
  311. procedure SetSocket(Value: TSocket); virtual;
  312. function GetWsaData: TWSAData;
  313. function FamilyToAF(f: TSocketFamily): TAddrFamily;
  314. protected
  315. FSocket: TSocket;
  316. FLastError: Integer;
  317. FLastErrorDesc: string;
  318. FOwner: TObject;
  319. procedure SetDelayedOption(const Value: TSynaOption);
  320. procedure DelayedOption(const Value: TSynaOption);
  321. procedure ProcessDelayedOptions;
  322. procedure InternalCreateSocket(Sin: TVarSin);
  323. procedure SetSin(var Sin: TVarSin; IP, Port: string);
  324. function GetSinIP(Sin: TVarSin): string;
  325. function GetSinPort(Sin: TVarSin): Integer;
  326. procedure DoStatus(Reason: THookSocketReason; const Value: string);
  327. procedure DoReadFilter(Buffer: TMemory; var Len: Integer);
  328. procedure DoMonitor(Writing: Boolean; const Buffer: TMemory; Len: Integer);
  329. procedure DoCreateSocket;
  330. procedure DoHeartbeat;
  331. procedure LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord);
  332. procedure SetBandwidth(Value: Integer);
  333. function TestStopFlag: Boolean;
  334. procedure InternalSendStream(const Stream: TStream; WithSize, Indy: boolean); virtual;
  335. function InternalCanRead(Timeout: Integer): Boolean; virtual;
  336. function InternalCanWrite(Timeout: Integer): Boolean; virtual;
  337. public
  338. constructor Create;
  339. {:Create object and load all necessary socket library. What library is
  340. loaded is described by STUB parameter. If STUB is empty string, then is
  341. loaded default libraries.}
  342. constructor CreateAlternate(Stub: string);
  343. destructor Destroy; override;
  344. {:If @link(family) is not SF_Any, then create socket with type defined in
  345. @link(Family) property. If family is SF_Any, then do nothing! (socket is
  346. created automaticly when you know what type of socket you need to create.
  347. (i.e. inside @link(Connect) or @link(Bind) call.) When socket is created,
  348. then is aplyed all stored delayed socket options.}
  349. procedure CreateSocket;
  350. {:It create socket. Address resolving of Value tells what type of socket is
  351. created. If Value is resolved as IPv4 IP, then is created IPv4 socket. If
  352. value is resolved as IPv6 address, then is created IPv6 socket.}
  353. procedure CreateSocketByName(const Value: String);
  354. {:Destroy socket in use. This method is also automatically called from
  355. object destructor.}
  356. procedure CloseSocket; virtual;
  357. {:Abort any work on Socket and destroy them.}
  358. procedure AbortSocket; virtual;
  359. {:Connects socket to local IP address and PORT. IP address may be numeric or
  360. symbolic ('192.168.74.50', 'cosi.nekde.cz', 'ff08::1'). The same for PORT
  361. - it may be number or mnemonic port ('23', 'telnet').
  362. If port value is '0', system chooses itself and conects unused port in the
  363. range 1024 to 4096 (this depending by operating system!). Structure
  364. LocalSin is filled after calling this method.
  365. Note: If you call this on non-created socket, then socket is created
  366. automaticly.
  367. Warning: when you call : Bind('0.0.0.0','0'); then is nothing done! In this
  368. case is used implicit system bind instead.}
  369. procedure Bind(const IP, Port: string);
  370. {:Connects socket to remote IP address and PORT. The same rules as with
  371. @link(BIND) method are valid. The only exception is that PORT with 0 value
  372. will not be connected!
  373. Structures LocalSin and RemoteSin will be filled with valid values.
  374. When you call this on non-created socket, then socket is created
  375. automaticly. Type of created socket is by @link(Family) property. If is
  376. used SF_IP4, then is created socket for IPv4. If is used SF_IP6, then is
  377. created socket for IPv6. When you have family on SF_Any (default!), then
  378. type of created socket is determined by address resolving of destination
  379. address. (Not work properly on prilimitary winsock IPv6 support!)}
  380. procedure Connect(IP, Port: string); virtual;
  381. {:Sets socket to receive mode for new incoming connections. It is necessary
  382. to use @link(TBlockSocket.BIND) function call before this method to select
  383. receiving port!}
  384. procedure Listen; virtual;
  385. {:Waits until new incoming connection comes. After it comes a new socket is
  386. automatically created (socket handler is returned by this function as
  387. result).}
  388. function Accept: TSocket; virtual;
  389. {:Sends data of LENGTH from BUFFER address via connected socket. System
  390. automatically splits data to packets.}
  391. function SendBuffer(const Buffer: Tmemory; Length: Integer): Integer; virtual;
  392. {:One data BYTE is sent via connected socket.}
  393. procedure SendByte(Data: Byte); virtual;
  394. {:Send data string via connected socket. Any terminator is not added! If you
  395. need send true string with CR-LF termination, you must add CR-LF characters
  396. to sended string! Because any termination is not added automaticly, you can
  397. use this function for sending any binary data in binary string.}
  398. procedure SendString(Data: AnsiString); virtual;
  399. {:Send integer as four bytes to socket.}
  400. procedure SendInteger(Data: integer); virtual;
  401. {:Send data as one block to socket. Each block begin with 4 bytes with
  402. length of data in block. This 4 bytes is added automaticly by this
  403. function.}
  404. procedure SendBlock(const Data: AnsiString); virtual;
  405. {:Send data from stream to socket.}
  406. procedure SendStreamRaw(const Stream: TStream); virtual;
  407. {:Send content of stream to socket. It using @link(SendBlock) method}
  408. procedure SendStream(const Stream: TStream); virtual;
  409. {:Send content of stream to socket. It using @link(SendBlock) method and
  410. this is compatible with streams in Indy library.}
  411. procedure SendStreamIndy(const Stream: TStream); virtual;
  412. {:Note: This is low-level receive function. You must be sure if data is
  413. waiting for read before call this function for avoid deadlock!
  414. Waits until allocated buffer is filled by received data. Returns number of
  415. data received, which equals to LENGTH value under normal operation. If it
  416. is not equal the communication channel is possibly broken.
  417. On stream oriented sockets if is received 0 bytes, it mean 'socket is
  418. closed!"
  419. On datagram socket is readed first waiting datagram.}
  420. function RecvBuffer(Buffer: TMemory; Length: Integer): Integer; virtual;
  421. {:Note: This is high-level receive function. It using internal
  422. @link(LineBuffer) and you can combine this function freely with other
  423. high-level functions!
  424. Method waits until data is received. If no data is received within TIMEOUT
  425. (in milliseconds) period, @link(LastError) is set to WSAETIMEDOUT. Methods
  426. serves for reading any size of data (i.e. one megabyte...). This method is
  427. preffered for reading from stream sockets (like TCP).}
  428. function RecvBufferEx(Buffer: Tmemory; Len: Integer;
  429. Timeout: Integer): Integer; virtual;
  430. {:Similar to @link(RecvBufferEx), but readed data is stored in binary
  431. string, not in memory buffer.}
  432. function RecvBufferStr(Len: Integer; Timeout: Integer): AnsiString; virtual;
  433. {:Note: This is high-level receive function. It using internal
  434. @link(LineBuffer) and you can combine this function freely with other
  435. high-level functions.
  436. Waits until one data byte is received which is also returned as function
  437. result. If no data is received within TIMEOUT (in milliseconds)period,
  438. @link(LastError) is set to WSAETIMEDOUT and result have value 0.}
  439. function RecvByte(Timeout: Integer): Byte; virtual;
  440. {:Note: This is high-level receive function. It using internal
  441. @link(LineBuffer) and you can combine this function freely with other
  442. high-level functions.
  443. Waits until one four bytes are received and return it as one Ineger Value.
  444. If no data is received within TIMEOUT (in milliseconds)period,
  445. @link(LastError) is set to WSAETIMEDOUT and result have value 0.}
  446. function RecvInteger(Timeout: Integer): Integer; virtual;
  447. {:Note: This is high-level receive function. It using internal
  448. @link(LineBuffer) and you can combine this function freely with other
  449. high-level functions.
  450. Method waits until data string is received. This string is terminated by
  451. CR-LF characters. The resulting string is returned without this termination
  452. (CR-LF)! If @link(ConvertLineEnd) is used, then CR-LF sequence may not be
  453. exactly CR-LF. See @link(ConvertLineEnd) description. If no data is
  454. received within TIMEOUT (in milliseconds) period, @link(LastError) is set
  455. to WSAETIMEDOUT. You may also specify maximum length of reading data by
  456. @link(MaxLineLength) property.}
  457. function RecvString(Timeout: Integer): AnsiString; virtual;
  458. {:Note: This is high-level receive function. It using internal
  459. @link(LineBuffer) and you can combine this function freely with other
  460. high-level functions.
  461. Method waits until data string is received. This string is terminated by
  462. Terminator string. The resulting string is returned without this
  463. termination. If no data is received within TIMEOUT (in milliseconds)
  464. period, @link(LastError) is set to WSAETIMEDOUT. You may also specify
  465. maximum length of reading data by @link(MaxLineLength) property.}
  466. function RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString; virtual;
  467. {:Note: This is high-level receive function. It using internal
  468. @link(LineBuffer) and you can combine this function freely with other
  469. high-level functions.
  470. Method reads all data waiting for read. If no data is received within
  471. TIMEOUT (in milliseconds) period, @link(LastError) is set to WSAETIMEDOUT.
  472. Methods serves for reading unknown size of data. Because before call this
  473. function you don't know size of received data, returned data is stored in
  474. dynamic size binary string. This method is preffered for reading from
  475. stream sockets (like TCP). It is very goot for receiving datagrams too!
  476. (UDP protocol)}
  477. function RecvPacket(Timeout: Integer): AnsiString; virtual;
  478. {:Read one block of data from socket. Each block begin with 4 bytes with
  479. length of data in block. This function read first 4 bytes for get lenght,
  480. then it wait for reported count of bytes.}
  481. function RecvBlock(Timeout: Integer): AnsiString; virtual;
  482. {:Read all data from socket to stream until socket is closed (or any error
  483. occured.)}
  484. procedure RecvStreamRaw(const Stream: TStream; Timeout: Integer); virtual;
  485. {:Read requested count of bytes from socket to stream.}
  486. procedure RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: int64);
  487. {:Receive data to stream. It using @link(RecvBlock) method.}
  488. procedure RecvStream(const Stream: TStream; Timeout: Integer); virtual;
  489. {:Receive data to stream. This function is compatible with similar function
  490. in Indy library. It using @link(RecvBlock) method.}
  491. procedure RecvStreamIndy(const Stream: TStream; Timeout: Integer); virtual;
  492. {:Same as @link(RecvBuffer), but readed data stays in system input buffer.
  493. Warning: this function not respect data in @link(LineBuffer)! Is not
  494. recommended to use this function!}
  495. function PeekBuffer(Buffer: TMemory; Length: Integer): Integer; virtual;
  496. {:Same as @link(RecvByte), but readed data stays in input system buffer.
  497. Warning: this function not respect data in @link(LineBuffer)! Is not
  498. recommended to use this function!}
  499. function PeekByte(Timeout: Integer): Byte; virtual;
  500. {:On stream sockets it returns number of received bytes waiting for picking.
  501. 0 is returned when there is no such data. On datagram socket it returns
  502. length of the first waiting datagram. Returns 0 if no datagram is waiting.}
  503. function WaitingData: Integer; virtual;
  504. {:Same as @link(WaitingData), but if exists some of data in @link(Linebuffer),
  505. return their length instead.}
  506. function WaitingDataEx: Integer;
  507. {:Clear all waiting data for read from buffers.}
  508. procedure Purge;
  509. {:Sets linger. Enabled linger means that the system waits another LINGER
  510. (in milliseconds) time for delivery of sent data. This function is only for
  511. stream type of socket! (TCP)}
  512. procedure SetLinger(Enable: Boolean; Linger: Integer);
  513. {:Actualize values in @link(LocalSin).}
  514. procedure GetSinLocal;
  515. {:Actualize values in @link(RemoteSin).}
  516. procedure GetSinRemote;
  517. {:Actualize values in @link(LocalSin) and @link(RemoteSin).}
  518. procedure GetSins;
  519. {:Reset @link(LastError) and @link(LastErrorDesc) to non-error state.}
  520. procedure ResetLastError;
  521. {:If you "manually" call Socket API functions, forward their return code as
  522. parameter to this function, which evaluates it, eventually calls
  523. GetLastError and found error code returns and stores to @link(LastError).}
  524. function SockCheck(SockResult: Integer): Integer; virtual;
  525. {:If @link(LastError) contains some error code and @link(RaiseExcept)
  526. property is @true, raise adequate exception.}
  527. procedure ExceptCheck;
  528. {:Returns local computer name as numerical or symbolic value. It try get
  529. fully qualified domain name. Name is returned in the format acceptable by
  530. functions demanding IP as input parameter.}
  531. function LocalName: string;
  532. {:Try resolve name to all possible IP address. i.e. If you pass as name
  533. result of @link(LocalName) method, you get all IP addresses used by local
  534. system.}
  535. procedure ResolveNameToIP(Name: string; const IPList: TStrings);
  536. {:Try resolve name to primary IP address. i.e. If you pass as name result of
  537. @link(LocalName) method, you get primary IP addresses used by local system.}
  538. function ResolveName(Name: string): string;
  539. {:Try resolve IP to their primary domain name. If IP not have domain name,
  540. then is returned original IP.}
  541. function ResolveIPToName(IP: string): string;
  542. {:Try resolve symbolic port name to port number. (i.e. 'Echo' to 8)}
  543. function ResolvePort(Port: string): Word;
  544. {:Set information about remote side socket. It is good for seting remote
  545. side for sending UDP packet, etc.}
  546. procedure SetRemoteSin(IP, Port: string);
  547. {:Picks IP socket address from @link(LocalSin).}
  548. function GetLocalSinIP: string; virtual;
  549. {:Picks IP socket address from @link(RemoteSin).}
  550. function GetRemoteSinIP: string; virtual;
  551. {:Picks socket PORT number from @link(LocalSin).}
  552. function GetLocalSinPort: Integer; virtual;
  553. {:Picks socket PORT number from @link(RemoteSin).}
  554. function GetRemoteSinPort: Integer; virtual;
  555. {:Return @TRUE, if you can read any data from socket or is incoming
  556. connection on TCP based socket. Status is tested for time Timeout (in
  557. milliseconds). If value in Timeout is 0, status is only tested and
  558. continue. If value in Timeout is -1, run is breaked and waiting for read
  559. data maybe forever.
  560. This function is need only on special cases, when you need use
  561. @link(RecvBuffer) function directly! read functioms what have timeout as
  562. calling parameter, calling this function internally.}
  563. function CanRead(Timeout: Integer): Boolean; virtual;
  564. {:Same as @link(CanRead), but additionally return @TRUE if is some data in
  565. @link(LineBuffer).}
  566. function CanReadEx(Timeout: Integer): Boolean; virtual;
  567. {:Return @TRUE, if you can to socket write any data (not full sending
  568. buffer). Status is tested for time Timeout (in milliseconds). If value in
  569. Timeout is 0, status is only tested and continue. If value in Timeout is
  570. -1, run is breaked and waiting for write data maybe forever.
  571. This function is need only on special cases!}
  572. function CanWrite(Timeout: Integer): Boolean; virtual;
  573. {:Same as @link(SendBuffer), but send datagram to address from
  574. @link(RemoteSin). Usefull for sending reply to datagram received by
  575. function @link(RecvBufferFrom).}
  576. function SendBufferTo(const Buffer: TMemory; Length: Integer): Integer; virtual;
  577. {:Note: This is low-lever receive function. You must be sure if data is
  578. waiting for read before call this function for avoid deadlock!
  579. Receives first waiting datagram to allocated buffer. If there is no waiting
  580. one, then waits until one comes. Returns length of datagram stored in
  581. BUFFER. If length exceeds buffer datagram is truncated. After this
  582. @link(RemoteSin) structure contains information about sender of UDP packet.}
  583. function RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer; virtual;
  584. {$IFNDEF CIL}
  585. {:This function is for check for incoming data on set of sockets. Whitch
  586. sockets is checked is decribed by SocketList Tlist with TBlockSocket
  587. objects. TList may have maximal number of objects defined by FD_SETSIZE
  588. constant. Return @TRUE, if you can from some socket read any data or is
  589. incoming connection on TCP based socket. Status is tested for time Timeout
  590. (in milliseconds). If value in Timeout is 0, status is only tested and
  591. continue. If value in Timeout is -1, run is breaked and waiting for read
  592. data maybe forever. If is returned @TRUE, CanReadList TList is filled by all
  593. TBlockSocket objects what waiting for read.}
  594. function GroupCanRead(const SocketList: TSocketList; Timeout: Integer;
  595. const CanReadList: TSocketList): Boolean;
  596. {$ENDIF}
  597. {:By this method you may turn address reuse mode for local @link(bind). It
  598. is good specially for UDP protocol. Using this with TCP protocol is
  599. hazardous!}
  600. procedure EnableReuse(Value: Boolean);
  601. {:Try set timeout for all sending and receiving operations, if socket
  602. provider can do it. (It not supported by all socket providers!)}
  603. procedure SetTimeout(Timeout: Integer);
  604. {:Try set timeout for all sending operations, if socket provider can do it.
  605. (It not supported by all socket providers!)}
  606. procedure SetSendTimeout(Timeout: Integer);
  607. {:Try set timeout for all receiving operations, if socket provider can do
  608. it. (It not supported by all socket providers!)}
  609. procedure SetRecvTimeout(Timeout: Integer);
  610. {:Return value of socket type.}
  611. function GetSocketType: integer; Virtual;
  612. {:Return value of protocol type for socket creation.}
  613. function GetSocketProtocol: integer; Virtual;
  614. {:WSA structure with information about socket provider. On non-windows
  615. platforms this structure is simulated!}
  616. property WSAData: TWSADATA read GetWsaData;
  617. {:FDset structure prepared for usage with this socket.}
  618. property FDset: TFDSet read FFDset;
  619. {:Structure describing local socket side.}
  620. property LocalSin: TVarSin read FLocalSin write FLocalSin;
  621. {:Structure describing remote socket side.}
  622. property RemoteSin: TVarSin read FRemoteSin write FRemoteSin;
  623. {:Socket handler. Suitable for "manual" calls to socket API or manual
  624. connection of socket to a previously created socket (i.e by Accept method
  625. on TCP socket)}
  626. property Socket: TSocket read FSocket write SetSocket;
  627. {:Last socket operation error code. Error codes are described in socket
  628. documentation. Human readable error description is stored in
  629. @link(LastErrorDesc) property.}
  630. property LastError: Integer read FLastError;
  631. {:Human readable error description of @link(LastError) code.}
  632. property LastErrorDesc: string read FLastErrorDesc;
  633. {:Buffer used by all high-level receiving functions. This buffer is used for
  634. optimized reading of data from socket. In normal cases you not need access
  635. to this buffer directly!}
  636. property LineBuffer: AnsiString read FBuffer write FBuffer;
  637. {:Size of Winsock receive buffer. If it is not supported by socket provider,
  638. it return as size one kilobyte.}
  639. property SizeRecvBuffer: Integer read GetSizeRecvBuffer write SetSizeRecvBuffer;
  640. {:Size of Winsock send buffer. If it is not supported by socket provider, it
  641. return as size one kilobyte.}
  642. property SizeSendBuffer: Integer read GetSizeSendBuffer write SetSizeSendBuffer;
  643. {:If @True, turn class to non-blocking mode. Not all functions are working
  644. properly in this mode, you must know exactly what you are doing! However
  645. when you have big experience with non-blocking programming, then you can
  646. optimise your program by non-block mode!}
  647. property NonBlockMode: Boolean read FNonBlockMode Write SetNonBlockMode;
  648. {:Set Time-to-live value. (if system supporting it!)}
  649. property TTL: Integer read GetTTL Write SetTTL;
  650. {:If is @true, then class in in IPv6 mode.}
  651. property IP6used: Boolean read FIP6used;
  652. {:Return count of received bytes on this socket from begin of current
  653. connection.}
  654. property RecvCounter: int64 read FRecvCounter;
  655. {:Return count of sended bytes on this socket from begin of current
  656. connection.}
  657. property SendCounter: int64 read FSendCounter;
  658. published
  659. {:Return descriptive string for given error code. This is class function.
  660. You may call it without created object!}
  661. class function GetErrorDesc(ErrorCode: Integer): string;
  662. {:Return descriptive string for @link(LastError).}
  663. function GetErrorDescEx: string; virtual;
  664. {:this value is for free use.}
  665. property Tag: Integer read FTag write FTag;
  666. {:If @true, winsock errors raises exception. Otherwise is setted
  667. @link(LastError) value only and you must check it from your program! Default
  668. value is @false.}
  669. property RaiseExcept: Boolean read FRaiseExcept write FRaiseExcept;
  670. {:Define maximum length in bytes of @link(LineBuffer) for high-level
  671. receiving functions. If this functions try to read more data then this
  672. limit, error is returned! If value is 0 (default), no limitation is used.
  673. This is very good protection for stupid attacks to your server by sending
  674. lot of data without proper terminator... until all your memory is allocated
  675. by LineBuffer!
  676. Note: This maximum length is checked only in functions, what read unknown
  677. number of bytes! (like @link(RecvString) or @link(RecvTerminated))}
  678. property MaxLineLength: Integer read FMaxLineLength Write FMaxLineLength;
  679. {:Define maximal bandwidth for all sending operations in bytes per second.
  680. If value is 0 (default), bandwidth limitation is not used.}
  681. property MaxSendBandwidth: Integer read FMaxSendBandwidth Write FMaxSendBandwidth;
  682. {:Define maximal bandwidth for all receiving operations in bytes per second.
  683. If value is 0 (default), bandwidth limitation is not used.}
  684. property MaxRecvBandwidth: Integer read FMaxRecvBandwidth Write FMaxRecvBandwidth;
  685. {:Define maximal bandwidth for all sending and receiving operations in bytes
  686. per second. If value is 0 (default), bandwidth limitation is not used.}
  687. property MaxBandwidth: Integer Write SetBandwidth;
  688. {:Do a conversion of non-standard line terminators to CRLF. (Off by default)
  689. If @True, then terminators like sigle CR, single LF or LFCR are converted
  690. to CRLF internally. This have effect only in @link(RecvString) method!}
  691. property ConvertLineEnd: Boolean read FConvertLineEnd Write FConvertLineEnd;
  692. {:Specified Family of this socket. When you are using Windows preliminary
  693. support for IPv6, then I recommend to set this property!}
  694. property Family: TSocketFamily read FFamily Write SetFamily;
  695. {:When resolving of domain name return both IPv4 and IPv6 addresses, then
  696. specify if is used IPv4 (dafault - @true) or IPv6.}
  697. property PreferIP4: Boolean read FPreferIP4 Write FPreferIP4;
  698. {:By default (@true) is all timeouts used as timeout between two packets in
  699. reading operations. If you set this to @false, then Timeouts is for overall
  700. reading operation!}
  701. property InterPacketTimeout: Boolean read FInterPacketTimeout Write FInterPacketTimeout;
  702. {:All sended datas was splitted by this value.}
  703. property SendMaxChunk: Integer read FSendMaxChunk Write FSendMaxChunk;
  704. {:By setting this property to @true you can stop any communication. You can
  705. use this property for soft abort of communication.}
  706. property StopFlag: Boolean read FStopFlag Write FStopFlag;
  707. {:Timeout for data sending by non-blocking socket mode.}
  708. property NonblockSendTimeout: Integer read FNonblockSendTimeout Write FNonblockSendTimeout;
  709. {:Timeout for @link(Connect) call. Default value 0 means default system timeout.
  710. Non-zero value means timeout in millisecond.}
  711. property ConnectionTimeout: Integer read FConnectionTimeout write FConnectionTimeout;
  712. {:This event is called by various reasons. It is good for monitoring socket,
  713. create gauges for data transfers, etc.}
  714. property OnStatus: THookSocketStatus read FOnStatus write FOnStatus;
  715. {:this event is good for some internal thinks about filtering readed datas.
  716. It is used by telnet client by example.}
  717. property OnReadFilter: THookDataFilter read FOnReadFilter write FOnReadFilter;
  718. {:This event is called after real socket creation for setting special socket
  719. options, because you not know when socket is created. (it is depended on
  720. Ipv4, IPv6 or automatic mode)}
  721. property OnCreateSocket: THookCreateSocket read FOnCreateSocket write FOnCreateSocket;
  722. {:This event is good for monitoring content of readed or writed datas.}
  723. property OnMonitor: THookMonitor read FOnMonitor write FOnMonitor;
  724. {:This event is good for calling your code during long socket operations.
  725. (Example, for refresing UI if class in not called within the thread.)
  726. Rate of heartbeats can be modified by @link(HeartbeatRate) property.}
  727. property OnHeartbeat: THookHeartbeat read FOnHeartbeat write FOnHeartbeat;
  728. {:Specify typical rate of @link(OnHeartbeat) event and @link(StopFlag) testing.
  729. Default value 0 disabling heartbeats! Value is in milliseconds.
  730. Real rate can be higher or smaller then this value, because it depending
  731. on real socket operations too!
  732. Note: Each heartbeat slowing socket processing.}
  733. property HeartbeatRate: integer read FHeartbeatRate Write FHeartbeatRate;
  734. {:What class own this socket? Used by protocol implementation classes.}
  735. property Owner: TObject read FOwner Write FOwner;
  736. end;
  737. {:@abstract(Support for SOCKS4 and SOCKS5 proxy)
  738. Layer with definition all necessary properties and functions for
  739. implementation SOCKS proxy client. Do not use this class directly.}
  740. TSocksBlockSocket = class(TBlockSocket)
  741. protected
  742. FSocksIP: string;
  743. FSocksPort: string;
  744. FSocksTimeout: integer;
  745. FSocksUsername: string;
  746. FSocksPassword: string;
  747. FUsingSocks: Boolean;
  748. FSocksResolver: Boolean;
  749. FSocksLastError: integer;
  750. FSocksResponseIP: string;
  751. FSocksResponsePort: string;
  752. FSocksLocalIP: string;
  753. FSocksLocalPort: string;
  754. FSocksRemoteIP: string;
  755. FSocksRemotePort: string;
  756. FBypassFlag: Boolean;
  757. FSocksType: TSocksType;
  758. function SocksCode(IP, Port: string): Ansistring;
  759. function SocksDecode(Value: Ansistring): integer;
  760. public
  761. constructor Create;
  762. {:Open connection to SOCKS proxy and if @link(SocksUsername) is set, do
  763. authorisation to proxy. This is needed only in special cases! (it is called
  764. internally!)}
  765. function SocksOpen: Boolean;
  766. {:Send specified request to SOCKS proxy. This is needed only in special
  767. cases! (it is called internally!)}
  768. function SocksRequest(Cmd: Byte; const IP, Port: string): Boolean;
  769. {:Receive response to previosly sended request. This is needed only in
  770. special cases! (it is called internally!)}
  771. function SocksResponse: Boolean;
  772. {:Is @True when class is using SOCKS proxy.}
  773. property UsingSocks: Boolean read FUsingSocks;
  774. {:If SOCKS proxy failed, here is error code returned from SOCKS proxy.}
  775. property SocksLastError: integer read FSocksLastError;
  776. published
  777. {:Address of SOCKS server. If value is empty string, SOCKS support is
  778. disabled. Assingning any value to this property enable SOCKS mode.
  779. Warning: You cannot combine this mode with HTTP-tunneling mode!}
  780. property SocksIP: string read FSocksIP write FSocksIP;
  781. {:Port of SOCKS server. Default value is '1080'.}
  782. property SocksPort: string read FSocksPort write FSocksPort;
  783. {:If you need authorisation on SOCKS server, set username here.}
  784. property SocksUsername: string read FSocksUsername write FSocksUsername;
  785. {:If you need authorisation on SOCKS server, set password here.}
  786. property SocksPassword: string read FSocksPassword write FSocksPassword;
  787. {:Specify timeout for communicatin with SOCKS server. Default is one minute.}
  788. property SocksTimeout: integer read FSocksTimeout write FSocksTimeout;
  789. {:If @True, all symbolic names of target hosts is not translated to IP's
  790. locally, but resolving is by SOCKS proxy. Default is @True.}
  791. property SocksResolver: Boolean read FSocksResolver write FSocksResolver;
  792. {:Specify SOCKS type. By default is used SOCKS5, but you can use SOCKS4 too.
  793. When you select SOCKS4, then if @link(SOCKSResolver) is enabled, then is
  794. used SOCKS4a. Othervise is used pure SOCKS4.}
  795. property SocksType: TSocksType read FSocksType write FSocksType;
  796. end;
  797. {:@abstract(Implementation of TCP socket.)
  798. Supported features: IPv4, IPv6, SSL/TLS or SSH (depending on used plugin),
  799. SOCKS5 proxy (outgoing connections and limited incomming), SOCKS4/4a proxy
  800. (outgoing connections and limited incomming), TCP through HTTP proxy tunnel.}
  801. TTCPBlockSocket = class(TSocksBlockSocket)
  802. protected
  803. FOnAfterConnect: THookAfterConnect;
  804. FSSL: TCustomSSL;
  805. FHTTPTunnelIP: string;
  806. FHTTPTunnelPort: string;
  807. FHTTPTunnel: Boolean;
  808. FHTTPTunnelRemoteIP: string;
  809. FHTTPTunnelRemotePort: string;
  810. FHTTPTunnelUser: string;
  811. FHTTPTunnelPass: string;
  812. FHTTPTunnelTimeout: integer;
  813. procedure SocksDoConnect(IP, Port: string);
  814. procedure HTTPTunnelDoConnect(IP, Port: string);
  815. procedure DoAfterConnect;
  816. public
  817. {:Create TCP socket class with default plugin for SSL/TSL/SSH implementation
  818. (see @link(SSLImplementation))}
  819. constructor Create;
  820. {:Create TCP socket class with desired plugin for SSL/TSL/SSH implementation}
  821. constructor CreateWithSSL(SSLPlugin: TSSLClass);
  822. destructor Destroy; override;
  823. {:See @link(TBlockSocket.CloseSocket)}
  824. procedure CloseSocket; override;
  825. {:See @link(TBlockSocket.WaitingData)}
  826. function WaitingData: Integer; override;
  827. {:Sets socket to receive mode for new incoming connections. It is necessary
  828. to use @link(TBlockSocket.BIND) function call before this method to select
  829. receiving port!
  830. If you use SOCKS, activate incoming TCP connection by this proxy. (By BIND
  831. method of SOCKS.)}
  832. procedure Listen; override;
  833. {:Waits until new incoming connection comes. After it comes a new socket is
  834. automatically created (socket handler is returned by this function as
  835. result).
  836. If you use SOCKS, new socket is not created! In this case is used same
  837. socket as socket for listening! So, you can accept only one connection in
  838. SOCKS mode.}
  839. function Accept: TSocket; override;
  840. {:Connects socket to remote IP address and PORT. The same rules as with
  841. @link(TBlockSocket.BIND) method are valid. The only exception is that PORT
  842. with 0 value will not be connected. After call to this method
  843. a communication channel between local and remote socket is created. Local
  844. socket is assigned automatically if not controlled by previous call to
  845. @link(TBlockSocket.BIND) method. Structures @link(TBlockSocket.LocalSin)
  846. and @link(TBlockSocket.RemoteSin) will be filled with valid values.
  847. If you use SOCKS, activate outgoing TCP connection by SOCKS proxy specified
  848. in @link(TSocksBlockSocket.SocksIP). (By CONNECT method of SOCKS.)
  849. If you use HTTP-tunnel mode, activate outgoing TCP connection by HTTP
  850. tunnel specified in @link(HTTPTunnelIP). (By CONNECT method of HTTP
  851. protocol.)
  852. Note: If you call this on non-created socket, then socket is created
  853. automaticly.}
  854. procedure Connect(IP, Port: string); override;
  855. {:If you need upgrade existing TCP connection to SSL/TLS (or SSH2, if plugin
  856. allows it) mode, then call this method. This method switch this class to
  857. SSL mode and do SSL/TSL handshake.}
  858. procedure SSLDoConnect;
  859. {:By this method you can downgrade existing SSL/TLS connection to normal TCP
  860. connection.}
  861. procedure SSLDoShutdown;
  862. {:If you need use this component as SSL/TLS TCP server, then after accepting
  863. of inbound connection you need start SSL/TLS session by this method. Before
  864. call this function, you must have assigned all neeeded certificates and
  865. keys!}
  866. function SSLAcceptConnection: Boolean;
  867. {:See @link(TBlockSocket.GetLocalSinIP)}
  868. function GetLocalSinIP: string; override;
  869. {:See @link(TBlockSocket.GetRemoteSinIP)}
  870. function GetRemoteSinIP: string; override;
  871. {:See @link(TBlockSocket.GetLocalSinPort)}
  872. function GetLocalSinPort: Integer; override;
  873. {:See @link(TBlockSocket.GetRemoteSinPort)}
  874. function GetRemoteSinPort: Integer; override;
  875. {:See @link(TBlockSocket.SendBuffer)}
  876. function SendBuffer(const Buffer: TMemory; Length: Integer): Integer; override;
  877. {:See @link(TBlockSocket.RecvBuffer)}
  878. function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; override;
  879. {:Return value of socket type. For TCP return SOCK_STREAM.}
  880. function GetSocketType: integer; override;
  881. {:Return value of protocol type for socket creation. For TCP return
  882. IPPROTO_TCP.}
  883. function GetSocketProtocol: integer; override;
  884. {:Class implementing SSL/TLS support. It is allways some descendant
  885. of @link(TCustomSSL) class. When programmer not select some SSL plugin
  886. class, then is used @link(TSSLNone)}
  887. property SSL: TCustomSSL read FSSL;
  888. {:@True if is used HTTP tunnel mode.}
  889. property HTTPTunnel: Boolean read FHTTPTunnel;
  890. published
  891. {:Return descriptive string for @link(LastError). On case of error
  892. in SSL/TLS subsystem, it returns right error description.}
  893. function GetErrorDescEx: string; override;
  894. {:Specify IP address of HTTP proxy. Assingning non-empty value to this
  895. property enable HTTP-tunnel mode. This mode is for tunnelling any outgoing
  896. TCP connection through HTTP proxy server. (If policy on HTTP proxy server
  897. allow this!) Warning: You cannot combine this mode with SOCK5 mode!}
  898. property HTTPTunnelIP: string read FHTTPTunnelIP Write FHTTPTunnelIP;
  899. {:Specify port of HTTP proxy for HTTP-tunneling.}
  900. property HTTPTunnelPort: string read FHTTPTunnelPort Write FHTTPTunnelPort;
  901. {:Specify authorisation username for access to HTTP proxy in HTTP-tunnel
  902. mode. If you not need authorisation, then let this property empty.}
  903. property HTTPTunnelUser: string read FHTTPTunnelUser Write FHTTPTunnelUser;
  904. {:Specify authorisation password for access to HTTP proxy in HTTP-tunnel
  905. mode.}
  906. property HTTPTunnelPass: string read FHTTPTunnelPass Write FHTTPTunnelPass;
  907. {:Specify timeout for communication with HTTP proxy in HTTPtunnel mode.}
  908. property HTTPTunnelTimeout: integer read FHTTPTunnelTimeout Write FHTTPTunnelTimeout;
  909. {:This event is called after sucessful TCP socket connection.}
  910. property OnAfterConnect: THookAfterConnect read FOnAfterConnect write FOnAfterConnect;
  911. end;
  912. {:@abstract(Datagram based communication)
  913. This class implementing datagram based communication instead default stream
  914. based communication style.}
  915. TDgramBlockSocket = class(TSocksBlockSocket)
  916. public
  917. {:Fill @link(TBlockSocket.RemoteSin) structure. This address is used for
  918. sending data.}
  919. procedure Connect(IP, Port: string); override;
  920. {:Silently redirected to @link(TBlockSocket.SendBufferTo).}
  921. function SendBuffer(const Buffer: TMemory; Length: Integer): Integer; override;
  922. {:Silently redirected to @link(TBlockSocket.RecvBufferFrom).}
  923. function RecvBuffer(Buffer: TMemory; Length: Integer): Integer; override;
  924. end;
  925. {:@abstract(Implementation of UDP socket.)
  926. NOTE: in this class is all receiving redirected to RecvBufferFrom. You can
  927. use for reading any receive function. Preffered is RecvPacket! Similary all
  928. sending is redirected to SendbufferTo. You can use for sending UDP packet any
  929. sending function, like SendString.
  930. Supported features: IPv4, IPv6, unicasts, broadcasts, multicasts, SOCKS5
  931. proxy (only unicasts! Outgoing and incomming.)}
  932. TUDPBlockSocket = class(TDgramBlockSocket)
  933. protected
  934. FSocksControlSock: TTCPBlockSocket;
  935. function UdpAssociation: Boolean;
  936. procedure SetMulticastTTL(TTL: integer);
  937. function GetMulticastTTL:integer;
  938. public
  939. destructor Destroy; override;
  940. {:Enable or disable sending of broadcasts. If seting OK, result is @true.
  941. This method is not supported in SOCKS5 mode! IPv6 does not support
  942. broadcasts! In this case you must use Multicasts instead.}
  943. procedure EnableBroadcast(Value: Boolean);
  944. {:See @link(TBlockSocket.SendBufferTo)}
  945. function SendBufferTo(const Buffer: TMemory; Length: Integer): Integer; override;
  946. {:See @link(TBlockSocket.RecvBufferFrom)}
  947. function RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer; override;
  948. {$IFNDEF CIL}
  949. {:Add this socket to given multicast group. You cannot use Multicasts in
  950. SOCKS mode!}
  951. procedure AddMulticast(MCastIP:string);
  952. {:Remove this socket from given multicast group.}
  953. procedure DropMulticast(MCastIP:string);
  954. {$ENDIF}
  955. {:All sended multicast datagrams is loopbacked to your interface too. (you
  956. can read your sended datas.) You can disable this feature by this function.
  957. This function not working on some Windows systems!}
  958. procedure EnableMulticastLoop(Value: Boolean);
  959. {:Return value of socket type. For UDP return SOCK_DGRAM.}
  960. function GetSocketType: integer; override;
  961. {:Return value of protocol type for socket creation. For UDP return
  962. IPPROTO_UDP.}
  963. function GetSocketProtocol: integer; override;
  964. {:Set Time-to-live value for multicasts packets. It define number of routers
  965. for transfer of datas. If you set this to 1 (dafault system value), then
  966. multicasts packet goes only to you local network. If you need transport
  967. multicast packet to worldwide, then increase this value, but be carefull,
  968. lot of routers on internet does not transport multicasts packets!}
  969. property MulticastTTL: Integer read GetMulticastTTL Write SetMulticastTTL;
  970. end;
  971. {:@abstract(Implementation of RAW ICMP socket.)
  972. For this object you must have rights for creating RAW sockets!}
  973. TICMPBlockSocket = class(TDgramBlockSocket)
  974. public
  975. {:Return value of socket type. For RAW and ICMP return SOCK_RAW.}
  976. function GetSocketType: integer; override;
  977. {:Return value of protocol type for socket creation. For ICMP returns
  978. IPPROTO_ICMP or IPPROTO_ICMPV6}
  979. function GetSocketProtocol: integer; override;
  980. end;
  981. {:@abstract(Implementation of RAW socket.)
  982. For this object you must have rights for creating RAW sockets!}
  983. TRAWBlockSocket = class(TBlockSocket)
  984. public
  985. {:Return value of socket type. For RAW and ICMP return SOCK_RAW.}
  986. function GetSocketType: integer; override;
  987. {:Return value of protocol type for socket creation. For RAW returns
  988. IPPROTO_RAW.}
  989. function GetSocketProtocol: integer; override;
  990. end;
  991. {:@abstract(Implementation of PGM-message socket.)
  992. Not all systems supports this protocol!}
  993. TPGMMessageBlockSocket = class(TBlockSocket)
  994. public
  995. {:Return value of socket type. For PGM-message return SOCK_RDM.}
  996. function GetSocketType: integer; override;
  997. {:Return value of protocol type for socket creation. For PGM-message returns
  998. IPPROTO_RM.}
  999. function GetSocketProtocol: integer; override;
  1000. end;
  1001. {:@abstract(Implementation of PGM-stream socket.)
  1002. Not all systems supports this protocol!}
  1003. TPGMStreamBlockSocket = class(TBlockSocket)
  1004. public
  1005. {:Return value of socket type. For PGM-stream return SOCK_STREAM.}
  1006. function GetSocketType: integer; override;
  1007. {:Return value of protocol type for socket creation. For PGM-stream returns
  1008. IPPROTO_RM.}
  1009. function GetSocketProtocol: integer; override;
  1010. end;
  1011. {:@abstract(Parent class for all SSL plugins.)
  1012. This is abstract class defining interface for other SSL plugins.
  1013. Instance of this class will be created for each @link(TTCPBlockSocket).
  1014. Warning: not all methods and propertis can work in all existing SSL plugins!
  1015. Please, read documentation of used SSL plugin.}
  1016. TCustomSSL = class(TObject)
  1017. private
  1018. protected
  1019. FSessionOld: Pointer;
  1020. FSessionNew: Pointer;
  1021. FOnVerifyCert: THookVerifyCert;
  1022. FSocket: TTCPBlockSocket;
  1023. FSSLEnabled: Boolean;
  1024. FLastError: integer;
  1025. FLastErrorDesc: string;
  1026. FSSLType: TSSLType;
  1027. FKeyPassword: string;
  1028. FCiphers: string;
  1029. FCertificateFile: string;
  1030. FPrivateKeyFile: string;
  1031. FCertificate: Ansistring;
  1032. FPrivateKey: Ansistring;
  1033. FPFX: Ansistring;
  1034. FPFXfile: string;
  1035. FCertCA: Ansistring;
  1036. FCertCAFile: string;
  1037. FTrustCertificate: Ansistring;
  1038. FTrustCertificateFile: string;
  1039. FVerifyCert: Boolean;
  1040. FUsername: string;
  1041. FPassword: string;
  1042. FSSHChannelType: string;
  1043. FSSHChannelArg1: string;
  1044. FSSHChannelArg2: string;
  1045. FCertComplianceLevel: integer;
  1046. FSNIHost: string;
  1047. procedure ReturnError;
  1048. procedure SetCertCAFile(const Value: string); virtual;
  1049. function DoVerifyCert:boolean;
  1050. function CreateSelfSignedCert(Host: string): Boolean; virtual;
  1051. public
  1052. {: Create plugin class. it is called internally from @link(TTCPBlockSocket)}
  1053. constructor Create(const Value: TTCPBlockSocket); virtual;
  1054. {: Assign settings (certificates and configuration) from another SSL plugin
  1055. class.}
  1056. procedure Assign(const Value: TCustomSSL); virtual;
  1057. {: return description of used plugin. It usually return name and version
  1058. of used SSL library.}
  1059. function LibVersion: String; virtual;
  1060. {: return name of used plugin.}
  1061. function LibName: String; virtual;
  1062. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1063. Here is needed code for start SSL connection.}
  1064. function Connect: boolean; virtual;
  1065. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1066. Here is needed code for acept new SSL connection.}
  1067. function Accept: boolean; virtual;
  1068. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1069. Here is needed code for hard shutdown of SSL connection. (for example,
  1070. before socket is closed)}
  1071. function Shutdown: boolean; virtual;
  1072. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1073. Here is needed code for soft shutdown of SSL connection. (for example,
  1074. when you need to continue with unprotected connection.)}
  1075. function BiShutdown: boolean; virtual;
  1076. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1077. Here is needed code for sending some datas by SSL connection.}
  1078. function SendBuffer(Buffer: TMemory; Len: Integer): Integer; virtual;
  1079. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1080. Here is needed code for receiving some datas by SSL connection.}
  1081. function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; virtual;
  1082. {: Do not call this directly. It is used internally by @link(TTCPBlockSocket)!
  1083. Here is needed code for getting count of datas what waiting for read.
  1084. If SSL plugin not allows this, then it should return 0.}
  1085. function WaitingData: Integer; virtual;
  1086. {:Return string with identificator of SSL/TLS version of existing
  1087. connection.}
  1088. function GetSSLVersion: string; virtual;
  1089. {:Return subject of remote SSL peer.}
  1090. function GetPeerSubject: string; virtual;
  1091. {:Return Serial number if remote X509 certificate.}
  1092. function GetPeerSerialNo: integer; virtual;
  1093. {:Return issuer certificate of remote SSL peer.}
  1094. function GetPeerIssuer: string; virtual;
  1095. {:Return peer name from remote side certificate. This is good for verify,
  1096. if certificate is generated for remote side IP name.}
  1097. function GetPeerName: string; virtual;
  1098. {:Returns has of peer name from remote side certificate. This is good
  1099. for fast remote side authentication.}
  1100. function GetPeerNameHash: cardinal; virtual;
  1101. {:Return fingerprint of remote SSL peer. (As binary nonprintable string!)}
  1102. function GetPeerFingerprint: AnsiString; virtual;
  1103. {:Return all detailed information about certificate from remote side of
  1104. SSL/TLS connection. Result string can be multilined! Each plugin can return
  1105. this informations in different format!}
  1106. function GetCertInfo: string; virtual;
  1107. {:Return currently used Cipher.}
  1108. function GetCipherName: string; virtual;
  1109. {:Return currently used number of bits in current Cipher algorythm.}
  1110. function GetCipherBits: integer; virtual;
  1111. {:Return number of bits in current Cipher algorythm.}
  1112. function GetCipherAlgBits: integer; virtual;
  1113. {:Return result value of verify remote side certificate. Look to OpenSSL
  1114. documentation for possible values. For example 0 is successfuly verified
  1115. certificate, or 18 is self-signed certificate.}
  1116. function GetVerifyCert: integer; virtual;
  1117. {: Resurn @true if SSL mode is enabled on existing cvonnection.}
  1118. property SSLEnabled: Boolean read FSSLEnabled;
  1119. {:Return error code of last SSL operation. 0 is OK.}
  1120. property LastError: integer read FLastError;
  1121. {:Return error description of last SSL operation.}
  1122. property LastErrorDesc: string read FLastErrorDesc;
  1123. {:Used for session resumption }
  1124. property Session: Pointer read FSessionNew write FSessionOld;
  1125. published
  1126. {:Here you can specify requested SSL/TLS mode. Default is autodetection, but
  1127. on some servers autodetection not working properly. In this case you must
  1128. specify requested SSL/TLS mode by your hand!}
  1129. property SSLType: TSSLType read FSSLType write FSSLType;
  1130. {:Password for decrypting of encoded certificate or key.}
  1131. property KeyPassword: string read FKeyPassword write FKeyPassword;
  1132. {:Username for possible credentials.}
  1133. property Username: string read FUsername write FUsername;
  1134. {:password for possible credentials.}
  1135. property Password: string read FPassword write FPassword;
  1136. {:By this property you can modify default set of SSL/TLS ciphers.}
  1137. property Ciphers: string read FCiphers write FCiphers;
  1138. {:Used for loading certificate from disk file. See to plugin documentation
  1139. if this method is supported and how!}
  1140. property CertificateFile: string read FCertificateFile write FCertificateFile;
  1141. {:Used for loading private key from disk file. See to plugin documentation
  1142. if this method is supported and how!}
  1143. property PrivateKeyFile: string read FPrivateKeyFile write FPrivateKeyFile;
  1144. {:Used for loading certificate from binary string. See to plugin documentation
  1145. if this method is supported and how!}
  1146. property Certificate: Ansistring read FCertificate write FCertificate;
  1147. {:Used for loading private key from binary string. See to plugin documentation
  1148. if this method is supported and how!}
  1149. property PrivateKey: Ansistring read FPrivateKey write FPrivateKey;
  1150. {:Used for loading PFX from binary string. See to plugin documentation
  1151. if this method is supported and how!}
  1152. property PFX: Ansistring read FPFX write FPFX;
  1153. {:Used for loading PFX from disk file. See to plugin documentation
  1154. if this method is supported and how!}
  1155. property PFXfile: string read FPFXfile write FPFXfile;
  1156. {:Used for loading trusted certificates from disk file. See to plugin documentation
  1157. if this method is supported and how!}
  1158. property TrustCertificateFile: string read FTrustCertificateFile write FTrustCertificateFile;
  1159. {:Used for loading trusted certificates from binary string. See to plugin documentation
  1160. if this method is supported and how!}
  1161. property TrustCertificate: Ansistring read FTrustCertificate write FTrustCertificate;
  1162. {:Used for loading CA certificates from binary string. See to plugin documentation
  1163. if this method is supported and how!}
  1164. property CertCA: Ansistring read FCertCA write FCertCA;
  1165. {:Used for loading CA certificates from disk file. See to plugin documentation
  1166. if this method is supported and how!}
  1167. property CertCAFile: string read FCertCAFile write SetCertCAFile;
  1168. {:If @true, then is verified client certificate. (it is good for writing
  1169. SSL/TLS servers.) When you are not server, but you are client, then if this
  1170. property is @true, verify servers certificate.}
  1171. property VerifyCert: Boolean read FVerifyCert write FVerifyCert;
  1172. {:channel type for possible SSH connections}
  1173. property SSHChannelType: string read FSSHChannelType write FSSHChannelType;
  1174. {:First argument of channel type for possible SSH connections}
  1175. property SSHChannelArg1: string read FSSHChannelArg1 write FSSHChannelArg1;
  1176. {:Second argument of channel type for possible SSH connections}
  1177. property SSHChannelArg2: string read FSSHChannelArg2 write FSSHChannelArg2;
  1178. {: Level of standards compliance level
  1179. (CryptLib: values in cryptlib.pas, -1: use default value ) }
  1180. property CertComplianceLevel:integer read FCertComplianceLevel write FCertComplianceLevel;
  1181. {:This event is called when verifying the server certificate immediatally after
  1182. a successfull verification in the ssl library.}
  1183. property OnVerifyCert: THookVerifyCert read FOnVerifyCert write FOnVerifyCert;
  1184. {: Server Name Identification. Host name to send to server. If empty the host name
  1185. found in URL will be used, which should be the normal use (http Header Host = SNI Host).
  1186. The value is cleared after the connection is established.
  1187. (SNI support requires OpenSSL 0.9.8k or later. Cryptlib not supported, yet ) }
  1188. property SNIHost:string read FSNIHost write FSNIHost;
  1189. end;
  1190. {:@abstract(Default SSL plugin with no SSL support.)
  1191. Dummy SSL plugin implementation for applications without SSL/TLS support.}
  1192. TSSLNone = class (TCustomSSL)
  1193. public
  1194. {:See @inherited}
  1195. function LibVersion: String; override;
  1196. {:See @inherited}
  1197. function LibName: String; override;
  1198. end;
  1199. {:@abstract(Record with definition of IP packet header.)
  1200. For reading data from ICMP or RAW sockets.}
  1201. TIPHeader = record
  1202. VerLen: Byte;
  1203. TOS: Byte;
  1204. TotalLen: Word;
  1205. Identifer: Word;
  1206. FragOffsets: Word;
  1207. TTL: Byte;
  1208. Protocol: Byte;
  1209. CheckSum: Word;
  1210. SourceIp: LongWord;
  1211. DestIp: LongWord;
  1212. Options: LongWord;
  1213. end;
  1214. {:@abstract(Parent class of application protocol implementations.)
  1215. By this class is defined common properties.}
  1216. TSynaClient = Class(TObject)
  1217. protected
  1218. FTargetHost: string;
  1219. FTargetPort: string;
  1220. FIPInterface: string;
  1221. FTimeout: integer;
  1222. FUserName: string;
  1223. FPassword: string;
  1224. public
  1225. constructor Create;
  1226. published
  1227. {:Specify terget server IP (or symbolic name). Default is 'localhost'.}
  1228. property TargetHost: string read FTargetHost Write FTargetHost;
  1229. {:Specify terget server port (or symbolic name).}
  1230. property TargetPort: string read FTargetPort Write FTargetPort;
  1231. {:Defined local socket address. (outgoing IP address). By default is used
  1232. '0.0.0.0' as wildcard for default IP.}
  1233. property IPInterface: string read FIPInterface Write FIPInterface;
  1234. {:Specify default timeout for socket operations.}
  1235. property Timeout: integer read FTimeout Write FTimeout;
  1236. {:If protocol need user authorization, then fill here username.}
  1237. property UserName: string read FUserName Write FUserName;
  1238. {:If protocol need user authorization, then fill here password.}
  1239. property Password: string read FPassword Write FPassword;
  1240. end;
  1241. var
  1242. {:Selected SSL plugin. Default is @link(TSSLNone).
  1243. Do not change this value directly!!!
  1244. Just add your plugin unit to your project uses instead. Each plugin unit have
  1245. initialization code what modify this variable.}
  1246. SSLImplementation: TSSLClass = TSSLNone;
  1247. implementation
  1248. {$IFDEF ONCEWINSOCK}
  1249. var
  1250. WsaDataOnce: TWSADATA;
  1251. e: ESynapseError;
  1252. {$ENDIF}
  1253. constructor TBlockSocket.Create;
  1254. begin
  1255. CreateAlternate('');
  1256. end;
  1257. constructor TBlockSocket.CreateAlternate(Stub: string);
  1258. {$IFNDEF ONCEWINSOCK}
  1259. var
  1260. e: ESynapseError;
  1261. {$ENDIF}
  1262. begin
  1263. inherited Create;
  1264. FDelayedOptions := TOptionList.Create;
  1265. FRaiseExcept := False;
  1266. {$IFDEF RAISEEXCEPT}
  1267. FRaiseExcept := True;
  1268. {$ENDIF}
  1269. FSocket := INVALID_SOCKET;
  1270. FBuffer := '';
  1271. FLastCR := False;
  1272. FLastLF := False;
  1273. FBinded := False;
  1274. FNonBlockMode := False;
  1275. FMaxLineLength := 0;
  1276. FMaxSendBandwidth := 0;
  1277. FNextSend := 0;
  1278. FMaxRecvBandwidth := 0;
  1279. FNextRecv := 0;
  1280. FConvertLineEnd := False;
  1281. FFamily := SF_Any;
  1282. FFamilySave := SF_Any;
  1283. FIP6used := False;
  1284. FPreferIP4 := True;
  1285. FInterPacketTimeout := True;
  1286. FRecvCounter := 0;
  1287. FSendCounter := 0;
  1288. FSendMaxChunk := c64k;
  1289. FStopFlag := False;
  1290. FNonblockSendTimeout := 15000;
  1291. FHeartbeatRate := 0;
  1292. FConnectionTimeout := 0;
  1293. FOwner := nil;
  1294. {$IFNDEF ONCEWINSOCK}
  1295. if Stub = '' then
  1296. Stub := DLLStackName;
  1297. if not InitSocketInterface(Stub) then
  1298. begin
  1299. e := ESynapseError.Create('Error loading Socket interface (' + Stub + ')!');
  1300. e.ErrorCode := 0;
  1301. e.ErrorMessage := 'Error loading Socket interface (' + Stub + ')!';
  1302. raise e;
  1303. end;
  1304. SockCheck(synsock.WSAStartup(WinsockLevel, FWsaDataOnce));
  1305. ExceptCheck;
  1306. {$ENDIF}
  1307. end;
  1308. destructor TBlockSocket.Destroy;
  1309. var
  1310. n: integer;
  1311. p: TSynaOption;
  1312. begin
  1313. CloseSocket;
  1314. {$IFNDEF ONCEWINSOCK}
  1315. synsock.WSACleanup;
  1316. DestroySocketInterface;
  1317. {$ENDIF}
  1318. for n := FDelayedOptions.Count - 1 downto 0 do
  1319. begin
  1320. p := TSynaOption(FDelayedOptions[n]);
  1321. p.Free;
  1322. end;
  1323. FDelayedOptions.Free;
  1324. inherited Destroy;
  1325. end;
  1326. function TBlockSocket.FamilyToAF(f: TSocketFamily): TAddrFamily;
  1327. begin
  1328. case f of
  1329. SF_ip4:
  1330. Result := AF_INET;
  1331. SF_ip6:
  1332. Result := AF_INET6;
  1333. else
  1334. Result := AF_UNSPEC;
  1335. end;
  1336. end;
  1337. procedure TBlockSocket.SetDelayedOption(const Value: TSynaOption);
  1338. var
  1339. li: TLinger;
  1340. x: integer;
  1341. buf: TMemory;
  1342. {$IFNDEF MSWINDOWS}
  1343. timeval: TTimeval;
  1344. {$ENDIF}
  1345. begin
  1346. case value.Option of
  1347. SOT_Linger:
  1348. begin
  1349. {$IFDEF CIL}
  1350. li := TLinger.Create(Value.Enabled, Value.Value div 1000);
  1351. synsock.SetSockOptObj(FSocket, integer(SOL_SOCKET), integer(SO_LINGER), li);
  1352. {$ELSE}
  1353. li.l_onoff := Ord(Value.Enabled);
  1354. li.l_linger := Value.Value div 1000;
  1355. buf := @li;
  1356. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_LINGER), buf, SizeOf(li));
  1357. {$ENDIF}
  1358. end;
  1359. SOT_RecvBuff:
  1360. begin
  1361. {$IFDEF CIL}
  1362. buf := System.BitConverter.GetBytes(value.Value);
  1363. {$ELSE}
  1364. buf := @Value.Value;
  1365. {$ENDIF}
  1366. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVBUF),
  1367. buf, SizeOf(Value.Value));
  1368. end;
  1369. SOT_SendBuff:
  1370. begin
  1371. {$IFDEF CIL}
  1372. buf := System.BitConverter.GetBytes(value.Value);
  1373. {$ELSE}
  1374. buf := @Value.Value;
  1375. {$ENDIF}
  1376. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDBUF),
  1377. buf, SizeOf(Value.Value));
  1378. end;
  1379. SOT_NonBlock:
  1380. begin
  1381. FNonBlockMode := Value.Enabled;
  1382. x := Ord(FNonBlockMode);
  1383. synsock.IoctlSocket(FSocket, FIONBIO, x);
  1384. end;
  1385. SOT_RecvTimeout:
  1386. begin
  1387. {$IFDEF CIL}
  1388. buf := System.BitConverter.GetBytes(value.Value);
  1389. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
  1390. buf, SizeOf(Value.Value));
  1391. {$ELSE}
  1392. {$IFDEF MSWINDOWS}
  1393. buf := @Value.Value;
  1394. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
  1395. buf, SizeOf(Value.Value));
  1396. {$ELSE}
  1397. timeval.tv_sec:=Value.Value div 1000;
  1398. timeval.tv_usec:=(Value.Value mod 1000) * 1000;
  1399. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVTIMEO),
  1400. @timeval, SizeOf(timeval));
  1401. {$ENDIF}
  1402. {$ENDIF}
  1403. end;
  1404. SOT_SendTimeout:
  1405. begin
  1406. {$IFDEF CIL}
  1407. buf := System.BitConverter.GetBytes(value.Value);
  1408. {$ELSE}
  1409. {$IFDEF MSWINDOWS}
  1410. buf := @Value.Value;
  1411. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDTIMEO),
  1412. buf, SizeOf(Value.Value));
  1413. {$ELSE}
  1414. timeval.tv_sec:=Value.Value div 1000;
  1415. timeval.tv_usec:=(Value.Value mod 1000) * 1000;
  1416. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDTIMEO),
  1417. @timeval, SizeOf(timeval));
  1418. {$ENDIF}
  1419. {$ENDIF}
  1420. end;
  1421. SOT_Reuse:
  1422. begin
  1423. x := Ord(Value.Enabled);
  1424. {$IFDEF CIL}
  1425. buf := System.BitConverter.GetBytes(x);
  1426. {$ELSE}
  1427. buf := @x;
  1428. {$ENDIF}
  1429. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_REUSEADDR), buf, SizeOf(x));
  1430. end;
  1431. SOT_TTL:
  1432. begin
  1433. {$IFDEF CIL}
  1434. buf := System.BitConverter.GetBytes(value.Value);
  1435. {$ELSE}
  1436. buf := @Value.Value;
  1437. {$ENDIF}
  1438. if FIP6Used then
  1439. synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_UNICAST_HOPS),
  1440. buf, SizeOf(Value.Value))
  1441. else
  1442. synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_TTL),
  1443. buf, SizeOf(Value.Value));
  1444. end;
  1445. SOT_Broadcast:
  1446. begin
  1447. //#todo1 broadcasty na IP6
  1448. x := Ord(Value.Enabled);
  1449. {$IFDEF CIL}
  1450. buf := System.BitConverter.GetBytes(x);
  1451. {$ELSE}
  1452. buf := @x;
  1453. {$ENDIF}
  1454. synsock.SetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_BROADCAST), buf, SizeOf(x));
  1455. end;
  1456. SOT_MulticastTTL:
  1457. begin
  1458. {$IFDEF CIL}
  1459. buf := System.BitConverter.GetBytes(value.Value);
  1460. {$ELSE}
  1461. buf := @Value.Value;
  1462. {$ENDIF}
  1463. if FIP6Used then
  1464. synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_MULTICAST_HOPS),
  1465. buf, SizeOf(Value.Value))
  1466. else
  1467. synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_MULTICAST_TTL),
  1468. buf, SizeOf(Value.Value));
  1469. end;
  1470. SOT_MulticastLoop:
  1471. begin
  1472. x := Ord(Value.Enabled);
  1473. {$IFDEF CIL}
  1474. buf := System.BitConverter.GetBytes(x);
  1475. {$ELSE}
  1476. buf := @x;
  1477. {$ENDIF}
  1478. if FIP6Used then
  1479. synsock.SetSockOpt(FSocket, integer(IPPROTO_IPV6), integer(IPV6_MULTICAST_LOOP), buf, SizeOf(x))
  1480. else
  1481. synsock.SetSockOpt(FSocket, integer(IPPROTO_IP), integer(IP_MULTICAST_LOOP), buf, SizeOf(x));
  1482. end;
  1483. end;
  1484. Value.Free;
  1485. end;
  1486. procedure TBlockSocket.DelayedOption(const Value: TSynaOption);
  1487. begin
  1488. if FSocket = INVALID_SOCKET then
  1489. begin
  1490. FDelayedOptions.Insert(0, Value);
  1491. end
  1492. else
  1493. SetDelayedOption(Value);
  1494. end;
  1495. procedure TBlockSocket.ProcessDelayedOptions;
  1496. var
  1497. n: integer;
  1498. d: TSynaOption;
  1499. begin
  1500. for n := FDelayedOptions.Count - 1 downto 0 do
  1501. begin
  1502. d := TSynaOption(FDelayedOptions[n]);
  1503. SetDelayedOption(d);
  1504. end;
  1505. FDelayedOptions.Clear;
  1506. end;
  1507. procedure TBlockSocket.SetSin(var Sin: TVarSin; IP, Port: string);
  1508. var
  1509. f: TSocketFamily;
  1510. begin
  1511. DoStatus(HR_ResolvingBegin, IP + ':' + Port);
  1512. ResetLastError;
  1513. //if socket exists, then use their type, else use users selection
  1514. f := SF_Any;
  1515. if (FSocket = INVALID_SOCKET) and (FFamily = SF_any) then
  1516. begin
  1517. if IsIP(IP) then
  1518. f := SF_IP4
  1519. else
  1520. if IsIP6(IP) then
  1521. f := SF_IP6;
  1522. end
  1523. else
  1524. f := FFamily;
  1525. FLastError := synsock.SetVarSin(sin, ip, port, FamilyToAF(f),
  1526. GetSocketprotocol, GetSocketType, FPreferIP4);
  1527. DoStatus(HR_ResolvingEnd, GetSinIP(sin) + ':' + IntTostr(GetSinPort(sin)));
  1528. end;
  1529. function TBlockSocket.GetSinIP(Sin: TVarSin): string;
  1530. begin
  1531. Result := synsock.GetSinIP(sin);
  1532. end;
  1533. function TBlockSocket.GetSinPort(Sin: TVarSin): Integer;
  1534. begin
  1535. Result := synsock.GetSinPort(sin);
  1536. end;
  1537. procedure TBlockSocket.CreateSocket;
  1538. var
  1539. sin: TVarSin;
  1540. begin
  1541. //dummy for SF_Any Family mode
  1542. ResetLastError;
  1543. if (FFamily <> SF_Any) and (FSocket = INVALID_SOCKET) then
  1544. begin
  1545. {$IFDEF CIL}
  1546. if FFamily = SF_IP6 then
  1547. sin := TVarSin.Create(IPAddress.Parse('::0'), 0)
  1548. else
  1549. sin := TVarSin.Create(IPAddress.Parse('0.0.0.0'), 0);
  1550. {$ELSE}
  1551. FillChar(Sin, Sizeof(Sin), 0);
  1552. if FFamily = SF_IP6 then
  1553. sin.sin_family := AF_INET6
  1554. else
  1555. sin.sin_family := AF_INET;
  1556. {$ENDIF}
  1557. InternalCreateSocket(Sin);
  1558. end;
  1559. end;
  1560. procedure TBlockSocket.CreateSocketByName(const Value: String);
  1561. var
  1562. sin: TVarSin;
  1563. begin
  1564. ResetLastError;
  1565. if FSocket = INVALID_SOCKET then
  1566. begin
  1567. SetSin(sin, value, '0');
  1568. if FLastError = 0 then
  1569. InternalCreateSocket(Sin);
  1570. end;
  1571. end;
  1572. procedure TBlockSocket.InternalCreateSocket(Sin: TVarSin);
  1573. begin
  1574. FStopFlag := False;
  1575. FRecvCounter := 0;
  1576. FSendCounter := 0;
  1577. ResetLastError;
  1578. if FSocket = INVALID_SOCKET then
  1579. begin
  1580. FBuffer := '';
  1581. FBinded := False;
  1582. FIP6Used := Sin.AddressFamily = AF_INET6;
  1583. FSocket := synsock.Socket(integer(Sin.AddressFamily), GetSocketType, GetSocketProtocol);
  1584. if FSocket = INVALID_SOCKET then
  1585. FLastError := synsock.WSAGetLastError;
  1586. {$IFNDEF CIL}
  1587. FD_ZERO(FFDSet);
  1588. FD_SET(FSocket, FFDSet);
  1589. {$ENDIF}
  1590. ExceptCheck;
  1591. if FIP6used then
  1592. DoStatus(HR_SocketCreate, 'IPv6')
  1593. else
  1594. DoStatus(HR_SocketCreate, 'IPv4');
  1595. ProcessDelayedOptions;
  1596. DoCreateSocket;
  1597. end;
  1598. end;
  1599. procedure TBlockSocket.CloseSocket;
  1600. begin
  1601. AbortSocket;
  1602. end;
  1603. procedure TBlockSocket.AbortSocket;
  1604. var
  1605. n: integer;
  1606. p: TSynaOption;
  1607. begin
  1608. if FSocket <> INVALID_SOCKET then
  1609. synsock.CloseSocket(FSocket);
  1610. FSocket := INVALID_SOCKET;
  1611. for n := FDelayedOptions.Count - 1 downto 0 do
  1612. begin
  1613. p := TSynaOption(FDelayedOptions[n]);
  1614. p.Free;
  1615. end;
  1616. FDelayedOptions.Clear;
  1617. FFamily := FFamilySave;
  1618. DoStatus(HR_SocketClose, '');
  1619. end;
  1620. procedure TBlockSocket.Bind(const IP, Port: string);
  1621. var
  1622. Sin: TVarSin;
  1623. begin
  1624. ResetLastError;
  1625. if (FSocket <> INVALID_SOCKET)
  1626. or not((FFamily = SF_ANY) and (IP = cAnyHost) and (Port = cAnyPort)) then
  1627. begin
  1628. SetSin(Sin, IP, Port);
  1629. if FLastError = 0 then
  1630. begin
  1631. if FSocket = INVALID_SOCKET then
  1632. InternalCreateSocket(Sin);
  1633. SockCheck(synsock.Bind(FSocket, Sin));
  1634. GetSinLocal;
  1635. FBuffer := '';
  1636. FBinded := True;
  1637. end;
  1638. ExceptCheck;
  1639. DoStatus(HR_Bind, IP + ':' + Port);
  1640. end;
  1641. end;
  1642. procedure TBlockSocket.Connect(IP, Port: string);
  1643. var
  1644. Sin: TVarSin;
  1645. b: boolean;
  1646. begin
  1647. SetSin(Sin, IP, Port);
  1648. if FLastError = 0 then
  1649. begin
  1650. if FSocket = INVALID_SOCKET then
  1651. InternalCreateSocket(Sin);
  1652. if FConnectionTimeout > 0 then
  1653. begin
  1654. // connect in non-blocking mode
  1655. b := NonBlockMode;
  1656. NonBlockMode := true;
  1657. SockCheck(synsock.Connect(FSocket, Sin));
  1658. if (FLastError = WSAEINPROGRESS) OR (FLastError = WSAEWOULDBLOCK) then
  1659. if not CanWrite(FConnectionTimeout) then
  1660. FLastError := WSAETIMEDOUT;
  1661. NonBlockMode := b;
  1662. end
  1663. else
  1664. SockCheck(synsock.Connect(FSocket, Sin));
  1665. if FLastError = 0 then
  1666. GetSins;
  1667. FBuffer := '';
  1668. FLastCR := False;
  1669. FLastLF := False;
  1670. end;
  1671. ExceptCheck;
  1672. DoStatus(HR_Connect, IP + ':' + Port);
  1673. end;
  1674. procedure TBlockSocket.Listen;
  1675. begin
  1676. SockCheck(synsock.Listen(FSocket, SOMAXCONN));
  1677. GetSins;
  1678. ExceptCheck;
  1679. DoStatus(HR_Listen, '');
  1680. end;
  1681. function TBlockSocket.Accept: TSocket;
  1682. begin
  1683. Result := synsock.Accept(FSocket, FRemoteSin);
  1684. /// SockCheck(Result);
  1685. ExceptCheck;
  1686. DoStatus(HR_Accept, '');
  1687. end;
  1688. procedure TBlockSocket.GetSinLocal;
  1689. begin
  1690. synsock.GetSockName(FSocket, FLocalSin);
  1691. end;
  1692. procedure TBlockSocket.GetSinRemote;
  1693. begin
  1694. synsock.GetPeerName(FSocket, FRemoteSin);
  1695. end;
  1696. procedure TBlockSocket.GetSins;
  1697. begin
  1698. GetSinLocal;
  1699. GetSinRemote;
  1700. end;
  1701. procedure TBlockSocket.SetBandwidth(Value: Integer);
  1702. begin
  1703. MaxSendBandwidth := Value;
  1704. MaxRecvBandwidth := Value;
  1705. end;
  1706. procedure TBlockSocket.LimitBandwidth(Length: Integer; MaxB: integer; var Next: LongWord);
  1707. var
  1708. x: LongWord;
  1709. y: LongWord;
  1710. n: integer;
  1711. begin
  1712. if FStopFlag then
  1713. exit;
  1714. if MaxB > 0 then
  1715. begin
  1716. y := GetTick;
  1717. if Next > y then
  1718. begin
  1719. x := Next - y;
  1720. if x > 0 then
  1721. begin
  1722. DoStatus(HR_Wait, IntToStr(x));
  1723. sleep(x mod 250);
  1724. for n := 1 to x div 250 do
  1725. if FStopFlag then
  1726. Break
  1727. else
  1728. sleep(250);
  1729. end;
  1730. end;
  1731. Next := GetTick + LongWord(Trunc((Length / MaxB) * 1000));
  1732. end;
  1733. end;
  1734. function TBlockSocket.TestStopFlag: Boolean;
  1735. begin
  1736. DoHeartbeat;
  1737. Result := FStopFlag;
  1738. if Result then
  1739. begin
  1740. FStopFlag := False;
  1741. FLastError := WSAECONNABORTED;
  1742. ExceptCheck;
  1743. end;
  1744. end;
  1745. function TBlockSocket.SendBuffer(const Buffer: TMemory; Length: Integer): Integer;
  1746. {$IFNDEF CIL}
  1747. var
  1748. x, y: integer;
  1749. l, r: integer;
  1750. p: Pointer;
  1751. {$ENDIF}
  1752. begin
  1753. Result := 0;
  1754. if TestStopFlag then
  1755. Exit;
  1756. DoMonitor(True, Buffer, Length);
  1757. {$IFDEF CIL}
  1758. Result := synsock.Send(FSocket, Buffer, Length, 0);
  1759. {$ELSE}
  1760. l := Length;
  1761. x := 0;
  1762. while x < l do
  1763. begin
  1764. y := l - x;
  1765. if y > FSendMaxChunk then
  1766. y := FSendMaxChunk;
  1767. if y > 0 then
  1768. begin
  1769. LimitBandwidth(y, FMaxSendBandwidth, FNextsend);
  1770. p := IncPoint(Buffer, x);
  1771. r := synsock.Send(FSocket, p, y, MSG_NOSIGNAL);
  1772. SockCheck(r);
  1773. if FLastError = WSAEWOULDBLOCK then
  1774. begin
  1775. if CanWrite(FNonblockSendTimeout) then
  1776. begin
  1777. r := synsock.Send(FSocket, p, y, MSG_NOSIGNAL);
  1778. SockCheck(r);
  1779. end
  1780. else
  1781. FLastError := WSAETIMEDOUT;
  1782. end;
  1783. if FLastError <> 0 then
  1784. Break;
  1785. Inc(x, r);
  1786. Inc(Result, r);
  1787. Inc(FSendCounter, r);
  1788. DoStatus(HR_WriteCount, IntToStr(r));
  1789. end
  1790. else
  1791. break;
  1792. end;
  1793. {$ENDIF}
  1794. ExceptCheck;
  1795. end;
  1796. procedure TBlockSocket.SendByte(Data: Byte);
  1797. {$IFDEF CIL}
  1798. var
  1799. buf: TMemory;
  1800. {$ENDIF}
  1801. begin
  1802. {$IFDEF CIL}
  1803. setlength(buf, 1);
  1804. buf[0] := Data;
  1805. SendBuffer(buf, 1);
  1806. {$ELSE}
  1807. SendBuffer(@Data, 1);
  1808. {$ENDIF}
  1809. end;
  1810. procedure TBlockSocket.SendString(Data: AnsiString);
  1811. var
  1812. buf: TMemory;
  1813. begin
  1814. {$IFDEF CIL}
  1815. buf := BytesOf(Data);
  1816. {$ELSE}
  1817. buf := Pointer(data);
  1818. {$ENDIF}
  1819. SendBuffer(buf, Length(Data));
  1820. end;
  1821. procedure TBlockSocket.SendInteger(Data: integer);
  1822. var
  1823. buf: TMemory;
  1824. begin
  1825. {$IFDEF CIL}
  1826. buf := System.BitConverter.GetBytes(Data);
  1827. {$ELSE}
  1828. buf := @Data;
  1829. {$ENDIF}
  1830. SendBuffer(buf, SizeOf(Data));
  1831. end;
  1832. procedure TBlockSocket.SendBlock(const Data: AnsiString);
  1833. var
  1834. i: integer;
  1835. begin
  1836. i := SwapBytes(Length(data));
  1837. SendString(Codelongint(i) + Data);
  1838. end;
  1839. procedure TBlockSocket.InternalSendStream(const Stream: TStream; WithSize, Indy: boolean);
  1840. var
  1841. l: integer;
  1842. yr: integer;
  1843. s: AnsiString;
  1844. b: boolean;
  1845. {$IFDEF CIL}
  1846. buf: TMemory;
  1847. {$ENDIF}
  1848. begin
  1849. b := true;
  1850. l := 0;
  1851. if WithSize then
  1852. begin
  1853. l := Stream.Size - Stream.Position;;
  1854. if not Indy then
  1855. l := synsock.HToNL(l);
  1856. end;
  1857. repeat
  1858. {$IFDEF CIL}
  1859. Setlength(buf, FSendMaxChunk);
  1860. yr := Stream.read(buf, FSendMaxChunk);
  1861. if yr > 0 then
  1862. begin
  1863. if WithSize and b then
  1864. begin
  1865. b := false;
  1866. SendString(CodeLongInt(l));
  1867. end;
  1868. SendBuffer(buf, yr);
  1869. if FLastError <> 0 then
  1870. break;
  1871. end
  1872. {$ELSE}
  1873. Setlength(s, FSendMaxChunk);
  1874. yr := Stream.read(Pointer(s)^, FSendMaxChunk);
  1875. if yr > 0 then
  1876. begin
  1877. SetLength(s, yr);
  1878. if WithSize and b then
  1879. begin
  1880. b := false;
  1881. SendString(CodeLongInt(l) + s);
  1882. end
  1883. else
  1884. SendString(s);
  1885. if FLastError <> 0 then
  1886. break;
  1887. end
  1888. {$ENDIF}
  1889. until yr <= 0;
  1890. end;
  1891. procedure TBlockSocket.SendStreamRaw(const Stream: TStream);
  1892. begin
  1893. InternalSendStream(Stream, false, false);
  1894. end;
  1895. procedure TBlockSocket.SendStreamIndy(const Stream: TStream);
  1896. begin
  1897. InternalSendStream(Stream, true, true);
  1898. end;
  1899. procedure TBlockSocket.SendStream(const Stream: TStream);
  1900. begin
  1901. InternalSendStream(Stream, true, false);
  1902. end;
  1903. function TBlockSocket.RecvBuffer(Buffer: TMemory; Length: Integer): Integer;
  1904. begin
  1905. Result := 0;
  1906. if TestStopFlag then
  1907. Exit;
  1908. LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
  1909. // Result := synsock.Recv(FSocket, Buffer^, Length, MSG_NOSIGNAL);
  1910. Result := synsock.Recv(FSocket, Buffer, Length, MSG_NOSIGNAL);
  1911. if Result = 0 then
  1912. FLastError := WSAECONNRESET
  1913. else
  1914. SockCheck(Result);
  1915. ExceptCheck;
  1916. if Result > 0 then
  1917. begin
  1918. Inc(FRecvCounter, Result);
  1919. DoStatus(HR_ReadCount, IntToStr(Result));
  1920. DoMonitor(False, Buffer, Result);
  1921. DoReadFilter(Buffer, Result);
  1922. end;
  1923. end;
  1924. function TBlockSocket.RecvBufferEx(Buffer: TMemory; Len: Integer;
  1925. Timeout: Integer): Integer;
  1926. var
  1927. s: AnsiString;
  1928. rl, l: integer;
  1929. ti: LongWord;
  1930. {$IFDEF CIL}
  1931. n: integer;
  1932. b: TMemory;
  1933. {$ENDIF}
  1934. begin
  1935. ResetLastError;
  1936. Result := 0;
  1937. if Len > 0 then
  1938. begin
  1939. rl := 0;
  1940. repeat
  1941. ti := GetTick;
  1942. s := RecvPacket(Timeout);
  1943. l := Length(s);
  1944. if (rl + l) > Len then
  1945. l := Len - rl;
  1946. {$IFDEF CIL}
  1947. b := BytesOf(s);
  1948. for n := 0 to l do
  1949. Buffer[rl + n] := b[n];
  1950. {$ELSE}
  1951. Move(Pointer(s)^, IncPoint(Buffer, rl)^, l);
  1952. {$ENDIF}
  1953. rl := rl + l;
  1954. if FLastError <> 0 then
  1955. Break;
  1956. if rl >= Len then
  1957. Break;
  1958. if not FInterPacketTimeout then
  1959. begin
  1960. Timeout := Timeout - integer(TickDelta(ti, GetTick));
  1961. if Timeout <= 0 then
  1962. begin
  1963. FLastError := WSAETIMEDOUT;
  1964. Break;
  1965. end;
  1966. end;
  1967. until False;
  1968. delete(s, 1, l);
  1969. FBuffer := s;
  1970. Result := rl;
  1971. end;
  1972. end;
  1973. function TBlockSocket.RecvBufferStr(Len: Integer; Timeout: Integer): AnsiString;
  1974. var
  1975. x: integer;
  1976. {$IFDEF CIL}
  1977. buf: Tmemory;
  1978. {$ENDIF}
  1979. begin
  1980. Result := '';
  1981. if Len > 0 then
  1982. begin
  1983. {$IFDEF CIL}
  1984. Setlength(Buf, Len);
  1985. x := RecvBufferEx(buf, Len , Timeout);
  1986. if FLastError = 0 then
  1987. begin
  1988. SetLength(Buf, x);
  1989. Result := StringOf(buf);
  1990. end
  1991. else
  1992. Result := '';
  1993. {$ELSE}
  1994. Setlength(Result, Len);
  1995. x := RecvBufferEx(Pointer(Result), Len , Timeout);
  1996. if FLastError = 0 then
  1997. SetLength(Result, x)
  1998. else
  1999. Result := '';
  2000. {$ENDIF}
  2001. end;
  2002. end;
  2003. function TBlockSocket.RecvPacket(Timeout: Integer): AnsiString;
  2004. var
  2005. x: integer;
  2006. {$IFDEF CIL}
  2007. buf: TMemory;
  2008. {$ENDIF}
  2009. begin
  2010. Result := '';
  2011. ResetLastError;
  2012. if FBuffer <> '' then
  2013. begin
  2014. Result := FBuffer;
  2015. FBuffer := '';
  2016. end
  2017. else
  2018. begin
  2019. {$IFDEF MSWINDOWS}
  2020. //not drain CPU on large downloads...
  2021. Sleep(0);
  2022. {$ENDIF}
  2023. x := WaitingData;
  2024. if x > 0 then
  2025. begin
  2026. {$IFDEF CIL}
  2027. SetLength(Buf, x);
  2028. x := RecvBuffer(Buf, x);
  2029. if x >= 0 then
  2030. begin
  2031. SetLength(Buf, x);
  2032. Result := StringOf(Buf);
  2033. end;
  2034. {$ELSE}
  2035. SetLength(Result, x);
  2036. x := RecvBuffer(Pointer(Result), x);
  2037. if x >= 0 then
  2038. SetLength(Result, x);
  2039. {$ENDIF}
  2040. end
  2041. else
  2042. begin
  2043. if CanRead(Timeout) then
  2044. begin
  2045. x := WaitingData;
  2046. if x = 0 then
  2047. FLastError := WSAECONNRESET;
  2048. if x > 0 then
  2049. begin
  2050. {$IFDEF CIL}
  2051. SetLength(Buf, x);
  2052. x := RecvBuffer(Buf, x);
  2053. if x >= 0 then
  2054. begin
  2055. SetLength(Buf, x);
  2056. result := StringOf(Buf);
  2057. end;
  2058. {$ELSE}
  2059. SetLength(Result, x);
  2060. x := RecvBuffer(Pointer(Result), x);
  2061. if x >= 0 then
  2062. SetLength(Result, x);
  2063. {$ENDIF}
  2064. end;
  2065. end
  2066. else
  2067. FLastError := WSAETIMEDOUT;
  2068. end;
  2069. end;
  2070. if FConvertLineEnd and (Result <> '') then
  2071. begin
  2072. if FLastCR and (Result[1] = LF) then
  2073. Delete(Result, 1, 1);
  2074. if FLastLF and (Result[1] = CR) then
  2075. Delete(Result, 1, 1);
  2076. FLastCR := False;
  2077. FLastLF := False;
  2078. end;
  2079. ExceptCheck;
  2080. end;
  2081. function TBlockSocket.RecvByte(Timeout: Integer): Byte;
  2082. begin
  2083. Result := 0;
  2084. ResetLastError;
  2085. if FBuffer = '' then
  2086. FBuffer := RecvPacket(Timeout);
  2087. if (FLastError = 0) and (FBuffer <> '') then
  2088. begin
  2089. Result := Ord(FBuffer[1]);
  2090. Delete(FBuffer, 1, 1);
  2091. end;
  2092. ExceptCheck;
  2093. end;
  2094. function TBlockSocket.RecvInteger(Timeout: Integer): Integer;
  2095. var
  2096. s: AnsiString;
  2097. begin
  2098. Result := 0;
  2099. s := RecvBufferStr(4, Timeout);
  2100. if FLastError = 0 then
  2101. Result := (ord(s[1]) + ord(s[2]) * 256) + (ord(s[3]) + ord(s[4]) * 256) * 65536;
  2102. end;
  2103. function TBlockSocket.RecvTerminated(Timeout: Integer; const Terminator: AnsiString): AnsiString;
  2104. var
  2105. x: Integer;
  2106. s: AnsiString;
  2107. l: Integer;
  2108. CorCRLF: Boolean;
  2109. t: AnsiString;
  2110. tl: integer;
  2111. ti: LongWord;
  2112. begin
  2113. ResetLastError;
  2114. Result := '';
  2115. l := Length(Terminator);
  2116. if l = 0 then
  2117. Exit;
  2118. tl := l;
  2119. CorCRLF := FConvertLineEnd and (Terminator = CRLF);
  2120. s := '';
  2121. x := 0;
  2122. repeat
  2123. //get rest of FBuffer or incomming new data...
  2124. ti := GetTick;
  2125. s := s + RecvPacket(Timeout);
  2126. if FLastError <> 0 then
  2127. Break;
  2128. x := 0;
  2129. if Length(s) > 0 then
  2130. if CorCRLF then
  2131. begin
  2132. t := '';
  2133. x := PosCRLF(s, t);
  2134. tl := Length(t);
  2135. if t = CR then
  2136. FLastCR := True;
  2137. if t = LF then
  2138. FLastLF := True;
  2139. end
  2140. else
  2141. begin
  2142. x := pos(Terminator, s);
  2143. tl := l;
  2144. end;
  2145. if (FMaxLineLength <> 0) and (Length(s) > FMaxLineLength) then
  2146. begin
  2147. FLastError := WSAENOBUFS;
  2148. Break;
  2149. end;
  2150. if x > 0 then
  2151. Break;
  2152. if not FInterPacketTimeout then
  2153. begin
  2154. Timeout := Timeout - integer(TickDelta(ti, GetTick));
  2155. if Timeout <= 0 then
  2156. begin
  2157. FLastError := WSAETIMEDOUT;
  2158. Break;
  2159. end;
  2160. end;
  2161. until False;
  2162. if x > 0 then
  2163. begin
  2164. Result := Copy(s, 1, x - 1);
  2165. Delete(s, 1, x + tl - 1);
  2166. end;
  2167. FBuffer := s;
  2168. ExceptCheck;
  2169. end;
  2170. function TBlockSocket.RecvString(Timeout: Integer): AnsiString;
  2171. var
  2172. s: AnsiString;
  2173. begin
  2174. Result := '';
  2175. s := RecvTerminated(Timeout, CRLF);
  2176. if FLastError = 0 then
  2177. Result := s;
  2178. end;
  2179. function TBlockSocket.RecvBlock(Timeout: Integer): AnsiString;
  2180. var
  2181. x: integer;
  2182. begin
  2183. Result := '';
  2184. x := RecvInteger(Timeout);
  2185. if FLastError = 0 then
  2186. Result := RecvBufferStr(x, Timeout);
  2187. end;
  2188. procedure TBlockSocket.RecvStreamRaw(const Stream: TStream; Timeout: Integer);
  2189. var
  2190. s: AnsiString;
  2191. begin
  2192. repeat
  2193. s := RecvPacket(Timeout);
  2194. if (Length(s) = 0) then
  2195. Break;
  2196. if FLastError = 0 then
  2197. WriteStrToStream(Stream, s);
  2198. until FLastError <> 0;
  2199. end;
  2200. procedure TBlockSocket.RecvStreamSize(const Stream: TStream; Timeout: Integer; Size: int64);
  2201. var
  2202. s: AnsiString;
  2203. n: int64;
  2204. {$IFDEF CIL}
  2205. buf: TMemory;
  2206. {$ENDIF}
  2207. begin
  2208. n := Size div int64(FSendMaxChunk);
  2209. while n > 0 do
  2210. begin
  2211. {$IFDEF CIL}
  2212. SetLength(buf, FSendMaxChunk);
  2213. RecvBufferEx(buf, FSendMaxChunk, Timeout);
  2214. if FLastError <> 0 then
  2215. Exit;
  2216. Stream.Write(buf, FSendMaxChunk);
  2217. {$ELSE}
  2218. s := RecvBufferStr(FSendMaxChunk, Timeout);
  2219. if FLastError <> 0 then
  2220. Exit;
  2221. WriteStrToStream(Stream, s);
  2222. {$ENDIF}
  2223. dec(n);
  2224. end;
  2225. n := Size mod int64(FSendMaxChunk);
  2226. if n > 0 then
  2227. begin
  2228. {$IFDEF CIL}
  2229. SetLength(buf, n);
  2230. RecvBufferEx(buf, n, Timeout);
  2231. if FLastError <> 0 then
  2232. Exit;
  2233. Stream.Write(buf, n);
  2234. {$ELSE}
  2235. s := RecvBufferStr(n, Timeout);
  2236. if FLastError <> 0 then
  2237. Exit;
  2238. WriteStrToStream(Stream, s);
  2239. {$ENDIF}
  2240. end;
  2241. end;
  2242. procedure TBlockSocket.RecvStreamIndy(const Stream: TStream; Timeout: Integer);
  2243. var
  2244. x: integer;
  2245. begin
  2246. x := RecvInteger(Timeout);
  2247. x := synsock.NToHL(x);
  2248. if FLastError = 0 then
  2249. RecvStreamSize(Stream, Timeout, x);
  2250. end;
  2251. procedure TBlockSocket.RecvStream(const Stream: TStream; Timeout: Integer);
  2252. var
  2253. x: integer;
  2254. begin
  2255. x := RecvInteger(Timeout);
  2256. if FLastError = 0 then
  2257. RecvStreamSize(Stream, Timeout, x);
  2258. end;
  2259. function TBlockSocket.PeekBuffer(Buffer: TMemory; Length: Integer): Integer;
  2260. begin
  2261. {$IFNDEF CIL}
  2262. // Result := synsock.Recv(FSocket, Buffer^, Length, MSG_PEEK + MSG_NOSIGNAL);
  2263. Result := synsock.Recv(FSocket, Buffer, Length, MSG_PEEK + MSG_NOSIGNAL);
  2264. SockCheck(Result);
  2265. ExceptCheck;
  2266. {$ENDIF}
  2267. end;
  2268. function TBlockSocket.PeekByte(Timeout: Integer): Byte;
  2269. var
  2270. s: string;
  2271. begin
  2272. {$IFNDEF CIL}
  2273. Result := 0;
  2274. if CanRead(Timeout) then
  2275. begin
  2276. SetLength(s, 1);
  2277. PeekBuffer(Pointer(s), 1);
  2278. if s <> '' then
  2279. Result := Ord(s[1]);
  2280. end
  2281. else
  2282. FLastError := WSAETIMEDOUT;
  2283. ExceptCheck;
  2284. {$ENDIF}
  2285. end;
  2286. procedure TBlockSocket.ResetLastError;
  2287. begin
  2288. FLastError := 0;
  2289. FLastErrorDesc := '';
  2290. end;
  2291. function TBlockSocket.SockCheck(SockResult: Integer): Integer;
  2292. begin
  2293. ResetLastError;
  2294. if SockResult = integer(SOCKET_ERROR) then
  2295. begin
  2296. FLastError := synsock.WSAGetLastError;
  2297. FLastErrorDesc := GetErrorDescEx;
  2298. end;
  2299. Result := FLastError;
  2300. end;
  2301. procedure TBlockSocket.ExceptCheck;
  2302. var
  2303. e: ESynapseError;
  2304. begin
  2305. FLastErrorDesc := GetErrorDescEx;
  2306. if (LastError <> 0) and (LastError <> WSAEINPROGRESS)
  2307. and (LastError <> WSAEWOULDBLOCK) then
  2308. begin
  2309. DoStatus(HR_Error, IntToStr(FLastError) + ',' + FLastErrorDesc);
  2310. if FRaiseExcept then
  2311. begin
  2312. e := ESynapseError.Create(Format('Synapse TCP/IP Socket error %d: %s',
  2313. [FLastError, FLastErrorDesc]));
  2314. e.ErrorCode := FLastError;
  2315. e.ErrorMessage := FLastErrorDesc;
  2316. raise e;
  2317. end;
  2318. end;
  2319. end;
  2320. function TBlockSocket.WaitingData: Integer;
  2321. var
  2322. x: Integer;
  2323. begin
  2324. Result := 0;
  2325. if synsock.IoctlSocket(FSocket, FIONREAD, x) = 0 then
  2326. Result := x;
  2327. if Result > c64k then
  2328. Result := c64k;
  2329. end;
  2330. function TBlockSocket.WaitingDataEx: Integer;
  2331. begin
  2332. if FBuffer <> '' then
  2333. Result := Length(FBuffer)
  2334. else
  2335. Result := WaitingData;
  2336. end;
  2337. procedure TBlockSocket.Purge;
  2338. begin
  2339. Sleep(1);
  2340. try
  2341. while (Length(FBuffer) > 0) or (WaitingData > 0) do
  2342. begin
  2343. RecvPacket(0);
  2344. if FLastError <> 0 then
  2345. break;
  2346. end;
  2347. except
  2348. on exception do;
  2349. end;
  2350. ResetLastError;
  2351. end;
  2352. procedure TBlockSocket.SetLinger(Enable: Boolean; Linger: Integer);
  2353. var
  2354. d: TSynaOption;
  2355. begin
  2356. d := TSynaOption.Create;
  2357. d.Option := SOT_Linger;
  2358. d.Enabled := Enable;
  2359. d.Value := Linger;
  2360. DelayedOption(d);
  2361. end;
  2362. function TBlockSocket.LocalName: string;
  2363. begin
  2364. Result := synsock.GetHostName;
  2365. if Result = '' then
  2366. Result := '127.0.0.1';
  2367. end;
  2368. procedure TBlockSocket.ResolveNameToIP(Name: string; const IPList: TStrings);
  2369. begin
  2370. IPList.Clear;
  2371. synsock.ResolveNameToIP(Name, FamilyToAF(FFamily), GetSocketprotocol, GetSocketType, IPList);
  2372. if IPList.Count = 0 then
  2373. IPList.Add(cAnyHost);
  2374. end;
  2375. function TBlockSocket.ResolveName(Name: string): string;
  2376. var
  2377. l: TStringList;
  2378. begin
  2379. l := TStringList.Create;
  2380. try
  2381. ResolveNameToIP(Name, l);
  2382. Result := l[0];
  2383. finally
  2384. l.Free;
  2385. end;
  2386. end;
  2387. function TBlockSocket.ResolvePort(Port: string): Word;
  2388. begin
  2389. Result := synsock.ResolvePort(Port, FamilyToAF(FFamily), GetSocketProtocol, GetSocketType);
  2390. end;
  2391. function TBlockSocket.ResolveIPToName(IP: string): string;
  2392. begin
  2393. if not IsIP(IP) and not IsIp6(IP) then
  2394. IP := ResolveName(IP);
  2395. Result := synsock.ResolveIPToName(IP, FamilyToAF(FFamily), GetSocketProtocol, GetSocketType);
  2396. end;
  2397. procedure TBlockSocket.SetRemoteSin(IP, Port: string);
  2398. begin
  2399. SetSin(FRemoteSin, IP, Port);
  2400. end;
  2401. function TBlockSocket.GetLocalSinIP: string;
  2402. begin
  2403. Result := GetSinIP(FLocalSin);
  2404. end;
  2405. function TBlockSocket.GetRemoteSinIP: string;
  2406. begin
  2407. Result := GetSinIP(FRemoteSin);
  2408. end;
  2409. function TBlockSocket.GetLocalSinPort: Integer;
  2410. begin
  2411. Result := GetSinPort(FLocalSin);
  2412. end;
  2413. function TBlockSocket.GetRemoteSinPort: Integer;
  2414. begin
  2415. Result := GetSinPort(FRemoteSin);
  2416. end;
  2417. function TBlockSocket.InternalCanRead(Timeout: Integer): Boolean;
  2418. {$IFDEF CIL}
  2419. begin
  2420. Result := FSocket.Poll(Timeout * 1000, SelectMode.SelectRead);
  2421. {$ELSE}
  2422. var
  2423. TimeVal: PTimeVal;
  2424. TimeV: TTimeVal;
  2425. x: Integer;
  2426. FDSet: TFDSet;
  2427. begin
  2428. TimeV.tv_usec := (Timeout mod 1000) * 1000;
  2429. TimeV.tv_sec := Timeout div 1000;
  2430. TimeVal := @TimeV;
  2431. if Timeout = -1 then
  2432. TimeVal := nil;
  2433. FDSet := FFdSet;
  2434. x := synsock.Select(FSocket + 1, @FDSet, nil, nil, TimeVal);
  2435. SockCheck(x);
  2436. if FLastError <> 0 then
  2437. x := 0;
  2438. Result := x > 0;
  2439. {$ENDIF}
  2440. end;
  2441. function TBlockSocket.CanRead(Timeout: Integer): Boolean;
  2442. var
  2443. ti, tr: Integer;
  2444. n: integer;
  2445. begin
  2446. if (FHeartbeatRate <> 0) and (Timeout <> -1) then
  2447. begin
  2448. ti := Timeout div FHeartbeatRate;
  2449. tr := Timeout mod FHeartbeatRate;
  2450. end
  2451. else
  2452. begin
  2453. ti := 0;
  2454. tr := Timeout;
  2455. end;
  2456. Result := InternalCanRead(tr);
  2457. if not Result then
  2458. for n := 0 to ti do
  2459. begin
  2460. DoHeartbeat;
  2461. if FStopFlag then
  2462. begin
  2463. Result := False;
  2464. FStopFlag := False;
  2465. Break;
  2466. end;
  2467. Result := InternalCanRead(FHeartbeatRate);
  2468. if Result then
  2469. break;
  2470. end;
  2471. ExceptCheck;
  2472. if Result then
  2473. DoStatus(HR_CanRead, '');
  2474. end;
  2475. function TBlockSocket.InternalCanWrite(Timeout: Integer): Boolean;
  2476. {$IFDEF CIL}
  2477. begin
  2478. Result := FSocket.Poll(Timeout * 1000, SelectMode.SelectWrite);
  2479. {$ELSE}
  2480. var
  2481. TimeVal: PTimeVal;
  2482. TimeV: TTimeVal;
  2483. x: Integer;
  2484. FDSet: TFDSet;
  2485. begin
  2486. TimeV.tv_usec := (Timeout mod 1000) * 1000;
  2487. TimeV.tv_sec := Timeout div 1000;
  2488. TimeVal := @TimeV;
  2489. if Timeout = -1 then
  2490. TimeVal := nil;
  2491. FDSet := FFdSet;
  2492. x := synsock.Select(FSocket + 1, nil, @FDSet, nil, TimeVal);
  2493. SockCheck(x);
  2494. if FLastError <> 0 then
  2495. x := 0;
  2496. Result := x > 0;
  2497. {$ENDIF}
  2498. end;
  2499. function TBlockSocket.CanWrite(Timeout: Integer): Boolean;
  2500. var
  2501. ti, tr: Integer;
  2502. n: integer;
  2503. begin
  2504. if (FHeartbeatRate <> 0) and (Timeout <> -1) then
  2505. begin
  2506. ti := Timeout div FHeartbeatRate;
  2507. tr := Timeout mod FHeartbeatRate;
  2508. end
  2509. else
  2510. begin
  2511. ti := 0;
  2512. tr := Timeout;
  2513. end;
  2514. Result := InternalCanWrite(tr);
  2515. if not Result then
  2516. for n := 0 to ti do
  2517. begin
  2518. DoHeartbeat;
  2519. if FStopFlag then
  2520. begin
  2521. Result := False;
  2522. FStopFlag := False;
  2523. Break;
  2524. end;
  2525. Result := InternalCanWrite(FHeartbeatRate);
  2526. if Result then
  2527. break;
  2528. end;
  2529. ExceptCheck;
  2530. if Result then
  2531. DoStatus(HR_CanWrite, '');
  2532. end;
  2533. function TBlockSocket.CanReadEx(Timeout: Integer): Boolean;
  2534. begin
  2535. if FBuffer <> '' then
  2536. Result := True
  2537. else
  2538. Result := CanRead(Timeout);
  2539. end;
  2540. function TBlockSocket.SendBufferTo(const Buffer: TMemory; Length: Integer): Integer;
  2541. begin
  2542. Result := 0;
  2543. if TestStopFlag then
  2544. Exit;
  2545. DoMonitor(True, Buffer, Length);
  2546. LimitBandwidth(Length, FMaxSendBandwidth, FNextsend);
  2547. Result := synsock.SendTo(FSocket, Buffer, Length, MSG_NOSIGNAL, FRemoteSin);
  2548. SockCheck(Result);
  2549. ExceptCheck;
  2550. Inc(FSendCounter, Result);
  2551. DoStatus(HR_WriteCount, IntToStr(Result));
  2552. end;
  2553. function TBlockSocket.RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer;
  2554. begin
  2555. Result := 0;
  2556. if TestStopFlag then
  2557. Exit;
  2558. LimitBandwidth(Length, FMaxRecvBandwidth, FNextRecv);
  2559. Result := synsock.RecvFrom(FSocket, Buffer, Length, MSG_NOSIGNAL, FRemoteSin);
  2560. SockCheck(Result);
  2561. ExceptCheck;
  2562. Inc(FRecvCounter, Result);
  2563. DoStatus(HR_ReadCount, IntToStr(Result));
  2564. DoMonitor(False, Buffer, Result);
  2565. end;
  2566. function TBlockSocket.GetSizeRecvBuffer: Integer;
  2567. var
  2568. l: Integer;
  2569. {$IFDEF CIL}
  2570. buf: TMemory;
  2571. {$ENDIF}
  2572. begin
  2573. {$IFDEF CIL}
  2574. setlength(buf, 4);
  2575. SockCheck(synsock.GetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_RCVBUF), buf, l));
  2576. Result := System.BitConverter.ToInt32(buf,0);
  2577. {$ELSE}
  2578. l := SizeOf(Result);
  2579. SockCheck(synsock.GetSockOpt(FSocket, SOL_SOCKET, SO_RCVBUF, @Result, l));
  2580. if FLastError <> 0 then
  2581. Result := 1024;
  2582. ExceptCheck;
  2583. {$ENDIF}
  2584. end;
  2585. procedure TBlockSocket.SetSizeRecvBuffer(Size: Integer);
  2586. var
  2587. d: TSynaOption;
  2588. begin
  2589. d := TSynaOption.Create;
  2590. d.Option := SOT_RecvBuff;
  2591. d.Value := Size;
  2592. DelayedOption(d);
  2593. end;
  2594. function TBlockSocket.GetSizeSendBuffer: Integer;
  2595. var
  2596. l: Integer;
  2597. {$IFDEF CIL}
  2598. buf: TMemory;
  2599. {$ENDIF}
  2600. begin
  2601. {$IFDEF CIL}
  2602. setlength(buf, 4);
  2603. SockCheck(synsock.GetSockOpt(FSocket, integer(SOL_SOCKET), integer(SO_SNDBUF), buf, l));
  2604. Result := System.BitConverter.ToInt32(buf,0);
  2605. {$ELSE}
  2606. l := SizeOf(Result);
  2607. SockCheck(synsock.GetSockOpt(FSocket, SOL_SOCKET, SO_SNDBUF, @Result, l));
  2608. if FLastError <> 0 then
  2609. Result := 1024;
  2610. ExceptCheck;
  2611. {$ENDIF}
  2612. end;
  2613. procedure TBlockSocket.SetSizeSendBuffer(Size: Integer);
  2614. var
  2615. d: TSynaOption;
  2616. begin
  2617. d := TSynaOption.Create;
  2618. d.Option := SOT_SendBuff;
  2619. d.Value := Size;
  2620. DelayedOption(d);
  2621. end;
  2622. procedure TBlockSocket.SetNonBlockMode(Value: Boolean);
  2623. var
  2624. d: TSynaOption;
  2625. begin
  2626. d := TSynaOption.Create;
  2627. d.Option := SOT_nonblock;
  2628. d.Enabled := Value;
  2629. DelayedOption(d);
  2630. end;
  2631. procedure TBlockSocket.SetTimeout(Timeout: Integer);
  2632. begin
  2633. SetSendTimeout(Timeout);
  2634. SetRecvTimeout(Timeout);
  2635. end;
  2636. procedure TBlockSocket.SetSendTimeout(Timeout: Integer);
  2637. var
  2638. d: TSynaOption;
  2639. begin
  2640. d := TSynaOption.Create;
  2641. d.Option := SOT_sendtimeout;
  2642. d.Value := Timeout;
  2643. DelayedOption(d);
  2644. end;
  2645. procedure TBlockSocket.SetRecvTimeout(Timeout: Integer);
  2646. var
  2647. d: TSynaOption;
  2648. begin
  2649. d := TSynaOption.Create;
  2650. d.Option := SOT_recvtimeout;
  2651. d.Value := Timeout;
  2652. DelayedOption(d);
  2653. end;
  2654. {$IFNDEF CIL}
  2655. function TBlockSocket.GroupCanRead(const SocketList: TSocketList; Timeout: Integer;
  2656. const CanReadList: TSocketList): boolean;
  2657. var
  2658. FDSet: TFDSet;
  2659. TimeVal: PTimeVal;
  2660. TimeV: TTimeVal;
  2661. x, n: Integer;
  2662. Max: Integer;
  2663. begin
  2664. TimeV.tv_usec := (Timeout mod 1000) * 1000;
  2665. TimeV.tv_sec := Timeout div 1000;
  2666. TimeVal := @TimeV;
  2667. if Timeout = -1 then
  2668. TimeVal := nil;
  2669. FD_ZERO(FDSet);
  2670. Max := 0;
  2671. for n := 0 to SocketList.Count - 1 do
  2672. if TObject(SocketList.Items[n]) is TBlockSocket then
  2673. begin
  2674. if TBlockSocket(SocketList.Items[n]).Socket > Max then
  2675. Max := TBlockSocket(SocketList.Items[n]).Socket;
  2676. FD_SET(TBlockSocket(SocketList.Items[n]).Socket, FDSet);
  2677. end;
  2678. x := synsock.Select(Max + 1, @FDSet, nil, nil, TimeVal);
  2679. SockCheck(x);
  2680. ExceptCheck;
  2681. if FLastError <> 0 then
  2682. x := 0;
  2683. Result := x > 0;
  2684. CanReadList.Clear;
  2685. if Result then
  2686. for n := 0 to SocketList.Count - 1 do
  2687. if TObject(SocketList.Items[n]) is TBlockSocket then
  2688. if FD_ISSET(TBlockSocket(SocketList.Items[n]).Socket, FDSet) then
  2689. CanReadList.Add(TBlockSocket(SocketList.Items[n]));
  2690. end;
  2691. {$ENDIF}
  2692. procedure TBlockSocket.EnableReuse(Value: Boolean);
  2693. var
  2694. d: TSynaOption;
  2695. begin
  2696. d := TSynaOption.Create;
  2697. d.Option := SOT_reuse;
  2698. d.Enabled := Value;
  2699. DelayedOption(d);
  2700. end;
  2701. procedure TBlockSocket.SetTTL(TTL: integer);
  2702. var
  2703. d: TSynaOption;
  2704. begin
  2705. d := TSynaOption.Create;
  2706. d.Option := SOT_TTL;
  2707. d.Value := TTL;
  2708. DelayedOption(d);
  2709. end;
  2710. function TBlockSocket.GetTTL:integer;
  2711. var
  2712. l: Integer;
  2713. begin
  2714. {$IFNDEF CIL}
  2715. l := SizeOf(Result);
  2716. if FIP6Used then
  2717. synsock.GetSockOpt(FSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, @Result, l)
  2718. else
  2719. synsock.GetSockOpt(FSocket, IPPROTO_IP, IP_TTL, @Result, l);
  2720. {$ENDIF}
  2721. end;
  2722. procedure TBlockSocket.SetFamily(Value: TSocketFamily);
  2723. begin
  2724. FFamily := Value;
  2725. FFamilySave := Value;
  2726. end;
  2727. procedure TBlockSocket.SetSocket(Value: TSocket);
  2728. begin
  2729. FRecvCounter := 0;
  2730. FSendCounter := 0;
  2731. FSocket := Value;
  2732. {$IFNDEF CIL}
  2733. FD_ZERO(FFDSet);
  2734. FD_SET(FSocket, FFDSet);
  2735. {$ENDIF}
  2736. GetSins;
  2737. FIP6Used := FRemoteSin.AddressFamily = AF_INET6;
  2738. end;
  2739. function TBlockSocket.GetWsaData: TWSAData;
  2740. begin
  2741. {$IFDEF ONCEWINSOCK}
  2742. Result := WsaDataOnce;
  2743. {$ELSE}
  2744. Result := FWsaDataOnce;
  2745. {$ENDIF}
  2746. end;
  2747. function TBlockSocket.GetSocketType: integer;
  2748. begin
  2749. Result := 0;
  2750. end;
  2751. function TBlockSocket.GetSocketProtocol: integer;
  2752. begin
  2753. Result := integer(IPPROTO_IP);
  2754. end;
  2755. procedure TBlockSocket.DoStatus(Reason: THookSocketReason; const Value: string);
  2756. begin
  2757. if assigned(OnStatus) then
  2758. OnStatus(Self, Reason, Value);
  2759. end;
  2760. procedure TBlockSocket.DoReadFilter(Buffer: TMemory; var Len: Integer);
  2761. var
  2762. s: AnsiString;
  2763. begin
  2764. if assigned(OnReadFilter) then
  2765. if Len > 0 then
  2766. begin
  2767. {$IFDEF CIL}
  2768. s := StringOf(Buffer);
  2769. {$ELSE}
  2770. SetLength(s, Len);
  2771. Move(Buffer^, Pointer(s)^, Len);
  2772. {$ENDIF}
  2773. OnReadFilter(Self, s);
  2774. if Length(s) > Len then
  2775. SetLength(s, Len);
  2776. Len := Length(s);
  2777. {$IFDEF CIL}
  2778. Buffer := BytesOf(s);
  2779. {$ELSE}
  2780. Move(Pointer(s)^, Buffer^, Len);
  2781. {$ENDIF}
  2782. end;
  2783. end;
  2784. procedure TBlockSocket.DoCreateSocket;
  2785. begin
  2786. if assigned(OnCreateSocket) then
  2787. OnCreateSocket(Self);
  2788. end;
  2789. procedure TBlockSocket.DoMonitor(Writing: Boolean; const Buffer: TMemory; Len: Integer);
  2790. begin
  2791. if assigned(OnMonitor) then
  2792. begin
  2793. OnMonitor(Self, Writing, Buffer, Len);
  2794. end;
  2795. end;
  2796. procedure TBlockSocket.DoHeartbeat;
  2797. begin
  2798. if assigned(OnHeartbeat) and (FHeartbeatRate <> 0) then
  2799. begin
  2800. OnHeartbeat(Self);
  2801. end;
  2802. end;
  2803. function TBlockSocket.GetErrorDescEx: string;
  2804. begin
  2805. Result := GetErrorDesc(FLastError);
  2806. end;
  2807. class function TBlockSocket.GetErrorDesc(ErrorCode: Integer): string;
  2808. begin
  2809. {$IFDEF CIL}
  2810. if ErrorCode = 0 then
  2811. Result := ''
  2812. else
  2813. begin
  2814. Result := WSAGetLastErrorDesc;
  2815. if Result = '' then
  2816. Result := 'Other Winsock error (' + IntToStr(ErrorCode) + ')';
  2817. end;
  2818. {$ELSE}
  2819. case ErrorCode of
  2820. 0:
  2821. Result := '';
  2822. WSAEINTR: {10004}
  2823. Result := 'Interrupted system call';
  2824. WSAEBADF: {10009}
  2825. Result := 'Bad file number';
  2826. WSAEACCES: {10013}
  2827. Result := 'Permission denied';
  2828. WSAEFAULT: {10014}
  2829. Result := 'Bad address';
  2830. WSAEINVAL: {10022}
  2831. Result := 'Invalid argument';
  2832. WSAEMFILE: {10024}
  2833. Result := 'Too many open files';
  2834. WSAEWOULDBLOCK: {10035}
  2835. Result := 'Operation would block';
  2836. WSAEINPROGRESS: {10036}
  2837. Result := 'Operation now in progress';
  2838. WSAEALREADY: {10037}
  2839. Result := 'Operation already in progress';
  2840. WSAENOTSOCK: {10038}
  2841. Result := 'Socket operation on nonsocket';
  2842. WSAEDESTADDRREQ: {10039}
  2843. Result := 'Destination address required';
  2844. WSAEMSGSIZE: {10040}
  2845. Result := 'Message too long';
  2846. WSAEPROTOTYPE: {10041}
  2847. Result := 'Protocol wrong type for Socket';
  2848. WSAENOPROTOOPT: {10042}
  2849. Result := 'Protocol not available';
  2850. WSAEPROTONOSUPPORT: {10043}
  2851. Result := 'Protocol not supported';
  2852. WSAESOCKTNOSUPPORT: {10044}
  2853. Result := 'Socket not supported';
  2854. WSAEOPNOTSUPP: {10045}
  2855. Result := 'Operation not supported on Socket';
  2856. WSAEPFNOSUPPORT: {10046}
  2857. Result := 'Protocol family not supported';
  2858. WSAEAFNOSUPPORT: {10047}
  2859. Result := 'Address family not supported';
  2860. WSAEADDRINUSE: {10048}
  2861. Result := 'Address already in use';
  2862. WSAEADDRNOTAVAIL: {10049}
  2863. Result := 'Can''t assign requested address';
  2864. WSAENETDOWN: {10050}
  2865. Result := 'Network is down';
  2866. WSAENETUNREACH: {10051}
  2867. Result := 'Network is unreachable';
  2868. WSAENETRESET: {10052}
  2869. Result := 'Network dropped connection on reset';
  2870. WSAECONNABORTED: {10053}
  2871. Result := 'Software caused connection abort';
  2872. WSAECONNRESET: {10054}
  2873. Result := 'Connection reset by peer';
  2874. WSAENOBUFS: {10055}
  2875. Result := 'No Buffer space available';
  2876. WSAEISCONN: {10056}
  2877. Result := 'Socket is already connected';
  2878. WSAENOTCONN: {10057}
  2879. Result := 'Socket is not connected';
  2880. WSAESHUTDOWN: {10058}
  2881. Result := 'Can''t send after Socket shutdown';
  2882. WSAETOOMANYREFS: {10059}
  2883. Result := 'Too many references:can''t splice';
  2884. WSAETIMEDOUT: {10060}
  2885. Result := 'Connection timed out';
  2886. WSAECONNREFUSED: {10061}
  2887. Result := 'Connection refused';
  2888. WSAELOOP: {10062}
  2889. Result := 'Too many levels of symbolic links';
  2890. WSAENAMETOOLONG: {10063}
  2891. Result := 'File name is too long';
  2892. WSAEHOSTDOWN: {10064}
  2893. Result := 'Host is down';
  2894. WSAEHOSTUNREACH: {10065}
  2895. Result := 'No route to host';
  2896. WSAENOTEMPTY: {10066}
  2897. Result := 'Directory is not empty';
  2898. WSAEPROCLIM: {10067}
  2899. Result := 'Too many processes';
  2900. WSAEUSERS: {10068}
  2901. Result := 'Too many users';
  2902. WSAEDQUOT: {10069}
  2903. Result := 'Disk quota exceeded';
  2904. WSAESTALE: {10070}
  2905. Result := 'Stale NFS file handle';
  2906. WSAEREMOTE: {10071}
  2907. Result := 'Too many levels of remote in path';
  2908. WSASYSNOTREADY: {10091}
  2909. Result := 'Network subsystem is unusable';
  2910. WSAVERNOTSUPPORTED: {10092}
  2911. Result := 'Winsock DLL cannot support this application';
  2912. WSANOTINITIALISED: {10093}
  2913. Result := 'Winsock not initialized';
  2914. WSAEDISCON: {10101}
  2915. Result := 'Disconnect';
  2916. WSAHOST_NOT_FOUND: {11001}
  2917. Result := 'Host not found';
  2918. WSATRY_AGAIN: {11002}
  2919. Result := 'Non authoritative - host not found';
  2920. WSANO_RECOVERY: {11003}
  2921. Result := 'Non recoverable error';
  2922. WSANO_DATA: {11004}
  2923. Result := 'Valid name, no data record of requested type'
  2924. else
  2925. Result := 'Other Winsock error (' + IntToStr(ErrorCode) + ')';
  2926. end;
  2927. {$ENDIF}
  2928. end;
  2929. {======================================================================}
  2930. constructor TSocksBlockSocket.Create;
  2931. begin
  2932. inherited Create;
  2933. FSocksIP:= '';
  2934. FSocksPort:= '1080';
  2935. FSocksTimeout:= 60000;
  2936. FSocksUsername:= '';
  2937. FSocksPassword:= '';
  2938. FUsingSocks := False;
  2939. FSocksResolver := True;
  2940. FSocksLastError := 0;
  2941. FSocksResponseIP := '';
  2942. FSocksResponsePort := '';
  2943. FSocksLocalIP := '';
  2944. FSocksLocalPort := '';
  2945. FSocksRemoteIP := '';
  2946. FSocksRemotePort := '';
  2947. FBypassFlag := False;
  2948. FSocksType := ST_Socks5;
  2949. end;
  2950. function TSocksBlockSocket.SocksOpen: boolean;
  2951. var
  2952. Buf: AnsiString;
  2953. n: integer;
  2954. begin
  2955. Result := False;
  2956. FUsingSocks := False;
  2957. if FSocksType <> ST_Socks5 then
  2958. begin
  2959. FUsingSocks := True;
  2960. Result := True;
  2961. end
  2962. else
  2963. begin
  2964. FBypassFlag := True;
  2965. try
  2966. if FSocksUsername = '' then
  2967. Buf := #5 + #1 + #0
  2968. else
  2969. Buf := #5 + #2 + #2 +#0;
  2970. SendString(Buf);
  2971. Buf := RecvBufferStr(2, FSocksTimeout);
  2972. if Length(Buf) < 2 then
  2973. Exit;
  2974. if Buf[1] <> #5 then
  2975. Exit;
  2976. n := Ord(Buf[2]);
  2977. case n of
  2978. 0: //not need authorisation
  2979. ;
  2980. 2:
  2981. begin
  2982. Buf := #1 + AnsiChar(Length(FSocksUsername)) + FSocksUsername
  2983. + AnsiChar(Length(FSocksPassword)) + FSocksPassword;
  2984. SendString(Buf);
  2985. Buf := RecvBufferStr(2, FSocksTimeout);
  2986. if Length(Buf) < 2 then
  2987. Exit;
  2988. if Buf[2] <> #0 then
  2989. Exit;
  2990. end;
  2991. else
  2992. //other authorisation is not supported!
  2993. Exit;
  2994. end;
  2995. FUsingSocks := True;
  2996. Result := True;
  2997. finally
  2998. FBypassFlag := False;
  2999. end;
  3000. end;
  3001. end;
  3002. function TSocksBlockSocket.SocksRequest(Cmd: Byte;
  3003. const IP, Port: string): Boolean;
  3004. var
  3005. Buf: AnsiString;
  3006. begin
  3007. FBypassFlag := True;
  3008. try
  3009. if FSocksType <> ST_Socks5 then
  3010. Buf := #4 + AnsiChar(Cmd) + SocksCode(IP, Port)
  3011. else
  3012. Buf := #5 + AnsiChar(Cmd) + #0 + SocksCode(IP, Port);
  3013. SendString(Buf);
  3014. Result := FLastError = 0;
  3015. finally
  3016. FBypassFlag := False;
  3017. end;
  3018. end;
  3019. function TSocksBlockSocket.SocksResponse: Boolean;
  3020. var
  3021. Buf, s: AnsiString;
  3022. x: integer;
  3023. begin
  3024. Result := False;
  3025. FBypassFlag := True;
  3026. try
  3027. FSocksResponseIP := '';
  3028. FSocksResponsePort := '';
  3029. FSocksLastError := -1;
  3030. if FSocksType <> ST_Socks5 then
  3031. begin
  3032. Buf := RecvBufferStr(8, FSocksTimeout);
  3033. if FLastError <> 0 then
  3034. Exit;
  3035. if Buf[1] <> #0 then
  3036. Exit;
  3037. FSocksLastError := Ord(Buf[2]);
  3038. end
  3039. else
  3040. begin
  3041. Buf := RecvBufferStr(4, FSocksTimeout);
  3042. if FLastError <> 0 then
  3043. Exit;
  3044. if Buf[1] <> #5 then
  3045. Exit;
  3046. case Ord(Buf[4]) of
  3047. 1:
  3048. s := RecvBufferStr(4, FSocksTimeout);
  3049. 3:
  3050. begin
  3051. x := RecvByte(FSocksTimeout);
  3052. if FLastError <> 0 then
  3053. Exit;
  3054. s := AnsiChar(x) + RecvBufferStr(x, FSocksTimeout);
  3055. end;
  3056. 4:
  3057. s := RecvBufferStr(16, FSocksTimeout);
  3058. else
  3059. Exit;
  3060. end;
  3061. Buf := Buf + s + RecvBufferStr(2, FSocksTimeout);
  3062. if FLastError <> 0 then
  3063. Exit;
  3064. FSocksLastError := Ord(Buf[2]);
  3065. end;
  3066. if ((FSocksLastError <> 0) and (FSocksLastError <> 90)) then
  3067. Exit;
  3068. SocksDecode(Buf);
  3069. Result := True;
  3070. finally
  3071. FBypassFlag := False;
  3072. end;
  3073. end;
  3074. function TSocksBlockSocket.SocksCode(IP, Port: string): Ansistring;
  3075. var
  3076. ip6: TIp6Bytes;
  3077. n: integer;
  3078. begin
  3079. if FSocksType <> ST_Socks5 then
  3080. begin
  3081. Result := CodeInt(ResolvePort(Port));
  3082. if not FSocksResolver then
  3083. IP := ResolveName(IP);
  3084. if IsIP(IP) then
  3085. begin
  3086. Result := Result + IPToID(IP);
  3087. Result := Result + FSocksUsername + #0;
  3088. end
  3089. else
  3090. begin
  3091. Result := Result + IPToID('0.0.0.1');
  3092. Result := Result + FSocksUsername + #0;
  3093. Result := Result + IP + #0;
  3094. end;
  3095. end
  3096. else
  3097. begin
  3098. if not FSocksResolver then
  3099. IP := ResolveName(IP);
  3100. if IsIP(IP) then
  3101. Result := #1 + IPToID(IP)
  3102. else
  3103. if IsIP6(IP) then
  3104. begin
  3105. ip6 := StrToIP6(IP);
  3106. Result := #4;
  3107. for n := 0 to 15 do
  3108. Result := Result + AnsiChar(ip6[n]);
  3109. end
  3110. else
  3111. Result := #3 + AnsiChar(Length(IP)) + IP;
  3112. Result := Result + CodeInt(ResolvePort(Port));
  3113. end;
  3114. end;
  3115. function TSocksBlockSocket.SocksDecode(Value: Ansistring): integer;
  3116. var
  3117. Atyp: Byte;
  3118. y, n: integer;
  3119. w: Word;
  3120. ip6: TIp6Bytes;
  3121. begin
  3122. FSocksResponsePort := '0';
  3123. Result := 0;
  3124. if FSocksType <> ST_Socks5 then
  3125. begin
  3126. if Length(Value) < 8 then
  3127. Exit;
  3128. Result := 3;
  3129. w := DecodeInt(Value, Result);
  3130. FSocksResponsePort := IntToStr(w);
  3131. FSocksResponseIP := Format('%d.%d.%d.%d',
  3132. [Ord(Value[5]), Ord(Value[6]), Ord(Value[7]), Ord(Value[8])]);
  3133. Result := 9;
  3134. end
  3135. else
  3136. begin
  3137. if Length(Value) < 4 then
  3138. Exit;
  3139. Atyp := Ord(Value[4]);
  3140. Result := 5;
  3141. case Atyp of
  3142. 1:
  3143. begin
  3144. if Length(Value) < 10 then
  3145. Exit;
  3146. FSocksResponseIP := Format('%d.%d.%d.%d',
  3147. [Ord(Value[5]), Ord(Value[6]), Ord(Value[7]), Ord(Value[8])]);
  3148. Result := 9;
  3149. end;
  3150. 3:
  3151. begin
  3152. y := Ord(Value[5]);
  3153. if Length(Value) < (5 + y + 2) then
  3154. Exit;
  3155. for n := 6 to 6 + y - 1 do
  3156. FSocksResponseIP := FSocksResponseIP + Value[n];
  3157. Result := 5 + y + 1;
  3158. end;
  3159. 4:
  3160. begin
  3161. if Length(Value) < 22 then
  3162. Exit;
  3163. for n := 0 to 15 do
  3164. ip6[n] := ord(Value[n + 5]);
  3165. FSocksResponseIP := IP6ToStr(ip6);
  3166. Result := 21;
  3167. end;
  3168. else
  3169. Exit;
  3170. end;
  3171. w := DecodeInt(Value, Result);
  3172. FSocksResponsePort := IntToStr(w);
  3173. Result := Result + 2;
  3174. end;
  3175. end;
  3176. {======================================================================}
  3177. procedure TDgramBlockSocket.Connect(IP, Port: string);
  3178. begin
  3179. SetRemoteSin(IP, Port);
  3180. InternalCreateSocket(FRemoteSin);
  3181. FBuffer := '';
  3182. DoStatus(HR_Connect, IP + ':' + Port);
  3183. end;
  3184. function TDgramBlockSocket.RecvBuffer(Buffer: TMemory; Length: Integer): Integer;
  3185. begin
  3186. Result := RecvBufferFrom(Buffer, Length);
  3187. end;
  3188. function TDgramBlockSocket.SendBuffer(const Buffer: TMemory; Length: Integer): Integer;
  3189. begin
  3190. Result := SendBufferTo(Buffer, Length);
  3191. end;
  3192. {======================================================================}
  3193. destructor TUDPBlockSocket.Destroy;
  3194. begin
  3195. if Assigned(FSocksControlSock) then
  3196. FSocksControlSock.Free;
  3197. inherited;
  3198. end;
  3199. procedure TUDPBlockSocket.EnableBroadcast(Value: Boolean);
  3200. var
  3201. d: TSynaOption;
  3202. begin
  3203. d := TSynaOption.Create;
  3204. d.Option := SOT_Broadcast;
  3205. d.Enabled := Value;
  3206. DelayedOption(d);
  3207. end;
  3208. function TUDPBlockSocket.UdpAssociation: Boolean;
  3209. var
  3210. b: Boolean;
  3211. begin
  3212. Result := True;
  3213. FUsingSocks := False;
  3214. if FSocksIP <> '' then
  3215. begin
  3216. Result := False;
  3217. if not Assigned(FSocksControlSock) then
  3218. FSocksControlSock := TTCPBlockSocket.Create;
  3219. FSocksControlSock.CloseSocket;
  3220. FSocksControlSock.CreateSocketByName(FSocksIP);
  3221. FSocksControlSock.Connect(FSocksIP, FSocksPort);
  3222. if FSocksControlSock.LastError <> 0 then
  3223. Exit;
  3224. // if not assigned local port, assign it!
  3225. if not FBinded then
  3226. Bind(cAnyHost, cAnyPort);
  3227. //open control TCP connection to SOCKS
  3228. FSocksControlSock.FSocksUsername := FSocksUsername;
  3229. FSocksControlSock.FSocksPassword := FSocksPassword;
  3230. b := FSocksControlSock.SocksOpen;
  3231. if b then
  3232. b := FSocksControlSock.SocksRequest(3, GetLocalSinIP, IntToStr(GetLocalSinPort));
  3233. if b then
  3234. b := FSocksControlSock.SocksResponse;
  3235. if not b and (FLastError = 0) then
  3236. FLastError := WSANO_RECOVERY;
  3237. FUsingSocks :=FSocksControlSock.UsingSocks;
  3238. FSocksRemoteIP := FSocksControlSock.FSocksResponseIP;
  3239. FSocksRemotePort := FSocksControlSock.FSocksResponsePort;
  3240. Result := b and (FLastError = 0);
  3241. end;
  3242. end;
  3243. function TUDPBlockSocket.SendBufferTo(const Buffer: TMemory; Length: Integer): Integer;
  3244. var
  3245. SIp: string;
  3246. SPort: integer;
  3247. Buf: Ansistring;
  3248. begin
  3249. Result := 0;
  3250. FUsingSocks := False;
  3251. if (FSocksIP <> '') and (not UdpAssociation) then
  3252. FLastError := WSANO_RECOVERY
  3253. else
  3254. begin
  3255. if FUsingSocks then
  3256. begin
  3257. {$IFNDEF CIL}
  3258. Sip := GetRemoteSinIp;
  3259. SPort := GetRemoteSinPort;
  3260. SetRemoteSin(FSocksRemoteIP, FSocksRemotePort);
  3261. SetLength(Buf,Length);
  3262. Move(Buffer^, Pointer(Buf)^, Length);
  3263. Buf := #0 + #0 + #0 + SocksCode(Sip, IntToStr(SPort)) + Buf;
  3264. Result := inherited SendBufferTo(Pointer(Buf), System.Length(buf));
  3265. SetRemoteSin(Sip, IntToStr(SPort));
  3266. {$ENDIF}
  3267. end
  3268. else
  3269. Result := inherited SendBufferTo(Buffer, Length);
  3270. end;
  3271. end;
  3272. function TUDPBlockSocket.RecvBufferFrom(Buffer: TMemory; Length: Integer): Integer;
  3273. var
  3274. Buf: Ansistring;
  3275. x: integer;
  3276. begin
  3277. Result := inherited RecvBufferFrom(Buffer, Length);
  3278. if FUsingSocks then
  3279. begin
  3280. {$IFNDEF CIL}
  3281. SetLength(Buf, Result);
  3282. Move(Buffer^, Pointer(Buf)^, Result);
  3283. x := SocksDecode(Buf);
  3284. Result := Result - x + 1;
  3285. Buf := Copy(Buf, x, Result);
  3286. Move(Pointer(Buf)^, Buffer^, Result);
  3287. SetRemoteSin(FSocksResponseIP, FSocksResponsePort);
  3288. {$ENDIF}
  3289. end;
  3290. end;
  3291. {$IFNDEF CIL}
  3292. procedure TUDPBlockSocket.AddMulticast(MCastIP: string);
  3293. var
  3294. Multicast: TIP_mreq;
  3295. Multicast6: TIPv6_mreq;
  3296. n: integer;
  3297. ip6: Tip6bytes;
  3298. begin
  3299. if FIP6Used then
  3300. begin
  3301. ip6 := StrToIp6(MCastIP);
  3302. for n := 0 to 15 do
  3303. Multicast6.ipv6mr_multiaddr.{$IFDEF POSIX}s6_addr{$ELSE}u6_addr8{$ENDIF}[n] := Ip6[n];
  3304. Multicast6.ipv6mr_interface := 0;
  3305. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IPV6, IPV6_JOIN_GROUP,
  3306. PAnsiChar(@Multicast6), SizeOf(Multicast6)));
  3307. end
  3308. else
  3309. begin
  3310. Multicast.imr_multiaddr.S_addr := swapbytes(strtoip(MCastIP));
  3311. // Multicast.imr_interface.S_addr := INADDR_ANY;
  3312. Multicast.imr_interface.S_addr := FLocalSin.sin_addr.S_addr;
  3313. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
  3314. PAnsiChar(@Multicast), SizeOf(Multicast)));
  3315. end;
  3316. ExceptCheck;
  3317. end;
  3318. procedure TUDPBlockSocket.DropMulticast(MCastIP: string);
  3319. var
  3320. Multicast: TIP_mreq;
  3321. Multicast6: TIPv6_mreq;
  3322. n: integer;
  3323. ip6: Tip6bytes;
  3324. begin
  3325. if FIP6Used then
  3326. begin
  3327. ip6 := StrToIp6(MCastIP);
  3328. for n := 0 to 15 do
  3329. Multicast6.ipv6mr_multiaddr.{$IFDEF POSIX}s6_addr{$ELSE}u6_addr8{$ENDIF}[n] := Ip6[n];
  3330. Multicast6.ipv6mr_interface := 0;
  3331. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
  3332. PAnsiChar(@Multicast6), SizeOf(Multicast6)));
  3333. end
  3334. else
  3335. begin
  3336. Multicast.imr_multiaddr.S_addr := swapbytes(strtoip(MCastIP));
  3337. // Multicast.imr_interface.S_addr := INADDR_ANY;
  3338. Multicast.imr_interface.S_addr := FLocalSin.sin_addr.S_addr;
  3339. SockCheck(synsock.SetSockOpt(FSocket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
  3340. PAnsiChar(@Multicast), SizeOf(Multicast)));
  3341. end;
  3342. ExceptCheck;
  3343. end;
  3344. {$ENDIF}
  3345. procedure TUDPBlockSocket.SetMulticastTTL(TTL: integer);
  3346. var
  3347. d: TSynaOption;
  3348. begin
  3349. d := TSynaOption.Create;
  3350. d.Option := SOT_MulticastTTL;
  3351. d.Value := TTL;
  3352. DelayedOption(d);
  3353. end;
  3354. function TUDPBlockSocket.GetMulticastTTL:integer;
  3355. var
  3356. l: Integer;
  3357. begin
  3358. {$IFNDEF CIL}
  3359. l := SizeOf(Result);
  3360. if FIP6Used then
  3361. synsock.GetSockOpt(FSocket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, @Result, l)
  3362. else
  3363. synsock.GetSockOpt(FSocket, IPPROTO_IP, IP_MULTICAST_TTL, @Result, l);
  3364. {$ENDIF}
  3365. end;
  3366. procedure TUDPBlockSocket.EnableMulticastLoop(Value: Boolean);
  3367. var
  3368. d: TSynaOption;
  3369. begin
  3370. d := TSynaOption.Create;
  3371. d.Option := SOT_MulticastLoop;
  3372. d.Enabled := Value;
  3373. DelayedOption(d);
  3374. end;
  3375. function TUDPBlockSocket.GetSocketType: integer;
  3376. begin
  3377. Result := integer(SOCK_DGRAM);
  3378. end;
  3379. function TUDPBlockSocket.GetSocketProtocol: integer;
  3380. begin
  3381. Result := integer(IPPROTO_UDP);
  3382. end;
  3383. {======================================================================}
  3384. constructor TTCPBlockSocket.CreateWithSSL(SSLPlugin: TSSLClass);
  3385. begin
  3386. inherited Create;
  3387. FSSL := SSLPlugin.Create(self);
  3388. FHTTPTunnelIP := '';
  3389. FHTTPTunnelPort := '';
  3390. FHTTPTunnel := False;
  3391. FHTTPTunnelRemoteIP := '';
  3392. FHTTPTunnelRemotePort := '';
  3393. FHTTPTunnelUser := '';
  3394. FHTTPTunnelPass := '';
  3395. FHTTPTunnelTimeout := 30000;
  3396. end;
  3397. constructor TTCPBlockSocket.Create;
  3398. begin
  3399. CreateWithSSL(SSLImplementation);
  3400. end;
  3401. destructor TTCPBlockSocket.Destroy;
  3402. begin
  3403. inherited Destroy;
  3404. FSSL.Free;
  3405. end;
  3406. function TTCPBlockSocket.GetErrorDescEx: string;
  3407. begin
  3408. Result := inherited GetErrorDescEx;
  3409. if (FLastError = WSASYSNOTREADY) and (self.SSL.LastError <> 0) then
  3410. begin
  3411. Result := self.SSL.LastErrorDesc;
  3412. end;
  3413. end;
  3414. procedure TTCPBlockSocket.CloseSocket;
  3415. begin
  3416. if FSSL.SSLEnabled then
  3417. FSSL.Shutdown;
  3418. if (FSocket <> INVALID_SOCKET) and (FLastError = 0) then
  3419. begin
  3420. Synsock.Shutdown(FSocket, 1);
  3421. Purge;
  3422. end;
  3423. inherited CloseSocket;
  3424. end;
  3425. procedure TTCPBlockSocket.DoAfterConnect;
  3426. begin
  3427. if assigned(OnAfterConnect) then
  3428. begin
  3429. OnAfterConnect(Self);
  3430. end;
  3431. end;
  3432. function TTCPBlockSocket.WaitingData: Integer;
  3433. begin
  3434. Result := 0;
  3435. if FSSL.SSLEnabled and (FSocket <> INVALID_SOCKET) then
  3436. Result := FSSL.WaitingData;
  3437. if Result = 0 then
  3438. Result := inherited WaitingData;
  3439. end;
  3440. procedure TTCPBlockSocket.Listen;
  3441. var
  3442. b: Boolean;
  3443. Sip,SPort: string;
  3444. begin
  3445. if FSocksIP = '' then
  3446. begin
  3447. inherited Listen;
  3448. end
  3449. else
  3450. begin
  3451. Sip := GetLocalSinIP;
  3452. if Sip = cAnyHost then
  3453. Sip := LocalName;
  3454. SPort := IntToStr(GetLocalSinPort);
  3455. inherited Connect(FSocksIP, FSocksPort);
  3456. b := SocksOpen;
  3457. if b then
  3458. b := SocksRequest(2, Sip, SPort);
  3459. if b then
  3460. b := SocksResponse;
  3461. if not b and (FLastError = 0) then
  3462. FLastError := WSANO_RECOVERY;
  3463. FSocksLocalIP := FSocksResponseIP;
  3464. if FSocksLocalIP = cAnyHost then
  3465. FSocksLocalIP := FSocksIP;
  3466. FSocksLocalPort := FSocksResponsePort;
  3467. FSocksRemoteIP := '';
  3468. FSocksRemotePort := '';
  3469. ExceptCheck;
  3470. DoStatus(HR_Listen, '');
  3471. end;
  3472. end;
  3473. function TTCPBlockSocket.Accept: TSocket;
  3474. begin
  3475. if FUsingSocks then
  3476. begin
  3477. if not SocksResponse and (FLastError = 0) then
  3478. FLastError := WSANO_RECOVERY;
  3479. FSocksRemoteIP := FSocksResponseIP;
  3480. FSocksRemotePort := FSocksResponsePort;
  3481. Result := FSocket;
  3482. ExceptCheck;
  3483. DoStatus(HR_Accept, '');
  3484. end
  3485. else
  3486. begin
  3487. result := inherited Accept;
  3488. end;
  3489. end;
  3490. procedure TTCPBlockSocket.Connect(IP, Port: string);
  3491. begin
  3492. if FSocksIP <> '' then
  3493. SocksDoConnect(IP, Port)
  3494. else
  3495. if FHTTPTunnelIP <> '' then
  3496. HTTPTunnelDoConnect(IP, Port)
  3497. else
  3498. inherited Connect(IP, Port);
  3499. if FLasterror = 0 then
  3500. DoAfterConnect;
  3501. end;
  3502. procedure TTCPBlockSocket.SocksDoConnect(IP, Port: string);
  3503. var
  3504. b: Boolean;
  3505. begin
  3506. inherited Connect(FSocksIP, FSocksPort);
  3507. if FLastError = 0 then
  3508. begin
  3509. b := SocksOpen;
  3510. if b then
  3511. b := SocksRequest(1, IP, Port);
  3512. if b then
  3513. b := SocksResponse;
  3514. if not b and (FLastError = 0) then
  3515. FLastError := WSASYSNOTREADY;
  3516. FSocksLocalIP := FSocksResponseIP;
  3517. FSocksLocalPort := FSocksResponsePort;
  3518. FSocksRemoteIP := IP;
  3519. FSocksRemotePort := Port;
  3520. end;
  3521. ExceptCheck;
  3522. DoStatus(HR_Connect, IP + ':' + Port);
  3523. end;
  3524. procedure TTCPBlockSocket.HTTPTunnelDoConnect(IP, Port: string);
  3525. //bugfixed by Mike Green ([email protected])
  3526. var
  3527. s: string;
  3528. begin
  3529. Port := IntToStr(ResolvePort(Port));
  3530. inherited Connect(FHTTPTunnelIP, FHTTPTunnelPort);
  3531. if FLastError <> 0 then
  3532. Exit;
  3533. FHTTPTunnel := False;
  3534. if IsIP6(IP) then
  3535. IP := '[' + IP + ']';
  3536. SendString('CONNECT ' + IP + ':' + Port + ' HTTP/1.0' + CRLF);
  3537. if FHTTPTunnelUser <> '' then
  3538. Sendstring('Proxy-Authorization: Basic ' +
  3539. EncodeBase64(FHTTPTunnelUser + ':' + FHTTPTunnelPass) + CRLF);
  3540. SendString(CRLF);
  3541. repeat
  3542. s := RecvTerminated(FHTTPTunnelTimeout, #$0a);
  3543. if FLastError <> 0 then
  3544. Break;
  3545. if (Pos('HTTP/', s) = 1) and (Length(s) > 11) then
  3546. FHTTPTunnel := s[10] = '2';
  3547. until (s = '') or (s = #$0d);
  3548. if (FLasterror = 0) and not FHTTPTunnel then
  3549. FLastError := WSAECONNREFUSED;
  3550. FHTTPTunnelRemoteIP := IP;
  3551. FHTTPTunnelRemotePort := Port;
  3552. ExceptCheck;
  3553. end;
  3554. procedure TTCPBlockSocket.SSLDoConnect;
  3555. begin
  3556. ResetLastError;
  3557. if not FSSL.Connect then
  3558. FLastError := WSASYSNOTREADY;
  3559. ExceptCheck;
  3560. end;
  3561. procedure TTCPBlockSocket.SSLDoShutdown;
  3562. begin
  3563. ResetLastError;
  3564. FSSL.BiShutdown;
  3565. end;
  3566. function TTCPBlockSocket.GetLocalSinIP: string;
  3567. begin
  3568. if FUsingSocks then
  3569. Result := FSocksLocalIP
  3570. else
  3571. Result := inherited GetLocalSinIP;
  3572. end;
  3573. function TTCPBlockSocket.GetRemoteSinIP: string;
  3574. begin
  3575. if FUsingSocks then
  3576. Result := FSocksRemoteIP
  3577. else
  3578. if FHTTPTunnel then
  3579. Result := FHTTPTunnelRemoteIP
  3580. else
  3581. Result := inherited GetRemoteSinIP;
  3582. end;
  3583. function TTCPBlockSocket.GetLocalSinPort: Integer;
  3584. begin
  3585. if FUsingSocks then
  3586. Result := StrToIntDef(FSocksLocalPort, 0)
  3587. else
  3588. Result := inherited GetLocalSinPort;
  3589. end;
  3590. function TTCPBlockSocket.GetRemoteSinPort: Integer;
  3591. begin
  3592. if FUsingSocks then
  3593. Result := ResolvePort(FSocksRemotePort)
  3594. else
  3595. if FHTTPTunnel then
  3596. Result := StrToIntDef(FHTTPTunnelRemotePort, 0)
  3597. else
  3598. Result := inherited GetRemoteSinPort;
  3599. end;
  3600. function TTCPBlockSocket.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
  3601. begin
  3602. if FSSL.SSLEnabled then
  3603. begin
  3604. Result := 0;
  3605. if TestStopFlag then
  3606. Exit;
  3607. ResetLastError;
  3608. LimitBandwidth(Len, FMaxRecvBandwidth, FNextRecv);
  3609. Result := FSSL.RecvBuffer(Buffer, Len);
  3610. if FSSL.LastError <> 0 then
  3611. FLastError := WSASYSNOTREADY;
  3612. ExceptCheck;
  3613. Inc(FRecvCounter, Result);
  3614. DoStatus(HR_ReadCount, IntToStr(Result));
  3615. DoMonitor(False, Buffer, Result);
  3616. DoReadFilter(Buffer, Result);
  3617. end
  3618. else
  3619. Result := inherited RecvBuffer(Buffer, Len);
  3620. end;
  3621. function TTCPBlockSocket.SendBuffer(const Buffer: TMemory; Length: Integer): Integer;
  3622. var
  3623. x, y: integer;
  3624. l, r: integer;
  3625. {$IFNDEF CIL}
  3626. p: Pointer;
  3627. {$ENDIF}
  3628. begin
  3629. if FSSL.SSLEnabled then
  3630. begin
  3631. Result := 0;
  3632. if TestStopFlag then
  3633. Exit;
  3634. ResetLastError;
  3635. DoMonitor(True, Buffer, Length);
  3636. {$IFDEF CIL}
  3637. Result := FSSL.SendBuffer(Buffer, Length);
  3638. if FSSL.LastError <> 0 then
  3639. FLastError := WSASYSNOTREADY;
  3640. Inc(FSendCounter, Result);
  3641. DoStatus(HR_WriteCount, IntToStr(Result));
  3642. {$ELSE}
  3643. l := Length;
  3644. x := 0;
  3645. while x < l do
  3646. begin
  3647. y := l - x;
  3648. if y > FSendMaxChunk then
  3649. y := FSendMaxChunk;
  3650. if y > 0 then
  3651. begin
  3652. LimitBandwidth(y, FMaxSendBandwidth, FNextsend);
  3653. p := IncPoint(Buffer, x);
  3654. r := FSSL.SendBuffer(p, y);
  3655. if FSSL.LastError <> 0 then
  3656. FLastError := WSASYSNOTREADY;
  3657. if Flasterror <> 0 then
  3658. Break;
  3659. Inc(x, r);
  3660. Inc(Result, r);
  3661. Inc(FSendCounter, r);
  3662. DoStatus(HR_WriteCount, IntToStr(r));
  3663. end
  3664. else
  3665. break;
  3666. end;
  3667. {$ENDIF}
  3668. ExceptCheck;
  3669. end
  3670. else
  3671. Result := inherited SendBuffer(Buffer, Length);
  3672. end;
  3673. function TTCPBlockSocket.SSLAcceptConnection: Boolean;
  3674. begin
  3675. ResetLastError;
  3676. if not FSSL.Accept then
  3677. FLastError := WSASYSNOTREADY;
  3678. ExceptCheck;
  3679. Result := FLastError = 0;
  3680. end;
  3681. function TTCPBlockSocket.GetSocketType: integer;
  3682. begin
  3683. Result := integer(SOCK_STREAM);
  3684. end;
  3685. function TTCPBlockSocket.GetSocketProtocol: integer;
  3686. begin
  3687. Result := integer(IPPROTO_TCP);
  3688. end;
  3689. {======================================================================}
  3690. function TICMPBlockSocket.GetSocketType: integer;
  3691. begin
  3692. Result := integer(SOCK_RAW);
  3693. end;
  3694. function TICMPBlockSocket.GetSocketProtocol: integer;
  3695. begin
  3696. if FIP6Used then
  3697. Result := integer(IPPROTO_ICMPV6)
  3698. else
  3699. Result := integer(IPPROTO_ICMP);
  3700. end;
  3701. {======================================================================}
  3702. function TRAWBlockSocket.GetSocketType: integer;
  3703. begin
  3704. Result := integer(SOCK_RAW);
  3705. end;
  3706. function TRAWBlockSocket.GetSocketProtocol: integer;
  3707. begin
  3708. Result := integer(IPPROTO_RAW);
  3709. end;
  3710. {======================================================================}
  3711. function TPGMmessageBlockSocket.GetSocketType: integer;
  3712. begin
  3713. Result := integer(SOCK_RDM);
  3714. end;
  3715. function TPGMmessageBlockSocket.GetSocketProtocol: integer;
  3716. begin
  3717. Result := integer(IPPROTO_RM);
  3718. end;
  3719. {======================================================================}
  3720. function TPGMstreamBlockSocket.GetSocketType: integer;
  3721. begin
  3722. Result := integer(SOCK_STREAM);
  3723. end;
  3724. function TPGMstreamBlockSocket.GetSocketProtocol: integer;
  3725. begin
  3726. Result := integer(IPPROTO_RM);
  3727. end;
  3728. {======================================================================}
  3729. constructor TSynaClient.Create;
  3730. begin
  3731. inherited Create;
  3732. FIPInterface := cAnyHost;
  3733. FTargetHost := cLocalhost;
  3734. FTargetPort := cAnyPort;
  3735. FTimeout := 5000;
  3736. FUsername := '';
  3737. FPassword := '';
  3738. end;
  3739. {======================================================================}
  3740. constructor TCustomSSL.Create(const Value: TTCPBlockSocket);
  3741. begin
  3742. inherited Create;
  3743. FSocket := Value;
  3744. FSSLEnabled := False;
  3745. FUsername := '';
  3746. FPassword := '';
  3747. FLastError := 0;
  3748. FLastErrorDesc := '';
  3749. FVerifyCert := False;
  3750. FSSLType := LT_all;
  3751. FKeyPassword := '';
  3752. FCiphers := '';
  3753. FCertificateFile := '';
  3754. FPrivateKeyFile := '';
  3755. FCertCAFile := '';
  3756. FCertCA := '';
  3757. FTrustCertificate := '';
  3758. FTrustCertificateFile := '';
  3759. FCertificate := '';
  3760. FPrivateKey := '';
  3761. FPFX := '';
  3762. FPFXfile := '';
  3763. FSSHChannelType := '';
  3764. FSSHChannelArg1 := '';
  3765. FSSHChannelArg2 := '';
  3766. FCertComplianceLevel := -1; //default
  3767. FSNIHost := '';
  3768. end;
  3769. procedure TCustomSSL.Assign(const Value: TCustomSSL);
  3770. begin
  3771. FUsername := Value.Username;
  3772. FPassword := Value.Password;
  3773. FVerifyCert := Value.VerifyCert;
  3774. FSSLType := Value.SSLType;
  3775. FKeyPassword := Value.KeyPassword;
  3776. FCiphers := Value.Ciphers;
  3777. FCertificateFile := Value.CertificateFile;
  3778. FPrivateKeyFile := Value.PrivateKeyFile;
  3779. FCertCAFile := Value.CertCAFile;
  3780. FCertCA := Value.CertCA;
  3781. FTrustCertificate := Value.TrustCertificate;
  3782. FTrustCertificateFile := Value.TrustCertificateFile;
  3783. FCertificate := Value.Certificate;
  3784. FPrivateKey := Value.PrivateKey;
  3785. FPFX := Value.PFX;
  3786. FPFXfile := Value.PFXfile;
  3787. FCertComplianceLevel := Value.CertComplianceLevel;
  3788. FSNIHost := Value.FSNIHost;
  3789. end;
  3790. procedure TCustomSSL.ReturnError;
  3791. begin
  3792. FLastError := -1;
  3793. FLastErrorDesc := 'SSL/TLS support is not compiled!';
  3794. end;
  3795. function TCustomSSL.LibVersion: String;
  3796. begin
  3797. Result := '';
  3798. end;
  3799. function TCustomSSL.LibName: String;
  3800. begin
  3801. Result := '';
  3802. end;
  3803. function TCustomSSL.CreateSelfSignedCert(Host: string): Boolean;
  3804. begin
  3805. Result := False;
  3806. end;
  3807. function TCustomSSL.Connect: boolean;
  3808. begin
  3809. ReturnError;
  3810. Result := False;
  3811. end;
  3812. function TCustomSSL.Accept: boolean;
  3813. begin
  3814. ReturnError;
  3815. Result := False;
  3816. end;
  3817. function TCustomSSL.Shutdown: boolean;
  3818. begin
  3819. ReturnError;
  3820. Result := False;
  3821. end;
  3822. function TCustomSSL.BiShutdown: boolean;
  3823. begin
  3824. ReturnError;
  3825. Result := False;
  3826. end;
  3827. function TCustomSSL.SendBuffer(Buffer: TMemory; Len: Integer): Integer;
  3828. begin
  3829. ReturnError;
  3830. Result := integer(SOCKET_ERROR);
  3831. end;
  3832. procedure TCustomSSL.SetCertCAFile(const Value: string);
  3833. begin
  3834. FCertCAFile := Value;
  3835. end;
  3836. function TCustomSSL.RecvBuffer(Buffer: TMemory; Len: Integer): Integer;
  3837. begin
  3838. ReturnError;
  3839. Result := integer(SOCKET_ERROR);
  3840. end;
  3841. function TCustomSSL.WaitingData: Integer;
  3842. begin
  3843. ReturnError;
  3844. Result := 0;
  3845. end;
  3846. function TCustomSSL.GetSSLVersion: string;
  3847. begin
  3848. Result := '';
  3849. end;
  3850. function TCustomSSL.GetPeerSubject: string;
  3851. begin
  3852. Result := '';
  3853. end;
  3854. function TCustomSSL.GetPeerSerialNo: integer;
  3855. begin
  3856. Result := -1;
  3857. end;
  3858. function TCustomSSL.GetPeerName: string;
  3859. begin
  3860. Result := '';
  3861. end;
  3862. function TCustomSSL.GetPeerNameHash: cardinal;
  3863. begin
  3864. Result := 0;
  3865. end;
  3866. function TCustomSSL.GetPeerIssuer: string;
  3867. begin
  3868. Result := '';
  3869. end;
  3870. function TCustomSSL.GetPeerFingerprint: AnsiString;
  3871. begin
  3872. Result := '';
  3873. end;
  3874. function TCustomSSL.GetCertInfo: string;
  3875. begin
  3876. Result := '';
  3877. end;
  3878. function TCustomSSL.GetCipherName: string;
  3879. begin
  3880. Result := '';
  3881. end;
  3882. function TCustomSSL.GetCipherBits: integer;
  3883. begin
  3884. Result := 0;
  3885. end;
  3886. function TCustomSSL.GetCipherAlgBits: integer;
  3887. begin
  3888. Result := 0;
  3889. end;
  3890. function TCustomSSL.GetVerifyCert: integer;
  3891. begin
  3892. Result := 1;
  3893. end;
  3894. function TCustomSSL.DoVerifyCert:boolean;
  3895. begin
  3896. if assigned(OnVerifyCert) then
  3897. begin
  3898. result:=OnVerifyCert(Self);
  3899. end
  3900. else
  3901. result:=true;
  3902. end;
  3903. {======================================================================}
  3904. function TSSLNone.LibVersion: String;
  3905. begin
  3906. Result := 'Without SSL support';
  3907. end;
  3908. function TSSLNone.LibName: String;
  3909. begin
  3910. Result := 'ssl_none';
  3911. end;
  3912. {======================================================================}
  3913. initialization
  3914. begin
  3915. {$IFDEF ONCEWINSOCK}
  3916. if not InitSocketInterface(DLLStackName) then
  3917. begin
  3918. e := ESynapseError.Create('Error loading Socket interface (' + DLLStackName + ')!');
  3919. e.ErrorCode := 0;
  3920. e.ErrorMessage := 'Error loading Socket interface (' + DLLStackName + ')!';
  3921. raise e;
  3922. end;
  3923. synsock.WSAStartup(WinsockLevel, WsaDataOnce);
  3924. {$ENDIF}
  3925. end;
  3926. finalization
  3927. begin
  3928. {$IFDEF ONCEWINSOCK}
  3929. synsock.WSACleanup;
  3930. DestroySocketInterface;
  3931. {$ENDIF}
  3932. end;
  3933. end.